Skip to content

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

fix(webv2): withhold policy recalls until capabilities load

Alexander Eichhorn27c7efe128a7
diff --git a/invokeai/frontend/webv2/src/app/GenerateWidgetSyncRuntime.tsx b/invokeai/frontend/webv2/src/app/GenerateWidgetSyncRuntime.tsx
index 17acbabe22..5a0f325864 100644
--- a/invokeai/frontend/webv2/src/app/GenerateWidgetSyncRuntime.tsx
+++ b/invokeai/frontend/webv2/src/app/GenerateWidgetSyncRuntime.tsx
@@ -45,7 +45,7 @@ export const GenerateWidgetSyncRuntime = () => {
// Kicked here, at app boot, so the gate's window is one round trip rather than "whenever the
// Generate panel is first opened".
- ensureArchitectureCapabilitiesLoaded();
+ void ensureArchitectureCapabilitiesLoaded();
void ensureModelsLoaded();
return () => runtime.dispose();
});
diff --git a/invokeai/frontend/webv2/src/features/generation/data/architectureCapabilitiesStore.ts b/invokeai/frontend/webv2/src/features/generation/data/architectureCapabilitiesStore.ts
index 958ab54c33..803d5c81a5 100644
--- a/invokeai/frontend/webv2/src/features/generation/data/architectureCapabilitiesStore.ts
+++ b/invokeai/frontend/webv2/src/features/generation/data/architectureCapabilitiesStore.ts
@@ -99,15 +99,20 @@ export const refreshArchitectureCapabilities = (): Promise<void> =>
});
});
-/** Fetch on first use or retry after an error, so one failed load never sticks. */
-export const ensureArchitectureCapabilitiesLoaded = (): void => {
+/**
+ * Fetch on first use or retry after an error, so one failed load never sticks. Settles when the load
+ * it started or joined does; it never rejects -- the outcome is the snapshot's status.
+ */
+export const ensureArchitectureCapabilitiesLoaded = (): Promise<void> => {
isRequested = true;
const { status } = store.getSnapshot();
if (status === 'idle' || status === 'error') {
- void refreshArchitectureCapabilities();
+ return refreshArchitectureCapabilities();
}
+
+ return refreshFlight.inflight() ?? Promise.resolve();
};
export const getArchitectureCapabilitiesSnapshot = (): ArchitectureCapabilitiesSnapshot => store.getSnapshot();
diff --git a/invokeai/frontend/webv2/src/features/generation/settings.ts b/invokeai/frontend/webv2/src/features/generation/settings.ts
index 987ecd2d34..074d2fbd65 100644
--- a/invokeai/frontend/webv2/src/features/generation/settings.ts
+++ b/invokeai/frontend/webv2/src/features/generation/settings.ts
@@ -56,6 +56,7 @@ export {
SCHEDULER_OPTIONS,
type GenerateModelSelectionResult,
} from './core/baseGenerationPolicies';
+export { hasArchitectureCapabilities } from './core/architectureCapabilities';
export {
resolveGenerateWidgetValues,
type ResolvedGenerateWidgetValues,
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.tsx
index 8a5667e064..d0916011fc 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.tsx
@@ -7,13 +7,12 @@ import { isLoraModelConfig, normalizeGenerateSettings } from '@features/generati
import {
ensureArchitectureCapabilitiesLoaded,
getArchitectureCapabilitiesSnapshot,
- subscribeArchitectureCapabilities,
useArchitectureCapabilitiesSelector,
} from '@features/generation/data/architectureCapabilitiesStore';
import { resolveGenerateWidgetValues } from '@features/generation/settings';
import { focusIfUnclaimed } from '@platform/react/focusIfUnclaimed';
import { Button } from '@platform/ui/Button';
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useCallback, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { getGenerateFormCommitPatch } from './generateFormViewModel';
@@ -62,26 +61,14 @@ export const GenerateWidgetView = () => {
focusHandoffPending.current = true;
setHasRequestedRetry(true);
- ensureArchitectureCapabilitiesLoaded();
- }, [isRetrying]);
-
- // The request belongs to one retry. Once that load settles, a later reload -- an account switch,
- // a retry started from another panel -- is not this widget's retry: no failure surface while it
- // loads, and no focus taken when it lands.
- useEffect(() => {
- if (!hasRequestedRetry) {
- return undefined;
- }
-
- return subscribeArchitectureCapabilities(() => {
- const next = getArchitectureCapabilitiesSnapshot().status;
-
- if (next !== 'loading') {
- focusHandoffPending.current = next === 'loaded';
- setHasRequestedRetry(false);
- }
+ // The request belongs to this retry. Once it settles, a later reload -- an account switch, a
+ // retry started from another panel -- is not this widget's: no failure surface while it loads,
+ // and no focus taken when it lands. The form may already have mounted and taken the handoff.
+ void ensureArchitectureCapabilitiesLoaded().then(() => {
+ focusHandoffPending.current &&= getArchitectureCapabilitiesSnapshot().status === 'loaded';
+ setHasRequestedRetry(false);
});
- }, [hasRequestedRetry]);
+ }, [isRetrying]);
const handOverFocus = useCallback((element: HTMLDivElement | null) => {
if (element && focusHandoffPending.current) {
diff --git a/invokeai/frontend/webv2/src/platform/react/focusIfUnclaimed.ts b/invokeai/frontend/webv2/src/platform/react/focusIfUnclaimed.ts
index 878f0008fe..87c3c24030 100644
--- a/invokeai/frontend/webv2/src/platform/react/focusIfUnclaimed.ts
+++ b/invokeai/frontend/webv2/src/platform/react/focusIfUnclaimed.ts
@@ -3,16 +3,21 @@ const FOCUSABLE = ['button', '[href]', 'input', 'select', 'textarea', '[tabindex
.map((selector) => `${selector}:not([disabled]):not([tabindex="-1"]):not([aria-hidden="true"])`)
.join(', ');
+/** Moves focus to the first operable element inside `element`. */
+export const focusFirstOperable = (element: HTMLElement | null): void => {
+ element?.querySelector<HTMLElement>(FOCUSABLE)?.focus();
+};
+
/**
* For content revealed after the control that held focus unmounted -- a retry button replaced by the
- * thing it loaded. Moves focus to the first operable element inside `element`, but only while nothing
- * holds focus: it rescues a keyboard user whose focus fell to `<body>` without pulling focus from
- * wherever someone has since moved it.
+ * thing it loaded. Moves focus into `element`, but only while nothing holds focus: it rescues a
+ * keyboard user whose focus fell to `<body>` without pulling focus from wherever someone has since
+ * moved it.
*/
export const focusIfUnclaimed = (element: HTMLElement | null): void => {
- if (!element || (document.activeElement !== null && document.activeElement !== document.body)) {
+ if (document.activeElement !== null && document.activeElement !== document.body) {
return;
}
- element.querySelector<HTMLElement>(FOCUSABLE)?.focus();
+ focusFirstOperable(element);
};
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.ts
index 6681e7e0c5..bd162f3cd9 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.ts
@@ -14,7 +14,14 @@ const galleryApi = vi.hoisted(() => ({
vi.mock('@features/gallery', () => galleryApi);
-import { seedArchitectureCapabilities } from '@features/generation/core/architectureCapabilities.testing';
+import {
+ resetArchitectureCapabilities,
+ setArchitectureCapabilities,
+} from '@features/generation/core/architectureCapabilities';
+import {
+ architectureCapabilitiesFixture,
+ seedArchitectureCapabilities,
+} from '@features/generation/core/architectureCapabilities.testing';
import { executeImageRecall } from './executeImageRecall';
@@ -88,6 +95,35 @@ describe('executeImageRecall', () => {
expect(add).toHaveBeenCalledWith(expect.objectContaining({ kind: 'success', title: 'Recalled remix settings' }));
});
+ it('persists no remix until model capabilities load, and says why', async () => {
+ const { add, commands, setSettings } = createCommands();
+
+ resetArchitectureCapabilities();
+ try {
+ await expect(
+ executeImageRecall({
+ commands,
+ generateValues: { modelKey: model.key },
+ image,
+ kind: 'remix',
+ models: [model],
+ projectId: 'project-1',
+ })
+ ).resolves.toBe(false);
+ } finally {
+ setArchitectureCapabilities(architectureCapabilitiesFixture);
+ }
+
+ expect(galleryApi.galleryImages.metadata).not.toHaveBeenCalled();
+ expect(setSettings).not.toHaveBeenCalled();
+ expect(add).toHaveBeenCalledWith({
+ kind: 'info',
+ message:
+ 'Model capabilities are not loaded, so settings that depend on the model cannot be recalled yet. Prompts and seed can. If loading failed, retry from the Generate panel.',
+ title: 'Cannot recall image data',
+ });
+ });
+
it('uses the freshest Generate values when recalling image dimensions', async () => {
const { commands, setSettings } = createCommands();
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.ts
index 383a12376f..3babdaf391 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.ts
@@ -28,6 +28,7 @@ import {
buildImageRecallSettings,
getImageRecallMessage,
getImageRecallTitle,
+ isImageRecallKindAvailable,
type ImageRecallKind,
} from './imageRecall';
@@ -158,6 +159,16 @@ export const executeImageRecall = async ({
return false;
}
+ if (!isImageRecallKindAvailable(kind)) {
+ commands.notifications.add({
+ kind: 'info',
+ message:
+ 'Model capabilities are not loaded, so settings that depend on the model cannot be recalled yet. Prompts and seed can. If loading failed, retry from the Generate panel.',
+ title: 'Cannot recall image data',
+ });
+ return false;
+ }
+
const metadata = kind === 'dimensions' ? null : await loadImageMetadata(image.imageName, owner);
assertAccountScopeCurrent(owner);
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts
index 5c33772474..4a9a24a256 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts
@@ -16,7 +16,7 @@ import {
} from '@features/generation/core/architectureCapabilities.testing';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-import { buildImageRecallSettings, getImageRecallCapabilities } from './imageRecall';
+import { buildImageRecallSettings, getImageRecallCapabilities, type ImageRecallKind } from './imageRecall';
const sdxlModel: MainModelConfig = { base: 'sdxl', key: 'sdxl-model', name: 'SDXL', type: 'main' };
const sd1Model: MainModelConfig = { base: 'sd-1', key: 'sd1-model', name: 'SD 1.5', type: 'main' };
@@ -577,19 +577,35 @@ describe('image recall', () => {
expect(result?.fields ?? []).not.toContain('size');
});
- it('recalls no size from metadata either', () => {
- const result = buildImageRecallSettings({
- currentValues: createValues(),
- image,
- kind: 'all',
- metadata: { height: 768, width: 512 },
- models: [],
- supportedModels: [],
- vaeModels: [],
- });
-
- // Without the fix this is ['size'] with the width snapped to the fallback grid 8.
- expect(result?.fields ?? []).not.toContain('size');
+ it('withholds Recall All and Remix but keeps prompts and seed', () => {
+ const metadata = { height: 768, model: { key: sdxlModel.key }, positive_prompt: 'a cat', seed: 7, width: 512 };
+ const recall = (kind: ImageRecallKind) =>
+ buildImageRecallSettings({
+ currentValues: createValues(),
+ image,
+ kind,
+ metadata,
+ models: [],
+ supportedModels: [sdxlModel],
+ vaeModels: [],
+ });
+
+ // Recall All used to apply the model's fallback defaults and skip the size, and the project kept
+ // that result after the table arrived.
+ expect(recall('all')).toBeNull();
+ expect(recall('remix')).toBeNull();
+ expect(recall('prompts')?.fields).toEqual(['prompts']);
+ expect(recall('seed')?.fields).toEqual(['seed']);
+ expect(
+ getImageRecallCapabilities({
+ currentValues: createValues(),
+ image,
+ metadata,
+ models: [],
+ supportedModels: [sdxlModel],
+ vaeModels: [],
+ })
+ ).toMatchObject({ all: false, clipSkip: false, prompts: true, remix: false, seed: true });
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts
index 761ae5c336..7408f24b85 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts
@@ -12,6 +12,7 @@ import {
getDimensionGrid,
getGenerationUiPolicy,
getSettingsWithModelDefaults,
+ hasArchitectureCapabilities,
isKnownScheduler,
isVaeCompatibleWithGenerateModel,
isValidKrea2RebalanceWeights,
@@ -464,6 +465,15 @@ export const getSupportedClipSkip = (metadata: unknown, model: GenerateModelConf
return clipSkip !== null && clipSkipMax !== null ? Math.min(clipSkipMax, clipSkip) : null;
};
+/**
+ * Recall All, Remix and CLIP skip read architecture policy -- model defaults, VAE and CLIP skip rules
+ * -- and their result is persisted into the project, where it outlives the outage. Without the served
+ * table they would be computed on fallbacks and stored. Prompts and seed are the image's own, and
+ * a dimensions recall already declines per model when it has no grid to snap to.
+ */
+export const isImageRecallKindAvailable = (kind: ImageRecallKind): boolean =>
+ kind === 'prompts' || kind === 'seed' || kind === 'dimensions' || hasArchitectureCapabilities();
+
export const getImageRecallCapabilities = ({
currentValues,
image,
@@ -517,11 +527,11 @@ export const getImageRecallCapabilities = ({
hasRebalance;
return {
- all: hasAnyMetadata,
- clipSkip: getSupportedClipSkip(metadata, currentValues.model) !== null,
+ all: hasAnyMetadata && isImageRecallKindAvailable('all'),
+ clipSkip: getSupportedClipSkip(metadata, currentValues.model) !== null && isImageRecallKindAvailable('clipSkip'),
dimensions: getImageSize(image, currentValues.model) !== null,
prompts: hasPrompts,
- remix: hasNonSeedMetadata,
+ remix: hasNonSeedMetadata && isImageRecallKindAvailable('remix'),
seed: hasSeed,
};
};
@@ -543,6 +553,10 @@ export const buildImageRecallSettings = ({
models: ComponentModelConfig[];
vaeModels: VaeModelConfig[];
}): ImageRecallResult | null => {
+ if (!isImageRecallKindAvailable(kind)) {
+ return null;
+ }
+
const fields: RecalledField[] = [];
let values: GenerateWidgetValues = cloneGenerateWidgetValues(currentValues);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.browser.test.tsx
index 264162b7c1..81fcc0d9f8 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.browser.test.tsx
@@ -146,4 +146,34 @@ describe('ControlLayerSettings and the capability table', () => {
expect(document.activeElement).not.toBe(document.body);
expect(host!.contains(document.activeElement)).toBe(true);
});
+
+ it('leaves focus where the user moved it while the retry was in flight', async () => {
+ getArchitectureCapabilities.mockRejectedValueOnce(new Error('Fixture capability outage.'));
+ await settle(ensureArchitectureCapabilitiesLoaded);
+ await render();
+
+ let finishLoad: (rows: ArchitectureCapabilitiesRow[]) => void = () => undefined;
+ getArchitectureCapabilities.mockReturnValueOnce(
+ new Promise((resolve) => {
+ finishLoad = resolve;
+ })
+ );
+ await settle(() => {
+ retryButton()?.focus();
+ retryButton()?.click();
+ });
+
+ // Someone starts typing elsewhere; the load landing must not pull them into this panel.
+ const elsewhere = document.createElement('input');
+ document.body.append(elsewhere);
+ elsewhere.focus();
+ try {
+ await settle(() => finishLoad(architectureCapabilitiesFixture));
+
+ expect(retryButton()).toBeUndefined();
+ expect(document.activeElement).toBe(elsewhere);
+ } finally {
+ elsewhere.remove();
+ }
+ });
});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx
index d512570739..2a73f59351 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx
@@ -25,13 +25,13 @@ import {
subscribeArchitectureCapabilities,
} from '@features/generation/runtime';
import { useModelsSelector } from '@features/models';
-import { focusIfUnclaimed } from '@platform/react/focusIfUnclaimed';
+import { focusFirstOperable } from '@platform/react/focusIfUnclaimed';
import { useExternalStoreSelector } from '@platform/state/selectors';
import { Button, Field, Select, Slider } from '@platform/ui';
import { lookupDocumentLeaf } from '@workbench/canvas-engine/api';
import { getCanvasOperations, resolveDefaultFilterForModel } from '@workbench/canvas-operations/api';
import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useCallback, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { getCompatibleControlModels } from './controlModelOptions';
@@ -124,29 +124,27 @@ export const ControlLayerSettings = ({ engine, layer, onOperationStarted }: Cont
);
const [hasRequestedCapabilitiesRetry, setHasRequestedCapabilitiesRetry] = useState(false);
const rootRef = useRef<HTMLDivElement | null>(null);
- // Set by the click, consumed once the retry has filled the panel in.
- const focusHandoffPending = useRef(false);
const retryCapabilities = useCallback(() => {
if (hasRequestedCapabilitiesRetry && capabilitiesStatus === 'loading') {
return;
}
- focusHandoffPending.current = true;
setHasRequestedCapabilitiesRetry(true);
- ensureArchitectureCapabilitiesLoaded();
+ // The request belongs to this retry; a later reload started elsewhere is not this panel's retry.
+ void ensureArchitectureCapabilitiesLoaded().then(() => setHasRequestedCapabilitiesRetry(false));
}, [capabilitiesStatus, hasRequestedCapabilitiesRetry]);
- // The request belongs to one retry; a later reload started elsewhere is not this panel's retry.
- useEffect(() => {
- if (!hasRequestedCapabilitiesRetry) {
+ // A load that lands unmounts the failure surface, and with it the retry button a keyboard user may
+ // be on. The ref's cleanup runs while the surface is still in the document, so focus is handed to
+ // the panel the load filled in before it can fall to <body>.
+ const handOverFocusOnLoad = useCallback((surface: HTMLDivElement | null) => {
+ if (!surface) {
return undefined;
}
- return subscribeArchitectureCapabilities(() => {
- const next = getArchitectureCapabilitiesSnapshot().status;
- if (next !== 'loading') {
- focusHandoffPending.current = next === 'loaded';
- setHasRequestedCapabilitiesRetry(false);
+ return () => {
+ if (surface.contains(document.activeElement) && getArchitectureCapabilitiesSnapshot().status === 'loaded') {
+ focusFirstOperable(rootRef.current);
}
- });
- }, [hasRequestedCapabilitiesRetry]);
+ };
+ }, []);
// Adapter kinds supported by the selected base. Z-Image Control is only shown
// when a compatible Z-Image main model is selected. Read inside the store's
// selector: the answer comes from the capability table, and a call memoised on
@@ -402,14 +400,6 @@ export const ControlLayerSettings = ({ engine, layer, onOperationStarted }: Cont
? validationReason
: null;
- // A successful retry unmounts the button that held focus; hand it to the panel the retry filled in.
- useEffect(() => {
- if (!capabilitiesUnavailable && focusHandoffPending.current) {
- focusHandoffPending.current = false;
- focusIfUnclaimed(rootRef.current);
- }
- }, [capabilitiesUnavailable]);
-
return (
<Stack ref={rootRef} gap="2">
<HStack gap="2">
@@ -519,7 +509,7 @@ export const ControlLayerSettings = ({ engine, layer, onOperationStarted }: Cont
</Text>
) : null}
{showCapabilitiesFailure ? (
- <HStack aria-busy={isRetryingCapabilities} gap="2" role="alert">
+ <HStack ref={handOverFocusOnLoad} aria-busy={isRetryingCapabilities} gap="2" role="alert">
<Text color="fg.warning" flex="1" fontSize="2xs">
{t('widgets.layers.control.capabilitiesLoadFailed')}
</Text>
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.py
index 4b7b6c99d4..e5d7194fa4 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
@@ -17,6 +17,7 @@ from unittest.mock import MagicMock, patch
import pytest
import torch
+from diffusers.models.autoencoders import AutoencoderKLWan
from invokeai.backend.model_manager.configs.vae import (
VAE_Checkpoint_Anima_Config,
@@ -40,6 +41,16 @@ _ORIGINAL_LAYOUT = {
}
+# The 16-channel Wan VAE's structure (8x spatial, unpatchified) at the smallest width that builds.
+_TINY_WAN_KWARGS = {
+ "base_dim": 2,
+ "dim_mult": [1, 1, 1, 1],
+ "num_res_blocks": 1,
+ "attn_scales": [],
+ "temperal_downsample": [False, True, True],
+}
+
+
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)
@@ -135,23 +146,29 @@ def test_a_wan_registered_checkpoint_follows_the_same_format_and_precision_polic
"""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."""
+ torch.manual_seed(0)
+ state_dict = AutoencoderKLWan(z_dim=16, **_TINY_WAN_KWARGS).state_dict()
path = tmp_path / "Wan2.1_VAE.pth"
- state_dict = _original_layout_state_dict()
torch.save(state_dict, path)
+ # A real module and the loader's own strict `load_state_dict`; only the width is shrunk. A
+ # checkpoint whose keys or shapes do not fit the model the loader builds fails here as it would
+ # for a user.
with (
- patch("accelerate.init_empty_weights"),
- patch("diffusers.models.autoencoders.autoencoder_kl_wan.AutoencoderKLWan") as wan,
+ patch(
+ "invokeai.backend.model_manager.load.model_loaders.vae._wan_vae_init_kwargs_for",
+ side_effect=lambda latent_channels: {**_TINY_WAN_KWARGS, "z_dim": latent_channels},
+ ),
patch("invokeai.backend.wan.rocm_causal_conv3d.patch_wan_causal_conv3d_for_rocm"),
):
- _loader(torch.float32)._load_model(
+ model = _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}
+ loaded = model.state_dict()
+ assert loaded.keys() == state_dict.keys()
+ assert all(torch.equal(loaded[key], state_dict[key]) for key in state_dict)
+ assert {tensor.dtype for tensor in loaded.values() if tensor.is_floating_point()} == {torch.float32}
@pytest.mark.parametrize(("requested", "expected"), [(torch.float16, torch.bfloat16), (torch.float32, torch.float32)])