Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(architectures): add the facet registry
Alexander Eichhorn1010b1651c48
diff --git a/invokeai/backend/architectures/__init__.py b/invokeai/backend/architectures/__init__.pynew file mode 100644index 0000000000..173996707d--- /dev/null+++ b/invokeai/backend/architectures/__init__.py@@ -0,0 +1,31 @@+"""Facts about model architectures, one file per architecture.++Import this package to use the registry; importing it fills the registry as a side effect. Modules+*inside* the package import `architectures.registry` directly instead — see `defs/__init__.py`.+"""++from invokeai.backend.architectures import defs as defs # noqa: F401 (imported for side effects)+from invokeai.backend.architectures import facets as facets # noqa: F401 (imported for side effects)+from invokeai.backend.architectures.facet import Facet+from invokeai.backend.architectures.registry import (+ ArchitectureError,+ defs_module_path,+ facets_of,+ generative_bases,+ get,+ register,+ require,+ validate,+)++__all__ = [+ "ArchitectureError",+ "Facet",+ "defs_module_path",+ "facets_of",+ "generative_bases",+ "get",+ "register",+ "require",+ "validate",+]diff --git a/invokeai/backend/architectures/defs/__init__.py b/invokeai/backend/architectures/defs/__init__.pynew file mode 100644index 0000000000..d56e1846ca--- /dev/null+++ b/invokeai/backend/architectures/defs/__init__.py@@ -0,0 +1,20 @@+"""One module per model architecture, each calling `registry.register(...)` exactly once.++The modules here are discovered and imported automatically — there is no list to add to. The+filename is the base value with `-` replaced by `_`, which is what `registry.defs_module_path()`+computes, so an error message can name the file to edit without a second table to keep in sync.++Modules here import `architectures.registry` directly and never the `architectures` package. Doing+the latter would ask a partially-initialized package for an attribute, since it is that package's+own import that brings us here.+"""++from importlib import import_module+from pathlib import Path+from types import ModuleType++from invokeai.backend.util.module_discovery import discover_modules++_MODULES: dict[str, ModuleType] = {+ name: import_module(name) for name in discover_modules(Path(__file__).parent, f"{__name__}.")+}diff --git a/invokeai/backend/architectures/defs/anima.py b/invokeai/backend/architectures/defs/anima.pynew file mode 100644index 0000000000..73d4ead201--- /dev/null+++ b/invokeai/backend/architectures/defs/anima.py@@ -0,0 +1,6 @@+"""What the anima architecture declares."""++from invokeai.backend.architectures.registry import register+from invokeai.backend.model_manager.taxonomy import BaseModelType++register(BaseModelType.Anima)diff --git a/invokeai/backend/architectures/defs/cogview4.py b/invokeai/backend/architectures/defs/cogview4.pynew file mode 100644index 0000000000..fd4cc68d19--- /dev/null+++ b/invokeai/backend/architectures/defs/cogview4.py@@ -0,0 +1,6 @@+"""What the cogview4 architecture declares."""++from invokeai.backend.architectures.registry import register+from invokeai.backend.model_manager.taxonomy import BaseModelType++register(BaseModelType.CogView4)diff --git a/invokeai/backend/architectures/defs/ernie_image.py b/invokeai/backend/architectures/defs/ernie_image.pynew file mode 100644index 0000000000..76a023dffa--- /dev/null+++ b/invokeai/backend/architectures/defs/ernie_image.py@@ -0,0 +1,6 @@+"""What the ernie-image architecture declares."""++from invokeai.backend.architectures.registry import register+from invokeai.backend.model_manager.taxonomy import BaseModelType++register(BaseModelType.ErnieImage)diff --git a/invokeai/backend/architectures/defs/flux.py b/invokeai/backend/architectures/defs/flux.pynew file mode 100644index 0000000000..048aeb0f84--- /dev/null+++ b/invokeai/backend/architectures/defs/flux.py@@ -0,0 +1,6 @@+"""What the flux architecture declares."""++from invokeai.backend.architectures.registry import register+from invokeai.backend.model_manager.taxonomy import BaseModelType++register(BaseModelType.Flux)diff --git a/invokeai/backend/architectures/defs/flux2.py b/invokeai/backend/architectures/defs/flux2.pynew file mode 100644index 0000000000..bbc1daa2af--- /dev/null+++ b/invokeai/backend/architectures/defs/flux2.py@@ -0,0 +1,6 @@+"""What the flux2 architecture declares."""++from invokeai.backend.architectures.registry import register+from invokeai.backend.model_manager.taxonomy import BaseModelType++register(BaseModelType.Flux2)diff --git a/invokeai/backend/architectures/defs/ideogram_4.py b/invokeai/backend/architectures/defs/ideogram_4.pynew file mode 100644index 0000000000..8d48d9fb5b--- /dev/null+++ b/invokeai/backend/architectures/defs/ideogram_4.py@@ -0,0 +1,6 @@+"""What the ideogram-4 architecture declares."""++from invokeai.backend.architectures.registry import register+from invokeai.backend.model_manager.taxonomy import BaseModelType++register(BaseModelType.Ideogram4)diff --git a/invokeai/backend/architectures/defs/krea_2.py b/invokeai/backend/architectures/defs/krea_2.pynew file mode 100644index 0000000000..7eeaca2c04--- /dev/null+++ b/invokeai/backend/architectures/defs/krea_2.py@@ -0,0 +1,6 @@+"""What the krea-2 architecture declares."""++from invokeai.backend.architectures.registry import register+from invokeai.backend.model_manager.taxonomy import BaseModelType++register(BaseModelType.Krea2)diff --git a/invokeai/backend/architectures/defs/minimax_h3.py b/invokeai/backend/architectures/defs/minimax_h3.pynew file mode 100644index 0000000000..3c3cb0fd19--- /dev/null+++ b/invokeai/backend/architectures/defs/minimax_h3.py@@ -0,0 +1,6 @@+"""What the minimax-h3 architecture declares."""++from invokeai.backend.architectures.registry import register+from invokeai.backend.model_manager.taxonomy import BaseModelType++register(BaseModelType.MiniMaxH3)diff --git a/invokeai/backend/architectures/defs/qwen_image.py b/invokeai/backend/architectures/defs/qwen_image.pynew file mode 100644index 0000000000..cf4714df77--- /dev/null+++ b/invokeai/backend/architectures/defs/qwen_image.py@@ -0,0 +1,6 @@+"""What the qwen-image architecture declares."""++from invokeai.backend.architectures.registry import register+from invokeai.backend.model_manager.taxonomy import BaseModelType++register(BaseModelType.QwenImage)diff --git a/invokeai/backend/architectures/defs/sd_1.py b/invokeai/backend/architectures/defs/sd_1.pynew file mode 100644index 0000000000..022d0385f7--- /dev/null+++ b/invokeai/backend/architectures/defs/sd_1.py@@ -0,0 +1,6 @@+"""What the sd-1 architecture declares."""++from invokeai.backend.architectures.registry import register+from invokeai.backend.model_manager.taxonomy import BaseModelType++register(BaseModelType.StableDiffusion1)diff --git a/invokeai/backend/architectures/defs/sd_2.py b/invokeai/backend/architectures/defs/sd_2.pynew file mode 100644index 0000000000..8e5f1a1cb2--- /dev/null+++ b/invokeai/backend/architectures/defs/sd_2.py@@ -0,0 +1,6 @@+"""What the sd-2 architecture declares."""++from invokeai.backend.architectures.registry import register+from invokeai.backend.model_manager.taxonomy import BaseModelType++register(BaseModelType.StableDiffusion2)diff --git a/invokeai/backend/architectures/defs/sd_3.py b/invokeai/backend/architectures/defs/sd_3.pynew file mode 100644index 0000000000..2104688303--- /dev/null+++ b/invokeai/backend/architectures/defs/sd_3.py@@ -0,0 +1,6 @@+"""What the sd-3 architecture declares."""++from invokeai.backend.architectures.registry import register+from invokeai.backend.model_manager.taxonomy import BaseModelType++register(BaseModelType.StableDiffusion3)diff --git a/invokeai/backend/architectures/defs/sdxl.py b/invokeai/backend/architectures/defs/sdxl.pynew file mode 100644index 0000000000..f6ad623422--- /dev/null+++ b/invokeai/backend/architectures/defs/sdxl.py@@ -0,0 +1,6 @@+"""What the sdxl architecture declares."""++from invokeai.backend.architectures.registry import register+from invokeai.backend.model_manager.taxonomy import BaseModelType++register(BaseModelType.StableDiffusionXL)diff --git a/invokeai/backend/architectures/defs/sdxl_refiner.py b/invokeai/backend/architectures/defs/sdxl_refiner.pynew file mode 100644index 0000000000..0b37e5eda4--- /dev/null+++ b/invokeai/backend/architectures/defs/sdxl_refiner.py@@ -0,0 +1,6 @@+"""What the sdxl-refiner architecture declares."""++from invokeai.backend.architectures.registry import register+from invokeai.backend.model_manager.taxonomy import BaseModelType++register(BaseModelType.StableDiffusionXLRefiner)diff --git a/invokeai/backend/architectures/defs/wan.py b/invokeai/backend/architectures/defs/wan.pynew file mode 100644index 0000000000..5b90c87db9--- /dev/null+++ b/invokeai/backend/architectures/defs/wan.py@@ -0,0 +1,6 @@+"""What the wan architecture declares."""++from invokeai.backend.architectures.registry import register+from invokeai.backend.model_manager.taxonomy import BaseModelType++register(BaseModelType.Wan)diff --git a/invokeai/backend/architectures/defs/z_image.py b/invokeai/backend/architectures/defs/z_image.pynew file mode 100644index 0000000000..8bd63d0814--- /dev/null+++ b/invokeai/backend/architectures/defs/z_image.py@@ -0,0 +1,6 @@+"""What the z-image architecture declares."""++from invokeai.backend.architectures.registry import register+from invokeai.backend.model_manager.taxonomy import BaseModelType++register(BaseModelType.ZImage)diff --git a/invokeai/backend/architectures/facet.py b/invokeai/backend/architectures/facet.pynew file mode 100644index 0000000000..cc6c114035--- /dev/null+++ b/invokeai/backend/architectures/facet.py@@ -0,0 +1,33 @@+"""The marker base class for architecture facets.++Deliberately its own module rather than part of `registry`: `facets/*` needs both, and putting+`Facet` in `registry` would make every facet module import the registry it is registered into.+"""++from typing import Any, ClassVar+++class Facet:+ """One immutable, self-contained fact about a model architecture.++ Concrete facets are frozen dataclasses carrying plain data — never services, never model+ instances. They are keyed in the registry by their *exact* runtime type, so a facet class must+ not be subclassed by another facet class.++ Subclasses are collected at class-creation time so `registry.validate()` can check every+ registered architecture against the facets that declare themselves required. This mirrors+ `Config_Base.CONFIG_CLASSES`, but uses a dict rather than a set: a set iterates in a+ non-deterministic order, which has already produced a real bug in this codebase (see+ tests/backend/model_manager/configs/test_wan_lora_probe_independence.py). Error messages built+ by walking this collection would otherwise reorder between runs.+ """++ REQUIRED: ClassVar[bool] = False+ """Whether every architecture must declare this facet. Checked at boot, not at first use."""++ FACET_TYPES: ClassVar[dict[type["Facet"], None]] = {}+ """Every concrete facet class, in definition order. A dict used as an ordered set."""++ def __init_subclass__(cls, **kwargs: Any) -> None:+ super().__init_subclass__(**kwargs)+ Facet.FACET_TYPES[cls] = Nonediff --git a/invokeai/backend/architectures/facets/__init__.py b/invokeai/backend/architectures/facets/__init__.pynew file mode 100644index 0000000000..96d26bb417--- /dev/null+++ b/invokeai/backend/architectures/facets/__init__.py@@ -0,0 +1,18 @@+"""Concrete facets — the kinds of fact an architecture can declare.++Imported automatically, like `defs/`, and for a sharper reason than symmetry: `validate()` checks+each architecture against the facets that marked themselves `REQUIRED`, and it learns which those+are from `Facet.FACET_TYPES`, which is filled at class-creation time. A facet module that nothing+happened to import would be absent from that collection, so its requirement would go unchecked —+silently, and precisely for a facet so new that no architecture declares it yet.+"""++from importlib import import_module+from pathlib import Path+from types import ModuleType++from invokeai.backend.util.module_discovery import discover_modules++_MODULES: dict[str, ModuleType] = {+ name: import_module(name) for name in discover_modules(Path(__file__).parent, f"{__name__}.")+}diff --git a/invokeai/backend/architectures/registry.py b/invokeai/backend/architectures/registry.pynew file mode 100644index 0000000000..5392674d89--- /dev/null+++ b/invokeai/backend/architectures/registry.py@@ -0,0 +1,154 @@+"""The architecture registry: which facets each `BaseModelType` declares.++Adding a model architecture means editing a long tail of core files — a `step_callback` branch, a+`safe_globals` entry, a variant-enum lookup — and forgetting one of them fails at *generation* time+rather than at boot. The registry moves those facts next to each other, in one file per+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.+"""++from typing import Final, TypeVar++from invokeai.backend.architectures.facet import Facet+from invokeai.backend.model_manager.taxonomy import BaseModelType++FacetT = TypeVar("FacetT", bound=Facet)++_ARCHITECTURES: Final[dict[BaseModelType, dict[type[Facet], Facet]]] = {}++_NOT_ARCHITECTURES: Final = frozenset(+ {+ # A fallback for models with no architecture association at all (CLIP, and the like).+ BaseModelType.Any,+ # Not an architecture but a hosting mode: the model runs at an external provider.+ BaseModelType.External,+ # Identification failed. Nothing can be declared about it by definition.+ BaseModelType.Unknown,+ }+)+"""The `BaseModelType` members that are not architectures. The single definition of that set: both+`register()` and `validate()` read it, so there is no second list to keep in sync."""++_PACKAGE = "invokeai/backend/architectures"+++class ArchitectureError(ValueError):+ """Raised for a missing or malformed architecture declaration.++ Subclasses `ValueError` deliberately: it replaces `raise ValueError(f"Unsupported base model:+ ...")` at the call sites it takes over, so existing `except ValueError` handlers keep behaving+ exactly as they did.+ """+++def defs_module_path(base: BaseModelType) -> str:+ """The file a contributor has to edit to change what `base` declares.++ Derived from `base.value` — the one identifier that cannot change, because it is persisted in+ the model database — rather than read from a second table that could disagree with reality.+ """+ return f"{_PACKAGE}/defs/{base.value.replace('-', '_')}.py"+++def register(base: BaseModelType, *facets: Facet) -> None:+ """Declare what `base` is. Called once per architecture, from its own module under `defs/`."""+ 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:+ facet_type = type(facet)+ if facet_type in by_type:+ raise ArchitectureError(+ f"Architecture '{base.value}' declares {facet_type.__name__} more than once in the "+ f"same register() call. See {defs_module_path(base)}."+ )+ by_type[facet_type] = facet+ _ARCHITECTURES[base] = by_type+++def get(base: BaseModelType, facet_type: type[FacetT]) -> FacetT | None:+ """The facet of that type declared by `base`, or None. Use `require` unless None is meaningful."""+ facet = _ARCHITECTURES.get(base, {}).get(facet_type)+ # `isinstance` narrows `Facet | None` to `FacetT`. The registry keys by exact runtime type, so a+ # hit always passes; the check is here to satisfy the type checker without a cast.+ return facet if isinstance(facet, facet_type) else None+++def require(base: BaseModelType, facet_type: type[FacetT]) -> FacetT:+ """The facet of that type declared by `base`. Raises, naming the file to edit, if it is missing.++ The message is the point of this function. It is read by someone whose new architecture just+ failed mid-generation, and it has to say which file to open — not merely which base was+ unsupported.+ """+ facet = get(base, facet_type)+ if facet is not None:+ return facet+ if base not in _ARCHITECTURES:+ raise ArchitectureError(+ f"Architecture '{base.value}' is not registered, so it cannot declare "+ f"{facet_type.__name__}. Create {defs_module_path(base)} with a "+ f"`register(BaseModelType.{base.name}, {facet_type.__name__}(...))` call. It is picked "+ f"up automatically; there is no import list to edit."+ )+ raise ArchitectureError(+ f"Architecture '{base.value}' does not declare {facet_type.__name__}. Add "+ f"{facet_type.__name__}(...) to the `register(...)` call in {defs_module_path(base)}."+ )+++def generative_bases() -> frozenset[BaseModelType]:+ """Every registered architecture."""+ return frozenset(_ARCHITECTURES)+++def facets_of(base: BaseModelType) -> tuple[Facet, ...]:+ """Everything `base` declares. For diagnostics and tests, not for dispatch."""+ return tuple(_ARCHITECTURES.get(base, {}).values())+++def validate() -> None:+ """Check the registry is complete. Called at boot; raises rather than warns.++ Two things are checked, and both are boot errors rather than CI-only assertions because the+ whole point is that an incompletely declared architecture cannot start the app:++ 1. Every `BaseModelType` that is not a sentinel has a module under `defs/`. Discovery is+ 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.+ """+ missing_bases = sorted(+ base.value for base in BaseModelType if base not in _NOT_ARCHITECTURES and base not in _ARCHITECTURES+ )+ if missing_bases:+ raise ArchitectureError(+ "These architectures are not registered: "+ + ", ".join(f"'{b}'" for b in missing_bases)+ + ". Each needs a module under "+ + f"{_PACKAGE}/defs/ calling `register(...)`; the filename is the base value with "+ + "'-' replaced by '_'."+ )++ required = [facet_type for facet_type in Facet.FACET_TYPES if facet_type.REQUIRED]+ 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)+ for facet_type in required+ if facet_type not in _ARCHITECTURES[base]+ ]+ if problems:+ raise ArchitectureError("Incomplete architecture declarations:\n " + "\n ".join(problems))