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
fix(architectures): one VAE policy for Generate, and format- and dtype-aware VAE loading
Alexander Eichhorn3a6aaa086e1c
diff --git a/invokeai/backend/model_manager/load/model_loaders/vae.py b/invokeai/backend/model_manager/load/model_loaders/vae.pyindex 003c5112ad..7dd8554094 100644--- a/invokeai/backend/model_manager/load/model_loaders/vae.py+++ b/invokeai/backend/model_manager/load/model_loaders/vae.py@@ -5,6 +5,7 @@ from pathlib import Pathfrom typing import Optionalimport accelerate+import torchfrom diffusers.models.autoencoders.autoencoder_kl import AutoencoderKLfrom invokeai.backend.model_manager.configs.factory import AnyModelConfig@@ -49,17 +50,51 @@ it is one `convert_wan_vae_to_diffusers` knows how to read.def _checkpoint_keys(path: str | Path) -> set[str]:- """The tensor names in a safetensors file, read from its header alone.+ """The tensor names in a single-file checkpoint, without reading its tensors.Layout is decided before anything is loaded, so the file is read once, by whichever branch- actually needs the tensors.+ actually needs the tensors. Safetensors answer from the header; a pickled checkpoint is unpickled+ onto the meta device, which skips its storages."""+ if Path(path).suffix != ".safetensors":+ return set(_unwrap_state_dict(torch.load(path, map_location="meta", weights_only=True)))+from safetensors import safe_openwith safe_open(path, framework="pt", device="cpu") as f:return set(f.keys())+def _read_checkpoint(path: str | Path) -> dict[str, torch.Tensor]:+ """Every tensor in a single-file checkpoint, whichever format it was saved in.++ Identification reads pickled checkpoints (`.pt`, `.pth`, `.ckpt`, `.bin`) as well as safetensors,+ so a loader that reads only safetensors fails on a VAE that installed cleanly. `weights_only`+ refuses anything in the pickle but tensors and plain containers.+ """+ if Path(path).suffix == ".safetensors":+ from safetensors.torch import load_file++ return load_file(path)++ return _unwrap_state_dict(torch.load(path, map_location="cpu", weights_only=True))+++def _unwrap_state_dict(checkpoint: dict) -> dict:+ """Training checkpoints nest the weights under `state_dict`, and identification unwraps them too."""+ return checkpoint.get("state_dict", checkpoint)+++def _wan_family_dtype(requested: torch.dtype) -> torch.dtype:+ """The precision a Wan-family VAE runs in: the configured one, except float16.++ float16 is unstable on this autoencoder and is what `precision: auto` resolves to on CUDA, so it is+ raised to bfloat16. A float32 request is kept -- casting it down would round the weights for the+ lifetime of the cached model.+ """+ return torch.bfloat16 if requested == torch.float16 else requested++# Architectural defaults for the Wan 2.2-VAE (TI2V-5B). Verbatim from the# vae/config.json shipped with Wan-AI/Wan2.2-TI2V-5B-Diffusers — only the# values that differ from diffusers' AutoencoderKLWan defaults are listed.@@ -224,7 +259,7 @@ class VAELoader(GenericDiffusersLoader):return super()._load_model(config, submodel_type)def _load_wan_vae(self, config: VAE_Checkpoint_Wan_Config) -> AnyModel:- """Load a Wan 2.2 VAE from a single safetensors file.+ """Load a Wan 2.2 VAE from a single-file checkpoint.Picks the correct ``AutoencoderKLWan`` config based on ``z_dim``. The Wanecosystem ships two distinct VAE architectures:@@ -240,23 +275,22 @@ class VAELoader(GenericDiffusersLoader):from the TI2V-5B VAE checkpoint won't load (channel and shape mismatchesthroughout the encoder + decoder).- Forces bfloat16 (same as ``WanDiffusersModel`` and ``_load_wan_vae_diffusers``) —- fp16 is unstable on the Wan VAE, and the default ``precision: auto`` resolves to- float16 on CUDA.+ Reads the same formats and follows the same precision policy as `_load_wan_family_vae`: a+ 16-channel file registered under ``wan`` is the VAE Anima also accepts, and must not behave+ differently for the base it was probed as."""import accelerate- import torchfrom diffusers.models.autoencoders.autoencoder_kl_wan import AutoencoderKLWan- from safetensors.torch import load_filefrom invokeai.backend.wan.rocm_causal_conv3d import patch_wan_causal_conv3d_for_rocmpatch_wan_causal_conv3d_for_rocm()- sd = load_file(config.path)+ dtype = _wan_family_dtype(self._torch_dtype)+ sd = _read_checkpoint(config.path)for k in list(sd.keys()):if sd[k].is_floating_point():- sd[k] = sd[k].to(torch.bfloat16)+ sd[k] = sd[k].to(dtype)new_sd_size = sum(t.nelement() * t.element_size() for t in sd.values())self._ram_cache.make_room(new_sd_size)@@ -279,10 +313,8 @@ class VAELoader(GenericDiffusersLoader):the model loader invocation since that's how cached entries are keyed.Loading ``AutoencoderKLWan`` directly here sidesteps the submodel check.- Forces bfloat16 (same as ``WanDiffusersModel``) — fp16 is unstable on the- Wan VAE.+ Runs in the configured precision except float16 -- see `_wan_family_dtype`."""- import torchfrom diffusers.models.autoencoders.autoencoder_kl_wan import AutoencoderKLWanfrom invokeai.backend.wan.rocm_causal_conv3d import patch_wan_causal_conv3d_for_rocm@@ -290,7 +322,7 @@ class VAELoader(GenericDiffusersLoader):patch_wan_causal_conv3d_for_rocm()return AutoencoderKLWan.from_pretrained(config.path,- torch_dtype=torch.bfloat16,+ torch_dtype=_wan_family_dtype(self._torch_dtype),local_files_only=True,)@@ -310,23 +342,22 @@ class VAELoader(GenericDiffusersLoader):checked here instead. Keys the module has no use for are not an error -- a redistributionmay carry extras -- but they are worth a line in the log.- Forces bfloat16 for the same reason as `_load_wan_vae` and `_load_wan_vae_diffusers` -- fp16- is unstable on the Wan VAE, and the default `precision: auto` resolves to float16 on CUDA.+ Reads safetensors and pickled checkpoints alike, and runs in the configured precision except+ float16, which is unstable on the Wan VAE -- see `_wan_family_dtype`."""import accelerate- import torchfrom diffusers.loaders.single_file_utils import convert_wan_vae_to_diffusersfrom diffusers.models.autoencoders import AutoencoderKLWan- from safetensors.torch import load_filefrom invokeai.backend.wan.rocm_causal_conv3d import patch_wan_causal_conv3d_for_rocmpatch_wan_causal_conv3d_for_rocm()- sd = convert_wan_vae_to_diffusers(load_file(path))+ dtype = _wan_family_dtype(self._torch_dtype)+ sd = convert_wan_vae_to_diffusers(_read_checkpoint(path))for k in list(sd.keys()):if sd[k].is_floating_point():- sd[k] = sd[k].to(torch.bfloat16)+ sd[k] = sd[k].to(dtype)self._ram_cache.make_room(sum(t.nelement() * t.element_size() for t in sd.values()))@@ -346,7 +377,7 @@ class VAELoader(GenericDiffusersLoader):return modeldef _load_qwen_image_vae(self, config: VAE_Checkpoint_QwenImage_Config) -> AnyModel:- """Load a Qwen Image VAE from a single safetensors file.+ """Load a Qwen Image VAE from a single-file checkpoint.Two layouts reach this method, and each is recognised by a key it must carry. Files exportedfrom the Qwen-Image repo carry the diffusers state-dict keys and are loaded directly,@@ -361,7 +392,6 @@ class VAELoader(GenericDiffusersLoader):"""import acceleratefrom diffusers.models.autoencoders.autoencoder_kl_qwenimage import AutoencoderKLQwenImage- from safetensors.torch import load_filekeys = _checkpoint_keys(config.path)@@ -375,7 +405,7 @@ class VAELoader(GenericDiffusersLoader):f"(the original Wan-family layout).")- sd = load_file(config.path)+ sd = _read_checkpoint(config.path)if self._torch_dtype is not None:for k in list(sd.keys()):diff --git a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.tsindex 9ccac8423d..eea8651c4f 100644--- a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts@@ -1027,7 +1027,7 @@ describe('Krea-2, Ideogram 4 and Wan policies', () => {name: 'Qwen3-VL',type: 'qwen3_vl_encoder',};- const wanVae: VaeModelConfig = { base: 'wan', key: 'wan-vae', name: 'Wan VAE', type: 'vae' };+ const wanVae: VaeModelConfig = { base: 'wan', key: 'wan-vae', latent_channels: 16, name: 'Wan VAE', type: 'vae' };const wanT5Encoder: ComponentModelConfig = { base: 'any', key: 'wan-t5', name: 'Wan T5', type: 'wan_t5_encoder' };it('uses a 16px grid for all three, matching their transformer patch sizes', () => {diff --git a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.tsindex c894e9577c..2932d77b8c 100644--- a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts@@ -31,9 +31,6 @@ import {getCompatibleDiffusersComponentSource,isBundledMainForBase,isAnimaQwen3Encoder,- isAnimaVae,- isKrea2Vae,- isQwenImageFamilyVae,isClipVariant,isDiffusersMainForBase,isFlux2DiffusersSourceForModel,@@ -42,7 +39,7 @@ import {isNonAnimaQwen3Encoder,isSelfContainedSDNQFlux1Pipeline,isSelfContainedSDNQPipeline,- isVaeForBases,+ isVaeAcceptedByBase,type GenerateComponentFilter,} from './componentCompatibility';import { DYNAMIC_PROMPTS_DEFAULT_MAX_PROMPTS } from './dynamicPrompts';@@ -255,9 +252,15 @@ const getBaseGenerationConfig = (** `null` rather than a default so callers keep owning their own "nothing selected" behaviour --* the canvas has a different sensible answer there than a generation graph does.+ *+ * External generators are the exception: the backend describes the architectures it runs, not a+ * provider's API, so no row will ever arrive for them. They keep the generic grid, as they did+ * before the table existed -- answering `null` would stop recall and the canvas size sync for good.*/export const getDimensionGrid = (base: string, variant?: unknown): number | null =>- getArchitectureFeatures(base, variant)?.dimension_grid ?? null;+ base === 'external'+ ? FALLBACK_GENERATION_CONFIG.dimensions.grid+ : (getArchitectureFeatures(base, variant)?.dimension_grid ?? null);/*** Whether the served table actually describes this model's architecture.@@ -950,6 +953,9 @@ const getBaseComponentSectionPolicy = (return EMPTY_COMPONENT_POLICY;}+ // The graph builder sends a VAE by `isVaeCompatibleWithGenerateModel`, which reads the same row.+ const isAcceptedVae = isVaeAcceptedByBase(model.base);+switch (model.base) {case 'flux':return {@@ -965,7 +971,7 @@ const getBaseComponentSectionPolicy = (missingMessage: 'Generate needs a CLIP Embed model for FLUX models.',},{- ...vaeSlot('Required for FLUX.1 models.', isVaeForBases(['flux'])),+ ...vaeSlot('Required for FLUX.1 models.', isAcceptedVae),required: (ctx) => !isSelfContainedSDNQFlux1Pipeline(ctx.model),missingMessage: 'Generate needs a VAE for FLUX models.',},@@ -1000,10 +1006,7 @@ const getBaseComponentSectionPolicy = (return createPolicy(!isSelfContainedSDNQPipeline(model) && model.format !== 'diffusers', [encoderSlot,{- ...vaeSlot(- 'Optional override; otherwise an installed FLUX.2 Diffusers model is used.',- isVaeForBases(['flux2'])- ),+ ...vaeSlot('Optional override; otherwise an installed FLUX.2 Diffusers model is used.', isAcceptedVae),required: (ctx) => !hasFlux2DiffusersVaeSource(ctx),missingMessage: 'Generate needs a VAE for non-Diffusers FLUX.2 models.',},@@ -1014,7 +1017,7 @@ const getBaseComponentSectionPolicy = (t5EncoderSlot('Optional override; the main model is used when omitted.'),clipVariantSlot('clipLEmbedModel', 'CLIP L', 'large', 'Optional CLIP-L override.'),clipVariantSlot('clipGEmbedModel', 'CLIP G', 'gigantic', 'Optional CLIP-G override.'),- vaeSlot('Optional VAE override.', isVaeForBases(['sd-3'])),+ vaeSlot('Optional VAE override.', isAcceptedVae),]);case 'qwen-image':return createPolicy(model.format !== 'diffusers', [@@ -1029,8 +1032,8 @@ const getBaseComponentSectionPolicy = (},{...vaeSlot(- 'Optional override, or required with a non-Diffusers model and no component source.',- isQwenImageFamilyVae+ 'The same VAE may be installed under the Qwen-Image or Anima base, so both are listed. Optional override, or required with a non-Diffusers model and no component source.',+ isAcceptedVae),required: (ctx) => !isBundledOrDiffusersSourceSatisfied(ctx),missingMessage: 'Generate needs a VAE for non-Diffusers Qwen Image models.',@@ -1050,7 +1053,7 @@ const getBaseComponentSectionPolicy = ({...vaeSlot('Z-Image decodes with the FLUX VAE, so FLUX-base VAEs are listed here — they are fully compatible. Required unless a Diffusers component source is available.',- isVaeForBases(['flux'])+ isAcceptedVae),required: (ctx) => !isBundledOrDiffusersSourceSatisfied(ctx),missingMessage: 'Generate needs a VAE for Z-Image models.',@@ -1063,7 +1066,7 @@ const getBaseComponentSectionPolicy = ({...vaeSlot('Krea-2 decodes with the Qwen-Image 16-channel VAE; the same VAE may be installed under the Qwen-Image or Anima base, so both are listed. Required for non-Diffusers Krea-2 models.',- isKrea2Vae+ isAcceptedVae),required: (ctx) => ctx.model.format !== 'diffusers',missingMessage: 'Generate needs a VAE for non-Diffusers Krea-2 models.',@@ -1083,7 +1086,7 @@ const getBaseComponentSectionPolicy = ('Select a Diffusers Wan model to provide VAE and text-encoder components.'),{- ...vaeSlot('Required unless a Diffusers component source is available.', isVaeForBases(['wan'])),+ ...vaeSlot('Required unless a Diffusers component source is available.', isAcceptedVae),required: (ctx) => !isBundledOrDiffusersSourceSatisfied(ctx),missingMessage: 'Generate needs a VAE for Wan models.',},@@ -1103,8 +1106,8 @@ const getBaseComponentSectionPolicy = (},{...vaeSlot(- 'Anima accepts VAEs installed under the Anima, Qwen-Image, or FLUX base — the same physical VAE ships under any of the three. Required for Anima models.',- isAnimaVae+ 'Anima decodes with the 16-channel Wan 2.1 VAE, which may be installed under the Anima, Qwen-Image, or Wan base, so all three are listed. Required for Anima models.',+ isAcceptedVae),required: () => true,missingMessage: 'Generate needs a VAE for Anima models.',diff --git a/invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.test.ts b/invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.test.tsindex 75cdf5a65a..30beb70935 100644--- a/invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.test.ts@@ -10,13 +10,13 @@ import type { ComponentModelConfig, GenerateModelConfig, VaeModelConfig } from 'import {getCompatibleSelectedComponentKey,isAnimaQwen3Encoder,- isAnimaVae,isFlux2DiffusersSourceForModel,isFlux2MistralEncoder,isFlux2Qwen3EncoderForModel,isNonAnimaQwen3Encoder,isSelfContainedSDNQFlux1Pipeline,isSelfContainedSDNQPipeline,+ isVaeAcceptedByBase,isVaeCompatibleWithGenerateModel,isVaeForBases,type GenerateComponentCandidate,@@ -144,6 +144,8 @@ describe('Generate component compatibility', () => {});it('allows only backend-supported Anima VAE families', () => {+ const isAnimaVae = isVaeAcceptedByBase('anima');+expect(isAnimaVae(candidate({ base: 'anima', type: 'vae' }))).toBe(true);expect(isAnimaVae(candidate({ base: 'qwen-image', type: 'vae' }))).toBe(true);expect(isAnimaVae(candidate({ base: 'wan', latent_channels: 16, type: 'vae' }))).toBe(true);@@ -156,7 +158,7 @@ describe('Generate component compatibility', () => {it('offers no VAE at all before the capability table has loaded', () => {resetArchitectureCapabilities();- expect(isAnimaVae(candidate({ base: 'anima', type: 'vae' }))).toBe(false);+ expect(isVaeAcceptedByBase('anima')(candidate({ base: 'anima', type: 'vae' }))).toBe(false);expect(isVaeCompatibleWithGenerateModel({ base: 'sdxl', key: 'sdxl', name: 'SDXL', type: 'main' }, {base: 'sdxl',@@ -183,7 +185,7 @@ describe('Generate component compatibility', () => {it('hides a stale selected component when it no longer passes the picker filter', () => {const staleVae: ComponentModelConfig = { base: 'sdxl', key: 'sdxl-vae', name: 'SDXL VAE', type: 'vae' };- expect(getCompatibleSelectedComponentKey(staleVae, isAnimaVae)).toBeNull();+ expect(getCompatibleSelectedComponentKey(staleVae, isVaeAcceptedByBase('anima'))).toBeNull();});});diff --git a/invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.ts b/invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.tsindex 4afea0d410..4cda7785b6 100644--- a/invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.ts@@ -186,22 +186,11 @@ export const isVaeAcceptedByBase =acceptsVae(base, model);/**- * Anima's decode takes the 16-channel Wan 2.1 VAE, which is the same 194-tensor checkpoint- * whichever of three bases it was installed under. The 48-channel Wan VAE is a different decoder,- * which is why the served row constrains the width as well as the base.+ * The one VAE rule for a Generate model. The component picker and its validation filter with+ * `isVaeAcceptedByBase(model.base)` and the graph builder with this, so a VAE the user can select is+ * always one the graph sends -- the served row decides for both, including cross-base families such+ * as a Qwen-Image VAE installed under `anima`.*/-export const isAnimaVae: GenerateComponentFilter = isVaeAcceptedByBase('anima');--/** Qwen-Image's VAE, wherever it is registered from. */-export const isQwenImageFamilyVae: GenerateComponentFilter = isVaeAcceptedByBase('qwen-image');--/**- * Krea-2 decodes with the Qwen-Image VAE, which is why its graph reuses `qwen_image_l2i`. It reads- * its own row rather than aliasing Qwen-Image's: they agree today, and the point of reading the- * table is that neither has to stay in step with the other by hand.- */-export const isKrea2Vae: GenerateComponentFilter = isVaeAcceptedByBase('krea-2');-export const isVaeCompatibleWithGenerateModel = (model: GenerateModelConfig, vae: VaeModelConfig): boolean => {if (model.type === 'external_image_generator') {return false;diff --git a/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts b/invokeai/frontend/webv2/src/features/generation/core/graph.test.tsindex 79943851d0..b55d974d0d 100644--- a/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts@@ -322,6 +322,44 @@ describe('compileGenerateGraph', () => {expect(getEdge(mismatched, 'canvas_output', 'vae')?.source.node_id).toBe('model_loader');});+ it('keeps an SD3 VAE override its picker would hide out of the graph', () => {+ // The slot is optional, so validation never looks at it and the picker only hides a stale+ // selection. The builder used to send whatever was stored -- a FLUX VAE left over from a model+ // switch reached `sd3_model_loader`.+ const graph = compile(sd3Model, { vae: fluxVae });++ expect(graph.nodes.model_loader?.vae_model).toBeUndefined();+ expect(compile(sd3Model, { vae: { ...fluxVae, base: 'sd-3', key: 'sd3-vae' } }).nodes.model_loader).toMatchObject({+ vae_model: { key: 'sd3-vae' },+ });+ });++ it('sends the Qwen Image loader every VAE its picker offers', () => {+ // Regression: the picker read the served row, which lists Qwen-Image VAEs installed under+ // `anima`, while the builder filtered to base `qwen-image`. A checkpoint model then failed to+ // compile, and a Diffusers model silently dropped the override the user had selected.+ const animaRegisteredVae: VaeModelConfig = {+ base: 'anima',+ key: 'anima-qwen-vae',+ name: 'Qwen VAE (installed for Anima)',+ type: 'vae',+ };+ const qwenVlEncoder: ComponentModelConfig = {+ base: 'any',+ key: 'qwen-vl',+ name: 'Qwen VL',+ type: 'qwen_vl_encoder',+ };+ const qwenImageCheckpoint: MainModelConfig = { ...qwenImageModel, format: 'checkpoint', key: 'qwen-checkpoint' };++ expect(+ compile(qwenImageCheckpoint, { qwenVLEncoderModel: qwenVlEncoder, vae: animaRegisteredVae }).nodes.model_loader+ ).toMatchObject({ vae_model: animaRegisteredVae });+ expect(compile(qwenImageModel, { vae: animaRegisteredVae }).nodes.model_loader).toMatchObject({+ vae_model: animaRegisteredVae,+ });+ });+it('routes SD LoRAs through the UNet and CLIP conditioning chain', () => {const graph = compile(sd1Model, {loras: [{ isEnabled: true, model: sd1Lora, weight: 0.5 }],diff --git a/invokeai/frontend/webv2/src/features/generation/core/graph.ts b/invokeai/frontend/webv2/src/features/generation/core/graph.tsindex a1c9632207..8187afd83f 100644--- a/invokeai/frontend/webv2/src/features/generation/core/graph.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.ts@@ -28,14 +28,12 @@ import {import {getCompatibleDiffusersComponentSource,isAnimaQwen3Encoder,- isAnimaVae,isBundledMainForBase,isFlux2MistralEncoder,isFlux2Qwen3EncoderForModel,isNonAnimaQwen3Encoder,isSelfContainedSDNQFlux1Pipeline,- isKrea2Vae,- isVaeForBases,+ isVaeCompatibleWithGenerateModel,} from './componentCompatibility';import {addEdge,@@ -56,8 +54,9 @@ const getCompatibleComponentSource = (model: MainModelConfig): MainModelConfig | undefined => getCompatibleDiffusersComponentSource(model, settings.componentSourceModel);-const getCompatibleVae = (settings: GenerateSettings, bases: readonly string[]) =>- settings.vae && isVaeForBases(bases)(settings.vae) ? settings.vae : null;+// The picker's rule, not a copy of it: a base list here once dropped a VAE the picker offered.+const getCompatibleVae = (settings: GenerateSettings, model: MainModelConfig) =>+ settings.vae && isVaeCompatibleWithGenerateModel(model, settings.vae) ? settings.vae : null;const toImageField = (image: GenerateReferenceImageAsset) => ({image_name: getEffectiveReferenceImage(image).image_name,@@ -350,10 +349,10 @@ const buildSDGraph = (type: 'denoise_latents',});// A VAE override only applies when it matches the main model's architecture.- const vaeLoader =- settings.vae && settings.vae.base === model.base- ? addNode(graph, { id: 'vae_loader', type: 'vae_loader', vae_model: settings.vae })- : null;+ const vaeOverride = getCompatibleVae(settings, model);+ const vaeLoader = vaeOverride+ ? addNode(graph, { id: 'vae_loader', type: 'vae_loader', vae_model: vaeOverride })+ : null;const seamless =settings.seamlessXAxis || settings.seamlessYAxis? addNode(graph, {@@ -542,6 +541,7 @@ const buildSD3Graph = (projectSettings: GenerationProjectSettings): BackendGraphContract => {const graph: BackendGraphContract = { edges: [], id: createId('sd3_graph'), nodes: {} };+ const vaeModel = getCompatibleVae(settings, model);const { negativePrompt, positivePrompt, seed } = addPromptAndSeedNodes(graph);const modelLoader = addNode(graph, {clip_g_model: settings.clipGEmbedModel ?? undefined,@@ -550,7 +550,7 @@ const buildSD3Graph = (model,t5_encoder_model: settings.t5EncoderModel ?? undefined,type: 'sd3_model_loader',- vae_model: settings.vae ?? undefined,+ vae_model: vaeModel ?? undefined,});const posCond = addNode(graph, { id: 'pos_cond', type: 'sd3_text_encoder' });const negCond = addNode(graph, { id: 'neg_cond', type: 'sd3_text_encoder' });@@ -591,7 +591,7 @@ const buildSD3Graph = (addEdge(graph, seed, 'value', denoise, 'seed');addMetadata(graph, output, settings, model, 'sd3_txt2img', projectSettings, {scheduler: undefined,- vae: settings.vae ?? undefined,+ vae: vaeModel ?? undefined,...(shouldUsePidDecode(settings, model.base) ? getPidMetadata(settings) : {}),});@@ -613,7 +613,7 @@ const buildFluxGraph = (const hasBundledComponents = isSelfContainedSDNQFlux1Pipeline(model);const t5EncoderModel = hasBundledComponents ? null : requireComponent(settings.t5EncoderModel, 'T5 Encoder');const clipEmbedModel = hasBundledComponents ? null : requireComponent(settings.clipEmbedModel, 'CLIP Embed');- const vaeModel = hasBundledComponents ? null : requireComponent(getCompatibleVae(settings, ['flux']), 'FLUX VAE');+ const vaeModel = hasBundledComponents ? null : requireComponent(getCompatibleVae(settings, model), 'FLUX VAE');const scheduler = coerceSchedulerForGraph(model, settings.scheduler);const activeLoras = getActiveCompatibleLoras(settings, model);const modelLoader = addNode(graph, {@@ -702,7 +702,7 @@ const buildFlux2Graph = (? settings.qwen3EncoderModel: null;const encoderModel = isDev ? mistralEncoderModel : qwen3EncoderModel;- const vaeModel = getCompatibleVae(settings, ['flux2']);+ const vaeModel = getCompatibleVae(settings, model);if (!hasBundledComponents && (!vaeModel || !encoderModel)) {throw new Error(@@ -900,7 +900,7 @@ const buildQwenImageGraph = (): BackendGraphContract => {const sourceModel = getCompatibleComponentSource(settings, model);const hasBundledComponents = model.format === 'diffusers' || sourceModel;- const vaeModel = getCompatibleVae(settings, ['qwen-image']);+ const vaeModel = getCompatibleVae(settings, model);if (!hasBundledComponents && (!vaeModel || !settings.qwenVLEncoderModel)) {throw new Error(@@ -1026,7 +1026,7 @@ const buildZImageGraph = (settings.qwen3EncoderModel && isNonAnimaQwen3Encoder(settings.qwen3EncoderModel)? settings.qwen3EncoderModel: null;- const vaeModel = getCompatibleVae(settings, ['flux']);+ const vaeModel = getCompatibleVae(settings, model);if (!sourceModel && (!vaeModel || !qwen3EncoderModel)) {throw new Error('Z-Image models require a VAE and Qwen3 Encoder, or a Diffusers component source.');@@ -1111,7 +1111,7 @@ const buildAnimaGraph = (outputIsIntermediate: boolean,projectSettings: GenerationProjectSettings): BackendGraphContract => {- const vaeModel = requireComponent(settings.vae && isAnimaVae(settings.vae) ? settings.vae : null, 'Anima VAE');+ const vaeModel = requireComponent(getCompatibleVae(settings, model), 'Anima VAE');const qwen3EncoderModel = requireComponent(settings.qwen3EncoderModel && isAnimaQwen3Encoder(settings.qwen3EncoderModel) ? settings.qwen3EncoderModel : null,'Qwen3 Encoder'@@ -1186,10 +1186,7 @@ const buildKrea2Graph = (// or GGUF) bundles neither VAE nor encoder, so both must be selected. A diffusers model// carries them, and the loader extracts them when these are omitted.const isDiffusers = model.format === 'diffusers';- // Same base set as the picker (`isKrea2Vae`) and the backend loader: a Qwen-Image VAE- // installed under the `anima` base is still the VAE Krea-2 wants. Narrowing it here would- // silently drop a VAE the user had legitimately selected.- const vaeModel = settings.vae && isKrea2Vae(settings.vae) ? settings.vae : null;+ const vaeModel = getCompatibleVae(settings, model);const qwen3VlEncoderModel = settings.qwen3VLEncoderModel;if (!isDiffusers) {@@ -1326,7 +1323,7 @@ const buildWanGraph = (// A GGUF Wan main carries only the transformer, so the VAE and UMT5-XXL encoder come from// standalone models or a Diffusers component source.const sourceModel = getDiffusersSource(settings, model);- const vaeModel = getCompatibleVae(settings, ['wan']);+ const vaeModel = getCompatibleVae(settings, model);const wanT5EncoderModel = settings.wanT5EncoderModel;if (!sourceModel && (!vaeModel || !wanT5EncoderModel)) {diff --git a/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.test.ts b/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.test.tsindex 30c904993c..950046df1a 100644--- a/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.test.ts@@ -37,7 +37,7 @@ import type {GenerateComponentValueKey,SupportedGenerateBase,} from './baseGenerationPolicies';-import type { GenerateSettings, MainModelConfig, ModelIdentifierConfig } from './types';+import type { GenerateSettings, MainModelConfig, ModelIdentifierConfig, VaeModelConfig } from './types';import {getComponentSectionPolicy,@@ -84,7 +84,7 @@ const shapesForBase = (base: SupportedGenerateBase): readonly ModelShape[] => SH* Candidate components the slot filters get to choose from.** Deliberately a search over a pool rather than a hand-written model per slot: the filters- * (`isAnimaQwen3Encoder`, `isKrea2Vae`, `isFlux2Qwen3EncoderForModel`, ...) encode which base and+ * (`isAnimaQwen3Encoder`, `isVaeAcceptedByBase`, `isFlux2Qwen3EncoderForModel`, ...) encode which base and* variant a component must carry, and duplicating that knowledge here would make the test agree* with itself instead of with the policy.*/@@ -100,6 +100,8 @@ const CANDIDATE_VARIANTS = ['klein_4b','klein_9b',] as const;+/** VAE widths. A served row can constrain the width as well as the base -- Wan ships 16 and 48. */+const CANDIDATE_LATENT_CHANNELS = [undefined, 16, 48] as const;const candidatesForSlot = (slot: ComponentSlotPolicy): ModelIdentifierConfig[] => {const candidates: ModelIdentifierConfig[] = [];@@ -107,16 +109,19 @@ const candidatesForSlot = (slot: ComponentSlotPolicy): ModelIdentifierConfig[] =for (const type of slot.modelTypes) {for (const base of CANDIDATE_BASES) {for (const variant of CANDIDATE_VARIANTS) {- candidates.push({- base,- // A component source is a main model, and only a bundled one can stand in for the slots- // it satisfies — `isDiffusersMainForBase` and `isBundledMainForBase` both demand it.- format: slot.valueKind === 'main' ? 'diffusers' : undefined,- key: `${base}-${type}-${variant ?? 'novariant'}`,- name: `${base} ${type} ${variant ?? ''}`.trim(),- type,- variant: variant ?? null,- });+ for (const latentChannels of type === 'vae' ? CANDIDATE_LATENT_CHANNELS : [undefined]) {+ candidates.push({+ base,+ // A component source is a main model, and only a bundled one can stand in for the slots+ // it satisfies — `isDiffusersMainForBase` and `isBundledMainForBase` both demand it.+ format: slot.valueKind === 'main' ? 'diffusers' : undefined,+ key: `${base}-${type}-${variant ?? 'novariant'}${latentChannels ? `-${latentChannels}` : ''}`,+ name: `${base} ${type} ${variant ?? ''}`.trim(),+ type,+ variant: variant ?? null,+ ...(latentChannels ? { latent_channels: latentChannels } : {}),+ });+ }}}}@@ -189,17 +194,25 @@ const createModel = (base: SupportedGenerateBase, shape: ModelShape): MainModelC...shape.overrides,});+const satisfiedSettingsFor = (base: SupportedGenerateBase, shape: ModelShape) => {+ const model = createModel(base, shape);++ return {+ model,+ ...satisfyRequiredComponents(model, {+ ...getDefaultGenerateSettings(model),+ positivePrompt: 'a test prompt',+ seed: 1,+ shouldRandomizeSeed: false,+ }),+ };+};+const compileForShape = (base: SupportedGenerateBase,shape: ModelShape): { filled: GenerateComponentValueKey[]; graph: BackendGraphContract } => {- const model = createModel(base, shape);- const { filled, settings } = satisfyRequiredComponents(model, {- ...getDefaultGenerateSettings(model),- positivePrompt: 'a test prompt',- seed: 1,- shouldRandomizeSeed: false,- });+ const { filled, model, settings } = satisfiedSettingsFor(base, shape);// Compiling an invalid selection throws the first reason, which makes for a poor failure message.// Asserting here reports every unmet requirement at once, and doubles as the check that the@@ -247,6 +260,60 @@ describe('generate graph coverage', () => {}});+ it('sends every VAE the picker offers into the graph wherever a VAE is required', () => {+ // The slots above are filled with their *first* accepted candidate, which is how a builder that+ // re-filtered VAEs by its own base list -- dropping a Qwen-Image VAE installed under `anima` --+ // passed this suite. One VAE per accepted (base, width) is enough to see every rule a row has.+ //+ // Deliberately one test iterating the cases rather than `it.each` over a pre-filtered list: which+ // shapes require a VAE is answered by the capability table, and that is only seeded once tests run.+ const checked: string[] = [];++ for (const { base, shape } of cases) {+ const { filled, model, settings } = satisfiedSettingsFor(base, shape);++ if (!filled.includes('vae')) {+ continue;+ }++ const { slots } = getComponentSectionPolicy(model, settings);+ const vaeSlot = slots.find((slot) => slot.key === 'vae')!;+ const context = buildContext(model, settings, slots);+ const offered = new Map<string, ModelIdentifierConfig>();++ for (const candidate of candidatesForSlot(vaeSlot)) {+ if (!vaeSlot.filter || vaeSlot.filter(candidate, context)) {+ offered.set(`${candidate.base}/${String(candidate.latent_channels)}`, candidate);+ }+ }++ for (const vae of offered.values()) {+ const { backendGraph } = compileGenerateGraph({ ...settings, vae: vae as VaeModelConfig }, model, 'gallery', {+ useCpuNoise: true,+ });+ // Metadata records the selection whether or not the builder used it, so it does not count.+ const sent = Object.values(backendGraph.nodes).some(+ (node) => node.type !== 'core_metadata' && JSON.stringify(node).includes(`"${vae.key}"`)+ );++ expect(sent, `${base}/${shape.label} dropped the offered VAE ${vae.key}`).toBe(true);+ checked.push(`${base}/${shape.label}:${vae.base}/${String(vae.latent_channels)}`);+ }+ }++ // Guards against this test passing vacuously -- it did, while the list was computed before seeding.+ // The cross-base rows must each have been exercised with a VAE from another base.+ expect(checked).toEqual(+ expect.arrayContaining([+ 'anima/standalone-components:qwen-image/undefined',+ 'anima/standalone-components:wan/16',+ 'krea-2/standalone-components:anima/undefined',+ 'qwen-image/standalone-components:anima/undefined',+ 'z-image/standalone-components:flux/undefined',+ ])+ );+ });+it('emits the node types and fields the backend has to provide', async () => {const byBase: Record<string, { componentsFilled: Record<string, string[]>; nodeTypes: string[] }> = {};const fields: Record<diff --git a/invokeai/frontend/webv2/src/workbench/canvasDimsSync.test.ts b/invokeai/frontend/webv2/src/workbench/canvasDimsSync.test.tsindex 5956f75d72..207f4689cb 100644--- a/invokeai/frontend/webv2/src/workbench/canvasDimsSync.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasDimsSync.test.ts@@ -1,4 +1,4 @@-import type { MainModelConfig } from '@features/generation/contracts';+import type { GenerateWidgetValues, MainModelConfig } from '@features/generation/contracts';import type { WorkbenchState } from '@workbench/projectContracts';import {@@ -487,6 +487,35 @@ describe('createCanvasDimsSync before the capability table arrives', () => {return { getSyncDispatches: () => syncDispatches, store, sync: createCanvasDimsSync(countingStore) };};+ it('reconciles an external generator at once, which will never get a row to wait for', () => {+ // Holding off on `null` is right for an architecture the backend will describe. An external+ // provider has no row coming, so waiting would leave its canvas sync off for the whole session.+ const externalModel = {+ base: 'external',+ capabilities: { modes: ['txt2img'], supports_seed: true },+ format: 'external_api',+ key: 'external-model',+ name: 'OpenAI Image',+ provider_id: 'openai',+ type: 'external_image_generator',+ } as GenerateWidgetValues['model'];+ const store = createWorkbenchStore();++ store.commands.generation.setSource('canvas');+ store.commands.generation.patchSettings({+ height: 1024,+ model: externalModel,+ modelKey: externalModel.key,+ width: 1024,+ });+ dispatchCanvas(store, { bbox: { height: 1032, width: 1032, x: 0, y: 0 }, type: 'setCanvasBbox' });++ const sync = createCanvasDimsSync(store);++ expect(getActiveGenerate(store.getState()).values.width).toBe(1032);+ sync.dispose();+ });+it('writes nothing into the project while the architecture has no answer', () => {// Reopening a saved canvas project: `prev` is null, so the bbox wins and the dims are patched// and persisted. With no table the grid reads as 8, which is a real answer for SDXL and a guessdiff --git a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.tsindex e7d8fedd4c..5c33772474 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts@@ -517,6 +517,39 @@ describe('image recall', () => {expect(result?.values.aspectRatioId).toBe('2:3');});+ it('recalls the size for an external generator, which has no architecture row to wait for', () => {+ // The fail-closed rule below is for architectures the backend describes. An external provider+ // never gets a row, so treating it the same way lost its dimension recall for good.+ const externalModel = {+ base: 'external',+ capabilities: { modes: ['txt2img'], supports_seed: true },+ format: 'external_api',+ key: 'external-model',+ name: 'OpenAI Image',+ provider_id: 'openai',+ type: 'external_image_generator',+ } as GenerateWidgetValues['model'];+ const recall = () =>+ buildImageRecallSettings({+ currentValues: createValues({ model: externalModel, modelKey: externalModel.key }),+ image,+ kind: 'dimensions',+ metadata: null,+ models: [],+ supportedModels: [],+ vaeModels: [],+ });++ expect(recall()?.values).toMatchObject({ height: 768, width: 512 });++ resetArchitectureCapabilities();+ try {+ expect(recall()?.values).toMatchObject({ height: 768, width: 512 });+ } finally {+ setArchitectureCapabilities(architectureCapabilitiesFixture);+ }+ });+describe('before the capability table arrives', () => {// Recalled dimensions are snapped to the architecture's grid and then persisted into the// project. With no table every base reads as grid 8, so a 16- or 32-grid project woulddiff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.test.tsindex 5bfcaa0ae2..e9d7b22ca8 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/bboxGrid.test.ts@@ -69,6 +69,12 @@ describe('resolveModelGrid before the capability table arrives', () => {expect(resolveModelGrid(undefined)).toBe(DEFAULT_MODEL_GRID);});+ it('answers for an external generator too, which will never get a row to wait for', () => {+ // A writer holds off on `null`, so answering it here would stop the bbox <-> dims sync for+ // external providers for the whole session.+ expect(resolveModelGrid('external')).toBe(DEFAULT_MODEL_GRID);+ });+it('keeps the default for readers that must show something', () => {expect(gridSizeForModelBase('wan')).toBe(DEFAULT_MODEL_GRID);});diff --git a/tests/backend/model_manager/load/test_qwen_image_vae_layout.py b/tests/backend/model_manager/load/test_qwen_image_vae_layout.pyindex 8774c3f5c1..b9d2c3ca5f 100644--- a/tests/backend/model_manager/load/test_qwen_image_vae_layout.py+++ b/tests/backend/model_manager/load/test_qwen_image_vae_layout.py@@ -12,12 +12,17 @@ Both branches are now keyed on a marker the layout must carry, and both registraWan-family file land in one loader, so the dtype and strictness policy cannot diverge between them."""+from pathlib import Pathfrom unittest.mock import MagicMock, patchimport pytestimport torch-from invokeai.backend.model_manager.configs.vae import VAE_Checkpoint_Anima_Config+from invokeai.backend.model_manager.configs.vae import (+ VAE_Checkpoint_Anima_Config,+ VAE_Checkpoint_Wan_Config,+ VAE_Diffusers_Wan_Config,+)from invokeai.backend.model_manager.load.model_loaders.vae import VAELoader# One key from each rule the Wan converter implements, so the assertion below is over a real@@ -35,10 +40,10 @@ _ORIGINAL_LAYOUT = {}-def _loader() -> VAELoader:+def _loader(dtype: torch.dtype = torch.float16) -> VAELoader:+ """float16 by default: what `precision: auto` resolves to on CUDA, and what the Wan VAE is unstable in."""loader = VAELoader.__new__(VAELoader)- # float16 on CUDA is what `precision: auto` resolves to, and what the Wan VAE is unstable in.- loader._torch_dtype = torch.float16 # type: ignore[attr-defined]+ loader._torch_dtype = dtype # type: ignore[attr-defined]loader._ram_cache = MagicMock() # type: ignore[attr-defined]loader._logger = MagicMock() # type: ignore[attr-defined]return loader@@ -50,11 +55,13 @@ def _config(path: str = "vae.safetensors") -> MagicMock:return config-def test_the_original_layout_is_converted_and_loaded_in_bfloat16() -> None:- """`from_single_file` would fetch the Wan config over HTTP at load time, and it would honour- `self._torch_dtype` -- float16 on a default CUDA install, the dtype `_load_wan_vae` and- `_load_wan_vae_diffusers` both refuse for this exact autoencoder."""- state_dict = {key: torch.zeros(2, dtype=torch.float32) for key in _ORIGINAL_LAYOUT}+def _original_layout_state_dict() -> dict[str, torch.Tensor]:+ return {key: torch.zeros(2, dtype=torch.float32) for key in _ORIGINAL_LAYOUT}+++def _load_original_layout(loader: VAELoader) -> tuple[dict[str, torch.Tensor], MagicMock, object]:+ """Load the original layout from a (mocked) safetensors file; returns what reached the module."""+ state_dict = _original_layout_state_dict()with (patch(@@ -67,14 +74,22 @@ def test_the_original_layout_is_converted_and_loaded_in_bfloat16() -> None:patch("invokeai.backend.wan.rocm_causal_conv3d.patch_wan_causal_conv3d_for_rocm"),):wan.return_value.load_state_dict.return_value = ([], [])- loader = _loader()result = loader._load_qwen_image_vae(_config())+ (loaded,), _ = wan.return_value.load_state_dict.call_args+ return loaded, wan, result+++def test_the_original_layout_is_converted_and_float16_is_raised_to_bfloat16() -> None:+ """`from_single_file` would fetch the Wan config over HTTP at load time, and it would honour a+ float16 `self._torch_dtype` -- the dtype `_load_wan_vae` and `_load_wan_vae_diffusers` both refuse+ for this exact autoencoder."""+ loader = _loader(torch.float16)+ loaded, wan, result = _load_original_layout(loader)+wan.from_single_file.assert_not_called()wan.assert_called_once_with(z_dim=16)-- (loaded,), kwargs = wan.return_value.load_state_dict.call_args- assert kwargs == {"strict": False, "assign": True}+ assert wan.return_value.load_state_dict.call_args.kwargs == {"strict": False, "assign": True}assert set(loaded) == set(_ORIGINAL_LAYOUT.values())assert {tensor.dtype for tensor in loaded.values()} == {torch.bfloat16}@@ -84,11 +99,79 @@ def test_the_original_layout_is_converted_and_loaded_in_bfloat16() -> None:assert result is wan.return_value+def test_an_explicit_float32_request_is_kept() -> None:+ """Only float16 is unstable on this autoencoder. Casting a float32 request down to bfloat16 rounds+ the weights for as long as the model stays cached, which is the precision the user opted out of."""+ loaded, _, _ = _load_original_layout(_loader(torch.float32))++ assert {tensor.dtype for tensor in loaded.values()} == {torch.float32}++[email protected]("registration", ["anima", "qwen-image"])+def test_a_pickled_checkpoint_loads_like_a_safetensors_one(tmp_path: Path, registration: str) -> None:+ """Identification reads `.pt` as well as safetensors, so an Anima VAE saved that way installed+ cleanly and then failed at load time with a `SafetensorError`. Real file, real readers."""+ path = tmp_path / "vae.pt"+ torch.save({"state_dict": _original_layout_state_dict()}, path)+ loader = _loader(torch.float32)++ with (+ patch("accelerate.init_empty_weights"),+ patch("diffusers.models.autoencoders.AutoencoderKLWan") as wan,+ patch("invokeai.backend.wan.rocm_causal_conv3d.patch_wan_causal_conv3d_for_rocm"),+ ):+ wan.return_value.load_state_dict.return_value = ([], [])+ if registration == "anima":+ loader._load_model(VAE_Checkpoint_Anima_Config.model_construct(path=str(path)))+ else:+ loader._load_qwen_image_vae(_config(str(path)))++ (loaded,), _ = wan.return_value.load_state_dict.call_args+ assert set(loaded) == set(_ORIGINAL_LAYOUT.values())+ assert {tensor.dtype for tensor in loaded.values()} == {torch.float32}+++def test_a_wan_registered_checkpoint_follows_the_same_format_and_precision_policy(tmp_path: Path) -> None:+ """Anima also accepts the 16-channel VAE installed under `wan`, and that registration has its own+ loader. It read safetensors only and forced bfloat16, so one file behaved differently depending+ on the base it happened to be probed as -- `Wan2.1_VAE.pth` installed, then failed to load."""+ path = tmp_path / "Wan2.1_VAE.pth"+ state_dict = _original_layout_state_dict()+ torch.save(state_dict, path)++ with (+ patch("accelerate.init_empty_weights"),+ patch("diffusers.models.autoencoders.autoencoder_kl_wan.AutoencoderKLWan") as wan,+ patch("invokeai.backend.wan.rocm_causal_conv3d.patch_wan_causal_conv3d_for_rocm"),+ ):+ _loader(torch.float32)._load_model(+ VAE_Checkpoint_Wan_Config.model_construct(path=str(path), latent_channels=16)+ )++ wan.assert_called_once_with(z_dim=16)+ (loaded,), _ = wan.return_value.load_state_dict.call_args+ assert set(loaded) == set(state_dict)+ assert {tensor.dtype for tensor in loaded.values()} == {torch.float32}++[email protected](("requested", "expected"), [(torch.float16, torch.bfloat16), (torch.float32, torch.float32)])+def test_a_wan_diffusers_folder_follows_the_same_precision_policy(+ requested: torch.dtype, expected: torch.dtype+) -> None:+ with (+ patch("diffusers.models.autoencoders.autoencoder_kl_wan.AutoencoderKLWan") as wan,+ patch("invokeai.backend.wan.rocm_causal_conv3d.patch_wan_causal_conv3d_for_rocm"),+ ):+ _loader(requested)._load_model(VAE_Diffusers_Wan_Config.model_construct(path="wan-vae"))++ assert wan.from_pretrained.call_args.kwargs["torch_dtype"] == expected++def test_a_conversion_that_leaves_a_tensor_unset_is_an_error_not_a_warning() -> None:"""`from_single_file` loads with `strict=False` and reports only *unexpected* keys, so a tensorthe conversion never produced stays on the meta device and surfaces at the first decode --after the model has loaded and generation has begun."""- state_dict = {key: torch.zeros(2, dtype=torch.float32) for key in _ORIGINAL_LAYOUT}+ state_dict = _original_layout_state_dict()with (patch(@@ -108,8 +191,7 @@ def test_a_conversion_that_leaves_a_tensor_unset_is_an_error_not_a_warning() ->def test_the_anima_registration_takes_the_same_path() -> None:"""The same checkpoint, registered for a different family. It used to be loaded by a separate- branch that passed `self._torch_dtype`, so `anima` and `qwen-image` disagreed about the dtype- of byte-identical weights."""+ branch, so `anima` and `qwen-image` disagreed about the dtype of byte-identical weights."""loader = _loader()with patch.object(VAELoader, "_load_wan_family_vae") as load_wan_family:result = loader._load_model(VAE_Checkpoint_Anima_Config.model_construct(path="anima-vae.safetensors"))@@ -139,6 +221,21 @@ def test_the_diffusers_layout_still_loads_directly() -> None:assert result is qwen.return_value+def test_a_pickled_checkpoint_in_the_diffusers_layout_loads_too(tmp_path: Path) -> None:+ """The layout probe and the load are separate reads; both have to understand a `.pt` file."""+ path = tmp_path / "qwen-image-vae.pt"+ torch.save({"decoder.conv_in.weight": torch.zeros(1)}, path)++ with (+ patch("accelerate.init_empty_weights"),+ patch("diffusers.models.autoencoders.autoencoder_kl_qwenimage.AutoencoderKLQwenImage") as qwen,+ ):+ _loader(torch.float32)._load_qwen_image_vae(_config(str(path)))++ (loaded,), _ = qwen.return_value.load_state_dict.call_args+ assert set(loaded) == {"decoder.conv_in.weight"}++def test_a_checkpoint_in_neither_layout_is_rejected() -> None:"""The discriminator used to be a negation, so this file was assumed to be the Wan layout.