Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(architectures): pin the latent space per base, and bound guidance from the node
Alexander Eichhorn70c852e8964a
diff --git a/.github/workflows/python-tests.yml b/.github/workflows/python-tests.ymlindex a0da6f4be7..8e58e36e00 100644--- a/.github/workflows/python-tests.yml+++ b/.github/workflows/python-tests.yml@@ -106,6 +106,9 @@ jobs:# Cross-stack generation contracts: the frontend writes these, Python validates them# against the invocation and architecture registries. A frontend-only change that# regenerates one would otherwise pass vitest while skipping the backend half.+ # `__fixtures__/` does not exist yet -- it arrives with the graph-builder fixtures.+ # A pattern matching nothing costs nothing here, and listing it now means the branch+ # that adds the directory does not also have to remember to add this line.- 'invokeai/frontend/webv2/src/features/generation/core/__snapshots__/**'- 'invokeai/frontend/webv2/src/features/generation/core/__fixtures__/**'- 'tests/**'diff --git a/docs/src/content/docs/contributing/new-model-integration.mdx b/docs/src/content/docs/contributing/new-model-integration.mdxindex b425dfac62..9f41e616fa 100644--- a/docs/src/content/docs/contributing/new-model-integration.mdx+++ b/docs/src/content/docs/contributing/new-model-integration.mdx@@ -81,7 +81,7 @@ exists to prevent.These live in the architecture's own declaration, keyed by variant. `None` is the fallback fora model whose variant is not listed.- ```python title="invokeai/backend/architectures/defs/new_model.py"+ ```python title="invokeai/backend/architectures/defs/newmodel.py"register(BaseModelType.NewModel,...,@@ -99,7 +99,8 @@ exists to prevent.- [ ] Extend `BaseModelType` enum (`taxonomy.py`)- [ ] Create variant enum if needed (`taxonomy.py`)- [ ] Update `AnyVariant` union (`taxonomy.py`)-- [ ] Declare default settings in `DefaultSettingsFacet` (`architectures/defs/<base>.py`)+- [ ] Create `architectures/defs/<base>.py` with a `register(...)` call — `validate()` refuses to boot without it+- [ ] Declare default settings in its `DefaultSettingsFacet`:::---@@ -1033,9 +1034,16 @@ const recallNewmodelEncoderModel = async (metadata: CoreMetadata) => {## 10. Starter Models-To allow users to easily download your model from the Model Manager UI, add it to the starter models list.+To allow users to easily download your model from the Model Manager UI, add it to the starter models catalogue.++The catalogue is a package, one module per architecture. Define the models in your own module —+`types.py` holds `StarterModel` itself, and `common.py` holds the encoders and upscalers that+several architectures share, so import an existing dependency from there rather than declaring a+second copy of it.++```python title="invokeai/backend/model_manager/starter_models/[newmodel].py"+from invokeai.backend.model_manager.starter_models.types import StarterModel-```python title="invokeai/backend/model_manager/starter_models.py"# Main Modelnewmodel_main = StarterModel(name="NewModel Main",@@ -1072,8 +1080,20 @@ newmodel_fp8 = StarterModel(type=ModelType.Main,dependencies=[newmodel_vae, newmodel_encoder], # Dependencies!)+```++Then list them in the package's `__init__.py`. `STARTER_MODELS` is a curated order — it is what the+install dialog shows, in the sequence someone chose, and nothing could reconstruct that order if it+were derived — so insert where the models belong rather than appending.++```python title="invokeai/backend/model_manager/starter_models/__init__.py"+from invokeai.backend.model_manager.starter_models.newmodel import (+ newmodel_encoder,+ newmodel_fp8,+ newmodel_main,+ newmodel_vae,+)-# Add to STARTER_MODELS list:STARTER_MODELS: list[StarterModel] = [# ... existing modelsnewmodel_main,@@ -1084,12 +1104,13 @@ STARTER_MODELS: list[StarterModel] = [```:::tip[Checklist: Starter Models]{icon="approve-check"}+- [ ] Create `starter_models/[newmodel].py`- [ ] Define main model StarterModel- [ ] Define VAE StarterModel if separate-- [ ] Define text encoder StarterModel if separate+- [ ] Define text encoder StarterModel if separate, or reuse one from `starter_models/common.py`- [ ] Define quantized variants (FP8, GGUF, etc.)- [ ] Set dependencies correctly-- [ ] Add to `STARTER_MODELS` list+- [ ] Import them in `starter_models/__init__.py` and place them in `STARTER_MODELS`:::---@@ -1229,6 +1250,7 @@ For a **minimal txt2img integration**, the following files are required:- app/invocations- metadata.py- `[newmodel]`+ - `__init__.py` required, or none of this package's nodes are discovered- `[newmodel]_model_loader.py`- `[newmodel]_denoise.py`- text_encoder@@ -1236,6 +1258,8 @@ For a **minimal txt2img integration**, the following files are required:- vae- `[newmodel]_vae_decode.py`- backend+ - architectures/defs+ - `[newmodel].py` the architecture's declaration; `validate()` refuses to boot without it- model_manager- taxonomy.py- configsdiff --git a/docs/src/content/docs/development/Guides/models.mdx b/docs/src/content/docs/development/Guides/models.mdxindex b6ded10087..61c65c0819 100644--- a/docs/src/content/docs/development/Guides/models.mdx+++ b/docs/src/content/docs/development/Guides/models.mdx@@ -54,27 +54,35 @@ The first step is to declare your model in the system's taxonomy and provide reaVariantB = "variant_b"```-3. **Define Default Settings**+3. **Declare the Architecture**- Provide default generation parameters (steps, CFG scale, etc.) for the UI to use when this model is selected.+ Every `BaseModelType` that is not a sentinel needs a module under+ `invokeai/backend/architectures/defs/`, named after the base value with `-` replaced by `_`. It+ is picked up automatically — there is no import list — but `registry.validate()` runs at boot and+ refuses to start when the file is missing or when it omits a required facet, naming the file.- These live in the architecture's own declaration, keyed by variant. `None` is the fallback for- a model whose variant is not listed.+ Default generation parameters live in this declaration, keyed by variant. `None` is the fallback+ for a model whose variant is not listed.- ```python title="invokeai/backend/architectures/defs/new_model.py"+ ```python title="invokeai/backend/architectures/defs/newmodel.py"register(BaseModelType.NewModel,...,DefaultSettingsFacet({None: MainModelDefaultSettings(steps=20, cfg_scale=7.0)}),)```++ `python scripts/new_architecture.py --base newmodel --name NewModel --write` generates this file+ with every required facet present but deliberately wrong, so it fails at boot until each value is+ filled in. It also prints the files it cannot generate, derived from the tree on each run.</Steps>:::tip[Checklist: Taxonomy]{icon="approve-check"}- [ ] Extend `BaseModelType` enum in `taxonomy.py`- [ ] Create variant enum if needed in `taxonomy.py`- [ ] Update `AnyVariant` union in `taxonomy.py`- - [ ] Declare default settings in `DefaultSettingsFacet` in `architectures/defs/<base>.py`+ - [ ] Create `architectures/defs/<base>.py` with a `register(...)` call — the app will not boot without it+ - [ ] Declare default settings in its `DefaultSettingsFacet`:::---@@ -277,12 +285,24 @@ This is where the actual mathematical implementation of the model lives.Invocations expose your PyTorch functions as isolated execution nodes in InvokeAI's graph.+:::note[Where node files go]+Node modules live in `invokeai/app/invocations/[newmodel]/`, one package per architecture. Three+kinds of node are grouped by role instead, because they are shared across architectures rather than+owned by one: VAE nodes go in `invocations/vae/`, text encoders in `invocations/text_encoder/`, and+PiD decode/upscale in `invocations/pid/`. Generic nodes — noise, primitives, image ops, metadata —+stay at the top level.++Keep the architecture prefix on the filename (`newmodel_denoise.py`) even inside `newmodel/`. The+package is discovered automatically, but it needs an `__init__.py`: a directory without one is not+a package, and every node in it would simply not exist at runtime.+:::+<Steps>1. **Model Loader Invocation**Loads the components (Transformer, VAE, etc.) and provides them to downstream nodes.- ```python title="invokeai/app/invocations/[newmodel]_model_loader.py"+ ```python title="invokeai/app/invocations/[newmodel]/[newmodel]_model_loader.py"@invocation("newmodel_model_loader", title="NewModel Loader", category="model_loader")class NewModelModelLoaderInvocation(BaseInvocation):model: ModelIdentifierField = InputField(description="Main model")@@ -297,7 +317,7 @@ Invocations expose your PyTorch functions as isolated execution nodes in InvokeATokenizes the prompt and runs the text encoder(s).- ```python title="invokeai/app/invocations/[newmodel]_text_encoder.py"+ ```python title="invokeai/app/invocations/text_encoder/[newmodel]_text_encoder.py"@invocation("newmodel_text_encode", title="NewModel Text Encoder", category="conditioning")class NewModelTextEncoderInvocation(BaseInvocation):prompt: str = InputField()@@ -315,7 +335,7 @@ Invocations expose your PyTorch functions as isolated execution nodes in InvokeAWraps the `denoise` loop you wrote in the previous section.- ```python title="invokeai/app/invocations/[newmodel]_denoise.py"+ ```python title="invokeai/app/invocations/[newmodel]/[newmodel]_denoise.py"@invocation("newmodel_denoise", title="NewModel Denoise", category="latents")class NewModelDenoiseInvocation(BaseInvocation):latents: LatentsField | None = InputField(default=None)@@ -341,11 +361,12 @@ Invocations expose your PyTorch functions as isolated execution nodes in InvokeA:::tip[Checklist: Invocations]{icon="approve-check"}- [ ] Define output classes (e.g., `NewModelLoaderOutput`)- - [ ] Model loader invocation (`[newmodel]_model_loader.py`)- - [ ] Text encoder invocation (`[newmodel]_text_encoder.py`)- - [ ] Denoise invocation (`[newmodel]_denoise.py`)+ - [ ] Model loader invocation (`[newmodel]/[newmodel]_model_loader.py`)+ - [ ] Text encoder invocation (`text_encoder/[newmodel]_text_encoder.py`)+ - [ ] Denoise invocation (`[newmodel]/[newmodel]_denoise.py`)- [ ] Extend the standard `noise` invocation if the architecture supports external noise- - [ ] VAE encode/decode invocations (`[newmodel]_vae_encode.py`, `[newmodel]_vae_decode.py`)+ - [ ] VAE encode/decode invocations (`vae/[newmodel]_vae_encode.py`, `vae/[newmodel]_vae_decode.py`)+ - [ ] `__init__.py` in `invocations/[newmodel]/`, or none of its nodes are discovered:::---@@ -489,21 +510,26 @@ Finally, add any custom UI controls (like a specific scheduler dropdown) and manDepending on the model, you may want to support additional features.### ControlNet Support-Requires backend configuration (`configs/controlnet.py`), a custom invocation (`[newmodel]_controlnet.py`), and frontend graph integration (`addControlNets`).+Requires backend configuration (`configs/controlnet.py`), a custom invocation (`[newmodel]/[newmodel]_controlnet.py`), and frontend graph integration (`addControlNets`).### LoRA SupportRequires defining a LoRA config (`configs/lora.py`), updating the model loader to pass LoRA fields, and wiring `addLoRAs` in the frontend graph builder.### IP-Adapter-Requires a custom invocation for image prompting (`[newmodel]_ip_adapter.py`) and frontend integration via `addIPAdapters`.+Requires a custom invocation for image prompting (`[newmodel]/[newmodel]_ip_adapter.py`) and frontend integration via `addIPAdapters`.---## 9. Starter Models-To allow users to easily download your model from the Model Manager UI, add it to the starter models list.+To allow users to easily download your model from the Model Manager UI, add it to the starter models catalogue.++The catalogue is a package: define the models in your own module, then list them in the package's+`__init__.py`.++```python title="invokeai/backend/model_manager/starter_models/[newmodel].py"+from invokeai.backend.model_manager.starter_models.types import StarterModel-```python title="invokeai/backend/model_manager/starter_models.py"newmodel_main = StarterModel(name="NewModel Main",base=BaseModelType.NewModel,@@ -511,15 +537,26 @@ newmodel_main = StarterModel(description="NewModel main transformer.",type=ModelType.Main,)+```++`STARTER_MODELS` is a curated order — it is what the install dialog shows, in the sequence someone+chose — so insert where the model belongs rather than appending.++```python title="invokeai/backend/model_manager/starter_models/__init__.py"+from invokeai.backend.model_manager.starter_models.newmodel import newmodel_main-STARTER_MODELS.append(newmodel_main)+STARTER_MODELS: list[StarterModel] = [+ # ... existing models+ newmodel_main,+]```:::tip[Checklist: Starter Models]{icon="approve-check"}+- [ ] Create `starter_models/[newmodel].py`- [ ] Define main model StarterModel-- [ ] Define VAE/Encoder StarterModels if separate+- [ ] Define VAE/Encoder StarterModels if separate — shared ones live in `starter_models/common.py`- [ ] Set dependencies correctly if required-- [ ] Add to `STARTER_MODELS` list+- [ ] Import and place them in `STARTER_MODELS` in `starter_models/__init__.py`:::---@@ -532,11 +569,17 @@ A complete minimal `txt2img` integration touches the following areas:- invokeai- app/invocations- metadata.py- - `[newmodel]_model_loader.py`- - `[newmodel]_text_encoder.py`- - `[newmodel]_denoise.py`- - `[newmodel]_vae_decode.py`+ - `[newmodel]`+ - `__init__.py` required, or none of this package's nodes are discovered+ - `[newmodel]_model_loader.py`+ - `[newmodel]_denoise.py`+ - text_encoder+ - `[newmodel]_text_encoder.py`+ - vae+ - `[newmodel]_vae_decode.py`- backend+ - architectures/defs+ - `[newmodel].py` the architecture's declaration; the app refuses to boot without it- model_manager- taxonomy.py- configs@@ -544,7 +587,9 @@ A complete minimal `txt2img` integration touches the following areas:- factory.py- load/model_loaders- `[newmodel].py`- - starter_models.py+ - starter_models+ - `[newmodel].py`+ - `__init__.py` import the models here and place them in `STARTER_MODELS`- `[newmodel]`- sampling_utils.py- denoise.pydiff --git a/invokeai/app/invocations/ideal_size.py b/invokeai/app/invocations/ideal_size.pyindex 4e20a1a09d..caa81c9b8a 100644--- a/invokeai/app/invocations/ideal_size.py+++ b/invokeai/app/invocations/ideal_size.py@@ -23,10 +23,15 @@ class IdealSizeOutput(BaseInvocationOutput):@invocation("ideal_size",- title="Ideal Size - SD1.5, SDXL",+ # No architecture suffix: the node reads what the architecture declares, so it now answers for+ # every registered one rather than for the six the old if/elif named.+ title="Ideal Size",tags=["latents", "math", "ideal_size"],category="latents",- version="1.0.6",+ # Minor, not patch: the fields are unchanged, so existing workflows still load, but the answer+ # moved. FLUX, FLUX.2 and SD3 are trimmed to their declared 16 rather than to a hardcoded 8,+ # and every architecture outside the six the old if/elif named returns a size where it raised.+ version="1.1.0",)class IdealSizeInvocation(BaseInvocation):"""Calculates the ideal size for generation to avoid duplication"""diff --git a/invokeai/backend/architectures/capabilities.py b/invokeai/backend/architectures/capabilities.pyindex cd8d999d88..f052d0f3fa 100644--- a/invokeai/backend/architectures/capabilities.py+++ b/invokeai/backend/architectures/capabilities.py@@ -60,6 +60,13 @@ class ArchitectureFeatures(BaseModel):)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'.")+ guidance_min: float = Field(+ description="Lowest guidance value the denoise node accepts; a smaller one fails at enqueue."+ )+ guidance_max: float | None = Field(+ default=None,+ description="Highest guidance value the denoise node accepts; null means it enforces no ceiling.",+ )scheduler_set: SchedulerSet | None = Field(default=None, description="Which scheduler family to offer; null means no choice.")@@ -109,6 +116,8 @@ def _features_of(dimension_grid=facet.resolve_dimension_grid(variant),spatial_compression=latent_space.resolve_variant(variant).spatial_compression,guidance_label=facet.guidance_label,+ guidance_min=facet.guidance_min,+ guidance_max=facet.guidance_max,scheduler_set=facet.scheduler_set,scheduler_applies_to_graph=facet.scheduler_applies_to_graph,control_kinds=sorted(facet.control_kinds),diff --git a/invokeai/backend/architectures/defs/anima.py b/invokeai/backend/architectures/defs/anima.pyindex 3051fb7be6..220f6f8940 100644--- a/invokeai/backend/architectures/defs/anima.py+++ b/invokeai/backend/architectures/defs/anima.py@@ -23,6 +23,8 @@ register(negative_prompt=NegativePrompt(visible=True, usage="cfg-gated"),dimension_grid=8,guidance_label="CFG",+ # anima_denoise.guidance_scale is ge=1.0; 1.0 is CFG off.+ guidance_min=1.0,scheduler_set="anima",scheduler_applies_to_graph=True,# Positive conditioning only, for the same reason as Z-Image: the negative list is accepteddiff --git a/invokeai/backend/architectures/defs/ernie_image.py b/invokeai/backend/architectures/defs/ernie_image.pyindex 42d1291810..db58da7b22 100644--- a/invokeai/backend/architectures/defs/ernie_image.py+++ b/invokeai/backend/architectures/defs/ernie_image.py@@ -34,6 +34,8 @@ register(negative_prompt=NegativePrompt(visible=True, usage="cfg-gated"),dimension_grid=16,guidance_label="CFG",+ # ernie_image_denoise.guidance_scale is ge=1.0; 1.0 is CFG off.+ guidance_min=1.0,scheduler_set="flow",# ernie_image_denoise takes the scheduler as an input, so the graph builder passes the# user's choice through rather than letting the node pick.diff --git a/invokeai/backend/architectures/defs/flux2.py b/invokeai/backend/architectures/defs/flux2.pyindex 4066287e19..4f3fd5ea69 100644--- a/invokeai/backend/architectures/defs/flux2.py+++ b/invokeai/backend/architectures/defs/flux2.py@@ -38,6 +38,9 @@ register(negative_prompt=NegativePrompt(visible=False, usage="never"),dimension_grid=16,guidance_label="Guidance",+ # flux2_denoise.guidance is le=20 -- unlike flux_denoise.guidance, which is unbounded and+ # where FLUX Fill wants 30.+ guidance_max=20.0,scheduler_set="flow",scheduler_applies_to_graph=True,max_reference_images=5,diff --git a/invokeai/backend/architectures/defs/wan.py b/invokeai/backend/architectures/defs/wan.pyindex b52b32d4ac..9a43cd6ba2 100644--- a/invokeai/backend/architectures/defs/wan.py+++ b/invokeai/backend/architectures/defs/wan.py@@ -47,6 +47,9 @@ register(# 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",+ # wan_denoise.guidance_scale is ge=1.0. Its optional low-noise counterpart is a separate+ # field with its own ge=0.0 and its own control, not this slider.+ guidance_min=1.0,scheduler_set="flow",),# The one architecture whose LoRAs carry a different variant enum from its mains. They are notdiff --git a/invokeai/backend/architectures/defs/z_image.py b/invokeai/backend/architectures/defs/z_image.pyindex 80a1561ce7..3de6b551fa 100644--- a/invokeai/backend/architectures/defs/z_image.py+++ b/invokeai/backend/architectures/defs/z_image.py@@ -31,6 +31,8 @@ register(negative_prompt=NegativePrompt(visible=True, usage="cfg-gated"),dimension_grid=16,guidance_label="CFG",+ # z_image_denoise.guidance_scale is ge=1.0; 1.0 is CFG off, which is what Turbo runs at.+ guidance_min=1.0,scheduler_set="flow",scheduler_applies_to_graph=True,control_kinds=frozenset({"z_image_control"}),diff --git a/invokeai/backend/architectures/facets/features.py b/invokeai/backend/architectures/facets/features.pyindex ec033e0ce5..a46870f399 100644--- a/invokeai/backend/architectures/facets/features.py+++ b/invokeai/backend/architectures/facets/features.py@@ -78,6 +78,28 @@ class FeaturesFacet(Facet):otherwise. Today only FLUX sets both (cfg_scale 1.0 meaning "off", guidance 3.5 meaning thedistilled embedding)."""+ guidance_min: float = 0.0+ """Lowest value the guidance slider may offer.++ Pinned to the `ge` of the node field the slider's value is actually sent as -- `guidance` for+ the models whose `guidance_label` says so, `cfg_scale` or `guidance_scale` for the rest -- so a+ test asserts the two agree and the UI cannot offer a number the graph will refuse. 0.0 is the+ default because most denoise nodes constrain neither end, and a slider still starts somewhere.++ Anima, ERNIE-Image, Wan and Z-Image are the exceptions: their `guidance_scale` is `ge=1.0`,+ 1.0 meaning "off", with nothing below it. The UI offered 0 and 0.5 for them anyway, and+ `graph.ts` forwarded the value unchanged into an enqueue that failed validation."""++ guidance_max: float | None = None+ """Highest value the guidance slider may offer, or None where the node enforces no ceiling.++ FLUX.2 is the only architecture with one: `flux2_denoise.guidance` is `le=20`, while the UI's+ numeric input accepted 100 for every architecture alike -- so 30, a value FLUX Fill really does+ want, persisted on a FLUX.2 model and was submitted and rejected.++ None is the node's answer, not the UI's: a client still needs its own slider ceiling, and None+ only says the graph will not reject a large value."""+scheduler_set: SchedulerSet | None = Nonescheduler_applies_to_graph: bool = False"""Whether the chosen scheduler reaches the graph, or is only a UI affordance."""@@ -107,6 +129,12 @@ class FeaturesFacet(Facet):"answer for every variant not named here, and a None key would be dead weight.")+ if self.guidance_max is not None and self.guidance_max < self.guidance_min:+ raise ValueError(+ f"FeaturesFacet declares a guidance range that holds no values: guidance_min="+ f"{self.guidance_min} is above guidance_max={self.guidance_max}."+ )+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:diff --git a/invokeai/backend/architectures/registry.py b/invokeai/backend/architectures/registry.pyindex b5bf23ebc7..fcb5fb0a0c 100644--- a/invokeai/backend/architectures/registry.py+++ b/invokeai/backend/architectures/registry.py@@ -59,9 +59,14 @@ def register(base: BaseModelType, *facets: Facet) -> None:"""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.+ under `--dev_reload` — calls this again. An identical declaration is the same fact stated twice,+ so it is a no-op; a *differing* one raises, which is the collision this guard exists for. Facets+ are frozen dataclasses, so "identical" is by value.++ A `defs/` module is therefore not usefully hot-reloadable: you reload it because you edited it,+ and an edited declaration is exactly the differing case, so it raises and needs a restart. The+ no-op path only keeps an *unedited* re-execution — a reload that swept this module up with the+ one that changed — from failing for no reason."""if base in _NOT_ARCHITECTURES:raise ArchitectureError(diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.jsonindex 8ec8b6ee07..0863d8654b 100644--- a/invokeai/frontend/web/openapi.json+++ b/invokeai/frontend/web/openapi.json@@ -17738,6 +17738,23 @@"title": "Guidance Label","description": "What to call the guidance slider: 'CFG' or 'Guidance'."},+ "guidance_min": {+ "type": "number",+ "title": "Guidance Min",+ "description": "Lowest guidance value the denoise node accepts; a smaller one fails at enqueue."+ },+ "guidance_max": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "title": "Guidance Max",+ "description": "Highest guidance value the denoise node accepts; null means it enforces no ceiling."+ },"scheduler_set": {"anyOf": [{@@ -17830,7 +17847,7 @@}},"type": "object",- "required": ["negative_prompt", "dimension_grid", "spatial_compression", "guidance_label"],+ "required": ["negative_prompt", "dimension_grid", "spatial_compression", "guidance_label", "guidance_min"],"title": "ArchitectureFeatures","description": "What a UI may offer for this architecture."},@@ -42293,9 +42310,9 @@},"required": ["type", "id"],"tags": ["latents", "math", "ideal_size"],- "title": "Ideal Size - SD1.5, SDXL",+ "title": "Ideal Size","type": "object",- "version": "1.0.6",+ "version": "1.1.0","output": {"$ref": "#/components/schemas/IdealSizeOutput"}diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.tsindex 46dbcce87e..4fc1709a70 100644--- a/invokeai/frontend/web/src/services/api/schema.ts+++ b/invokeai/frontend/web/src/services/api/schema.ts@@ -5196,6 +5196,16 @@ export type components = {* @description What to call the guidance slider: 'CFG' or 'Guidance'.*/guidance_label: string;+ /**+ * Guidance Min+ * @description Lowest guidance value the denoise node accepts; a smaller one fails at enqueue.+ */+ guidance_min: number;+ /**+ * Guidance Max+ * @description Highest guidance value the denoise node accepts; null means it enforces no ceiling.+ */+ guidance_max?: number | null;/*** Scheduler Set* @description Which scheduler family to offer; null means no choice.@@ -17224,7 +17234,7 @@ export type components = {base: "sdxl";};/**- * Ideal Size - SD1.5, SDXL+ * Ideal Size* @description Calculates the ideal size for generation to avoid duplication*/IdealSizeInvocation: {diff --git a/tests/app/routers/test_architecture_capabilities.py b/tests/app/routers/test_architecture_capabilities.pyindex fcd79e3837..bac34c9e7f 100644--- a/tests/app/routers/test_architecture_capabilities.py+++ b/tests/app/routers/test_architecture_capabilities.py@@ -69,11 +69,14 @@ def test_the_rows_come_from_the_registry_not_a_service(client: TestClient, mock_"""The response is the same table for every install. Nothing about it is looked up.Asserted by the model manager service never being touched: if a later version resolved- capabilities per model record, this is where it would show.+ capabilities per model record, this is where it would show -- including a lookup that happened+ to produce the same table, which the rendering test below would not catch."""mock_invoker.services.model_manager = MagicMock()assert client.get(URL).status_code == 200- mock_invoker.services.model_manager.assert_not_called()+ # `mock_calls`, not `assert_not_called()`: that only sees the mock invoked as a function, so a+ # `services.model_manager.store.get_model(...)` would pass it. `mock_calls` records the chain.+ assert mock_invoker.services.model_manager.mock_calls == []def test_the_response_matches_what_the_registry_renders(client: TestClient) -> None:diff --git a/tests/backend/architectures/test_guidance_range.py b/tests/backend/architectures/test_guidance_range.pynew file mode 100644index 0000000000..64c40e4827--- /dev/null+++ b/tests/backend/architectures/test_guidance_range.py@@ -0,0 +1,188 @@+"""The guidance range each architecture declares, against the node field that enforces it.++There is one guidance slider in the UI and its bounds were hardcoded: minimum 0, numeric input+maximum 100, for every architecture alike. Both ends were wrong somewhere. `flux2_denoise.guidance`+is `le=20`, so 30 -- a value FLUX Fill genuinely wants, on a *different* architecture -- persisted+on a FLUX.2 model and failed at enqueue. `ernie_image_denoise.guidance_scale` is `ge=1.0`, so 0 and+0.5 were offered, forwarded unchanged by `graph.ts`, and failed the same way.++`FeaturesFacet.guidance_min` / `guidance_max` move those bounds to the architecture, and this module+pins them to the node that actually validates the value -- the same way+`test_features.py::test_the_dimension_grid_matches_the_node_that_enforces_it` pins the dimension+grid to the node's `multipleOf`. Transcribing 1.0 and 20.0 into assertions here would check a number+against itself; reading them off the invocation schema is what makes the pin worth having.+"""++from typing import Any++import pytest++from invokeai.app.invocations.baseinvocation import InvocationRegistry+from invokeai.app.services.shared.graph import * # noqa: F401 F403 -- imports all invocations, populating the registry+from invokeai.backend.architectures import generative_bases+from invokeai.backend.architectures.capabilities import architecture_capabilities+from invokeai.backend.architectures.facets.default_settings import DefaultSettingsFacet+from invokeai.backend.architectures.facets.features import FeaturesFacet, NegativePrompt+from invokeai.backend.architectures.registry import require+from invokeai.backend.model_manager.configs.default_settings import MainModelDefaultSettings+from invokeai.backend.model_manager.taxonomy import BaseModelType++GUIDANCE_FIELD: dict[BaseModelType, tuple[str, str]] = {+ BaseModelType.StableDiffusion1: ("denoise_latents", "cfg_scale"),+ BaseModelType.StableDiffusion2: ("denoise_latents", "cfg_scale"),+ BaseModelType.StableDiffusionXL: ("denoise_latents", "cfg_scale"),+ BaseModelType.StableDiffusion3: ("sd3_denoise", "cfg_scale"),+ BaseModelType.CogView4: ("cogview4_denoise", "cfg_scale"),+ BaseModelType.Krea2: ("krea2_denoise", "cfg_scale"),+ BaseModelType.QwenImage: ("qwen_image_denoise", "cfg_scale"),+ BaseModelType.Flux: ("flux_denoise", "guidance"),+ BaseModelType.Flux2: ("flux2_denoise", "guidance"),+ BaseModelType.Anima: ("anima_denoise", "guidance_scale"),+ BaseModelType.ErnieImage: ("ernie_image_denoise", "guidance_scale"),+ BaseModelType.Wan: ("wan_denoise", "guidance_scale"),+ BaseModelType.ZImage: ("z_image_denoise", "guidance_scale"),+}+"""Where the one guidance slider's value ends up, per architecture.++Not derivable from the node: `flux2_denoise` takes both a `guidance` and a `cfg_scale`, and only+`guidance` carries the slider -- `FeaturesFacet.guidance_label` is what says so. Recorded in+`generateGraphNodeTypes.json` under each node type's `literalInputs`, which is where these thirteen+were read off, and checked against the graph builders by+`tests/app/invocations/test_frontend_graph_node_types.py`.+"""++NO_GUIDANCE_SLIDER = frozenset(+ {+ # `ideogram4_denoise.guidance_scale` exists and is bounded, but it is preset-derived and has+ # its own optional control (`ideogram4GuidanceScale`); the shared slider never reaches it.+ BaseModelType.Ideogram4,+ # No generation path in webv2, and no guidance field on its denoise node: video-first, with+ # two hardcoded flow schedules.+ BaseModelType.MiniMaxH3,+ # A second pass over someone else's latents rather than a model you generate with.+ BaseModelType.StableDiffusionXLRefiner,+ }+)++UNCONSTRAINED_MIN = 0.0+"""What an architecture whose node enforces no floor declares. A slider has to start somewhere and+none of these samplers reads a negative guidance, so zero is the UI's floor rather than the node's.+"""+++def _numeric_bounds(node_type: str, field_name: str) -> tuple[float | None, float | None]:+ """The `ge`/`le` a node applies to one numeric field, as a client sees them.++ Read through the JSON schema rather than off the annotation, because that is the artifact the+ frontend is generated from. A field that is optional or accepts a list of values puts its+ constraints on the numeric branch of an `anyOf` -- `denoise_latents.cfg_scale` is+ `float | list[float]` -- so the top level is not always where they are.+ """+ cls = InvocationRegistry.get_invocations_map().get(node_type)+ assert cls is not None, f"no invocation is registered as '{node_type}'"+ schema: dict[str, Any] = cls.model_json_schema()["properties"][field_name]+ numeric = [branch for branch in schema.get("anyOf", [schema]) if branch.get("type") == "number"]+ assert len(numeric) == 1, f"{node_type}.{field_name} has {len(numeric)} numeric branches, not one"+ return numeric[0].get("minimum"), numeric[0].get("maximum")+++def test_every_architecture_is_accounted_for() -> None:+ """A new architecture cannot be added without saying where its guidance value goes.++ Without this the pin below is only as complete as the map above it, and an architecture omitted+ from both would go silently unchecked -- which is how the UI came to offer 0 for ERNIE-Image.+ """+ covered = set(GUIDANCE_FIELD) | NO_GUIDANCE_SLIDER+ missing = sorted(b.value for b in generative_bases() if b not in covered)+ assert missing == [], (+ f"{missing} declare a guidance range that nothing checks. Add the denoise node and the "+ f"field its slider value is sent as to GUIDANCE_FIELD, or say why there is none in "+ f"NO_GUIDANCE_SLIDER."+ )+ assert not (set(GUIDANCE_FIELD) & NO_GUIDANCE_SLIDER)++[email protected]("base", sorted(GUIDANCE_FIELD, key=lambda b: b.value), ids=lambda b: b.value)+def test_the_guidance_range_matches_the_node_that_enforces_it(base: BaseModelType) -> None:+ node_type, field_name = GUIDANCE_FIELD[base]+ node_min, node_max = _numeric_bounds(node_type, field_name)+ facet = require(base, FeaturesFacet)++ expected_min = UNCONSTRAINED_MIN if node_min is None else node_min+ assert (facet.guidance_min, facet.guidance_max) == (expected_min, node_max), (+ f"'{base.value}' declares guidance {facet.guidance_min}..{facet.guidance_max} but "+ f"{node_type}.{field_name} accepts {expected_min}..{node_max}. Whichever is wrong, a UI "+ f"reading the declaration offers a value the graph rejects -- see "+ f"invokeai/backend/architectures/defs/{base.value.replace('-', '_')}.py."+ )++[email protected]("base", sorted(NO_GUIDANCE_SLIDER, key=lambda b: b.value), ids=lambda b: b.value)+def test_an_architecture_with_no_slider_declares_no_range(base: BaseModelType) -> None:+ """Nothing sends these a guidance value, so a narrowed range here would be a claim about a+ control that does not exist."""+ facet = require(base, FeaturesFacet)+ assert (facet.guidance_min, facet.guidance_max) == (UNCONSTRAINED_MIN, None), base.value+++def test_a_range_that_holds_no_values_is_refused() -> None:+ """Declaration-time, like `dimension_grid_by_variant`'s None-key guard. The two bounds are+ separate fields and nothing about the types stops them being entered the wrong way round; a+ ceiling below the floor leaves the UI a slider with nothing on it."""+ with pytest.raises(ValueError, match="holds no values"):+ FeaturesFacet(+ negative_prompt=NegativePrompt(visible=True, usage="always"),+ dimension_grid=16,+ guidance_min=1.0,+ guidance_max=0.5,+ )+++def _slider_value(settings: MainModelDefaultSettings) -> float | None:+ """The number the slider is restored to: `guidance` where the declaration sets it, `cfg_scale`+ otherwise -- the rule `FeaturesFacet.guidance_label` documents, and the reason FLUX can carry+ both (`cfg_scale=1.0` meaning off, `guidance=3.5` meaning the distilled embedding)."""+ return settings.guidance if settings.guidance is not None else settings.cfg_scale++[email protected]("base", sorted(GUIDANCE_FIELD, key=lambda b: b.value), ids=lambda b: b.value)+def test_every_recommended_guidance_value_is_inside_the_declared_range(base: BaseModelType) -> None:+ """A recommended default outside its own architecture's range is a one-click failed enqueue.++ Reaches the per-variant and per-name-hint settings too: FLUX Fill's `guidance=30.0` is a variant+ row, and it is exactly the kind of value a ceiling copied from the wrong architecture forbids.+ """+ facet = require(base, FeaturesFacet)+ defaults = require(base, DefaultSettingsFacet)++ labelled = [(str(variant), s) for variant, s in defaults.by_variant.items()]+ labelled += [(f"name hint '{hint}'", s) for hint, s in defaults.by_name_hint.items()]++ outside = []+ for label, settings in labelled:+ value = _slider_value(settings)+ if value is None:+ continue+ if value < facet.guidance_min or (facet.guidance_max is not None and value > facet.guidance_max):+ outside.append(f"{label}: {value}")+ assert outside == [], (+ f"'{base.value}' recommends {outside}, outside its declared guidance range "+ f"{facet.guidance_min}..{facet.guidance_max}."+ )+++def test_the_served_table_carries_the_range_on_every_row() -> None:+ """The declaration is only useful if a client can read it, and it has to be on the variant rows+ as well: a client joins on `(base, variant)` and does not fall back to the base row."""+ declared = {base.value: require(base, FeaturesFacet) for base in generative_bases()}+ served = {+ (row.base.value, row.variant): (row.features.guidance_min, row.features.guidance_max)+ for row in architecture_capabilities()+ }+ assert served, "no rows served"+ mismatched = {+ key: value+ for key, value in served.items()+ if value != (declared[key[0]].guidance_min, declared[key[0]].guidance_max)+ }+ assert mismatched == {}diff --git a/tests/backend/architectures/test_latent_space.py b/tests/backend/architectures/test_latent_space.pyindex afbeac75e4..c8f3ac9707 100644--- a/tests/backend/architectures/test_latent_space.py+++ b/tests/backend/architectures/test_latent_space.py@@ -1,35 +1,168 @@-"""The latent-space facet: the projection maths, and what each architecture declares."""+"""The latent-space facet: the projection maths, and what each architecture declares.+Two tables carry this file. `DECLARED_LATENT_SPACES` says which space each of the sixteen+architectures denoises in; `PINNED_PREVIEW_PIXELS` says what each of the nine spaces actually+computes. Together they are what stops a wrong space reaching generation: swapping `FLUX_16` for+`SD3_16` in `defs/flux.py` moves one row of the first table, and the second table is what proves+the two rows are not interchangeable.+"""++import pytestimport torchfrom invokeai.backend.architectures import generative_bases, resolve_latent_space+from invokeai.backend.architectures.facets import latent_spacefrom invokeai.backend.architectures.facets.latent_space import (+ COGVIEW4_16,+ FLUX2_32,+ FLUX_16,+ MINIMAX_H3_24,+ SD3_16,+ SD15_4,SDXL_4,WAN21_16,WAN22_48,LatentSpace,LatentSpaceFacet,)-from invokeai.backend.architectures.registry import get+from invokeai.backend.architectures.registry import get, requirefrom invokeai.backend.model_manager.taxonomy import BaseModelType+_SPACE_NAMES = {id(space): name for name, space in vars(latent_space).items() if isinstance(space, LatentSpace)}+"""The module-level name of each declared space, by identity.++Read off the facets module rather than transcribed, so it cannot fall behind. Assertions below+compare these names instead of the `LatentSpace` objects for two reasons: a failure then reads+`['SD3_16'] != ['FLUX_16']` rather than two screens of matrix, and a space that is an equal *copy*+of a declared one has no name here, so `==` on names is as strict as `is`."""+++def _name(space: LatentSpace) -> str:+ return _SPACE_NAMES.get(id(space), f"an unnamed {space.channels}-channel space")-class TestProjection:- def test_a_known_pixel(self) -> None:- """One reference value, written down rather than recomputed.- The previous version of this test derived its expectation by summing the columns of the very- matrix under test, which made it a tautology: any change to the matrix changed both sides- and the test stayed green. Its docstring claimed 0.3677/0.4577/0.9101 for these column sums;- the real values are 0.3887/0.8771/1.3152, and nothing noticed for as long as it existed.+# The space each architecture denoises in. Derived twice: from `defs/<base>.py`, and from the+# pre-refactor dispatch this PR replaced, which is still readable at the base revision as+# `git show bfccc6e4643a760ca4e2d34376940d286272486a:invokeai/app/util/step_callback.py`. That+# `if/elif` chain is the independent source; where the two disagree the disagreement is the finding.+# It named its matrices rather than its spaces, so a row matches when the old branch selected the+# same factors, bias and smoothing kernel the space declares.+DECLARED_LATENT_SPACES: dict[BaseModelType, tuple[LatentSpace, ...]] = {+ # Old branch: ANIMA_LATENT_RGB_FACTORS + ANIMA_LATENT_RGB_BIAS, a byte-identical copy of the+ # Wan 2.1 matrix under a second name. Same for Krea-2 and Qwen-Image, which shared a third copy+ # (QWEN_IMAGE_*). The merge into one `WAN21_16` is the change; the numbers are unchanged.+ BaseModelType.Anima: (WAN21_16,),+ BaseModelType.CogView4: (COGVIEW4_16,),+ BaseModelType.ErnieImage: (FLUX2_32,),+ BaseModelType.Flux: (FLUX_16,),+ BaseModelType.Flux2: (FLUX2_32,),+ # The one row the `if/elif` chain cannot corroborate: it had no Ideogram 4 branch and would+ # have raised "Unsupported base model" here. The second, divergent copy of the projection is+ # the source instead -- `ideogram4_denoise.py` at the same revision built its own preview from+ # FLUX2_LATENT_RGB_FACTORS and FLUX2_LATENT_RGB_BIAS at 8x. Folding that copy in is what gives+ # Ideogram 4 a row at all.+ BaseModelType.Ideogram4: (FLUX2_32,),+ BaseModelType.Krea2: (WAN21_16,),+ BaseModelType.MiniMaxH3: (MINIMAX_H3_24,),+ BaseModelType.QwenImage: (WAN21_16,),+ BaseModelType.StableDiffusion1: (SD15_4,),+ BaseModelType.StableDiffusion2: (SD15_4,),+ BaseModelType.StableDiffusion3: (SD3_16,),+ BaseModelType.StableDiffusionXL: (SDXL_4,),+ BaseModelType.StableDiffusionXLRefiner: (SDXL_4,),+ # The only architecture with more than one: the old chain read `sample.shape[-3] == 48` inside+ # the Wan branch. Every other row is a one-tuple, which is the declaration that an architecture+ # does not depend on the shape of its latents.+ BaseModelType.Wan: (WAN21_16, WAN22_48),+ # Old branch: FLUX_LATENT_RGB_FACTORS, commented "Z-Image uses FLUX-compatible VAE".+ BaseModelType.ZImage: (FLUX_16,),+}- A 1x16x1x1 tensor of ones projects to the column sums of WAN21, plus the bias, mapped from- -1..1 to 0..255.+# What each space projects a latent whose every channel holds the same value to.+#+# A `1 x C x 1 x 1` sample of `fill` projects to `fill * (column sums of rgb_factors) + rgb_bias`,+# which `preview()` then maps from -1..1 to 0..255 as `int(clamp((v + 1) / 2, 0, 1) * 255)` -- a+# truncating cast, not a round. Each row's comment carries the column sums, added by hand from the+# declared matrix; the bytes follow from them by that formula alone.+#+# Deriving them the other way round -- calling `preview()` and writing down the answer -- is how the+# WAN21 expectation went wrong before: a previous version of this test summed the very matrix under+# test, so any change to the matrix moved both sides at once. Its docstring claimed column sums of+# 0.3677/0.4577/0.9101 where the matrix really sums to 0.3887/0.8771/1.3152.+#+# `fill` is 1.0 everywhere except MiniMax H3, whose matrix sums past the clamp in two channels --+# a ones sample there reports 255 for anything summing above 0.881, which pins nothing. A quarter+# of that lands all three channels inside the range.+PINNED_PREVIEW_PIXELS: list[tuple[LatentSpace, float, tuple[int, int, int], tuple[int, int, int]]] = [+ # colsums (0.0192, 0.6051, -0.3178), no bias+ (SD15_4, 1.0, (129, 204, 86), (127, 127, 127)),+ # colsums (-0.2517, 0.7505, 0.0722), no bias, and then the 3x3 kernel. A 1x1 latent pads to+ # 3x3 with zeros, so only the kernel's centre weight survives: the projection is scaled by+ # 0.4711 before the mapping. Without the kernel these bytes would be (95, 223, 136).+ (SDXL_4, 1.0, (112, 172, 131), (127, 127, 127)),+ # colsums (0.06665435, 0.50958726, 0.32699234), no bias. R lands at 135.998, so the truncating+ # cast -- not a round -- is what makes it 135.+ (SD3_16, 1.0, (135, 192, 169), (127, 127, 127)),+ # colsums (0.66503498, 0.33521276, 0.26056899), no bias+ (COGVIEW4_16, 1.0, (212, 170, 160), (127, 127, 127)),+ # colsums (-0.0023, 0.2058, 0.2752), no bias+ (FLUX_16, 1.0, (127, 153, 162), (127, 127, 127)),+ # colsums (0.3887, 0.8771, 1.3152), bias (-0.1835, -0.0868, -0.3360)+ (WAN21_16, 1.0, (153, 228, 252), (104, 116, 84)),+ # colsums (-0.0122, 0.1637, 0.1435), bias (-0.0329, -0.0718, -0.0851)+ (FLUX2_32, 1.0, (121, 139, 134), (123, 118, 116)),+ # colsums (0.9628, 1.0896, -0.9290), bias (0.1189, 0.1415, -0.0034). See the note on `fill`.+ (MINIMAX_H3_24, 0.25, (173, 180, 97), (142, 145, 127)),+ # colsums (-0.5209, -0.1927, 0.9241), bias (0.0317, -0.0878, -0.1388)+ (WAN22_48, 1.0, (65, 91, 227), (131, 116, 109)),+]+++class TestProjection:+ @pytest.mark.parametrize(+ ("space", "fill", "uniform_pixel", "zero_pixel"),+ [pytest.param(*row, id=_name(row[0])) for row in PINNED_PREVIEW_PIXELS],+ )+ def test_what_a_space_projects_a_uniform_latent_to(+ self,+ space: LatentSpace,+ fill: float,+ uniform_pixel: tuple[int, int, int],+ zero_pixel: tuple[int, int, int],+ ) -> None:+ """One reference colour per space, written down rather than recomputed.++ The zero sample is the bias on its own, which is the only thing separating two spaces that+ share a matrix -- and (127, 127, 127) is the assertion that a space declaring no bias has+ not quietly acquired one."""- assert WAN21_16.preview(torch.ones(1, 16, 1, 1)).getpixel((0, 0)) == (153, 228, 252)+ filled = torch.full((1, space.channels, 1, 1), fill)+ assert (+ space.preview(filled).getpixel((0, 0)),+ space.preview(torch.zeros(1, space.channels, 1, 1)).getpixel((0, 0)),+ ) == (uniform_pixel, zero_pixel)++ def test_every_declared_space_has_a_pinned_pixel(self) -> None:+ """A tenth space, or a matrix edited in place, has to land in the table above."""+ reachable = {+ _name(space)+ for base in generative_bases()+ for facet in [require(base, LatentSpaceFacet)]+ for space in (facet.primary, *facet.alternates)+ }+ assert reachable == {_name(row[0]) for row in PINNED_PREVIEW_PIXELS}++ def test_the_smoothing_kernel_reaches_beyond_the_pixel_it_centres_on(self) -> None:+ """SDXL is the only space with a kernel, and a uniform 1x1 latent only sees its centre.- def test_a_zero_sample_shows_the_bias(self) -> None:- assert WAN21_16.preview(torch.zeros(1, 16, 1, 1)).getpixel((0, 0)) == (104, 116, 84)+ A 1x3 latent of ones sees the rest of the middle kernel row: the centre pixel is scaled by+ 0.0964 + 0.4711 + 0.0964 = 0.6639, and each end pixel by 0.4711 + 0.0964 = 0.5675, because+ `conv2d(..., padding=1)` supplies a zero on its outer side. Dropping the kernel entirely+ would make all three (95, 223, 136); getting an off-centre weight wrong would move the ends+ without moving the centre.+ """+ image = SDXL_4.preview(torch.ones(1, 4, 1, 3))+ assert [image.getpixel((x, 0)) for x in range(3)] == [(109, 181, 132), (106, 191, 133), (109, 181, 132)]def test_the_preview_is_one_pixel_per_latent(self) -> None:assert WAN21_16.preview(torch.zeros(1, 16, 5, 7)).size == (7, 5)@@ -42,13 +175,6 @@ class TestProjection:pixels = [image.getpixel((x, y)) for y in range(3) for x in range(3)]assert all(p == pixels[0] for p in pixels)- def test_the_smoothing_kernel_changes_the_result(self) -> None:- """SDXL is the only space with one; without this, dropping it would go unnoticed."""- unsmoothed = LatentSpace(channels=4, spatial_compression=8, rgb_factors=SDXL_4.rgb_factors)- sample = torch.randn(1, 4, 8, 8)- torch.manual_seed(0)- assert SDXL_4.preview(sample).tobytes() != unsmoothed.preview(sample).tobytes()-class TestResolution:def test_wan_picks_its_space_by_channel_count(self) -> None:@@ -69,6 +195,34 @@ class TestResolution:class TestWhatArchitecturesDeclare:+ @pytest.mark.parametrize(+ ("base", "expected"),+ [+ pytest.param(base, expected, id=base.value)+ for base, expected in sorted(DECLARED_LATENT_SPACES.items(), key=lambda item: item[0].value)+ ],+ )+ def test_the_space_each_architecture_denoises_in(+ self, base: BaseModelType, expected: tuple[LatentSpace, ...]+ ) -> None:+ """The single most load-bearing thing an architecture declares.++ A wrong space here is not a crash: the shapes still line up wherever the channel counts+ match, so FLUX declaring `SD3_16` would produce a plausible-looking preview in the wrong+ colours for every FLUX generation and nothing else would notice. Both directions are+ asserted -- what the facet declares, and what `resolve_latent_space` hands the step callback+ for a sample of that space's channel count.+ """+ facet = require(base, LatentSpaceFacet)+ declared = (facet.primary, *facet.alternates)+ assert [_name(space) for space in declared] == [_name(space) for space in expected]+ for space in expected:+ assert resolve_latent_space(base, torch.zeros(1, space.channels, 1, 1)) is space++ def test_every_architecture_is_pinned(self) -> None:+ """A new architecture has to land in the table above, rather than going unchecked."""+ assert set(DECLARED_LATENT_SPACES) == set(generative_bases())+def test_every_architecture_declares_a_latent_space(self) -> None:"""`REQUIRED = True` makes `validate()` enforce this at boot; this says what it means."""undeclared = sorted(b.value for b in generative_bases() if get(b, LatentSpaceFacet) is None)@@ -101,16 +255,3 @@ class TestWhatArchitecturesDeclare:spaces.append(space)matrices = [tuple(tuple(row) for row in s.rgb_factors) for s in spaces]assert len(set(matrices)) == len(matrices)-- def test_the_shared_spaces_are_actually_shared(self) -> None:- """Sharing is by identity, not by an equal copy — the point of naming the spaces."""- for base in (BaseModelType.QwenImage, BaseModelType.Krea2, BaseModelType.Anima, BaseModelType.Wan):- facet = get(base, LatentSpaceFacet)- assert facet is not None and facet.primary is WAN21_16, base.value-- def test_only_wan_has_alternates(self) -> None:- """Every other architecture stays independent of what shape its latents happen to be."""- with_alternates = sorted(- b.value for b in generative_bases() if (f := get(b, LatentSpaceFacet)) is not None and f.alternates- )- assert with_alternates == ["wan"]diff --git a/tests/test_docs_json_export.py b/tests/test_docs_json_export.pyindex d2ecaa9c28..d242bc2c33 100644--- a/tests/test_docs_json_export.py+++ b/tests/test_docs_json_export.py@@ -4,6 +4,11 @@ import importlib.utilimport jsonfrom pathlib import Path+# Absolute, like `test_check_pins.py` and `test_new_architecture_script.py`: a path relative to+# the process cwd only resolves when pytest is started from the repository root, and the four+# tests below fail with a FileNotFoundError from anywhere else.+REPO_ROOT = Path(__file__).resolve().parent.parent+def _load_module(module_path: Path, module_name: str):spec = importlib.util.spec_from_file_location(module_name, module_path)@@ -15,7 +20,7 @@ def _load_module(module_path: Path, module_name: str):def test_docs_json_export_bundle_structure():- module = _load_module(Path("scripts/generate_docs_json.py"), "generate_docs_json")+ module = _load_module(REPO_ROOT / "scripts" / "generate_docs_json.py", "generate_docs_json")bundle = module.build_docs_bundle()@@ -23,7 +28,7 @@ def test_docs_json_export_bundle_structure():def test_docs_json_export_includes_images_interface_and_host_setting():- module = _load_module(Path("scripts/generate_docs_json.py"), "generate_docs_json")+ module = _load_module(REPO_ROOT / "scripts" / "generate_docs_json.py", "generate_docs_json")bundle = module.build_docs_bundle()@@ -36,7 +41,7 @@ def test_docs_json_export_includes_images_interface_and_host_setting():def test_docs_json_export_includes_rendering_metadata():- module = _load_module(Path("scripts/generate_docs_json.py"), "generate_docs_json")+ module = _load_module(REPO_ROOT / "scripts" / "generate_docs_json.py", "generate_docs_json")bundle = module.build_docs_bundle()@@ -57,7 +62,7 @@ def test_docs_json_export_includes_rendering_metadata():def test_docs_json_export_writes_expected_files(tmp_path: Path):- module = _load_module(Path("scripts/generate_docs_json.py"), "generate_docs_json")+ module = _load_module(REPO_ROOT / "scripts" / "generate_docs_json.py", "generate_docs_json")bundle = module.build_docs_bundle()module.write_docs_bundle(bundle, tmp_path)diff --git a/tests/test_new_architecture_script.py b/tests/test_new_architecture_script.pyindex d59f42e81f..0d02343fc7 100644--- a/tests/test_new_architecture_script.py+++ b/tests/test_new_architecture_script.py@@ -1,8 +1,9 @@"""The scaffolder generates valid stubs, and its residual list stays honest."""import ast-import sys+import importlib.utilfrom pathlib import Path+from types import ModuleTypefrom typing import Anyimport pytest@@ -10,15 +11,29 @@ import pytestfrom invokeai.backend.architectures import registryREPO_ROOT = Path(__file__).resolve().parents[1]-sys.path.insert(0, str(REPO_ROOT / "scripts"))--from new_architecture import ( # noqa: E402- defs_module,- derive_residual_edits,- invocations_package,- planned_files,- starter_models_module,-)+++def _load_module(module_path: Path, module_name: str) -> ModuleType:+ """Load a `scripts/` module by path, as `test_check_pins.py` and `test_docs_json_export.py` do.++ `scripts/` is not a package and is not importable. Putting it on `sys.path` instead would leave+ it there for every other file the xdist worker runs afterwards, where a script's name could+ shadow a real module.+ """+ spec = importlib.util.spec_from_file_location(module_name, module_path)+ assert spec is not None+ assert spec.loader is not None+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++new_architecture = _load_module(REPO_ROOT / "scripts" / "new_architecture.py", "new_architecture")+defs_module = new_architecture.defs_module+derive_residual_edits = new_architecture.derive_residual_edits+invocations_package = new_architecture.invocations_package+planned_files = new_architecture.planned_files+starter_models_module = new_architecture.starter_models_moduleREQUIRED_FACETS = {"LatentSpaceFacet", "ConditioningFacet", "DefaultSettingsFacet", "ModalityFacet", "FeaturesFacet"}