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(vae): tile large decodes up front, switchable with auto_tiled_decode

Alexander Eichhornfe707b55a834
diff --git a/docs/src/content/docs/configuration/low-vram-mode.mdx b/docs/src/content/docs/configuration/low-vram-mode.mdx
index 2d31c70e88..24e9d7e42c 100644
--- a/docs/src/content/docs/configuration/low-vram-mode.mdx
+++ b/docs/src/content/docs/configuration/low-vram-mode.mdx
@@ -38,6 +38,7 @@ Low-VRAM mode and related workload-specific optimizations include:
- PyTorch CUDA allocator config (`pytorch_cuda_alloc_conf`)
- Dynamic RAM and VRAM cache sizes (`max_cache_ram_gb`, `max_cache_vram_gb`)
- Working memory (`device_working_mem_gb`)
+- Tiled VAE decoding (`auto_tiled_decode`, `force_tiled_decode`)
- Keeping a RAM weight copy (`keep_ram_copy_of_weights`)
- Wan video memory optimization (`wan_memory_optimization`)
- PiD decode activation chunking (`pid_memory_optimization`)
@@ -158,6 +159,22 @@ device_working_mem_gb: 4
Once decoding completes, the model manager "reclaims" the extra VRAM allocated as working memory for future model loading operations.
:::
+### Tiled VAE decoding
+
+Turning latents into the final image (the VAE decode) needs working memory that grows with the image's pixel count. When an untiled decode would claim most of the GPU's memory, Invoke decodes in tiles instead, for the FLUX.1, Z-Image, Qwen-Image, Krea-2, Anima and Wan decodes. A tiled decode is not pixel-identical to an untiled one, so this only kicks in for images too large for the card: for Z-Image on a 16GB GPU, for example, from about 1850x1850 on Nvidia and from about 1500x1500 on AMD, whose convolution library needs more memory. Anima tiles a little earlier, because its untiled decode pushes the Anima model itself out of VRAM on 8GB cards.
+
+To always decode untiled unless you ask for tiling, turn it off:
+
+```yaml
+auto_tiled_decode: false
+```
+
+To tile every decode regardless of size:
+
+```yaml
+force_tiled_decode: true
+```
+
### Keeping a RAM weight copy
Invoke has the option of keeping a RAM copy of all model weights, even when they are loaded onto the GPU. This optimization is _on_ by default, and enables faster model switching and LoRA patching. Disabling this feature will reduce the average RAM load while running Invoke (peak RAM likely won't change), at the cost of slower model switching and LoRA patching. If you have limited RAM, you can disable this optimization:
@@ -210,6 +227,7 @@ Invoke does not officially support ROCm on Windows (see the [System Requirements
- The model cache plans against the video-memory budget Windows grants Invoke, not against the card's total VRAM.
- The PyTorch allocator defaults to `expandable_segments:True` (see [PyTorch CUDA allocator config](#pytorch-cuda-allocator-config)), so fragmented VRAM does not force allocations out.
+- Decodes too large for the card are tiled before they start (see [Tiled VAE decoding](#tiled-vae-decoding)); waiting for an out-of-memory error does not work there, because none comes.
- When a generation ends with part of Invoke's GPU memory in system memory, the log says so. Other programs using the same GPU, like games or browsers, can push Invoke's memory out as well. Close them, or restart Invoke to get the memory back into VRAM.
## Troubleshooting
diff --git a/docs/src/generated/settings.json b/docs/src/generated/settings.json
index cf71fadd7b..b20e4b4414 100644
--- a/docs/src/generated/settings.json
+++ b/docs/src/generated/settings.json
@@ -725,6 +725,17 @@
"type": "<class 'bool'>",
"validation": {}
},
+ {
+ "category": "GENERATION",
+ "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, Anima 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.",
+ "env_var": "INVOKEAI_AUTO_TILED_DECODE",
+ "literal_values": [],
+ "name": "auto_tiled_decode",
+ "required": false,
+ "type": "<class 'bool'>",
+ "validation": {}
+ },
{
"category": "GENERATION",
"default": 1,
diff --git a/invokeai/app/invocations/vae/anima_latents_to_image.py b/invokeai/app/invocations/vae/anima_latents_to_image.py
index 9cc3d4735e..10433e3883 100644
--- a/invokeai/app/invocations/vae/anima_latents_to_image.py
+++ b/invokeai/app/invocations/vae/anima_latents_to_image.py
@@ -44,6 +44,7 @@ from invokeai.backend.util.vae_decode_diagnostics import (
)
from invokeai.backend.util.vae_working_memory import (
estimate_vae_working_memory_anima,
+ should_pretile_vae_decode,
)
# Tile geometry for tiled Wan VAE decode. 512px tiles with a 384px stride (128px blended
@@ -54,6 +55,13 @@ from invokeai.backend.util.vae_working_memory import (
ANIMA_VAE_TILE_SIZE = 512
ANIMA_VAE_TILE_STRIDE = 384
+# Lower than the other decodes' `VAE_PRETILE_VRAM_FRACTION`, on purpose. A full 1024x1024 Wan VAE decode reserves ~6GB
+# of working memory; on small-VRAM GPUs that evicts the (~4GB) Anima transformer from the model cache and thrashes the
+# allocator near the VRAM ceiling (decode times of 7s+ observed on 8GB, vs ~1s tiled with the transformer left
+# resident). Above this share of the device a tiled decode wins; below it a single pass is faster (~0.65s vs ~1.05s at
+# 1024x1024) and exact.
+ANIMA_PRETILE_VRAM_FRACTION = 0.7
+
@invocation(
"anima_l2i",
@@ -69,25 +77,6 @@ class AnimaLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):
latents: LatentsField = InputField(description=FieldDescriptions.latents, input=Input.Connection)
vae: VAEField = InputField(description=FieldDescriptions.vae, input=Input.Connection)
- @staticmethod
- def _use_tiled_decode(device: torch.device, full_decode_working_memory: int) -> bool:
- """Decide whether to decode in tiles.
-
- A full 1024x1024 Wan VAE decode reserves ~6GB of working memory. On small-VRAM
- GPUs this evicts the (~4GB) Anima transformer from the model cache and thrashes
- the allocator near the VRAM ceiling (decode times of 7s+ observed on 8GB, vs
- ~1s tiled with the transformer left resident). Tile when the full-decode working
- memory would consume most of the device, otherwise a single-pass decode is
- faster (~0.65s vs ~1.05s at 1024x1024) and exact.
- """
- if device.type == "cuda":
- total_vram = torch.cuda.get_device_properties(device).total_memory
- elif device.type == "xpu":
- total_vram = torch.xpu.get_device_properties(device).total_memory
- else:
- return False
- return full_decode_working_memory > 0.7 * total_vram
-
@torch.no_grad()
def invoke(self, context: InvocationContext) -> ImageOutput:
latents = context.tensors.load(self.latents.latents_name)
@@ -117,7 +106,9 @@ class AnimaLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):
vae=vae_info.model,
tile_size=None,
)
- use_tiling = self._use_tiled_decode(TorchDevice.choose_torch_device(), full_decode_working_memory)
+ use_tiling = context.config.get().auto_tiled_decode and should_pretile_vae_decode(
+ vae_info.compute_device, full_decode_working_memory, ANIMA_PRETILE_VRAM_FRACTION
+ )
estimated_working_memory = estimate_vae_working_memory_anima(
operation="decode",
image_tensor=latents,
diff --git a/invokeai/app/invocations/vae/flux_vae_decode.py b/invokeai/app/invocations/vae/flux_vae_decode.py
index fdcb507c46..ad3d473861 100644
--- a/invokeai/app/invocations/vae/flux_vae_decode.py
+++ b/invokeai/app/invocations/vae/flux_vae_decode.py
@@ -20,7 +20,11 @@ from invokeai.backend.model_manager.load.load_base import LoadedModel
from invokeai.backend.util.devices import TorchDevice
from invokeai.backend.util.oom import is_oom_error
from invokeai.backend.util.vae_tiling_scope import scoped_vae_tiling
-from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_flux
+from invokeai.backend.util.vae_working_memory import (
+ VAE_PRETILE_VRAM_FRACTION,
+ estimate_vae_working_memory_flux,
+ should_pretile_vae_decode,
+)
@invocation(
@@ -48,7 +52,8 @@ class FluxVaeDecodeInvocation(BaseInvocation, WithMetadata, WithBoard):
# This node has no tiling fields, so the config switch is the only way a user can ask for a
# tiled decode here -- the same one the Z-Image, SD and Qwen-Image decode nodes honour. 0 is
# the "use the VAE's default tile" sentinel shared by the estimator and `scoped_vae_tiling`.
- use_tiling = context.config.get().force_tiled_decode
+ config = context.config.get()
+ use_tiling = config.force_tiled_decode
tile_size = 0 if use_tiling else None
# Only estimate working memory for BFL AutoEncoder (diffusers VAE handles this internally)
@@ -60,6 +65,22 @@ class FluxVaeDecodeInvocation(BaseInvocation, WithMetadata, WithBoard):
tile_size=tile_size,
device=vae_info.compute_device,
)
+ if (
+ not use_tiling
+ and config.auto_tiled_decode
+ and should_pretile_vae_decode(
+ vae_info.compute_device, estimated_working_memory, VAE_PRETILE_VRAM_FRACTION
+ )
+ ):
+ use_tiling = True
+ tile_size = 0
+ estimated_working_memory = estimate_vae_working_memory_flux(
+ operation="decode",
+ image_tensor=latents,
+ vae=vae_info.model,
+ tile_size=tile_size,
+ device=vae_info.compute_device,
+ )
else:
estimated_working_memory = 0
diff --git a/invokeai/app/invocations/vae/qwen_image_latents_to_image.py b/invokeai/app/invocations/vae/qwen_image_latents_to_image.py
index 8459c31e86..cb91594300 100644
--- a/invokeai/app/invocations/vae/qwen_image_latents_to_image.py
+++ b/invokeai/app/invocations/vae/qwen_image_latents_to_image.py
@@ -22,7 +22,11 @@ from invokeai.backend.util.qwen_image_vae import (
patch_qwen_image_vae_tiling,
resolve_qwen_image_vae_tile_size,
)
-from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_qwen_image
+from invokeai.backend.util.vae_working_memory import (
+ VAE_PRETILE_VRAM_FRACTION,
+ estimate_vae_working_memory_qwen_image,
+ should_pretile_vae_decode,
+)
@invocation(
@@ -53,7 +57,8 @@ class QwenImageLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard)
latents = context.tensors.load(self.latents.latents_name)
vae_info = context.models.load(self.vae.vae)
- tiled = self.tiled or context.config.get().force_tiled_decode
+ config = context.config.get()
+ tiled = self.tiled or config.force_tiled_decode
# Resolve tile_size=0 ("model default") before estimating, so the memory the cache reserves
# matches the tiles the VAE will actually use. Without this the estimate stays at the
# full-frame figure (~21 GB at 2560x1440 on CUDA) and tiling frees nothing: the VAE is
@@ -72,6 +77,18 @@ class QwenImageLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard)
vae=vae_info.model,
tile_size=effective_tile_size,
)
+ if (
+ not tiled
+ and config.auto_tiled_decode
+ and should_pretile_vae_decode(vae_info.compute_device, estimated_working_memory, VAE_PRETILE_VRAM_FRACTION)
+ ):
+ effective_tile_size = resolve_qwen_image_vae_tile_size(self.tile_size)
+ estimated_working_memory = estimate_vae_working_memory_qwen_image(
+ operation="decode",
+ image_tensor=latents,
+ vae=vae_info.model,
+ tile_size=effective_tile_size,
+ )
with vae_info.model_on_device(working_mem_bytes=estimated_working_memory) as (_, vae):
context.util.signal_progress("Running VAE")
# A native-layout qwen_image_vae single file is classified with the Anima base and loaded
diff --git a/invokeai/app/invocations/vae/wan_latents_to_video.py b/invokeai/app/invocations/vae/wan_latents_to_video.py
index 25d2e63e92..07289a95e2 100644
--- a/invokeai/app/invocations/vae/wan_latents_to_video.py
+++ b/invokeai/app/invocations/vae/wan_latents_to_video.py
@@ -35,7 +35,11 @@ from invokeai.app.services.shared.invocation_context import InvocationContext
from invokeai.app.util.video_encoding import make_mp4_writer
from invokeai.backend.model_manager.load.model_cache.utils import get_effective_device
from invokeai.backend.util.devices import TorchDevice
-from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_wan
+from invokeai.backend.util.vae_working_memory import (
+ VAE_PRETILE_VRAM_FRACTION,
+ estimate_vae_working_memory_wan,
+ should_pretile_vae_decode,
+)
from invokeai.backend.wan.vae_decode import iter_wan_vae_decode_chunks
@@ -129,29 +133,23 @@ class WanLatentsToVideoInvocation(BaseInvocation, WithMetadata, WithBoard):
streaming=optimize_memory,
)
# Long/high-res clips can need a working set no card fits. When the full-frame
- # estimate exceeds the execution device's total VRAM, fall back to spatial tiling
- # and budget for the tiled working set instead. (A cpu_only VAE runs in system
- # RAM, where the working set is not the constraint.)
- use_tiling = False
- if not getattr(vae_info.config, "cpu_only", None):
- exec_device = TorchDevice.choose_torch_device()
- total_vram: int | None = None
- if exec_device.type == "cuda":
- total_vram = torch.cuda.get_device_properties(exec_device).total_memory
- elif exec_device.type == "xpu":
- total_vram = torch.xpu.get_device_properties(exec_device).total_memory
- if total_vram is not None and estimated_working_memory > 0.9 * total_vram:
- use_tiling = True
- tile_size = int(getattr(vae_info.model, "tile_sample_min_height", 256))
- estimated_working_memory = estimate_vae_working_memory_wan(
- operation="decode",
- vae=vae_info.model,
- pixel_height=h_pixel,
- pixel_width=w_pixel,
- pixel_frames=t_pixel,
- tile_size=tile_size,
- streaming=False,
- )
+ # estimate would claim most of the VAE's device, fall back to spatial tiling and
+ # budget for the tiled working set instead. (A cpu_only VAE runs in system RAM,
+ # where the working set is not the constraint; the helper never tiles off-GPU.)
+ use_tiling = context.config.get().auto_tiled_decode and should_pretile_vae_decode(
+ vae_info.compute_device, estimated_working_memory, VAE_PRETILE_VRAM_FRACTION
+ )
+ if use_tiling:
+ tile_size = int(getattr(vae_info.model, "tile_sample_min_height", 256))
+ estimated_working_memory = estimate_vae_working_memory_wan(
+ operation="decode",
+ vae=vae_info.model,
+ pixel_height=h_pixel,
+ pixel_width=w_pixel,
+ pixel_frames=t_pixel,
+ tile_size=tile_size,
+ streaming=False,
+ )
tmp = tempfile.NamedTemporaryFile(prefix="invokeai_wan_video_", suffix=".mp4", delete=False)
tmp.close()
diff --git a/invokeai/app/invocations/vae/z_image_latents_to_image.py b/invokeai/app/invocations/vae/z_image_latents_to_image.py
index 74213f2233..ff609ea343 100644
--- a/invokeai/app/invocations/vae/z_image_latents_to_image.py
+++ b/invokeai/app/invocations/vae/z_image_latents_to_image.py
@@ -23,7 +23,11 @@ from invokeai.backend.stable_diffusion.extensions.seamless import SeamlessExt
from invokeai.backend.util.devices import TorchDevice
from invokeai.backend.util.oom import is_oom_error
from invokeai.backend.util.vae_tiling_scope import scoped_vae_tiling
-from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_flux
+from invokeai.backend.util.vae_working_memory import (
+ VAE_PRETILE_VRAM_FRACTION,
+ estimate_vae_working_memory_flux,
+ should_pretile_vae_decode,
+)
# Z-Image can use either the Diffusers AutoencoderKL or the FLUX AutoEncoder
ZImageVAE = Union[AutoencoderKL, FluxAutoEncoder]
@@ -60,7 +64,8 @@ class ZImageLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):
)
is_flux_vae = isinstance(vae_info.model, FluxAutoEncoder)
- use_tiling = self.tiled or context.config.get().force_tiled_decode
+ config = context.config.get()
+ use_tiling = self.tiled or config.force_tiled_decode
# Estimate working memory needed for VAE decode
estimated_working_memory = estimate_vae_working_memory_flux(
@@ -70,6 +75,19 @@ class ZImageLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):
tile_size=self.tile_size if use_tiling else None,
device=vae_info.compute_device,
)
+ if (
+ not use_tiling
+ and config.auto_tiled_decode
+ and should_pretile_vae_decode(vae_info.compute_device, estimated_working_memory, VAE_PRETILE_VRAM_FRACTION)
+ ):
+ use_tiling = True
+ estimated_working_memory = estimate_vae_working_memory_flux(
+ operation="decode",
+ image_tensor=latents,
+ vae=vae_info.model,
+ tile_size=self.tile_size,
+ device=vae_info.compute_device,
+ )
# FLUX VAE doesn't support seamless, so only apply for AutoencoderKL
seamless_context = (
diff --git a/invokeai/app/services/config/config_default.py b/invokeai/app/services/config/config_default.py
index 6cdd2ffff1..321b12e9f7 100644
--- a/invokeai/app/services/config/config_default.py
+++ b/invokeai/app/services/config/config_default.py
@@ -125,6 +125,7 @@ class InvokeAIAppConfig(BaseSettings):
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. As of this release the setting also applies to FLUX.1, which previously ignored 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, Anima 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.
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.
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`
@@ -249,6 +250,7 @@ class InvokeAIAppConfig(BaseSettings):
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. As of this release the setting also applies to FLUX.1, which previously ignored 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, Anima 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.")
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.")
session_queue_mode: SESSION_QUEUE_MODE = Field(default="round_robin", description="Session queue mode. Use 'FIFO' for strict first-in-first-out, or 'round_robin' to serve each user's jobs in turn. In round-robin mode, priority orders each user's own jobs, but the user rotation takes precedence: one user's high-priority job does not preempt another user's turn. In single-user mode, jobs are served in submission order either way — except that on multi-GPU systems the default 'round_robin' allows same-priority jobs to be reordered slightly so a freed GPU prefers jobs whose models it already has loaded. Set 'FIFO' to disable that reordering and enforce strict submission order.")
diff --git a/invokeai/backend/util/vae_working_memory.py b/invokeai/backend/util/vae_working_memory.py
index 715799fa11..e9800a276c 100644
--- a/invokeai/backend/util/vae_working_memory.py
+++ b/invokeai/backend/util/vae_working_memory.py
@@ -11,6 +11,38 @@ from invokeai.app.invocations.constants import LATENT_SCALE_FACTOR
from invokeai.backend.flux.modules.autoencoder import AutoEncoder, resolve_tile_size
from invokeai.backend.util.attention import sdpa_score_matrix_bytes
from invokeai.backend.util.devices import TorchDevice
+from invokeai.backend.util.logging import InvokeAILogger
+
+# Share of the device's memory an untiled decode may claim before the decode nodes tile it up front (see
+# `should_pretile_vae_decode`). High enough that common resolutions on common cards stay untiled -- tiled output is
+# not pixel-identical -- and low enough that a decode no card of that size can hold is tiled before it starts.
+VAE_PRETILE_VRAM_FRACTION = 0.9
+
+
+def should_pretile_vae_decode(device: torch.device, full_decode_bytes: int, vram_fraction: float) -> bool:
+ """Whether a decode should be tiled up front because its untiled working memory would claim more than
+ ``vram_fraction`` of ``device``'s memory.
+
+ Waiting for an out-of-memory error does not work everywhere: on Windows, drivers page an allocation that does not
+ fit into system memory instead of failing it (always for ROCm, by default for NVIDIA's sysmem fallback), and the
+ decode just runs very slowly. ``device`` is where the VAE runs: a ``cpu_only`` VAE (and MPS, sharing system
+ memory) is never tiled on these grounds.
+ """
+ if device.type == "cuda":
+ total_bytes = torch.cuda.get_device_properties(device).total_memory
+ elif device.type == "xpu":
+ total_bytes = torch.xpu.get_device_properties(device).total_memory
+ else:
+ return False
+ if full_decode_bytes <= vram_fraction * total_bytes:
+ return False
+ InvokeAILogger.get_logger(__name__).info(
+ f"Decoding in tiles: an untiled decode would need ~{full_decode_bytes / 2**30:.1f} GiB of working memory, more "
+ f"than {vram_fraction:.0%} of the GPU's {total_bytes / 2**30:.1f} GiB. Set auto_tiled_decode to false to "
+ "decode untiled."
+ )
+ return True
+
# The diffusers AutoencoderKL (SD1/SDXL, SD3, CogView4) and the FLUX.1 AutoEncoder run the same
# mid-block self-attention as the FLUX.2 VAE: one head over the 512-channel width, on the
diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.json
index 3a919fe197..0dd671f955 100644
--- a/invokeai/frontend/web/openapi.json
+++ b/invokeai/frontend/web/openapi.json
@@ -55090,6 +55090,12 @@
"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. As of this release the setting also applies to FLUX.1, which previously ignored it.",
"default": false
},
+ "auto_tiled_decode": {
+ "type": "boolean",
+ "title": "Auto Tiled Decode",
+ "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, Anima 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.",
+ "default": true
+ },
"pil_compress_level": {
"type": "integer",
"title": "Pil Compress Level",
@@ -55384,7 +55390,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 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_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 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 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; falls back automatically otherwise). Roughly halves the transformer's VRAM and speeds up denoising, 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 sequential_guidance: Whether to calculate guidance in serial instead of in parallel, lowering memory requirements.\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. As of this release the setting also applies to FLUX.1, which previously ignored it.\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_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 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_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 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 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; falls back automatically otherwise). Roughly halves the transformer's VRAM and speeds up denoising, 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 sequential_guidance: Whether to calculate guidance in serial instead of in parallel, lowering memory requirements.\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. As of this release the setting also applies to FLUX.1, which previously ignored 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, Anima 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.\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_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": {
diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.ts
index a6721ac594..a38c2d0f54 100644
--- a/invokeai/frontend/web/src/services/api/schema.ts
+++ b/invokeai/frontend/web/src/services/api/schema.ts
@@ -21129,6 +21129,7 @@ export type components = {
* 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. As of this release the setting also applies to FLUX.1, which previously ignored 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, Anima 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.
* 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.
* 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`
@@ -21557,6 +21558,12 @@ export type components = {
* @default false
*/
force_tiled_decode?: boolean;
+ /**
+ * Auto Tiled Decode
+ * @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, Anima 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.
+ * @default true
+ */
+ auto_tiled_decode?: boolean;
/**
* Pil Compress Level
* @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.
diff --git a/tests/app/invocations/test_anima_vae.py b/tests/app/invocations/test_anima_vae.py
index 855f0638ba..17d79a8952 100644
--- a/tests/app/invocations/test_anima_vae.py
+++ b/tests/app/invocations/test_anima_vae.py
@@ -1,7 +1,6 @@
"""Tests for the Anima VAE invocations: which VAEs they accept, working-memory estimation, the
tiled-decode decision, and the tiled retry on out-of-memory."""
-import math
from unittest.mock import MagicMock, patch
import accelerate
@@ -97,21 +96,6 @@ class TestEstimateVaeWorkingMemoryAnima:
assert fp32 == 2 * fp16
-class TestUseTiledDecode:
- @pytest.mark.parametrize("device_type", ["cpu", "mps"])
- def test_non_cuda_never_tiles(self, device_type):
- assert AnimaLatentsToImageInvocation._use_tiled_decode(torch.device(device_type), 10**12) is False
-
- def test_cuda_flips_at_70_percent_of_total_vram(self):
- total_vram = 8 * 2**30
- boundary = 0.7 * total_vram
- device = torch.device("cuda")
- with patch("torch.cuda.get_device_properties", return_value=MagicMock(total_memory=total_vram)) as mock_props:
- assert AnimaLatentsToImageInvocation._use_tiled_decode(device, math.floor(boundary)) is False
- assert AnimaLatentsToImageInvocation._use_tiled_decode(device, math.ceil(boundary) + 1) is True
- mock_props.assert_called_with(device)
-
-
def _build_decode_mocks(latents: torch.Tensor, decoded: torch.Tensor, vae_class: type = AutoencoderKLWan):
"""Mock the Anima VAE decode path: a spec'd VAE, its LoadedModel wrapper, and the invocation
context, wired so `AnimaLatentsToImageInvocation.invoke` runs end-to-end on CPU."""
@@ -316,7 +300,7 @@ class TestAnimaLatentsToImageOomFallback:
with (
patch.object(TorchDevice, "choose_torch_device", return_value=torch.device("cpu")),
- patch.object(AnimaLatentsToImageInvocation, "_use_tiled_decode", return_value=True),
+ patch("invokeai.app.invocations.vae.anima_latents_to_image.should_pretile_vae_decode", return_value=True),
):
with pytest.raises(torch.cuda.OutOfMemoryError):
_build_l2i_invocation().invoke(context)
diff --git a/tests/app/invocations/test_anima_vae_tiling.py b/tests/app/invocations/test_anima_vae_tiling.py
index 5ff52f3088..3052f08a51 100644
--- a/tests/app/invocations/test_anima_vae_tiling.py
+++ b/tests/app/invocations/test_anima_vae_tiling.py
@@ -121,7 +121,7 @@ def test_a_tiled_decode_applies_the_calibrated_geometry_and_restores_it():
vae.decode = spy_decode
with (
patch.object(TorchDevice, "choose_torch_device", return_value=torch.device("cpu")),
- patch.object(AnimaLatentsToImageInvocation, "_use_tiled_decode", return_value=True),
+ patch("invokeai.app.invocations.vae.anima_latents_to_image.should_pretile_vae_decode", return_value=True),
):
_build_invocation().invoke(context)
diff --git a/tests/app/invocations/test_flux_vae_decode_tiling.py b/tests/app/invocations/test_flux_vae_decode_tiling.py
index 9dadc9682d..c87f6fd492 100644
--- a/tests/app/invocations/test_flux_vae_decode_tiling.py
+++ b/tests/app/invocations/test_flux_vae_decode_tiling.py
@@ -13,6 +13,7 @@ import torch
from invokeai.app.invocations.vae.flux_vae_decode import FluxVaeDecodeInvocation
from invokeai.backend.flux.modules.autoencoder import DEFAULT_TILE_SAMPLE_MIN_SIZE
from invokeai.backend.flux.modules.autoencoder import AutoEncoder as FluxAutoEncoder
+from invokeai.backend.util.vae_working_memory import VAE_PRETILE_VRAM_FRACTION
def _build_decode_mocks(latents: torch.Tensor, decoded: torch.Tensor, force_tiled_decode: bool = False):
@@ -78,6 +79,26 @@ class TestForceTiledDecode:
_build_invocation().invoke(context)
assert estimate.call_args.kwargs["tile_size"] == expected_tile_size
+ @pytest.mark.parametrize("auto", [True, False], ids=["auto-tiled-decode-on", "auto-tiled-decode-off"])
+ def test_a_decode_too_large_for_its_gpu_is_tiled_up_front_unless_switched_off(self, auto):
+ module = "invokeai.app.invocations.vae.flux_vae_decode"
+ vae, vae_info, context = _build_decode_mocks(torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512))
+ context.config.get.return_value.auto_tiled_decode = auto
+ with (
+ patch(f"{module}.estimate_vae_working_memory_flux", side_effect=[20 * 2**30, 2 * 2**30]) as estimate,
+ patch(f"{module}.should_pretile_vae_decode", return_value=True) as pretile,
+ ):
+ _build_invocation().invoke(context)
+
+ if auto:
+ pretile.assert_called_once_with(vae_info.compute_device, 20 * 2**30, VAE_PRETILE_VRAM_FRACTION)
+ assert estimate.call_args.kwargs["tile_size"] == 0
+ vae_info.model_on_device.assert_called_once_with(working_mem_bytes=2 * 2**30)
+ vae.enable_tiling.assert_called_once_with(tile_sample_min_size=DEFAULT_TILE_SAMPLE_MIN_SIZE)
+ else:
+ pretile.assert_not_called()
+ vae.disable_tiling.assert_called_once()
+
class TestOomFallback:
def test_an_untiled_oom_retries_once_tiled_and_says_so(self):
diff --git a/tests/app/invocations/test_qwen_image_working_memory.py b/tests/app/invocations/test_qwen_image_working_memory.py
index a9267641d0..1aaa3c81f3 100644
--- a/tests/app/invocations/test_qwen_image_working_memory.py
+++ b/tests/app/invocations/test_qwen_image_working_memory.py
@@ -14,7 +14,7 @@ from invokeai.backend.util.qwen_image_vae import (
QWEN_IMAGE_VAE_DEFAULT_TILE_SIZE,
patch_qwen_image_vae_tiling,
)
-from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_qwen_image
+from invokeai.backend.util.vae_working_memory import VAE_PRETILE_VRAM_FRACTION, estimate_vae_working_memory_qwen_image
class TestQwenImageWorkingMemoryEstimate:
@@ -416,6 +416,46 @@ class TestQwenImageWorkingMemory:
assert mock_estimate.call_args.kwargs["tile_size"] == QWEN_IMAGE_VAE_DEFAULT_TILE_SIZE
mock_vae.enable_tiling.assert_called_once()
+ @pytest.mark.parametrize("auto", [True, False], ids=["auto-tiled-decode-on", "auto-tiled-decode-off"])
+ def test_a_decode_too_large_for_its_gpu_is_tiled_up_front_unless_switched_off(self, auto):
+ """Krea-2 decodes through this node, and it has no OOM retry at all: the estimate is the only trigger."""
+ module = "invokeai.app.invocations.vae.qwen_image_latents_to_image"
+ mock_vae, mock_vae_info = self._mock_vae_info()
+ mock_vae.decode.side_effect = RuntimeError("stop at decode")
+ mock_vae.config.z_dim = 16
+ mock_vae.config.latents_mean = [0.0] * 16
+ mock_vae.config.latents_std = [1.0] * 16
+
+ mock_context = MagicMock()
+ mock_context.models.load.return_value = mock_vae_info
+ mock_context.tensors.load.return_value = torch.zeros(1, 16, 1, 64, 64)
+ mock_context.config.get.return_value.force_tiled_decode = False
+ mock_context.config.get.return_value.auto_tiled_decode = auto
+
+ with (
+ patch(f"{module}.estimate_vae_working_memory_qwen_image", side_effect=[20 * 2**30, 2 * 2**30]) as estimate,
+ patch(f"{module}.should_pretile_vae_decode", return_value=True) as pretile,
+ patch(f"{module}.SeamlessExt.static_patch_model", return_value=nullcontext()),
+ ):
+ invocation = QwenImageLatentsToImageInvocation.model_construct(
+ latents=MagicMock(latents_name="test_latents"),
+ vae=MagicMock(vae=MagicMock(), seamless_axes=[]),
+ tiled=False,
+ tile_size=0,
+ )
+ with pytest.raises(RuntimeError, match="stop at decode"):
+ invocation.invoke(mock_context)
+
+ if auto:
+ pretile.assert_called_once_with(mock_vae_info.compute_device, 20 * 2**30, VAE_PRETILE_VRAM_FRACTION)
+ assert estimate.call_args.kwargs["tile_size"] == QWEN_IMAGE_VAE_DEFAULT_TILE_SIZE
+ mock_vae_info.model_on_device.assert_called_once_with(working_mem_bytes=2 * 2**30)
+ mock_vae.enable_tiling.assert_called_once()
+ else:
+ pretile.assert_not_called()
+ assert estimate.call_count == 1
+ mock_vae.enable_tiling.assert_not_called()
+
class TestQwenImageVaeTiling:
"""Exercise the tiling parameters against a real (tiny, randomly initialised) Qwen-Image VAE.
diff --git a/tests/app/invocations/test_wan_working_memory.py b/tests/app/invocations/test_wan_working_memory.py
index 967bbefb78..0239b424f3 100644
--- a/tests/app/invocations/test_wan_working_memory.py
+++ b/tests/app/invocations/test_wan_working_memory.py
@@ -299,6 +299,7 @@ class TestWanInvocationsRequestWorkingMemory:
def test_latents_to_video_falls_back_to_tiling_when_estimate_exceeds_vram(self):
vae = _mock_wan_vae()
vae_info = _mock_vae_info(vae)
+ vae_info.compute_device = torch.device("cuda")
mock_context = self._video_context(vae_info)
with (
diff --git a/tests/app/invocations/test_z_image_tiled_decode.py b/tests/app/invocations/test_z_image_tiled_decode.py
index 9fafbb2fad..75dd323ebc 100644
--- a/tests/app/invocations/test_z_image_tiled_decode.py
+++ b/tests/app/invocations/test_z_image_tiled_decode.py
@@ -9,7 +9,7 @@ from diffusers.models.autoencoders.autoencoder_kl import AutoencoderKL
from invokeai.app.invocations.vae.z_image_latents_to_image import ZImageLatentsToImageInvocation
from invokeai.backend.flux.modules.autoencoder import DEFAULT_TILE_SAMPLE_MIN_SIZE, MIN_TILE_SAMPLE_SIZE
from invokeai.backend.flux.modules.autoencoder import AutoEncoder as FluxAutoEncoder
-from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_flux
+from invokeai.backend.util.vae_working_memory import VAE_PRETILE_VRAM_FRACTION, estimate_vae_working_memory_flux
def _mock_flux_vae(element_size_bytes: int = 2) -> MagicMock:
@@ -250,6 +250,39 @@ class TestTilingIsWired:
_build_invocation(tiled=True, tile_size=384).invoke(context)
vae.enable_tiling.assert_called_once_with(tile_sample_min_size=384)
+ @pytest.mark.parametrize("auto", [True, False], ids=["auto-tiled-decode-on", "auto-tiled-decode-off"])
+ def test_a_decode_too_large_for_its_gpu_is_tiled_up_front_unless_switched_off(self, auto):
+ """Where the driver pages instead of raising an OOM, the retry below never fires: the estimate decides."""
+ module = "invokeai.app.invocations.vae.z_image_latents_to_image"
+ vae, vae_info, context = _build_decode_mocks(torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512))
+ context.config.get.return_value.auto_tiled_decode = auto
+ with (
+ patch(f"{module}.estimate_vae_working_memory_flux", side_effect=[20 * 2**30, 2 * 2**30]) as estimate,
+ patch(f"{module}.should_pretile_vae_decode", return_value=True) as pretile,
+ ):
+ _build_invocation().invoke(context)
+
+ if auto:
+ pretile.assert_called_once_with(vae_info.compute_device, 20 * 2**30, VAE_PRETILE_VRAM_FRACTION)
+ assert estimate.call_args.kwargs["tile_size"] == 0
+ vae_info.model_on_device.assert_called_once_with(working_mem_bytes=2 * 2**30)
+ vae.enable_tiling.assert_called_once_with(tile_sample_min_size=DEFAULT_TILE_SAMPLE_MIN_SIZE)
+ else:
+ pretile.assert_not_called()
+ assert estimate.call_count == 1
+ vae.disable_tiling.assert_called_once()
+
+ def test_requested_tiling_skips_the_untiled_estimate(self):
+ module = "invokeai.app.invocations.vae.z_image_latents_to_image"
+ _, _, context = _build_decode_mocks(torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512))
+ with (
+ patch(f"{module}.estimate_vae_working_memory_flux", return_value=2 * 2**30) as estimate,
+ patch(f"{module}.should_pretile_vae_decode") as pretile,
+ ):
+ _build_invocation(tiled=True).invoke(context)
+ assert estimate.call_count == 1
+ pretile.assert_not_called()
+
@pytest.mark.parametrize("tiled,expected_tile_size", [(False, None), (True, 0)])
def test_the_estimate_is_tile_bounded_only_when_tiling(self, tiled, expected_tile_size):
path = "invokeai.app.invocations.vae.z_image_latents_to_image.estimate_vae_working_memory_flux"
diff --git a/tests/backend/util/test_vae_pretile.py b/tests/backend/util/test_vae_pretile.py
new file mode 100644
index 0000000000..6ef2fc1098
--- /dev/null
+++ b/tests/backend/util/test_vae_pretile.py
@@ -0,0 +1,40 @@
+"""The decode nodes' up-front tiling rule: tile when an untiled decode would claim more than a share of the VAE's GPU.
+
+Waiting for an out-of-memory error does not work where the driver pages into system memory instead of failing
+(Windows ROCm always, NVIDIA's sysmem fallback by default), so the rule has to hold on the estimate alone.
+"""
+
+import math
+from unittest.mock import MagicMock, patch
+
+import pytest
+import torch
+
+from invokeai.backend.util.vae_working_memory import VAE_PRETILE_VRAM_FRACTION, should_pretile_vae_decode
+
+TOTAL = 16 * 2**30
+
+
[email protected]("fraction", [0.7, VAE_PRETILE_VRAM_FRACTION], ids=["anima", "image-and-video-vaes"])
+def test_a_gpu_decode_flips_at_the_share_of_its_devices_memory(fraction):
+ device = torch.device("cuda", 1)
+ boundary = fraction * TOTAL
+ with patch("torch.cuda.get_device_properties", return_value=MagicMock(total_memory=TOTAL)) as props:
+ assert should_pretile_vae_decode(device, math.floor(boundary), fraction) is False
+ assert should_pretile_vae_decode(device, math.ceil(boundary) + 1, fraction) is True
+ props.assert_called_with(device) # the VAE's own device, not whichever is current
+
+
[email protected]("device_type", ["cpu", "mps"])
+def test_a_decode_off_the_gpu_is_never_tiled_on_these_grounds(device_type):
+ """A cpu_only VAE runs in system RAM, and MPS shares it: device totals are not the constraint there."""
+ assert should_pretile_vae_decode(torch.device(device_type), 10**15, VAE_PRETILE_VRAM_FRACTION) is False
+
+
+def test_1024px_stays_untiled_on_an_8gb_card_and_1536px_tiles_on_16gb():
+ """The share is chosen so common sizes keep the exact single-pass decode: a Qwen-Image VAE decode at 1024px
+ (~5.7 GiB) on an 8 GiB card stays untiled; a FLUX VAE decode at 1536px on ROCm (~15.8 GiB) tiles on 16 GiB."""
+ with patch("torch.cuda.get_device_properties", return_value=MagicMock(total_memory=8 * 2**30)):
+ assert not should_pretile_vae_decode(torch.device("cuda"), 1024 * 1024 * 2 * 2900, VAE_PRETILE_VRAM_FRACTION)
+ with patch("torch.cuda.get_device_properties", return_value=MagicMock(total_memory=TOTAL)):
+ assert should_pretile_vae_decode(torch.device("cuda"), 1536 * 1536 * 2 * 3600, VAE_PRETILE_VRAM_FRACTION)