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.

feat(upscale): support Z-Image and Anima in the Upscale widget

Alexander Eichhorn295ff27f6cb8
diff --git a/.github/workflows/python-tests.yml b/.github/workflows/python-tests.yml
index 6e94e777f4..a4eeac8e1b 100644
--- a/.github/workflows/python-tests.yml
+++ b/.github/workflows/python-tests.yml
@@ -127,6 +127,7 @@ jobs:
- 'invokeai/frontend/webv2/src/features/generation/core/__snapshots__/**'
- 'invokeai/frontend/webv2/src/features/generation/core/__fixtures__/**'
- 'invokeai/frontend/webv2/src/features/video/core/__snapshots__/**'
+ - 'invokeai/frontend/webv2/src/features/upscale/core/__snapshots__/**'
# test_ideogram4_frontend_bounds.py reads the Ideogram 4 control bounds from here.
- 'invokeai/frontend/webv2/src/features/generation/core/settings.ts'
- 'tests/**'
diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/z-image.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/z-image.mdx
index 55b00e7582..956cf447a5 100644
--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/z-image.mdx
+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/z-image.mdx
@@ -103,7 +103,8 @@ shift. Leave it blank to have it calculated from the image size, which is the re
Two Z-Image ControlNets are available as starters (both are part of the bundle):
- **Z-Image ControlNet Union** handles Canny, HED, Depth, Pose and MLSD control images.
-- **Z-Image ControlNet Tile** is useful for upscaling and adding detail.
+- **Z-Image ControlNet Tile** is useful for upscaling and adding detail. The **Upscale** tool can use it as an
+ optional anchor; see [Upscaling](/users-guide/image-generation/upscale/).
On the Canvas, add a **Control Layer** while a Z-Image model is selected. The layer uses a Z-Image
ControlNet with a default weight of `0.75`. The weight ranges from `0` to `2`, and `0.65` to `0.80` is the
diff --git a/docs/src/content/docs/Users Guide/04.Image Generation/upscale.mdx b/docs/src/content/docs/Users Guide/04.Image Generation/upscale.mdx
index 3179292b73..5a7954b52c 100644
--- a/docs/src/content/docs/Users Guide/04.Image Generation/upscale.mdx
+++ b/docs/src/content/docs/Users Guide/04.Image Generation/upscale.mdx
@@ -1,6 +1,6 @@
---
title: Upscaling
-lastUpdated: 2026-09-30
+lastUpdated: 2026-10-12
sidebar:
order: 8
---
@@ -17,30 +17,39 @@ The panel is split into sections, top to bottom:
- **Source image**: pick an image from the gallery, drag one in, or upload one.
- **Spandrel model**: the first-pass upscaler. Choose one suited to your image: photography, illustration or linework.
- **Scale**: the output size is the source size multiplied by this value. The panel shows the resulting input and output size and warns when the output is large enough to need much more time and VRAM.
- - **Treatment preset**, or **Creativity** and **Structure** directly. Higher Creativity invents more detail and gives the prompt more influence. Higher Structure keeps the source composition more strictly; it is only shown for models that use a Tile ControlNet.
+ - **Treatment preset**, or **Creativity** and **Structure** directly. Higher Creativity invents more detail and gives the prompt more influence. Higher Structure keeps the source composition more strictly; it is only shown when a Tile ControlNet is in use.
- **Detail guidance**: the prompt. It is the project prompt shared with Generate. For upscaling, describe the medium, texture and style rather than new content.
-- **Generation**: the **Main model** for the detail pass (**SD1.5**, **SDXL** or **FLUX.1**), steps, CFG scale, scheduler, seed, and LoRAs that match the main model.
+- **Generation**: the **Main model** for the detail pass (**SD1.5**, **SDXL**, **FLUX.1**, **Z-Image** or **Anima**), steps, CFG scale, scheduler, seed, and LoRAs that match the main model.
- **Advanced**: the components the main model needs (see below), tile size and tile overlap, VAE and VAE precision, and CLIP skip for SD1.5.
## What each model family needs
-| | SD1.5 / SDXL | FLUX.1 |
-|---|---|---|
-| Tile ControlNet | Required: a Tile or Union ControlNet for the same family, under **Advanced** | Not used; the Structure slider is hidden |
-| Negative prompt | Available | Not used; FLUX.1 ignores it, so it is hidden and not recorded |
-| Other components | Taken from the main model | Every FLUX.1 model except an SDNQ pipeline needs a **T5 Encoder**, **CLIP Embed** and **VAE**, all under **Advanced**. SDNQ pipelines bring their own. FLUX Fill models cannot be used |
-| Detail pass | Tile by tile | One pass over the whole image |
+| | SD1.5 / SDXL | FLUX.1 | Z-Image | Anima |
+|---|---|---|---|---|
+| Tile ControlNet | Required: a Tile or Union ControlNet for the same family, under **Advanced** | Not used; the Structure slider is hidden | Optional: **Z-Image ControlNet Tile**, under **Advanced**. The Union ControlNet has no tile mode and is not offered | Not used; the Structure slider is hidden |
+| Negative prompt | Available | Not used; FLUX.1 ignores it, so it is hidden and not recorded | Used only when CFG is greater than 1 | Used only when CFG is greater than 1 |
+| CFG scale | Kept as you set it; back to 2 when you switch from Z-Image or Anima | Kept as you set it, and used as guidance; back to 2 when you switch from Z-Image or Anima | Set to the model's default when you pick the model: 1 for Z-Image Turbo, 4 for Z-Image Base | Set to the model's default when you pick the model: 4.5, or 6 for Anima-3.8B |
+| Other components | Taken from the main model | Every FLUX.1 model except an SDNQ pipeline needs a **T5 Encoder**, **CLIP Embed** and **VAE**, all under **Advanced**. SDNQ pipelines bring their own. FLUX Fill models cannot be used | A **Qwen3 Encoder** (the 4B) and a FLUX **VAE**, unless the model is a Diffusers or complete SDNQ install that brings its own | A **Qwen3 Encoder** (the 0.6B) and a Qwen-Image **VAE**; Anima-3.8B also a **Qwen3.5 Encoder** |
+| Detail pass | Tile by tile | One pass over the whole image | One pass over the whole image | One pass over the whole image |
The panel says what is missing before you can queue, for example "Select a compatible Tile or Union ControlNet." or "This model needs a T5 encoder selected."
-:::note[FLUX.1 output size]
-FLUX.1 needs sizes that are a multiple of 16. When the enlarged image is not, the panel shrinks it slightly to the nearest fitting size before the detail pass — for example 2040 px becomes 2032 px.
+:::note[Output size]
+FLUX.1 and Z-Image need sizes that are a multiple of 16. When the enlarged image is not, the panel shrinks it slightly to the nearest fitting size before the detail pass — for example 2040 px becomes 2032 px.
:::
+### Creativity on Z-Image and Anima
+
+Z-Image and Anima count the start of the detail pass in steps rather than in noise level, so the same Creativity setting would add much more noise there than on FLUX.1. The panel translates Creativity for them: it starts the pass on the step whose noise level is closest to where FLUX.1 would start. A preset therefore means the same thing on all three, and the pass runs fewer steps than the Steps setting suggests. For example, **Balanced** at 30 steps runs the last 7 or 8, and both need at least 2 steps.
+
+This holds for the schedulers that follow the noise schedule they are given: on Z-Image only **Euler**, on Anima every scheduler except **LCM**. The others build their own schedule and do not start where the panel asks.
+
+The Z-Image Tile ControlNet is optional because the detail pass runs over the whole image at once: there are no tile seams for it to hold together. Adding it lets **Structure** pull the result back toward the enlarged image, at the cost of a second network's memory and time.
+
## Memory
For SD1.5 and SDXL the detail pass works in tiles, so the output can be much larger than what the model generates in one go. Larger tiles can improve continuity but need more VRAM; more tile overlap reduces seams but costs time and memory.
-For FLUX.1 the detail pass runs over the whole image at once, so its memory use grows with the output size. There, **Tile size** only sets the tiles for the VAE encode and decode, and **Tile overlap** has no effect.
+For FLUX.1, Z-Image and Anima the detail pass runs over the whole image at once, so its memory use grows with the output size. There, **Tile size** only sets the tiles for the VAE encode and decode, and **Tile overlap** has no effect. Anima's decode picks its own tiles.
For all model families, encoding and decoding the enlarged image with the VAE runs in tiles. See [Low-VRAM mode](/configuration/optimization/low-vram-mode/) if you still run out of memory.
diff --git a/docs/src/content/docs/configuration/Optimization/low-vram-mode.mdx b/docs/src/content/docs/configuration/Optimization/low-vram-mode.mdx
index 162a810d73..c7284b4414 100644
--- a/docs/src/content/docs/configuration/Optimization/low-vram-mode.mdx
+++ b/docs/src/content/docs/configuration/Optimization/low-vram-mode.mdx
@@ -210,8 +210,8 @@ To always decode untiled unless you ask for tiling, turn this off. A decode too
auto_tiled_decode: false
```
-- **Always tile:** set `force_tiled_decode: true` in `invokeai.yaml`. It covers the VAE decode and encode for SD1.5/SDXL, FLUX.1, Z-Image and Qwen-Image, the Anima encode, and the Krea-2 style reference. Other model families (for example SD3, FLUX.2, Wan and LTX-2) ignore it.
-- **Per node:** the SD, FLUX.1, Z-Image and Qwen-Image **Latents to Image** and **Image to Latents** nodes, and **Image to Latents - Anima**, have **Tiled** and **Tile Size** fields for workflows. The [Upscale panel](/users-guide/image-generation/upscale/) turns tiling on by itself.
+- **Always tile:** set `force_tiled_decode: true` in `invokeai.yaml`. It covers the VAE decode and encode for SD1.5/SDXL, FLUX.1, Z-Image and Qwen-Image, the Anima encode, the control image of a Z-Image ControlNet, and the Krea-2 style reference. Other model families (for example SD3, FLUX.2, Wan and LTX-2) ignore it.
+- **Per node:** the SD, FLUX.1, Z-Image and Qwen-Image **Latents to Image** and **Image to Latents** nodes, and **Image to Latents - Anima**, have **Tiled** and **Tile Size** fields for workflows. So does the **Z-Image ControlNet** node, for the control image the denoise encodes. The [Upscale panel](/users-guide/image-generation/upscale/) turns tiling on by itself.
- **Automatic retry:** if a FLUX.1, Z-Image or Anima decode, or a FLUX.1 encode, runs out of memory, InvokeAI retries it once with tiling and logs that it did.
A tiled decode is not pixel-identical to a single-pass one. The VAE looks at the whole image at once, so the difference is spread over the image rather than limited to the tile seams; it is small, but the same seed will not reproduce an untiled result exactly.
diff --git a/docs/src/generated/settings.json b/docs/src/generated/settings.json
index 8a1cc4fb1b..7fc9d4d6ac 100644
--- a/docs/src/generated/settings.json
+++ b/docs/src/generated/settings.json
@@ -801,7 +801,7 @@
{
"category": "GENERATION",
"default": false,
- "description": "Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty). A tiled decode is not pixel-identical to a single-pass one: a VAE decoder normalises and attends over the whole image, so the difference is spread across it rather than confined to the tile seams. Also tiles the encode. Read by the SD1.5/SDXL, FLUX.1, Z-Image and Qwen-Image VAE nodes, the Anima encode and the Krea-2 style reference; other model families ignore it.",
+ "description": "Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty). A tiled decode is not pixel-identical to a single-pass one: a VAE decoder normalises and attends over the whole image, so the difference is spread across it rather than confined to the tile seams. Also tiles the encode. Read by the SD1.5/SDXL, FLUX.1, Z-Image and Qwen-Image VAE nodes, the Anima encode, the Z-Image control encode and the Krea-2 style reference; other model families ignore it.",
"env_var": "INVOKEAI_FORCE_TILED_DECODE",
"literal_values": [],
"name": "force_tiled_decode",
diff --git a/invokeai/app/invocations/vae/z_image_image_to_latents.py b/invokeai/app/invocations/vae/z_image_image_to_latents.py
index d3aaa13513..de71e54ea0 100644
--- a/invokeai/app/invocations/vae/z_image_image_to_latents.py
+++ b/invokeai/app/invocations/vae/z_image_image_to_latents.py
@@ -53,9 +53,9 @@ class ZImageImageToLatentsInvocation(BaseInvocation, WithMetadata, WithBoard):
) -> torch.Tensor:
"""Encode an image to a Z-Image latent.
- `tiled` defaults to off so `z_image_denoise`'s control-latent call keeps the behaviour it
- has: a control image is already at generation resolution, not the upscaled frame tiling
- exists for.
+ `z_image_denoise` also encodes its control image here, at generation resolution. That is
+ usually small enough to encode whole, but an upscale's generation resolution is the
+ enlarged frame, so the control field carries its own `tiled` and `tile_size`.
"""
if not isinstance(vae_info.model, AutoencoderKL):
raise TypeError(
diff --git a/invokeai/app/invocations/z_image/z_image_control.py b/invokeai/app/invocations/z_image/z_image_control.py
index 392368944e..226750a094 100644
--- a/invokeai/app/invocations/z_image/z_image_control.py
+++ b/invokeai/app/invocations/z_image/z_image_control.py
@@ -18,6 +18,7 @@ from invokeai.app.invocations.fields import (
from invokeai.app.invocations.model import ModelIdentifierField
from invokeai.app.services.shared.invocation_context import InvocationContext
from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelType
+from invokeai.backend.util.vae_tiling_scope import MIN_TILE_SAMPLE_SIZE
class ZImageControlField(BaseModel):
@@ -43,6 +44,17 @@ class ZImageControlField(BaseModel):
le=1.0,
description="When the control is last applied (% of total steps)",
)
+ tiled: bool = Field(
+ default=False,
+ description="Encode the control image in tiles. The denoise encodes it at generation size, which for an "
+ "upscale is the enlarged frame -- too large for an untiled encode on consumer hardware.",
+ )
+ tile_size: int = Field(
+ default=0,
+ ge=0,
+ multiple_of=8,
+ description="Tile size in pixels for a tiled control encode; 0 uses the VAE's default.",
+ )
@invocation_output("z_image_control_output")
@@ -57,7 +69,7 @@ class ZImageControlOutput(BaseInvocationOutput):
title="Z-Image ControlNet",
tags=["image", "z-image", "control", "controlnet"],
category="conditioning",
- version="1.1.0",
+ version="1.2.0",
classification=Classification.Prototype,
)
class ZImageControlInvocation(BaseInvocation):
@@ -98,6 +110,15 @@ class ZImageControlInvocation(BaseInvocation):
le=1.0,
description="When the control is last applied (% of total steps)",
)
+ tiled: bool = InputField(default=False, description=FieldDescriptions.tiled)
+ # NOTE: tile_size = 0 is a special value, as on the Z-Image VAE nodes: the workflow UI cannot set None.
+ tile_size: int = InputField(
+ default=0,
+ ge=0,
+ multiple_of=8,
+ description=f"{FieldDescriptions.vae_tile_size} Values between 1 and "
+ f"{MIN_TILE_SAMPLE_SIZE} are raised to {MIN_TILE_SAMPLE_SIZE}.",
+ )
def invoke(self, context: InvocationContext) -> ZImageControlOutput:
return ZImageControlOutput(
@@ -107,5 +128,7 @@ class ZImageControlInvocation(BaseInvocation):
control_context_scale=self.control_context_scale,
begin_step_percent=self.begin_step_percent,
end_step_percent=self.end_step_percent,
+ tiled=self.tiled,
+ tile_size=self.tile_size,
)
)
diff --git a/invokeai/app/invocations/z_image/z_image_denoise.py b/invokeai/app/invocations/z_image/z_image_denoise.py
index 66623c3058..6bd2c38e37 100644
--- a/invokeai/app/invocations/z_image/z_image_denoise.py
+++ b/invokeai/app/invocations/z_image/z_image_denoise.py
@@ -627,6 +627,8 @@ class ZImageDenoiseInvocation(BaseInvocation):
control_latents = ZImageImageToLatentsInvocation.vae_encode(
vae_info=vae_info,
image_tensor=control_image_tensor,
+ tiled=self.control.tiled or context.config.get().force_tiled_decode,
+ tile_size=self.control.tile_size,
)
# Move to inference device/dtype
diff --git a/invokeai/app/services/config/config_default.py b/invokeai/app/services/config/config_default.py
index 90cf75be8f..cbb8363878 100644
--- a/invokeai/app/services/config/config_default.py
+++ b/invokeai/app/services/config/config_default.py
@@ -135,7 +135,7 @@ class InvokeAIAppConfig(BaseSettings):
pid_memory_optimization: Enable experimental PiD decode memory optimizations. Roughly halves the peak activation memory of a PiD decode; in exchange the decoded image changes slightly, because neither the chunked pixel pathway nor the float32 sampler intermediates are bit-exact with the default path.
attention_type: Attention type.<br>Valid values: `auto`, `normal`, `xformers`, `sliced`, `torch-sdp`
attention_slice_size: Slice size, valid when attention_type=="sliced".<br>Valid values: `auto`, `balanced`, `max`, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`
- force_tiled_decode: Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty). A tiled decode is not pixel-identical to a single-pass one: a VAE decoder normalises and attends over the whole image, so the difference is spread across it rather than confined to the tile seams. Also tiles the encode. Read by the SD1.5/SDXL, FLUX.1, Z-Image and Qwen-Image VAE nodes, the Anima encode and the Krea-2 style reference; other model families ignore it.
+ force_tiled_decode: Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty). A tiled decode is not pixel-identical to a single-pass one: a VAE decoder normalises and attends over the whole image, so the difference is spread across it rather than confined to the tile seams. Also tiles the encode. Read by the SD1.5/SDXL, FLUX.1, Z-Image and Qwen-Image VAE nodes, the Anima encode, the Z-Image control encode and the Krea-2 style reference; other model families ignore it.
auto_tiled_decode: Decode large images in tiles when an untiled decode's estimated working memory would take most of the GPU's memory (FLUX.1, Z-Image, Qwen-Image, Krea-2 and Wan decodes). Turn off to decode untiled unless tiling is requested; the FLUX.1 and Z-Image decodes then still retry tiled after running out of memory. Anima keeps tiling a decode too large for its GPU either way, because tiling is what makes that case fast there.
pil_compress_level: The compress_level setting of PIL.Image.save(), used for PNG encoding. All settings are lossless. 0 = no compression, 1 = fastest with slightly larger filesize, 9 = slowest with smallest filesize. 1 is typically the best setting.
max_queue_size: Maximum number of items in the session queue.
@@ -269,7 +269,7 @@ class InvokeAIAppConfig(BaseSettings):
pid_memory_optimization: bool = Field(default=False, description="Enable experimental PiD decode memory optimizations. Roughly halves the peak activation memory of a PiD decode; in exchange the decoded image changes slightly, because neither the chunked pixel pathway nor the float32 sampler intermediates are bit-exact with the default path.")
attention_type: ATTENTION_TYPE = Field(default="auto", description="Attention type.")
attention_slice_size: ATTENTION_SLICE_SIZE = Field(default="auto", description='Slice size, valid when attention_type=="sliced".')
- force_tiled_decode: bool = Field(default=False, description="Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty). A tiled decode is not pixel-identical to a single-pass one: a VAE decoder normalises and attends over the whole image, so the difference is spread across it rather than confined to the tile seams. Also tiles the encode. Read by the SD1.5/SDXL, FLUX.1, Z-Image and Qwen-Image VAE nodes, the Anima encode and the Krea-2 style reference; other model families ignore it.")
+ force_tiled_decode: bool = Field(default=False, description="Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty). A tiled decode is not pixel-identical to a single-pass one: a VAE decoder normalises and attends over the whole image, so the difference is spread across it rather than confined to the tile seams. Also tiles the encode. Read by the SD1.5/SDXL, FLUX.1, Z-Image and Qwen-Image VAE nodes, the Anima encode, the Z-Image control encode and the Krea-2 style reference; other model families ignore it.")
auto_tiled_decode: bool = Field(default=True, description="Decode large images in tiles when an untiled decode's estimated working memory would take most of the GPU's memory (FLUX.1, Z-Image, Qwen-Image, Krea-2 and Wan decodes). Turn off to decode untiled unless tiling is requested; the FLUX.1 and Z-Image decodes then still retry tiled after running out of memory. Anima keeps tiling a decode too large for its GPU either way, because tiling is what makes that case fast there.")
pil_compress_level: int = Field(default=1, description="The compress_level setting of PIL.Image.save(), used for PNG encoding. All settings are lossless. 0 = no compression, 1 = fastest with slightly larger filesize, 9 = slowest with smallest filesize. 1 is typically the best setting.")
max_queue_size: int = Field(default=10000, gt=0, description="Maximum number of items in the session queue.")
diff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.json
index 06c65b30c3..6e5b1c9e0d 100644
--- a/invokeai/frontend/api/openapi.json
+++ b/invokeai/frontend/api/openapi.json
@@ -59652,7 +59652,7 @@
"force_tiled_decode": {
"type": "boolean",
"title": "Force Tiled Decode",
- "description": "Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty). A tiled decode is not pixel-identical to a single-pass one: a VAE decoder normalises and attends over the whole image, so the difference is spread across it rather than confined to the tile seams. Also tiles the encode. Read by the SD1.5/SDXL, FLUX.1, Z-Image and Qwen-Image VAE nodes, the Anima encode and the Krea-2 style reference; other model families ignore it.",
+ "description": "Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty). A tiled decode is not pixel-identical to a single-pass one: a VAE decoder normalises and attends over the whole image, so the difference is spread across it rather than confined to the tile seams. Also tiles the encode. Read by the SD1.5/SDXL, FLUX.1, Z-Image and Qwen-Image VAE nodes, the Anima encode, the Z-Image control encode and the Krea-2 style reference; other model families ignore it.",
"default": false
},
"auto_tiled_decode": {
@@ -59979,7 +59979,7 @@
"additionalProperties": false,
"type": "object",
"title": "InvokeAIAppConfig",
- "description": "Invoke's global app configuration.\n\nTypically, you won't need to interact with this class directly. Instead, use the `get_config` function from `invokeai.app.services.config` to get a singleton config object.\n\nAttributes:\n host: IP address to bind to. Use `0.0.0.0` to serve to your local network.\n port: Port to bind to.\n allow_origins: Allowed CORS origins.\n allow_credentials: Allow CORS credentials.\n allow_methods: Methods allowed for CORS.\n allow_headers: Headers allowed for CORS.\n ssl_certfile: SSL certificate file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n ssl_keyfile: SSL key file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n show_donation_link: Show the Donate to InvokeAI link in the frontend menus.\n log_tokenization: Enable logging of parsed prompt tokens.\n patchmatch: Enable patchmatch inpaint code.\n models_dir: Path to the models directory.\n convert_cache_dir: Path to the converted models cache directory (DEPRECATED, but do not delete because it is needed for migration from previous versions).\n download_cache_dir: Path to the directory that contains dynamically downloaded models.\n legacy_conf_dir: Path to directory of legacy checkpoint config files.\n db_dir: Path to InvokeAI databases directory.\n db_url: URL of a MySQL 8.4+ or MariaDB 10.11+ database to use instead of the SQLite database in `db_dir`, e.g. `mariadb+pymysql://invokeai:[email protected]/invokeai`. Needs the `mysql` extra. One InvokeAI process uses a database at a time. Read at startup only.\n db_synchronous: SQLite durability setting. `full`, the default and what InvokeAI has always used, flushes every commit to disk. `normal` acknowledges commits without waiting for that flush - measured at roughly 12x shorter commits on an SSD - and cannot corrupt the database under WAL, which is why it is refused, with a warning, when WAL is unavailable for the database file. What `normal` gives up is the most recent transactions on a power loss or OS crash: a just-written image record or queue status, not the image file itself.<br>Valid values: `full`, `normal`\n outputs_dir: Path to directory for outputs.\n image_subfolder_strategy: Strategy for organizing images into subfolders. 'flat' stores all images in a single folder. 'date' organizes by YYYY/MM/DD. 'type' organizes by image category. 'hash' uses first 2 characters of UUID for filesystem performance.<br>Valid values: `flat`, `date`, `type`, `hash`\n custom_nodes_dir: Path to directory for custom nodes.\n style_presets_dir: Path to directory for style presets.\n workflow_thumbnails_dir: Path to directory for workflow thumbnails.\n log_handlers: Log handler. Valid options are \"console\", \"file=<path>\", \"syslog=path|address:host:port\", \"http=<url>\".\n log_format: Log format. Use \"plain\" for text-only, \"color\" for colorized output, \"legacy\" for 2.3-style logging and \"syslog\" for syslog-style.<br>Valid values: `plain`, `color`, `syslog`, `legacy`\n log_level: Emit logging messages at this level or higher.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n log_sql: Log SQL queries. `log_level` must be `debug` for this to do anything. Extremely verbose.\n log_level_network: Log level for network-related messages. 'info' and 'debug' are very verbose.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n use_memory_db: Use in-memory database. Useful for development.\n dev_reload: Automatically reload when Python sources are changed. Does not reload node definitions.\n profile_graphs: Enable graph profiling using `cProfile`.\n profile_prefix: An optional prefix for profile output files.\n profiles_dir: Path to profiles output directory.\n max_cache_ram_gb: The maximum amount of CPU RAM to use for model caching in GB. If unset, the limit will be configured based on the available RAM. In most cases, it is recommended to leave this unset.\n max_cache_vram_gb: The amount of VRAM to use for model caching in GB. If unset, the limit will be configured based on the available VRAM and the device_working_mem_gb. In most cases, it is recommended to leave this unset.\n reserve_vram_gb: The amount of VRAM (in GB) to subtract from the model cache's available memory budget. Defaults to 0.\n log_memory_usage: If True, a memory snapshot will be captured before and after every model cache operation, and the result will be logged (at debug level). There is a time cost to capturing the memory snapshots, so it is recommended to only enable this feature if you are actively inspecting the model cache's behaviour.\n model_cache_keep_alive_min: How long to keep models in cache after last use, in minutes. A value of 0 (the default) means models are kept in cache indefinitely. If no model generations occur within the timeout period, the model cache is cleared using the same logic as the 'Clear Model Cache' button.\n device_working_mem_gb: The amount of working memory to keep available on the compute device (in GB). Has no effect if running on CPU. If you are experiencing OOM errors, try increasing this value.\n enable_partial_loading: Enable partial loading of models. This enables models to run with reduced VRAM requirements (at the cost of slower speed) by streaming the model from RAM to VRAM as its used. In some edge cases, partial loading can cause models to run more slowly if they were previously being fully loaded into VRAM.\n keep_ram_copy_of_weights: Whether to keep a full RAM copy of a model's weights when the model is loaded in VRAM. Keeping a RAM copy increases average RAM usage, but speeds up model switching and LoRA patching (assuming there is sufficient RAM). Set this to False if RAM pressure is consistently high.\n offload_on_architecture_switch: When a session uses main models of another architecture than the previous one on the same GPU, move every model it does not use from VRAM to RAM before it runs. Models both sessions use stay. Switching back reloads the moved models from RAM, which costs a few seconds per switch when both architectures would have fit in VRAM together; turn this off if you alternate between such models.\n clear_vram_after_session: After every queue item (each image of a batch), move the models held in VRAM to RAM and return the freed memory to the GPU driver. The models stay cached in RAM; the next item reloads them from there, which costs a few seconds (more with keep_ram_copy_of_weights off). Changes nothing where VRAM is system memory (CPU, MPS, integrated GPUs). Turn this on if a generation that runs fine the first time runs out of memory, or slows down sharply because the GPU spills into shared memory, when it is repeated.\n fp8_compute: Keep ComfyUI 'scaled fp8' checkpoints quantized instead of dequantizing them at load, and run their matmuls on the fp8 tensor cores (requires an Ada/SM 8.9 or newer NVIDIA GPU, or a ROCm GPU that passes an fp8 matmul probe; falls back automatically otherwise). Speeds up denoising and keeps the transformer at fp8 size - FP8 Storage alone also keeps it at that size, without the speedup - but quantizes activations as well, so images will differ from previous versions at the same seed. Reproducibility also requires the model to be FULLY resident in VRAM: a layer whose weights are still in RAM falls back to the dequantized path, and since which layers are resident shifts from run to run, the same seed then yields visibly different images. For repeatable output, ensure the model loads at 100% (e.g. enable_partial_loading=false with enough free VRAM).\n fp8_compute_full_precision_hints: Honor the per-layer 'full_precision_matrix_mult' flags that some scaled-fp8 checkpoints ship. Those layers then dequantize on every forward instead of using the fp8 tensor cores, which can cost a large part of the fp8_compute speedup - on checkpoints that mark many layers, most of it. Set to false to run every quantized layer on the fp8 tensor cores, ignoring the producer's instruction; faster, but the marked layers were flagged as numerically sensitive, so quality may suffer. Only has an effect when fp8_compute is enabled.\n ram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_ram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n vram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_vram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n lazy_offload: DEPRECATED: This setting is no longer used. Lazy-offloading is enabled by default. This config setting will be removed once the new model cache behavior is stable.\n pytorch_cuda_alloc_conf: Configure the Torch CUDA memory allocator. This will impact peak reserved VRAM usage and performance. Setting to \"backend:cudaMallocAsync\" works well on many systems. The optimal configuration is highly dependent on the system configuration (device type, VRAM, CUDA driver version, etc.), so must be tuned experimentally. Unset on a ROCm build of PyTorch on Windows, \"expandable_segments:True\" is used.\n device: Preferred execution device. `auto` will choose the device depending on the hardware platform and the installed torch capabilities.<br>Valid values: `auto`, `cpu`, `cuda`, `mps`, `xpu`, `cuda:N`, `xpu:N` (where N is a device number)\n precision: Floating point precision. `float16` will consume half the memory of `float32` but produce slightly lower-quality images. The `auto` setting will guess the proper precision based on your video card and operating system.<br>Valid values: `auto`, `float16`, `bfloat16`, `float32`\n rocm_aotriton_experimental: Use AOTriton's fused (flash and memory-efficient) attention kernels on AMD GPUs that PyTorch marks experimental for them, such as the RX 7600/7700/7800 series, Ryzen AI 300/Max and the RX 9060 series, by setting TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL. Without them, attention on those GPUs runs on the slower math kernel, which also needs far more memory. `auto` turns them on only with a ROCm 10 build of PyTorch, and only when every GPU used for generation is one they were measured correct on (so far gfx1200, the RX 9060 series); `on` and `off` decide for any build and GPU. A TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL value already set in the environment takes precedence. Has no effect on other GPUs.<br>Valid values: `auto`, `on`, `off`\n sequential_guidance: Whether to calculate guidance in serial instead of in parallel, lowering memory requirements.\n noise_dtype: The dtype seeded noise is drawn in for SD1.5/SDXL, SD3, FLUX.1, FLUX.2, CogView4 and the Z-Image seed variance enhancer. `float32` draws the same noise on every platform. `float16` is the half-precision draw of earlier versions: on macOS it keeps the images your seeds gave before this update; on Windows and Linux both values give (nearly) the same images, and images made before the update cannot be reproduced there.<br>Valid values: `float32`, `float16`\n wan_memory_optimization: Enable experimental Wan memory optimizations at the cost of slower generation.\n pid_memory_optimization: Enable experimental PiD decode memory optimizations. Roughly halves the peak activation memory of a PiD decode; in exchange the decoded image changes slightly, because neither the chunked pixel pathway nor the float32 sampler intermediates are bit-exact with the default path.\n attention_type: Attention type.<br>Valid values: `auto`, `normal`, `xformers`, `sliced`, `torch-sdp`\n attention_slice_size: Slice size, valid when attention_type==\"sliced\".<br>Valid values: `auto`, `balanced`, `max`, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`\n force_tiled_decode: Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty). A tiled decode is not pixel-identical to a single-pass one: a VAE decoder normalises and attends over the whole image, so the difference is spread across it rather than confined to the tile seams. Also tiles the encode. Read by the SD1.5/SDXL, FLUX.1, Z-Image and Qwen-Image VAE nodes, the Anima encode and the Krea-2 style reference; other model families ignore it.\n auto_tiled_decode: Decode large images in tiles when an untiled decode's estimated working memory would take most of the GPU's memory (FLUX.1, Z-Image, Qwen-Image, Krea-2 and Wan decodes). Turn off to decode untiled unless tiling is requested; the FLUX.1 and Z-Image decodes then still retry tiled after running out of memory. Anima keeps tiling a decode too large for its GPU either way, because tiling is what makes that case fast there.\n pil_compress_level: The compress_level setting of PIL.Image.save(), used for PNG encoding. All settings are lossless. 0 = no compression, 1 = fastest with slightly larger filesize, 9 = slowest with smallest filesize. 1 is typically the best setting.\n max_queue_size: Maximum number of items in the session queue.\n session_queue_mode: Session queue mode. Use 'FIFO' for traditional first-in-first-out, or 'round_robin' to serve each user's jobs in turn. In single-user mode, FIFO is always used regardless of this setting.<br>Valid values: `FIFO`, `round_robin`\n clear_queue_on_startup: Empties session queue on startup. If true, disables `max_queue_history`.\n max_queue_history: Keep the last N completed, failed, and canceled queue items. Older items are deleted on startup. Set to 0 to prune all terminal items. Ignored if `clear_queue_on_startup` is true.\n allow_nodes: List of nodes to allow. Omit to allow all.\n deny_nodes: List of nodes to deny. Omit to deny none.\n node_cache_size: How many cached nodes to keep in memory.\n hashing_algorithm: Model hashing algorthim for model installs. 'blake3_multi' is best for SSDs. 'blake3_single' is best for spinning disk HDDs. 'random' disables hashing, instead assigning a UUID to models. Useful when using a memory db to reduce model installation time, or if you don't care about storing stable hashes for models. Alternatively, any other hashlib algorithm is accepted, though these are not nearly as performant as blake3.<br>Valid values: `blake3_multi`, `blake3_single`, `random`, `md5`, `sha1`, `sha224`, `sha256`, `sha384`, `sha512`, `blake2b`, `blake2s`, `sha3_224`, `sha3_256`, `sha3_384`, `sha3_512`, `shake_128`, `shake_256`\n remote_api_tokens: List of regular expression and token pairs used when downloading models from URLs. The download URL is tested against the regex, and if it matches, the token is provided in as a Bearer token.\n scan_models_on_startup: Scan the models directory on startup, registering orphaned models. This is typically only used in conjunction with `use_memory_db` for testing purposes.\n allow_private_download_urls: Allow the download queue to fetch from loopback, link-local and private-network addresses. Disabled by default so that a download URL cannot be used to reach services that are only reachable from the server. Enable this only if you install models from a mirror on your own network.\n download_proxy: Optional HTTP proxy for model downloads. The proxy must enforce the public-address policy because proxy-side DNS cannot be checked by InvokeAI.\n unsafe_disable_picklescan: UNSAFE. Disable the picklescan security check during model installation. Recommended only for development and testing purposes. This will allow arbitrary code execution during model installation, so should never be used in production.\n allow_unknown_models: Allow installation of models that we are unable to identify. If enabled, models will be marked as `unknown` in the database, and will not have any metadata associated with them. If disabled, unknown models will be rejected during installation.\n multiuser: Enable multiuser support. When disabled, the application runs in single-user mode using a default system account with administrator privileges. When enabled, requires user authentication and authorization.\n strict_password_checking: Enforce strict password requirements. When True, passwords must contain uppercase, lowercase, and numbers. When False (default), any password is accepted but its strength (weak/moderate/strong) is reported to the user.\n image_index_enabled: Maintain a semantic embedding index of gallery images and videos, used by the image map and semantic search features.\n image_index_model: Name of the installed CLIP Vision or SigLIP model used to embed gallery images and video thumbnails. Changing the model discards embeddings computed by the previous model.\n image_index_device: Set to `cpu` to compute image embeddings on the CPU with a service-local copy of the model - avoids VRAM use and lets indexing run during generations. Any other value is ignored: embeddings otherwise run on the model cache's device, pausing while generations are in progress.\n image_index_batch_size: Number of gallery items embedded per batch by the image index worker.\n external_alibabacloud_api_key: API key for Alibaba Cloud DashScope image generation.\n external_alibabacloud_base_url: Base URL override for Alibaba Cloud DashScope image generation.\n external_atlascloud_api_key: API key for Atlas Cloud image generation.\n external_atlascloud_base_url: Base URL override for Atlas Cloud image generation.\n external_gemini_api_key: API key for Gemini image generation.\n external_openai_api_key: API key for OpenAI image generation.\n external_gemini_base_url: Base URL override for Gemini image generation.\n external_openai_base_url: Base URL override for OpenAI image generation.\n external_seedream_api_key: API key for Seedream image generation.\n external_seedream_base_url: Base URL override for Seedream image generation.\n base_url: Public base path when running behind a reverse proxy under a sub-path, e.g. `/invoke`. Set only when the proxy PRESERVES the sub-path (the backend receives `/invoke/api/...`). Leave unset when the proxy strips the sub-path or when serving at the domain root.\n forwarded_allow_ips: Comma-separated list of IPs (or `*`) allowed to set X-Forwarded-* headers. Set to the reverse proxy's IP. Only used when `base_url` is set.\n http_compression_level: Compression level for gzipped HTTP API responses. 0 disables response compression entirely, 1 is fastest, 9 (the default) is smallest. Compression runs on the event loop and blocks the whole server while it works, and level 9 costs about 5.5x the time of level 1 for 0.4 percentage points of extra compression, so lowering this makes the app noticeably more responsive on large libraries. Set to 0 when a reverse proxy already compresses responses."
+ "description": "Invoke's global app configuration.\n\nTypically, you won't need to interact with this class directly. Instead, use the `get_config` function from `invokeai.app.services.config` to get a singleton config object.\n\nAttributes:\n host: IP address to bind to. Use `0.0.0.0` to serve to your local network.\n port: Port to bind to.\n allow_origins: Allowed CORS origins.\n allow_credentials: Allow CORS credentials.\n allow_methods: Methods allowed for CORS.\n allow_headers: Headers allowed for CORS.\n ssl_certfile: SSL certificate file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n ssl_keyfile: SSL key file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n show_donation_link: Show the Donate to InvokeAI link in the frontend menus.\n log_tokenization: Enable logging of parsed prompt tokens.\n patchmatch: Enable patchmatch inpaint code.\n models_dir: Path to the models directory.\n convert_cache_dir: Path to the converted models cache directory (DEPRECATED, but do not delete because it is needed for migration from previous versions).\n download_cache_dir: Path to the directory that contains dynamically downloaded models.\n legacy_conf_dir: Path to directory of legacy checkpoint config files.\n db_dir: Path to InvokeAI databases directory.\n db_url: URL of a MySQL 8.4+ or MariaDB 10.11+ database to use instead of the SQLite database in `db_dir`, e.g. `mariadb+pymysql://invokeai:[email protected]/invokeai`. Needs the `mysql` extra. One InvokeAI process uses a database at a time. Read at startup only.\n db_synchronous: SQLite durability setting. `full`, the default and what InvokeAI has always used, flushes every commit to disk. `normal` acknowledges commits without waiting for that flush - measured at roughly 12x shorter commits on an SSD - and cannot corrupt the database under WAL, which is why it is refused, with a warning, when WAL is unavailable for the database file. What `normal` gives up is the most recent transactions on a power loss or OS crash: a just-written image record or queue status, not the image file itself.<br>Valid values: `full`, `normal`\n outputs_dir: Path to directory for outputs.\n image_subfolder_strategy: Strategy for organizing images into subfolders. 'flat' stores all images in a single folder. 'date' organizes by YYYY/MM/DD. 'type' organizes by image category. 'hash' uses first 2 characters of UUID for filesystem performance.<br>Valid values: `flat`, `date`, `type`, `hash`\n custom_nodes_dir: Path to directory for custom nodes.\n style_presets_dir: Path to directory for style presets.\n workflow_thumbnails_dir: Path to directory for workflow thumbnails.\n log_handlers: Log handler. Valid options are \"console\", \"file=<path>\", \"syslog=path|address:host:port\", \"http=<url>\".\n log_format: Log format. Use \"plain\" for text-only, \"color\" for colorized output, \"legacy\" for 2.3-style logging and \"syslog\" for syslog-style.<br>Valid values: `plain`, `color`, `syslog`, `legacy`\n log_level: Emit logging messages at this level or higher.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n log_sql: Log SQL queries. `log_level` must be `debug` for this to do anything. Extremely verbose.\n log_level_network: Log level for network-related messages. 'info' and 'debug' are very verbose.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n use_memory_db: Use in-memory database. Useful for development.\n dev_reload: Automatically reload when Python sources are changed. Does not reload node definitions.\n profile_graphs: Enable graph profiling using `cProfile`.\n profile_prefix: An optional prefix for profile output files.\n profiles_dir: Path to profiles output directory.\n max_cache_ram_gb: The maximum amount of CPU RAM to use for model caching in GB. If unset, the limit will be configured based on the available RAM. In most cases, it is recommended to leave this unset.\n max_cache_vram_gb: The amount of VRAM to use for model caching in GB. If unset, the limit will be configured based on the available VRAM and the device_working_mem_gb. In most cases, it is recommended to leave this unset.\n reserve_vram_gb: The amount of VRAM (in GB) to subtract from the model cache's available memory budget. Defaults to 0.\n log_memory_usage: If True, a memory snapshot will be captured before and after every model cache operation, and the result will be logged (at debug level). There is a time cost to capturing the memory snapshots, so it is recommended to only enable this feature if you are actively inspecting the model cache's behaviour.\n model_cache_keep_alive_min: How long to keep models in cache after last use, in minutes. A value of 0 (the default) means models are kept in cache indefinitely. If no model generations occur within the timeout period, the model cache is cleared using the same logic as the 'Clear Model Cache' button.\n device_working_mem_gb: The amount of working memory to keep available on the compute device (in GB). Has no effect if running on CPU. If you are experiencing OOM errors, try increasing this value.\n enable_partial_loading: Enable partial loading of models. This enables models to run with reduced VRAM requirements (at the cost of slower speed) by streaming the model from RAM to VRAM as its used. In some edge cases, partial loading can cause models to run more slowly if they were previously being fully loaded into VRAM.\n keep_ram_copy_of_weights: Whether to keep a full RAM copy of a model's weights when the model is loaded in VRAM. Keeping a RAM copy increases average RAM usage, but speeds up model switching and LoRA patching (assuming there is sufficient RAM). Set this to False if RAM pressure is consistently high.\n offload_on_architecture_switch: When a session uses main models of another architecture than the previous one on the same GPU, move every model it does not use from VRAM to RAM before it runs. Models both sessions use stay. Switching back reloads the moved models from RAM, which costs a few seconds per switch when both architectures would have fit in VRAM together; turn this off if you alternate between such models.\n clear_vram_after_session: After every queue item (each image of a batch), move the models held in VRAM to RAM and return the freed memory to the GPU driver. The models stay cached in RAM; the next item reloads them from there, which costs a few seconds (more with keep_ram_copy_of_weights off). Changes nothing where VRAM is system memory (CPU, MPS, integrated GPUs). Turn this on if a generation that runs fine the first time runs out of memory, or slows down sharply because the GPU spills into shared memory, when it is repeated.\n fp8_compute: Keep ComfyUI 'scaled fp8' checkpoints quantized instead of dequantizing them at load, and run their matmuls on the fp8 tensor cores (requires an Ada/SM 8.9 or newer NVIDIA GPU, or a ROCm GPU that passes an fp8 matmul probe; falls back automatically otherwise). Speeds up denoising and keeps the transformer at fp8 size - FP8 Storage alone also keeps it at that size, without the speedup - but quantizes activations as well, so images will differ from previous versions at the same seed. Reproducibility also requires the model to be FULLY resident in VRAM: a layer whose weights are still in RAM falls back to the dequantized path, and since which layers are resident shifts from run to run, the same seed then yields visibly different images. For repeatable output, ensure the model loads at 100% (e.g. enable_partial_loading=false with enough free VRAM).\n fp8_compute_full_precision_hints: Honor the per-layer 'full_precision_matrix_mult' flags that some scaled-fp8 checkpoints ship. Those layers then dequantize on every forward instead of using the fp8 tensor cores, which can cost a large part of the fp8_compute speedup - on checkpoints that mark many layers, most of it. Set to false to run every quantized layer on the fp8 tensor cores, ignoring the producer's instruction; faster, but the marked layers were flagged as numerically sensitive, so quality may suffer. Only has an effect when fp8_compute is enabled.\n ram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_ram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n vram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_vram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n lazy_offload: DEPRECATED: This setting is no longer used. Lazy-offloading is enabled by default. This config setting will be removed once the new model cache behavior is stable.\n pytorch_cuda_alloc_conf: Configure the Torch CUDA memory allocator. This will impact peak reserved VRAM usage and performance. Setting to \"backend:cudaMallocAsync\" works well on many systems. The optimal configuration is highly dependent on the system configuration (device type, VRAM, CUDA driver version, etc.), so must be tuned experimentally. Unset on a ROCm build of PyTorch on Windows, \"expandable_segments:True\" is used.\n device: Preferred execution device. `auto` will choose the device depending on the hardware platform and the installed torch capabilities.<br>Valid values: `auto`, `cpu`, `cuda`, `mps`, `xpu`, `cuda:N`, `xpu:N` (where N is a device number)\n precision: Floating point precision. `float16` will consume half the memory of `float32` but produce slightly lower-quality images. The `auto` setting will guess the proper precision based on your video card and operating system.<br>Valid values: `auto`, `float16`, `bfloat16`, `float32`\n rocm_aotriton_experimental: Use AOTriton's fused (flash and memory-efficient) attention kernels on AMD GPUs that PyTorch marks experimental for them, such as the RX 7600/7700/7800 series, Ryzen AI 300/Max and the RX 9060 series, by setting TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL. Without them, attention on those GPUs runs on the slower math kernel, which also needs far more memory. `auto` turns them on only with a ROCm 10 build of PyTorch, and only when every GPU used for generation is one they were measured correct on (so far gfx1200, the RX 9060 series); `on` and `off` decide for any build and GPU. A TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL value already set in the environment takes precedence. Has no effect on other GPUs.<br>Valid values: `auto`, `on`, `off`\n sequential_guidance: Whether to calculate guidance in serial instead of in parallel, lowering memory requirements.\n noise_dtype: The dtype seeded noise is drawn in for SD1.5/SDXL, SD3, FLUX.1, FLUX.2, CogView4 and the Z-Image seed variance enhancer. `float32` draws the same noise on every platform. `float16` is the half-precision draw of earlier versions: on macOS it keeps the images your seeds gave before this update; on Windows and Linux both values give (nearly) the same images, and images made before the update cannot be reproduced there.<br>Valid values: `float32`, `float16`\n wan_memory_optimization: Enable experimental Wan memory optimizations at the cost of slower generation.\n pid_memory_optimization: Enable experimental PiD decode memory optimizations. Roughly halves the peak activation memory of a PiD decode; in exchange the decoded image changes slightly, because neither the chunked pixel pathway nor the float32 sampler intermediates are bit-exact with the default path.\n attention_type: Attention type.<br>Valid values: `auto`, `normal`, `xformers`, `sliced`, `torch-sdp`\n attention_slice_size: Slice size, valid when attention_type==\"sliced\".<br>Valid values: `auto`, `balanced`, `max`, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`\n force_tiled_decode: Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty). A tiled decode is not pixel-identical to a single-pass one: a VAE decoder normalises and attends over the whole image, so the difference is spread across it rather than confined to the tile seams. Also tiles the encode. Read by the SD1.5/SDXL, FLUX.1, Z-Image and Qwen-Image VAE nodes, the Anima encode, the Z-Image control encode and the Krea-2 style reference; other model families ignore it.\n auto_tiled_decode: Decode large images in tiles when an untiled decode's estimated working memory would take most of the GPU's memory (FLUX.1, Z-Image, Qwen-Image, Krea-2 and Wan decodes). Turn off to decode untiled unless tiling is requested; the FLUX.1 and Z-Image decodes then still retry tiled after running out of memory. Anima keeps tiling a decode too large for its GPU either way, because tiling is what makes that case fast there.\n pil_compress_level: The compress_level setting of PIL.Image.save(), used for PNG encoding. All settings are lossless. 0 = no compression, 1 = fastest with slightly larger filesize, 9 = slowest with smallest filesize. 1 is typically the best setting.\n max_queue_size: Maximum number of items in the session queue.\n session_queue_mode: Session queue mode. Use 'FIFO' for traditional first-in-first-out, or 'round_robin' to serve each user's jobs in turn. In single-user mode, FIFO is always used regardless of this setting.<br>Valid values: `FIFO`, `round_robin`\n clear_queue_on_startup: Empties session queue on startup. If true, disables `max_queue_history`.\n max_queue_history: Keep the last N completed, failed, and canceled queue items. Older items are deleted on startup. Set to 0 to prune all terminal items. Ignored if `clear_queue_on_startup` is true.\n allow_nodes: List of nodes to allow. Omit to allow all.\n deny_nodes: List of nodes to deny. Omit to deny none.\n node_cache_size: How many cached nodes to keep in memory.\n hashing_algorithm: Model hashing algorthim for model installs. 'blake3_multi' is best for SSDs. 'blake3_single' is best for spinning disk HDDs. 'random' disables hashing, instead assigning a UUID to models. Useful when using a memory db to reduce model installation time, or if you don't care about storing stable hashes for models. Alternatively, any other hashlib algorithm is accepted, though these are not nearly as performant as blake3.<br>Valid values: `blake3_multi`, `blake3_single`, `random`, `md5`, `sha1`, `sha224`, `sha256`, `sha384`, `sha512`, `blake2b`, `blake2s`, `sha3_224`, `sha3_256`, `sha3_384`, `sha3_512`, `shake_128`, `shake_256`\n remote_api_tokens: List of regular expression and token pairs used when downloading models from URLs. The download URL is tested against the regex, and if it matches, the token is provided in as a Bearer token.\n scan_models_on_startup: Scan the models directory on startup, registering orphaned models. This is typically only used in conjunction with `use_memory_db` for testing purposes.\n allow_private_download_urls: Allow the download queue to fetch from loopback, link-local and private-network addresses. Disabled by default so that a download URL cannot be used to reach services that are only reachable from the server. Enable this only if you install models from a mirror on your own network.\n download_proxy: Optional HTTP proxy for model downloads. The proxy must enforce the public-address policy because proxy-side DNS cannot be checked by InvokeAI.\n unsafe_disable_picklescan: UNSAFE. Disable the picklescan security check during model installation. Recommended only for development and testing purposes. This will allow arbitrary code execution during model installation, so should never be used in production.\n allow_unknown_models: Allow installation of models that we are unable to identify. If enabled, models will be marked as `unknown` in the database, and will not have any metadata associated with them. If disabled, unknown models will be rejected during installation.\n multiuser: Enable multiuser support. When disabled, the application runs in single-user mode using a default system account with administrator privileges. When enabled, requires user authentication and authorization.\n strict_password_checking: Enforce strict password requirements. When True, passwords must contain uppercase, lowercase, and numbers. When False (default), any password is accepted but its strength (weak/moderate/strong) is reported to the user.\n image_index_enabled: Maintain a semantic embedding index of gallery images and videos, used by the image map and semantic search features.\n image_index_model: Name of the installed CLIP Vision or SigLIP model used to embed gallery images and video thumbnails. Changing the model discards embeddings computed by the previous model.\n image_index_device: Set to `cpu` to compute image embeddings on the CPU with a service-local copy of the model - avoids VRAM use and lets indexing run during generations. Any other value is ignored: embeddings otherwise run on the model cache's device, pausing while generations are in progress.\n image_index_batch_size: Number of gallery items embedded per batch by the image index worker.\n external_alibabacloud_api_key: API key for Alibaba Cloud DashScope image generation.\n external_alibabacloud_base_url: Base URL override for Alibaba Cloud DashScope image generation.\n external_atlascloud_api_key: API key for Atlas Cloud image generation.\n external_atlascloud_base_url: Base URL override for Atlas Cloud image generation.\n external_gemini_api_key: API key for Gemini image generation.\n external_openai_api_key: API key for OpenAI image generation.\n external_gemini_base_url: Base URL override for Gemini image generation.\n external_openai_base_url: Base URL override for OpenAI image generation.\n external_seedream_api_key: API key for Seedream image generation.\n external_seedream_base_url: Base URL override for Seedream image generation.\n base_url: Public base path when running behind a reverse proxy under a sub-path, e.g. `/invoke`. Set only when the proxy PRESERVES the sub-path (the backend receives `/invoke/api/...`). Leave unset when the proxy strips the sub-path or when serving at the domain root.\n forwarded_allow_ips: Comma-separated list of IPs (or `*`) allowed to set X-Forwarded-* headers. Set to the reverse proxy's IP. Only used when `base_url` is set.\n http_compression_level: Compression level for gzipped HTTP API responses. 0 disables response compression entirely, 1 is fastest, 9 (the default) is smallest. Compression runs on the event loop and blocks the whole server while it works, and level 9 costs about 5.5x the time of level 1 for 0.4 percentage points of extra compression, so lowering this makes the app noticeably more responsive on large libraries. Set to 0 when a reverse proxy already compresses responses."
},
"InvokeAIAppConfigWithSetFields": {
"properties": {
@@ -113623,6 +113623,20 @@
"minimum": 0.0,
"title": "End Step Percent",
"type": "number"
+ },
+ "tiled": {
+ "default": false,
+ "description": "Encode the control image in tiles. The denoise encodes it at generation size, which for an upscale is the enlarged frame -- too large for an untiled encode on consumer hardware.",
+ "title": "Tiled",
+ "type": "boolean"
+ },
+ "tile_size": {
+ "default": 0,
+ "description": "Tile size in pixels for a tiled control encode; 0 uses the VAE's default.",
+ "minimum": 0,
+ "multipleOf": 8,
+ "title": "Tile Size",
+ "type": "integer"
}
},
"required": ["image_name", "control_model"],
@@ -113729,6 +113743,28 @@
"title": "End Step Percent",
"type": "number"
},
+ "tiled": {
+ "default": false,
+ "description": "Processing using overlapping tiles (reduce memory consumption)",
+ "field_kind": "input",
+ "input": "any",
+ "orig_default": false,
+ "orig_required": false,
+ "title": "Tiled",
+ "type": "boolean"
+ },
+ "tile_size": {
+ "default": 0,
+ "description": "The tile size for VAE tiling in pixels (image space). If set to 0, the default tile size for the model will be used. Larger tile sizes generally produce better results at the cost of higher memory usage. Values between 1 and 128 are raised to 128.",
+ "field_kind": "input",
+ "input": "any",
+ "minimum": 0,
+ "multipleOf": 8,
+ "orig_default": 0,
+ "orig_required": false,
+ "title": "Tile Size",
+ "type": "integer"
+ },
"type": {
"const": "z_image_control",
"default": "z_image_control",
@@ -113741,7 +113777,7 @@
"tags": ["image", "z-image", "control", "controlnet"],
"title": "Z-Image ControlNet",
"type": "object",
- "version": "1.1.0",
+ "version": "1.2.0",
"output": {
"$ref": "#/components/schemas/ZImageControlOutput"
}
diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.ts
index f4c062c0db..40a9dc2b90 100644
--- a/invokeai/frontend/api/schema.ts
+++ b/invokeai/frontend/api/schema.ts
@@ -22672,7 +22672,7 @@ export type components = {
* pid_memory_optimization: Enable experimental PiD decode memory optimizations. Roughly halves the peak activation memory of a PiD decode; in exchange the decoded image changes slightly, because neither the chunked pixel pathway nor the float32 sampler intermediates are bit-exact with the default path.
* attention_type: Attention type.<br>Valid values: `auto`, `normal`, `xformers`, `sliced`, `torch-sdp`
* attention_slice_size: Slice size, valid when attention_type=="sliced".<br>Valid values: `auto`, `balanced`, `max`, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`
- * force_tiled_decode: Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty). A tiled decode is not pixel-identical to a single-pass one: a VAE decoder normalises and attends over the whole image, so the difference is spread across it rather than confined to the tile seams. Also tiles the encode. Read by the SD1.5/SDXL, FLUX.1, Z-Image and Qwen-Image VAE nodes, the Anima encode and the Krea-2 style reference; other model families ignore it.
+ * force_tiled_decode: Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty). A tiled decode is not pixel-identical to a single-pass one: a VAE decoder normalises and attends over the whole image, so the difference is spread across it rather than confined to the tile seams. Also tiles the encode. Read by the SD1.5/SDXL, FLUX.1, Z-Image and Qwen-Image VAE nodes, the Anima encode, the Z-Image control encode and the Krea-2 style reference; other model families ignore it.
* auto_tiled_decode: Decode large images in tiles when an untiled decode's estimated working memory would take most of the GPU's memory (FLUX.1, Z-Image, Qwen-Image, Krea-2 and Wan decodes). Turn off to decode untiled unless tiling is requested; the FLUX.1 and Z-Image decodes then still retry tiled after running out of memory. Anima keeps tiling a decode too large for its GPU either way, because tiling is what makes that case fast there.
* pil_compress_level: The compress_level setting of PIL.Image.save(), used for PNG encoding. All settings are lossless. 0 = no compression, 1 = fastest with slightly larger filesize, 9 = slowest with smallest filesize. 1 is typically the best setting.
* max_queue_size: Maximum number of items in the session queue.
@@ -23143,7 +23143,7 @@ export type components = {
attention_slice_size?: "auto" | "balanced" | "max" | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;
/**
* Force Tiled Decode
- * @description Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty). A tiled decode is not pixel-identical to a single-pass one: a VAE decoder normalises and attends over the whole image, so the difference is spread across it rather than confined to the tile seams. Also tiles the encode. Read by the SD1.5/SDXL, FLUX.1, Z-Image and Qwen-Image VAE nodes, the Anima encode and the Krea-2 style reference; other model families ignore it.
+ * @description Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty). A tiled decode is not pixel-identical to a single-pass one: a VAE decoder normalises and attends over the whole image, so the difference is spread across it rather than confined to the tile seams. Also tiles the encode. Read by the SD1.5/SDXL, FLUX.1, Z-Image and Qwen-Image VAE nodes, the Anima encode, the Z-Image control encode and the Krea-2 style reference; other model families ignore it.
* @default false
*/
force_tiled_decode?: boolean;
@@ -51418,6 +51418,18 @@ export type components = {
* @default 1
*/
end_step_percent?: number;
+ /**
+ * Tiled
+ * @description Encode the control image in tiles. The denoise encodes it at generation size, which for an upscale is the enlarged frame -- too large for an untiled encode on consumer hardware.
+ * @default false
+ */
+ tiled?: boolean;
+ /**
+ * Tile Size
+ * @description Tile size in pixels for a tiled control encode; 0 uses the VAE's default.
+ * @default 0
+ */
+ tile_size?: number;
};
/**
* Z-Image ControlNet
@@ -51476,6 +51488,18 @@ export type components = {
* @default 1
*/
end_step_percent?: number;
+ /**
+ * Tiled
+ * @description Processing using overlapping tiles (reduce memory consumption)
+ * @default false
+ */
+ tiled?: boolean;
+ /**
+ * Tile Size
+ * @description The tile size for VAE tiling in pixels (image space). If set to 0, the default tile size for the model will be used. Larger tile sizes generally produce better results at the cost of higher memory usage. Values between 1 and 128 are raised to 128.
+ * @default 0
+ */
+ tile_size?: number;
/**
* type
* @default z_image_control
diff --git a/invokeai/frontend/webv2/.oxfmtrc.json b/invokeai/frontend/webv2/.oxfmtrc.json
index 8efc1a798e..b4548ee4ca 100644
--- a/invokeai/frontend/webv2/.oxfmtrc.json
+++ b/invokeai/frontend/webv2/.oxfmtrc.json
@@ -11,6 +11,8 @@
"src/features/generation/core/__snapshots__/generateGraphNodeTypes.json",
"src/features/generation/core/__snapshots__/animaLLLiteCanvasGraphs.json",
"src/features/video/core/__snapshots__/videoGraphNodeTypes.json",
+ "src/features/upscale/core/__snapshots__/upscaleGraphNodeTypes.json",
+ "src/features/upscale/core/__snapshots__/upscaleIndexClippedStarts.json",
"src/features/generation/core/__fixtures__/architectureCapabilities.json"
],
"printWidth": 120,
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 728a9fad1f..5a894c0641 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -959,6 +959,18 @@
"Compel and Dynamic Prompts syntaxes and embeddings."
]
},
+ "qwen35Encoder": {
+ "heading": "Qwen3.5 Encoder",
+ "paragraphs": [
+ "Anima-3.8B's prompt adapter also reads a Qwen3.5 4B text encoder. The checkpoint does not carry one, so it has to be selected here."
+ ]
+ },
+ "qwen3Encoder": {
+ "heading": "Qwen3 Encoder",
+ "paragraphs": [
+ "Z-Image and Anima read your prompt with a Qwen3 text encoder: Z-Image with the 4B, Anima with the 0.6B. A bare checkpoint does not carry one, so it has to be selected here."
+ ]
+ },
"referenceImage": {
"heading": "Global Reference Image",
"paragraphs": ["Applies a reference image to influence the entire generation."]
@@ -2725,10 +2737,19 @@
"selectT5Encoder": "Select a T5 encoder",
"t5Encoder": "T5 Encoder",
"t5EncoderRequired": "This model needs a T5 encoder selected.",
+ "qwen3Encoder": "Qwen3 Encoder",
+ "qwen3EncoderRequired": "This model needs a Qwen3 encoder selected.",
+ "selectQwen3Encoder": "Select a Qwen3 encoder",
+ "qwen35Encoder": "Qwen3.5 Encoder",
+ "qwen35EncoderRequired": "This model needs a Qwen3.5 encoder selected.",
+ "selectQwen35Encoder": "Select a Qwen3.5 encoder",
+ "negativePromptCfgGated": "Used only when CFG is greater than 1.",
"vaeRequired": "This model needs a VAE selected.",
"tileControlNet": "Tile ControlNet",
"tileControlNetHelp": "Guides detail generation with the source image and must match the main model architecture.",
"tileControlNetRequired": "Select a compatible Tile or Union ControlNet.",
+ "tileControlNetOptionalHelp": "Optional. Holds the result to the source image; Structure sets how firmly.",
+ "selectOptionalTileControlNet": "None (Creativity alone anchors the pass)",
"tileOverlap": "Tile overlap",
"tileOverlapHelp": "More overlap reduces seams but increases processing and memory use.",
"tileSize": "Tile size",
diff --git a/invokeai/frontend/webv2/src/features/generation/settings.ts b/invokeai/frontend/webv2/src/features/generation/settings.ts
index 8561bbc1a9..088197489f 100644
--- a/invokeai/frontend/webv2/src/features/generation/settings.ts
+++ b/invokeai/frontend/webv2/src/features/generation/settings.ts
@@ -44,6 +44,7 @@ export {
getGenerationValidationReasons,
getMaxReferenceImages,
getPromptHistoryRecallPatch,
+ getSchedulerOptions,
getSettingsWithModelDefaults,
isArchitectureDescribed,
isGenerateModelSelectable,
@@ -61,7 +62,11 @@ export {
} from './core/resolveGenerateWidgetValues';
export {
getCompatibleDiffusersComponentSource,
+ isAnimaQwen35Encoder,
+ isAnimaQwen3Encoder,
+ isBundledMainForBase,
isDiffusersMainForBase,
+ isNonAnimaQwen3Encoder,
isVaeAcceptedByBase,
isVaeCompatibleWithGenerateModel,
} from './core/componentCompatibility';
diff --git a/invokeai/frontend/webv2/src/features/upscale/core/__snapshots__/upscaleGraphNodeTypes.json b/invokeai/frontend/webv2/src/features/upscale/core/__snapshots__/upscaleGraphNodeTypes.json
new file mode 100644
index 0000000000..d0ea989f0f
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/upscale/core/__snapshots__/upscaleGraphNodeTypes.json
@@ -0,0 +1,1145 @@
+{
+ "connections": [
+ "anima_denoise latents anima_l2i latents",
+ "anima_i2l latents anima_denoise latents",
+ "anima_lora_collection_loader qwen3_encoder anima_text_encoder qwen3_encoder",
+ "anima_lora_collection_loader transformer anima_denoise transformer",
+ "anima_model_loader qwen3_5_encoder anima_text_encoder qwen3_5_encoder",
+ "anima_model_loader qwen3_encoder anima_lora_collection_loader qwen3_encoder",
+ "anima_model_loader transformer anima_lora_collection_loader transformer",
+ "anima_model_loader vae anima_i2l vae",
+ "anima_model_loader vae anima_l2i vae",
+ "anima_text_encoder conditioning collect item",
+ "clip_skip clip lora_collection_loader clip",
+ "collect collection anima_denoise negative_conditioning",
+ "collect collection anima_denoise positive_conditioning",
+ "collect collection anima_lora_collection_loader loras",
+ "collect collection flux_denoise positive_text_conditioning",
+ "collect collection flux_lora_collection_loader loras",
+ "collect collection lora_collection_loader loras",
+ "collect collection sdxl_lora_collection_loader loras",
+ "collect collection tiled_multi_diffusion_denoise_latents control",
+ "collect collection z_image_denoise negative_conditioning",
+ "collect collection z_image_denoise positive_conditioning",
+ "collect collection z_image_lora_collection_loader loras",
+ "compel conditioning tiled_multi_diffusion_denoise_latents negative_conditioning",
+ "compel conditioning tiled_multi_diffusion_denoise_latents positive_conditioning",
+ "controlnet control collect item",
+ "core_metadata metadata anima_l2i metadata",
+ "core_metadata metadata flux_vae_decode metadata",
+ "core_metadata metadata l2i metadata",
+ "core_metadata metadata z_image_l2i metadata",
+ "flux_denoise latents flux_vae_decode latents",
+ "flux_lora_collection_loader clip flux_text_encoder clip",
+ "flux_lora_collection_loader t5_encoder flux_text_encoder t5_encoder",
+ "flux_lora_collection_loader transformer flux_denoise transformer",
+ "flux_model_loader clip flux_lora_collection_loader clip",
+ "flux_model_loader max_seq_len flux_text_encoder t5_max_seq_len",
+ "flux_model_loader t5_encoder flux_lora_collection_loader t5_encoder",
+ "flux_model_loader transformer flux_lora_collection_loader transformer",
+ "flux_model_loader vae flux_vae_decode vae",
+ "flux_model_loader vae flux_vae_encode vae",
+ "flux_text_encoder conditioning collect item",
+ "flux_vae_encode latents flux_denoise latents",
+ "i2l latents tiled_multi_diffusion_denoise_latents latents",
+ "img_resize image anima_i2l image",
+ "img_resize image flux_vae_encode image",
+ "img_resize image z_image_control image",
+ "img_resize image z_image_i2l image",
+ "integer value anima_denoise seed",
+ "integer value core_metadata seed",
+ "integer value flux_denoise seed",
+ "integer value noise seed",
+ "integer value z_image_denoise seed",
+ "lora_collection_loader clip compel clip",
+ "lora_collection_loader unet tiled_multi_diffusion_denoise_latents unet",
+ "lora_selector lora collect item",
+ "main_model_loader clip clip_skip clip",
+ "main_model_loader unet lora_collection_loader unet",
+ "main_model_loader vae i2l vae",
+ "main_model_loader vae l2i vae",
+ "noise noise tiled_multi_diffusion_denoise_latents noise",
+ "sdxl_compel_prompt conditioning tiled_multi_diffusion_denoise_latents negative_conditioning",
+ "sdxl_compel_prompt conditioning tiled_multi_diffusion_denoise_latents positive_conditioning",
+ "sdxl_lora_collection_loader clip sdxl_compel_prompt clip",
+ "sdxl_lora_collection_loader clip2 sdxl_compel_prompt clip2",
+ "sdxl_lora_collection_loader unet tiled_multi_diffusion_denoise_latents unet",
+ "sdxl_model_loader clip sdxl_lora_collection_loader clip",
+ "sdxl_model_loader clip2 sdxl_lora_collection_loader clip2",
+ "sdxl_model_loader unet sdxl_lora_collection_loader unet",
+ "sdxl_model_loader vae i2l vae",
+ "sdxl_model_loader vae l2i vae",
+ "spandrel_image_to_image_autoscale height core_metadata height",
+ "spandrel_image_to_image_autoscale image unsharp_mask image",
+ "spandrel_image_to_image_autoscale width core_metadata width",
+ "string value anima_text_encoder prompt",
+ "string value compel prompt",
+ "string value core_metadata negative_prompt",
+ "string value core_metadata positive_prompt",
+ "string value flux_text_encoder prompt",
+ "string value sdxl_compel_prompt prompt",
+ "string value sdxl_compel_prompt style",
+ "string value z_image_text_encoder prompt",
+ "tiled_multi_diffusion_denoise_latents latents l2i latents",
+ "unsharp_mask height noise height",
+ "unsharp_mask image controlnet image",
+ "unsharp_mask image i2l image",
+ "unsharp_mask image img_resize image",
+ "unsharp_mask width noise width",
+ "z_image_control control z_image_denoise control",
+ "z_image_denoise latents z_image_l2i latents",
+ "z_image_i2l latents z_image_denoise latents",
+ "z_image_lora_collection_loader qwen3_encoder z_image_text_encoder qwen3_encoder",
+ "z_image_lora_collection_loader transformer z_image_denoise transformer",
+ "z_image_model_loader qwen3_encoder z_image_lora_collection_loader qwen3_encoder",
+ "z_image_model_loader transformer z_image_lora_collection_loader transformer",
+ "z_image_model_loader vae z_image_denoise vae",
+ "z_image_model_loader vae z_image_i2l vae",
+ "z_image_model_loader vae z_image_l2i vae",
+ "z_image_text_encoder conditioning collect item"
+ ],
+ "_comment": "Generated by src/features/upscale/core/upscaleGraphCoverage.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, and every connection for whether the backend considers the two field types compatible. 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": {
+ "nodeTypes": [
+ "clip_skip",
+ "collect",
+ "compel",
+ "controlnet",
+ "core_metadata",
+ "i2l",
+ "integer",
+ "l2i",
+ "lora_collection_loader",
+ "lora_selector",
+ "main_model_loader",
+ "noise",
+ "spandrel_image_to_image_autoscale",
+ "string",
+ "tiled_multi_diffusion_denoise_latents",
+ "unsharp_mask"
+ ]
+ },
+ "sdxl": {
+ "nodeTypes": [
+ "collect",
+ "controlnet",
+ "core_metadata",
+ "i2l",
+ "integer",
+ "l2i",
+ "lora_selector",
+ "noise",
+ "sdxl_compel_prompt",
+ "sdxl_lora_collection_loader",
+ "sdxl_model_loader",
+ "spandrel_image_to_image_autoscale",
+ "string",
+ "tiled_multi_diffusion_denoise_latents",
+ "unsharp_mask"
+ ]
+ },
+ "flux": {
+ "nodeTypes": [
+ "collect",
+ "core_metadata",
+ "flux_denoise",
+ "flux_lora_collection_loader",
+ "flux_model_loader",
+ "flux_text_encoder",
+ "flux_vae_decode",
+ "flux_vae_encode",
+ "img_resize",
+ "integer",
+ "lora_selector",
+ "spandrel_image_to_image_autoscale",
+ "string",
+ "unsharp_mask"
+ ]
+ },
+ "z-image": {
+ "nodeTypes": [
+ "collect",
+ "core_metadata",
+ "img_resize",
+ "integer",
+ "lora_selector",
+ "spandrel_image_to_image_autoscale",
+ "string",
+ "unsharp_mask",
+ "z_image_control",
+ "z_image_denoise",
+ "z_image_i2l",
+ "z_image_l2i",
+ "z_image_lora_collection_loader",
+ "z_image_model_loader",
+ "z_image_text_encoder"
+ ]
+ },
+ "anima": {
+ "nodeTypes": [
+ "anima_denoise",
+ "anima_i2l",
+ "anima_l2i",
+ "anima_lora_collection_loader",
+ "anima_model_loader",
+ "anima_text_encoder",
+ "collect",
+ "core_metadata",
+ "img_resize",
+ "integer",
+ "lora_selector",
+ "spandrel_image_to_image_autoscale",
+ "string",
+ "unsharp_mask"
+ ]
+ }
+ },
+ "fieldsByNodeType": {
+ "anima_denoise": {
+ "inputs": [
+ "latents",
+ "negative_conditioning",
+ "positive_conditioning",
+ "seed",
+ "transformer"
+ ],
+ "literalInputs": {
+ "denoising_end": [
+ 1
+ ],
+ "denoising_start": [
+ 0.75
+ ],
+ "guidance_scale": [
+ 4.5,
+ 6
+ ],
+ "height": [
+ 400
+ ],
+ "is_intermediate": [
+ true
+ ],
+ "scheduler": [
+ "euler"
+ ],
+ "steps": [
+ 30
+ ],
+ "use_cache": [
+ true
+ ],
+ "width": [
+ 808
+ ]
+ },
+ "outputs": [
+ "latents"
+ ]
+ },
+ "anima_i2l": {
+ "inputs": [
+ "image",
+ "vae"
+ ],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "tile_size": [
+ 1024
+ ],
+ "tiled": [
+ true
+ ],
+ "use_cache": [
+ true
+ ]
+ },
+ "outputs": [
+ "latents"
+ ]
+ },
+ "anima_l2i": {
+ "inputs": [
+ "latents",
+ "metadata",
+ "vae"
+ ],
+ "literalInputs": {
+ "is_intermediate": [
+ false
+ ],
+ "use_cache": [
+ false
+ ]
+ },
+ "outputs": []
+ },
+ "anima_lora_collection_loader": {
+ "inputs": [
+ "loras",
+ "qwen3_encoder",
+ "transformer"
+ ],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "use_cache": [
+ true
+ ]
+ },
+ "outputs": [
+ "qwen3_encoder",
+ "transformer"
+ ]
+ },
+ "anima_model_loader": {
+ "inputs": [],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "model": [],
+ "qwen3_5_encoder_model": [],
+ "qwen3_encoder_model": [],
+ "use_cache": [
+ true
+ ],
+ "vae_model": []
+ },
+ "outputs": [
+ "qwen3_5_encoder",
+ "qwen3_encoder",
+ "transformer",
+ "vae"
+ ]
+ },
+ "anima_text_encoder": {
+ "inputs": [
+ "prompt",
+ "qwen3_5_encoder",
+ "qwen3_encoder"
+ ],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "use_cache": [
+ true
+ ]
+ },
+ "outputs": [
+ "conditioning"
+ ]
+ },
+ "clip_skip": {
+ "inputs": [
+ "clip"
+ ],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "skipped_layers": [
+ 0
+ ],
+ "use_cache": [
+ true
+ ]
+ },
+ "outputs": [
+ "clip"
+ ]
+ },
+ "collect": {
+ "inputs": [
+ "item"
+ ],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "use_cache": [
+ true
+ ]
+ },
+ "outputs": [
+ "collection"
+ ]
+ },
+ "compel": {
+ "inputs": [
+ "clip",
+ "prompt"
+ ],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "use_cache": [
+ true
+ ]
+ },
+ "outputs": [
+ "conditioning"
+ ]
+ },
+ "controlnet": {
+ "inputs": [
+ "image"
+ ],
+ "literalInputs": {
+ "begin_step_percent": [
+ 0,
+ 0.55
+ ],
+ "control_mode": [
+ "balanced"
+ ],
+ "control_model": [],
+ "control_weight": [
+ 0.21375,
+ 0.625
+ ],
+ "end_step_percent": [
+ 0.55,
+ 0.85
+ ],
+ "is_intermediate": [
+ true
+ ],
+ "resize_mode": [
+ "just_resize"
+ ],
+ "use_cache": [
+ true
+ ]
+ },
+ "outputs": [
+ "control"
+ ]
+ },
+ "core_metadata": {
+ "inputs": [
+ "height",
+ "negative_prompt",
+ "positive_prompt",
+ "seed",
+ "width"
+ ],
+ "literalInputs": {
+ "cfg_scale": [
+ 1,
+ 2,
+ 4,
+ 4.5,
+ 6
+ ],
+ "clip_embed_model": [],
+ "creativity": [
+ 0
+ ],
+ "guidance": [
+ 2
+ ],
+ "is_intermediate": [
+ true
+ ],
+ "loras": [],
+ "model": [],
+ "qwen3_5_encoder": [],
+ "qwen3_encoder": [],
+ "rand_device": [
+ "cpu"
+ ],
+ "scheduler": [
+ "euler",
+ "kdpm_2"
+ ],
+ "steps": [
+ 30
+ ],
+ "structure": [
+ 0
+ ],
+ "t5_encoder": [],
+ "tile_overlap": [
+ 128
+ ],
+ "tile_size": [
+ 1024
+ ],
+ "upscale_initial_image": [],
+ "upscale_model": [],
+ "upscale_scale": [
+ 4
+ ],
+ "use_cache": [
+ true
+ ],
+ "vae": []
+ },
+ "outputs": [
+ "metadata"
+ ]
+ },
+ "flux_denoise": {
+ "inputs": [
+ "latents",
+ "positive_text_conditioning",
+ "seed",
+ "transformer"
+ ],
+ "literalInputs": {
+ "denoising_end": [
+ 1
+ ],
+ "denoising_start": [
+ 0.49900000000000005
+ ],
+ "guidance": [
+ 2
+ ],
+ "height": [
+ 400
+ ],
+ "is_intermediate": [
+ true
+ ],
+ "num_steps": [
+ 30
+ ],
+ "scheduler": [
+ "euler"
+ ],
+ "use_cache": [
+ true
+ ],
+ "width": [
+ 800
+ ]
+ },
+ "outputs": [
+ "latents"
+ ]
+ },
+ "flux_lora_collection_loader": {
+ "inputs": [
+ "clip",
+ "loras",
+ "t5_encoder",
+ "transformer"
+ ],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "use_cache": [
+ true
+ ]
+ },
+ "outputs": [
+ "clip",
+ "t5_encoder",
+ "transformer"
+ ]
+ },
+ "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",
+ "t5_encoder",
+ "transformer",
+ "vae"
+ ]
+ },
+ "flux_text_encoder": {
+ "inputs": [
+ "clip",
+ "prompt",
+ "t5_encoder",
+ "t5_max_seq_len"
+ ],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "use_cache": [
+ true
+ ]
+ },
+ "outputs": [
+ "conditioning"
+ ]
+ },
+ "flux_vae_decode": {
+ "inputs": [
+ "latents",
+ "metadata",
+ "vae"
+ ],
+ "literalInputs": {
+ "is_intermediate": [
+ false
+ ],
+ "tile_size": [
+ 1024
+ ],
+ "tiled": [
+ true
+ ],
+ "use_cache": [
+ false
+ ]
+ },
+ "outputs": []
+ },
+ "flux_vae_encode": {
+ "inputs": [
+ "image",
+ "vae"
+ ],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "tile_size": [
+ 1024
+ ],
+ "tiled": [
+ true
+ ],
+ "use_cache": [
+ true
+ ]
+ },
+ "outputs": [
+ "latents"
+ ]
+ },
+ "i2l": {
+ "inputs": [
+ "image",
+ "vae"
+ ],
+ "literalInputs": {
+ "fp32": [
+ true
+ ],
+ "is_intermediate": [
+ true
+ ],
+ "tile_size": [
+ 1024
+ ],
+ "tiled": [
+ true
+ ],
+ "use_cache": [
+ true
+ ]
+ },
+ "outputs": [
+ "latents"
+ ]
+ },
+ "img_resize": {
+ "inputs": [
+ "image"
+ ],
+ "literalInputs": {
+ "height": [
+ 400
+ ],
+ "is_intermediate": [
+ true
+ ],
+ "resample_mode": [
+ "bicubic"
+ ],
+ "use_cache": [
+ true
+ ],
+ "width": [
+ 800,
+ 808
+ ]
+ },
+ "outputs": [
+ "image"
+ ]
+ },
+ "integer": {
+ "inputs": [],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "use_cache": [
+ true
+ ]
+ },
+ "outputs": [
+ "value"
+ ]
+ },
+ "l2i": {
+ "inputs": [
+ "latents",
+ "metadata",
+ "vae"
+ ],
+ "literalInputs": {
+ "fp32": [
+ true
+ ],
+ "is_intermediate": [
+ false
+ ],
+ "tile_size": [
+ 1024
+ ],
+ "tiled": [
+ true
+ ],
+ "use_cache": [
+ false
+ ]
+ },
+ "outputs": []
+ },
+ "lora_collection_loader": {
+ "inputs": [
+ "clip",
+ "loras",
+ "unet"
+ ],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "use_cache": [
+ true
+ ]
+ },
+ "outputs": [
+ "clip",
+ "unet"
+ ]
+ },
+ "lora_selector": {
+ "inputs": [],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "lora": [],
+ "use_cache": [
+ true
+ ],
+ "weight": [
+ 1
+ ]
+ },
+ "outputs": [
+ "lora"
+ ]
+ },
+ "main_model_loader": {
+ "inputs": [],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "model": [],
+ "use_cache": [
+ true
+ ]
+ },
+ "outputs": [
+ "clip",
+ "unet",
+ "vae"
+ ]
+ },
+ "noise": {
+ "inputs": [
+ "height",
+ "seed",
+ "width"
+ ],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "use_cache": [
+ true
+ ],
+ "use_cpu": [
+ true
+ ]
+ },
+ "outputs": [
+ "noise"
+ ]
+ },
+ "sdxl_compel_prompt": {
+ "inputs": [
+ "clip",
+ "clip2",
+ "prompt",
+ "style"
+ ],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "use_cache": [
+ true
+ ]
+ },
+ "outputs": [
+ "conditioning"
+ ]
+ },
+ "sdxl_lora_collection_loader": {
+ "inputs": [
+ "clip",
+ "clip2",
+ "loras",
+ "unet"
+ ],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "use_cache": [
+ true
+ ]
+ },
+ "outputs": [
+ "clip",
+ "clip2",
+ "unet"
+ ]
+ },
+ "sdxl_model_loader": {
+ "inputs": [],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "model": [],
+ "use_cache": [
+ true
+ ]
+ },
+ "outputs": [
+ "clip",
+ "clip2",
+ "unet",
+ "vae"
+ ]
+ },
+ "spandrel_image_to_image_autoscale": {
+ "inputs": [],
+ "literalInputs": {
+ "fit_to_multiple_of_8": [
+ true
+ ],
+ "image": [],
+ "image_to_image_model": [],
+ "is_intermediate": [
+ true
+ ],
+ "scale": [
+ 4
+ ],
+ "use_cache": [
+ true
+ ]
+ },
+ "outputs": [
+ "height",
+ "image",
+ "width"
+ ]
+ },
+ "string": {
+ "inputs": [],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "use_cache": [
+ true
+ ]
+ },
+ "outputs": [
+ "value"
+ ]
+ },
+ "tiled_multi_diffusion_denoise_latents": {
+ "inputs": [
+ "control",
+ "latents",
+ "negative_conditioning",
+ "noise",
+ "positive_conditioning",
+ "unet"
+ ],
+ "literalInputs": {
+ "cfg_scale": [
+ 2
+ ],
+ "denoising_end": [
+ 1
+ ],
+ "denoising_start": [
+ 0.49900000000000005
+ ],
+ "is_intermediate": [
+ true
+ ],
+ "scheduler": [
+ "kdpm_2"
+ ],
+ "steps": [
+ 30
+ ],
+ "tile_height": [
+ 1024
+ ],
+ "tile_overlap": [
+ 128
+ ],
+ "tile_width": [
+ 1024
+ ],
+ "use_cache": [
+ true
+ ]
+ },
+ "outputs": [
+ "latents"
+ ]
+ },
+ "unsharp_mask": {
+ "inputs": [
+ "image"
+ ],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "radius": [
+ 2
+ ],
+ "strength": [
+ 60
+ ],
+ "use_cache": [
+ true
+ ]
+ },
+ "outputs": [
+ "height",
+ "image",
+ "width"
+ ]
+ },
+ "z_image_control": {
+ "inputs": [
+ "image"
+ ],
+ "literalInputs": {
+ "begin_step_percent": [
+ 0
+ ],
+ "control_context_scale": [
+ 0.65
+ ],
+ "control_model": [],
+ "end_step_percent": [
+ 0.75
+ ],
+ "is_intermediate": [
+ true
+ ],
+ "tile_size": [
+ 1024
+ ],
+ "tiled": [
+ true
+ ],
+ "use_cache": [
+ true
+ ]
+ },
+ "outputs": [
+ "control"
+ ]
+ },
+ "z_image_denoise": {
+ "inputs": [
+ "control",
+ "latents",
+ "negative_conditioning",
+ "positive_conditioning",
+ "seed",
+ "transformer",
+ "vae"
+ ],
+ "literalInputs": {
+ "denoising_end": [
+ 1
+ ],
+ "denoising_start": [
+ 0.6833333333333333
+ ],
+ "guidance_scale": [
+ 1,
+ 4
+ ],
+ "height": [
+ 400
+ ],
+ "is_intermediate": [
+ true
+ ],
+ "scheduler": [
+ "euler"
+ ],
+ "steps": [
+ 30
+ ],
+ "use_cache": [
+ true
+ ],
+ "width": [
+ 800
+ ]
+ },
+ "outputs": [
+ "latents"
+ ]
+ },
+ "z_image_i2l": {
+ "inputs": [
+ "image",
+ "vae"
+ ],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "tile_size": [
+ 1024
+ ],
+ "tiled": [
+ true
+ ],
+ "use_cache": [
+ true
+ ]
+ },
+ "outputs": [
+ "latents"
+ ]
+ },
+ "z_image_l2i": {
+ "inputs": [
+ "latents",
+ "metadata",
+ "vae"
+ ],
+ "literalInputs": {
+ "is_intermediate": [
+ false
+ ],
+ "tile_size": [
+ 1024
+ ],
+ "tiled": [
+ true
+ ],
+ "use_cache": [
+ false
+ ]
+ },
+ "outputs": []
+ },
+ "z_image_lora_collection_loader": {
+ "inputs": [
+ "loras",
+ "qwen3_encoder",
+ "transformer"
+ ],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "use_cache": [
+ true
+ ]
+ },
+ "outputs": [
+ "qwen3_encoder",
+ "transformer"
+ ]
+ },
+ "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",
+ "vae"
+ ]
+ },
+ "z_image_text_encoder": {
+ "inputs": [
+ "prompt",
+ "qwen3_encoder"
+ ],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "use_cache": [
+ true
+ ]
+ },
+ "outputs": [
+ "conditioning"
+ ]
+ }
+ }
+}
diff --git a/invokeai/frontend/webv2/src/features/upscale/core/__snapshots__/upscaleIndexClippedStarts.json b/invokeai/frontend/webv2/src/features/upscale/core/__snapshots__/upscaleIndexClippedStarts.json
new file mode 100644
index 0000000000..28c5d5ff3b
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/upscale/core/__snapshots__/upscaleIndexClippedStarts.json
@@ -0,0 +1,485 @@
+{
+ "_comment": "Generated by src/features/upscale/core/denoisingStart.test.ts; regenerate with `vitest -u`. Consumed by tests/app/invocations/test_upscale_index_clipped_starts.py, which drives the real z_image_denoise and anima_denoise with each denoisingStart and checks the pass enters at the step nearest fluxEntrySigma.",
+ "cases": [
+ {
+ "base": "anima",
+ "creativity": -10,
+ "denoisingStart": 0.9375,
+ "fluxEntrySigma": 0.0019999999999998908,
+ "side": 1024,
+ "steps": 8
+ },
+ {
+ "base": "anima",
+ "creativity": -5,
+ "denoisingStart": 0.9375,
+ "fluxEntrySigma": 0.25149999999999995,
+ "side": 1024,
+ "steps": 8
+ },
+ {
+ "base": "anima",
+ "creativity": 0,
+ "denoisingStart": 0.8125,
+ "fluxEntrySigma": 0.5009999999999999,
+ "side": 1024,
+ "steps": 8
+ },
+ {
+ "base": "anima",
+ "creativity": 5,
+ "denoisingStart": 0.5625,
+ "fluxEntrySigma": 0.7505,
+ "side": 1024,
+ "steps": 8
+ },
+ {
+ "base": "anima",
+ "creativity": 8,
+ "denoisingStart": 0.3125,
+ "fluxEntrySigma": 0.9002,
+ "side": 1024,
+ "steps": 8
+ },
+ {
+ "base": "anima",
+ "creativity": 10,
+ "denoisingStart": 0,
+ "fluxEntrySigma": 1,
+ "side": 1024,
+ "steps": 8
+ },
+ {
+ "base": "anima",
+ "creativity": -10,
+ "denoisingStart": 0.9833333333333333,
+ "fluxEntrySigma": 0.0019999999999998908,
+ "side": 1024,
+ "steps": 30
+ },
+ {
+ "base": "anima",
+ "creativity": -5,
+ "denoisingStart": 0.9166666666666666,
+ "fluxEntrySigma": 0.25149999999999995,
+ "side": 1024,
+ "steps": 30
+ },
+ {
+ "base": "anima",
+ "creativity": 0,
+ "denoisingStart": 0.75,
+ "fluxEntrySigma": 0.5009999999999999,
+ "side": 1024,
+ "steps": 30
+ },
+ {
+ "base": "anima",
+ "creativity": 5,
+ "denoisingStart": 0.5166666666666667,
+ "fluxEntrySigma": 0.7505,
+ "side": 1024,
+ "steps": 30
+ },
+ {
+ "base": "anima",
+ "creativity": 8,
+ "denoisingStart": 0.25,
+ "fluxEntrySigma": 0.9002,
+ "side": 1024,
+ "steps": 30
+ },
+ {
+ "base": "anima",
+ "creativity": 10,
+ "denoisingStart": 0,
+ "fluxEntrySigma": 1,
+ "side": 1024,
+ "steps": 30
+ },
+ {
+ "base": "z-image",
+ "creativity": -10,
+ "denoisingStart": 0.9375,
+ "fluxEntrySigma": 0.0019999999999998908,
+ "side": 512,
+ "steps": 8
+ },
+ {
+ "base": "z-image",
+ "creativity": -5,
+ "denoisingStart": 0.9375,
+ "fluxEntrySigma": 0.25149999999999995,
+ "side": 512,
+ "steps": 8
+ },
+ {
+ "base": "z-image",
+ "creativity": 0,
+ "denoisingStart": 0.6875,
+ "fluxEntrySigma": 0.5009999999999999,
+ "side": 512,
+ "steps": 8
+ },
+ {
+ "base": "z-image",
+ "creativity": 5,
+ "denoisingStart": 0.4375,
+ "fluxEntrySigma": 0.7505,
+ "side": 512,
+ "steps": 8
+ },
+ {
+ "base": "z-image",
+ "creativity": 8,
+ "denoisingStart": 0.1875,
+ "fluxEntrySigma": 0.9002,
+ "side": 512,
+ "steps": 8
+ },
+ {
+ "base": "z-image",
+ "creativity": 10,
+ "denoisingStart": 0,
+ "fluxEntrySigma": 1,
+ "side": 512,
+ "steps": 8
+ },
+ {
+ "base": "z-image",
+ "creativity": -10,
+ "denoisingStart": 0.9833333333333333,
+ "fluxEntrySigma": 0.0019999999999998908,
+ "side": 512,
+ "steps": 30
+ },
+ {
+ "base": "z-image",
+ "creativity": -5,
+ "denoisingStart": 0.85,
+ "fluxEntrySigma": 0.25149999999999995,
+ "side": 512,
+ "steps": 30
+ },
+ {
+ "base": "z-image",
+ "creativity": 0,
+ "denoisingStart": 0.6833333333333333,
+ "fluxEntrySigma": 0.5009999999999999,
+ "side": 512,
+ "steps": 30
+ },
+ {
+ "base": "z-image",
+ "creativity": 5,
+ "denoisingStart": 0.4166666666666667,
+ "fluxEntrySigma": 0.7505,
+ "side": 512,
+ "steps": 30
+ },
+ {
+ "base": "z-image",
+ "creativity": 8,
+ "denoisingStart": 0.18333333333333332,
+ "fluxEntrySigma": 0.9002,
+ "side": 512,
+ "steps": 30
+ },
+ {
+ "base": "z-image",
+ "creativity": 10,
+ "denoisingStart": 0,
+ "fluxEntrySigma": 1,
+ "side": 512,
+ "steps": 30
+ },
+ {
+ "base": "z-image",
+ "creativity": -10,
+ "denoisingStart": 0.9375,
+ "fluxEntrySigma": 0.0019999999999998908,
+ "side": 1024,
+ "steps": 8
+ },
+ {
+ "base": "z-image",
+ "creativity": -5,
+ "denoisingStart": 0.9375,
+ "fluxEntrySigma": 0.25149999999999995,
+ "side": 1024,
+ "steps": 8
+ },
+ {
+ "base": "z-image",
+ "creativity": 0,
+ "denoisingStart": 0.8125,
+ "fluxEntrySigma": 0.5009999999999999,
+ "side": 1024,
+ "steps": 8
+ },
+ {
+ "base": "z-image",
+ "creativity": 5,
+ "denoisingStart": 0.5625,
+ "fluxEntrySigma": 0.7505,
+ "side": 1024,
+ "steps": 8
+ },
+ {
+ "base": "z-image",
+ "creativity": 8,
+ "denoisingStart": 0.3125,
+ "fluxEntrySigma": 0.9002,
+ "side": 1024,
+ "steps": 8
+ },
+ {
+ "base": "z-image",
+ "creativity": 10,
+ "denoisingStart": 0,
+ "fluxEntrySigma": 1,
+ "side": 1024,
+ "steps": 8
+ },
+ {
+ "base": "z-image",
+ "creativity": -10,
+ "denoisingStart": 0.9833333333333333,
+ "fluxEntrySigma": 0.0019999999999998908,
+ "side": 1024,
+ "steps": 30
+ },
+ {
+ "base": "z-image",
+ "creativity": -5,
+ "denoisingStart": 0.9166666666666666,
+ "fluxEntrySigma": 0.25149999999999995,
+ "side": 1024,
+ "steps": 30
+ },
+ {
+ "base": "z-image",
+ "creativity": 0,
+ "denoisingStart": 0.7833333333333333,
+ "fluxEntrySigma": 0.5009999999999999,
+ "side": 1024,
+ "steps": 30
+ },
+ {
+ "base": "z-image",
+ "creativity": 5,
+ "denoisingStart": 0.5166666666666667,
+ "fluxEntrySigma": 0.7505,
+ "side": 1024,
+ "steps": 30
+ },
+ {
+ "base": "z-image",
+ "creativity": 8,
+ "denoisingStart": 0.2833333333333333,
+ "fluxEntrySigma": 0.9002,
+ "side": 1024,
+ "steps": 30
+ },
+ {
+ "base": "z-image",
+ "creativity": 10,
+ "denoisingStart": 0,
+ "fluxEntrySigma": 1,
+ "side": 1024,
+ "steps": 30
+ },
+ {
+ "base": "z-image",
+ "creativity": -10,
+ "denoisingStart": 0.9375,
+ "fluxEntrySigma": 0.0019999999999998908,
+ "side": 2048,
+ "steps": 8
+ },
+ {
+ "base": "z-image",
+ "creativity": -5,
+ "denoisingStart": 0.9375,
+ "fluxEntrySigma": 0.25149999999999995,
+ "side": 2048,
+ "steps": 8
+ },
+ {
+ "base": "z-image",
+ "creativity": 0,
+ "denoisingStart": 0.8125,
+ "fluxEntrySigma": 0.5009999999999999,
+ "side": 2048,
+ "steps": 8
+ },
+ {
+ "base": "z-image",
+ "creativity": 5,
+ "denoisingStart": 0.5625,
+ "fluxEntrySigma": 0.7505,
+ "side": 2048,
+ "steps": 8
+ },
+ {
+ "base": "z-image",
+ "creativity": 8,
+ "denoisingStart": 0.3125,
+ "fluxEntrySigma": 0.9002,
+ "side": 2048,
+ "steps": 8
+ },
+ {
+ "base": "z-image",
+ "creativity": 10,
+ "denoisingStart": 0,
+ "fluxEntrySigma": 1,
+ "side": 2048,
+ "steps": 8
+ },
+ {
+ "base": "z-image",
+ "creativity": -10,
+ "denoisingStart": 0.9833333333333333,
+ "fluxEntrySigma": 0.0019999999999998908,
+ "side": 2048,
+ "steps": 30
+ },
+ {
+ "base": "z-image",
+ "creativity": -5,
+ "denoisingStart": 0.9166666666666666,
+ "fluxEntrySigma": 0.25149999999999995,
+ "side": 2048,
+ "steps": 30
+ },
+ {
+ "base": "z-image",
+ "creativity": 0,
+ "denoisingStart": 0.7833333333333333,
+ "fluxEntrySigma": 0.5009999999999999,
+ "side": 2048,
+ "steps": 30
+ },
+ {
+ "base": "z-image",
+ "creativity": 5,
+ "denoisingStart": 0.5166666666666667,
+ "fluxEntrySigma": 0.7505,
+ "side": 2048,
+ "steps": 30
+ },
+ {
+ "base": "z-image",
+ "creativity": 8,
+ "denoisingStart": 0.2833333333333333,
+ "fluxEntrySigma": 0.9002,
+ "side": 2048,
+ "steps": 30
+ },
+ {
+ "base": "z-image",
+ "creativity": 10,
+ "denoisingStart": 0,
+ "fluxEntrySigma": 1,
+ "side": 2048,
+ "steps": 30
+ },
+ {
+ "base": "z-image",
+ "creativity": -10,
+ "denoisingStart": 0.9375,
+ "fluxEntrySigma": 0.0019999999999998908,
+ "side": 4096,
+ "steps": 8
+ },
+ {
+ "base": "z-image",
+ "creativity": -5,
+ "denoisingStart": 0.9375,
+ "fluxEntrySigma": 0.25149999999999995,
+ "side": 4096,
+ "steps": 8
+ },
+ {
+ "base": "z-image",
+ "creativity": 0,
+ "denoisingStart": 0.8125,
+ "fluxEntrySigma": 0.5009999999999999,
+ "side": 4096,
+ "steps": 8
+ },
+ {
+ "base": "z-image",
+ "creativity": 5,
+ "denoisingStart": 0.5625,
+ "fluxEntrySigma": 0.7505,
+ "side": 4096,
+ "steps": 8
+ },
+ {
+ "base": "z-image",
+ "creativity": 8,
+ "denoisingStart": 0.3125,
+ "fluxEntrySigma": 0.9002,
+ "side": 4096,
+ "steps": 8
+ },
+ {
+ "base": "z-image",
+ "creativity": 10,
+ "denoisingStart": 0,
+ "fluxEntrySigma": 1,
+ "side": 4096,
+ "steps": 8
+ },
+ {
+ "base": "z-image",
+ "creativity": -10,
+ "denoisingStart": 0.9833333333333333,
+ "fluxEntrySigma": 0.0019999999999998908,
+ "side": 4096,
+ "steps": 30
+ },
+ {
+ "base": "z-image",
+ "creativity": -5,
+ "denoisingStart": 0.9166666666666666,
+ "fluxEntrySigma": 0.25149999999999995,
+ "side": 4096,
+ "steps": 30
+ },
+ {
+ "base": "z-image",
+ "creativity": 0,
+ "denoisingStart": 0.7833333333333333,
+ "fluxEntrySigma": 0.5009999999999999,
+ "side": 4096,
+ "steps": 30
+ },
+ {
+ "base": "z-image",
+ "creativity": 5,
+ "denoisingStart": 0.5166666666666667,
+ "fluxEntrySigma": 0.7505,
+ "side": 4096,
+ "steps": 30
+ },
+ {
+ "base": "z-image",
+ "creativity": 8,
+ "denoisingStart": 0.2833333333333333,
+ "fluxEntrySigma": 0.9002,
+ "side": 4096,
+ "steps": 30
+ },
+ {
+ "base": "z-image",
+ "creativity": 10,
+ "denoisingStart": 0,
+ "fluxEntrySigma": 1,
+ "side": 4096,
+ "steps": 30
+ }
+ ]
+}
diff --git a/invokeai/frontend/webv2/src/features/upscale/core/denoisingStart.test.ts b/invokeai/frontend/webv2/src/features/upscale/core/denoisingStart.test.ts
new file mode 100644
index 0000000000..4e559b9d76
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/upscale/core/denoisingStart.test.ts
@@ -0,0 +1,57 @@
+/** The starts the widget sends index-clipping denoise nodes, recorded for the backend to replay. */
+
+import { describe, expect, it } from 'vitest';
+
+import type { UpscaleBase } from './settings';
+
+import { getIndexClippedDenoisingStart, getUpscaleDenoisingStart } from './denoisingStart';
+import { UPSCALE_ARCHITECTURES } from './settings';
+
+const CREATIVITIES = [-10, -5, 0, 5, 8, 10];
+const STEP_COUNTS = [8, 30];
+// Z-Image's shift follows the frame up to one megapixel; Anima's is fixed.
+const FRAME_SIDES: Partial<Record<UpscaleBase, number[]>> = { anima: [1024], 'z-image': [512, 1024, 2048, 4096] };
+
+describe('index-clipped denoising starts', () => {
+ it('covers every architecture whose denoise node clips by index', () => {
+ const indexClipped = Object.entries(UPSCALE_ARCHITECTURES)
+ .filter(([, architecture]) => architecture.indexClippedShift)
+ .map(([base]) => base);
+
+ expect(Object.keys(FRAME_SIDES).sort()).toEqual(indexClipped.sort());
+ });
+
+ it('records what the widget sends, so the backend can check it against its real schedules', async () => {
+ const cases = Object.entries(FRAME_SIDES).flatMap(([base, sides]) =>
+ sides.flatMap((side) =>
+ STEP_COUNTS.flatMap((steps) =>
+ CREATIVITIES.map((creativity) => {
+ const valueStart = getUpscaleDenoisingStart(creativity);
+ const shift = UPSCALE_ARCHITECTURES[base as UpscaleBase].indexClippedShift!({ height: side, width: side });
+
+ return {
+ base,
+ creativity,
+ denoisingStart: getIndexClippedDenoisingStart(valueStart, steps, shift),
+ fluxEntrySigma: 1 - valueStart,
+ side,
+ steps,
+ };
+ })
+ )
+ )
+ );
+ const fixture = {
+ _comment:
+ 'Generated by src/features/upscale/core/denoisingStart.test.ts; regenerate with `vitest -u`. ' +
+ 'Consumed by tests/app/invocations/test_upscale_index_clipped_starts.py, which drives the real ' +
+ 'z_image_denoise and anima_denoise with each denoisingStart and checks the pass enters at the ' +
+ 'step nearest fluxEntrySigma.',
+ cases,
+ };
+
+ await expect(`${JSON.stringify(fixture, null, 2)}\n`).toMatchFileSnapshot(
+ './__snapshots__/upscaleIndexClippedStarts.json'
+ );
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/upscale/core/denoisingStart.ts b/invokeai/frontend/webv2/src/features/upscale/core/denoisingStart.ts
new file mode 100644
index 0000000000..ff2690bd9a
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/upscale/core/denoisingStart.ts
@@ -0,0 +1,56 @@
+/**
+ * Where on its schedule the second pass starts, from the Creativity slider.
+ *
+ * Creativity is defined by where FLUX enters: `flux_denoise` clips the schedule by *value*, so a
+ * start of 0.499 enters at sigma 0.501 whatever the shift or step count. Z-Image and Anima clip by
+ * *index* instead (`start_idx = int(denoising_start * steps)` on a shifted schedule), so the same
+ * number enters far noisier there -- 0.499 starts Z-Image at sigma 0.78. Handing them the step whose
+ * sigma is nearest FLUX's keeps one slider meaning one thing. This module goes away when those
+ * nodes clip by value.
+ */
+
+/** The legacy formula: creativity -10..10 to a value-clipped start of 0.998..0. */
+export const getUpscaleDenoisingStart = (creativity: number): number => ((creativity * -1 + 10) * 4.99) / 100;
+
+/** `z_image_denoise._calculate_shift`, held at the fit's 4096-token end since the clamp (#378). */
+const Z_IMAGE_SHIFT_MIN_SEQ_LEN = 256;
+const Z_IMAGE_SHIFT_MAX_SEQ_LEN = 4096;
+const Z_IMAGE_BASE_SHIFT = 0.5;
+const Z_IMAGE_MAX_SHIFT = 1.15;
+
+/** Z-Image's linear shift for a frame: one token per 16x16 pixels, as `z_image_denoise` patches it. */
+export const zImageScheduleShift = ({ width, height }: { width: number; height: number }): number => {
+ const seqLen = Math.min(Math.floor(width / 16) * Math.floor(height / 16), Z_IMAGE_SHIFT_MAX_SEQ_LEN);
+ const slope = (Z_IMAGE_MAX_SHIFT - Z_IMAGE_BASE_SHIFT) / (Z_IMAGE_SHIFT_MAX_SEQ_LEN - Z_IMAGE_SHIFT_MIN_SEQ_LEN);
+
+ return Math.exp(seqLen * slope + Z_IMAGE_BASE_SHIFT - slope * Z_IMAGE_SHIFT_MIN_SEQ_LEN);
+};
+
+/** `ANIMA_SHIFT`: Anima's schedule is shifted by a constant, not by resolution. */
+export const ANIMA_SCHEDULE_SHIFT = 3;
+
+/**
+ * The start an index-clipping node needs to enter where a value-clipping one would.
+ *
+ * Both nodes build `sigma = shift * t / (1 + (shift - 1) * t)` at `t = 1 - i / steps` and begin at
+ * `i = int(start * steps)`. This picks the `i` whose sigma is nearest `1 - valueStart` and aims at
+ * the middle of that step, so float error in the node's product cannot floor it one step short.
+ */
+export const getIndexClippedDenoisingStart = (valueStart: number, steps: number, shift: number): number => {
+ const target = 1 - valueStart;
+ let entryIndex = 0;
+ let entryDistance = Number.POSITIVE_INFINITY;
+
+ // The last index would leave nothing to denoise, so it is never a candidate.
+ for (let index = 0; index < steps; index += 1) {
+ const t = 1 - index / steps;
+ const distance = Math.abs((shift * t) / (1 + (shift - 1) * t) - target);
+
+ if (distance < entryDistance) {
+ entryIndex = index;
+ entryDistance = distance;
+ }
+ }
+
+ return entryIndex === 0 ? 0 : (entryIndex + 0.5) / steps;
+};
diff --git a/invokeai/frontend/webv2/src/features/upscale/core/graph.test.ts b/invokeai/frontend/webv2/src/features/upscale/core/graph.test.ts
index 76258d1e8e..d335d9710b 100644
--- a/invokeai/frontend/webv2/src/features/upscale/core/graph.test.ts
+++ b/invokeai/frontend/webv2/src/features/upscale/core/graph.test.ts
@@ -4,7 +4,10 @@ import type { ModelConfig } from '@features/models';
import { seedArchitectureCapabilities } from '@features/generation/core/architectureCapabilities.testing';
import { describe, expect, it } from 'vitest';
-import { compileUpscaleGraph, getUpscaleControlNetValues, getUpscaleDenoisingStart } from './graph';
+import type { TileControlNetModelConfig, UpscaleWidgetValues } from './types';
+
+import { getUpscaleDenoisingStart } from './denoisingStart';
+import { compileUpscaleGraph, getUpscaleControlNetValues, getZImageTileControlValues } from './graph';
import { createDefaultUpscaleWidgetValues } from './settings';
const model = (key: string, type: string, base: string, name = key): ModelConfig => ({
@@ -182,6 +185,20 @@ describe('compileUpscaleGraph for FLUX.1', () => {
expect(nodes.fit_to_grid).toBeUndefined();
});
+ it('resizes a frame the scale already puts on the grid, because a 1x model makes Spandrel ignore the scale', () => {
+ // The literal 2048 on the denoise node is a promise only the resize keeps: a restoration model
+ // that does not enlarge leaves the frame at 1024, and the latents would not match the node.
+ const { edges, nodes } = compileUpscaleGraph(
+ { ...createFluxValues(), inputImage: { height: 1024, image_name: 'input.png', width: 1024 }, scale: 2 },
+ 'gallery',
+ { useCpuNoise: true }
+ ).backendGraph;
+
+ expect(nodes.fit_to_grid).toMatchObject({ height: 2048, width: 2048 });
+ expect(nodes.denoise_latents).toMatchObject({ height: 2048, width: 2048 });
+ expect(hasEdge(edges, 'fit_to_grid', 'image', 'i2l', 'image')).toBe(true);
+ });
+
it('wires no ControlNet, because FLUX.1 has no tile model to anchor with', () => {
const { nodes } = compileUpscaleGraph(createFluxValues(), 'gallery', { useCpuNoise: true }).backendGraph;
@@ -204,11 +221,235 @@ describe('compileUpscaleGraph for FLUX.1', () => {
});
});
+const withVariant = (config: ModelConfig, variant: string): ModelConfig => ({ ...config, variant }) as ModelConfig;
+
+const createZImageValues = (options: { tileControlNet?: boolean; cfgScale?: number } = {}) => {
+ const models = [
+ model('main', 'main', 'z-image'),
+ model('spandrel', 'spandrel_image_to_image', 'any'),
+ model('lora', 'lora', 'z-image'),
+ // Z-Image decodes with a FLUX VAE, and reads the 4B Qwen3, never Anima's 0.6B.
+ model('fluxvae', 'vae', 'flux'),
+ withVariant(model('qwen3-06b', 'qwen3_encoder', 'any'), 'qwen3_06b'),
+ withVariant(model('qwen3-4b', 'qwen3_encoder', 'any'), 'qwen3_4b'),
+ model('tile', 'controlnet', 'z-image', 'Z-Image ControlNet Tile'),
+ ];
+ const values = createDefaultUpscaleWidgetValues(models);
+
+ return {
+ ...values,
+ cfgScale: options.cfgScale ?? 1,
+ inputImage: { height: 101, image_name: 'input.png', width: 203 },
+ loras: [{ isEnabled: true, model: models[2] as GenerateLora['model'], weight: 0.7 }],
+ negativePrompt: 'blur',
+ positivePrompt: 'detail',
+ tileControlnetModel: options.tileControlNet ? (models[6] as TileControlNetModelConfig) : null,
+ };
+};
+
+describe('compileUpscaleGraph for Z-Image', () => {
+ it('drives the second pass with z-image nodes, tiles both VAE ends and fits the 16px grid', () => {
+ const { edges, nodes } = compileUpscaleGraph(createZImageValues(), 'gallery', { useCpuNoise: true }).backendGraph;
+
+ expect(nodes.model_loader).toMatchObject({ type: 'z_image_model_loader' });
+ expect(nodes.model_loader?.qwen3_encoder_model).toMatchObject({ key: 'qwen3-4b' });
+ expect(nodes.model_loader?.vae_model).toMatchObject({ key: 'fluxvae' });
+ expect(nodes.model_loader?.qwen3_source_model).toBeUndefined();
+ expect(nodes.i2l).toMatchObject({ tile_size: 1024, tiled: true, type: 'z_image_i2l' });
+ expect(nodes.upscale_output).toMatchObject({ tile_size: 1024, tiled: true, type: 'z_image_l2i' });
+ // 203x101 at 4x: Spandrel gives 808x400, and z_image_denoise takes multiples of 16 only.
+ expect(nodes.fit_to_grid).toMatchObject({ height: 400, width: 800 });
+ expect(nodes.denoise_latents).toMatchObject({
+ guidance_scale: 1,
+ height: 400,
+ steps: 30,
+ type: 'z_image_denoise',
+ width: 800,
+ });
+ expect(hasEdge(edges, 'fit_to_grid', 'image', 'i2l', 'image')).toBe(true);
+ expect(hasEdge(edges, 'i2l', 'latents', 'denoise_latents', 'latents')).toBe(true);
+ expect(hasEdge(edges, 'pos_cond_collect', 'collection', 'denoise_latents', 'positive_conditioning')).toBe(true);
+ expect(Object.values(nodes).some((node) => node.type === 'z_image_lora_collection_loader')).toBe(true);
+ });
+
+ it('gives the negative prompt a branch exactly where CFG runs an unconditional pass, as Generate does', () => {
+ const turbo = compileUpscaleGraph(createZImageValues(), 'gallery', { useCpuNoise: true }).backendGraph;
+ const withCfg = compileUpscaleGraph(createZImageValues({ cfgScale: 4 }), 'gallery', { useCpuNoise: true });
+ // Switched off, the prompt still gets its branch and the queue fills it with an empty string.
+ // Leaving the branch out would turn CFG off while the slider and the metadata still say 4.
+ const switchedOff = compileUpscaleGraph(
+ { ...createZImageValues({ cfgScale: 4 }), negativePromptEnabled: false },
+ 'gallery',
+ { useCpuNoise: true }
+ ).backendGraph;
+
+ expect(turbo.nodes.neg_cond).toBeUndefined();
+ expect(switchedOff.nodes.neg_cond).toMatchObject({ type: 'z_image_text_encoder' });
+ expect(
+ hasEdge(withCfg.backendGraph.edges, 'neg_cond_collect', 'collection', 'denoise_latents', 'negative_conditioning')
+ ).toBe(true);
+ expect(hasEdge(withCfg.backendGraph.edges, 'negative_prompt', 'value', 'core_metadata', 'negative_prompt')).toBe(
+ true
+ );
+ expect(hasEdge(turbo.edges, 'negative_prompt', 'value', 'core_metadata', 'negative_prompt')).toBe(false);
+ });
+
+ it('anchors to the enlarged frame with a tiled control encode when a tile ControlNet is chosen', () => {
+ const { edges, nodes } = compileUpscaleGraph(
+ { ...createZImageValues({ tileControlNet: true }), structure: 0 },
+ 'gallery',
+ { useCpuNoise: true }
+ ).backendGraph;
+
+ // The control image is encoded inside the denoise at the frame's full size; untiled, that is
+ // the encode the i2l node is tiled to avoid.
+ expect(nodes.tile_control).toMatchObject({
+ begin_step_percent: 0,
+ control_model: { key: 'tile' },
+ tile_size: 1024,
+ tiled: true,
+ type: 'z_image_control',
+ });
+ expect(nodes.tile_control?.control_context_scale).toBeCloseTo(0.65);
+ expect(nodes.tile_control?.end_step_percent).toBeCloseTo(0.75);
+ expect(hasEdge(edges, 'fit_to_grid', 'image', 'tile_control', 'image')).toBe(true);
+ expect(hasEdge(edges, 'tile_control', 'control', 'denoise_latents', 'control')).toBe(true);
+ expect(hasEdge(edges, 'model_loader', 'vae', 'denoise_latents', 'vae')).toBe(true);
+ });
+
+ it('runs without a ControlNet when none is chosen', () => {
+ const { nodes } = compileUpscaleGraph(createZImageValues(), 'gallery', { useCpuNoise: true }).backendGraph;
+
+ expect(nodes.tile_control).toBeUndefined();
+ expect(Object.values(nodes).some((node) => node.type === 'z_image_control')).toBe(false);
+ });
+
+ it('spans Structure from a light early nudge to holding the whole pass', () => {
+ expect(getZImageTileControlValues(-10)).toEqual({
+ beginStepPercent: 0,
+ controlContextScale: expect.closeTo(0.3),
+ endStepPercent: expect.closeTo(0.5),
+ });
+ expect(getZImageTileControlValues(10)).toEqual({
+ beginStepPercent: 0,
+ controlContextScale: expect.closeTo(1),
+ endStepPercent: expect.closeTo(1),
+ });
+ });
+
+ it('keeps an encoder the architecture does not read out of the graph and its metadata', () => {
+ // A T5 picked while FLUX was selected stays in the widget for when FLUX comes back.
+ const staleT5 = { base: 'any', key: 'stale-t5', name: 'stale-t5', type: 't5_encoder' } as never;
+ const { nodes } = compileUpscaleGraph({ ...createZImageValues(), t5EncoderModel: staleT5 }, 'gallery', {
+ useCpuNoise: true,
+ }).backendGraph;
+
+ expect(JSON.stringify(nodes)).not.toContain('stale-t5');
+ });
+
+ it('lets a Diffusers install supply its own encoder and VAE', () => {
+ const diffusers = { ...model('main', 'main', 'z-image'), format: 'diffusers' } as ModelConfig;
+ const values = {
+ ...createDefaultUpscaleWidgetValues([diffusers, model('spandrel', 'spandrel_image_to_image', 'any')]),
+ inputImage: { height: 64, image_name: 'input.png', width: 64 },
+ };
+ const { nodes } = compileUpscaleGraph(values, 'gallery', { useCpuNoise: true }).backendGraph;
+
+ expect(nodes.model_loader?.qwen3_source_model).toMatchObject({ key: 'main' });
+ expect(nodes.model_loader?.qwen3_encoder_model).toBeUndefined();
+ expect(nodes.model_loader?.vae_model).toBeUndefined();
+ });
+});
+
+const createAnimaValues = (variant = 'anima_qwen3') => {
+ const models = [
+ withVariant(model('main', 'main', 'anima'), variant),
+ model('spandrel', 'spandrel_image_to_image', 'any'),
+ model('qwenvae', 'vae', 'qwen-image'),
+ withVariant(model('qwen3-4b', 'qwen3_encoder', 'any'), 'qwen3_4b'),
+ withVariant(model('qwen3-06b', 'qwen3_encoder', 'any'), 'qwen3_06b'),
+ withVariant(model('qwen35', 'qwen3_5_encoder', 'any'), 'qwen3_5_4b'),
+ ];
+
+ return {
+ ...createDefaultUpscaleWidgetValues(models),
+ cfgScale: 1,
+ inputImage: { height: 101, image_name: 'input.png', width: 203 },
+ positivePrompt: 'detail',
+ };
+};
+
+describe('compileUpscaleGraph for Anima', () => {
+ it('drives the second pass with anima nodes at the size it states', () => {
+ const { edges, nodes } = compileUpscaleGraph(createAnimaValues(), 'gallery', { useCpuNoise: true }).backendGraph;
+
+ expect(nodes.model_loader).toMatchObject({ type: 'anima_model_loader' });
+ expect(nodes.model_loader?.qwen3_encoder_model).toMatchObject({ key: 'qwen3-06b' });
+ expect(nodes.model_loader?.vae_model).toMatchObject({ key: 'qwenvae' });
+ expect(nodes.model_loader?.qwen3_5_encoder_model).toBeUndefined();
+ expect(nodes.i2l).toMatchObject({ tile_size: 1024, tiled: true, type: 'anima_i2l' });
+ expect(nodes.upscale_output).toMatchObject({ type: 'anima_l2i' });
+ // anima_denoise takes multiples of 8, so 808x400 needs no rounding -- but the size is a literal.
+ expect(nodes.fit_to_grid).toMatchObject({ height: 400, width: 808 });
+ expect(nodes.denoise_latents).toMatchObject({ height: 400, type: 'anima_denoise', width: 808 });
+ expect(hasEdge(edges, 'fit_to_grid', 'image', 'i2l', 'image')).toBe(true);
+ expect(Object.values(nodes).some((node) => node.type.includes('control'))).toBe(false);
+ });
+
+ it('hands Anima-3.8B the Qwen3.5 encoder its connector reads', () => {
+ const { edges, nodes } = compileUpscaleGraph(createAnimaValues('anima_qwen35'), 'gallery', {
+ useCpuNoise: true,
+ }).backendGraph;
+
+ expect(nodes.model_loader?.qwen3_5_encoder_model).toMatchObject({ key: 'qwen35' });
+ expect(hasEdge(edges, 'model_loader', 'qwen3_5_encoder', 'pos_cond', 'qwen3_5_encoder')).toBe(true);
+ expect(nodes.core_metadata?.qwen3_5_encoder).toMatchObject({ key: 'qwen35' });
+ });
+});
+
+describe('Creativity on index-clipping architectures', () => {
+ // Expected starts come from the backend's own schedules (`ZImageDenoiseInvocation._get_sigmas`
+ // with `_calculate_shift`, `AnimaDenoiseInvocation._get_sigmas`) and the nodes' clipping line,
+ // `int(start * steps)`: each enters within one step of the sigma FLUX enters at, 1 - start.
+ const startFor = (values: UpscaleWidgetValues, creativity: number, inputSide: number) =>
+ compileUpscaleGraph(
+ { ...values, creativity, inputImage: { height: inputSide, image_name: 'in.png', width: inputSide }, scale: 2 },
+ 'gallery',
+ { useCpuNoise: true }
+ ).backendGraph.nodes.denoise_latents?.denoising_start;
+
+ it.each([
+ [-5, 27.5 / 30],
+ [0, 23.5 / 30],
+ [5, 15.5 / 30],
+ [10, 0],
+ ])('starts Z-Image at 2048px where FLUX starts for creativity %i', (creativity, expected) => {
+ // Today's 0.499 for balanced would enter Z-Image at sigma 0.783; this enters at 0.490.
+ expect(startFor(createZImageValues(), creativity, 1024)).toBeCloseTo(expected, 6);
+ });
+
+ it("follows Z-Image's resolution-dependent shift below one megapixel", () => {
+ expect(startFor(createZImageValues(), 0, 256)).toBeCloseTo(20.5 / 30, 6);
+ });
+
+ it.each([
+ [0, 22.5 / 30],
+ [8, 7.5 / 30],
+ ])('starts Anima, whose shift is fixed, where FLUX starts for creativity %i', (creativity, expected) => {
+ expect(startFor(createAnimaValues(), creativity, 1024)).toBeCloseTo(expected, 6);
+ });
+
+ it('leaves the value-clipping FLUX pass on the legacy formula', () => {
+ expect(startFor(createFluxValues(), 0, 1024)).toBeCloseTo(0.499, 6);
+ });
+});
+
describe('upscale metadata', () => {
it.each([
['sd-1', () => createValues('sd-1')],
['sdxl', () => createValues('sdxl')],
['flux', () => createFluxValues()],
+ ['z-image', () => createZImageValues()],
] as const)('records exactly the concepts the %s pass loads', (_base, createBaseValues) => {
const values = createBaseValues();
const { nodes } = compileUpscaleGraph(
diff --git a/invokeai/frontend/webv2/src/features/upscale/core/graph.ts b/invokeai/frontend/webv2/src/features/upscale/core/graph.ts
index f0da060db7..174ccf5f4a 100644
--- a/invokeai/frontend/webv2/src/features/upscale/core/graph.ts
+++ b/invokeai/frontend/webv2/src/features/upscale/core/graph.ts
@@ -16,14 +16,19 @@ import {
toGraphContract,
toModelIdentifier,
} from '@features/generation/graph';
-import { coerceSchedulerForGraph } from '@features/generation/settings';
+import { coerceSchedulerForGraph, isBundledMainForBase } from '@features/generation/settings';
import type { UpscaleBase } from './settings';
import type { CompiledUpscaleGraph, UpscaleWidgetValues } from './types';
-import { getUpscaleValidationReasons, upscaleArchitectureFor, upscaleDenoiseDimension } from './settings';
-
-export const getUpscaleDenoisingStart = (creativity: number): number => ((creativity * -1 + 10) * 4.99) / 100;
+import { getIndexClippedDenoisingStart, getUpscaleDenoisingStart } from './denoisingStart';
+import {
+ activeUpscaleComponents,
+ getUpscaleValidationReasons,
+ upscaleArchitectureFor,
+ upscaleDenoiseDimension,
+ wiresUpscaleNegativePrompt,
+} from './settings';
export const getUpscaleControlNetValues = (structure: number) => {
const splitPoint = (structure + 10) * 0.025 + 0.3;
@@ -42,6 +47,17 @@ export const getUpscaleControlNetValues = (structure: number) => {
};
};
+/**
+ * Z-Image takes one control, not SD's pair. At Structure 0 it sits at the bottom of the adapter's
+ * recommended 0.65-0.80 and lets go for the last quarter of the pass, where the detail is drawn;
+ * the slider runs it from a light early nudge (0.3, first half) to holding the whole pass at 1.0.
+ */
+export const getZImageTileControlValues = (structure: number) => ({
+ beginStepPercent: 0,
+ controlContextScale: 0.65 + structure * 0.035,
+ endStepPercent: 0.75 + structure * 0.025,
+});
+
const addUpscaleMetadata = (
graph: BackendGraphContract,
output: BackendInvocationContract,
@@ -54,14 +70,16 @@ const addUpscaleMetadata = (
}
const architecture = upscaleArchitectureFor(settings.model);
- // FLUX calls this guidance, not CFG, and its encoders have to be recalled with the rest.
- const guidanceField = architecture?.usesNegativePrompt
- ? { cfg_scale: settings.cfgScale }
- : { guidance: settings.cfgScale };
+ const components = activeUpscaleComponents(settings);
+ // FLUX calls this guidance, not CFG, and the encoders have to be recalled with the rest.
+ const guidanceField =
+ architecture?.negativePrompt === 'never' ? { guidance: settings.cfgScale } : { cfg_scale: settings.cfgScale };
const metadata = addNode(graph, {
...guidanceField,
- ...(settings.t5EncoderModel ? { t5_encoder: toModelIdentifier(settings.t5EncoderModel) } : {}),
- ...(settings.clipEmbedModel ? { clip_embed_model: toModelIdentifier(settings.clipEmbedModel) } : {}),
+ ...(components.t5EncoderModel ? { t5_encoder: toModelIdentifier(components.t5EncoderModel) } : {}),
+ ...(components.clipEmbedModel ? { clip_embed_model: toModelIdentifier(components.clipEmbedModel) } : {}),
+ ...(components.qwen3EncoderModel ? { qwen3_encoder: toModelIdentifier(components.qwen3EncoderModel) } : {}),
+ ...(components.qwen35EncoderModel ? { qwen3_5_encoder: toModelIdentifier(components.qwen35EncoderModel) } : {}),
creativity: settings.creativity,
id: 'core_metadata',
// Runs after the path builder, so the graph already holds the LoRAs this architecture loads.
@@ -85,7 +103,7 @@ const addUpscaleMetadata = (
});
addEdge(graph, graph.nodes.positive_prompt, 'value', metadata, 'positive_prompt');
- if (architecture?.usesNegativePrompt) {
+ if (wiresUpscaleNegativePrompt(settings.model, settings.cfgScale)) {
addEdge(graph, graph.nodes.negative_prompt, 'value', metadata, 'negative_prompt');
}
addEdge(graph, graph.nodes.seed, 'value', metadata, 'seed');
@@ -105,14 +123,22 @@ interface UpscalePathContext {
graph: BackendGraphContract;
settings: UpscaleWidgetValues;
model: MainModelConfig;
+ /** The encoders this main model reads. A field it has no slot for is null here, whatever the widget holds. */
+ components: ReturnType<typeof activeUpscaleComponents>;
destination: ResultDestination;
projectSettings: GenerationProjectSettings;
positivePrompt: BackendInvocationContract;
negativePrompt: BackendInvocationContract;
seed: BackendInvocationContract;
- unsharpMask: BackendInvocationContract;
+ /**
+ * The enlarged image, at whatever size Spandrel produced. That is not always `denoiseSize`: a
+ * model that does not enlarge makes Spandrel ignore the scale. See `fitFrameToDenoiseSize`.
+ */
+ frame: BackendInvocationContract;
/** The frame size the second pass will run at, already floored to the architecture's grid. */
denoiseSize: { width: number; height: number };
+ /** Where the pass starts, already translated into this architecture's denoise node's terms. */
+ denoisingStart: number;
}
interface UpscalePathResult {
@@ -124,6 +150,33 @@ interface UpscalePathResult {
type UpscalePathBuilder = (context: UpscalePathContext) => UpscalePathResult;
+/**
+ * Resize the frame to the size a builder states as a literal on its denoise node.
+ *
+ * The literal is computed from the scale, but Spandrel ignores the scale for a model that does not
+ * enlarge (a 1x restoration model), and it rounds to a multiple of 8 where `flux_denoise` and
+ * `z_image_denoise` take multiples of 16. Either way the latents would disagree with the node's size,
+ * and the pass would fail -- after the upscale has run. SD needs none of this: its sizes follow the
+ * frame through edges.
+ */
+const fitFrameToDenoiseSize = (
+ graph: BackendGraphContract,
+ frame: BackendInvocationContract,
+ denoiseSize: { width: number; height: number }
+): BackendInvocationContract => {
+ const fitted = addNode(graph, {
+ height: denoiseSize.height,
+ id: 'fit_to_grid',
+ resample_mode: 'bicubic',
+ type: 'img_resize',
+ width: denoiseSize.width,
+ });
+
+ addEdge(graph, frame, 'image', fitted, 'image');
+
+ return fitted;
+};
+
const buildSdUpscalePath: UpscalePathBuilder = ({
graph,
settings,
@@ -133,7 +186,8 @@ const buildSdUpscalePath: UpscalePathBuilder = ({
positivePrompt,
negativePrompt,
seed,
- unsharpMask,
+ frame,
+ denoisingStart,
}) => {
const { tileControlnetModel } = settings;
@@ -161,7 +215,7 @@ const buildSdUpscalePath: UpscalePathBuilder = ({
const denoise = addNode(graph, {
cfg_scale: settings.cfgScale,
denoising_end: 1,
- denoising_start: getUpscaleDenoisingStart(settings.creativity),
+ denoising_start: denoisingStart,
id: 'tiled_multidiffusion_denoise_latents',
scheduler: coerceSchedulerForGraph(model, settings.scheduler),
steps: settings.steps,
@@ -187,9 +241,9 @@ const buildSdUpscalePath: UpscalePathBuilder = ({
let clip2Source: BackendInvocationContract | undefined = model.base === 'sdxl' ? modelLoader : undefined;
addEdge(graph, seed, 'value', noise, 'seed');
- addEdge(graph, unsharpMask, 'width', noise, 'width');
- addEdge(graph, unsharpMask, 'height', noise, 'height');
- addEdge(graph, unsharpMask, 'image', imageToLatents, 'image');
+ addEdge(graph, frame, 'width', noise, 'width');
+ addEdge(graph, frame, 'height', noise, 'height');
+ addEdge(graph, frame, 'image', imageToLatents, 'image');
if (model.base === 'sdxl') {
addEdge(graph, positivePrompt, 'value', posCond, 'prompt');
@@ -262,8 +316,8 @@ const buildSdUpscalePath: UpscalePathBuilder = ({
});
const controlNetCollector = addNode(graph, { id: 'controlnet_collector', type: 'collect' });
- addEdge(graph, unsharpMask, 'image', controlNet1, 'image');
- addEdge(graph, unsharpMask, 'image', controlNet2, 'image');
+ addEdge(graph, frame, 'image', controlNet1, 'image');
+ addEdge(graph, frame, 'image', controlNet2, 'image');
addEdge(graph, controlNet1, 'control', controlNetCollector, 'item');
addEdge(graph, controlNet2, 'control', controlNetCollector, 'item');
addEdge(graph, controlNetCollector, 'collection', denoise, 'control');
@@ -280,17 +334,19 @@ const buildFluxUpscalePath: UpscalePathBuilder = ({
graph,
settings,
model,
+ components,
destination,
positivePrompt,
seed,
- unsharpMask,
+ frame,
denoiseSize,
+ denoisingStart,
}) => {
const modelLoader = addNode(graph, {
- clip_embed_model: settings.clipEmbedModel ? toModelIdentifier(settings.clipEmbedModel) : undefined,
+ clip_embed_model: components.clipEmbedModel ? toModelIdentifier(components.clipEmbedModel) : undefined,
id: 'model_loader',
model: toModelIdentifier(model),
- t5_encoder_model: settings.t5EncoderModel ? toModelIdentifier(settings.t5EncoderModel) : undefined,
+ t5_encoder_model: components.t5EncoderModel ? toModelIdentifier(components.t5EncoderModel) : undefined,
type: 'flux_model_loader',
vae_model: settings.vae ? toModelIdentifier(settings.vae) : undefined,
});
@@ -304,16 +360,6 @@ const buildFluxUpscalePath: UpscalePathBuilder = ({
: modelLoader;
const posCond = addNode(graph, { id: 'pos_cond', type: 'flux_text_encoder' });
const posCondCollect = addNode(graph, { id: 'pos_cond_collect', type: 'collect' });
- // Spandrel rounds to a multiple of 8; `flux_denoise` accepts only multiples of 16 and rejects the
- // rest *after* the upscale has run. Resizing here makes the frame, its latents and the denoise
- // size agree, and lets the compiler state the size rather than defer it to an edge.
- const fitToGrid = addNode(graph, {
- height: denoiseSize.height,
- id: 'fit_to_grid',
- resample_mode: 'bicubic',
- type: 'img_resize',
- width: denoiseSize.width,
- });
const imageToLatents = addNode(graph, {
id: 'i2l',
tile_size: settings.tileSize,
@@ -322,7 +368,7 @@ const buildFluxUpscalePath: UpscalePathBuilder = ({
});
const denoise = addNode(graph, {
denoising_end: 1,
- denoising_start: getUpscaleDenoisingStart(settings.creativity),
+ denoising_start: denoisingStart,
guidance: settings.cfgScale,
height: denoiseSize.height,
id: 'denoise_latents',
@@ -349,8 +395,7 @@ const buildFluxUpscalePath: UpscalePathBuilder = ({
addEdge(graph, loraSource, 'transformer', denoise, 'transformer');
addEdge(graph, seed, 'value', denoise, 'seed');
- addEdge(graph, unsharpMask, 'image', fitToGrid, 'image');
- addEdge(graph, fitToGrid, 'image', imageToLatents, 'image');
+ addEdge(graph, fitFrameToDenoiseSize(graph, frame, denoiseSize), 'image', imageToLatents, 'image');
addEdge(graph, modelLoader, 'vae', imageToLatents, 'vae');
addEdge(graph, imageToLatents, 'latents', denoise, 'latents');
addEdge(graph, denoise, 'latents', output, 'latents');
@@ -359,14 +404,232 @@ const buildFluxUpscalePath: UpscalePathBuilder = ({
return { output, title: `${model.name} upscale` };
};
+/**
+ * Z-Image runs the pass whole like FLUX.1, both VAE ends tiled. Its tile ControlNet is optional: a
+ * pass that does not tile has no seams to hold together, so the ControlNet only lets Structure pull
+ * the result back toward the enlarged frame. The ControlNet encodes that frame inside the denoise,
+ * at the same size as `i2l` does, so it is tiled the same way.
+ */
+const buildZImageUpscalePath: UpscalePathBuilder = ({
+ graph,
+ settings,
+ model,
+ components,
+ destination,
+ positivePrompt,
+ negativePrompt,
+ seed,
+ frame,
+ denoiseSize,
+ denoisingStart,
+}) => {
+ const fitted = fitFrameToDenoiseSize(graph, frame, denoiseSize);
+ const modelLoader = addNode(graph, {
+ id: 'model_loader',
+ model: toModelIdentifier(model),
+ qwen3_encoder_model: components.qwen3EncoderModel ? toModelIdentifier(components.qwen3EncoderModel) : undefined,
+ // A Diffusers or complete SDNQ install supplies its own VAE and Qwen3 where none is chosen.
+ qwen3_source_model: isBundledMainForBase('z-image')(model) ? toModelIdentifier(model) : undefined,
+ type: 'z_image_model_loader',
+ vae_model: settings.vae ? toModelIdentifier(settings.vae) : undefined,
+ });
+ const activeLoras = getActiveCompatibleLoras({ loras: settings.loras }, model);
+ const loraSource = activeLoras.length
+ ? addTransformerLoraCollectionLoader(graph, activeLoras, 'z_image_lora_collection_loader', modelLoader, [
+ 'transformer',
+ 'qwen3_encoder',
+ ])
+ : modelLoader;
+ const imageToLatents = addNode(graph, {
+ id: 'i2l',
+ tile_size: settings.tileSize,
+ tiled: true,
+ type: 'z_image_i2l',
+ });
+ const denoise = addNode(graph, {
+ denoising_end: 1,
+ denoising_start: denoisingStart,
+ guidance_scale: settings.cfgScale,
+ height: denoiseSize.height,
+ id: 'denoise_latents',
+ scheduler: coerceSchedulerForGraph(model, settings.scheduler),
+ steps: settings.steps,
+ type: 'z_image_denoise',
+ width: denoiseSize.width,
+ });
+ const output = addNode(graph, {
+ id: 'upscale_output',
+ is_intermediate: destination === 'canvas',
+ tile_size: settings.tileSize,
+ tiled: true,
+ type: 'z_image_l2i',
+ use_cache: false,
+ });
+
+ addPromptConditioning(graph, {
+ denoise,
+ encoderFields: [{ field: 'qwen3_encoder', source: loraSource }],
+ encoderType: 'z_image_text_encoder',
+ negativePrompt: wiresUpscaleNegativePrompt(model, settings.cfgScale) ? negativePrompt : null,
+ positivePrompt,
+ });
+ addEdge(graph, loraSource, 'transformer', denoise, 'transformer');
+ addEdge(graph, seed, 'value', denoise, 'seed');
+ addEdge(graph, fitted, 'image', imageToLatents, 'image');
+ addEdge(graph, modelLoader, 'vae', imageToLatents, 'vae');
+ addEdge(graph, imageToLatents, 'latents', denoise, 'latents');
+ // The denoise encodes its control image itself, with this VAE.
+ addEdge(graph, modelLoader, 'vae', denoise, 'vae');
+ addEdge(graph, denoise, 'latents', output, 'latents');
+ addEdge(graph, modelLoader, 'vae', output, 'vae');
+
+ if (settings.tileControlnetModel) {
+ const control = getZImageTileControlValues(settings.structure);
+ const tileControl = addNode(graph, {
+ begin_step_percent: control.beginStepPercent,
+ control_context_scale: control.controlContextScale,
+ control_model: toModelIdentifier(settings.tileControlnetModel),
+ end_step_percent: control.endStepPercent,
+ id: 'tile_control',
+ tile_size: settings.tileSize,
+ tiled: true,
+ type: 'z_image_control',
+ });
+
+ addEdge(graph, fitted, 'image', tileControl, 'image');
+ addEdge(graph, tileControl, 'control', denoise, 'control');
+ }
+
+ return { output, title: `${model.name} upscale` };
+};
+
+/**
+ * Anima has no tile ControlNet (only LLLite adapters), so like FLUX.1 the pass is anchored by where
+ * it starts. Its decode has no tiling switch: `anima_l2i` tiles on its own once an untiled decode
+ * would take most of the card.
+ */
+const buildAnimaUpscalePath: UpscalePathBuilder = ({
+ graph,
+ settings,
+ model,
+ components,
+ destination,
+ positivePrompt,
+ negativePrompt,
+ seed,
+ frame,
+ denoiseSize,
+ denoisingStart,
+}) => {
+ const modelLoader = addNode(graph, {
+ id: 'model_loader',
+ model: toModelIdentifier(model),
+ qwen3_5_encoder_model: components.qwen35EncoderModel ? toModelIdentifier(components.qwen35EncoderModel) : undefined,
+ qwen3_encoder_model: components.qwen3EncoderModel ? toModelIdentifier(components.qwen3EncoderModel) : undefined,
+ type: 'anima_model_loader',
+ vae_model: settings.vae ? toModelIdentifier(settings.vae) : undefined,
+ });
+ const activeLoras = getActiveCompatibleLoras({ loras: settings.loras }, model);
+ const loraSource = activeLoras.length
+ ? addTransformerLoraCollectionLoader(graph, activeLoras, 'anima_lora_collection_loader', modelLoader, [
+ 'transformer',
+ 'qwen3_encoder',
+ ])
+ : modelLoader;
+ const imageToLatents = addNode(graph, {
+ id: 'i2l',
+ tile_size: settings.tileSize,
+ tiled: true,
+ type: 'anima_i2l',
+ });
+ const denoise = addNode(graph, {
+ denoising_end: 1,
+ denoising_start: denoisingStart,
+ guidance_scale: settings.cfgScale,
+ height: denoiseSize.height,
+ id: 'denoise_latents',
+ scheduler: coerceSchedulerForGraph(model, settings.scheduler),
+ steps: settings.steps,
+ type: 'anima_denoise',
+ width: denoiseSize.width,
+ });
+ const output = addNode(graph, {
+ id: 'upscale_output',
+ is_intermediate: destination === 'canvas',
+ type: 'anima_l2i',
+ use_cache: false,
+ });
+
+ addPromptConditioning(graph, {
+ denoise,
+ encoderFields: [
+ { field: 'qwen3_encoder', source: loraSource },
+ // Straight from the loader: the LoRA collection loader passes Qwen3.5 through untouched.
+ ...(components.qwen35EncoderModel ? [{ field: 'qwen3_5_encoder', source: modelLoader }] : []),
+ ],
+ encoderType: 'anima_text_encoder',
+ negativePrompt: wiresUpscaleNegativePrompt(model, settings.cfgScale) ? negativePrompt : null,
+ positivePrompt,
+ });
+ addEdge(graph, loraSource, 'transformer', denoise, 'transformer');
+ addEdge(graph, seed, 'value', denoise, 'seed');
+ addEdge(graph, fitFrameToDenoiseSize(graph, frame, denoiseSize), 'image', imageToLatents, 'image');
+ addEdge(graph, modelLoader, 'vae', imageToLatents, 'vae');
+ addEdge(graph, imageToLatents, 'latents', denoise, 'latents');
+ addEdge(graph, denoise, 'latents', output, 'latents');
+ addEdge(graph, modelLoader, 'vae', output, 'vae');
+
+ return { output, title: `${model.name} upscale` };
+};
+
+/**
+ * Z-Image's and Anima's text encoders take their encoders on named fields and hand the denoise a
+ * collected list; the negative branch exists only where the caller decided it is read.
+ */
+const addPromptConditioning = (
+ graph: BackendGraphContract,
+ {
+ denoise,
+ encoderFields,
+ encoderType,
+ negativePrompt,
+ positivePrompt,
+ }: {
+ denoise: BackendInvocationContract;
+ encoderFields: readonly { field: string; source: BackendInvocationContract }[];
+ encoderType: string;
+ negativePrompt: BackendInvocationContract | null;
+ positivePrompt: BackendInvocationContract;
+ }
+): void => {
+ const branches = [
+ { conditioningField: 'positive_conditioning', prefix: 'pos', prompt: positivePrompt },
+ ...(negativePrompt ? [{ conditioningField: 'negative_conditioning', prefix: 'neg', prompt: negativePrompt }] : []),
+ ];
+
+ for (const { conditioningField, prefix, prompt } of branches) {
+ const encoder = addNode(graph, { id: `${prefix}_cond`, type: encoderType });
+ const collect = addNode(graph, { id: `${prefix}_cond_collect`, type: 'collect' });
+
+ for (const { field, source } of encoderFields) {
+ addEdge(graph, source, field, encoder, field);
+ }
+ addEdge(graph, prompt, 'value', encoder, 'prompt');
+ addEdge(graph, encoder, 'conditioning', collect, 'item');
+ addEdge(graph, collect, 'collection', denoise, conditioningField);
+ }
+};
+
/**
* Keyed by the same bases as `UPSCALE_ARCHITECTURES`, and `satisfies` makes that a compile error to
* break: declaring an architecture supported without giving it a builder will not type-check.
*/
const UPSCALE_PATH_BUILDERS = {
+ anima: buildAnimaUpscalePath,
flux: buildFluxUpscalePath,
'sd-1': buildSdUpscalePath,
sdxl: buildSdUpscalePath,
+ 'z-image': buildZImageUpscalePath,
} satisfies Record<UpscaleBase, UpscalePathBuilder>;
export const compileUpscaleGraph = (
@@ -393,11 +656,16 @@ export const compileUpscaleGraph = (
throw new Error(`Upscale does not support ${model.base} main models.`);
}
- const grid = upscaleArchitectureFor(model)?.denoiseGrid ?? 8;
+ const architecture = upscaleArchitectureFor(model);
+ const grid = architecture?.denoiseGrid ?? 8;
const denoiseSize = {
height: upscaleDenoiseDimension(inputImage.height, settings.scale, grid),
width: upscaleDenoiseDimension(inputImage.width, settings.scale, grid),
};
+ const valueClippedStart = getUpscaleDenoisingStart(settings.creativity);
+ const denoisingStart = architecture?.indexClippedShift
+ ? getIndexClippedDenoisingStart(valueClippedStart, settings.steps, architecture.indexClippedShift(denoiseSize))
+ : valueClippedStart;
const graph: BackendGraphContract = { edges: [], id: 'upscale-graph', nodes: {} };
const positivePrompt = addNode(graph, { id: 'positive_prompt', type: 'string' });
const negativePrompt = addNode(graph, { id: 'negative_prompt', type: 'string' });
@@ -415,8 +683,11 @@ export const compileUpscaleGraph = (
addEdge(graph, spandrelAutoscale, 'image', unsharpMask, 'image');
const { output, title } = buildPath({
+ components: activeUpscaleComponents(settings),
denoiseSize,
+ denoisingStart,
destination,
+ frame: unsharpMask,
graph,
model,
negativePrompt,
@@ -424,7 +695,6 @@ export const compileUpscaleGraph = (
projectSettings,
seed,
settings,
- unsharpMask,
});
addUpscaleMetadata(graph, output, settings, projectSettings, randDevice);
diff --git a/invokeai/frontend/webv2/src/features/upscale/core/settings.test.ts b/invokeai/frontend/webv2/src/features/upscale/core/settings.test.ts
index db863226b6..9482be0f55 100644
--- a/invokeai/frontend/webv2/src/features/upscale/core/settings.test.ts
+++ b/invokeai/frontend/webv2/src/features/upscale/core/settings.test.ts
@@ -1,7 +1,11 @@
import type { GenerateLora, VaeModelConfig } from '@features/generation/contracts';
import type { ModelConfig } from '@features/models';
-import { seedArchitectureCapabilities } from '@features/generation/core/architectureCapabilities.testing';
+import { resetArchitectureCapabilities } from '@features/generation/core/architectureCapabilities';
+import {
+ architectureCapabilitiesFixture,
+ seedArchitectureCapabilities,
+} from '@features/generation/core/architectureCapabilities.testing';
import { describe, expect, it } from 'vitest';
import {
@@ -12,7 +16,11 @@ import {
normalizeUpscaleWidgetValues,
spandrelAutoscaleDimension,
upscaleDenoiseDimension,
+ activeUpscaleComponents,
+ isTileControlNetCandidate,
+ selectUpscaleMainModel,
syncUpscaleWidgetValuesWithModels,
+ UPSCALE_ARCHITECTURES,
UPSCALE_PRESETS,
} from './settings';
@@ -203,6 +211,243 @@ describe('architecture-driven validation', () => {
});
});
+describe('the architecture table', () => {
+ it.each(Object.entries(UPSCALE_ARCHITECTURES))('agrees with the served %s capabilities', (base, architecture) => {
+ // The fixture is the response the backend serves, pinned by `test_capabilities_fixture.py`, so
+ // a grid or negative-prompt change on a denoise node fails here instead of at enqueue.
+ const served = architectureCapabilitiesFixture.find((row) => row.base === base && row.variant === null);
+
+ expect(served?.features.dimension_grid).toBe(architecture.denoiseGrid);
+ expect(served?.features.negative_prompt.usage).toBe(architecture.negativePrompt);
+ });
+});
+
+const withVariant = (config: ModelConfig, variant: string): ModelConfig => ({ ...config, variant }) as ModelConfig;
+
+const QWEN3_4B = withVariant(model('qwen3-4b', 'qwen3_encoder', 'any'), 'qwen3_4b');
+const QWEN3_8B = withVariant(model('qwen3-8b', 'qwen3_encoder', 'any'), 'qwen3_8b');
+const QWEN3_06B = withVariant(model('qwen3-06b', 'qwen3_encoder', 'any'), 'qwen3_06b');
+const QWEN35 = withVariant(model('qwen35', 'qwen3_5_encoder', 'any'), 'qwen3_5_4b');
+
+describe('Z-Image and Anima components', () => {
+ const ready = (models: ModelConfig[]) => ({
+ ...createDefaultUpscaleWidgetValues(models),
+ inputImage: { height: 64, image_name: 'in.png', width: 64 },
+ });
+
+ it('gives each architecture the Qwen3 its loader reads and the VAE it decodes with', () => {
+ const shared = [model('spandrel', 'spandrel_image_to_image', 'any'), QWEN3_06B, QWEN3_4B];
+ const zImage = ready([
+ model('z', 'main', 'z-image'),
+ ...shared,
+ model('anima-vae', 'vae', 'qwen-image'),
+ model('flux-vae', 'vae', 'flux'),
+ ]);
+ const anima = ready([
+ withVariant(model('a', 'main', 'anima'), 'anima_qwen3'),
+ ...shared,
+ model('flux-vae', 'vae', 'flux'),
+ model('anima-vae', 'vae', 'qwen-image'),
+ ]);
+
+ expect([zImage.qwen3EncoderModel?.key, zImage.vae?.key]).toEqual(['qwen3-4b', 'flux-vae']);
+ expect([anima.qwen3EncoderModel?.key, anima.vae?.key]).toEqual(['qwen3-06b', 'anima-vae']);
+ expect(getUpscaleValidationReasons(zImage)).toEqual([]);
+ expect(getUpscaleValidationReasons(anima)).toEqual([]);
+ });
+
+ it('swaps the encoder when the main model moves to the other architecture', () => {
+ const models = [
+ model('z', 'main', 'z-image'),
+ withVariant(model('a', 'main', 'anima'), 'anima_qwen3'),
+ model('spandrel', 'spandrel_image_to_image', 'any'),
+ QWEN3_4B,
+ QWEN3_06B,
+ ];
+ const zImage = createDefaultUpscaleWidgetValues(models);
+ const anima = syncUpscaleWidgetValuesWithModels({ ...zImage, model: models[1] as typeof zImage.model }, models);
+
+ expect(zImage.qwen3EncoderModel?.key).toBe('qwen3-4b');
+ expect(anima.qwen3EncoderModel?.key).toBe('qwen3-06b');
+ });
+
+ it('asks Anima-3.8B for the Qwen3.5 encoder and no other Anima for it', () => {
+ const base = [model('spandrel', 'spandrel_image_to_image', 'any'), QWEN3_06B, model('vae', 'vae', 'qwen-image')];
+
+ expect(
+ getUpscaleValidationReasons(ready([withVariant(model('a', 'main', 'anima'), 'anima_qwen35'), ...base]))
+ ).toEqual(['Upscale needs a Qwen3.5 encoder for this main model.']);
+ expect(
+ ready([withVariant(model('a', 'main', 'anima'), 'anima_qwen35'), ...base, QWEN35]).qwen35EncoderModel?.key
+ ).toBe('qwen35');
+ expect(
+ ready([withVariant(model('a', 'main', 'anima'), 'anima_qwen3'), ...base, QWEN35]).qwen35EncoderModel
+ ).toBeNull();
+ });
+
+ it('names a missing Qwen3 encoder rather than failing in the loader', () => {
+ const values = ready([
+ model('z', 'main', 'z-image'),
+ model('spandrel', 'spandrel_image_to_image', 'any'),
+ QWEN3_06B,
+ ]);
+
+ expect(getUpscaleValidationReasons(values)).toEqual([
+ 'Upscale needs a Qwen3 4B encoder for this main model.',
+ 'Upscale needs a VAE for this main model.',
+ ]);
+ });
+
+ it('never gives Z-Image the 8B, which its 2560-wide caption embedder cannot take', () => {
+ // FLUX.2 Klein's 8B sorts first here, as it can by name in a real install.
+ const values = ready([
+ model('z', 'main', 'z-image'),
+ model('spandrel', 'spandrel_image_to_image', 'any'),
+ QWEN3_8B,
+ QWEN3_4B,
+ ]);
+
+ expect(values.qwen3EncoderModel?.key).toBe('qwen3-4b');
+ expect(getUpscaleValidationReasons({ ...values, qwen3EncoderModel: QWEN3_8B as never })).toContain(
+ 'qwen3-8b is not a Qwen3 4B encoder this main model can use.'
+ );
+ });
+
+ it('keeps a hand-picked encoder through a switch to an architecture that does not read it', () => {
+ const models = [
+ model('flux', 'main', 'flux'),
+ model('z', 'main', 'z-image'),
+ model('spandrel', 'spandrel_image_to_image', 'any'),
+ model('t5-a', 't5_encoder', 'any'),
+ model('t5-b', 't5_encoder', 'any'),
+ model('clip', 'clip_embed', 'any'),
+ QWEN3_4B,
+ ];
+ const flux = { ...createDefaultUpscaleWidgetValues(models), t5EncoderModel: models[4] as never };
+ const zImage = syncUpscaleWidgetValuesWithModels({ ...flux, model: models[1] as typeof flux.model }, models);
+ const backToFlux = syncUpscaleWidgetValuesWithModels({ ...zImage, model: models[0] as typeof flux.model }, models);
+
+ expect(zImage.t5EncoderModel?.key).toBe('t5-b');
+ expect(activeUpscaleComponents(zImage)).toMatchObject({
+ qwen3EncoderModel: { key: 'qwen3-4b' },
+ t5EncoderModel: null,
+ });
+ expect(backToFlux.t5EncoderModel?.key).toBe('t5-b');
+ });
+});
+
+describe('picking a main model', () => {
+ const MODELS_BY_BASE = [
+ model('sd15', 'main', 'sd-1'),
+ model('flux', 'main', 'flux'),
+ model('z-turbo', 'main', 'z-image'),
+ withVariant(model('z-base', 'main', 'z-image'), 'zbase'),
+ withVariant(model('anima', 'main', 'anima'), 'anima_qwen3'),
+ withVariant(model('anima-38', 'main', 'anima'), 'anima_qwen35'),
+ ];
+ const cfgAfterPicking = (key: string) =>
+ selectUpscaleMainModel(
+ { ...createDefaultUpscaleWidgetValues(MODELS_BY_BASE), cfgScale: 3 },
+ MODELS_BY_BASE.find((candidate) => candidate.key === key) as never,
+ MODELS_BY_BASE
+ ).cfgScale;
+
+ it('runs Z-Image and Anima at the CFG their model is served with', () => {
+ // Turbo is distilled for CFG 1; anything above doubles every step at upscale resolution.
+ expect(['z-turbo', 'z-base', 'anima', 'anima-38'].map(cfgAfterPicking)).toEqual([1, 4, 4.5, 6]);
+ });
+
+ it('leaves SD and FLUX at the CFG the user set', () => {
+ expect(['sd15', 'flux'].map(cfgAfterPicking)).toEqual([3, 3]);
+ });
+
+ it('gives SD and FLUX the widget CFG back after a model that set its own', () => {
+ const fromTurbo = selectUpscaleMainModel(
+ { ...createDefaultUpscaleWidgetValues(MODELS_BY_BASE), cfgScale: 3 },
+ MODELS_BY_BASE[2] as never,
+ MODELS_BY_BASE
+ );
+ const fromAnima38 = selectUpscaleMainModel(fromTurbo, MODELS_BY_BASE[5] as never, MODELS_BY_BASE);
+
+ expect(fromTurbo.cfgScale).toBe(1);
+ expect(selectUpscaleMainModel(fromTurbo, MODELS_BY_BASE[0] as never, MODELS_BY_BASE).cfgScale).toBe(2);
+ expect(selectUpscaleMainModel(fromAnima38, MODELS_BY_BASE[1] as never, MODELS_BY_BASE).cfgScale).toBe(2);
+ });
+
+ it("gives a model the widget picks on its own that model's CFG, as a pick would", () => {
+ // A fresh widget is created without models and gets its first one from the sync.
+ const fresh = syncUpscaleWidgetValuesWithModels(createDefaultUpscaleWidgetValues(), [MODELS_BY_BASE[4]!]);
+ // An uninstalled Z-Image Turbo falls back to SD, which gets the widget's CFG, not Turbo's 1.
+ const turbo = selectUpscaleMainModel(fresh, MODELS_BY_BASE[2] as never, MODELS_BY_BASE);
+ const fellBack = syncUpscaleWidgetValuesWithModels(turbo, [MODELS_BY_BASE[0]!]);
+
+ expect(fresh.cfgScale).toBe(4.5);
+ expect([turbo.cfgScale, fellBack.model?.key, fellBack.cfgScale]).toEqual([1, 'sd15', 2]);
+ });
+
+ it('leaves CFG alone while the served table is missing, rather than writing the fallback 7', () => {
+ resetArchitectureCapabilities();
+
+ const fresh = syncUpscaleWidgetValuesWithModels(createDefaultUpscaleWidgetValues(), [MODELS_BY_BASE[2]!]);
+
+ expect([fresh.model?.key, fresh.cfgScale]).toEqual(['z-turbo', 2]);
+ });
+
+ it('keeps the CFG the user tuned when the same model is picked again', () => {
+ const tuned = {
+ ...selectUpscaleMainModel(
+ createDefaultUpscaleWidgetValues(MODELS_BY_BASE),
+ MODELS_BY_BASE[4] as never,
+ MODELS_BY_BASE
+ ),
+ cfgScale: 5,
+ };
+
+ expect(selectUpscaleMainModel(tuned, MODELS_BY_BASE[4] as never, MODELS_BY_BASE).cfgScale).toBe(5);
+ });
+
+ it('asks index-clipping architectures for two steps, since one leaves no partial pass', () => {
+ const zImage = { ...createDefaultUpscaleWidgetValues([model('z', 'main', 'z-image')]), steps: 1 };
+ const sd = { ...createDefaultUpscaleWidgetValues([model('sd15', 'main', 'sd-1')]), steps: 1 };
+
+ expect(getUpscaleValidationReasons(zImage)).toContain('Steps must be between 2 and 1000.');
+ expect(getUpscaleValidationReasons(sd).some((reason) => reason.startsWith('Steps'))).toBe(false);
+ });
+});
+
+describe('tile ControlNet per architecture', () => {
+ const zImage = { base: 'z-image' };
+ const tile = model('zt', 'controlnet', 'z-image', 'Z-Image ControlNet Tile');
+ const union = model('zu', 'controlnet', 'z-image', 'Z-Image ControlNet Union');
+
+ it("accepts only Z-Image's tile model: its Union has no tile mode", () => {
+ expect(isTileControlNetCandidate(tile, zImage)).toBe(true);
+ expect(isTileControlNetCandidate(union, zImage)).toBe(false);
+ expect(isTileControlNetCandidate(model('su', 'controlnet', 'sdxl', 'xinsir union'), { base: 'sdxl' })).toBe(true);
+ });
+
+ it('leaves the optional Z-Image ControlNet off until chosen, and keeps it once it is', () => {
+ const models = [model('z', 'main', 'z-image'), model('spandrel', 'spandrel_image_to_image', 'any'), tile];
+ const defaults = createDefaultUpscaleWidgetValues(models);
+ const chosen = syncUpscaleWidgetValuesWithModels({ ...defaults, tileControlnetModel: tile as never }, models);
+
+ expect(defaults.tileControlnetModel).toBeNull();
+ expect(syncUpscaleWidgetValuesWithModels(defaults, models).tileControlnetModel).toBeNull();
+ expect(chosen.tileControlnetModel?.key).toBe('zt');
+ });
+
+ it('refuses a Union model chosen for Z-Image', () => {
+ const values = {
+ ...createDefaultUpscaleWidgetValues([model('z', 'main', 'z-image')]),
+ tileControlnetModel: union as never,
+ };
+
+ expect(getUpscaleValidationReasons(values)).toContain(
+ 'The Tile ControlNet must match the main model base and be a Tile model.'
+ );
+ });
+});
+
describe('upscaleDenoiseDimension', () => {
it('floors to the grid the architecture demands, not to the one Spandrel used', () => {
// 1020 * 2 = 2040: a legal Spandrel size that flux_denoise rejects.
diff --git a/invokeai/frontend/webv2/src/features/upscale/core/settings.ts b/invokeai/frontend/webv2/src/features/upscale/core/settings.ts
index 3fec6fd6cc..abd8363c2f 100644
--- a/invokeai/frontend/webv2/src/features/upscale/core/settings.ts
+++ b/invokeai/frontend/webv2/src/features/upscale/core/settings.ts
@@ -11,6 +11,11 @@ import type { ModelConfig } from '@features/models';
import {
DEFAULT_NEGATIVE_PROMPT_HEIGHT_PX,
DEFAULT_POSITIVE_PROMPT_HEIGHT_PX,
+ getDefaultGenerateSettings,
+ hasArchitectureCapabilities,
+ isAnimaQwen35Encoder,
+ isAnimaQwen3Encoder,
+ isBundledMainForBase,
isLoraCompatibleWithModel,
isLoraModelConfig,
isMainModelConfig,
@@ -27,6 +32,85 @@ import { isSeedMode, SEED_MAX } from '@platform/core/seed';
import type { SpandrelModelConfig, TileControlNetModelConfig, UpscaleWidgetValues } from './types';
+import { ANIMA_SCHEDULE_SHIFT, zImageScheduleShift } from './denoisingStart';
+
+/** A text encoder the widget can be asked for; each is its own persisted field. */
+export type UpscaleComponentField = 't5EncoderModel' | 'clipEmbedModel' | 'qwen3EncoderModel' | 'qwen35EncoderModel';
+
+const UPSCALE_COMPONENT_TYPES: Record<UpscaleComponentField, string> = {
+ clipEmbedModel: 'clip_embed',
+ qwen35EncoderModel: 'qwen3_5_encoder',
+ qwen3EncoderModel: 'qwen3_encoder',
+ t5EncoderModel: 't5_encoder',
+};
+
+export const UPSCALE_COMPONENT_FIELDS = Object.keys(UPSCALE_COMPONENT_TYPES) as UpscaleComponentField[];
+
+export interface UpscaleComponentSlot {
+ readonly field: UpscaleComponentField;
+ /** Which installed models fit. Also the default pick, so it must be as narrow as the loader is. */
+ readonly accepts: (candidate: ModelConfig) => boolean;
+ /** Read in validation messages: "Upscale needs a {label} for this main model." */
+ readonly label: string;
+}
+
+const T5_ENCODER_SLOT: UpscaleComponentSlot = {
+ accepts: (candidate) => candidate.type === 't5_encoder',
+ field: 't5EncoderModel',
+ label: 'T5 encoder',
+};
+const CLIP_EMBED_SLOT: UpscaleComponentSlot = {
+ accepts: (candidate) => candidate.type === 'clip_embed',
+ field: 'clipEmbedModel',
+ label: 'CLIP Embed model',
+};
+// Z-Image and Anima both read a `qwen3_encoder`, but not the same one. Z-Image's caption embedder is
+// 2560 wide, so it takes the 4B and nothing else: Generate's shared filter also lets FLUX.2 Klein's
+// 8B through, which fails in the denoise -- here, after the upscale has run, and it would be the
+// automatic pick wherever its name sorts first. Anima's is the 0.6B.
+const Z_IMAGE_QWEN3_SLOT: UpscaleComponentSlot = {
+ accepts: (candidate) => candidate.type === 'qwen3_encoder' && candidate.variant === 'qwen3_4b',
+ field: 'qwen3EncoderModel',
+ label: 'Qwen3 4B encoder',
+};
+const ANIMA_QWEN3_SLOT: UpscaleComponentSlot = {
+ accepts: isAnimaQwen3Encoder,
+ field: 'qwen3EncoderModel',
+ label: 'Qwen3 0.6B encoder',
+};
+const ANIMA_QWEN35_SLOT: UpscaleComponentSlot = {
+ accepts: isAnimaQwen35Encoder,
+ field: 'qwen35EncoderModel',
+ label: 'Qwen3.5 encoder',
+};
+
+/** What a main model's loader must be handed. A model that bundles its own parts needs none of it. */
+export interface UpscaleComponents {
+ readonly slots: readonly UpscaleComponentSlot[];
+ readonly vae: boolean;
+}
+
+const NO_COMPONENTS: UpscaleComponents = { slots: [], vae: false };
+
+export interface UpscaleTileControlNet {
+ /**
+ * SD's multi-diffusion denoises tiles independently, and without a tile ControlNet they drift
+ * apart. Elsewhere the pass runs whole and the ControlNet is an extra anchor it can do without.
+ */
+ readonly required: boolean;
+ /**
+ * Nothing in a checkpoint says which mode it was trained for -- Z-Image's Tile and Union 2.1 are
+ * tensor-for-tensor identical -- so the name decides. Union models tile on SD and SDXL; Z-Image's
+ * Union does Canny, HED, Depth, Pose, MLSD and inpainting, but not tile.
+ */
+ readonly matchesName: (name: string) => boolean;
+}
+
+const nameIncludes =
+ (...needles: string[]) =>
+ (name: string): boolean =>
+ needles.some((needle) => name.toLowerCase().includes(needle));
+
/**
* Which main-model architectures the Upscale widget can drive, and what each one needs.
*
@@ -37,17 +121,17 @@ import type { SpandrelModelConfig, TileControlNetModelConfig, UpscaleWidgetValue
*/
export interface UpscaleArchitecture {
/**
- * A tile ControlNet anchors the second pass to the upscaled frame. Where one exists the widget
- * requires it and the Structure slider drives its weights; where it does not, Structure has
- * nothing to scale and is hidden rather than left inert.
+ * A tile ControlNet anchors the second pass to the upscaled frame, and the Structure slider drives
+ * its weights. Where the architecture has none, Structure has nothing to scale and is hidden rather
+ * than left inert.
*/
- readonly usesTileControlNet: boolean;
+ readonly tileControlNet: UpscaleTileControlNet | null;
/**
- * Whether the pipeline's parts must be picked separately. FLUX transformers ship as bare
- * checkpoints far more often than not, and `flux_model_loader` refuses those without an explicit
- * T5 encoder, CLIP Embed *and* VAE -- only a complete SDNQ pipeline install can supply its own.
+ * The parts the loader refuses to run without. Bare transformer checkpoints are the common case
+ * for every architecture past SDXL; only a bundled pipeline (Diffusers, complete SDNQ) carries its
+ * own text encoder and VAE.
*/
- readonly needsExplicitComponents: boolean;
+ readonly components: (model: MainModelConfig) => UpscaleComponents;
/**
* The size granularity the architecture's denoise node demands. Spandrel's autoscale rounds to a
* multiple of 8, which `flux_denoise` (multiple_of=16) rejects outright — after the upscale has
@@ -55,33 +139,86 @@ export interface UpscaleArchitecture {
* the size as a literal, so the graph cannot be built with a size the backend will refuse.
*/
readonly denoiseGrid: number;
- /** Guidance-distilled architectures ignore a negative prompt; showing one invites a silent no-op. */
- readonly usesNegativePrompt: boolean;
+ /**
+ * The served `FeaturesFacet` answer, pinned to it by test. Guidance-distilled architectures ignore
+ * a negative prompt, so showing one invites a silent no-op; `cfg-gated` ones read it only above
+ * CFG 1, which is the only case the graph wires it.
+ */
+ readonly negativePrompt: 'always' | 'cfg-gated' | 'never';
+ /**
+ * The schedule shift of a denoise node that clips `denoising_start` by step index rather than by
+ * value, for the frame it runs at. The compiler uses it to start such a node where FLUX would
+ * start for the same Creativity; null where the node clips by value or runs its own schedule.
+ */
+ readonly indexClippedShift: ((size: { width: number; height: number }) => number) | null;
+ /**
+ * Whether a new main model sets CFG to that model's served default. Z-Image Turbo is distilled for
+ * CFG 1, and anything above runs a second, unconditional pass per step at upscale resolution;
+ * Z-Image Base and Anima want 4 to 6. SD and FLUX keep the user's CFG -- SD's multi-diffusion pass
+ * is tuned to the widget's 2 -- and get that 2 back when the user comes from one of the others.
+ */
+ readonly takesModelGuidance: boolean;
/** Shown in validation messages, so a user reads "FLUX.1" rather than "flux". */
readonly label: string;
}
+const SD_TILE_CONTROLNET: UpscaleTileControlNet = { matchesName: nameIncludes('tile', 'union'), required: true };
+
export const UPSCALE_ARCHITECTURES = {
'sd-1': {
+ components: () => NO_COMPONENTS,
denoiseGrid: 8,
+ indexClippedShift: null,
label: 'SD1.5',
- needsExplicitComponents: false,
- usesNegativePrompt: true,
- usesTileControlNet: true,
+ negativePrompt: 'always',
+ takesModelGuidance: false,
+ tileControlNet: SD_TILE_CONTROLNET,
},
sdxl: {
+ components: () => NO_COMPONENTS,
denoiseGrid: 8,
+ indexClippedShift: null,
label: 'SDXL',
- needsExplicitComponents: false,
- usesNegativePrompt: true,
- usesTileControlNet: true,
+ negativePrompt: 'always',
+ takesModelGuidance: false,
+ tileControlNet: SD_TILE_CONTROLNET,
},
flux: {
+ // `flux_model_loader` refuses a bare transformer without T5, CLIP Embed *and* VAE. The backend
+ // also checks a self-contained SDNQ pipeline really has those submodels, which the model list
+ // does not expose; one missing a submodel passes here and the loader refuses it precisely.
+ components: (model) =>
+ model.format === 'sdnq_quantized' ? NO_COMPONENTS : { slots: [T5_ENCODER_SLOT, CLIP_EMBED_SLOT], vae: true },
denoiseGrid: 16,
+ indexClippedShift: null,
label: 'FLUX.1',
- needsExplicitComponents: true,
- usesNegativePrompt: false,
- usesTileControlNet: false,
+ negativePrompt: 'never',
+ takesModelGuidance: false,
+ tileControlNet: null,
+ },
+ 'z-image': {
+ // `z_image_model_loader` falls back to a bundled main model's own VAE and Qwen3.
+ components: (model) =>
+ isBundledMainForBase('z-image')(model) ? NO_COMPONENTS : { slots: [Z_IMAGE_QWEN3_SLOT], vae: true },
+ denoiseGrid: 16,
+ indexClippedShift: zImageScheduleShift,
+ label: 'Z-Image',
+ negativePrompt: 'cfg-gated',
+ takesModelGuidance: true,
+ tileControlNet: { matchesName: nameIncludes('tile'), required: false },
+ },
+ anima: {
+ // Anima-3.8B's semantic connector also reads Qwen3.5; no other Anima model does.
+ components: (model) => ({
+ slots: model.variant === 'anima_qwen35' ? [ANIMA_QWEN3_SLOT, ANIMA_QWEN35_SLOT] : [ANIMA_QWEN3_SLOT],
+ vae: true,
+ }),
+ denoiseGrid: 8,
+ indexClippedShift: () => ANIMA_SCHEDULE_SHIFT,
+ label: 'Anima',
+ negativePrompt: 'cfg-gated',
+ takesModelGuidance: true,
+ tileControlNet: null,
},
} as const satisfies Record<string, UpscaleArchitecture>;
@@ -101,17 +238,31 @@ export const supportedUpscaleArchitectureLabels = (): string => {
return labels.length > 1 ? `${labels.slice(0, -1).join(', ')} or ${last}` : (last ?? '');
};
+/** The parts the selected main model must be given explicitly; none where it bundles them or is unsupported. */
+export const upscaleComponentsFor = (model: MainModelConfig | null): UpscaleComponents => {
+ const architecture = upscaleArchitectureFor(model);
+
+ return model && architecture ? architecture.components(model) : NO_COMPONENTS;
+};
+
/**
- * A self-contained SDNQ pipeline carries its own transformer, CLIP, T5 and VAE, so asking the user
- * to pick them would be busywork. Every other FLUX format must have them chosen explicitly.
- *
- * The backend is stricter still -- it also checks the pipeline actually contains those submodels
- * (`is_self_contained_sdnq_flux1_pipeline`), which the model list does not expose. An SDNQ install
- * missing a submodel therefore passes here and is refused by the loader with a precise message,
- * which is the right way round.
+ * Whether the graph has a negative branch. The CFG-gated architectures run an unconditional pass only
+ * above CFG 1, and need a negative conditioning to run it on. As in Generate, a switched-off negative
+ * prompt still gets its branch -- the queue fills it with an empty string -- so CFG runs at the value
+ * the slider and the image's metadata show.
*/
-export const needsExplicitComponents = (model: MainModelConfig | null): boolean =>
- (upscaleArchitectureFor(model)?.needsExplicitComponents ?? false) && model?.format !== 'sdnq_quantized';
+export const wiresUpscaleNegativePrompt = (model: MainModelConfig | null, cfgScale: number): boolean => {
+ const usage = upscaleArchitectureFor(model)?.negativePrompt;
+
+ return usage === 'always' || (usage === 'cfg-gated' && cfgScale > 1);
+};
+
+/**
+ * Index clipping keeps `int(start * steps)` of the schedule, so a single step leaves nothing between
+ * starting from pure noise and not denoising at all; the pass needs at least two.
+ */
+export const upscaleMinSteps = (model: MainModelConfig | null): number =>
+ upscaleArchitectureFor(model)?.indexClippedShift ? 2 : 1;
/** What Spandrel's autoscale produces: the scaled dimension floored to a multiple of 8. */
export const spandrelAutoscaleDimension = (dimension: number, scale: number): number =>
@@ -155,21 +306,49 @@ export const isSupportedUpscaleMainModel = (value: unknown): value is MainModelC
const isComponentModelOfType = (value: unknown, type: string): value is ComponentModelConfig =>
isRecord(value) && value.type === type && isModelIdentifierConfig(value);
-const pickComponent = (
- stored: unknown,
+type UpscaleComponentValues = Record<UpscaleComponentField, ComponentModelConfig | null>;
+
+/**
+ * For each slot the architecture has: the stored encoder if the slot still accepts it, otherwise the
+ * first installed one that fits. A field it has no slot for keeps its stored encoder while that is
+ * still installed, so switching to another architecture and back does not lose a hand-picked one;
+ * `activeUpscaleComponents` keeps it out of the graph and the metadata meanwhile.
+ */
+const pickComponents = (
+ stored: Partial<Record<UpscaleComponentField, unknown>>,
models: readonly ModelConfig[],
- type: string,
- required: boolean
-): ComponentModelConfig | null => {
- if (isComponentModelOfType(stored, type)) {
- return stored;
+ model: MainModelConfig | null
+): UpscaleComponentValues => {
+ const slots = upscaleComponentsFor(model).slots;
+ const picked = {} as UpscaleComponentValues;
+
+ for (const field of UPSCALE_COMPONENT_FIELDS) {
+ const current = stored[field];
+ const slot = slots.find((candidate) => candidate.field === field);
+ const fits = (candidate: unknown): candidate is ComponentModelConfig =>
+ isComponentModelOfType(candidate, UPSCALE_COMPONENT_TYPES[field]) &&
+ (!slot || slot.accepts(candidate as ModelConfig));
+
+ picked[field] = fits(current) ? current : slot ? (models.find(fits) ?? null) : null;
}
- // Only auto-pick where the architecture cannot run without one; elsewhere a stale selection is
- // simply dropped rather than replaced with an arbitrary encoder.
- return required
- ? ((models.find((model) => isComponentModelOfType(model, type)) as ComponentModelConfig) ?? null)
- : null;
+ return picked;
+};
+
+/** The encoders the selected main model reads; every other field reads as null. */
+export const activeUpscaleComponents = (values: Pick<UpscaleWidgetValues, 'model' | UpscaleComponentField>) => {
+ const active: UpscaleComponentValues = {
+ clipEmbedModel: null,
+ qwen35EncoderModel: null,
+ qwen3EncoderModel: null,
+ t5EncoderModel: null,
+ };
+
+ for (const slot of upscaleComponentsFor(values.model).slots) {
+ active[slot.field] = values[slot.field];
+ }
+
+ return active;
};
const pickCompatibleVae = (
@@ -198,13 +377,34 @@ export const isTileControlNetCandidate = (
value: unknown,
model: Pick<MainModelConfig, 'base'> | null
): value is TileControlNetModelConfig => {
- if (!model || !isTileControlNetModelConfig(value) || value.base !== model.base) {
- return false;
- }
+ const base = model?.base;
+ const tileControlNet = isUpscaleBase(base) ? UPSCALE_ARCHITECTURES[base].tileControlNet : null;
+
+ return (
+ tileControlNet !== null &&
+ isTileControlNetModelConfig(value) &&
+ value.base === base &&
+ tileControlNet.matchesName(value.name)
+ );
+};
- const name = value.name.toLowerCase();
+/**
+ * Keep a stored ControlNet that still fits. Only a required one is picked automatically: an optional
+ * one costs a second network's memory and time, and auto-picking it here would also re-add it every
+ * time the user cleared it.
+ */
+const pickTileControlNet = (
+ stored: unknown,
+ models: readonly ModelConfig[],
+ model: MainModelConfig | null
+): TileControlNetModelConfig | null => {
+ if (isTileControlNetCandidate(stored, model)) {
+ return stored;
+ }
- return name.includes('tile') || name.includes('union');
+ return upscaleArchitectureFor(model)?.tileControlNet?.required
+ ? (models.find((candidate) => isTileControlNetCandidate(candidate, model)) ?? null)
+ : null;
};
export const isUpscaleImage = (value: unknown): value is ImageWithDims =>
@@ -229,14 +429,39 @@ const normalizeLoras = (value: unknown): GenerateLora[] =>
)
: [];
+/** What SD and FLUX run at until the user changes it; SD's multi-diffusion pass is tuned to it. */
+const DEFAULT_UPSCALE_CFG_SCALE = 2;
+
+/**
+ * The CFG a change of main model leaves, see `takesModelGuidance`. Leaving a model that took its
+ * served guidance for one that keeps the user's restores the widget's default, so SD's tuned pass
+ * does not inherit Turbo's 1, nor FLUX Anima-3.8B's 6.
+ */
+const guidanceAfterModelChange = (
+ previous: MainModelConfig | null,
+ next: MainModelConfig | null,
+ current: number
+): number => {
+ // Without the served table the defaults fall back to a generic 7, which would burn a Turbo pass
+ // and then stick, since nothing re-applies a default to a model that is already selected.
+ if (!hasArchitectureCapabilities()) {
+ return current;
+ }
+ if (next && upscaleArchitectureFor(next)?.takesModelGuidance) {
+ return getDefaultGenerateSettings(next).cfgScale;
+ }
+
+ return upscaleArchitectureFor(previous)?.takesModelGuidance ? DEFAULT_UPSCALE_CFG_SCALE : current;
+};
+
export const createDefaultUpscaleWidgetValues = (models: readonly ModelConfig[] = []): UpscaleWidgetValues => {
const model = (models.find(isSupportedUpscaleMainModel) as MainModelConfig | undefined) ?? null;
- const needsComponents = needsExplicitComponents(model);
+ const components = upscaleComponentsFor(model);
return {
+ ...pickComponents({}, models, model),
batchCount: 1,
- cfgScale: 2,
- clipEmbedModel: pickComponent(null, models, 'clip_embed', needsComponents),
+ cfgScale: guidanceAfterModelChange(null, model, DEFAULT_UPSCALE_CFG_SCALE),
clipSkip: 0,
creativity: 0,
inputImage: null,
@@ -253,12 +478,11 @@ export const createDefaultUpscaleWidgetValues = (models: readonly ModelConfig[]
seedMode: 'random',
steps: 30,
structure: 0,
- t5EncoderModel: pickComponent(null, models, 't5_encoder', needsComponents),
- tileControlnetModel: models.find((candidate) => isTileControlNetCandidate(candidate, model)) ?? null,
+ tileControlnetModel: pickTileControlNet(null, models, model),
tileOverlap: 128,
tileSize: 1024,
upscaleModel: (models.find(isSpandrelModelConfig) as SpandrelModelConfig | undefined) ?? null,
- vae: needsComponents ? pickCompatibleVae(null, models, model) : null,
+ vae: components.vae ? pickCompatibleVae(null, models, model) : null,
vaePrecision: 'fp32',
};
};
@@ -278,6 +502,12 @@ export const normalizeUpscaleWidgetValues = (value: unknown): UpscaleWidgetValue
batchCount: sanitizeBatchCount(value.batchCount),
cfgScale: isFiniteNumber(value.cfgScale) ? value.cfgScale : defaults.cfgScale,
clipEmbedModel: isComponentModelOfType(value.clipEmbedModel, 'clip_embed') ? value.clipEmbedModel : null,
+ qwen35EncoderModel: isComponentModelOfType(value.qwen35EncoderModel, 'qwen3_5_encoder')
+ ? value.qwen35EncoderModel
+ : null,
+ qwen3EncoderModel: isComponentModelOfType(value.qwen3EncoderModel, 'qwen3_encoder')
+ ? value.qwen3EncoderModel
+ : null,
clipSkip: isFiniteNumber(value.clipSkip) ? value.clipSkip : defaults.clipSkip,
creativity: isFiniteNumber(value.creativity) ? value.creativity : defaults.creativity,
inputImage:
@@ -336,32 +566,31 @@ export const syncUpscaleWidgetValuesWithModels = (
const model: MainModelConfig | null = isSupportedUpscaleMainModel(storedMain)
? storedMain
: ((models.find(isSupportedUpscaleMainModel) as MainModelConfig | undefined) ?? null);
+ // A fresh widget, or one whose model was uninstalled, gets its model here rather than from a pick,
+ // and so the CFG a pick would have given it.
+ const cfgScale =
+ model?.key === values.model?.key ? values.cfgScale : guidanceAfterModelChange(values.model, model, values.cfgScale);
const storedSpandrel = values.upscaleModel ? modelsByKey.get(values.upscaleModel.key) : undefined;
const upscaleModel: SpandrelModelConfig | null = isSpandrelModelConfig(storedSpandrel)
? storedSpandrel
: ((models.find(isSpandrelModelConfig) as SpandrelModelConfig | undefined) ?? null);
- const storedControlNet = values.tileControlnetModel ? modelsByKey.get(values.tileControlnetModel.key) : undefined;
- const tileControlnetModel = isTileControlNetCandidate(storedControlNet, model)
- ? storedControlNet
- : (models.find((candidate) => isTileControlNetCandidate(candidate, model)) ?? null);
- const needsComponents = needsExplicitComponents(model);
- const t5EncoderModel = pickComponent(
- values.t5EncoderModel ? modelsByKey.get(values.t5EncoderModel.key) : undefined,
+ const tileControlnetModel = pickTileControlNet(
+ values.tileControlnetModel ? modelsByKey.get(values.tileControlnetModel.key) : undefined,
models,
- 't5_encoder',
- needsComponents
+ model
);
- const clipEmbedModel = pickComponent(
- values.clipEmbedModel ? modelsByKey.get(values.clipEmbedModel.key) : undefined,
+ const components = pickComponents(
+ Object.fromEntries(
+ UPSCALE_COMPONENT_FIELDS.map((field) => [field, values[field] ? modelsByKey.get(values[field].key) : undefined])
+ ),
models,
- 'clip_embed',
- needsComponents
+ model
);
const storedVae = values.vae ? modelsByKey.get(values.vae.key) : undefined;
const vae =
storedVae && isVaeModelConfig(storedVae) && model && isVaeCompatibleWithGenerateModel(model, storedVae)
? storedVae
- : needsComponents
+ : upscaleComponentsFor(model).vae
? pickCompatibleVae(null, models, model)
: null;
const loras = model
@@ -376,10 +605,10 @@ export const syncUpscaleWidgetValuesWithModels = (
if (
values.model === model &&
+ values.cfgScale === cfgScale &&
values.upscaleModel === upscaleModel &&
values.tileControlnetModel === tileControlnetModel &&
- values.t5EncoderModel === t5EncoderModel &&
- values.clipEmbedModel === clipEmbedModel &&
+ UPSCALE_COMPONENT_FIELDS.every((field) => values[field] === components[field]) &&
values.vae === vae &&
loras.length === values.loras.length &&
loras.every((lora, index) => lora.model === values.loras[index]?.model)
@@ -387,7 +616,20 @@ export const syncUpscaleWidgetValuesWithModels = (
return values;
}
- return { ...values, clipEmbedModel, loras, model, t5EncoderModel, tileControlnetModel, upscaleModel, vae };
+ return { ...values, ...components, cfgScale, loras, model, tileControlnetModel, upscaleModel, vae };
+};
+
+/** A main model the user picked: everything synced to it, and the CFG it should run at. */
+export const selectUpscaleMainModel = (
+ values: UpscaleWidgetValues,
+ model: MainModelConfig,
+ models: readonly ModelConfig[]
+): UpscaleWidgetValues => {
+ const synced = syncUpscaleWidgetValuesWithModels({ ...values, model }, models);
+
+ return synced.model?.key === values.model?.key
+ ? synced
+ : { ...synced, cfgScale: guidanceAfterModelChange(values.model, synced.model, values.cfgScale) };
};
const addRangeReason = (reasons: string[], label: string, value: number, min: number, max: number): void => {
@@ -418,34 +660,43 @@ export const getUpscaleValidationReasons = (values: UpscaleWidgetValues, models?
reasons.push('Upscale cannot use a FLUX Fill model.');
}
- // Only asked for where the architecture has a tile ControlNet to anchor the second pass with.
- if (architecture?.usesTileControlNet) {
- if (!values.tileControlnetModel) {
- reasons.push('Upscale needs a Tile or Union ControlNet compatible with the main model.');
- } else if (!isTileControlNetCandidate(values.tileControlnetModel, values.model)) {
- reasons.push('The Tile ControlNet must match the main model base and be a Tile or Union model.');
- }
+ const tileControlNet = architecture?.tileControlNet ?? null;
+
+ if (tileControlNet?.required && !values.tileControlnetModel) {
+ reasons.push('Upscale needs a Tile or Union ControlNet compatible with the main model.');
+ } else if (
+ tileControlNet &&
+ values.tileControlnetModel &&
+ !isTileControlNetCandidate(values.tileControlnetModel, values.model)
+ ) {
+ reasons.push(
+ tileControlNet.required
+ ? 'The Tile ControlNet must match the main model base and be a Tile or Union model.'
+ : 'The Tile ControlNet must match the main model base and be a Tile model.'
+ );
}
- // A bare FLUX transformer cannot supply these itself, and `flux_model_loader` refuses without them.
- if (needsExplicitComponents(values.model)) {
- if (!values.t5EncoderModel) {
- reasons.push('Upscale needs a T5 encoder for this main model.');
- }
- if (!values.clipEmbedModel) {
- reasons.push('Upscale needs a CLIP Embed model for this main model.');
- }
- if (!values.vae) {
- reasons.push('Upscale needs a VAE for this main model.');
+ // A bare transformer cannot supply these itself, and its loader refuses to run without them.
+ const components = upscaleComponentsFor(values.model);
+ const activeComponents = activeUpscaleComponents(values);
+
+ for (const slot of components.slots) {
+ if (!values[slot.field]) {
+ reasons.push(`Upscale needs a ${slot.label} for this main model.`);
+ } else if (!slot.accepts(values[slot.field] as ModelConfig)) {
+ reasons.push(`${values[slot.field]?.name} is not a ${slot.label} this main model can use.`);
}
}
+ if (components.vae && !values.vae) {
+ reasons.push('Upscale needs a VAE for this main model.');
+ }
addRangeReason(reasons, 'Scale', values.scale, UPSCALE_SCALE_MIN, UPSCALE_SCALE_MAX);
addRangeReason(reasons, 'Creativity', values.creativity, UPSCALE_CREATIVITY_MIN, UPSCALE_CREATIVITY_MAX);
addRangeReason(reasons, 'Structure', values.structure, UPSCALE_STRUCTURE_MIN, UPSCALE_STRUCTURE_MAX);
addRangeReason(reasons, 'Tile size', values.tileSize, UPSCALE_TILE_SIZE_MIN, UPSCALE_TILE_SIZE_MAX);
addRangeReason(reasons, 'Tile overlap', values.tileOverlap, UPSCALE_TILE_OVERLAP_MIN, UPSCALE_TILE_OVERLAP_MAX);
- addRangeReason(reasons, 'Steps', values.steps, 1, 1000);
+ addRangeReason(reasons, 'Steps', values.steps, upscaleMinSteps(values.model), 1000);
addRangeReason(reasons, 'CFG scale', values.cfgScale, 1, 100);
addRangeReason(reasons, 'Seed', values.seed, 0, SEED_MAX);
@@ -455,9 +706,8 @@ export const getUpscaleValidationReasons = (values: UpscaleWidgetValues, models?
...(values.model ? [values.model] : []),
...(values.upscaleModel ? [values.upscaleModel] : []),
...(values.tileControlnetModel ? [values.tileControlnetModel] : []),
- // Required for FLUX, so a deleted encoder must block the run rather than fail mid-graph.
- ...(values.t5EncoderModel ? [values.t5EncoderModel] : []),
- ...(values.clipEmbedModel ? [values.clipEmbedModel] : []),
+ // A deleted encoder must block the run rather than fail mid-graph.
+ ...UPSCALE_COMPONENT_FIELDS.flatMap((field) => (activeComponents[field] ? [activeComponents[field]] : [])),
...(values.vae ? [values.vae] : []),
];
@@ -476,7 +726,7 @@ export const getUpscaleValidationReasons = (values: UpscaleWidgetValues, models?
: undefined;
if (values.model && installedMain && !isSupportedUpscaleMainModel(installedMain)) {
- reasons.push(`${values.model.name} is not an installed SD1.5 or SDXL main model.`);
+ reasons.push(`${values.model.name} is not an installed ${supportedUpscaleArchitectureLabels()} main model.`);
}
if (values.upscaleModel && installedSpandrel && !isSpandrelModelConfig(installedSpandrel)) {
reasons.push(`${values.upscaleModel.name} is not an installed Spandrel model.`);
@@ -486,7 +736,7 @@ export const getUpscaleValidationReasons = (values: UpscaleWidgetValues, models?
installedControlNet &&
!isTileControlNetCandidate(installedControlNet, values.model)
) {
- reasons.push(`${values.tileControlnetModel.name} is not an installed compatible Tile or Union ControlNet.`);
+ reasons.push(`${values.tileControlnetModel.name} is not an installed compatible Tile ControlNet.`);
}
if (values.vae) {
const installedVae = installedByKey.get(values.vae.key);
diff --git a/invokeai/frontend/webv2/src/features/upscale/core/types.ts b/invokeai/frontend/webv2/src/features/upscale/core/types.ts
index 97610cbae9..924b5f2945 100644
--- a/invokeai/frontend/webv2/src/features/upscale/core/types.ts
+++ b/invokeai/frontend/webv2/src/features/upscale/core/types.ts
@@ -37,9 +37,11 @@ export interface UpscaleWidgetValues {
clipSkip: number;
vae: VaeModelConfig | null;
vaePrecision: VaePrecision;
- /** Only used by architectures whose `needsExplicitComponents` is set; null elsewhere. */
+ /** Set only where the main model's architecture asks for it (`upscaleComponentsFor`); null elsewhere. */
t5EncoderModel: ComponentModelConfig | null;
clipEmbedModel: ComponentModelConfig | null;
+ qwen3EncoderModel: ComponentModelConfig | null;
+ qwen35EncoderModel: ComponentModelConfig | null;
tileControlnetModel: TileControlNetModelConfig | null;
tileSize: number;
diff --git a/invokeai/frontend/webv2/src/features/upscale/core/upscaleGraphCoverage.test.ts b/invokeai/frontend/webv2/src/features/upscale/core/upscaleGraphCoverage.test.ts
new file mode 100644
index 0000000000..e6216c5b66
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/upscale/core/upscaleGraphCoverage.test.ts
@@ -0,0 +1,172 @@
+/** Cover every upscale builder against the backend-validated node/field/literal/connection fixture. */
+
+import type { BackendGraphContract } from '@features/generation/contracts';
+import type { ModelConfig } from '@features/models';
+
+import { seedArchitectureCapabilities } from '@features/generation/core/architectureCapabilities.testing';
+import { describe, expect, it } from 'vitest';
+
+import type { UpscaleWidgetValues } from './types';
+
+import { compileUpscaleGraph } from './graph';
+import { createDefaultUpscaleWidgetValues, getUpscaleValidationReasons, UPSCALE_ARCHITECTURES } from './settings';
+
+seedArchitectureCapabilities();
+
+const model = (key: string, type: string, base: string, extra: Record<string, unknown> = {}): ModelConfig =>
+ ({
+ base,
+ file_size: 1,
+ format: 'checkpoint',
+ hash: `${key}-hash`,
+ key,
+ name: key,
+ path: key,
+ source: key,
+ source_type: 'path',
+ type,
+ ...extra,
+ }) as ModelConfig;
+
+/** What the widget picks components from, the way it does for a user. */
+const INSTALLED = [
+ model('spandrel', 'spandrel_image_to_image', 'any'),
+ model('t5', 't5_encoder', 'any'),
+ model('clip', 'clip_embed', 'any'),
+ model('qwen3-4b', 'qwen3_encoder', 'any', { variant: 'qwen3_4b' }),
+ model('qwen3-06b', 'qwen3_encoder', 'any', { variant: 'qwen3_06b' }),
+ model('qwen35', 'qwen3_5_encoder', 'any', { variant: 'qwen3_5_4b' }),
+ model('flux-vae', 'vae', 'flux'),
+ model('qwen-vae', 'vae', 'qwen-image'),
+ model('sd1-tile', 'controlnet', 'sd-1', { name: 'sd1 tile' }),
+ model('sdxl-tile', 'controlnet', 'sdxl', { name: 'sdxl tile' }),
+ model('z-tile', 'controlnet', 'z-image', { name: 'Z-Image ControlNet Tile' }),
+];
+
+/**
+ * One case per path a builder can take: CFG above 1 where the negative branch is CFG-gated, the
+ * optional Z-Image ControlNet, a bundled Z-Image install, and Anima-3.8B's second encoder.
+ */
+const CASES: { label: string; main: ModelConfig; patch?: Partial<UpscaleWidgetValues> }[] = [
+ { label: 'sd-1', main: model('sd1', 'main', 'sd-1') },
+ { label: 'sdxl', main: model('sdxl', 'main', 'sdxl') },
+ { label: 'flux', main: model('flux', 'main', 'flux') },
+ {
+ label: 'z-image',
+ main: model('z', 'main', 'z-image'),
+ patch: { cfgScale: 4, tileControlnetModel: INSTALLED[10] as UpscaleWidgetValues['tileControlnetModel'] },
+ },
+ { label: 'z-image-diffusers', main: model('z-diffusers', 'main', 'z-image', { format: 'diffusers' }) },
+ { label: 'anima', main: model('anima', 'main', 'anima', { variant: 'anima_qwen3' }), patch: { cfgScale: 4.5 } },
+ {
+ label: 'anima-3.8b',
+ main: model('anima-38', 'main', 'anima', { variant: 'anima_qwen35' }),
+ patch: { cfgScale: 6 },
+ },
+];
+
+const compileCase = ({ main, patch }: (typeof CASES)[number]): BackendGraphContract => {
+ const installed = [main, ...INSTALLED, model(`${main.key}-lora`, 'lora', main.base)];
+ const defaults = createDefaultUpscaleWidgetValues(installed);
+ const values: UpscaleWidgetValues = {
+ ...defaults,
+ inputImage: { height: 101, image_name: 'input.png', width: 203 },
+ // Every builder's concept loader, so its node and edges reach the contract too.
+ loras: [{ isEnabled: true, model: installed.at(-1) as UpscaleWidgetValues['loras'][number]['model'], weight: 1 }],
+ ...patch,
+ };
+
+ expect(getUpscaleValidationReasons(values), `${main.key} is not satisfiable`).toEqual([]);
+
+ return compileUpscaleGraph(values, 'gallery', { useCpuNoise: true }).backendGraph;
+};
+
+describe('upscale graph coverage', () => {
+ it('covers every architecture the widget supports', () => {
+ expect([...new Set(CASES.map(({ main }) => main.base))].sort()).toEqual(Object.keys(UPSCALE_ARCHITECTURES).sort());
+ });
+
+ it('emits the node types, fields and connections the backend has to provide', async () => {
+ const byBase: Record<string, { nodeTypes: string[] }> = {};
+ const connections = new 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(), literals: new Map(), outputs: new Set() });
+
+ for (const testCase of CASES) {
+ const graph = compileCase(testCase);
+ const entry = (byBase[testCase.main.base] ??= { nodeTypes: [] });
+
+ entry.nodeTypes = [
+ ...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; an undefined value is not serialized at all.
+ if (field === 'id' || field === 'type' || value === undefined) {
+ continue;
+ }
+
+ const values = literals.get(field) ?? new Map<string, unknown>();
+ literals.set(field, values);
+
+ // Scalars only: object values are model identifiers and images from this file's fixtures.
+ if (value === null || typeof value !== 'object') {
+ values.set(JSON.stringify(value), value);
+ }
+ }
+ }
+
+ for (const edge of graph.edges) {
+ const source = graph.nodes[edge.source.node_id]!.type;
+ const destination = graph.nodes[edge.destination.node_id]!.type;
+
+ fieldsFor(source).outputs.add(edge.source.field);
+ fieldsFor(destination).inputs.add(edge.destination.field);
+ connections.add([source, edge.source.field, destination, edge.destination.field].join(' '));
+ }
+ }
+
+ const contract = {
+ connections: [...connections].sort(),
+ _comment:
+ 'Generated by src/features/upscale/core/upscaleGraphCoverage.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, and ' +
+ 'every connection for whether the backend considers the two field types compatible. 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, literals, outputs }]) => [
+ nodeType,
+ {
+ 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(),
+ },
+ ])
+ ),
+ };
+
+ await expect(`${JSON.stringify(contract, null, 2)}\n`).toMatchFileSnapshot(
+ './__snapshots__/upscaleGraphNodeTypes.json'
+ );
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleFormFields.tsx b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleFormFields.tsx
index 9c8588337c..9e605ba518 100644
--- a/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleFormFields.tsx
+++ b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleFormFields.tsx
@@ -68,6 +68,7 @@ export const UpscalePromptFields = memo(
(negativePromptHeight: number) => onPatchValues({ negativePromptHeightPx: negativePromptHeight }),
[onPatchValues]
);
+ const negativePromptUsage = upscaleArchitectureFor(model)?.negativePrompt ?? 'always';
return (
<Stack gap="2" p="2">
@@ -85,9 +86,10 @@ export const UpscalePromptFields = memo(
onResizeEnd={handlePositiveResizeEnd}
onUsePrompt={handleUsePrompt}
/>
- {(upscaleArchitectureFor(model)?.usesNegativePrompt ?? true) && (
+ {negativePromptUsage !== 'never' && (
<NegativePromptField
heightPx={negativePromptHeightPx}
+ helpText={negativePromptUsage === 'cfg-gated' ? t('widgets.upscale.negativePromptCfgGated') : undefined}
isEnabled={promptDraft.negativePromptEnabled}
loras={loras}
projectId={projectId}
diff --git a/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleWidgetView.tsx b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleWidgetView.tsx
index 824be0be23..9bf86c599f 100644
--- a/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleWidgetView.tsx
@@ -1,7 +1,9 @@
import type { GenerateLora, MainModelConfig } from '@features/generation/contracts';
import type { ProjectPromptDraftPatch } from '@features/generation/settings';
import type { ModelConfig, ModelTaxonomyType } from '@features/models';
+import type { UpscaleComponentField, UpscaleComponentSlot } from '@features/upscale/core/settings';
import type { UpscaleWidgetValues } from '@features/upscale/core/types';
+import type { FeatureHintId } from '@platform/ui/hints/hintRegistry';
import {
Badge,
@@ -21,14 +23,22 @@ import {
GenerationSettingsSection,
SeedField,
} from '@features/generation/components';
+import {
+ type ArchitectureCapabilitiesSnapshot,
+ ensureArchitectureCapabilitiesLoaded,
+ getArchitectureCapabilitiesSnapshot,
+ subscribeArchitectureCapabilities,
+} from '@features/generation/runtime';
import {
getDefaultLoraWeight,
isLoraCompatibleWithModel,
isLoraModelConfig,
isMainModelConfig,
+ coerceSchedulerForGraph,
+ getSchedulerOptions,
isModelIdentifierConfig,
+ isVaeCompatibleWithGenerateModel,
isVaeModelConfig,
- SCHEDULER_OPTIONS,
} from '@features/generation/settings';
import {
ensureModelsLoaded,
@@ -41,12 +51,12 @@ import {
import { ModelSelect } from '@features/models/react';
import {
createDefaultUpscaleWidgetValues,
- needsExplicitComponents,
getUpscaleOutputDimensions,
isSpandrelModelConfig,
isSupportedUpscaleMainModel,
isTileControlNetCandidate,
normalizeUpscaleWidgetValues,
+ selectUpscaleMainModel,
upscaleArchitectureFor,
syncUpscaleWidgetValuesWithModels,
UPSCALE_CREATIVITY_MAX,
@@ -60,9 +70,12 @@ import {
UPSCALE_TILE_OVERLAP_MIN,
UPSCALE_TILE_SIZE_MAX,
UPSCALE_TILE_SIZE_MIN,
+ upscaleComponentsFor,
+ upscaleMinSteps,
} from '@features/upscale/core/settings';
import { SEED_MAX } from '@platform/core/seed';
import { useMountEffect } from '@platform/react/useMountEffect';
+import { useExternalStoreSelector } from '@platform/state/selectors';
import { Combobox, Field, Select, Tooltip } from '@platform/ui';
import { ScrubberField } from '@platform/ui/ScrubberField';
import { toaster } from '@platform/ui/toaster';
@@ -91,9 +104,49 @@ const MAIN_MODEL_TYPES: readonly ModelTaxonomyType[] = ['main'];
const LORA_MODEL_TYPES: readonly ModelTaxonomyType[] = ['lora'];
const CONTROLNET_MODEL_TYPES: readonly ModelTaxonomyType[] = ['controlnet'];
const VAE_MODEL_TYPES: readonly ModelTaxonomyType[] = ['vae'];
-const T5_ENCODER_MODEL_TYPES: readonly ModelTaxonomyType[] = ['t5_encoder'];
-const CLIP_EMBED_MODEL_TYPES: readonly ModelTaxonomyType[] = ['clip_embed'];
+/** How each encoder slot reads in the form; which slots show, and what fits them, is the core's call. */
+const COMPONENT_FIELD_UI: Record<
+ UpscaleComponentField,
+ {
+ hint: FeatureHintId;
+ label: string;
+ modelTypes: readonly ModelTaxonomyType[];
+ placeholder: string;
+ required: string;
+ }
+> = {
+ clipEmbedModel: {
+ hint: 'clipEmbed',
+ label: 'widgets.upscale.clipEmbed',
+ modelTypes: ['clip_embed'],
+ placeholder: 'widgets.upscale.selectClipEmbed',
+ required: 'widgets.upscale.clipEmbedRequired',
+ },
+ qwen35EncoderModel: {
+ hint: 'qwen35Encoder',
+ label: 'widgets.upscale.qwen35Encoder',
+ modelTypes: ['qwen3_5_encoder'],
+ placeholder: 'widgets.upscale.selectQwen35Encoder',
+ required: 'widgets.upscale.qwen35EncoderRequired',
+ },
+ qwen3EncoderModel: {
+ hint: 'qwen3Encoder',
+ label: 'widgets.upscale.qwen3Encoder',
+ modelTypes: ['qwen3_encoder'],
+ placeholder: 'widgets.upscale.selectQwen3Encoder',
+ required: 'widgets.upscale.qwen3EncoderRequired',
+ },
+ t5EncoderModel: {
+ hint: 't5Encoder',
+ label: 'widgets.upscale.t5Encoder',
+ modelTypes: ['t5_encoder'],
+ placeholder: 'widgets.upscale.selectT5Encoder',
+ required: 'widgets.upscale.t5EncoderRequired',
+ },
+};
+
+const selectCapabilitiesStatus = (snapshot: ArchitectureCapabilitiesSnapshot) => snapshot.status;
const SCALE_MARKS = [1, 2, 4, 8, 16];
const CREATIVITY_MARKS = [UPSCALE_CREATIVITY_MIN, 0, UPSCALE_CREATIVITY_MAX];
const STRUCTURE_MARKS = [UPSCALE_STRUCTURE_MIN, 0, UPSCALE_STRUCTURE_MAX];
@@ -108,6 +161,37 @@ const PRESET_ENTRIES = Object.entries(UPSCALE_PRESETS);
const isSelectableMainModel = (model: ModelConfig): boolean => isSupportedUpscaleMainModel(model);
+const UpscaleComponentPicker = memo(function UpscaleComponentPicker({
+ onPatch,
+ slot,
+ value,
+}: {
+ onPatch: (patch: Partial<UpscaleWidgetValues>) => void;
+ slot: UpscaleComponentSlot;
+ value: UpscaleWidgetValues[UpscaleComponentField];
+}) {
+ const { t } = useTranslation();
+ const ui = COMPONENT_FIELD_UI[slot.field];
+ const select = useCallback(
+ (model: ModelConfig | null) =>
+ onPatch({ [slot.field]: isModelIdentifierConfig(model) && slot.accepts(model) ? model : null }),
+ [onPatch, slot]
+ );
+
+ return (
+ <Field error={value ? undefined : t(ui.required)} hint={ui.hint} label={t(ui.label)}>
+ <ModelSelect
+ filter={slot.accepts}
+ invalid={!value}
+ modelTypes={ui.modelTypes}
+ placeholder={t(ui.placeholder)}
+ value={value?.key ?? null}
+ onChange={select}
+ />
+ </Field>
+ );
+});
+
const formatScale = (scale: number): string => `${scale}×`;
const getRangeError = (label: string, value: number, min: number, max: number): string | undefined =>
@@ -250,13 +334,21 @@ export const UpscaleWidgetView = () => {
const selection = useUpscaleUi();
const models = useModelsSelector((snapshot) => snapshot.models);
const modelsStatus = useModelsSelector((snapshot) => snapshot.status);
+ const capabilitiesStatus = useExternalStoreSelector(
+ subscribeArchitectureCapabilities,
+ getArchitectureCapabilitiesSnapshot,
+ selectCapabilitiesStatus
+ );
+ // The sync picks VAEs and a new model's CFG from the served table, so like Generate's reconcile it
+ // waits for that table. A failed fetch still syncs; the CFG rule then leaves CFG alone.
+ const canSync = modelsStatus === 'loaded' && (capabilitiesStatus === 'loaded' || capabilitiesStatus === 'error');
const { patchPromptDraft: patchDraft, patchValues, projectId, promptDraft, rawValues } = selection;
// Reuse normalization/reconciliation results across unrelated renders to preserve section identities.
const values = useMemo(() => {
const normalized = normalizeUpscaleWidgetValues(rawValues) ?? createDefaultUpscaleWidgetValues();
- return modelsStatus === 'loaded' ? syncUpscaleWidgetValuesWithModels(normalized, models) : normalized;
- }, [models, modelsStatus, rawValues]);
+ return canSync ? syncUpscaleWidgetValuesWithModels(normalized, models) : normalized;
+ }, [canSync, models, rawValues]);
const modelsFingerprint = useMemo(
() =>
models
@@ -278,7 +370,7 @@ export const UpscaleWidgetView = () => {
),
scale: getRangeError(t('widgets.upscale.scale'), values.scale, UPSCALE_SCALE_MIN, UPSCALE_SCALE_MAX),
seed: getRangeError(t('widgets.upscale.seed'), values.seed, 0, SEED_MAX),
- steps: getRangeError(t('widgets.upscale.steps'), values.steps, 1, 1000),
+ steps: getRangeError(t('widgets.upscale.steps'), values.steps, upscaleMinSteps(values.model), 1000),
structure: getRangeError(
t('widgets.upscale.structure'),
values.structure,
@@ -305,6 +397,7 @@ export const UpscaleWidgetView = () => {
useMountEffect(() => {
void ensureModelsLoaded();
+ void ensureArchitectureCapabilitiesLoaded();
});
const selectMainModel = useCallback(
@@ -313,7 +406,7 @@ export const UpscaleWidgetView = () => {
return;
}
- const nextValues = syncUpscaleWidgetValuesWithModels({ ...values, model: model as MainModelConfig }, models);
+ const nextValues = selectUpscaleMainModel(values, model as MainModelConfig, models);
const notices: string[] = [];
if (values.tileControlnetModel?.key !== nextValues.tileControlnetModel?.key) {
@@ -379,8 +472,10 @@ export const UpscaleWidgetView = () => {
// A control with nothing to steer is worse than no control, so the widget follows the table
// rather than showing every field for every architecture.
const architecture = upscaleArchitectureFor(values.model);
- const showTileControlNet = architecture?.usesTileControlNet ?? false;
- const showComponentPickers = needsExplicitComponents(values.model);
+ const tileControlNet = architecture?.tileControlNet ?? null;
+ // Structure scales the ControlNet's weights, so with an optional one left out it steers nothing.
+ const showStructure = tileControlNet !== null && (tileControlNet.required || values.tileControlnetModel !== null);
+ const components = useMemo(() => upscaleComponentsFor(values.model), [values.model]);
const activePresetId = useMemo(
() =>
@@ -389,9 +484,9 @@ export const UpscaleWidgetView = () => {
values.creativity === preset.creativity &&
// Structure is hidden where nothing consumes it, so a stale value must not keep every
// preset unhighlighted with nothing on screen to explain why.
- (!showTileControlNet || values.structure === preset.structure)
+ (!showStructure || values.structure === preset.structure)
)?.[0] ?? null,
- [showTileControlNet, values.creativity, values.structure]
+ [showStructure, values.creativity, values.structure]
);
const applyPreset = useCallback(
({ value }: { value: string | null }) => {
@@ -444,28 +539,25 @@ export const UpscaleWidgetView = () => {
patch({ tileControlnetModel: isTileControlNetCandidate(model, values.model) ? model : null }),
[patch, values.model]
);
+ // The served rule, not a base match: Z-Image decodes with a FLUX VAE, Anima with a Qwen-Image one.
const vaeFilter = useCallback(
- (model: ModelConfig) => Boolean(values.model && model.base === values.model.base),
+ (model: ModelConfig) =>
+ Boolean(values.model && isVaeModelConfig(model) && isVaeCompatibleWithGenerateModel(values.model, model)),
[values.model]
);
const vaePrecisionValue = useMemo(() => [values.vaePrecision], [values.vaePrecision]);
-
- const setT5Encoder = useCallback(
- (model: ModelConfig | null) => patch({ t5EncoderModel: isModelIdentifierConfig(model) ? model : null }),
- [patch]
- );
- const setClipEmbed = useCallback(
- (model: ModelConfig | null) => patch({ clipEmbedModel: isModelIdentifierConfig(model) ? model : null }),
- [patch]
- );
+ // The architecture's own list, showing the scheduler the graph will really run. The stored value is
+ // left alone, so switching back to SD brings back an SD scheduler the flow models do not have.
+ const schedulerOptions = useMemo(() => getSchedulerOptions(values.model ?? undefined), [values.model]);
+ const scheduler = coerceSchedulerForGraph(values.model ?? undefined, values.scheduler);
const sharedBadge = useMemo(() => <Badge fontFamily="mono">{t('widgets.upscale.shared')}</Badge>, [t]);
return (
<Stack gap={1} minW={0} p="1">
<UpscaleModelReconciler
- key={`${projectId}:${modelsStatus}:${modelsFingerprint}`}
+ key={`${projectId}:${modelsStatus}:${capabilitiesStatus}:${modelsFingerprint}`}
rawValues={rawValues}
values={values}
/>
@@ -539,7 +631,7 @@ export const UpscaleWidgetView = () => {
value={values.creativity}
onChange={set.creativity}
/>
- {showTileControlNet && (
+ {showStructure && (
<ScrubberField
error={errors.structure}
helpText={t('widgets.upscale.structureHelp')}
@@ -594,7 +686,7 @@ export const UpscaleWidgetView = () => {
inputMax={1000}
label={t('widgets.upscale.steps')}
max={STEPS_SLIDER_MAX}
- min={1}
+ min={upscaleMinSteps(values.model)}
step={1}
value={values.steps}
onChange={set.steps}
@@ -613,8 +705,8 @@ export const UpscaleWidgetView = () => {
<Field hint="scheduler" label={t('widgets.upscale.scheduler')}>
<Combobox
aria-label={t('widgets.upscale.scheduler')}
- options={SCHEDULER_OPTIONS}
- value={values.scheduler}
+ options={schedulerOptions}
+ value={scheduler}
onValueChange={set.scheduler}
/>
</Field>
@@ -659,7 +751,7 @@ export const UpscaleWidgetView = () => {
<GenerationSettingsSection label={t('widgets.upscale.advanced')}>
<Stack gap="3" p="2">
- {showTileControlNet && (
+ {tileControlNet?.required && (
<Field
error={values.tileControlnetModel ? undefined : t('widgets.upscale.tileControlNetRequired')}
helpText={values.tileControlnetModel ? t('widgets.upscale.tileControlNetHelp') : undefined}
@@ -676,36 +768,25 @@ export const UpscaleWidgetView = () => {
/>
</Field>
)}
- {showComponentPickers && (
- <>
- <Field
- error={values.t5EncoderModel ? undefined : t('widgets.upscale.t5EncoderRequired')}
- hint="t5Encoder"
- label={t('widgets.upscale.t5Encoder')}
- >
- <ModelSelect
- invalid={!values.t5EncoderModel}
- modelTypes={T5_ENCODER_MODEL_TYPES}
- placeholder={t('widgets.upscale.selectT5Encoder')}
- value={values.t5EncoderModel?.key ?? null}
- onChange={setT5Encoder}
- />
- </Field>
- <Field
- error={values.clipEmbedModel ? undefined : t('widgets.upscale.clipEmbedRequired')}
- hint="clipEmbed"
- label={t('widgets.upscale.clipEmbed')}
- >
- <ModelSelect
- invalid={!values.clipEmbedModel}
- modelTypes={CLIP_EMBED_MODEL_TYPES}
- placeholder={t('widgets.upscale.selectClipEmbed')}
- value={values.clipEmbedModel?.key ?? null}
- onChange={setClipEmbed}
- />
- </Field>
- </>
+ {tileControlNet && !tileControlNet.required && (
+ <Field
+ helpText={t('widgets.upscale.tileControlNetOptionalHelp')}
+ hint="tileControlNet"
+ label={t('widgets.upscale.tileControlNet')}
+ >
+ <ModelSelect
+ filter={tileControlNetFilter}
+ isClearable
+ modelTypes={CONTROLNET_MODEL_TYPES}
+ placeholder={t('widgets.upscale.selectOptionalTileControlNet')}
+ value={values.tileControlnetModel?.key ?? null}
+ onChange={setTileControlNet}
+ />
+ </Field>
)}
+ {components.slots.map((slot) => (
+ <UpscaleComponentPicker key={slot.field} slot={slot} value={values[slot.field]} onPatch={patch} />
+ ))}
<ScrubberField
error={errors.tileSize}
helpText={t('widgets.upscale.tileSizeHelp')}
@@ -732,16 +813,16 @@ export const UpscaleWidgetView = () => {
/>
<SimpleGrid columns={ADVANCED_GRID_COLUMNS} gap="2">
<Field
- error={showComponentPickers && !values.vae ? t('widgets.upscale.vaeRequired') : undefined}
+ error={components.vae && !values.vae ? t('widgets.upscale.vaeRequired') : undefined}
hint="vae"
label={t('widgets.upscale.vae')}
>
<ModelSelect
filter={vaeFilter}
- invalid={showComponentPickers && !values.vae}
- isClearable={!showComponentPickers}
+ invalid={components.vae && !values.vae}
+ isClearable={!components.vae}
modelTypes={VAE_MODEL_TYPES}
- placeholder={showComponentPickers ? t('widgets.upscale.selectVae') : t('widgets.upscale.bundledVae')}
+ placeholder={components.vae ? t('widgets.upscale.selectVae') : t('widgets.upscale.bundledVae')}
value={values.vae?.key ?? null}
onChange={set.vae}
/>
diff --git a/invokeai/frontend/webv2/src/platform/ui/hints/hintRegistry.ts b/invokeai/frontend/webv2/src/platform/ui/hints/hintRegistry.ts
index 224b8f0cb1..77f751b0f1 100644
--- a/invokeai/frontend/webv2/src/platform/ui/hints/hintRegistry.ts
+++ b/invokeai/frontend/webv2/src/platform/ui/hints/hintRegistry.ts
@@ -48,6 +48,8 @@ export const FEATURE_HINTS = {
positivePrompt: {
href: 'https://support.invoke.ai/support/solutions/articles/151000096606-tips-on-crafting-prompts',
},
+ qwen35Encoder: {},
+ qwen3Encoder: {},
referenceImage: {
href: 'https://support.invoke.ai/support/solutions/articles/151000159340-global-and-regional-reference-images-ip-adapters-',
},
diff --git a/invokeai/frontend/webv2/src/workbench/invocation.test.ts b/invokeai/frontend/webv2/src/workbench/invocation.test.ts
index ae814701f3..94bf1d85d6 100644
--- a/invokeai/frontend/webv2/src/workbench/invocation.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/invocation.test.ts
@@ -232,7 +232,9 @@ describe('resolveInvocationRoute — upscale source', () => {
const result = resolveInvocationRouteInput({ ...input, upscaleValues: values }, 'global', route, models);
expect(result.sourceValid).toBe(false);
- expect(result.validationReasons).toContain('Upscale supports only SD1.5, SDXL or FLUX.1 main models.');
+ expect(result.validationReasons).toContain(
+ 'Upscale supports only SD1.5, SDXL, FLUX.1, Z-Image or Anima main models.'
+ );
});
it('rejects a ControlNet that is not a Tile model for its base', () => {
diff --git a/tests/app/invocations/test_frontend_graph_node_types.py b/tests/app/invocations/test_frontend_graph_node_types.py
index a7b3399804..0a6b3ea1bb 100644
--- a/tests/app/invocations/test_frontend_graph_node_types.py
+++ b/tests/app/invocations/test_frontend_graph_node_types.py
@@ -6,11 +6,12 @@ schema, so a node type or field that moves, is renamed, or loses its module impo
suite sees that on its own: the frontend only knows the strings it emits, and the backend only knows
the invocations it has.
-The contracts in between are `generateGraphNodeTypes.json` and `videoGraphNodeTypes.json`, written
-by `graphCoverage.test.ts` and `videoGraphCoverage.test.ts` (regenerate with `vitest -u`). Each
-records every 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 its compiler produces for every supported
-architecture. This module checks both against the real registry.
+The contracts in between are `generateGraphNodeTypes.json`, `videoGraphNodeTypes.json` and
+`upscaleGraphNodeTypes.json`, written by `graphCoverage.test.ts`, `videoGraphCoverage.test.ts` and
+`upscaleGraphCoverage.test.ts` (regenerate with `vitest -u`). Each records every 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 its compiler produces for every supported architecture. This module
+checks all of them 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
@@ -34,14 +35,15 @@ _WEBV2 = Path(__file__).parents[3] / "invokeai" / "frontend" / "webv2" / "src" /
CONTRACT_PATHS = {
"generate": _WEBV2 / "generation" / "core" / "__snapshots__" / "generateGraphNodeTypes.json",
"video": _WEBV2 / "video" / "core" / "__snapshots__" / "videoGraphNodeTypes.json",
+ "upscale": _WEBV2 / "upscale" / "core" / "__snapshots__" / "upscaleGraphNodeTypes.json",
}
CONTRACTS: dict[str, dict[str, Any]] = {
name: json.loads(path.read_text(encoding="utf-8")) for name, path in CONTRACT_PATHS.items()
}
-# The two panels compile different graphs from different tables, so each contract is checked on its
-# own; every assertion below is parameterized over both.
+# The panels compile different graphs from different tables, so each contract is checked on its
+# own; every assertion below is parameterized over all of them.
BASE_CASES = [(name, base) for name, contract in CONTRACTS.items() for base in sorted(contract["byBase"])]
NODE_CASES = [
(name, node_type) for name, contract in CONTRACTS.items() for node_type in sorted(contract["fieldsByNodeType"])
@@ -101,14 +103,15 @@ def test_every_connection_the_panel_compiles_is_one_the_queue_will_accept(contra
# The number of architectures each panel supports. A contract that silently stopped being
# regenerated would make every assertion below vacuous, so the count is pinned: a new architecture
# updates this number and the fixture in the same commit.
-SUPPORTED_BASE_COUNTS = {"generate": 14, "video": 3}
+SUPPORTED_BASE_COUNTS = {"generate": 14, "video": 3, "upscale": 5}
# Floors separating "the fixture records literals" from "it records a fraction of them". Set just
# under the current numbers (generate: 58 node types carrying 252 scalar values; video: 25 carrying
-# 142) rather than far below them: a recording bug that dropped most of the values while keeping the
-# names would otherwise leave every annotation check below passing over a short list. They are not
-# per-architecture expectations, so removing an architecture means lowering them deliberately.
-LITERAL_FLOORS = {"generate": (55, 240), "video": (23, 135)}
+# 142; upscale: 39 carrying 164) rather than far below them: a recording bug that dropped most of the
+# values while keeping the names would otherwise leave every annotation check below passing over a
+# short list. They are not per-architecture expectations, so removing an architecture means lowering
+# them deliberately.
+LITERAL_FLOORS = {"generate": (55, 240), "video": (23, 135), "upscale": (37, 155)}
@pytest.mark.parametrize("contract", sorted(CONTRACTS), ids=lambda contract: contract)
@@ -175,15 +178,18 @@ def _annotation(cls: type[BaseInvocation], field_name: str) -> Any:
return Annotated[(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"},
+SILENTLY_IGNORED: dict[str, dict[str, set[str]]] = {
+ "generate": {
+ # `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.
+"""Inputs webv2 writes that the invocation does not declare, per contract.
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,
@@ -201,7 +207,7 @@ def test_literal_inputs_are_real_invocation_fields(contract: str, node_type: str
pytest.skip(f"'{node_type}' accepts extra fields by design")
unknown = sorted(set(_fields(contract, node_type)["literalInputs"]) - set(cls.model_fields))
- assert unknown == sorted(SILENTLY_IGNORED.get(node_type, set())), (
+ assert unknown == sorted(SILENTLY_IGNORED.get(contract, {}).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."
)
diff --git a/tests/app/invocations/test_upscale_index_clipped_starts.py b/tests/app/invocations/test_upscale_index_clipped_starts.py
new file mode 100644
index 0000000000..a3fdd10eea
--- /dev/null
+++ b/tests/app/invocations/test_upscale_index_clipped_starts.py
@@ -0,0 +1,175 @@
+"""The Upscale widget's Creativity translation holds against the real Z-Image and Anima nodes.
+
+`flux_denoise` clips `denoising_start` by sigma value; `z_image_denoise` and `anima_denoise` clip it by
+step index on a shifted schedule, so the same number enters them far noisier. The widget therefore
+does not send them FLUX's start: `features/upscale/core/denoisingStart.ts` picks the step whose sigma
+is nearest the one FLUX would enter at, from its own copy of each node's shift and clipping rule.
+
+`upscaleIndexClippedStarts.json`, written by `denoisingStart.test.ts` (regenerate with `vitest -u`),
+records what the widget sends. Each case here drives the real `_run_diffusion` -- the real shift, the
+real `_get_sigmas`, the real clipping and the real img2img blend -- and reads the entry sigma back out
+of the blended tensor. It has to be the step nearest FLUX's entry. A change to either node's shift,
+schedule or clipping fails here instead of silently moving every Upscale preset; that includes a move
+to value clipping, which would leave the translation entering far too late.
+"""
+
+import json
+from contextlib import ExitStack
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import MagicMock, patch
+
+import pytest
+import torch
+
+from invokeai.app.invocations.anima.anima_denoise import AnimaDenoiseInvocation
+from invokeai.app.invocations.z_image.z_image_denoise import ZImageDenoiseInvocation
+
+FIXTURE = (
+ Path(__file__).parents[3]
+ / "invokeai"
+ / "frontend"
+ / "webv2"
+ / "src"
+ / "features"
+ / "upscale"
+ / "core"
+ / "__snapshots__"
+ / "upscaleIndexClippedStarts.json"
+)
+CASES = json.loads(FIXTURE.read_text(encoding="utf-8"))["cases"]
+
+
+class _StopAfterBlend(Exception):
+ """Ends the run at the first call after the img2img blend."""
+
+
+def _entry(node, module: str, dtype_attr: str, latents: torch.Tensor, noise: torch.Tensor, patches) -> tuple:
+ """Run `node._run_diffusion` to the blend; return the full schedule it built and the entry sigma.
+
+ The input latents are zeros and the noise is ones, so `s * noise + (1 - s) * init` is `s` in every
+ element: the entry sigma falls out of the tensor instead of being derived a second time.
+ """
+ schedule: dict[str, list[float]] = {}
+ real_get_sigmas = node._get_sigmas
+
+ def record(*args):
+ schedule["sigmas"] = real_get_sigmas(*args)
+ return schedule["sigmas"]
+
+ captured: dict[str, torch.Tensor] = {}
+
+ def capture(_context, blended):
+ captured["latents"] = blended
+ raise _StopAfterBlend
+
+ context = MagicMock()
+ context.tensors.load.return_value = latents
+ with ExitStack() as stack:
+ stack.enter_context(patch(f"{module}.TorchDevice.choose_torch_device", return_value=torch.device("cpu")))
+ # float32: the entry sigma is read back out of the tensor, and bfloat16 keeps three digits.
+ stack.enter_context(patch(f"{module}.TorchDevice.{dtype_attr}", return_value=torch.float32))
+ stack.enter_context(patch.object(node, "_prepare_noise_tensor", return_value=noise))
+ stack.enter_context(patch.object(node, "_get_sigmas", record))
+ stack.enter_context(patch.object(node, "_prep_inpaint_mask", capture))
+ for extra in patches:
+ stack.enter_context(extra)
+ with pytest.raises(_StopAfterBlend):
+ node._run_diffusion(context)
+
+ blended = captured["latents"]
+ assert torch.allclose(blended, blended.flatten()[:1].expand_as(blended)), "the blend should be uniform"
+ return schedule["sigmas"], float(blended.flatten()[0])
+
+
+def z_image_entry(side: int, steps: int, denoising_start: float) -> tuple[list[float], float]:
+ node = ZImageDenoiseInvocation.model_construct(
+ id="upscale",
+ latents=MagicMock(latents_name="latents"),
+ add_noise=True,
+ width=side,
+ height=side,
+ steps=steps,
+ denoising_start=denoising_start,
+ denoising_end=1.0,
+ shift=None,
+ positive_conditioning=SimpleNamespace(conditioning_name="positive", mask=None),
+ transformer=MagicMock(transformer="transformer"),
+ seed=0,
+ scheduler="euler",
+ )
+ regional = SimpleNamespace(regional_text_conditioning=SimpleNamespace(prompt_embeds=torch.zeros(1, 4, 16)))
+ return _entry(
+ node,
+ "invokeai.app.invocations.z_image.z_image_denoise",
+ "choose_bfloat16_safe_dtype",
+ torch.zeros(1, 16, 8, 8),
+ torch.ones(1, 16, 8, 8),
+ [
+ patch(
+ "invokeai.app.invocations.z_image.z_image_denoise.ZImageRegionalPromptingExtension.from_text_conditionings",
+ return_value=regional,
+ ),
+ patch.object(
+ node,
+ "_load_text_conditioning",
+ return_value=[SimpleNamespace(prompt_embeds=torch.zeros(1, 4, 16), mask=None)],
+ ),
+ ],
+ )
+
+
+def anima_entry(side: int, steps: int, denoising_start: float) -> tuple[list[float], float]:
+ node = AnimaDenoiseInvocation.model_construct(
+ id="upscale",
+ latents=MagicMock(latents_name="latents"),
+ noise=None,
+ denoise_mask=None,
+ add_noise=True,
+ width=side,
+ height=side,
+ steps=steps,
+ denoising_start=denoising_start,
+ denoising_end=1.0,
+ guidance_scale=1.0,
+ negative_conditioning=None,
+ positive_conditioning=SimpleNamespace(conditioning_name="positive", mask=None),
+ transformer=MagicMock(transformer="transformer"),
+ control_lllite=None,
+ seed=0,
+ scheduler="euler",
+ )
+ return _entry(
+ node,
+ "invokeai.app.invocations.anima.anima_denoise",
+ "choose_anima_inference_dtype",
+ torch.zeros(1, 16, 8, 8),
+ torch.ones(1, 16, 1, 8, 8),
+ [patch.object(node, "_load_text_conditionings", return_value=[SimpleNamespace(mask=None)])],
+ )
+
+
+ENTRY = {"z-image": z_image_entry, "anima": anima_entry}
+
+
+def test_the_fixture_covers_both_index_clipping_nodes():
+ """An empty or one-sided fixture would make every case below vacuous."""
+ assert {case["base"] for case in CASES} == set(ENTRY)
+ assert len(CASES) >= 60
+
+
+ "case",
+ CASES,
+ ids=lambda case: f"{case['base']}-{case['side']}px-{case['steps']}st-creativity{case['creativity']}",
+)
+def test_the_pass_enters_at_the_step_nearest_where_flux_enters(case: dict) -> None:
+ sigmas, entry = ENTRY[case["base"]](case["side"], case["steps"], case["denoisingStart"])
+ target = case["fluxEntrySigma"]
+ # The last sigma is 0, where nothing is left to denoise; ties go to the noisier step.
+ nearest = min(sigmas[:-1], key=lambda sigma: (abs(sigma - target), -sigma))
+
+ assert entry == pytest.approx(nearest, abs=1e-5), (
+ f"the widget sends denoising_start={case['denoisingStart']:.6f}, which enters at sigma {entry:.4f}; "
+ f"the step nearest FLUX's {target:.4f} is at {nearest:.4f}"
+ )
diff --git a/tests/app/invocations/test_z_image_denoise_working_memory.py b/tests/app/invocations/test_z_image_denoise_working_memory.py
index 3340bb38c9..0fe5698d0b 100644
--- a/tests/app/invocations/test_z_image_denoise_working_memory.py
+++ b/tests/app/invocations/test_z_image_denoise_working_memory.py
@@ -19,9 +19,12 @@ from unittest.mock import MagicMock, patch
import pytest
import torch
+from PIL import Image
-from invokeai.app.invocations.fields import ZImageConditioningField
-from invokeai.app.invocations.z_image.z_image_control import ZImageControlField
+from invokeai.app.invocations.fields import ImageField, ZImageConditioningField
+from invokeai.app.invocations.model import ModelIdentifierField
+from invokeai.app.invocations.vae.z_image_image_to_latents import ZImageImageToLatentsInvocation
+from invokeai.app.invocations.z_image.z_image_control import ZImageControlField, ZImageControlInvocation
from invokeai.app.invocations.z_image.z_image_denoise import ZImageDenoiseInvocation
from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, ModelType
from invokeai.backend.quantization.int8_convrot import CONVROT_GROUP_SIZE, Int8ConvrotLinear
@@ -144,7 +147,17 @@ class TestNodeReservation:
"""The wire from the node to `model_on_device()`: deleting any of these arguments leaves the estimate's own tests
green."""
- def _run(self, transformer=None, *, control_blocks=None, negative_tokens=None, loras=0, regional_mask=None):
+ def _run(
+ self,
+ transformer=None,
+ *,
+ control_blocks=None,
+ control_tiling=None,
+ force_tiled_decode=False,
+ negative_tokens=None,
+ loras=0,
+ regional_mask=None,
+ ):
from invokeai.backend.stable_diffusion.diffusion.conditioning_data import (
ConditioningFieldData,
ZImageConditioningInfo,
@@ -161,16 +174,25 @@ class TestNodeReservation:
else:
# Past the transformer's lock, up to the adapter's.
transformer_info.model_on_device = MagicMock(return_value=nullcontext((None, transformer)))
- control = ZImageControlField.model_construct(control_model=MagicMock(), image_name="control")
+ control = ZImageControlField.model_construct(
+ control_model=MagicMock(), image_name="control", **(control_tiling or {})
+ )
control_info.model = MagicMock(spec=ZImageControlAdapter)
control_info.model.control_layers = [torch.nn.Identity()] * control_blocks
- control_info.model_on_device = MagicMock(side_effect=_StopBeforeLoad)
+ if control_tiling is None:
+ control_info.model_on_device = MagicMock(side_effect=_StopBeforeLoad)
+ else:
+ # Past the adapter's lock too, up to the control image's encode.
+ control_info.model.config = {"control_in_dim": 33}
+ control_info.model_on_device = MagicMock(return_value=nullcontext((None, control_info.model)))
caption_tokens = {"pos": POSITIVE_TOKENS, "neg": negative_tokens}
context = MagicMock()
context.models.load.side_effect = lambda identifier: (
control_info if control is not None and identifier is control.control_model else transformer_info
)
+ context.images.get_pil.return_value = Image.new("RGB", (256, 256))
+ context.config.get.return_value.force_tiled_decode = force_tiled_decode
context.models.get_config.return_value = SimpleNamespace(
base=BaseModelType.ZImage, type=ModelType.Main, format=ModelFormat.Checkpoint
)
@@ -189,7 +211,7 @@ class TestNodeReservation:
positive_conditioning=ZImageConditioningField(conditioning_name="pos"),
negative_conditioning=ZImageConditioningField(conditioning_name="neg") if negative_tokens else None,
control=control,
- vae=None,
+ vae=MagicMock() if control is not None else None,
guidance_scale=2.0 if negative_tokens else 1.0,
width=256,
height=256,
@@ -217,6 +239,9 @@ class TestNodeReservation:
estimate = stack.enter_context(
patch.object(ZImageDenoiseInvocation, "_estimate_working_memory", return_value=ACTIVATION_ESTIMATE)
)
+ control_encode = stack.enter_context(
+ patch.object(ZImageImageToLatentsInvocation, "vae_encode", side_effect=_StopBeforeLoad)
+ )
if regional_mask is not None:
regional = ZImageRegionalPromptingExtension(
regional_text_conditioning=ZImageRegionalTextConditioning(
@@ -236,6 +261,7 @@ class TestNodeReservation:
adapter_reserved=(
control_info.model_on_device.call_args.kwargs.get("working_mem_bytes") if control is not None else None
),
+ control_encode=control_encode.call_args.kwargs if control_encode.called else None,
)
def test_an_unquantized_transformer_reserves_the_estimate_for_its_sequence(self):
@@ -284,3 +310,33 @@ class TestNodeReservation:
assert (run.estimate["num_control_blocks"], run.estimate["has_attention_mask"]) == (15, True)
assert run.adapter_reserved == run.reserved == ACTIVATION_ESTIMATE
+
+ def test_the_control_fields_tiling_reaches_the_control_encode(self):
+ """The control image is encoded at generation size. For an upscale that is the enlarged frame, whose untiled
+ encode does not fit on a consumer card, so the tiling the control field asks for has to reach the encode."""
+ run = self._run(control_blocks=15, control_tiling={"tiled": True, "tile_size": 768})
+
+ assert (run.control_encode["tiled"], run.control_encode["tile_size"]) == (True, 768)
+
+ def test_force_tiled_decode_tiles_a_control_encode_the_field_leaves_whole(self):
+ """Low-VRAM setups force every VAE pass to tile, and the control encode is one of them."""
+ run = self._run(control_blocks=15, control_tiling={"tiled": False, "tile_size": 0}, force_tiled_decode=True)
+
+ assert run.control_encode["tiled"] is True
+
+
+def test_the_control_node_hands_its_tiling_to_the_field():
+ """The denoise reads the tiling off the field, so a node that stopped copying it would encode whole."""
+ node = ZImageControlInvocation(
+ id="control",
+ image=ImageField(image_name="frame"),
+ control_model=ModelIdentifierField(
+ key="tile", hash="tile", name="tile", base=BaseModelType.ZImage, type=ModelType.ControlNet
+ ),
+ tiled=True,
+ tile_size=768,
+ )
+
+ control = node.invoke(MagicMock()).control
+
+ assert (control.tiled, control.tile_size) == (True, 768)