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(architectures): close the review findings on the facet registry

Alexander Eichhornf7f3a8634ff7
diff --git a/invokeai/app/api/dependencies.py b/invokeai/app/api/dependencies.py
index c7bfe08a2f..a0d0902816 100644
--- a/invokeai/app/api/dependencies.py
+++ b/invokeai/app/api/dependencies.py
@@ -66,7 +66,7 @@ from invokeai.app.services.videos.videos_default import VideoService
from invokeai.app.services.wildcard_records.wildcard_records_sqlite import SqliteWildcardRecordsStorage
from invokeai.app.services.workflow_records.workflow_records_sqlite import SqliteWorkflowRecordsStorage
from invokeai.app.services.workflow_thumbnails.workflow_thumbnails_disk import WorkflowThumbnailFileStorageDisk
-from invokeai.backend.architectures import conditioning_infos
+from invokeai.backend.architectures import conditioning_safe_globals
from invokeai.backend.architectures import validate as validate_architectures
from invokeai.backend.stable_diffusion.diffusion.conditioning_data import ConditioningFieldData
from invokeai.backend.util.logging import InvokeAILogger
@@ -104,10 +104,13 @@ class ApiDependencies:
loop: asyncio.AbstractEventLoop,
logger: Logger = logger,
) -> None:
- # Before anything else, and at module scope above rather than lazily inside a function: the
- # registry has to be filled before `ObjectSerializerDisk` is constructed below, because that
- # mutates process-global torch state (`add_safe_globals`). Also covers every embedder that
- # never goes through `run_app` — tests, and scripts/generate_openapi_schema.py.
+ # The one authoritative architecture gate. Every entry point that builds services comes
+ # through here — `run_app`'s lifespan, and the embedders and tests that never go through
+ # `run_app` at all — so this is the only place it is called. It runs before anything else
+ # because `ObjectSerializerDisk` below derives its `safe_globals` from the registry, and
+ # that mutates process-global torch state. The import above is at module scope rather than
+ # lazily inside this function for the same reason, one step earlier: it is what fills the
+ # registry, and importing this module is all `scripts/generate_openapi_schema.py` does.
validate_architectures()
logger.info(f"InvokeAI version {__version__}")
@@ -162,8 +165,9 @@ class ApiDependencies:
# Every architecture's conditioning class, from what each declares under
# invokeai/backend/architectures/defs/. Missing one here fails nowhere near
# here: the encoder runs, writes its output, and the denoise node then dies
- # unpickling it.
- safe_globals=[ConditioningFieldData, *conditioning_infos()],
+ # unpickling it — which is why the list is assembled in one place and this call
+ # site is asserted against it in tests/backend/architectures/test_conditioning.py.
+ safe_globals=conditioning_safe_globals(),
ephemeral=True,
),
)
diff --git a/invokeai/app/invocations/flux/flux_redux.py b/invokeai/app/invocations/flux/flux_redux.py
index fb1128acf7..0bc9fdf1d8 100644
--- a/invokeai/app/invocations/flux/flux_redux.py
+++ b/invokeai/app/invocations/flux/flux_redux.py
@@ -25,7 +25,7 @@ from invokeai.app.services.model_records.model_records_base import ModelRecordCh
from invokeai.app.services.shared.invocation_context import InvocationContext
from invokeai.backend.flux.redux.flux_redux_model import FluxReduxModel
from invokeai.backend.model_manager.configs.factory import AnyModelConfig
-from invokeai.backend.model_manager.starter_models import siglip
+from invokeai.backend.model_manager.starter_models.common import siglip
from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelType
from invokeai.backend.sig_lip.sig_lip_pipeline import SigLipPipeline
from invokeai.backend.util.devices import TorchDevice
diff --git a/invokeai/app/invocations/ideal_size.py b/invokeai/app/invocations/ideal_size.py
index 8be24366fa..c35be6a808 100644
--- a/invokeai/app/invocations/ideal_size.py
+++ b/invokeai/app/invocations/ideal_size.py
@@ -58,7 +58,12 @@ class IdealSizeInvocation(BaseInvocation):
"ideal size to compute from."
)
dimension = settings.width * self.multiplier
- grid = require(unet_config.base, FeaturesFacet).dimension_grid
+ # The variant matters where an architecture's grid depends on it -- Wan TI2V-5B wants
+ # multiples of 32 where A14B wants 16. `wan_denoise` reads it off the same config the same
+ # way; a config that has no `variant` field, or whose variant is not named, gets the base
+ # grid.
+ variant = getattr(unet_config, "variant", None)
+ grid = require(unet_config.base, FeaturesFacet).resolve_dimension_grid(variant)
min_dimension = math.floor(dimension * 0.5)
# NOTE: this squares the *recommended default* width, which is a product decision, not the
# native training resolution. They coincide for the SD family this node was written for, but
diff --git a/invokeai/app/invocations/sd/ip_adapter.py b/invokeai/app/invocations/sd/ip_adapter.py
index 711f910d58..c6a45a0bb3 100644
--- a/invokeai/app/invocations/sd/ip_adapter.py
+++ b/invokeai/app/invocations/sd/ip_adapter.py
@@ -16,12 +16,12 @@ from invokeai.backend.model_manager.configs.ip_adapter import (
IPAdapter_Checkpoint_Config_Base,
IPAdapter_InvokeAI_Config_Base,
)
-from invokeai.backend.model_manager.starter_models import (
- StarterModel,
+from invokeai.backend.model_manager.starter_models.common import (
clip_vit_l_image_encoder,
ip_adapter_sd_image_encoder,
ip_adapter_sdxl_image_encoder,
)
+from invokeai.backend.model_manager.starter_models.types import StarterModel
from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelType
diff --git a/invokeai/app/run_app.py b/invokeai/app/run_app.py
index 022c2dec2c..0f0f18fa8c 100644
--- a/invokeai/app/run_app.py
+++ b/invokeai/app/run_app.py
@@ -74,7 +74,6 @@ def run_app() -> None:
# This import must happen after configure_torch_cuda_allocator() is called, because the module imports torch.
from invokeai.app.invocations.baseinvocation import InvocationRegistry
from invokeai.app.invocations.load_custom_nodes import load_custom_nodes
- from invokeai.backend.architectures import validate as validate_architectures
from invokeai.backend.util.devices import TorchDevice
torch_device_name = TorchDevice.get_generation_devices_summary(app_config.generation_devices)
@@ -118,11 +117,6 @@ def run_app() -> None:
f'Invocation "{invocation_type}" has unregistered output class "{output_annotation.__name__}"'
)
- # Every registered architecture must declare every required facet. Unlike the invocation-output
- # check above, this raises rather than warns: that one inspects third-party node packs, while
- # architectures are first-party and the set is closed, so an incomplete one is a bug here.
- validate_architectures()
-
if app_config.dev_reload:
# load_custom_nodes seems to bypass jurrigged's import sniffer, so be sure to call it *after* they're already
# imported.
diff --git a/invokeai/backend/architectures/__init__.py b/invokeai/backend/architectures/__init__.py
index cf4e50885f..0ea730afa1 100644
--- a/invokeai/backend/architectures/__init__.py
+++ b/invokeai/backend/architectures/__init__.py
@@ -14,7 +14,11 @@ from invokeai.backend.architectures.capabilities import (
architecture_capabilities,
)
from invokeai.backend.architectures.facet import Facet
-from invokeai.backend.architectures.facets.conditioning import ConditioningFacet, conditioning_infos
+from invokeai.backend.architectures.facets.conditioning import (
+ ConditioningFacet,
+ conditioning_infos,
+ conditioning_safe_globals,
+)
from invokeai.backend.architectures.facets.default_settings import (
DefaultSettingsFacet,
resolve_default_settings,
@@ -74,6 +78,7 @@ __all__ = [
"LatentSpace",
"LatentSpaceFacet",
"conditioning_infos",
+ "conditioning_safe_globals",
"declared_variant_enums",
"generation_modes",
"get_max_unet_downscale",
diff --git a/invokeai/backend/architectures/capabilities.py b/invokeai/backend/architectures/capabilities.py
index 72a0355919..dc4fbf8b91 100644
--- a/invokeai/backend/architectures/capabilities.py
+++ b/invokeai/backend/architectures/capabilities.py
@@ -12,9 +12,13 @@ fields on a schema webv2 already consumes.
Also deliberately not a computed field on `AnyModelConfig`: that would add these fields to all 115
config schemas and risk them being persisted into model records.
+
+The models here are response-only and stay open. `extra="forbid"` on one would reject nothing at
+runtime -- nothing parses these -- and only stamp `additionalProperties: false` into `openapi.json`,
+which turns every field this table grows into a breaking change for a strictly-validating client.
"""
-from pydantic import BaseModel, ConfigDict, Field
+from pydantic import BaseModel, Field
from invokeai.backend.architectures.facets.default_settings import DefaultSettingsFacet
from invokeai.backend.architectures.facets.features import (
@@ -27,7 +31,7 @@ from invokeai.backend.architectures.facets.latent_space import LatentSpaceFacet
from invokeai.backend.architectures.facets.modality import GenerationModeKind, ModalityFacet
from invokeai.backend.architectures.registry import generative_bases, require
from invokeai.backend.model_manager.configs.default_settings import MainModelDefaultSettings
-from invokeai.backend.model_manager.taxonomy import BaseModelType
+from invokeai.backend.model_manager.taxonomy import AnyVariant, BaseModelType
class NegativePromptPolicy(BaseModel):
@@ -36,8 +40,6 @@ class NegativePromptPolicy(BaseModel):
description="'always', 'cfg-gated' (only above CFG 1), or 'never'.",
)
- model_config = ConfigDict(extra="forbid")
-
class ArchitectureModality(BaseModel):
"""What this architecture can produce, and what it calls it in image metadata."""
@@ -48,14 +50,14 @@ class ArchitectureModality(BaseModel):
description="Prefix its mode strings carry in image metadata; null means unprefixed.",
)
- model_config = ConfigDict(extra="forbid")
-
class ArchitectureFeatures(BaseModel):
"""What a UI may offer for this architecture."""
negative_prompt: NegativePromptPolicy
- dimension_grid: int = Field(description="Width and height must be a multiple of this.")
+ dimension_grid: int = Field(
+ description="Width and height must be a multiple of this. A variant row may carry its own."
+ )
spatial_compression: int = Field(description="How much smaller a latent is than the image, per side.")
guidance_label: str = Field(description="What to call the guidance slider: 'CFG' or 'Guidance'.")
scheduler_set: SchedulerSet | None = Field(
@@ -77,8 +79,6 @@ class ArchitectureFeatures(BaseModel):
color_compensation: bool = False
vae_precision: bool = False
- model_config = ConfigDict(extra="forbid")
-
class ArchitectureCapabilities(BaseModel):
"""One row of the table."""
@@ -94,16 +94,16 @@ class ArchitectureCapabilities(BaseModel):
default=None, description="Recommended generation parameters, if the architecture has any."
)
- model_config = ConfigDict(extra="forbid")
-
-def _features_of(facet: FeaturesFacet, spatial_compression: int) -> ArchitectureFeatures:
+def _features_of(
+ facet: FeaturesFacet, spatial_compression: int, variant: AnyVariant | None = None
+) -> ArchitectureFeatures:
return ArchitectureFeatures(
negative_prompt=NegativePromptPolicy(
visible=facet.negative_prompt.visible,
usage=facet.negative_prompt.usage,
),
- dimension_grid=facet.dimension_grid,
+ dimension_grid=facet.resolve_dimension_grid(variant),
spatial_compression=spatial_compression,
guidance_label=facet.guidance_label,
scheduler_set=facet.scheduler_set,
@@ -125,11 +125,14 @@ def _features_of(facet: FeaturesFacet, spatial_compression: int) -> Architecture
def architecture_capabilities() -> list[ArchitectureCapabilities]:
"""Every row, base rows first, then the variant rows that override them.
- A variant gets its own row only where something actually differs — today that is the five
- architectures whose recommended parameters depend on the variant. Feature differences that hang
- on a variant are expressed on the base row instead, by
- `features.reference_images_require_variant`; Qwen-Image is the only one, and inventing a row for
- it would mean inventing which fields a variant row is allowed to omit.
+ A variant gets its own row only where something actually differs: its recommended parameters
+ (`DefaultSettingsFacet.by_variant`) or its dimension grid
+ (`FeaturesFacet.dimension_grid_by_variant`). Those two mappings are the whole rule — a row is
+ emitted for the union of their keys, and every row is rendered in full, so a client never has to
+ know which fields a variant row is allowed to omit.
+
+ Differences too small to have earned a mapping are expressed on the base row instead, by
+ `features.reference_images_require_variant`; Qwen-Image is the only one.
Sorted by base value, then variant, so the response is stable and diffable.
"""
@@ -143,17 +146,19 @@ def architecture_capabilities() -> list[ArchitectureCapabilities]:
defaults = require(base, DefaultSettingsFacet)
rendered = ArchitectureModality(modes=sorted(modality.modes), metadata_slug=modality.metadata_slug)
- rendered_features = _features_of(features, latent_space.primary.spatial_compression)
+ compression = latent_space.primary.spatial_compression
+ base_defaults = defaults.resolve()
rows.append(
ArchitectureCapabilities(
base=base,
modality=rendered,
- features=rendered_features,
- defaults=defaults.resolve(),
+ features=_features_of(features, compression),
+ defaults=base_defaults,
)
)
- for variant in sorted(v for v in defaults.by_variant if v is not None):
+ differing = (set(defaults.by_variant) | set(features.dimension_grid_by_variant)) - {None}
+ for variant in sorted(differing):
rows.append(
ArchitectureCapabilities(
base=base,
@@ -161,8 +166,8 @@ def architecture_capabilities() -> list[ArchitectureCapabilities]:
# "FluxVariantType.DevFill" rather than the "dev_fill" a client stores and sends.
variant=variant.value,
modality=rendered,
- features=rendered_features,
- defaults=defaults.by_variant[variant],
+ features=_features_of(features, compression, variant),
+ defaults=defaults.by_variant.get(variant, base_defaults),
)
)
return rows
diff --git a/invokeai/backend/architectures/defs/anima.py b/invokeai/backend/architectures/defs/anima.py
index 0953d44fb3..3051fb7be6 100644
--- a/invokeai/backend/architectures/defs/anima.py
+++ b/invokeai/backend/architectures/defs/anima.py
@@ -25,5 +25,8 @@ register(
guidance_label="CFG",
scheduler_set="anima",
scheduler_applies_to_graph=True,
+ # Positive conditioning only, for the same reason as Z-Image: the negative list is accepted
+ # but its masks are dropped.
+ supports_regional_guidance=True,
),
)
diff --git a/invokeai/backend/architectures/defs/sd_2.py b/invokeai/backend/architectures/defs/sd_2.py
index 068371fbdf..b5d1a2c004 100644
--- a/invokeai/backend/architectures/defs/sd_2.py
+++ b/invokeai/backend/architectures/defs/sd_2.py
@@ -29,6 +29,8 @@ register(
guidance_label="CFG",
scheduler_set="standard",
scheduler_applies_to_graph=True,
+ supports_regional_guidance=True,
+ regional_negative=True,
clip_skip_max=24,
supports_seamless=True,
supports_cfg_rescale=True,
diff --git a/invokeai/backend/architectures/defs/wan.py b/invokeai/backend/architectures/defs/wan.py
index ea69eaca66..0f07399ba7 100644
--- a/invokeai/backend/architectures/defs/wan.py
+++ b/invokeai/backend/architectures/defs/wan.py
@@ -36,6 +36,10 @@ register(
FeaturesFacet(
negative_prompt=NegativePrompt(visible=True, usage="always"),
dimension_grid=16,
+ # The transformer's patch_size=(1, 2, 2) doubles the VAE's spatial compression: 8x VAE for
+ # A14B is a 16-pixel grid, the TI2V-5B Wan2.2-VAE's 16x is a 32-pixel one. `wan_denoise`
+ # enforces the A14B number as a field constraint and the TI2V-5B one inside `invoke()`.
+ dimension_grid_by_variant={WanVariantType.TI2V_5B: 32},
guidance_label="Guidance",
scheduler_set="flow",
),
diff --git a/invokeai/backend/architectures/defs/z_image.py b/invokeai/backend/architectures/defs/z_image.py
index 2a031af3ea..80a1561ce7 100644
--- a/invokeai/backend/architectures/defs/z_image.py
+++ b/invokeai/backend/architectures/defs/z_image.py
@@ -34,6 +34,9 @@ register(
scheduler_set="flow",
scheduler_applies_to_graph=True,
control_kinds=frozenset({"z_image_control"}),
+ # The denoiser masks positive conditioning only: it accepts a negative list but discards
+ # the masks, so a "regional" negative would silently act globally.
+ supports_regional_guidance=True,
),
VariantFacet(
{
diff --git a/invokeai/backend/architectures/facets/conditioning.py b/invokeai/backend/architectures/facets/conditioning.py
index 58ed7be247..40bf335c4b 100644
--- a/invokeai/backend/architectures/facets/conditioning.py
+++ b/invokeai/backend/architectures/facets/conditioning.py
@@ -20,6 +20,7 @@ from typing import Any, ClassVar
from invokeai.backend.architectures.facet import Facet
from invokeai.backend.architectures.registry import generative_bases, get
+from invokeai.backend.stable_diffusion.diffusion.conditioning_data import ConditioningFieldData
@dataclass(frozen=True)
@@ -47,3 +48,16 @@ def conditioning_infos() -> tuple[type[Any], ...]:
"""
infos = {facet.info for base in generative_bases() if (facet := get(base, ConditioningFacet)) is not None}
return tuple(sorted(infos, key=lambda cls: cls.__name__))
+
+
+def conditioning_safe_globals() -> list[type[Any]]:
+ """The exact list `dependencies` hands the conditioning `ObjectSerializerDisk`.
+
+ Assembled here rather than at the call site so that a test can assert the call site passes
+ *this* list. A test that rebuilt `[ConditioningFieldData, *conditioning_infos()]` itself would
+ only ever agree with itself, and would stay green if the call site were shortened.
+
+ `ConditioningFieldData` leads because it is the envelope every saved conditioning is wrapped in;
+ the per-architecture classes it holds follow.
+ """
+ return [ConditioningFieldData, *conditioning_infos()]
diff --git a/invokeai/backend/architectures/facets/features.py b/invokeai/backend/architectures/facets/features.py
index f2180b5067..ec033e0ce5 100644
--- a/invokeai/backend/architectures/facets/features.py
+++ b/invokeai/backend/architectures/facets/features.py
@@ -12,10 +12,12 @@ be added without them, and where the three bases webv2 has never heard of — ER
and the SDXL refiner — get an answer too.
"""
-from dataclasses import dataclass
+from collections.abc import Mapping
+from dataclasses import dataclass, field
from typing import ClassVar, Literal
from invokeai.backend.architectures.facet import Facet
+from invokeai.backend.model_manager.taxonomy import AnyVariant
NegativePromptUsage = Literal["always", "cfg-gated", "never"]
"""`cfg-gated` means the field exists but only does anything above CFG 1 — the distilled models."""
@@ -43,9 +45,26 @@ class FeaturesFacet(Facet):
negative_prompt: NegativePrompt
dimension_grid: int
- """Width and height must be a multiple of this. Already declared on the denoise node as
- `multiple_of`; a test asserts the two agree, so this cannot drift into a UI that offers
- dimensions the node will reject."""
+ """Width and height must be a multiple of this, for every variant `dimension_grid_by_variant`
+ does not override.
+
+ Pinned to the `multiple_of` on the architecture's denoise node, where it has one: a test asserts
+ the two agree, so the base grid cannot drift into a UI that offers dimensions that node's field
+ validation will reject. It says nothing about constraints a node applies inside `invoke()` --
+ those are per-variant, and `dimension_grid_by_variant` is where they are declared."""
+
+ dimension_grid_by_variant: Mapping[AnyVariant, int] = field(default_factory=dict)
+ """Variants whose grid is coarser (or finer) than the base one, keyed by variant enum member.
+
+ Wan is the reason this exists: A14B denoises in the 16-channel space at 8x and takes multiples
+ of 16, TI2V-5B in the 48-channel Wan2.2 space at 16x and takes multiples of 32. The node fields
+ carry the A14B number, so 1280x720 -- both multiples of 16 -- was offered by the UI and then
+ rejected inside `wan_denoise.invoke()`, after enqueue and after the model had loaded.
+
+ Keys are variant enum members, with the same `str`-mixin hashing caveat as
+ `DefaultSettingsFacet.by_variant`. A variant that is not named, or a model whose variant is not
+ known, gets `dimension_grid`; `None` is not a key, because the base value is already the
+ fallback."""
guidance_label: Literal["CFG", "Guidance"] = "CFG"
"""What to call the slider. FLUX-family models expose a distilled guidance embedding rather than
@@ -80,6 +99,20 @@ class FeaturesFacet(Facet):
color_compensation: bool = False
vae_precision: bool = False
+ def __post_init__(self) -> None:
+ if None in self.dimension_grid_by_variant:
+ raise ValueError(
+ "FeaturesFacet.dimension_grid_by_variant has a None key. Unlike "
+ "DefaultSettingsFacet.by_variant, it has no fallback entry: `dimension_grid` is the "
+ "answer for every variant not named here, and a None key would be dead weight."
+ )
+
+ def resolve_dimension_grid(self, variant: AnyVariant | None = None) -> int:
+ """The grid one concrete model's width and height must be a multiple of."""
+ if variant is None:
+ return self.dimension_grid
+ return self.dimension_grid_by_variant.get(variant, self.dimension_grid)
+
@property
def supports_reference_images(self) -> bool:
return self.max_reference_images > 0
diff --git a/invokeai/backend/architectures/facets/latent_space.py b/invokeai/backend/architectures/facets/latent_space.py
index 76fe3aa81a..06c679c3fd 100644
--- a/invokeai/backend/architectures/facets/latent_space.py
+++ b/invokeai/backend/architectures/facets/latent_space.py
@@ -12,15 +12,20 @@ previously expressed by duplicating matrices under different names.
"""
from dataclasses import dataclass
-from typing import ClassVar
+from typing import ClassVar, Final
import torch
from PIL import Image
from invokeai.backend.architectures.facet import Facet
-from invokeai.backend.architectures.registry import require
+from invokeai.backend.architectures.registry import ArchitectureError, require
from invokeai.backend.model_manager.taxonomy import BaseModelType
+_DEFS_PACKAGE: Final = "invokeai/backend/architectures/defs/"
+"""Where a declaration lives. `registry.defs_module_path` names the exact file given a base; a
+`LatentSpace` is constructed before anything associates it with one, so the messages below point at
+the package and leave the filename to the traceback."""
+
# origingally adapted from code by @erucipe and @keturn here:
# https://discuss.huggingface.co/t/decoding-latents-to-rgb-without-upscaling/23204/7
# these updated numbers for v1.5 are from @torridgristle
@@ -264,6 +269,40 @@ class LatentSpace:
smooth_matrix: list[list[float]] | None = None
"""A 3x3 kernel convolved over the projection. Only SDXL's four-channel space uses one."""
+ def __post_init__(self) -> None:
+ """Reject a declaration `preview()` could not use.
+
+ Every shape here is read for the first time on the *first preview step* — after the model
+ has loaded and generation has begun — where a mismatch is a `RuntimeError` from a matmul or
+ a reshape. Checking at construction moves that to the import of the `defs/` module that
+ declared it, which happens at boot: the traceback names the file to fix, and a placeholder
+ never reaches a user's generation.
+ """
+ if len(self.rgb_factors) != self.channels or any(len(row) != 3 for row in self.rgb_factors):
+ widths = sorted({len(row) for row in self.rgb_factors})
+ raise ArchitectureError(
+ f"LatentSpace declares {self.channels} channels but its rgb_factors are "
+ f"{len(self.rgb_factors)} rows of width {widths}; the projection must be exactly "
+ f"{self.channels} rows of 3. The traceback names the module under {_DEFS_PACKAGE} "
+ f"that declared it."
+ )
+ if not any(factor for row in self.rgb_factors for factor in row):
+ raise ArchitectureError(
+ "LatentSpace.rgb_factors is all zeros, which projects every latent to the same "
+ "colour — it is the scaffolder's placeholder, not a VAE. Replace it with this "
+ f"VAE's real latent -> RGB matrix in the module under {_DEFS_PACKAGE} the traceback "
+ "names."
+ )
+ if self.rgb_bias is not None and len(self.rgb_bias) != 3:
+ raise ArchitectureError(
+ f"LatentSpace.rgb_bias has {len(self.rgb_bias)} entries; it is added to an RGB "
+ "triple and must have exactly 3."
+ )
+ if self.smooth_matrix is not None and (
+ len(self.smooth_matrix) != 3 or any(len(row) != 3 for row in self.smooth_matrix)
+ ):
+ raise ArchitectureError("LatentSpace.smooth_matrix is convolved as a 3x3 kernel and must be 3x3.")
+
def preview(self, sample: torch.Tensor) -> Image.Image:
"""Project a latent sample to a low-resolution RGB image.
diff --git a/invokeai/backend/architectures/facets/variant.py b/invokeai/backend/architectures/facets/variant.py
index 8ae945a1b7..0976571f8d 100644
--- a/invokeai/backend/architectures/facets/variant.py
+++ b/invokeai/backend/architectures/facets/variant.py
@@ -8,10 +8,10 @@ enum:
layer patcher.
- The PiD decoder's resolution presets are one enum shared across five bases.
-Two variant enums cannot live here at all: `ClipVariantType` and `Qwen3VariantType` sit on
-`base=Any` configs, and `Any` is a sentinel the registry refuses to register. They are named
-explicitly in `tests/backend/architectures/test_variants.py` so the completeness check against
-`AnyVariant` stays total rather than quietly partial.
+Three variant enums cannot live here at all: `ClipVariantType`, `Qwen3VariantType` and
+`MistralVariantType` sit on `base=Any` configs, and `Any` is a sentinel the registry refuses to
+register. They are named explicitly in `tests/backend/architectures/test_variants.py` so the
+completeness check against `AnyVariant` stays total rather than quietly partial.
This facet is deliberately *not* wired into `configs/factory.py`. That module validates a bare
variant string against `variant_type_adapter` without passing the base (`build_common_fields`), so
diff --git a/invokeai/backend/architectures/registry.py b/invokeai/backend/architectures/registry.py
index 5392674d89..b5bf23ebc7 100644
--- a/invokeai/backend/architectures/registry.py
+++ b/invokeai/backend/architectures/registry.py
@@ -6,7 +6,8 @@ rather than at boot. The registry moves those facts next to each other, in one f
architecture, and `validate()` turns "you forgot one" into a startup error.
Storage and error behaviour follow `model_manager.load.model_loader_registry`: a plain dict, and a
-double registration raises with the full context rather than overwriting.
+double registration raises with the full context rather than overwriting. Re-stating the *same*
+declaration is the exception — see `register()`.
"""
from typing import Final, TypeVar
@@ -32,6 +33,8 @@ _NOT_ARCHITECTURES: Final = frozenset(
`register()` and `validate()` read it, so there is no second list to keep in sync."""
_PACKAGE = "invokeai/backend/architectures"
+_FACETS_MODULE: Final = "invokeai.backend.architectures.facets"
+"""Where a facet has to live to be enforced by `validate()`. See the filter there."""
class ArchitectureError(ValueError):
@@ -53,17 +56,18 @@ def defs_module_path(base: BaseModelType) -> str:
def register(base: BaseModelType, *facets: Facet) -> None:
- """Declare what `base` is. Called once per architecture, from its own module under `defs/`."""
+ """Declare what `base` is. Called once per architecture, from its own module under `defs/`.
+
+ Re-executing a `defs/` module — `importlib.reload`, or jurigged re-running the file on save
+ under `--dev_reload` — calls this again with the same arguments. An identical declaration is the
+ same fact stated twice, so it is a no-op; only a *differing* one is the collision this guard
+ exists for. Facets are frozen dataclasses, so "identical" is by value.
+ """
if base in _NOT_ARCHITECTURES:
raise ArchitectureError(
f"'{base.value}' is not a model architecture and cannot be registered. "
f"It is one of {sorted(b.value for b in _NOT_ARCHITECTURES)}."
)
- if base in _ARCHITECTURES:
- raise ArchitectureError(
- f"Architecture '{base.value}' is already registered. Every architecture is declared "
- f"exactly once, in {defs_module_path(base)}."
- )
by_type: dict[type[Facet], Facet] = {}
for facet in facets:
@@ -74,6 +78,13 @@ def register(base: BaseModelType, *facets: Facet) -> None:
f"same register() call. See {defs_module_path(base)}."
)
by_type[facet_type] = facet
+
+ declared = _ARCHITECTURES.get(base)
+ if declared is not None and declared != by_type:
+ raise ArchitectureError(
+ f"Architecture '{base.value}' is already registered with a different declaration. Every "
+ f"architecture is declared exactly once, in {defs_module_path(base)}."
+ )
_ARCHITECTURES[base] = by_type
@@ -128,8 +139,9 @@ def validate() -> None:
automatic, so the way to fail here is to add an enum member and no file.
2. Every registered architecture declares every facet marked `REQUIRED`.
- Unlike the neighbouring custom-node check in `run_app`, which warns, this raises: architectures
- are first-party and the set is closed, so an incomplete one is a bug in this repository.
+ Called from `ApiDependencies.initialize`, which is the one place every entry point that builds
+ services passes through. Unlike the custom-node checks in `run_app`, which warn, this raises:
+ architectures are first-party and the set is closed, so an incomplete one is a bug here.
"""
missing_bases = sorted(
base.value for base in BaseModelType if base not in _NOT_ARCHITECTURES and base not in _ARCHITECTURES
@@ -143,7 +155,16 @@ def validate() -> None:
+ "'-' replaced by '_'."
)
- required = [facet_type for facet_type in Facet.FACET_TYPES if facet_type.REQUIRED]
+ # `Facet.FACET_TYPES` collects every `Facet` subclass created anywhere in the interpreter,
+ # custom-node packs included. A pack that merely defines a REQUIRED facet would otherwise make
+ # this raise sixteen times over, naming first-party files under defs/ as the culprit — and
+ # `load_custom_nodes` has already swallowed the pack's own errors by then, so nothing would
+ # point at the pack. Only this package's facets are requirements of this package.
+ required = [
+ facet_type
+ for facet_type in Facet.FACET_TYPES
+ if facet_type.REQUIRED and facet_type.__module__.startswith(f"{_FACETS_MODULE}.")
+ ]
problems = [
f"'{base.value}' does not declare {facet_type.__name__} (add it in {defs_module_path(base)})"
for base in sorted(_ARCHITECTURES, key=lambda b: b.value)
diff --git a/invokeai/backend/model_manager/starter_models/__init__.py b/invokeai/backend/model_manager/starter_models/__init__.py
index 3f6990e7f7..a6f17efe61 100644
--- a/invokeai/backend/model_manager/starter_models/__init__.py
+++ b/invokeai/backend/model_manager/starter_models/__init__.py
@@ -5,692 +5,248 @@ the sequence someone decided on. It stays written out here rather than assembled
per-architecture modules, because assembling it would lose that sequence and nothing could
reconstruct it.
-Every name is re-exported, so `from ...starter_models import <anything>` keeps working.
+The package exports the two catalogues and the types. Individual models are not API: import one
+from the module that defines it, the way `sd/ip_adapter.py` and `flux/flux_redux.py` do.
"""
from invokeai.backend.model_manager.starter_models.anima import (
- anima_base as anima_base,
-)
-from invokeai.backend.model_manager.starter_models.anima import (
- anima_lllite_depth_preview3 as anima_lllite_depth_preview3,
-)
-from invokeai.backend.model_manager.starter_models.anima import (
- anima_lllite_inpainting as anima_lllite_inpainting,
-)
-from invokeai.backend.model_manager.starter_models.anima import (
- anima_lllite_lineart_preview3 as anima_lllite_lineart_preview3,
-)
-from invokeai.backend.model_manager.starter_models.anima import (
- anima_lllite_pose_preview3 as anima_lllite_pose_preview3,
-)
-from invokeai.backend.model_manager.starter_models.anima import (
- anima_lllite_scribble_preview3 as anima_lllite_scribble_preview3,
-)
-from invokeai.backend.model_manager.starter_models.anima import (
- anima_lllite_sketch as anima_lllite_sketch,
-)
-from invokeai.backend.model_manager.starter_models.anima import (
- anima_vae as anima_vae,
-)
-from invokeai.backend.model_manager.starter_models.cogview4 import (
- cogview4 as cogview4,
-)
-from invokeai.backend.model_manager.starter_models.common import (
- anima_qwen3_encoder as anima_qwen3_encoder,
-)
-from invokeai.backend.model_manager.starter_models.common import (
- animesharp_v4_rcan as animesharp_v4_rcan,
-)
-from invokeai.backend.model_manager.starter_models.common import (
- clip_l_encoder as clip_l_encoder,
-)
-from invokeai.backend.model_manager.starter_models.common import (
- clip_vit_l_image_encoder as clip_vit_l_image_encoder,
-)
-from invokeai.backend.model_manager.starter_models.common import (
- dfn2b_clip_vit_l_image_encoder as dfn2b_clip_vit_l_image_encoder,
-)
-from invokeai.backend.model_manager.starter_models.common import (
- esrgan_srx4 as esrgan_srx4,
-)
-from invokeai.backend.model_manager.starter_models.common import (
- flux2_dev_comfy_mistral_bf16 as flux2_dev_comfy_mistral_bf16,
-)
-from invokeai.backend.model_manager.starter_models.common import (
- flux2_dev_comfy_mistral_fp4 as flux2_dev_comfy_mistral_fp4,
-)
-from invokeai.backend.model_manager.starter_models.common import (
- flux2_dev_comfy_mistral_fp8 as flux2_dev_comfy_mistral_fp8,
-)
-from invokeai.backend.model_manager.starter_models.common import (
- flux2_dev_cow_mistral_iq4_xs as flux2_dev_cow_mistral_iq4_xs,
-)
-from invokeai.backend.model_manager.starter_models.common import (
- flux2_dev_cow_mistral_q4 as flux2_dev_cow_mistral_q4,
-)
-from invokeai.backend.model_manager.starter_models.common import (
- flux2_dev_cow_mistral_q8 as flux2_dev_cow_mistral_q8,
-)
-from invokeai.backend.model_manager.starter_models.common import (
- flux2_klein_qwen3_4b_encoder as flux2_klein_qwen3_4b_encoder,
-)
-from invokeai.backend.model_manager.starter_models.common import (
- flux2_klein_qwen3_8b_encoder as flux2_klein_qwen3_8b_encoder,
-)
-from invokeai.backend.model_manager.starter_models.common import (
- gemma2_2b_encoder as gemma2_2b_encoder,
-)
-from invokeai.backend.model_manager.starter_models.common import (
- ip_adapter_sd_image_encoder as ip_adapter_sd_image_encoder,
-)
-from invokeai.backend.model_manager.starter_models.common import (
- ip_adapter_sdxl_image_encoder as ip_adapter_sdxl_image_encoder,
-)
-from invokeai.backend.model_manager.starter_models.common import (
- llava_onevision as llava_onevision,
-)
-from invokeai.backend.model_manager.starter_models.common import (
- llava_onevision_7b as llava_onevision_7b,
-)
-from invokeai.backend.model_manager.starter_models.common import (
- qwen2_5_1_5b_instruct as qwen2_5_1_5b_instruct,
-)
-from invokeai.backend.model_manager.starter_models.common import (
- qwen2_5_3b_instruct as qwen2_5_3b_instruct,
-)
-from invokeai.backend.model_manager.starter_models.common import (
- qwen3_vl_encoder_4b as qwen3_vl_encoder_4b,
-)
-from invokeai.backend.model_manager.starter_models.common import (
- qwen_vl_encoder_diffusers as qwen_vl_encoder_diffusers,
-)
-from invokeai.backend.model_manager.starter_models.common import (
- qwen_vl_encoder_fp8 as qwen_vl_encoder_fp8,
-)
-from invokeai.backend.model_manager.starter_models.common import (
- realesrgan_x2 as realesrgan_x2,
-)
-from invokeai.backend.model_manager.starter_models.common import (
- realesrgan_x4 as realesrgan_x4,
-)
-from invokeai.backend.model_manager.starter_models.common import (
- siglip as siglip,
-)
-from invokeai.backend.model_manager.starter_models.common import (
- smollm2_1_7b_instruct as smollm2_1_7b_instruct,
-)
-from invokeai.backend.model_manager.starter_models.common import (
- swinir as swinir,
-)
-from invokeai.backend.model_manager.starter_models.common import (
- t5_8b_quantized_encoder as t5_8b_quantized_encoder,
-)
-from invokeai.backend.model_manager.starter_models.common import (
- t5_base_encoder as t5_base_encoder,
-)
-from invokeai.backend.model_manager.starter_models.common import (
- t5_gguf_q3_k_s_encoder as t5_gguf_q3_k_s_encoder,
-)
-from invokeai.backend.model_manager.starter_models.common import (
- t5_gguf_q6_k_encoder as t5_gguf_q6_k_encoder,
-)
-from invokeai.backend.model_manager.starter_models.common import (
- wan_22_t5_encoder as wan_22_t5_encoder,
-)
-from invokeai.backend.model_manager.starter_models.common import (
- z_image_qwen3_encoder as z_image_qwen3_encoder,
+ anima_base,
+ anima_lllite_depth_preview3,
+ anima_lllite_inpainting,
+ anima_lllite_lineart_preview3,
+ anima_lllite_pose_preview3,
+ anima_lllite_scribble_preview3,
+ anima_lllite_sketch,
+ anima_vae,
)
+from invokeai.backend.model_manager.starter_models.cogview4 import cogview4
from invokeai.backend.model_manager.starter_models.common import (
- z_image_qwen3_encoder_quantized as z_image_qwen3_encoder_quantized,
-)
-from invokeai.backend.model_manager.starter_models.ernie_image import (
- ernie_image as ernie_image,
-)
-from invokeai.backend.model_manager.starter_models.ernie_image import (
- ernie_image_turbo as ernie_image_turbo,
-)
-from invokeai.backend.model_manager.starter_models.external import (
- GEMINI_3_1_FLASH_RESOLUTION_PRESETS as GEMINI_3_1_FLASH_RESOLUTION_PRESETS,
-)
-from invokeai.backend.model_manager.starter_models.external import (
- GEMINI_3_IMAGE_ALLOWED_ASPECT_RATIOS as GEMINI_3_IMAGE_ALLOWED_ASPECT_RATIOS,
-)
-from invokeai.backend.model_manager.starter_models.external import (
- GEMINI_3_IMAGE_MAX_SIZE as GEMINI_3_IMAGE_MAX_SIZE,
-)
-from invokeai.backend.model_manager.starter_models.external import (
- GEMINI_3_PRO_RESOLUTION_PRESETS as GEMINI_3_PRO_RESOLUTION_PRESETS,
-)
-from invokeai.backend.model_manager.starter_models.external import (
- OPENAI_GPT_IMAGE_ASPECT_RATIO_SIZES as OPENAI_GPT_IMAGE_ASPECT_RATIO_SIZES,
-)
-from invokeai.backend.model_manager.starter_models.external import (
- OPENAI_GPT_IMAGE_ASPECT_RATIOS as OPENAI_GPT_IMAGE_ASPECT_RATIOS,
-)
-from invokeai.backend.model_manager.starter_models.external import (
- OPENAI_GPT_IMAGE_PANEL_SCHEMA as OPENAI_GPT_IMAGE_PANEL_SCHEMA,
-)
-from invokeai.backend.model_manager.starter_models.external import (
- QWEN_IMAGE_2_ALLOWED_ASPECT_RATIOS as QWEN_IMAGE_2_ALLOWED_ASPECT_RATIOS,
-)
-from invokeai.backend.model_manager.starter_models.external import (
- QWEN_IMAGE_MAX_ALLOWED_ASPECT_RATIOS as QWEN_IMAGE_MAX_ALLOWED_ASPECT_RATIOS,
-)
-from invokeai.backend.model_manager.starter_models.external import (
- SEEDREAM_1K_SIZES as SEEDREAM_1K_SIZES,
-)
-from invokeai.backend.model_manager.starter_models.external import (
- SEEDREAM_2K_SIZES as SEEDREAM_2K_SIZES,
-)
-from invokeai.backend.model_manager.starter_models.external import (
- SEEDREAM_ASPECT_RATIOS as SEEDREAM_ASPECT_RATIOS,
-)
-from invokeai.backend.model_manager.starter_models.external import (
- SEEDREAM_PANEL_SCHEMA as SEEDREAM_PANEL_SCHEMA,
-)
-from invokeai.backend.model_manager.starter_models.external import (
- WAN_V2_ALLOWED_ASPECT_RATIOS as WAN_V2_ALLOWED_ASPECT_RATIOS,
-)
-from invokeai.backend.model_manager.starter_models.external import (
- _gemini_3_resolution_presets as _gemini_3_resolution_presets,
-)
-from invokeai.backend.model_manager.starter_models.external import (
- alibabacloud_qwen_image_2 as alibabacloud_qwen_image_2,
-)
-from invokeai.backend.model_manager.starter_models.external import (
- alibabacloud_qwen_image_2_pro as alibabacloud_qwen_image_2_pro,
-)
-from invokeai.backend.model_manager.starter_models.external import (
- alibabacloud_qwen_image_edit_max as alibabacloud_qwen_image_edit_max,
-)
-from invokeai.backend.model_manager.starter_models.external import (
- alibabacloud_qwen_image_max as alibabacloud_qwen_image_max,
-)
-from invokeai.backend.model_manager.starter_models.external import (
- alibabacloud_wan26_t2i as alibabacloud_wan26_t2i,
-)
-from invokeai.backend.model_manager.starter_models.external import (
- gemini_3_1_flash_image_preview as gemini_3_1_flash_image_preview,
-)
-from invokeai.backend.model_manager.starter_models.external import (
- gemini_flash_image as gemini_flash_image,
-)
-from invokeai.backend.model_manager.starter_models.external import (
- gemini_pro_image_preview as gemini_pro_image_preview,
-)
-from invokeai.backend.model_manager.starter_models.external import (
- openai_dall_e_3 as openai_dall_e_3,
-)
-from invokeai.backend.model_manager.starter_models.external import (
- openai_gpt_image_1 as openai_gpt_image_1,
-)
-from invokeai.backend.model_manager.starter_models.external import (
- openai_gpt_image_1_5 as openai_gpt_image_1_5,
-)
-from invokeai.backend.model_manager.starter_models.external import (
- openai_gpt_image_1_mini as openai_gpt_image_1_mini,
-)
-from invokeai.backend.model_manager.starter_models.external import (
- openai_gpt_image_2 as openai_gpt_image_2,
-)
-from invokeai.backend.model_manager.starter_models.external import (
- seedream_4_0 as seedream_4_0,
-)
-from invokeai.backend.model_manager.starter_models.external import (
- seedream_4_5 as seedream_4_5,
-)
-from invokeai.backend.model_manager.starter_models.external import (
- seedream_5_0 as seedream_5_0,
-)
-from invokeai.backend.model_manager.starter_models.external import (
- seedream_5_0_lite as seedream_5_0_lite,
-)
-from invokeai.backend.model_manager.starter_models.flux import (
- flux_canny_control_lora as flux_canny_control_lora,
-)
-from invokeai.backend.model_manager.starter_models.flux import (
- flux_depth_control_lora as flux_depth_control_lora,
-)
-from invokeai.backend.model_manager.starter_models.flux import (
- flux_dev as flux_dev,
-)
-from invokeai.backend.model_manager.starter_models.flux import (
- flux_dev_quantized as flux_dev_quantized,
-)
-from invokeai.backend.model_manager.starter_models.flux import (
- flux_fill as flux_fill,
-)
-from invokeai.backend.model_manager.starter_models.flux import (
- flux_kontext as flux_kontext,
-)
-from invokeai.backend.model_manager.starter_models.flux import (
- flux_kontext_quantized as flux_kontext_quantized,
-)
-from invokeai.backend.model_manager.starter_models.flux import (
- flux_krea as flux_krea,
-)
-from invokeai.backend.model_manager.starter_models.flux import (
- flux_krea_quantized as flux_krea_quantized,
-)
-from invokeai.backend.model_manager.starter_models.flux import (
- flux_redux as flux_redux,
-)
-from invokeai.backend.model_manager.starter_models.flux import (
- flux_schnell as flux_schnell,
-)
-from invokeai.backend.model_manager.starter_models.flux import (
- flux_schnell_quantized as flux_schnell_quantized,
-)
-from invokeai.backend.model_manager.starter_models.flux import (
- flux_schnell_sdnq as flux_schnell_sdnq,
-)
-from invokeai.backend.model_manager.starter_models.flux import (
- flux_vae as flux_vae,
-)
-from invokeai.backend.model_manager.starter_models.flux import (
- ip_adapter_flux as ip_adapter_flux,
-)
-from invokeai.backend.model_manager.starter_models.flux import (
- pid_decoder_flux_2k as pid_decoder_flux_2k,
-)
-from invokeai.backend.model_manager.starter_models.flux import (
- pid_decoder_flux_2kto4k as pid_decoder_flux_2kto4k,
-)
-from invokeai.backend.model_manager.starter_models.flux import (
- union_cnet_flux as union_cnet_flux,
-)
-from invokeai.backend.model_manager.starter_models.flux2 import (
- flux2_dev_diffusers as flux2_dev_diffusers,
-)
-from invokeai.backend.model_manager.starter_models.flux2 import (
- flux2_dev_diffusers_nf4 as flux2_dev_diffusers_nf4,
-)
-from invokeai.backend.model_manager.starter_models.flux2 import (
- flux2_dev_gguf_q3_k_m as flux2_dev_gguf_q3_k_m,
-)
-from invokeai.backend.model_manager.starter_models.flux2 import (
- flux2_dev_gguf_q4_k_m as flux2_dev_gguf_q4_k_m,
-)
-from invokeai.backend.model_manager.starter_models.flux2 import (
- flux2_dev_gguf_q5_k_m as flux2_dev_gguf_q5_k_m,
-)
-from invokeai.backend.model_manager.starter_models.flux2 import (
- flux2_dev_gguf_q6_k as flux2_dev_gguf_q6_k,
-)
-from invokeai.backend.model_manager.starter_models.flux2 import (
- flux2_dev_gguf_q8_0 as flux2_dev_gguf_q8_0,
-)
-from invokeai.backend.model_manager.starter_models.flux2 import (
- flux2_klein_4b as flux2_klein_4b,
-)
-from invokeai.backend.model_manager.starter_models.flux2 import (
- flux2_klein_4b_fp8 as flux2_klein_4b_fp8,
-)
-from invokeai.backend.model_manager.starter_models.flux2 import (
- flux2_klein_4b_gguf_q4 as flux2_klein_4b_gguf_q4,
-)
-from invokeai.backend.model_manager.starter_models.flux2 import (
- flux2_klein_4b_gguf_q8 as flux2_klein_4b_gguf_q8,
-)
-from invokeai.backend.model_manager.starter_models.flux2 import (
- flux2_klein_4b_sdnq as flux2_klein_4b_sdnq,
-)
-from invokeai.backend.model_manager.starter_models.flux2 import (
- flux2_klein_4b_single as flux2_klein_4b_single,
-)
-from invokeai.backend.model_manager.starter_models.flux2 import (
- flux2_klein_9b as flux2_klein_9b,
-)
-from invokeai.backend.model_manager.starter_models.flux2 import (
- flux2_klein_9b_fp8 as flux2_klein_9b_fp8,
-)
-from invokeai.backend.model_manager.starter_models.flux2 import (
- flux2_klein_9b_gguf_q4 as flux2_klein_9b_gguf_q4,
-)
-from invokeai.backend.model_manager.starter_models.flux2 import (
- flux2_klein_9b_gguf_q8 as flux2_klein_9b_gguf_q8,
-)
-from invokeai.backend.model_manager.starter_models.flux2 import (
- flux2_klein_9b_sdnq as flux2_klein_9b_sdnq,
-)
-from invokeai.backend.model_manager.starter_models.flux2 import (
- flux2_vae as flux2_vae,
-)
-from invokeai.backend.model_manager.starter_models.flux2 import (
- pid_decoder_flux2_2k as pid_decoder_flux2_2k,
-)
-from invokeai.backend.model_manager.starter_models.flux2 import (
- pid_decoder_flux2_2kto4k as pid_decoder_flux2_2kto4k,
-)
-from invokeai.backend.model_manager.starter_models.ideogram_4 import (
- ideogram_4_fp8 as ideogram_4_fp8,
-)
-from invokeai.backend.model_manager.starter_models.ideogram_4 import (
- ideogram_4_nf4 as ideogram_4_nf4,
-)
-from invokeai.backend.model_manager.starter_models.krea_2 import (
- krea2_raw as krea2_raw,
-)
-from invokeai.backend.model_manager.starter_models.krea_2 import (
- krea2_turbo as krea2_turbo,
-)
-from invokeai.backend.model_manager.starter_models.krea_2 import (
- krea2_turbo_gguf_q4_k_m as krea2_turbo_gguf_q4_k_m,
-)
-from invokeai.backend.model_manager.starter_models.krea_2 import (
- krea2_turbo_gguf_q8_0 as krea2_turbo_gguf_q8_0,
-)
-from invokeai.backend.model_manager.starter_models.minimax_h3 import (
- minimax_h3_components as minimax_h3_components,
-)
-from invokeai.backend.model_manager.starter_models.minimax_h3 import (
- minimax_h3_int8_text_encoder as minimax_h3_int8_text_encoder,
-)
-from invokeai.backend.model_manager.starter_models.minimax_h3 import (
- minimax_h3_int8_transformer as minimax_h3_int8_transformer,
-)
-from invokeai.backend.model_manager.starter_models.minimax_h3 import (
- minimax_h3_lightx2v_ref2v_turbo_lora as minimax_h3_lightx2v_ref2v_turbo_lora,
-)
-from invokeai.backend.model_manager.starter_models.minimax_h3 import (
- minimax_h3_lightx2v_turbo_lora as minimax_h3_lightx2v_turbo_lora,
-)
-from invokeai.backend.model_manager.starter_models.minimax_h3 import (
- minimax_h3_ref2va_int8_transformer as minimax_h3_ref2va_int8_transformer,
-)
-from invokeai.backend.model_manager.starter_models.minimax_h3 import (
- minimax_h3_turbo_lora as minimax_h3_turbo_lora,
-)
-from invokeai.backend.model_manager.starter_models.qwen_image import (
- pid_decoder_qwenimage_2kto4k as pid_decoder_qwenimage_2kto4k,
-)
-from invokeai.backend.model_manager.starter_models.qwen_image import (
- qwen_image as qwen_image,
-)
-from invokeai.backend.model_manager.starter_models.qwen_image import (
- qwen_image_edit as qwen_image_edit,
-)
-from invokeai.backend.model_manager.starter_models.qwen_image import (
- qwen_image_edit_gguf_q2_k as qwen_image_edit_gguf_q2_k,
-)
-from invokeai.backend.model_manager.starter_models.qwen_image import (
- qwen_image_edit_gguf_q4_k_m as qwen_image_edit_gguf_q4_k_m,
-)
-from invokeai.backend.model_manager.starter_models.qwen_image import (
- qwen_image_edit_gguf_q6_k as qwen_image_edit_gguf_q6_k,
-)
-from invokeai.backend.model_manager.starter_models.qwen_image import (
- qwen_image_edit_gguf_q8_0 as qwen_image_edit_gguf_q8_0,
-)
-from invokeai.backend.model_manager.starter_models.qwen_image import (
- qwen_image_edit_lightning_4step as qwen_image_edit_lightning_4step,
-)
-from invokeai.backend.model_manager.starter_models.qwen_image import (
- qwen_image_edit_lightning_8step as qwen_image_edit_lightning_8step,
-)
-from invokeai.backend.model_manager.starter_models.qwen_image import (
- qwen_image_gguf_q2_k as qwen_image_gguf_q2_k,
-)
-from invokeai.backend.model_manager.starter_models.qwen_image import (
- qwen_image_gguf_q4_k_m as qwen_image_gguf_q4_k_m,
-)
-from invokeai.backend.model_manager.starter_models.qwen_image import (
- qwen_image_gguf_q6_k as qwen_image_gguf_q6_k,
-)
-from invokeai.backend.model_manager.starter_models.qwen_image import (
- qwen_image_gguf_q8_0 as qwen_image_gguf_q8_0,
-)
-from invokeai.backend.model_manager.starter_models.qwen_image import (
- qwen_image_lightning_4step as qwen_image_lightning_4step,
-)
-from invokeai.backend.model_manager.starter_models.qwen_image import (
- qwen_image_lightning_8step as qwen_image_lightning_8step,
-)
-from invokeai.backend.model_manager.starter_models.qwen_image import (
- qwen_image_vae as qwen_image_vae,
-)
-from invokeai.backend.model_manager.starter_models.sd_1 import (
- canny_sd1 as canny_sd1,
-)
-from invokeai.backend.model_manager.starter_models.sd_1 import (
- cyberrealistic_negative as cyberrealistic_negative,
-)
-from invokeai.backend.model_manager.starter_models.sd_1 import (
- cyberrealistic_sd1 as cyberrealistic_sd1,
-)
-from invokeai.backend.model_manager.starter_models.sd_1 import (
- deliberate_inpainting_sd1 as deliberate_inpainting_sd1,
-)
-from invokeai.backend.model_manager.starter_models.sd_1 import (
- deliberate_sd1 as deliberate_sd1,
-)
-from invokeai.backend.model_manager.starter_models.sd_1 import (
- depth_sd1 as depth_sd1,
-)
-from invokeai.backend.model_manager.starter_models.sd_1 import (
- dreamshaper_8_inpainting_sd1 as dreamshaper_8_inpainting_sd1,
-)
-from invokeai.backend.model_manager.starter_models.sd_1 import (
- dreamshaper_8_sd1 as dreamshaper_8_sd1,
-)
-from invokeai.backend.model_manager.starter_models.sd_1 import (
- easy_neg_sd1 as easy_neg_sd1,
-)
-from invokeai.backend.model_manager.starter_models.sd_1 import (
- inpaint_cnet_sd1 as inpaint_cnet_sd1,
-)
-from invokeai.backend.model_manager.starter_models.sd_1 import (
- ip_adapter_plus_face_sd1 as ip_adapter_plus_face_sd1,
-)
-from invokeai.backend.model_manager.starter_models.sd_1 import (
- ip_adapter_plus_sd1 as ip_adapter_plus_sd1,
-)
-from invokeai.backend.model_manager.starter_models.sd_1 import (
- ip_adapter_sd1 as ip_adapter_sd1,
-)
-from invokeai.backend.model_manager.starter_models.sd_1 import (
- lineart_anime_sd1 as lineart_anime_sd1,
-)
-from invokeai.backend.model_manager.starter_models.sd_1 import (
- lineart_sd1 as lineart_sd1,
-)
-from invokeai.backend.model_manager.starter_models.sd_1 import (
- mlsd_sd1 as mlsd_sd1,
-)
-from invokeai.backend.model_manager.starter_models.sd_1 import (
- normal_bae_sd1 as normal_bae_sd1,
-)
-from invokeai.backend.model_manager.starter_models.sd_1 import (
- openpose_sd1 as openpose_sd1,
-)
-from invokeai.backend.model_manager.starter_models.sd_1 import (
- qr_code_cnet_sd1 as qr_code_cnet_sd1,
-)
-from invokeai.backend.model_manager.starter_models.sd_1 import (
- rev_animated_sd1 as rev_animated_sd1,
-)
-from invokeai.backend.model_manager.starter_models.sd_1 import (
- scribble_sd1 as scribble_sd1,
-)
-from invokeai.backend.model_manager.starter_models.sd_1 import (
- seg_sd1 as seg_sd1,
-)
-from invokeai.backend.model_manager.starter_models.sd_1 import (
- shuffle_sd1 as shuffle_sd1,
-)
-from invokeai.backend.model_manager.starter_models.sd_1 import (
- softedge_sd1 as softedge_sd1,
-)
-from invokeai.backend.model_manager.starter_models.sd_1 import (
- t2i_canny_sd1 as t2i_canny_sd1,
-)
-from invokeai.backend.model_manager.starter_models.sd_1 import (
- t2i_depth_sd1 as t2i_depth_sd1,
-)
-from invokeai.backend.model_manager.starter_models.sd_1 import (
- t2i_sketch_sd1 as t2i_sketch_sd1,
-)
-from invokeai.backend.model_manager.starter_models.sd_1 import (
- tile_sd1 as tile_sd1,
-)
-from invokeai.backend.model_manager.starter_models.sd_3 import (
- pid_decoder_sd3_2k as pid_decoder_sd3_2k,
-)
-from invokeai.backend.model_manager.starter_models.sd_3 import (
- pid_decoder_sd3_2kto4k as pid_decoder_sd3_2kto4k,
-)
-from invokeai.backend.model_manager.starter_models.sd_3 import (
- sd35_large as sd35_large,
-)
-from invokeai.backend.model_manager.starter_models.sd_3 import (
- sd35_medium as sd35_medium,
-)
-from invokeai.backend.model_manager.starter_models.sdxl import (
- alien_lora_sdxl as alien_lora_sdxl,
-)
-from invokeai.backend.model_manager.starter_models.sdxl import (
- archvis_sdxl as archvis_sdxl,
-)
-from invokeai.backend.model_manager.starter_models.sdxl import (
- canny_sdxl as canny_sdxl,
-)
-from invokeai.backend.model_manager.starter_models.sdxl import (
- depth_sdxl as depth_sdxl,
-)
-from invokeai.backend.model_manager.starter_models.sdxl import (
- dreamshaper_sdxl as dreamshaper_sdxl,
-)
-from invokeai.backend.model_manager.starter_models.sdxl import (
- ip_adapter_plus_sdxl as ip_adapter_plus_sdxl,
-)
-from invokeai.backend.model_manager.starter_models.sdxl import (
- ip_adapter_sdxl as ip_adapter_sdxl,
-)
-from invokeai.backend.model_manager.starter_models.sdxl import (
- juggernaut_sdxl as juggernaut_sdxl,
-)
-from invokeai.backend.model_manager.starter_models.sdxl import (
- noodle_lora_sdxl as noodle_lora_sdxl,
+ anima_qwen3_encoder,
+ animesharp_v4_rcan,
+ clip_l_encoder,
+ dfn2b_clip_vit_l_image_encoder,
+ flux2_dev_comfy_mistral_bf16,
+ flux2_dev_comfy_mistral_fp4,
+ flux2_dev_comfy_mistral_fp8,
+ flux2_dev_cow_mistral_iq4_xs,
+ flux2_dev_cow_mistral_q4,
+ flux2_dev_cow_mistral_q8,
+ flux2_klein_qwen3_4b_encoder,
+ flux2_klein_qwen3_8b_encoder,
+ gemma2_2b_encoder,
+ llava_onevision,
+ llava_onevision_7b,
+ qwen2_5_1_5b_instruct,
+ qwen2_5_3b_instruct,
+ qwen3_vl_encoder_4b,
+ qwen_vl_encoder_diffusers,
+ qwen_vl_encoder_fp8,
+ realesrgan_x2,
+ realesrgan_x4,
+ siglip,
+ smollm2_1_7b_instruct,
+ swinir,
+ t5_8b_quantized_encoder,
+ t5_base_encoder,
+ t5_gguf_q3_k_s_encoder,
+ t5_gguf_q6_k_encoder,
+ wan_22_t5_encoder,
+ z_image_qwen3_encoder,
+ z_image_qwen3_encoder_quantized,
)
-from invokeai.backend.model_manager.starter_models.sdxl import (
- openpose_sdxl as openpose_sdxl,
+from invokeai.backend.model_manager.starter_models.ernie_image import (
+ ernie_image,
+ ernie_image_turbo,
)
-from invokeai.backend.model_manager.starter_models.sdxl import (
- pid_decoder_sdxl_2kto4k as pid_decoder_sdxl_2kto4k,
+from invokeai.backend.model_manager.starter_models.external import (
+ alibabacloud_qwen_image_2,
+ alibabacloud_qwen_image_2_pro,
+ alibabacloud_qwen_image_edit_max,
+ alibabacloud_qwen_image_max,
+ alibabacloud_wan26_t2i,
+ gemini_3_1_flash_image_preview,
+ gemini_flash_image,
+ gemini_pro_image_preview,
+ openai_dall_e_3,
+ openai_gpt_image_1,
+ openai_gpt_image_1_5,
+ openai_gpt_image_1_mini,
+ openai_gpt_image_2,
+ seedream_4_0,
+ seedream_4_5,
+ seedream_5_0,
+ seedream_5_0_lite,
)
-from invokeai.backend.model_manager.starter_models.sdxl import (
- qr_code_cnet_sdxl as qr_code_cnet_sdxl,
+from invokeai.backend.model_manager.starter_models.flux import (
+ flux_canny_control_lora,
+ flux_depth_control_lora,
+ flux_dev,
+ flux_dev_quantized,
+ flux_fill,
+ flux_kontext_quantized,
+ flux_krea,
+ flux_krea_quantized,
+ flux_redux,
+ flux_schnell,
+ flux_schnell_quantized,
+ flux_schnell_sdnq,
+ flux_vae,
+ ip_adapter_flux,
+ pid_decoder_flux_2k,
+ pid_decoder_flux_2kto4k,
+ union_cnet_flux,
)
-from invokeai.backend.model_manager.starter_models.sdxl import (
- scribble_sdxl as scribble_sdxl,
+from invokeai.backend.model_manager.starter_models.flux2 import (
+ flux2_dev_diffusers,
+ flux2_dev_diffusers_nf4,
+ flux2_dev_gguf_q3_k_m,
+ flux2_dev_gguf_q4_k_m,
+ flux2_dev_gguf_q5_k_m,
+ flux2_dev_gguf_q6_k,
+ flux2_dev_gguf_q8_0,
+ flux2_klein_4b,
+ flux2_klein_4b_fp8,
+ flux2_klein_4b_gguf_q4,
+ flux2_klein_4b_gguf_q8,
+ flux2_klein_4b_sdnq,
+ flux2_klein_4b_single,
+ flux2_klein_9b,
+ flux2_klein_9b_fp8,
+ flux2_klein_9b_gguf_q4,
+ flux2_klein_9b_gguf_q8,
+ flux2_klein_9b_sdnq,
+ flux2_vae,
+ pid_decoder_flux2_2k,
+ pid_decoder_flux2_2kto4k,
)
-from invokeai.backend.model_manager.starter_models.sdxl import (
- sdxl_fp16_vae_fix as sdxl_fp16_vae_fix,
+from invokeai.backend.model_manager.starter_models.ideogram_4 import (
+ ideogram_4_fp8,
+ ideogram_4_nf4,
)
-from invokeai.backend.model_manager.starter_models.sdxl import (
- softedge_sdxl as softedge_sdxl,
+from invokeai.backend.model_manager.starter_models.krea_2 import (
+ krea2_raw,
+ krea2_turbo,
+ krea2_turbo_gguf_q4_k_m,
+ krea2_turbo_gguf_q8_0,
)
-from invokeai.backend.model_manager.starter_models.sdxl import (
- t2i_canny_sdxl as t2i_canny_sdxl,
+from invokeai.backend.model_manager.starter_models.minimax_h3 import (
+ minimax_h3_components,
+ minimax_h3_int8_text_encoder,
+ minimax_h3_int8_transformer,
+ minimax_h3_lightx2v_ref2v_turbo_lora,
+ minimax_h3_lightx2v_turbo_lora,
+ minimax_h3_ref2va_int8_transformer,
+ minimax_h3_turbo_lora,
)
-from invokeai.backend.model_manager.starter_models.sdxl import (
- t2i_lineart_sdxl as t2i_lineart_sdxl,
+from invokeai.backend.model_manager.starter_models.qwen_image import (
+ pid_decoder_qwenimage_2kto4k,
+ qwen_image,
+ qwen_image_edit,
+ qwen_image_edit_gguf_q2_k,
+ qwen_image_edit_gguf_q4_k_m,
+ qwen_image_edit_gguf_q6_k,
+ qwen_image_edit_gguf_q8_0,
+ qwen_image_edit_lightning_4step,
+ qwen_image_edit_lightning_8step,
+ qwen_image_gguf_q2_k,
+ qwen_image_gguf_q4_k_m,
+ qwen_image_gguf_q6_k,
+ qwen_image_gguf_q8_0,
+ qwen_image_lightning_4step,
+ qwen_image_lightning_8step,
+ qwen_image_vae,
)
-from invokeai.backend.model_manager.starter_models.sdxl import (
- t2i_sketch_sdxl as t2i_sketch_sdxl,
+from invokeai.backend.model_manager.starter_models.sd_1 import (
+ canny_sd1,
+ cyberrealistic_sd1,
+ deliberate_inpainting_sd1,
+ deliberate_sd1,
+ depth_sd1,
+ dreamshaper_8_inpainting_sd1,
+ dreamshaper_8_sd1,
+ easy_neg_sd1,
+ inpaint_cnet_sd1,
+ ip_adapter_plus_face_sd1,
+ ip_adapter_plus_sd1,
+ ip_adapter_sd1,
+ lineart_anime_sd1,
+ lineart_sd1,
+ mlsd_sd1,
+ normal_bae_sd1,
+ openpose_sd1,
+ qr_code_cnet_sd1,
+ rev_animated_sd1,
+ scribble_sd1,
+ seg_sd1,
+ shuffle_sd1,
+ softedge_sd1,
+ t2i_canny_sd1,
+ t2i_depth_sd1,
+ t2i_sketch_sd1,
+ tile_sd1,
)
-from invokeai.backend.model_manager.starter_models.sdxl import (
- tile_sdxl as tile_sdxl,
+from invokeai.backend.model_manager.starter_models.sd_3 import (
+ pid_decoder_sd3_2k,
+ pid_decoder_sd3_2kto4k,
+ sd35_large,
+ sd35_medium,
)
from invokeai.backend.model_manager.starter_models.sdxl import (
- union_cnet_sdxl as union_cnet_sdxl,
-)
-from invokeai.backend.model_manager.starter_models.sdxl_refiner import (
- sdxl_refiner as sdxl_refiner,
-)
-from invokeai.backend.model_manager.starter_models.types import (
- StarterModel as StarterModel,
-)
-from invokeai.backend.model_manager.starter_models.types import (
- StarterModelBundle as StarterModelBundle,
+ alien_lora_sdxl,
+ archvis_sdxl,
+ canny_sdxl,
+ depth_sdxl,
+ dreamshaper_sdxl,
+ ip_adapter_plus_sdxl,
+ ip_adapter_sdxl,
+ juggernaut_sdxl,
+ noodle_lora_sdxl,
+ openpose_sdxl,
+ pid_decoder_sdxl_2kto4k,
+ qr_code_cnet_sdxl,
+ scribble_sdxl,
+ sdxl_fp16_vae_fix,
+ softedge_sdxl,
+ t2i_canny_sdxl,
+ t2i_lineart_sdxl,
+ t2i_sketch_sdxl,
+ tile_sdxl,
+ union_cnet_sdxl,
)
+from invokeai.backend.model_manager.starter_models.sdxl_refiner import sdxl_refiner
from invokeai.backend.model_manager.starter_models.types import (
- StarterModelWithoutDependencies as StarterModelWithoutDependencies,
-)
-from invokeai.backend.model_manager.starter_models.wan import (
- wan_22_5b_vae as wan_22_5b_vae,
-)
-from invokeai.backend.model_manager.starter_models.wan import (
- wan_22_a14b_vae as wan_22_a14b_vae,
-)
-from invokeai.backend.model_manager.starter_models.wan import (
- wan_22_i2v_a14b_diffusers as wan_22_i2v_a14b_diffusers,
-)
-from invokeai.backend.model_manager.starter_models.wan import (
- wan_22_i2v_a14b_gguf_q4_k_m as wan_22_i2v_a14b_gguf_q4_k_m,
-)
-from invokeai.backend.model_manager.starter_models.wan import (
- wan_22_i2v_a14b_gguf_q8_0 as wan_22_i2v_a14b_gguf_q8_0,
-)
-from invokeai.backend.model_manager.starter_models.wan import (
- wan_22_i2v_a14b_low_gguf_q4_k_m as wan_22_i2v_a14b_low_gguf_q4_k_m,
-)
-from invokeai.backend.model_manager.starter_models.wan import (
- wan_22_i2v_a14b_low_gguf_q8_0 as wan_22_i2v_a14b_low_gguf_q8_0,
-)
-from invokeai.backend.model_manager.starter_models.wan import (
- wan_22_i2v_lightning_high as wan_22_i2v_lightning_high,
-)
-from invokeai.backend.model_manager.starter_models.wan import (
- wan_22_i2v_lightning_low as wan_22_i2v_lightning_low,
-)
-from invokeai.backend.model_manager.starter_models.wan import (
- wan_22_t2v_a14b_diffusers as wan_22_t2v_a14b_diffusers,
-)
-from invokeai.backend.model_manager.starter_models.wan import (
- wan_22_t2v_a14b_gguf_q4_k_m as wan_22_t2v_a14b_gguf_q4_k_m,
-)
-from invokeai.backend.model_manager.starter_models.wan import (
- wan_22_t2v_a14b_gguf_q8_0 as wan_22_t2v_a14b_gguf_q8_0,
-)
-from invokeai.backend.model_manager.starter_models.wan import (
- wan_22_t2v_a14b_low_gguf_q4_k_m as wan_22_t2v_a14b_low_gguf_q4_k_m,
-)
-from invokeai.backend.model_manager.starter_models.wan import (
- wan_22_t2v_a14b_low_gguf_q8_0 as wan_22_t2v_a14b_low_gguf_q8_0,
-)
-from invokeai.backend.model_manager.starter_models.wan import (
- wan_22_t2v_lightning_high as wan_22_t2v_lightning_high,
-)
-from invokeai.backend.model_manager.starter_models.wan import (
- wan_22_t2v_lightning_low as wan_22_t2v_lightning_low,
-)
-from invokeai.backend.model_manager.starter_models.wan import (
- wan_22_ti2v_5b_diffusers as wan_22_ti2v_5b_diffusers,
-)
-from invokeai.backend.model_manager.starter_models.wan import (
- wan_22_ti2v_5b_gguf_q4_k_m as wan_22_ti2v_5b_gguf_q4_k_m,
+ StarterModel,
+ StarterModelBundle,
+ StarterModelWithoutDependencies,
)
from invokeai.backend.model_manager.starter_models.wan import (
- wan_22_ti2v_5b_gguf_q8_0 as wan_22_ti2v_5b_gguf_q8_0,
-)
-from invokeai.backend.model_manager.starter_models.z_image import (
- z_image_controlnet_tile as z_image_controlnet_tile,
-)
-from invokeai.backend.model_manager.starter_models.z_image import (
- z_image_controlnet_union as z_image_controlnet_union,
-)
-from invokeai.backend.model_manager.starter_models.z_image import (
- z_image_turbo as z_image_turbo,
-)
-from invokeai.backend.model_manager.starter_models.z_image import (
- z_image_turbo_q8 as z_image_turbo_q8,
-)
-from invokeai.backend.model_manager.starter_models.z_image import (
- z_image_turbo_quantized as z_image_turbo_quantized,
+ wan_22_5b_vae,
+ wan_22_a14b_vae,
+ wan_22_i2v_a14b_diffusers,
+ wan_22_i2v_a14b_gguf_q4_k_m,
+ wan_22_i2v_a14b_gguf_q8_0,
+ wan_22_i2v_a14b_low_gguf_q4_k_m,
+ wan_22_i2v_a14b_low_gguf_q8_0,
+ wan_22_i2v_lightning_high,
+ wan_22_i2v_lightning_low,
+ wan_22_t2v_a14b_diffusers,
+ wan_22_t2v_a14b_gguf_q4_k_m,
+ wan_22_t2v_a14b_gguf_q8_0,
+ wan_22_t2v_a14b_low_gguf_q4_k_m,
+ wan_22_t2v_a14b_low_gguf_q8_0,
+ wan_22_t2v_lightning_high,
+ wan_22_t2v_lightning_low,
+ wan_22_ti2v_5b_diffusers,
+ wan_22_ti2v_5b_gguf_q4_k_m,
+ wan_22_ti2v_5b_gguf_q8_0,
)
from invokeai.backend.model_manager.starter_models.z_image import (
- z_image_turbo_sdnq as z_image_turbo_sdnq,
+ z_image_controlnet_tile,
+ z_image_controlnet_union,
+ z_image_turbo,
+ z_image_turbo_q8,
+ z_image_turbo_quantized,
+ z_image_turbo_sdnq,
)
from invokeai.backend.model_manager.taxonomy import BaseModelType
@@ -1069,3 +625,11 @@ STARTER_BUNDLES: dict[str, StarterModelBundle] = {
}
assert len(STARTER_MODELS) == len({m.source for m in STARTER_MODELS}), "Duplicate starter models"
+
+__all__ = [
+ "STARTER_BUNDLES",
+ "STARTER_MODELS",
+ "StarterModel",
+ "StarterModelBundle",
+ "StarterModelWithoutDependencies",
+]
diff --git a/invokeai/backend/util/module_discovery.py b/invokeai/backend/util/module_discovery.py
index fcc0e2cbc0..07ea0a6e6f 100644
--- a/invokeai/backend/util/module_discovery.py
+++ b/invokeai/backend/util/module_discovery.py
@@ -8,6 +8,7 @@ pitfalls are handled and tested in one place.
"""
import pkgutil
+from collections.abc import Iterator
from pathlib import Path
@@ -24,6 +25,35 @@ def _reraise(name: str) -> None:
raise ImportError(f"Failed to walk package {name!r} while discovering modules.")
+def _holds_modules(directory: Path) -> bool:
+ """Whether `directory` contains any module that discovery would be expected to reach.
+
+ Ignores `_`-prefixed path components, so a stale `__pycache__` does not make an ordinary data
+ directory look like a package someone forgot to finish.
+ """
+ return any(
+ not any(part.startswith("_") for part in module.relative_to(directory).parts)
+ for module in directory.rglob("*.py")
+ )
+
+
+def _orphan_directories(package_dir: Path) -> Iterator[Path]:
+ """Directories under `package_dir` that hold modules but have no `__init__.py`.
+
+ `pkgutil.walk_packages` does not descend into such a directory, and says nothing about it: every
+ module below it is simply absent from the result, which is indistinguishable from there being
+ nothing to find. That is the discovery mistake that actually happens — one `__init__.py`
+ forgotten in a new subdirectory — so it is looked for rather than waited for.
+ """
+ for child in sorted(package_dir.iterdir()):
+ if not child.is_dir() or child.name.startswith("_"):
+ continue
+ if (child / "__init__.py").exists():
+ yield from _orphan_directories(child)
+ elif _holds_modules(child):
+ yield child
+
+
def discover_modules(root: Path, prefix: str) -> list[str]:
"""Fully-qualified names of every non-private module in the package tree rooted at `root`.
@@ -35,10 +65,21 @@ def discover_modules(root: Path, prefix: str) -> list[str]:
module as internal. Packages themselves are skipped — importing them is a side effect of the
walk, and it is their contents that carry the registrations.
+ A directory holding modules but no `__init__.py` raises: `walk_packages` would skip it in
+ silence, which is the one discovery failure that produces no symptom at all.
+
Names only; importing them is the caller's job. Keeping the two apart is what lets the walk be
tested against a synthetic tree, which matters because a walker with a bug returns an empty list
and no test that merely asserts "some modules were found" would notice.
"""
+ orphans = [d.relative_to(root).as_posix() for d in _orphan_directories(root)]
+ if orphans:
+ raise ImportError(
+ f"These directories under {root} hold modules but no __init__.py, so nothing in them is "
+ f"discovered and nothing registers: {', '.join(orphans)}. Add an __init__.py to each, or "
+ f"rename it with a leading underscore if it is not meant to be imported."
+ )
+
names: list[str] = []
for info in pkgutil.walk_packages([str(root)], prefix=prefix, onerror=_reraise):
relative = info.name.removeprefix(prefix)
diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.json
index 173cb3b325..48825500be 100644
--- a/invokeai/frontend/web/openapi.json
+++ b/invokeai/frontend/web/openapi.json
@@ -17713,7 +17713,6 @@
"description": "Recommended generation parameters, if the architecture has any."
}
},
- "additionalProperties": false,
"type": "object",
"required": ["base", "modality", "features"],
"title": "ArchitectureCapabilities",
@@ -17727,7 +17726,7 @@
"dimension_grid": {
"type": "integer",
"title": "Dimension Grid",
- "description": "Width and height must be a multiple of this."
+ "description": "Width and height must be a multiple of this. A variant row may carry its own."
},
"spatial_compression": {
"type": "integer",
@@ -17830,7 +17829,6 @@
"default": false
}
},
- "additionalProperties": false,
"type": "object",
"required": ["negative_prompt", "dimension_grid", "spatial_compression", "guidance_label"],
"title": "ArchitectureFeatures",
@@ -17872,7 +17870,6 @@
"description": "Prefix its mode strings carry in image metadata; null means unprefixed."
}
},
- "additionalProperties": false,
"type": "object",
"required": ["modes"],
"title": "ArchitectureModality",
@@ -78364,7 +78361,6 @@
"description": "'always', 'cfg-gated' (only above CFG 1), or 'never'."
}
},
- "additionalProperties": false,
"type": "object",
"required": ["visible", "usage"],
"title": "NegativePromptPolicy"
diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.ts
index 7bfe54d153..a526195b4f 100644
--- a/invokeai/frontend/web/src/services/api/schema.ts
+++ b/invokeai/frontend/web/src/services/api/schema.ts
@@ -5183,7 +5183,7 @@ export type components = {
negative_prompt: components["schemas"]["NegativePromptPolicy"];
/**
* Dimension Grid
- * @description Width and height must be a multiple of this.
+ * @description Width and height must be a multiple of this. A variant row may carry its own.
*/
dimension_grid: number;
/**
diff --git a/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/generateGraphNodeTypes.json b/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/generateGraphNodeTypes.json
index 1942f85a46..677fb1c3e7 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/generateGraphNodeTypes.json
+++ b/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/generateGraphNodeTypes.json
@@ -1,5 +1,5 @@
{
- "_comment": "Generated by src/features/generation/core/graphCoverage.test.ts; regenerate with `vitest -u`. Excluded from oxfmt so the test alone owns its layout. Consumed by tests/app/invocations/test_frontend_graph_node_types.py, which checks every node type and field below against the backend invocation registry.",
+ "_comment": "Generated by src/features/generation/core/graphCoverage.test.ts; regenerate with `vitest -u`. Excluded from oxfmt so the test alone owns its layout. Consumed by tests/app/invocations/test_frontend_graph_node_types.py, which checks every node type, edge field and literal input value below against the backend invocation registry. An empty literalInputs value list means the field is set to something other than a scalar, so only its name is checked.",
"byBase": {
"sd-1": {
"componentsFilled": {
@@ -269,6 +269,35 @@
"seed",
"transformer"
],
+ "literalInputs": {
+ "denoising_end": [
+ 1
+ ],
+ "denoising_start": [
+ 0
+ ],
+ "guidance_scale": [
+ 4
+ ],
+ "height": [
+ 1024
+ ],
+ "is_intermediate": [
+ true
+ ],
+ "scheduler": [
+ "euler"
+ ],
+ "steps": [
+ 30
+ ],
+ "use_cache": [
+ true
+ ],
+ "width": [
+ 1024
+ ]
+ },
"outputs": [
"latents"
]
@@ -279,10 +308,29 @@
"metadata",
"vae"
],
+ "literalInputs": {
+ "is_intermediate": [
+ false
+ ],
+ "use_cache": [
+ false
+ ]
+ },
"outputs": []
},
"anima_model_loader": {
"inputs": [],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "model": [],
+ "qwen3_encoder_model": [],
+ "use_cache": [
+ true
+ ],
+ "vae_model": []
+ },
"outputs": [
"qwen3_encoder",
"transformer",
@@ -294,6 +342,14 @@
"prompt",
"qwen3_encoder"
],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "use_cache": [
+ true
+ ]
+ },
"outputs": [
"conditioning"
]
@@ -302,6 +358,17 @@
"inputs": [
"clip"
],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "skipped_layers": [
+ 0
+ ],
+ "use_cache": [
+ true
+ ]
+ },
"outputs": [
"clip"
]
@@ -313,6 +380,26 @@
"seed",
"transformer"
],
+ "literalInputs": {
+ "cfg_scale": [
+ 7
+ ],
+ "height": [
+ 1024
+ ],
+ "is_intermediate": [
+ true
+ ],
+ "steps": [
+ 30
+ ],
+ "use_cache": [
+ true
+ ],
+ "width": [
+ 1024
+ ]
+ },
"outputs": [
"latents"
]
@@ -323,10 +410,27 @@
"metadata",
"vae"
],
+ "literalInputs": {
+ "is_intermediate": [
+ false
+ ],
+ "use_cache": [
+ false
+ ]
+ },
"outputs": []
},
"cogview4_model_loader": {
"inputs": [],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "model": [],
+ "use_cache": [
+ true
+ ]
+ },
"outputs": [
"glm_encoder",
"transformer",
@@ -338,6 +442,14 @@
"glm_encoder",
"prompt"
],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "use_cache": [
+ true
+ ]
+ },
"outputs": [
"conditioning"
]
@@ -346,6 +458,14 @@
"inputs": [
"item"
],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "use_cache": [
+ true
+ ]
+ },
"outputs": [
"collection"
]
@@ -355,6 +475,14 @@
"clip",
"prompt"
],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "use_cache": [
+ true
+ ]
+ },
"outputs": [
"conditioning"
]
@@ -365,6 +493,121 @@
"positive_prompt",
"seed"
],
+ "literalInputs": {
+ "cfg_rescale_multiplier": [
+ 0
+ ],
+ "cfg_scale": [
+ 1,
+ 4,
+ 7
+ ],
+ "clip_embed_model": [],
+ "clip_skip": [
+ 0
+ ],
+ "generation_mode": [
+ "anima_txt2img",
+ "cogview4_txt2img",
+ "ernie_image_txt2img",
+ "flux_txt2img",
+ "flux2_txt2img",
+ "ideogram4_txt2img",
+ "krea2_txt2img",
+ "qwen_image_txt2img",
+ "sd3_txt2img",
+ "sdxl_txt2img",
+ "txt2img",
+ "wan_txt2img",
+ "z_image_txt2img"
+ ],
+ "guidance": [
+ 4
+ ],
+ "height": [
+ 1024,
+ 512
+ ],
+ "hidiffusion": [
+ false
+ ],
+ "hidiffusion_raunet": [
+ true
+ ],
+ "hidiffusion_t1_ratio": [
+ 0.4
+ ],
+ "hidiffusion_t2_ratio": [
+ 0
+ ],
+ "hidiffusion_window_attn": [
+ true
+ ],
+ "ideogram4_color_palette": [],
+ "ideogram4_sampler_preset": [
+ "V4_QUALITY_48"
+ ],
+ "is_intermediate": [
+ true
+ ],
+ "krea2_rebalance_enabled": [
+ false
+ ],
+ "krea2_rebalance_multiplier": [
+ 4
+ ],
+ "krea2_rebalance_weights": [
+ "1.0,1.0,1.0,1.0,1.0,1.0,1.0,2.5,5.0,1.1,4.0,1.0"
+ ],
+ "krea2_seed_variance_enabled": [
+ false
+ ],
+ "krea2_seed_variance_randomize_percent": [
+ 50
+ ],
+ "krea2_seed_variance_strength": [
+ 0.1
+ ],
+ "mistral_encoder": [],
+ "model": [],
+ "qwen_image_qwen_vl_encoder": [],
+ "qwen_image_vae": [],
+ "qwen3_encoder": [],
+ "qwen3_source": [],
+ "qwen3_vl_encoder": [],
+ "rand_device": [
+ "cpu"
+ ],
+ "scheduler": [
+ "euler_a",
+ "euler"
+ ],
+ "seamless_x": [
+ false
+ ],
+ "seamless_y": [
+ false
+ ],
+ "steps": [
+ 30,
+ 4,
+ 40,
+ 48,
+ 50,
+ 8
+ ],
+ "t5_encoder": [],
+ "use_cache": [
+ true
+ ],
+ "vae": [],
+ "wan_component_source": [],
+ "wan_t5_encoder": [],
+ "width": [
+ 1024,
+ 512
+ ]
+ },
"outputs": [
"metadata"
]
@@ -376,6 +619,41 @@
"positive_conditioning",
"unet"
],
+ "literalInputs": {
+ "cfg_rescale_multiplier": [
+ 0
+ ],
+ "cfg_scale": [
+ 7
+ ],
+ "denoising_end": [
+ 1
+ ],
+ "denoising_start": [
+ 0
+ ],
+ "hidiffusion": [
+ false
+ ],
+ "hidiffusion_raunet": [
+ true
+ ],
+ "hidiffusion_window_attn": [
+ true
+ ],
+ "is_intermediate": [
+ true
+ ],
+ "scheduler": [
+ "euler_a"
+ ],
+ "steps": [
+ 30
+ ],
+ "use_cache": [
+ true
+ ]
+ },
"outputs": [
"latents"
]
@@ -387,12 +665,53 @@
"seed",
"transformer"
],
+ "literalInputs": {
+ "denoising_end": [
+ 1
+ ],
+ "denoising_start": [
+ 0
+ ],
+ "guidance_scale": [
+ 4
+ ],
+ "height": [
+ 1024
+ ],
+ "is_intermediate": [
+ true
+ ],
+ "scheduler": [
+ "euler"
+ ],
+ "steps": [
+ 50
+ ],
+ "use_cache": [
+ true
+ ],
+ "width": [
+ 1024
+ ]
+ },
"outputs": [
"latents"
]
},
"ernie_image_model_loader": {
"inputs": [],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "model": [],
+ "use_cache": [
+ true
+ ],
+ "use_prompt_enhancer": [
+ false
+ ]
+ },
"outputs": [
"text_encoder",
"transformer",
@@ -404,6 +723,14 @@
"prompt",
"text_encoder"
],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "use_cache": [
+ true
+ ]
+ },
"outputs": [
"conditioning"
]
@@ -414,6 +741,14 @@
"metadata",
"vae"
],
+ "literalInputs": {
+ "is_intermediate": [
+ false
+ ],
+ "use_cache": [
+ false
+ ]
+ },
"outputs": []
},
"flux_denoise": {
@@ -423,12 +758,53 @@
"seed",
"transformer"
],
+ "literalInputs": {
+ "denoising_end": [
+ 1
+ ],
+ "denoising_start": [
+ 0
+ ],
+ "guidance": [
+ 4
+ ],
+ "height": [
+ 1024
+ ],
+ "is_intermediate": [
+ true
+ ],
+ "num_steps": [
+ 4
+ ],
+ "scheduler": [
+ "euler"
+ ],
+ "use_cache": [
+ true
+ ],
+ "width": [
+ 1024
+ ]
+ },
"outputs": [
"latents"
]
},
"flux_model_loader": {
"inputs": [],
+ "literalInputs": {
+ "clip_embed_model": [],
+ "is_intermediate": [
+ true
+ ],
+ "model": [],
+ "t5_encoder_model": [],
+ "use_cache": [
+ true
+ ],
+ "vae_model": []
+ },
"outputs": [
"clip",
"max_seq_len",
@@ -444,6 +820,14 @@
"t5_encoder",
"t5_max_seq_len"
],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "use_cache": [
+ true
+ ]
+ },
"outputs": [
"conditioning"
]
@@ -454,6 +838,14 @@
"metadata",
"vae"
],
+ "literalInputs": {
+ "is_intermediate": [
+ false
+ ],
+ "use_cache": [
+ false
+ ]
+ },
"outputs": []
},
"flux2_denoise": {
@@ -463,12 +855,55 @@
"transformer",
"vae"
],
+ "literalInputs": {
+ "cfg_scale": [
+ 1
+ ],
+ "denoising_end": [
+ 1
+ ],
+ "denoising_start": [
+ 0
+ ],
+ "guidance": [
+ 1
+ ],
+ "height": [
+ 1024
+ ],
+ "is_intermediate": [
+ true
+ ],
+ "num_steps": [
+ 4
+ ],
+ "scheduler": [
+ "euler"
+ ],
+ "use_cache": [
+ true
+ ],
+ "width": [
+ 1024
+ ]
+ },
"outputs": [
"latents"
]
},
"flux2_dev_model_loader": {
"inputs": [],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "mistral_encoder_model": [],
+ "model": [],
+ "use_cache": [
+ true
+ ],
+ "vae_model": []
+ },
"outputs": [
"max_seq_len",
"mistral_encoder",
@@ -482,12 +917,31 @@
"mistral_encoder",
"prompt"
],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "use_cache": [
+ true
+ ]
+ },
"outputs": [
"conditioning"
]
},
"flux2_klein_model_loader": {
"inputs": [],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "model": [],
+ "qwen3_encoder_model": [],
+ "use_cache": [
+ true
+ ],
+ "vae_model": []
+ },
"outputs": [
"max_seq_len",
"qwen3_encoder",
@@ -501,6 +955,14 @@
"prompt",
"qwen3_encoder"
],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "use_cache": [
+ true
+ ]
+ },
"outputs": [
"conditioning"
]
@@ -511,12 +973,29 @@
"metadata",
"vae"
],
+ "literalInputs": {
+ "is_intermediate": [
+ false
+ ],
+ "use_cache": [
+ false
+ ]
+ },
"outputs": []
},
"ideogram4_caption_builder": {
"inputs": [
"prompt"
],
+ "literalInputs": {
+ "color_palette": [],
+ "is_intermediate": [
+ true
+ ],
+ "use_cache": [
+ true
+ ]
+ },
"outputs": [
"value"
]
@@ -527,6 +1006,23 @@
"seed",
"transformer"
],
+ "literalInputs": {
+ "height": [
+ 1024
+ ],
+ "is_intermediate": [
+ true
+ ],
+ "sampler_preset": [
+ "V4_QUALITY_48"
+ ],
+ "use_cache": [
+ true
+ ],
+ "width": [
+ 1024
+ ]
+ },
"outputs": [
"latents"
]
@@ -537,10 +1033,27 @@
"metadata",
"vae"
],
+ "literalInputs": {
+ "is_intermediate": [
+ false
+ ],
+ "use_cache": [
+ false
+ ]
+ },
"outputs": []
},
"ideogram4_model_loader": {
"inputs": [],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "model": [],
+ "use_cache": [
+ true
+ ]
+ },
"outputs": [
"qwen3_encoder",
"transformer",
@@ -552,12 +1065,28 @@
"prompt",
"qwen3_encoder"
],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "use_cache": [
+ true
+ ]
+ },
"outputs": [
"conditioning"
]
},
"integer": {
"inputs": [],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "use_cache": [
+ true
+ ]
+ },
"outputs": [
"value"
]
@@ -568,12 +1097,43 @@
"seed",
"transformer"
],
+ "literalInputs": {
+ "cfg_scale": [
+ 1
+ ],
+ "height": [
+ 1024
+ ],
+ "is_intermediate": [
+ true
+ ],
+ "steps": [
+ 8
+ ],
+ "use_cache": [
+ true
+ ],
+ "width": [
+ 1024
+ ]
+ },
"outputs": [
"latents"
]
},
"krea2_model_loader": {
"inputs": [],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "model": [],
+ "qwen3_vl_encoder_model": [],
+ "use_cache": [
+ true
+ ],
+ "vae_model": []
+ },
"outputs": [
"qwen3_vl_encoder",
"transformer",
@@ -585,6 +1145,14 @@
"prompt",
"qwen3_vl_encoder"
],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "use_cache": [
+ true
+ ]
+ },
"outputs": [
"conditioning"
]
@@ -595,10 +1163,33 @@
"metadata",
"vae"
],
+ "literalInputs": {
+ "color_compensation": [
+ "None"
+ ],
+ "fp32": [
+ true
+ ],
+ "is_intermediate": [
+ false
+ ],
+ "use_cache": [
+ false
+ ]
+ },
"outputs": []
},
"main_model_loader": {
"inputs": [],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "model": [],
+ "use_cache": [
+ true
+ ]
+ },
"outputs": [
"clip",
"unet",
@@ -609,6 +1200,25 @@
"inputs": [
"seed"
],
+ "literalInputs": {
+ "height": [
+ 1024,
+ 512
+ ],
+ "is_intermediate": [
+ true
+ ],
+ "use_cache": [
+ true
+ ],
+ "use_cpu": [
+ true
+ ],
+ "width": [
+ 1024,
+ 512
+ ]
+ },
"outputs": [
"noise"
]
@@ -620,6 +1230,26 @@
"seed",
"transformer"
],
+ "literalInputs": {
+ "cfg_scale": [
+ 4
+ ],
+ "height": [
+ 1024
+ ],
+ "is_intermediate": [
+ true
+ ],
+ "steps": [
+ 40
+ ],
+ "use_cache": [
+ true
+ ],
+ "width": [
+ 1024
+ ]
+ },
"outputs": [
"latents"
]
@@ -630,10 +1260,29 @@
"metadata",
"vae"
],
+ "literalInputs": {
+ "is_intermediate": [
+ false
+ ],
+ "use_cache": [
+ false
+ ]
+ },
"outputs": []
},
"qwen_image_model_loader": {
"inputs": [],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "model": [],
+ "qwen_vl_encoder_model": [],
+ "use_cache": [
+ true
+ ],
+ "vae_model": []
+ },
"outputs": [
"qwen_vl_encoder",
"transformer",
@@ -645,6 +1294,14 @@
"prompt",
"qwen_vl_encoder"
],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "use_cache": [
+ true
+ ]
+ },
"outputs": [
"conditioning"
]
@@ -656,6 +1313,32 @@
"seed",
"transformer"
],
+ "literalInputs": {
+ "cfg_scale": [
+ 7
+ ],
+ "denoising_end": [
+ 1
+ ],
+ "denoising_start": [
+ 0
+ ],
+ "height": [
+ 1024
+ ],
+ "is_intermediate": [
+ true
+ ],
+ "steps": [
+ 30
+ ],
+ "use_cache": [
+ true
+ ],
+ "width": [
+ 1024
+ ]
+ },
"outputs": [
"latents"
]
@@ -666,10 +1349,27 @@
"metadata",
"vae"
],
+ "literalInputs": {
+ "is_intermediate": [
+ false
+ ],
+ "use_cache": [
+ false
+ ]
+ },
"outputs": []
},
"sd3_model_loader": {
"inputs": [],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "model": [],
+ "use_cache": [
+ true
+ ]
+ },
"outputs": [
"clip_g",
"clip_l",
@@ -685,6 +1385,14 @@
"prompt",
"t5_encoder"
],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "use_cache": [
+ true
+ ]
+ },
"outputs": [
"conditioning"
]
@@ -696,12 +1404,29 @@
"prompt",
"style"
],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "use_cache": [
+ true
+ ]
+ },
"outputs": [
"conditioning"
]
},
"sdxl_model_loader": {
"inputs": [],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "model": [],
+ "use_cache": [
+ true
+ ]
+ },
"outputs": [
"clip",
"clip2",
@@ -711,6 +1436,14 @@
},
"string": {
"inputs": [],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "use_cache": [
+ true
+ ]
+ },
"outputs": [
"value"
]
@@ -722,6 +1455,26 @@
"seed",
"transformer"
],
+ "literalInputs": {
+ "guidance_scale": [
+ 4
+ ],
+ "height": [
+ 1024
+ ],
+ "is_intermediate": [
+ true
+ ],
+ "steps": [
+ 40
+ ],
+ "use_cache": [
+ true
+ ],
+ "width": [
+ 1024
+ ]
+ },
"outputs": [
"latents"
]
@@ -732,10 +1485,30 @@
"metadata",
"vae"
],
+ "literalInputs": {
+ "is_intermediate": [
+ false
+ ],
+ "use_cache": [
+ false
+ ]
+ },
"outputs": []
},
"wan_model_loader": {
"inputs": [],
+ "literalInputs": {
+ "component_source": [],
+ "is_intermediate": [
+ true
+ ],
+ "model": [],
+ "use_cache": [
+ true
+ ],
+ "vae_model": [],
+ "wan_t5_encoder_model": []
+ },
"outputs": [
"transformer",
"vae",
@@ -747,6 +1520,14 @@
"prompt",
"wan_t5_encoder"
],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "use_cache": [
+ true
+ ]
+ },
"outputs": [
"conditioning"
]
@@ -758,6 +1539,35 @@
"transformer",
"vae"
],
+ "literalInputs": {
+ "denoising_end": [
+ 1
+ ],
+ "denoising_start": [
+ 0
+ ],
+ "guidance_scale": [
+ 1
+ ],
+ "height": [
+ 1024
+ ],
+ "is_intermediate": [
+ true
+ ],
+ "scheduler": [
+ "euler"
+ ],
+ "steps": [
+ 8
+ ],
+ "use_cache": [
+ true
+ ],
+ "width": [
+ 1024
+ ]
+ },
"outputs": [
"latents"
]
@@ -768,10 +1578,30 @@
"metadata",
"vae"
],
+ "literalInputs": {
+ "is_intermediate": [
+ false
+ ],
+ "use_cache": [
+ false
+ ]
+ },
"outputs": []
},
"z_image_model_loader": {
"inputs": [],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "model": [],
+ "qwen3_encoder_model": [],
+ "qwen3_source_model": [],
+ "use_cache": [
+ true
+ ],
+ "vae_model": []
+ },
"outputs": [
"qwen3_encoder",
"transformer",
@@ -783,6 +1613,14 @@
"prompt",
"qwen3_encoder"
],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "use_cache": [
+ true
+ ]
+ },
"outputs": [
"conditioning"
]
diff --git a/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts b/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts
index 2429462990..3517532ae2 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts
@@ -934,6 +934,49 @@ describe('Krea-2, Ideogram 4 and Wan graphs', () => {
});
});
+describe('ERNIE-Image graphs', () => {
+ const ernieModel: MainModelConfig = {
+ base: 'ernie-image',
+ format: 'diffusers',
+ key: 'ernie-image',
+ name: 'ERNIE-Image',
+ type: 'main',
+ };
+
+ it('encodes the negative prompt only while CFG is on', () => {
+ // `negative_conditioning` is required when guidance_scale != 1 and unused otherwise, and the
+ // coverage suite only ever compiles at the base default of 4 — so the CFG-off branch is
+ // compiled nowhere else. ERNIE-Image-Turbo ships `guidance=1.0`, which is how a user gets there.
+ const withCfg = compile(ernieModel, { cfgScale: 4 });
+
+ expect(withCfg.nodes.neg_cond?.type).toBe('ernie_image_text_encoder');
+ expect(getEdge(withCfg, 'neg_cond', 'text_encoder')?.source.node_id).toBe('model_loader');
+ expect(getEdge(withCfg, 'neg_cond', 'prompt')?.source.node_id).toBe('negative_prompt');
+ expect(getEdge(withCfg, 'denoise_latents', 'negative_conditioning')?.source.node_id).toBe('neg_cond');
+ expect(withCfg.nodes.denoise_latents?.guidance_scale).toBe(4);
+
+ const withoutCfg = compile(ernieModel, { cfgScale: 1 });
+
+ expect(withoutCfg.nodes.neg_cond).toBeUndefined();
+ expect(getEdge(withoutCfg, 'denoise_latents', 'negative_conditioning')).toBeUndefined();
+ expect(withoutCfg.nodes.denoise_latents?.guidance_scale).toBe(1);
+ });
+
+ it('builds the rest of the graph out of the one bundled pipeline', () => {
+ const graph = compile(ernieModel, { scheduler: 'dpmpp_2m' });
+
+ expect(graph.nodes.canvas_output?.type).toBe('ernie_image_vae_decode');
+ expect(getEdge(graph, 'canvas_output', 'vae')?.source.node_id).toBe('model_loader');
+ expect(getEdge(graph, 'denoise_latents', 'transformer')?.source.node_id).toBe('model_loader');
+ // The loader can hold a prompt enhancer resident, which cannot be idle-offloaded; Generate
+ // never surfaces it, so the graph has to keep asking for it to stay unloaded.
+ expect(graph.nodes.model_loader?.use_prompt_enhancer).toBe(false);
+ // The node's scheduler is a euler/heun/lcm Literal, so a standard-set value left over from
+ // another model has to be coerced before it reaches the graph.
+ expect(graph.nodes.denoise_latents?.scheduler).toBe('euler');
+ });
+});
+
describe('PiD decode', () => {
const pidDecoder = (base: string): ComponentModelConfig => ({
base,
diff --git a/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.test.ts b/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.test.ts
index 9357826fda..f0abef18bc 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.test.ts
@@ -7,12 +7,20 @@
* the moment it is registered, and asserts the properties that hold for *all* of them: the
* component policy is satisfiable, the builder runs, and the resulting graph is structurally sound.
*
- * It also checks the node types and edge fields each base emits against a committed fixture. That
+ * It also checks the node types and fields each base emits against a committed fixture. That
* fixture is the frontend half of a cross-stack contract — `tests/app/invocations/
* test_frontend_graph_node_types.py` reads it and checks every type and field against the backend's
* `InvocationRegistry`. A node moved between modules and accidentally renamed shows up there, which
* no frontend-only assertion can see.
*
+ * Edges are only half of what a builder writes. The other half is what it sets *literally* on a
+ * node — `use_prompt_enhancer: false`, a scheduler string, `denoising_start: 0` — which no edge
+ * records. Those inputs are the ones nothing could check: the frontend never sees a backend schema,
+ * so it cannot know that `ernie_image_denoise.scheduler` is a three-value `Literal`. Recording the
+ * literal names *and* their values lets the Python half validate each against the field's real
+ * annotation, turning a renamed input or an out-of-range scheduler into a test failure instead of
+ * an enqueue-time error on a graph the user cannot edit.
+ *
* The snapshot file is written by this test and by nothing else — `.oxfmtrc.json` excludes it for
* that reason. Letting the formatter reflow a generated file too would leave both in charge of the
* same bytes, and `format:check` would fail on whichever layout the other one wrote last.
@@ -238,9 +246,13 @@ describe('generate graph coverage', () => {
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<string, { inputs: Set<string>; outputs: Set<string> }> = {};
+ const fields: Record<
+ string,
+ { inputs: Set<string>; literals: Map<string, Map<string, unknown>>; outputs: Set<string> }
+ > = {};
- const fieldsFor = (nodeType: string) => (fields[nodeType] ??= { inputs: new Set(), outputs: new Set() });
+ const fieldsFor = (nodeType: string) =>
+ (fields[nodeType] ??= { inputs: new Set(), literals: new Map(), outputs: new Set() });
for (const { base, shape } of cases) {
const { filled, graph } = compileForShape(base, shape);
@@ -251,6 +263,29 @@ describe('generate graph coverage', () => {
...new Set([...entry.nodeTypes, ...Object.values(graph.nodes).map((node) => node.type)]),
].sort();
+ for (const node of Object.values(graph.nodes)) {
+ const { literals } = fieldsFor(node.type);
+
+ for (const [field, value] of Object.entries(node)) {
+ // `id` and `type` address the node rather than feed it, and an undefined value is not
+ // serialized into the request at all — the builders use it to mean "leave the default".
+ if (field === 'id' || field === 'type' || value === undefined) {
+ continue;
+ }
+
+ const values = literals.get(field) ?? new Map<string, unknown>();
+ literals.set(field, values);
+
+ // Values are recorded for scalars only, so the name is always checked but the value is
+ // checked where checking it means something. The object-valued inputs are model
+ // identifiers and LoRA lists built from this file's synthetic fixtures, which carry no
+ // `hash`; validating those would assert something about the fixture, not the contract.
+ if (value === null || typeof value !== 'object') {
+ values.set(JSON.stringify(value), value);
+ }
+ }
+ }
+
for (const edge of graph.edges) {
fieldsFor(graph.nodes[edge.source.node_id]!.type).outputs.add(edge.source.field);
fieldsFor(graph.nodes[edge.destination.node_id]!.type).inputs.add(edge.destination.field);
@@ -261,15 +296,28 @@ describe('generate graph coverage', () => {
_comment:
'Generated by src/features/generation/core/graphCoverage.test.ts; regenerate with ' +
'`vitest -u`. Excluded from oxfmt so the test alone owns its layout. Consumed by ' +
- 'tests/app/invocations/test_frontend_graph_node_types.py, which checks every node type and ' +
- 'field below against the backend invocation registry.',
+ 'tests/app/invocations/test_frontend_graph_node_types.py, which checks every node type, ' +
+ 'edge field and literal input value below against the backend invocation registry. An ' +
+ 'empty literalInputs value list means the field is set to something other than a scalar, ' +
+ 'so only its name is checked.',
byBase,
fieldsByNodeType: Object.fromEntries(
Object.entries(fields)
.sort(([a], [b]) => a.localeCompare(b))
- .map(([nodeType, { inputs, outputs }]) => [
+ .map(([nodeType, { inputs, literals, outputs }]) => [
nodeType,
- { inputs: [...inputs].sort(), outputs: [...outputs].sort() },
+ {
+ inputs: [...inputs].sort(),
+ literalInputs: Object.fromEntries(
+ [...literals]
+ .sort(([a], [b]) => a.localeCompare(b))
+ .map(([field, values]) => [
+ field,
+ [...values].sort(([a], [b]) => a.localeCompare(b)).map(([, value]) => value),
+ ])
+ ),
+ outputs: [...outputs].sort(),
+ },
])
),
};
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateRenderSection.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateRenderSection.browser.test.tsx
new file mode 100644
index 0000000000..7f35308903
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateRenderSection.browser.test.tsx
@@ -0,0 +1,130 @@
+/* oxlint-disable react-perf/jsx-no-new-object-as-prop */
+import type { MainModelConfig } from '@features/generation/core/types';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { getDefaultGenerateSettings } from '@features/generation/core/baseGenerationPolicies';
+import { system } from '@theme/system';
+import { createInstance } from 'i18next';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { GenerateRenderSection } from './GenerateRenderSection';
+
+vi.mock('./GenerationUiContext', () => ({
+ useGenerationUi: () => ({
+ queueInsights: { seedHistory: [] },
+ sectionPreferences: { sectionsOpen: { render: true }, setSectionOpen: vi.fn() },
+ }),
+}));
+
+const i18n = createInstance();
+void i18n.use(initReactI18next).init({
+ fallbackLng: 'en',
+ initAsync: false,
+ lng: 'en',
+ resources: {
+ en: {
+ translation: {
+ widgets: {
+ generate: {
+ random: 'Random',
+ render: 'Render',
+ scheduler: 'Scheduler',
+ seed: 'Seed',
+ steps: 'Steps',
+ useModelDefaultField: 'Use model default {{field}}',
+ useModelDefaultScheduler: 'Use model default scheduler',
+ useModelDefaultSteps: 'Use model default steps',
+ },
+ },
+ },
+ },
+ },
+});
+
+/**
+ * FLUX Fill's own recommendation is `guidance=30`, well past the guidance slider's practical top of
+ * 10. That is the case the number input's looser `numberInputMax` exists for: without it the field
+ * clamps to the slider's bound the first time it loses focus, and the model's own default is gone
+ * before the user has touched anything.
+ */
+const fluxFillModel: MainModelConfig = {
+ base: 'flux',
+ default_settings: { cfg_scale: 1, guidance: 30 },
+ format: 'diffusers',
+ key: 'flux-fill',
+ name: 'FLUX Fill',
+ type: 'main',
+};
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const settle = (action: () => void): Promise<void> =>
+ act(async () => {
+ action();
+ await new Promise<void>((resolve) => {
+ globalThis.setTimeout(resolve, 50);
+ });
+ });
+
+const render = async (model: MainModelConfig) => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ const onCommit = vi.fn();
+
+ await settle(() => {
+ root?.render(
+ <ChakraProvider value={system}>
+ <I18nextProvider i18n={i18n}>
+ <GenerateRenderSection
+ selectedModel={model}
+ settings={getDefaultGenerateSettings(model)}
+ onCommit={onCommit}
+ onCommitImmediate={vi.fn()}
+ />
+ </I18nextProvider>
+ </ChakraProvider>
+ );
+ });
+
+ return onCommit;
+};
+
+afterEach(async () => {
+ await settle(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+describe('GenerateRenderSection guidance field', () => {
+ it('does not clamp a model default above the slider track when the field loses focus', async () => {
+ const onCommit = await render(fluxFillModel);
+ const input = host?.querySelector<HTMLInputElement>('input[aria-label="Guidance"]');
+
+ expect(input?.value).toBe('30');
+
+ await settle(() => input?.focus());
+ await settle(() => input?.blur());
+
+ // The commit is the observable, not the input's value: the field is controlled, so the value
+ // prop puts 30 back either way and only the caller sees the clamp. Dropping numberInputMax
+ // makes this a commit of 10, which is then the value every subsequent graph is compiled with.
+ expect(onCommit).not.toHaveBeenCalled();
+ });
+
+ it('still holds the guidance slider itself to its practical range', async () => {
+ await render(fluxFillModel);
+ // The thumb is the tooltip trigger, so `role="slider"` is the stable selector. Guidance is the
+ // second slider in the section; steps is the first.
+ const thumbs = [...(host?.querySelectorAll('[role="slider"]') ?? [])];
+
+ expect(thumbs[1]?.getAttribute('aria-valuenow')).toBe('10');
+ expect(thumbs[1]?.getAttribute('aria-valuemax')).toBe('10');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/video/core/dimensions.ts b/invokeai/frontend/webv2/src/features/video/core/dimensions.ts
index 6f671cc2bc..a147a9b868 100644
--- a/invokeai/frontend/webv2/src/features/video/core/dimensions.ts
+++ b/invokeai/frontend/webv2/src/features/video/core/dimensions.ts
@@ -9,7 +9,7 @@ import type {
* Client-side ports of the backend's video canvas math, so the panel can show
* and validate the exact dimensions a graph will run at without extra nodes:
*
- * - Wan: `_scale_and_snap` in `invokeai/app/invocations/wan_ideal_dimensions.py`
+ * - Wan: `_scale_and_snap` in `invokeai/app/invocations/wan/wan_ideal_dimensions.py`
* ("nearest" rounding — the node default; the other modes are workflow-only).
* - MiniMax H3: `resolve_canvas_size` in `invokeai/backend/minimax_h3/packing.py`
* and `resolve_lowres_canvas_size` in `invokeai/backend/minimax_h3/presets.py`.
diff --git a/scripts/new_architecture.py b/scripts/new_architecture.py
index 7368512046..286c556fbe 100644
--- a/scripts/new_architecture.py
+++ b/scripts/new_architecture.py
@@ -8,6 +8,11 @@ declaration under `architectures/defs/`, its invocation package, and its starter
declaration is generated with every required facet present but obviously wrong, so it fails loudly
at boot until someone fills it in — a stub that boots would be worse than no stub.
+"Fails loudly" is carried by `LatentSpace.__post_init__`, not by `registry.validate()`, which only
+checks that the required facets are *present*: the placeholder projection is a single all-zero row,
+which no VAE has, so constructing it raises while `defs/` is being imported. That is before the
+registry is even called, and the traceback names the generated file.
+
The rest cannot be generated, and the point of this script is as much to enumerate that rest as to
write the three. That list is *derived* on each run rather than written down here: any module naming
five or more `BaseModelType` members is dispatching on base, so a new one has to be added to it by
@@ -73,6 +78,8 @@ from invokeai.backend.stable_diffusion.diffusion.conditioning_data import BasicC
# TODO: the latent -> RGB projection for this VAE, one row per latent channel. If the architecture
# reuses another's VAE, import that LatentSpace instead of declaring a second copy of its matrix.
+# An all-zero projection is rejected by LatentSpace, so importing this module raises until it is
+# replaced — that is what keeps a half-filled declaration from reaching a generation.
{enum_name.upper()}_LATENT_RGB_FACTORS = [
[0.0, 0.0, 0.0],
]
@@ -195,7 +202,8 @@ def main() -> int:
print(f" {count:>3} bases {path}")
print(
- "\nThe app will not boot until the generated declaration is filled in — that is deliberate."
+ "\nThe app will not boot until the generated declaration is filled in — that is deliberate:"
+ "\nits placeholder latent projection is all zeros, which LatentSpace refuses to construct."
if args.write
else "\nNothing was written. Re-run with --write."
)
diff --git a/tests/app/invocations/test_frontend_graph_node_types.py b/tests/app/invocations/test_frontend_graph_node_types.py
index 87101c92e4..ed98c89921 100644
--- a/tests/app/invocations/test_frontend_graph_node_types.py
+++ b/tests/app/invocations/test_frontend_graph_node_types.py
@@ -8,15 +8,22 @@ the invocations it has.
The contract in between is `generateGraphNodeTypes.json`, written by
`src/features/generation/core/graphCoverage.test.ts` (regenerate with `vitest -u`). It records every
-node type and every edge field that webv2's `compileGenerateGraph` produces for every supported
+node type, every edge field, and every *literal* input value — the ones webv2 writes straight onto a
+node, with no edge to record them — that `compileGenerateGraph` produces for every supported
architecture. This module checks all of it against the real registry.
+
+The literal values are checked against the field's own annotation, not merely against its name. That
+is where the frontend is blindest: it picks a scheduler from its own `FLOW_SCHEDULER_OPTIONS` while
+`ernie_image_denoise.scheduler` is a three-value `Literal`, and nothing but this comparison relates
+the two.
"""
import json
from pathlib import Path
-from typing import Any
+from typing import Annotated, Any
import pytest
+from pydantic import TypeAdapter, ValidationError
from invokeai.app.invocations.baseinvocation import BaseInvocation, InvocationRegistry
from invokeai.app.services.shared.graph import * # noqa: F401 F403 -- imports all invocations, populating the registry
@@ -41,7 +48,7 @@ def _contract() -> dict[str, Any]:
CONTRACT = _contract()
BY_BASE: dict[str, dict[str, Any]] = CONTRACT["byBase"]
-FIELDS_BY_NODE_TYPE: dict[str, dict[str, list[str]]] = CONTRACT["fieldsByNodeType"]
+FIELDS_BY_NODE_TYPE: dict[str, dict[str, Any]] = CONTRACT["fieldsByNodeType"]
def _invocation(node_type: str) -> type[BaseInvocation]:
@@ -65,6 +72,23 @@ def test_the_contract_covers_every_supported_base() -> None:
assert all(entry["nodeTypes"] for entry in BY_BASE.values())
+def test_the_contract_records_the_values_webv2_writes_onto_nodes() -> None:
+ """The literal section going vacuous is the failure mode the edge-only contract already had.
+
+ A recording bug that dropped the values while keeping the names would leave every annotation
+ check below passing over an empty list. Both floors are well under the current numbers (58 node
+ types carry literals, 241 scalar values between them) — they separate "recorded" from "empty",
+ not one architecture from the next.
+ """
+ with_literals = [node_type for node_type, entry in FIELDS_BY_NODE_TYPE.items() if entry["literalInputs"]]
+ recorded_values = sum(
+ len(values) for entry in FIELDS_BY_NODE_TYPE.values() for values in entry["literalInputs"].values()
+ )
+
+ assert len(with_literals) >= 40
+ assert recorded_values >= 150
+
+
@pytest.mark.parametrize("base", sorted(BY_BASE), ids=lambda base: base)
def test_every_node_type_a_base_compiles_is_registered(base: str) -> None:
missing = [
@@ -90,3 +114,70 @@ def test_edge_source_fields_are_real_output_fields(node_type: str) -> None:
output_fields = set(cls.get_output_annotation().model_fields)
unknown = sorted(set(FIELDS_BY_NODE_TYPE[node_type]["outputs"]) - output_fields)
assert unknown == [], f"webv2 wires edges out of unknown outputs on '{node_type}': {unknown}"
+
+
+def _annotation(cls: type[BaseInvocation], field_name: str) -> Any:
+ """The field's annotation together with the constraints declared beside it.
+
+ `multiple_of=16` on a denoise node's `width` lives in `FieldInfo.metadata`, not in the
+ annotation, and it is exactly the kind of bound the frontend restates in its own table
+ (`BASE_GENERATION['ernie-image'].dimensions.grid`) with nothing relating the two.
+ """
+ field = cls.model_fields[field_name]
+ return Annotated[tuple([field.annotation, *field.metadata])] if field.metadata else field.annotation
+
+
+SILENTLY_IGNORED: dict[str, set[str]] = {
+ # `color_compensation` is a field of `i2l`, the *encode* node — legacy web sets it only there,
+ # on the img2img/inpaint/outpaint paths. webv2 writes it onto the `l2i` decode node instead
+ # (`graph.ts`, `l2iProps`), where no such field exists, so the Generate tab's SDXL colour
+ # -compensation toggle changes nothing about the generated image. Invocations ignore extra
+ # fields rather than rejecting them, which is why this never surfaced as an enqueue error.
+ "l2i": {"color_compensation"},
+}
+"""Inputs webv2 writes that the invocation does not declare.
+
+Not an exemption list: the assertion below is an equality, so a new mismatch fails here and so does
+fixing one of these — the entry has to be deleted with the fix. Each is a silent no-op today,
+because `BaseInvocation` does not forbid extra fields.
+"""
+
+
[email protected]("node_type", sorted(FIELDS_BY_NODE_TYPE), ids=lambda node_type: node_type)
+def test_literal_inputs_are_real_invocation_fields(node_type: str) -> None:
+ """The half no edge records: a field webv2 sets directly, with no edge to point at it."""
+ cls = _invocation(node_type)
+ if cls.model_config.get("extra") == "allow":
+ # `CoreMetadataInvocation` is an open bag by design — `invoke` dumps whatever was set on it
+ # into the image's metadata record — so there is no closed field set to check against.
+ pytest.skip(f"'{node_type}' accepts extra fields by design")
+
+ unknown = sorted(set(FIELDS_BY_NODE_TYPE[node_type]["literalInputs"]) - set(cls.model_fields))
+ assert unknown == sorted(SILENTLY_IGNORED.get(node_type, set())), (
+ f"webv2 sets inputs '{node_type}' does not declare: {unknown}. They are ignored rather than "
+ f"rejected, so whatever they were meant to do silently does not happen."
+ )
+
+
[email protected]("node_type", sorted(FIELDS_BY_NODE_TYPE), ids=lambda node_type: node_type)
+def test_literal_input_values_satisfy_the_field_they_are_written_to(node_type: str) -> None:
+ """A name that still exists but no longer accepts the value is the same enqueue failure.
+
+ The scheduler fields are the motivating case: webv2 offers its own option list per base, the
+ node declares a `Literal`, and until the two are compared here an option the node never accepted
+ reaches the user as a validation error after they press Invoke.
+ """
+ cls = _invocation(node_type)
+ rejected: list[str] = []
+
+ for field_name, values in sorted(FIELDS_BY_NODE_TYPE[node_type]["literalInputs"].items()):
+ if field_name not in cls.model_fields:
+ continue # Reported by the test above; a missing field has no annotation to check.
+ adapter = TypeAdapter(_annotation(cls, field_name))
+ for value in values:
+ try:
+ adapter.validate_python(value)
+ except ValidationError as error:
+ rejected.append(f"{field_name}={value!r}: {error.errors()[0]['msg']}")
+
+ assert rejected == [], f"webv2 writes values '{node_type}' rejects: {'; '.join(rejected)}"
diff --git a/tests/app/invocations/test_ideal_size.py b/tests/app/invocations/test_ideal_size.py
index 00694b56d8..73233c4c7d 100644
--- a/tests/app/invocations/test_ideal_size.py
+++ b/tests/app/invocations/test_ideal_size.py
@@ -9,8 +9,8 @@ import pytest
from invokeai.app.invocations.ideal_size import IdealSizeInvocation
from invokeai.app.invocations.model import ModelIdentifierField, UNetField
-from invokeai.backend.architectures import ArchitectureError, generative_bases, resolve_default_settings
-from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelType
+from invokeai.backend.architectures import ArchitectureError, generative_bases
+from invokeai.backend.model_manager.taxonomy import AnyVariant, BaseModelType, ModelType, WanVariantType
def _unet(base: BaseModelType) -> UNetField:
@@ -19,71 +19,77 @@ def _unet(base: BaseModelType) -> UNetField:
return UNetField(unet=identifier, scheduler=identifier, loras=[])
-def _invoke(base: BaseModelType, width: int = 1024, height: int = 576, multiplier: float = 1.0) -> Any:
+def _invoke(
+ base: BaseModelType,
+ width: int = 1024,
+ height: int = 576,
+ multiplier: float = 1.0,
+ variant: AnyVariant | None = None,
+) -> Any:
node = IdealSizeInvocation(width=width, height=height, multiplier=multiplier, unet=_unet(base))
context = MagicMock()
- context.models.get_config.return_value = SimpleNamespace(base=base)
+ # No `variant` attribute at all unless one is asked for: plenty of model configs have none, and
+ # the node has to cope with that rather than only with `variant=None`.
+ config = SimpleNamespace(base=base) if variant is None else SimpleNamespace(base=base, variant=variant)
+ context.models.get_config.return_value = config
return node.invoke(context)
- ("base", "expected"),
- [
- # The six the old if/elif covered, at the aspect ratio of the node's own defaults.
- (BaseModelType.StableDiffusion1, (680, 384)),
- (BaseModelType.StableDiffusion2, (1024, 576)),
- (BaseModelType.StableDiffusionXL, (1360, 768)),
- # The other three were hardcoded to 1024 and trimmed to 8. They now derive the dimension
- # from `DefaultSettingsFacet.width` and the grid from `FeaturesFacet.dimension_grid`, so
- # both halves are pinned here: a model-card width edited for a UX reason would otherwise
- # silently move every legacy workflow's output resolution.
- (BaseModelType.StableDiffusion3, (1360, 768)),
- (BaseModelType.Flux, (1360, 768)),
- (BaseModelType.Flux2, (1360, 768)),
- ],
-)
-def test_the_previously_supported_bases_are_unchanged(base: BaseModelType, expected: tuple[int, int]) -> None:
- """SD 1.x, 2.x and XL have an 8-pixel grid, which is what the old hardcoded value was. SD3,
- FLUX and FLUX.2 land on 16 and happen to agree at this aspect ratio."""
+# What the node returns for each architecture at its own field defaults (1024x576). Derived by
+# hand, not from the implementation: the node squares the architecture's recommended width to get a
+# target area, fits that area to the requested 1.7778 aspect, floors, and trims to the dimension
+# grid. SD 1.x: 512^2 = 262144 px; height = sqrt(262144 / 1.7778) = 384; width = 682.67 -> 682 ->
+# trimmed to 680 on the 8-pixel grid.
+#
+# Both halves are pinned deliberately. The dimension follows `DefaultSettingsFacet.width`, so a
+# model-card width edited for a UX reason would otherwise silently move every legacy workflow's
+# output resolution; the grid follows `FeaturesFacet.dimension_grid`, which the old code hardcoded
+# to 8 for everything -- a FLUX size came back off-grid and the denoise node then rejected it.
+IDEAL_SIZE_AT_NODE_DEFAULTS: dict[BaseModelType, tuple[int, int]] = {
+ BaseModelType.Anima: (1360, 768),
+ BaseModelType.CogView4: (1344, 768),
+ BaseModelType.ErnieImage: (1360, 768),
+ BaseModelType.Flux: (1360, 768),
+ BaseModelType.Flux2: (1360, 768),
+ BaseModelType.Ideogram4: (1360, 768),
+ BaseModelType.Krea2: (1360, 768),
+ BaseModelType.MiniMaxH3: (1792, 992),
+ BaseModelType.QwenImage: (1360, 768),
+ BaseModelType.StableDiffusion1: (680, 384),
+ BaseModelType.StableDiffusion2: (1024, 576),
+ BaseModelType.StableDiffusion3: (1360, 768),
+ BaseModelType.StableDiffusionXL: (1360, 768),
+ BaseModelType.StableDiffusionXLRefiner: (1360, 768),
+ BaseModelType.Wan: (1360, 768),
+ BaseModelType.ZImage: (1360, 768),
+}
+
+
[email protected](("base", "expected"), sorted(IDEAL_SIZE_AT_NODE_DEFAULTS.items(), key=lambda i: i[0].value))
+def test_the_ideal_size_is_pinned_for_every_architecture(base: BaseModelType, expected: tuple[int, int]) -> None:
+ """The old dispatch was an if/elif over six bases ending in `raise ValueError(Unsupported model
+ type)`, which fired here -- at generation time, after the model had loaded -- for the other
+ nine. Every architecture now has an answer, and these are the answers."""
output = _invoke(base)
assert (output.width, output.height) == expected
-def test_flux_now_lands_on_its_own_grid() -> None:
- """The old code trimmed to 8 for every architecture. FLUX needs 16, so a size could come back
- off-grid — the node would hand the graph a width the denoise node then rejects."""
- output = _invoke(BaseModelType.Flux)
- assert output.width % 16 == 0 and output.height % 16 == 0
-
-
-def test_every_architecture_gets_an_answer() -> None:
- """The old dispatch raised `Unsupported model type` for nine of the sixteen — at generation
- time, after the model had loaded."""
- failed = []
- for base in generative_bases():
- settings = resolve_default_settings(base)
- if settings is None or settings.width is None:
- continue # the refiner, which declares a canvas but is not run on its own
- try:
- _invoke(base)
- except Exception as exc: # noqa: BLE001 - the point is that nothing raises
- failed.append(f"{base.value}: {type(exc).__name__}")
- assert failed == []
-
-
-def test_the_result_stays_on_the_declared_grid_for_every_architecture() -> None:
- from invokeai.backend.architectures import FeaturesFacet, require
-
- off_grid = []
- for base in generative_bases():
- settings = resolve_default_settings(base)
- if settings is None or settings.width is None:
- continue
- grid = require(base, FeaturesFacet).dimension_grid
- output = _invoke(base)
- if output.width % grid or output.height % grid:
- off_grid.append(f"{base.value}: {output.width}x{output.height} not a multiple of {grid}")
- assert off_grid == []
+def test_every_architecture_is_pinned() -> None:
+ """A new architecture has to land in the table above, rather than going unchecked."""
+ assert set(IDEAL_SIZE_AT_NODE_DEFAULTS) == set(generative_bases())
+
+
+def test_wan_uses_the_grid_of_the_variant_it_was_given() -> None:
+ """TI2V-5B takes multiples of 32 where A14B takes 16, and `wan_denoise` only rejects the
+ mismatch inside `invoke()`. 1360 is the A14B answer and `1360 % 32 == 16`, so a TI2V-5B model
+ routed through this node used to produce a width its own denoise node refuses."""
+ a14b = _invoke(BaseModelType.Wan, variant=WanVariantType.T2V_A14B)
+ assert (a14b.width, a14b.height) == IDEAL_SIZE_AT_NODE_DEFAULTS[BaseModelType.Wan]
+ assert a14b.width % 32 == 16, "otherwise the case below proves nothing"
+
+ ti2v = _invoke(BaseModelType.Wan, variant=WanVariantType.TI2V_5B)
+ assert (ti2v.width, ti2v.height) == (1344, 768)
+ assert ti2v.width % 32 == 0 and ti2v.height % 32 == 0
def test_an_architecture_without_dimensions_says_so() -> None:
diff --git a/tests/app/services/external_generation/test_external_generation_service.py b/tests/app/services/external_generation/test_external_generation_service.py
index aed641fe60..4bf6eae0c8 100644
--- a/tests/app/services/external_generation/test_external_generation_service.py
+++ b/tests/app/services/external_generation/test_external_generation_service.py
@@ -251,7 +251,7 @@ def test_generate_resizes_inpaint_result_to_original_init_size() -> None:
def test_qwen_image_edit_max_enforces_three_reference_images() -> None:
- from invokeai.backend.model_manager.starter_models import alibabacloud_qwen_image_edit_max
+ from invokeai.backend.model_manager.starter_models.external import alibabacloud_qwen_image_edit_max
capabilities = alibabacloud_qwen_image_edit_max.capabilities
assert capabilities is not None
diff --git a/tests/backend/architectures/test_conditioning.py b/tests/backend/architectures/test_conditioning.py
index 9c60ee9756..f99245712b 100644
--- a/tests/backend/architectures/test_conditioning.py
+++ b/tests/backend/architectures/test_conditioning.py
@@ -1,16 +1,22 @@
"""The conditioning facet, and the `safe_globals` list built from it."""
-from invokeai.backend.architectures import conditioning_infos, generative_bases
+import ast
+from pathlib import Path
+
+from invokeai.backend.architectures import conditioning_infos, conditioning_safe_globals, generative_bases
from invokeai.backend.architectures.facets.conditioning import ConditioningFacet
from invokeai.backend.architectures.registry import get
from invokeai.backend.model_manager.taxonomy import BaseModelType
from invokeai.backend.stable_diffusion.diffusion.conditioning_data import (
BasicConditioningInfo,
+ ConditioningFieldData,
FLUXConditioningInfo,
IPAdapterConditioningInfo,
SDXLConditioningInfo,
)
+DEPENDENCIES = Path(__file__).parents[3] / "invokeai" / "app" / "api" / "dependencies.py"
+
def test_every_architecture_declares_a_conditioning_type() -> None:
undeclared = sorted(b.value for b in generative_bases() if get(b, ConditioningFacet) is None)
@@ -54,13 +60,67 @@ def test_the_declared_classes_are_the_ones_that_get_serialized() -> None:
assert all(isinstance(cls, type) for cls in infos)
-def test_it_matches_what_dependencies_installs() -> None:
- """The list the app actually builds, assembled the same way `dependencies` assembles it."""
- from invokeai.backend.stable_diffusion.diffusion.conditioning_data import ConditioningFieldData
+def _dependencies_ast() -> ast.Module:
+ return ast.parse(DEPENDENCIES.read_text(encoding="utf-8"))
+
+
+def _conditioning_serializer_call() -> ast.Call:
+ """The `ObjectSerializerDisk[ConditioningFieldData](...)` call in `dependencies.py`.
+
+ Found by its type parameter, which is what distinguishes it from the tensor serializer built
+ three lines above it.
+ """
+ calls = [
+ node
+ for node in ast.walk(_dependencies_ast())
+ if isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Subscript)
+ and isinstance(node.func.value, ast.Name)
+ and node.func.value.id == "ObjectSerializerDisk"
+ and isinstance(node.func.slice, ast.Name)
+ and node.func.slice.id == "ConditioningFieldData"
+ ]
+ assert len(calls) == 1, f"expected exactly one conditioning serializer in {DEPENDENCIES.name}, found {len(calls)}"
+ return calls[0]
+
+
+def test_dependencies_passes_the_assembled_list_as_safe_globals() -> None:
+ """Read out of `dependencies.py` itself, because this is the assertion the PR exists for.
+
+ Importing `dependencies` to inspect the built list is not an option — it pulls in the whole
+ service graph — and rebuilding the list here would only ever agree with itself: shortening the
+ call site to `[ConditioningFieldData]` would leave such a test green and the first FLUX, Wan or
+ Qwen generation dying mid-graph on an `UnpicklingError`. So the call site is parsed instead.
+ """
+ keywords = [kw for kw in _conditioning_serializer_call().keywords if kw.arg == "safe_globals"]
+ assert len(keywords) == 1, "safe_globals is not passed by keyword"
+
+ argument = keywords[0].value
+ assert isinstance(argument, ast.Call) and isinstance(argument.func, ast.Name), (
+ "safe_globals must be the assembled list itself, not an expression built at the call site"
+ )
+ assert argument.func.id == "conditioning_safe_globals"
+ assert not argument.args and not argument.keywords
+
+
+def test_dependencies_imports_that_list_from_the_architecture_package() -> None:
+ """Otherwise the name asserted above could be satisfied by anything defined locally."""
+ imported = {
+ alias.name
+ for node in ast.walk(_dependencies_ast())
+ if isinstance(node, ast.ImportFrom) and node.module == "invokeai.backend.architectures"
+ for alias in node.names
+ }
+ assert "conditioning_safe_globals" in imported
+
+
+def test_the_assembled_list_holds_every_conditioning_class_exactly_once() -> None:
+ """The content of what the call site passes: the envelope first, then all thirteen classes."""
+ safe_globals = conditioning_safe_globals()
- safe_globals = [ConditioningFieldData, *conditioning_infos()]
- assert len(safe_globals) == 14
assert safe_globals[0] is ConditioningFieldData
+ assert set(safe_globals[1:]) == set(conditioning_infos())
+ assert len(safe_globals) == 14
assert len(set(safe_globals)) == len(safe_globals), "a class appears twice"
diff --git a/tests/backend/architectures/test_default_settings.py b/tests/backend/architectures/test_default_settings.py
index 68194d909b..9aea4de63a 100644
--- a/tests/backend/architectures/test_default_settings.py
+++ b/tests/backend/architectures/test_default_settings.py
@@ -4,16 +4,20 @@ ERNIE-Image's name-based detection is covered by tests/backend/model_manager/tes
which now runs through this resolver.
"""
+from typing import Any
+
import pytest
from invokeai.backend.architectures import generative_bases, resolve_default_settings
from invokeai.backend.architectures.facets.default_settings import DefaultSettingsFacet
from invokeai.backend.architectures.registry import get
from invokeai.backend.model_manager.taxonomy import (
+ AnyVariant,
BaseModelType,
Flux2VariantType,
FluxVariantType,
Krea2VariantType,
+ WanVariantType,
ZImageVariantType,
)
@@ -33,36 +37,232 @@ def test_every_architecture_declares_defaults() -> None:
assert undeclared == []
-def test_the_refiner_declares_a_canvas_but_no_sampler_settings() -> None:
- """It is a second pass over an SDXL latent, driven by the UI's own refiner parameters."""
- settings = resolve_default_settings(BaseModelType.StableDiffusionXLRefiner)
- assert settings is not None
- assert (settings.width, settings.height) == (1024, 1024)
- assert (settings.steps, settings.cfg_scale) == (None, None)
+_SQUARE_1024 = {"width": 1024, "height": 1024}
+
+# The whole matrix, hand-transcribed from `architectures/defs/` rather than read back out of it.
+# Each row is *every* field its declaration sets — the comparison is against
+# `model_dump(exclude_none=True)` — so a field nobody thought to pin cannot arrive unnoticed
+# either.
+#
+# These numbers are persisted onto a model's config when it is identified and drive the generation
+# sliders from then on, so editing one reaches users without passing through any UI review. This
+# table is what makes such an edit a reviewable diff.
+#
+# Where the values come from:
+#
+# scheduler: mirrors `BASE_GENERATION[base].defaults.scheduler` in webv2's
+# `baseGenerationPolicies.ts` for all fourteen bases that table knows. Which scheduler
+# to prefer is a product decision, not a model-card fact, and mirroring means nothing
+# changes for users when webv2 switches over to these values. MiniMax H3 and the SDXL
+# refiner are absent from that table and declare none — see
+# `test_every_architecture_with_a_scheduler_declares_which_one`.
+# sd-1/2/XL: the classic Stable Diffusion defaults, which every SD generation is built around,
+# each on its native canvas. 2.x is the judgment call: 768 is right for the
+# v-prediction checkpoints and wrong for the 512 `-base` ones, and nothing in the
+# config distinguishes them, so one of the two had to be picked.
+# refiner: a canvas and nothing else. It is a second pass over an SDXL latent, driven by the
+# UI's own refiner parameters, and is never run on its own.
+# sd-3: stable-diffusion-3.5-medium, 40 steps at guidance 4.5. Medium, not Large (28/3.5):
+# there is one `sd-3` row and no variant to tell them apart.
+# cogview4: THUDM/CogView4-6B, 50 steps at guidance 3.5 — true CFG, it takes a negative prompt.
+# flux: `guidance` is the distilled guidance embedding, not CFG, so cfg_scale stays at its
+# floor (1.0, meaning "off") for every FLUX and FLUX.2 variant. schnell is
+# timestep-distilled and ignores guidance entirely. Fill's 30.0 is corroborated
+# in-tree: `flux_denoise.py` warns when guidance drops below 25.0 for a Fill model.
+# dev's card uses 50 steps; 28 is the de-facto standard and what FLUX.2 [dev] declares,
+# so the two stay consistent.
+# ernie: the base model's 50/4.0, and Turbo's 8/1.0 — reached by name hint rather than
+# variant, because the two share an architecture and a config with nothing to probe.
+# z-image: Tongyi-MAI/Z-Image-Turbo, `num_inference_steps=9`, guidance 0 -> cfg_scale 1.0. The
+# undistilled base needs more steps and supports CFG.
+# ideogram-4: cfg_scale 1.0, because the model is CFG-distilled and cannot do CFG at all —
+# `ideogram4_denoise` has no `cfg_scale` input, only `guidance_scale`, and the
+# FeaturesFacet says `negative_prompt: never`. This field previously held 7.0, taken
+# from the main weight in our own PRESETS. That number is the sampler's internal
+# guidance schedule, not a default anyone sets: the node reads `guidance_scale=None` as
+# "use the preset", and webv2 sends nothing unless the user overrides it through
+# Ideogram's own dedicated fields. Declaring 7.0 advertised a CFG default for a model
+# with no CFG. 48 steps is the preset default, V4_QUALITY_48.
+# krea-2: Diffusers' Krea-2 guidance 4.5 uses cond + 4.5 * (cond - uncond), equivalent to
+# InvokeAI's CFG convention at 5.5. Turbo is distilled; cfg_scale's floor is 1.
+DEFAULT_SETTINGS_MATRIX: list[tuple[str, BaseModelType, AnyVariant | None, str | None, dict[str, Any]]] = [
+ (
+ "sd-1",
+ BaseModelType.StableDiffusion1,
+ None,
+ None,
+ {"scheduler": "euler_a", "steps": 30, "cfg_scale": 7.0, "width": 512, "height": 512},
+ ),
+ (
+ "sd-2",
+ BaseModelType.StableDiffusion2,
+ None,
+ None,
+ {"scheduler": "euler_a", "steps": 30, "cfg_scale": 7.0, "width": 768, "height": 768},
+ ),
+ (
+ "sdxl",
+ BaseModelType.StableDiffusionXL,
+ None,
+ None,
+ {"scheduler": "euler_a", "steps": 30, "cfg_scale": 7.0, **_SQUARE_1024},
+ ),
+ ("sdxl-refiner", BaseModelType.StableDiffusionXLRefiner, None, None, {**_SQUARE_1024}),
+ (
+ "sd-3",
+ BaseModelType.StableDiffusion3,
+ None,
+ None,
+ {"scheduler": "euler_a", "steps": 40, "cfg_scale": 4.5, **_SQUARE_1024},
+ ),
+ (
+ "cogview4",
+ BaseModelType.CogView4,
+ None,
+ None,
+ {"scheduler": "euler_a", "steps": 50, "cfg_scale": 3.5, **_SQUARE_1024},
+ ),
+ (
+ "flux-schnell",
+ BaseModelType.Flux,
+ FluxVariantType.Schnell,
+ None,
+ {"scheduler": "euler", "steps": 4, "cfg_scale": 1.0, **_SQUARE_1024},
+ ),
+ (
+ "flux-dev-fill",
+ BaseModelType.Flux,
+ FluxVariantType.DevFill,
+ None,
+ {"scheduler": "euler", "steps": 50, "cfg_scale": 1.0, "guidance": 30.0, **_SQUARE_1024},
+ ),
+ (
+ "flux-dev",
+ BaseModelType.Flux,
+ FluxVariantType.Dev,
+ None,
+ {"scheduler": "euler", "steps": 28, "cfg_scale": 1.0, "guidance": 3.5, **_SQUARE_1024},
+ ),
+ (
+ "flux2-dev",
+ BaseModelType.Flux2,
+ Flux2VariantType.Dev,
+ None,
+ {"scheduler": "euler", "steps": 28, "cfg_scale": 1.0, "guidance": 3.5, **_SQUARE_1024},
+ ),
+ (
+ "flux2-klein-4b-base",
+ BaseModelType.Flux2,
+ Flux2VariantType.Klein4BBase,
+ None,
+ {"scheduler": "euler", "steps": 28, "cfg_scale": 1.0, **_SQUARE_1024},
+ ),
+ (
+ "flux2-klein-9b-base",
+ BaseModelType.Flux2,
+ Flux2VariantType.Klein9BBase,
+ None,
+ {"scheduler": "euler", "steps": 28, "cfg_scale": 1.0, **_SQUARE_1024},
+ ),
+ (
+ "flux2-klein-distilled",
+ BaseModelType.Flux2,
+ None,
+ None,
+ {"scheduler": "euler", "steps": 4, "cfg_scale": 1.0, **_SQUARE_1024},
+ ),
+ (
+ "ernie-image",
+ BaseModelType.ErnieImage,
+ None,
+ None,
+ {"scheduler": "euler", "steps": 50, "cfg_scale": 4.0, **_SQUARE_1024},
+ ),
+ (
+ "ernie-image-turbo",
+ BaseModelType.ErnieImage,
+ None,
+ "ERNIE-Image-Turbo",
+ {"scheduler": "euler", "steps": 8, "cfg_scale": 1.0, **_SQUARE_1024},
+ ),
+ (
+ "qwen-image",
+ BaseModelType.QwenImage,
+ None,
+ None,
+ {"scheduler": "euler_a", "steps": 40, "cfg_scale": 4.0, **_SQUARE_1024},
+ ),
+ (
+ "z-image-base",
+ BaseModelType.ZImage,
+ ZImageVariantType.ZBase,
+ None,
+ {"scheduler": "euler", "steps": 50, "cfg_scale": 4.0, **_SQUARE_1024},
+ ),
+ (
+ "z-image-turbo",
+ BaseModelType.ZImage,
+ None,
+ None,
+ {"scheduler": "euler", "steps": 9, "cfg_scale": 1.0, **_SQUARE_1024},
+ ),
+ (
+ "ideogram-4",
+ BaseModelType.Ideogram4,
+ None,
+ None,
+ {"scheduler": "euler", "steps": 48, "cfg_scale": 1.0, **_SQUARE_1024},
+ ),
+ (
+ "krea-2-base",
+ BaseModelType.Krea2,
+ Krea2VariantType.Base,
+ None,
+ {"scheduler": "euler", "steps": 28, "cfg_scale": 5.5, **_SQUARE_1024},
+ ),
+ (
+ "krea-2-turbo",
+ BaseModelType.Krea2,
+ None,
+ None,
+ {"scheduler": "euler", "steps": 8, "cfg_scale": 1.0, **_SQUARE_1024},
+ ),
+ (
+ "wan-ti2v-5b",
+ BaseModelType.Wan,
+ WanVariantType.TI2V_5B,
+ None,
+ {"scheduler": "euler", "steps": 30, "cfg_scale": 5.0, **_SQUARE_1024},
+ ),
+ (
+ "wan-a14b",
+ BaseModelType.Wan,
+ None,
+ None,
+ {"scheduler": "euler", "steps": 40, "cfg_scale": 4.0, **_SQUARE_1024},
+ ),
+ ("minimax-h3", BaseModelType.MiniMaxH3, None, None, {"steps": 50, "cfg_scale": 1.0, "width": 1344, "height": 768}),
+ ("anima", BaseModelType.Anima, None, None, {"scheduler": "euler", "steps": 35, "cfg_scale": 4.5, **_SQUARE_1024}),
+]
@pytest.mark.parametrize(
- ("variant", "expected"),
- [
- (ZImageVariantType.ZBase, (50, 4.0)),
- (None, (9, 1.0)),
- ],
+ ("base", "variant", "name", "expected"),
+ [pytest.param(*row[1:], id=row[0]) for row in DEFAULT_SETTINGS_MATRIX],
)
-def test_z_image_dispatches_on_variant(variant: ZImageVariantType | None, expected: tuple[int, float]) -> None:
- settings = resolve_default_settings(BaseModelType.ZImage, variant)
- assert settings is not None
- assert (settings.steps, settings.cfg_scale) == expected
+def test_the_resolved_defaults_are_exactly_what_was_declared(
+ base: BaseModelType, variant: AnyVariant | None, name: str | None, expected: dict[str, Any]
+) -> None:
+ settings = resolve_default_settings(base, variant, name)
+ assert settings is not None, base.value
+ assert settings.model_dump(exclude_none=True) == expected
-def test_flux2_has_three_distinct_answers() -> None:
- """[dev] carries guidance, the undistilled Klein bases carry steps, distilled Klein carries neither."""
- dev = resolve_default_settings(BaseModelType.Flux2, Flux2VariantType.Dev)
- klein_base = resolve_default_settings(BaseModelType.Flux2, Flux2VariantType.Klein4BBase)
- klein = resolve_default_settings(BaseModelType.Flux2, None)
- assert dev is not None and klein_base is not None and klein is not None
- assert (dev.steps, dev.guidance) == (28, 3.5)
- assert (klein_base.steps, klein_base.guidance) == (28, None)
- assert (klein.steps, klein.guidance) == (4, None)
+def test_the_matrix_covers_every_architecture() -> None:
+ """A new architecture whose defaults are pinned nowhere is the state this table exists to end,
+ and parametrizing over the table cannot notice its own omission."""
+ covered = {row[1].value for row in DEFAULT_SETTINGS_MATRIX}
+ assert sorted({b.value for b in generative_bases()} - covered) == []
def test_an_unknown_variant_falls_back() -> None:
@@ -88,73 +288,6 @@ def test_a_variant_from_another_architecture_falls_back_rather_than_matching() -
)
-def test_flux1_dispatches_on_variant() -> None:
- """Three genuinely different answers, and `guidance` is not CFG.
-
- FLUX's `guidance` is the distilled guidance embedding, so cfg_scale stays at its floor (1.0,
- meaning "off") for every variant. Fill's 30.0 is corroborated in-tree: `flux_denoise.py` warns
- when guidance drops below 25.0 for a Fill model.
- """
- schnell = resolve_default_settings(BaseModelType.Flux, FluxVariantType.Schnell)
- dev = resolve_default_settings(BaseModelType.Flux, FluxVariantType.Dev)
- fill = resolve_default_settings(BaseModelType.Flux, FluxVariantType.DevFill)
- assert schnell is not None and dev is not None and fill is not None
-
- assert (schnell.steps, schnell.guidance) == (4, None), "schnell is distilled and ignores guidance"
- assert (dev.steps, dev.guidance) == (28, 3.5)
- assert (fill.steps, fill.guidance) == (50, 30.0)
- assert {schnell.cfg_scale, dev.cfg_scale, fill.cfg_scale} == {1.0}, "FLUX never uses CFG"
-
-
-def test_the_researched_values_are_what_the_model_cards_say() -> None:
- """Pinned against their sources, so a later edit has to argue with the citation.
-
- cogview4: THUDM/CogView4-6B, 50 steps at guidance 3.5 (true CFG — it takes a negative prompt).
- sd-3: stable-diffusion-3.5-medium, 40 steps at guidance 4.5. Medium, not Large (28/3.5):
- there is one `sd-3` row and no variant to tell them apart.
- z-image: Tongyi-MAI/Z-Image-Turbo, `num_inference_steps=9`, guidance 0 -> cfg_scale 1.0.
- ideogram: 1.0, because the model is CFG-distilled and cannot do CFG at all -- `ideogram4_denoise`
- has no `cfg_scale` input, only `guidance_scale`, and the FeaturesFacet says
- `negative_prompt: never`. This field previously held 7.0, taken from the main weight in
- our own PRESETS. That number is the sampler's internal guidance schedule, not a default
- anyone sets: the node reads `guidance_scale=None` as "use the preset", and webv2 sends
- nothing unless the user overrides it through Ideogram's own dedicated fields. Declaring
- 7.0 advertised a CFG default for a model that has no CFG.
- """
- expected = {
- BaseModelType.CogView4: (50, 3.5),
- BaseModelType.StableDiffusion3: (40, 4.5),
- BaseModelType.ZImage: (9, 1.0),
- BaseModelType.Ideogram4: (48, 1.0),
- BaseModelType.ErnieImage: (50, 4.0),
- # The classic Stable Diffusion defaults, which every SD generation is built around.
- BaseModelType.StableDiffusion1: (30, 7.0),
- BaseModelType.StableDiffusion2: (30, 7.0),
- BaseModelType.StableDiffusionXL: (30, 7.0),
- }
- for base, (steps, cfg) in expected.items():
- settings = resolve_default_settings(base)
- assert settings is not None, base.value
- assert (settings.steps, settings.cfg_scale) == (steps, cfg), base.value
-
-
-def test_the_sd_family_keeps_its_native_sizes() -> None:
- """Same steps and CFG, three different canvases — 2.x is the judgment call.
-
- 768 is right for the v-prediction checkpoints and wrong for the 512 `-base` ones. Nothing in the
- config distinguishes them, so one of the two had to be picked.
- """
- sizes = {
- BaseModelType.StableDiffusion1: (512, 512),
- BaseModelType.StableDiffusion2: (768, 768),
- BaseModelType.StableDiffusionXL: (1024, 1024),
- }
- for base, (width, height) in sizes.items():
- settings = resolve_default_settings(base)
- assert settings is not None, base.value
- assert (settings.width, settings.height) == (width, height), base.value
-
-
def test_every_architecture_with_a_scheduler_declares_which_one() -> None:
"""The last piece webv2 still hardcodes.
diff --git a/tests/backend/architectures/test_dimension_grid.py b/tests/backend/architectures/test_dimension_grid.py
new file mode 100644
index 0000000000..23f35d6660
--- /dev/null
+++ b/tests/backend/architectures/test_dimension_grid.py
@@ -0,0 +1,119 @@
+"""The dimension grid, where it depends on the variant rather than only on the base.
+
+`FeaturesFacet.dimension_grid` is pinned to a denoise node's `multiple_of` by
+`test_features.py`, which is a field constraint and therefore one number per base. Wan has two: the
+A14B family denoises in the 16-channel space at 8x and takes multiples of 16, TI2V-5B in the
+48-channel Wan2.2 space at 16x and takes multiples of 32, and the transformer's `patch_size=(1, 2,
+2)` doubles both. The second constraint is enforced inside `wan_denoise.invoke()` -- after enqueue
+and after the model has loaded -- so nothing a field-schema gate can see was ever wrong. 1280x720 is
+the failure that motivated this: both multiples of 16, offered by the canvas, and `720 % 32 == 16`.
+"""
+
+import pytest
+
+# `_validate_spatial_dimensions` is the enforcement site: it is what actually refuses an off-grid
+# request. Reading the declaration against it, rather than against a number transcribed here, is the
+# only way this file can fail for a real reason.
+from invokeai.app.invocations.wan.wan_denoise import _validate_spatial_dimensions
+from invokeai.backend.architectures import architecture_capabilities, generative_bases
+from invokeai.backend.architectures.facets.features import FeaturesFacet, NegativePrompt
+from invokeai.backend.architectures.registry import require
+from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelVariantType, WanVariantType
+
+
+def test_wan_declares_the_grid_ti2v_5b_actually_enforces() -> None:
+ """Both directions, so the declaration cannot be a coarser number that merely happens to pass:
+ the declared grid is accepted and half of it -- still a valid A14B size -- is not."""
+ facet = require(BaseModelType.Wan, FeaturesFacet)
+ grid = facet.resolve_dimension_grid(WanVariantType.TI2V_5B)
+ assert grid == 32
+
+ _validate_spatial_dimensions(WanVariantType.TI2V_5B, grid * 40, grid * 22)
+ with pytest.raises(ValueError, match="multiples of 32"):
+ _validate_spatial_dimensions(WanVariantType.TI2V_5B, grid * 40, grid * 22 + grid // 2)
+
+
+def test_the_a14b_variants_keep_the_base_grid() -> None:
+ """A variant the mapping does not name gets `dimension_grid`, which `test_features.py` has
+ already pinned to `wan_denoise`'s own `multiple_of`."""
+ facet = require(BaseModelType.Wan, FeaturesFacet)
+ for variant in (WanVariantType.T2V_A14B, WanVariantType.I2V_A14B):
+ assert facet.resolve_dimension_grid(variant) == facet.dimension_grid == 16
+ _validate_spatial_dimensions(variant, 1280, 720)
+
+
+def test_an_unknown_variant_falls_back_to_the_base_grid() -> None:
+ """A model whose variant could not be identified, or whose variant enum the grid mapping says
+ nothing about, still has to get an answer: the base grid, which is the one the architecture's own
+ denoise node enforces on every request."""
+ for base in generative_bases():
+ facet = require(base, FeaturesFacet)
+ assert facet.resolve_dimension_grid(None) == facet.dimension_grid
+ assert facet.resolve_dimension_grid(ModelVariantType.Normal) == facet.dimension_grid
+
+
+def test_a_none_key_is_refused() -> None:
+ """`DefaultSettingsFacet.by_variant` spells its fallback `None`; this mapping's fallback is
+ `dimension_grid`, so the same habit here would declare a grid that is silently never read."""
+ with pytest.raises(ValueError, match="None key"):
+ FeaturesFacet(
+ negative_prompt=NegativePrompt(visible=True, usage="always"),
+ dimension_grid=16,
+ dimension_grid_by_variant={None: 32},
+ )
+
+
+def test_the_served_table_carries_the_variant_grid() -> None:
+ """A client joins on `(base, variant)` and falls back to `(base, None)`. Without the TI2V-5B row
+ carrying 32, that join hands it 16 and it offers sizes the graph rejects."""
+ rows = {(r.base, r.variant): r for r in architecture_capabilities()}
+
+ assert rows[(BaseModelType.Wan, None)].features.dimension_grid == 16
+ assert rows[(BaseModelType.Wan, "ti2v_5b")].features.dimension_grid == 32
+
+
+def test_a_variant_row_appears_wherever_a_grid_override_is_declared() -> None:
+ """The declaration has to reach the table. A grid an architecture declares for a variant but
+ that no row carries is invisible to the client doing the `(base, variant)` join, which is the
+ only consumer that can act on it."""
+ rows = {(r.base, r.variant): r for r in architecture_capabilities()}
+ missing = []
+ for base in generative_bases():
+ for variant, grid in require(base, FeaturesFacet).dimension_grid_by_variant.items():
+ row = rows.get((base, variant.value))
+ if row is None or row.features.dimension_grid != grid:
+ missing.append(f"{base.value}/{variant.value}: declared {grid}, served {row and row.features}")
+ assert missing == []
+
+
+def test_no_variant_row_repeats_its_base_row() -> None:
+ """A variant row exists to override something. One identical to its base row is noise in a
+ response clients diff, and a sign the emit rule has drifted from what actually differs."""
+ by_base = {r.base: r for r in architecture_capabilities() if r.variant is None}
+ redundant = [
+ f"{r.base.value}/{r.variant}"
+ for r in architecture_capabilities()
+ if r.variant is not None and (r.features, r.defaults) == (by_base[r.base].features, by_base[r.base].defaults)
+ ]
+ assert redundant == []
+
+
+def test_every_variant_row_is_rendered_in_full() -> None:
+ """A variant row overrides its base row rather than patching it, so a client never has to know
+ which fields a variant row may omit. A row emitted for a grid difference alone must still carry
+ the architecture's recommended parameters."""
+ by_base = {r.base: r for r in architecture_capabilities() if r.variant is None}
+ for row in architecture_capabilities():
+ if row.variant is None:
+ continue
+ base_row = by_base[row.base]
+ assert row.modality == base_row.modality
+ assert (row.defaults is None) == (base_row.defaults is None), row.base.value
+
+
+def test_the_variant_rows_of_a_base_stay_sorted() -> None:
+ """The emit set is now a union of two mappings' keys, and an unsorted set iteration would
+ reorder the response between runs -- `str` hashing is randomized per process."""
+ for base in generative_bases():
+ variants = [r.variant for r in architecture_capabilities() if r.base is base and r.variant is not None]
+ assert variants == sorted(variants), base.value
diff --git a/tests/backend/architectures/test_features.py b/tests/backend/architectures/test_features.py
index fe418d0dec..829744f7b3 100644
--- a/tests/backend/architectures/test_features.py
+++ b/tests/backend/architectures/test_features.py
@@ -97,13 +97,21 @@ def test_reference_images_and_the_one_variant_condition() -> None:
def test_regional_guidance_and_its_negative_subset() -> None:
- """Regional negative prompts are a strict subset — only the SD family has them."""
+ """Transcribed from `REGIONAL_GUIDANCE_SUPPORT` in webv2's `addRegionalGuidance.ts`, which is
+ the only place these two facts live today — neither field is in the generated capability
+ contract, so `test_frontend_capability_parity.py` cannot check them.
+
+ Regional negative prompts are a strict subset: only the SD family's `compel` /
+ `sdxl_compel_prompt` path masks both prompt polarities. The FLUX / FLUX.2 / Krea-2 / Z-Image /
+ Anima denoisers mask positive conditioning only — Z-Image and Anima accept a negative list but
+ discard its masks, so a "regional" negative there would act globally and webv2 rejects it.
+ """
regional = {
b.value for b in generative_bases() if (f := get(b, FeaturesFacet)) is not None and f.supports_regional_guidance
}
negative = {b.value for b in generative_bases() if (f := get(b, FeaturesFacet)) is not None and f.regional_negative}
- assert regional == {"sd-1", "sdxl", "flux", "flux2", "krea-2"}
- assert negative == {"sd-1", "sdxl"}
+ assert regional == {"sd-1", "sd-2", "sdxl", "flux", "flux2", "krea-2", "z-image", "anima"}
+ assert negative == {"sd-1", "sd-2", "sdxl"}
assert negative < regional, "a regional negative prompt without regional guidance is meaningless"
diff --git a/tests/backend/architectures/test_frontend_capability_parity.py b/tests/backend/architectures/test_frontend_capability_parity.py
index 685d2a7579..5759ee68dc 100644
--- a/tests/backend/architectures/test_frontend_capability_parity.py
+++ b/tests/backend/architectures/test_frontend_capability_parity.py
@@ -53,12 +53,26 @@ def _declared(base_value: str) -> FeaturesFacet:
def test_the_contract_covers_bases_that_exist() -> None:
- """A base webv2 offers but the registry does not know is a broken generation path, and an empty
- contract would make every other test in this module vacuous."""
- assert BY_BASE, f"{CONTRACT_PATH.name} recorded no bases; regenerate it with `vitest -u`."
+ """A base webv2 offers but the registry does not know is a broken generation path, and a
+ shrunken contract would make every other test in this module vacuous — the per-base checks are
+ parametrized over this file, so a truncated one takes the assertions with it rather than
+ failing.
+
+ 14 is the current length of webv2's `BASE_GENERATION`; a new architecture updates this number
+ and the file in the same commit.
+ """
+ assert len(BY_BASE) == 14, (
+ f"{CONTRACT_PATH.name} records {len(BY_BASE)} bases, not 14; regenerate it with `vitest -u` "
+ f"and update this count if webv2 really gained or dropped an architecture."
+ )
registered = {base.value for base in generative_bases()}
assert sorted(set(BY_BASE) - registered) == []
+ # The other direction is not an error, but it has to be a reviewable line: these two are the
+ # only architectures nothing in this module checks, because webv2 has no generation path for
+ # them. MiniMax H3 is video-first with its own hardcoded schedules, and the SDXL refiner is a
+ # second pass rather than a model you generate with.
+ assert sorted(registered - set(BY_BASE)) == ["minimax-h3", "sdxl-refiner"]
@pytest.mark.parametrize("base_value", sorted(BY_BASE))
diff --git a/tests/backend/architectures/test_registry.py b/tests/backend/architectures/test_registry.py
index 0a7b9151e7..2f1b1150c2 100644
--- a/tests/backend/architectures/test_registry.py
+++ b/tests/backend/architectures/test_registry.py
@@ -30,13 +30,7 @@ class _Mandatory(Facet):
REQUIRED = True
-# `Facet.__init_subclass__` put the three above into the real `Facet.FACET_TYPES` the moment this
-# module was imported, and `validate()` reads that collection to decide what every architecture must
-# declare — so leaving `_Mandatory` in it would make the real registry fail validation for the rest
-# of the session. Undone here rather than in a fixture: the damage is done at import time, which is
-# before any fixture runs.
-for _test_double in (_Colour, _Size, _Mandatory):
- Facet.FACET_TYPES.pop(_test_double, None)
+FACETS_MODULE = "invokeai.backend.architectures.facets"
@pytest.fixture
@@ -46,12 +40,23 @@ def isolated_registry(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
Both have to be reset. `Facet.FACET_TYPES` is class state filled at import time by every facet
in the codebase, so leaving it alone would let a real `REQUIRED` facet leak into `validate()`
here and fail against architectures this test never registered.
+
+ The doubles above go the other way: `Facet.__init_subclass__` added them to the real collection
+ at import time, and nothing here takes them back out, because `validate()` only enforces facets
+ declared under `invokeai.backend.architectures.facets` — which is what
+ `test_a_required_facet_from_elsewhere_is_not_enforced` below pins.
"""
monkeypatch.setattr(registry, "_ARCHITECTURES", {})
monkeypatch.setattr(Facet, "FACET_TYPES", {})
yield
+def _register_every_architecture() -> None:
+ for base in BaseModelType:
+ if base not in registry._NOT_ARCHITECTURES:
+ registry.register(base)
+
+
def test_register_then_get_round_trips(isolated_registry: None) -> None:
registry.register(BaseModelType.Flux, _Colour("blue"), _Size(3))
assert registry.get(BaseModelType.Flux, _Colour) == _Colour("blue")
@@ -72,12 +77,33 @@ def test_facets_of_returns_everything_declared(isolated_registry: None) -> None:
assert set(registry.facets_of(BaseModelType.Flux)) == {_Colour("blue"), _Size(3)}
-def test_registering_twice_raises(isolated_registry: None) -> None:
+def test_registering_a_different_declaration_raises(isolated_registry: None) -> None:
registry.register(BaseModelType.Flux, _Colour("blue"))
with pytest.raises(registry.ArchitectureError, match="already registered"):
registry.register(BaseModelType.Flux, _Colour("red"))
+def test_re_registering_an_identical_declaration_is_a_no_op(isolated_registry: None) -> None:
+ """A `defs/` module re-executed by `importlib.reload`, or by jurigged under `--dev_reload`.
+
+ Without this, a developer's next save on any file under `defs/` crashes the running server with
+ a message blaming a file that is correct.
+ """
+ registry.register(BaseModelType.Flux, _Colour("blue"), _Size(3))
+ registry.register(BaseModelType.Flux, _Colour("blue"), _Size(3))
+
+ assert set(registry.facets_of(BaseModelType.Flux)) == {_Colour("blue"), _Size(3)}
+
+
+def test_re_registering_with_a_facet_dropped_raises(isolated_registry: None) -> None:
+ """The subtler half: same base, same remaining facets, one gone. Still a collision."""
+ registry.register(BaseModelType.Flux, _Colour("blue"), _Size(3))
+ with pytest.raises(registry.ArchitectureError, match="already registered"):
+ registry.register(BaseModelType.Flux, _Colour("blue"))
+
+ assert set(registry.facets_of(BaseModelType.Flux)) == {_Colour("blue"), _Size(3)}, "the first one stands"
+
+
def test_the_same_facet_type_twice_in_one_call_raises(isolated_registry: None) -> None:
with pytest.raises(registry.ArchitectureError, match="more than once"):
registry.register(BaseModelType.Flux, _Colour("blue"), _Colour("red"))
@@ -112,11 +138,16 @@ def test_architecture_error_is_a_value_error() -> None:
assert issubclass(registry.ArchitectureError, ValueError)
-def test_validate_reports_an_undeclared_required_facet(isolated_registry: None) -> None:
- """The negative probe for the boot gate. Without this, `validate()` could be a no-op forever."""
- for base in BaseModelType:
- if base not in registry._NOT_ARCHITECTURES:
- registry.register(base)
+def test_validate_reports_an_undeclared_required_facet(
+ isolated_registry: None, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The negative probe for the boot gate. Without this, `validate()` could be a no-op forever.
+
+ The double has to claim a module inside the facets package, because that is what `validate()`
+ enforces; the test below is the other side of that filter.
+ """
+ _register_every_architecture()
+ monkeypatch.setattr(_Mandatory, "__module__", f"{FACETS_MODULE}.mandatory")
Facet.FACET_TYPES[_Mandatory] = None
with pytest.raises(registry.ArchitectureError) as exc:
@@ -125,6 +156,21 @@ def test_validate_reports_an_undeclared_required_facet(isolated_registry: None)
assert "invokeai/backend/architectures/defs/flux.py" in str(exc.value)
+def test_a_required_facet_from_elsewhere_is_not_enforced(isolated_registry: None) -> None:
+ """A custom-node pack that merely *defines* a REQUIRED facet must not take the app down.
+
+ `Facet.FACET_TYPES` collects every subclass created anywhere in the interpreter, and
+ `load_custom_nodes` swallows a pack's own exceptions — so such a pack would load
+ "successfully" and then fail boot with a wall of errors naming first-party files under `defs/`.
+ `_Mandatory` is defined in this test module, which stands in for exactly that third-party facet.
+ """
+ _register_every_architecture()
+ assert _Mandatory.__module__ == __name__ and not __name__.startswith(FACETS_MODULE)
+ Facet.FACET_TYPES[_Mandatory] = None
+
+ registry.validate()
+
+
def test_validate_reports_an_unregistered_architecture(isolated_registry: None) -> None:
"""Discovery is automatic, so the way to fail is a new enum member with no module under defs/."""
for base in BaseModelType:
diff --git a/tests/backend/flux/test_flow_matching_schedulers.py b/tests/backend/flux/test_flow_matching_schedulers.py
new file mode 100644
index 0000000000..ee0ceb3860
--- /dev/null
+++ b/tests/backend/flux/test_flow_matching_schedulers.py
@@ -0,0 +1,62 @@
+"""Every scheduler a denoise node will accept is one it can actually build.
+
+`FlowMatchLCMScheduler` is imported under `try: ... except ImportError`, so `"lcm"` lands in each
+`*_SCHEDULER_MAP` only when the installed diffusers has it. The `*_SCHEDULER_NAME_VALUES` literals
+accept it unconditionally, and webv2 offers it unconditionally — so on a diffusers without it the
+node validates the request, queues the graph, and raises `KeyError: 'lcm'` out of its
+`MAP[self.scheduler]` lookup partway through generation. The user sees a failed queue item, not a
+rejected setting.
+
+This is the assertion that turns that into a red test on the machine that builds the wheel rather
+than a bug report from whoever installs it. `test_anima_schedulers.py` already covers the opposite
+direction (every map key is in the literal), which catches a scheduler that ships without a type
+but not one whose type ships without the scheduler.
+"""
+
+import typing
+
+import pytest
+
+from invokeai.backend.flux.schedulers import (
+ ANIMA_SCHEDULER_LABELS,
+ ANIMA_SCHEDULER_MAP,
+ ANIMA_SCHEDULER_NAME_VALUES,
+ ERNIE_IMAGE_SCHEDULER_LABELS,
+ ERNIE_IMAGE_SCHEDULER_MAP,
+ ERNIE_IMAGE_SCHEDULER_NAME_VALUES,
+ FLUX_SCHEDULER_LABELS,
+ FLUX_SCHEDULER_MAP,
+ FLUX_SCHEDULER_NAME_VALUES,
+ ZIMAGE_SCHEDULER_LABELS,
+ ZIMAGE_SCHEDULER_MAP,
+ ZIMAGE_SCHEDULER_NAME_VALUES,
+)
+
+SCHEDULER_FAMILIES = [
+ ("flux", FLUX_SCHEDULER_NAME_VALUES, FLUX_SCHEDULER_MAP, FLUX_SCHEDULER_LABELS),
+ ("z-image", ZIMAGE_SCHEDULER_NAME_VALUES, ZIMAGE_SCHEDULER_MAP, ZIMAGE_SCHEDULER_LABELS),
+ ("ernie-image", ERNIE_IMAGE_SCHEDULER_NAME_VALUES, ERNIE_IMAGE_SCHEDULER_MAP, ERNIE_IMAGE_SCHEDULER_LABELS),
+ ("anima", ANIMA_SCHEDULER_NAME_VALUES, ANIMA_SCHEDULER_MAP, ANIMA_SCHEDULER_LABELS),
+]
+
+
+ ("names", "scheduler_map"),
+ [pytest.param(family[1], family[2], id=family[0]) for family in SCHEDULER_FAMILIES],
+)
+def test_every_accepted_scheduler_name_can_be_built(names: object, scheduler_map: dict[str, object]) -> None:
+ unbuildable = sorted(set(typing.get_args(names)) - set(scheduler_map))
+ assert unbuildable == [], (
+ f"accepted by the node's field but absent from its scheduler map: {unbuildable}. "
+ f"The lookup is unguarded, so choosing one fails mid-generation."
+ )
+
+
+ ("names", "labels"),
+ [pytest.param(family[1], family[3], id=family[0]) for family in SCHEDULER_FAMILIES],
+)
+def test_every_accepted_scheduler_name_has_a_label(names: object, labels: dict[str, str]) -> None:
+ """The UI renders the label; a missing one shows the raw key or nothing at all."""
+ unlabelled = sorted(set(typing.get_args(names)) - set(labels))
+ assert unlabelled == []
diff --git a/tests/backend/model_manager/test_starter_models_package.py b/tests/backend/model_manager/test_starter_models_package.py
index 1674a030b3..31d7d6c386 100644
--- a/tests/backend/model_manager/test_starter_models_package.py
+++ b/tests/backend/model_manager/test_starter_models_package.py
@@ -107,7 +107,12 @@ def test_every_defined_model_is_reachable() -> None:
model, which looks like it was never added.
"""
reachable = {id(m) for m in STARTER_MODELS}
- reachable |= {id(m) for models in STARTER_BUNDLES.values() for m in models}
+ # `bundle.models`, not `bundle`: `StarterModelBundle` is a pydantic model, so iterating it
+ # yields ('name', ...) field tuples whose ids belong to nothing. The set stayed correct only
+ # because every bundle entry is today the same object as its STARTER_MODELS row.
+ bundled = {id(m) for bundle in STARTER_BUNDLES.values() for m in bundle.models}
+ assert bundled, "no bundle contributed a model; the reachability set below would be too small"
+ reachable |= bundled
# One pass is enough: dependencies are leaves, and none declares dependencies of its own.
reachable |= {id(d) for m in STARTER_MODELS for d in (m.dependencies or [])}
diff --git a/tests/backend/util/test_module_discovery.py b/tests/backend/util/test_module_discovery.py
index f7f0d560c4..70079f6cb6 100644
--- a/tests/backend/util/test_module_discovery.py
+++ b/tests/backend/util/test_module_discovery.py
@@ -15,16 +15,22 @@ from invokeai.backend.util.module_discovery import discover_modules
@pytest.fixture
def tree(tmp_path: Path) -> Iterator[Path]:
- """A miniature package: one flat module, one in a subpackage, plus things that must be skipped."""
+ """A miniature package: one flat module, one in a subpackage, plus things that must be skipped.
+
+ `assets/` holds no modules and so is none of discovery's business; it is here because the
+ missing-`__init__.py` check must not mistake an ordinary data directory for a broken package.
+ """
root = tmp_path / "synthetic_pkg"
(root / "sub").mkdir(parents=True)
(root / "__pycache__").mkdir()
+ (root / "assets").mkdir()
(root / "__init__.py").write_text("", encoding="utf-8")
(root / "flat.py").write_text("", encoding="utf-8")
(root / "_private.py").write_text("", encoding="utf-8")
(root / "sub" / "__init__.py").write_text("", encoding="utf-8")
(root / "sub" / "nested.py").write_text("", encoding="utf-8")
(root / "__pycache__" / "stale.py").write_text("", encoding="utf-8")
+ (root / "assets" / "palette.json").write_text("{}", encoding="utf-8")
sys.path.insert(0, str(tmp_path))
try:
@@ -52,3 +58,33 @@ def test_reports_a_broken_subpackage(tree: Path) -> None:
(tree / "sub" / "__init__.py").write_text("raise RuntimeError('boom')", encoding="utf-8")
with pytest.raises(ImportError, match="synthetic_pkg.sub"):
discover_modules(tree, "synthetic_pkg.")
+
+
+def test_reports_a_directory_with_no_init(tree: Path) -> None:
+ """`walk_packages` does not descend into one, and does not complain either.
+
+ The result is a module that is simply never imported and a registration that silently never
+ happens — the failure this whole module exists to make impossible.
+ """
+ (tree / "sub_noinit").mkdir()
+ (tree / "sub_noinit" / "orphan.py").write_text("", encoding="utf-8")
+
+ with pytest.raises(ImportError, match="sub_noinit"):
+ discover_modules(tree, "synthetic_pkg.")
+
+
+def test_reports_a_directory_with_no_init_nested_in_a_package(tree: Path) -> None:
+ """The same mistake one level down, where it is easier to make and harder to spot."""
+ (tree / "sub" / "deeper").mkdir()
+ (tree / "sub" / "deeper" / "orphan.py").write_text("", encoding="utf-8")
+
+ with pytest.raises(ImportError, match="sub/deeper"):
+ discover_modules(tree, "synthetic_pkg.")
+
+
+def test_a_directory_holding_no_modules_is_not_reported(tree: Path) -> None:
+ """`assets/` and `__pycache__` have no `__init__.py` either, and neither is a mistake.
+
+ Without this, the check above would fire on every data directory in the repository.
+ """
+ assert discover_modules(tree, "synthetic_pkg.")
diff --git a/tests/test_new_architecture_script.py b/tests/test_new_architecture_script.py
index deaf955c9c..d59f42e81f 100644
--- a/tests/test_new_architecture_script.py
+++ b/tests/test_new_architecture_script.py
@@ -3,9 +3,12 @@
import ast
import sys
from pathlib import Path
+from typing import Any
import pytest
+from invokeai.backend.architectures import registry
+
REPO_ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(REPO_ROOT / "scripts"))
@@ -33,12 +36,28 @@ def test_the_declaration_carries_every_required_facet() -> None:
assert REQUIRED_FACETS <= called, sorted(REQUIRED_FACETS - called)
-def test_the_declaration_is_obviously_unfinished() -> None:
- """It must not look plausible. Someone who runs the scaffolder and forgets to fill it in should
- ship nothing — the placeholder projection is a single black row."""
- source = defs_module("new-model", "NewModel")
- assert source.count("TODO") >= 5
- assert "[0.0, 0.0, 0.0]" in source
+def test_the_generated_declaration_refuses_to_be_imported(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The scaffolder's central claim, executed.
+
+ Its docstring promises the stub "fails loudly at boot until someone fills it in". `validate()`
+ alone does not deliver that — it checks only that the required facets are present, and the stub
+ declares all five with values that pass their own constructors. The all-zero latent projection
+ is what makes the promise true: it raises while the module is being executed, which for a file
+ under `defs/` is during boot.
+
+ The module is executed with `register` replaced, so a stub that ever stopped raising could not
+ pass this by reaching the real registry instead.
+ """
+ registered: list[tuple[Any, ...]] = []
+ monkeypatch.setattr(registry, "register", lambda *args: registered.append(args))
+
+ with pytest.raises(registry.ArchitectureError, match="rgb_factors is all zeros"):
+ exec( # noqa: S102 -- executing the generated module *is* the behaviour under test
+ compile(defs_module("new-model", "NewModel"), "defs/new_model.py", "exec"),
+ {"__name__": "invokeai.backend.architectures.defs.new_model"},
+ )
+
+ assert registered == [], "the stub reached register(), so a boot would have accepted it"
def test_the_slug_convention_matches_the_registry() -> None:
@@ -58,13 +77,16 @@ def test_the_residual_list_is_derived_from_the_tree() -> None:
assert "invokeai/backend/model_manager/configs/main.py" in residual
# No longer dispatching — each of these was a chain the registry absorbed. If one reappears
- # here, a facet has been bypassed.
+ # here, a facet has been bypassed. Checked at threshold=1, not at the reporting threshold: a
+ # reintroduced four-branch `if/elif` in step_callback.py is exactly the regression this guards,
+ # and it would sit under a five-base floor unnoticed.
+ every_module_naming_a_base = dict(derive_residual_edits(REPO_ROOT / "invokeai", threshold=1))
for absorbed in (
"invokeai/app/util/step_callback.py",
"invokeai/app/api/dependencies.py",
"invokeai/app/invocations/ideal_size.py",
):
- assert absorbed not in residual, f"{absorbed} dispatches on base again"
+ assert absorbed not in every_module_naming_a_base, f"{absorbed} dispatches on base again"
def test_the_registry_itself_is_never_listed_as_a_cost() -> None: