Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

fix(vae): budget diffusers FLUX.1 decodes and quiet up-front tiling

Alexander Eichhorn2ab7aaaea25a
diff --git a/docs/src/content/docs/configuration/low-vram-mode.mdx b/docs/src/content/docs/configuration/low-vram-mode.mdx
index 24e9d7e42c..77208d4e53 100644
--- a/docs/src/content/docs/configuration/low-vram-mode.mdx
+++ b/docs/src/content/docs/configuration/low-vram-mode.mdx
@@ -163,7 +163,7 @@ device_working_mem_gb: 4
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:
+To always decode untiled unless you ask for tiling, turn it off. A decode too large for the card then runs out of memory: the FLUX.1, Z-Image and Anima decodes retry in tiles, the others fail, and on Windows the driver may move the decode into system memory and run it very slowly instead.
```yaml
auto_tiled_decode: false
@@ -228,7 +228,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.
+- When part of Invoke's GPU memory stays in system memory across two generations, the log says so. Other programs using the same GPU, like games or browsers, can push Invoke's memory out as well; close them. If it keeps happening, lower the image size, set `max_cache_vram_gb` lower or `device_working_mem_gb` higher, and 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 b20e4b4414..dae131d13d 100644
--- a/docs/src/generated/settings.json
+++ b/docs/src/generated/settings.json
@@ -160,7 +160,7 @@
},
{
"category": "PATHS",
- "default": "models\\.convert_cache",
+ "default": "models/.convert_cache",
"description": "Path to the converted models cache directory (DEPRECATED, but do not delete because it is needed for migration from previous versions).",
"env_var": "INVOKEAI_CONVERT_CACHE_DIR",
"literal_values": [],
@@ -171,7 +171,7 @@
},
{
"category": "PATHS",
- "default": "models\\.download_cache",
+ "default": "models/.download_cache",
"description": "Path to the directory that contains dynamically downloaded models.",
"env_var": "INVOKEAI_DOWNLOAD_CACHE_DIR",
"literal_values": [],
@@ -728,7 +728,7 @@
{
"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.",
+ "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, Z-Image and Anima decodes then still retry tiled after running out of memory.",
"env_var": "INVOKEAI_AUTO_TILED_DECODE",
"literal_values": [],
"name": "auto_tiled_decode",
diff --git a/invokeai/app/invocations/vae/flux_vae_decode.py b/invokeai/app/invocations/vae/flux_vae_decode.py
index ad3d473861..5118429b8c 100644
--- a/invokeai/app/invocations/vae/flux_vae_decode.py
+++ b/invokeai/app/invocations/vae/flux_vae_decode.py
@@ -21,7 +21,6 @@ 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 (
- VAE_PRETILE_VRAM_FRACTION,
estimate_vae_working_memory_flux,
should_pretile_vae_decode,
)
@@ -56,8 +55,22 @@ class FluxVaeDecodeInvocation(BaseInvocation, WithMetadata, WithBoard):
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)
- if isinstance(vae_info.model, AutoEncoder):
+ # Priced for either class, as in the Z-Image decode: a diffusers-layout FLUX VAE runs the same network, and a
+ # decode with nothing reserved is one Windows pages into system memory rather than failing.
+ 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,
+ )
+ if (
+ not use_tiling
+ and config.auto_tiled_decode
+ and should_pretile_vae_decode(vae_info.compute_device, estimated_working_memory)
+ ):
+ use_tiling = True
+ tile_size = 0
estimated_working_memory = estimate_vae_working_memory_flux(
operation="decode",
image_tensor=latents,
@@ -65,24 +78,6 @@ 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
with vae_info.model_on_device(working_mem_bytes=estimated_working_memory) as (_, vae):
assert isinstance(vae, (AutoEncoder, AutoencoderKL))
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 cb91594300..2c3034cd5e 100644
--- a/invokeai/app/invocations/vae/qwen_image_latents_to_image.py
+++ b/invokeai/app/invocations/vae/qwen_image_latents_to_image.py
@@ -23,7 +23,6 @@ from invokeai.backend.util.qwen_image_vae import (
resolve_qwen_image_vae_tile_size,
)
from invokeai.backend.util.vae_working_memory import (
- VAE_PRETILE_VRAM_FRACTION,
estimate_vae_working_memory_qwen_image,
should_pretile_vae_decode,
)
@@ -80,7 +79,7 @@ class QwenImageLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard)
if (
not tiled
and config.auto_tiled_decode
- and should_pretile_vae_decode(vae_info.compute_device, estimated_working_memory, VAE_PRETILE_VRAM_FRACTION)
+ and should_pretile_vae_decode(vae_info.compute_device, estimated_working_memory)
):
effective_tile_size = resolve_qwen_image_vae_tile_size(self.tile_size)
estimated_working_memory = estimate_vae_working_memory_qwen_image(
diff --git a/invokeai/app/invocations/vae/wan_latents_to_video.py b/invokeai/app/invocations/vae/wan_latents_to_video.py
index 07289a95e2..2658a33ff6 100644
--- a/invokeai/app/invocations/vae/wan_latents_to_video.py
+++ b/invokeai/app/invocations/vae/wan_latents_to_video.py
@@ -36,7 +36,6 @@ 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 (
- VAE_PRETILE_VRAM_FRACTION,
estimate_vae_working_memory_wan,
should_pretile_vae_decode,
)
@@ -137,7 +136,7 @@ class WanLatentsToVideoInvocation(BaseInvocation, WithMetadata, WithBoard):
# 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
+ vae_info.compute_device, estimated_working_memory
)
if use_tiling:
tile_size = int(getattr(vae_info.model, "tile_sample_min_height", 256))
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 ff609ea343..dadf047a40 100644
--- a/invokeai/app/invocations/vae/z_image_latents_to_image.py
+++ b/invokeai/app/invocations/vae/z_image_latents_to_image.py
@@ -24,7 +24,6 @@ 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 (
- VAE_PRETILE_VRAM_FRACTION,
estimate_vae_working_memory_flux,
should_pretile_vae_decode,
)
@@ -78,7 +77,7 @@ class ZImageLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):
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)
+ and should_pretile_vae_decode(vae_info.compute_device, estimated_working_memory)
):
use_tiling = True
estimated_working_memory = estimate_vae_working_memory_flux(
diff --git a/invokeai/app/services/config/config_default.py b/invokeai/app/services/config/config_default.py
index 321b12e9f7..d0e9152a34 100644
--- a/invokeai/app/services/config/config_default.py
+++ b/invokeai/app/services/config/config_default.py
@@ -125,7 +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.
+ 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, Z-Image and Anima 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`
@@ -250,7 +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.")
+ 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, Z-Image and Anima 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 e9800a276c..16c7015f85 100644
--- a/invokeai/backend/util/vae_working_memory.py
+++ b/invokeai/backend/util/vae_working_memory.py
@@ -19,7 +19,9 @@ from invokeai.backend.util.logging import InvokeAILogger
VAE_PRETILE_VRAM_FRACTION = 0.9
-def should_pretile_vae_decode(device: torch.device, full_decode_bytes: int, vram_fraction: float) -> bool:
+def should_pretile_vae_decode(
+ device: torch.device, full_decode_bytes: int, vram_fraction: float = VAE_PRETILE_VRAM_FRACTION
+) -> bool:
"""Whether a decode should be tiled up front because its untiled working memory would claim more than
``vram_fraction`` of ``device``'s memory.
@@ -36,10 +38,9 @@ def should_pretile_vae_decode(device: torch.device, full_decode_bytes: int, vram
return False
if full_decode_bytes <= vram_fraction * total_bytes:
return False
- InvokeAILogger.get_logger(__name__).info(
+ InvokeAILogger.get_logger(__name__).debug(
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."
+ f"than {vram_fraction:.0%} of the GPU's {total_bytes / 2**30:.1f} GiB."
)
return True
diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.json
index 0dd671f955..a31844effe 100644
--- a/invokeai/frontend/web/openapi.json
+++ b/invokeai/frontend/web/openapi.json
@@ -55093,7 +55093,7 @@
"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.",
+ "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, Z-Image and Anima decodes then still retry tiled after running out of memory.",
"default": true
},
"pil_compress_level": {
@@ -55390,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 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."
+ "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, Z-Image and Anima 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 a38c2d0f54..8a8f990b7d 100644
--- a/invokeai/frontend/web/src/services/api/schema.ts
+++ b/invokeai/frontend/web/src/services/api/schema.ts
@@ -21129,7 +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.
+ * 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, Z-Image and Anima 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`
@@ -21560,7 +21560,7 @@ export type components = {
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.
+ * @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, Z-Image and Anima decodes then still retry tiled after running out of memory.
* @default true
*/
auto_tiled_decode?: boolean;
diff --git a/scripts/generate_docs_json.py b/scripts/generate_docs_json.py
index d1ece13615..1a09cea5a8 100644
--- a/scripts/generate_docs_json.py
+++ b/scripts/generate_docs_json.py
@@ -225,7 +225,7 @@ def write_docs_bundle(bundle: dict[str, Any], output_dir: Path = OUTPUT_DIR) ->
def _normalize_value(value: Any) -> str | int | float | bool | list[Any] | dict[str, Any] | None:
if isinstance(value, Path):
- return str(value)
+ return value.as_posix()
if isinstance(value, (str, int, float, bool)) or value is None:
return value
if isinstance(value, list):
diff --git a/tests/app/invocations/test_anima_vae.py b/tests/app/invocations/test_anima_vae.py
index 17d79a8952..40061116c1 100644
--- a/tests/app/invocations/test_anima_vae.py
+++ b/tests/app/invocations/test_anima_vae.py
@@ -12,6 +12,7 @@ from diffusers.models.autoencoders.autoencoder_kl_qwenimage import AutoencoderKL
from invokeai.app.invocations.constants import LATENT_SCALE_FACTOR
from invokeai.app.invocations.vae.anima_image_to_latents import AnimaImageToLatentsInvocation
from invokeai.app.invocations.vae.anima_latents_to_image import (
+ ANIMA_PRETILE_VRAM_FRACTION,
ANIMA_VAE_TILE_SIZE,
ANIMA_VAE_TILE_STRIDE,
AnimaLatentsToImageInvocation,
@@ -24,6 +25,8 @@ from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory
# diffusers-layout Qwen-Image export as AutoencoderKLQwenImage.
WAN21_VAE_LAYOUTS = [AutoencoderKLWan, AutoencoderKLQwenImage]
+_L2I = "invokeai.app.invocations.vae.anima_latents_to_image"
+
def _mock_vae(vae_class: type = AutoencoderKLWan, dtype: torch.dtype = torch.float16) -> MagicMock:
vae = MagicMock(spec=vae_class)
@@ -326,6 +329,31 @@ class TestAnimaLatentsToImageOomFallback:
vae_info.model_on_device.assert_called_once_with(working_mem_bytes=expected_memory)
+class TestAnimaPretiling:
+ @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):
+ """Anima asks with its own, lower fraction (measured on 8GB cards) about the VAE's own device."""
+ decoded = torch.zeros(1, 3, 1, 64, 64)
+ vae, vae_info, context = _build_decode_mocks(latents=torch.zeros(1, 16, 32, 32), decoded=decoded)
+ context.config.get.return_value.auto_tiled_decode = auto
+ full = estimate_vae_working_memory_anima(
+ operation="decode", image_tensor=torch.zeros(1, 16, 32, 32), vae=vae, tile_size=None
+ )
+
+ with (
+ patch.object(TorchDevice, "choose_torch_device", return_value=torch.device("cpu")),
+ patch(f"{_L2I}.should_pretile_vae_decode", return_value=True) as pretile,
+ ):
+ _build_l2i_invocation().invoke(context)
+
+ if auto:
+ pretile.assert_called_once_with(vae_info.compute_device, full, ANIMA_PRETILE_VRAM_FRACTION)
+ vae.enable_tiling.assert_called_once()
+ else:
+ pretile.assert_not_called()
+ vae.enable_tiling.assert_not_called()
+
+
class TestAnimaImageToLatentsEncode:
def test_encode_disables_tiling_and_requests_working_memory(self):
vae = _mock_vae(dtype=torch.float32)
diff --git a/tests/app/invocations/test_flux_vae_decode_tiling.py b/tests/app/invocations/test_flux_vae_decode_tiling.py
index c87f6fd492..c80e1c3a5f 100644
--- a/tests/app/invocations/test_flux_vae_decode_tiling.py
+++ b/tests/app/invocations/test_flux_vae_decode_tiling.py
@@ -9,16 +9,18 @@ from unittest.mock import MagicMock, patch
import pytest
import torch
+from diffusers.models.autoencoders.autoencoder_kl import AutoencoderKL
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):
+def _build_decode_mocks(
+ latents: torch.Tensor, decoded: torch.Tensor, force_tiled_decode: bool = False, vae_class: type = FluxAutoEncoder
+):
"""Wire FluxVaeDecodeInvocation.invoke to run end-to-end on CPU against a mocked FLUX VAE."""
- vae = MagicMock(spec=FluxAutoEncoder)
+ vae = MagicMock(spec=vae_class)
# A fresh iterator per call: the decode path reads `parameters()` after the estimator already
# has, and a single stored iterator would be exhausted by then.
vae.parameters.side_effect = lambda: iter([torch.zeros(1, dtype=torch.float16)])
@@ -91,7 +93,7 @@ class TestForceTiledDecode:
_build_invocation().invoke(context)
if auto:
- pretile.assert_called_once_with(vae_info.compute_device, 20 * 2**30, VAE_PRETILE_VRAM_FRACTION)
+ pretile.assert_called_once_with(vae_info.compute_device, 20 * 2**30)
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)
@@ -100,6 +102,21 @@ class TestForceTiledDecode:
vae.disable_tiling.assert_called_once()
+class TestDiffusersLayoutVae:
+ def test_a_diffusers_layout_flux_vae_reserves_its_working_memory(self):
+ """It runs the same network; a decode with nothing reserved is the one Windows pages instead of failing."""
+ vae, vae_info, context = _build_decode_mocks(
+ torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512), vae_class=AutoencoderKL
+ )
+ vae.config = MagicMock(scaling_factor=0.3611, shift_factor=0.1159)
+ vae.decode.return_value = (torch.zeros(1, 3, 512, 512),)
+
+ _build_invocation().invoke(context)
+
+ (reservation,) = vae_info.model_on_device.call_args.kwargs.values()
+ assert reservation > 0
+
+
class TestOomFallback:
def test_an_untiled_oom_retries_once_tiled_and_says_so(self):
decoded = torch.zeros(1, 3, 512, 512)
diff --git a/tests/app/invocations/test_qwen_image_working_memory.py b/tests/app/invocations/test_qwen_image_working_memory.py
index 1aaa3c81f3..dd8e4e8a75 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 VAE_PRETILE_VRAM_FRACTION, estimate_vae_working_memory_qwen_image
+from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_qwen_image
class TestQwenImageWorkingMemoryEstimate:
@@ -447,7 +447,7 @@ class TestQwenImageWorkingMemory:
invocation.invoke(mock_context)
if auto:
- pretile.assert_called_once_with(mock_vae_info.compute_device, 20 * 2**30, VAE_PRETILE_VRAM_FRACTION)
+ pretile.assert_called_once_with(mock_vae_info.compute_device, 20 * 2**30)
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()
diff --git a/tests/app/invocations/test_wan_working_memory.py b/tests/app/invocations/test_wan_working_memory.py
index 0239b424f3..82ed50cbb7 100644
--- a/tests/app/invocations/test_wan_working_memory.py
+++ b/tests/app/invocations/test_wan_working_memory.py
@@ -3,6 +3,7 @@
from unittest.mock import MagicMock, patch
import PIL.Image
+import pytest
import torch
from diffusers.models.autoencoders import AutoencoderKLWan
@@ -296,11 +297,13 @@ class TestWanInvocationsRequestWorkingMemory:
vae.disable_tiling.assert_called_once()
vae.decode.assert_not_called()
- def test_latents_to_video_falls_back_to_tiling_when_estimate_exceeds_vram(self):
+ @pytest.mark.parametrize("auto", [True, False], ids=["auto-tiled-decode-on", "auto-tiled-decode-off"])
+ def test_latents_to_video_falls_back_to_tiling_when_estimate_exceeds_vram(self, auto):
vae = _mock_wan_vae()
vae_info = _mock_vae_info(vae)
vae_info.compute_device = torch.device("cuda")
mock_context = self._video_context(vae_info)
+ mock_context.config.get.return_value.auto_tiled_decode = auto
with (
patch(
@@ -319,16 +322,22 @@ class TestWanInvocationsRequestWorkingMemory:
except Exception:
pass
- assert mock_estimate.call_count == 2
- assert mock_estimate.call_args_list[1].kwargs["tile_size"] == 256
- vae.enable_tiling.assert_called_once()
+ if auto:
+ assert mock_estimate.call_count == 2
+ assert mock_estimate.call_args_list[1].kwargs["tile_size"] == 256
+ vae.enable_tiling.assert_called_once()
+ vae_info.model_on_device.assert_called_once_with(working_mem_bytes=4 * 2**30)
+ else:
+ assert mock_estimate.call_count == 1
+ vae.enable_tiling.assert_not_called()
+ vae_info.model_on_device.assert_called_once_with(working_mem_bytes=100 * 2**30)
vae.disable_tiling.assert_called_once()
- vae_info.model_on_device.assert_called_once_with(working_mem_bytes=4 * 2**30)
def test_latents_to_video_skips_tiling_for_cpu_only_vae(self):
- """A cpu_only VAE runs in system RAM; VRAM-based tiling must not kick in."""
+ """A cpu_only VAE runs in system RAM; VRAM-based tiling must not kick in, even with a small GPU present."""
vae = _mock_wan_vae()
vae_info = _mock_vae_info(vae, cpu_only=True)
+ vae_info.compute_device = torch.device("cpu")
mock_context = self._video_context(vae_info)
with (
@@ -338,6 +347,7 @@ class TestWanInvocationsRequestWorkingMemory:
) as mock_estimate,
patch.object(TorchDevice, "choose_torch_device", return_value=torch.device("cuda")),
patch.object(TorchDevice, "empty_cache"),
+ patch("torch.cuda.get_device_properties", return_value=MagicMock(total_memory=8 * 2**30)),
):
invocation = WanLatentsToVideoInvocation.model_construct(
latents=MagicMock(latents_name="l"), vae=MagicMock(vae=MagicMock()), fps=16
diff --git a/tests/app/invocations/test_z_image_tiled_decode.py b/tests/app/invocations/test_z_image_tiled_decode.py
index 75dd323ebc..de36fd1ffa 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 VAE_PRETILE_VRAM_FRACTION, estimate_vae_working_memory_flux
+from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_flux
def _mock_flux_vae(element_size_bytes: int = 2) -> MagicMock:
@@ -263,7 +263,7 @@ class TestTilingIsWired:
_build_invocation().invoke(context)
if auto:
- pretile.assert_called_once_with(vae_info.compute_device, 20 * 2**30, VAE_PRETILE_VRAM_FRACTION)
+ pretile.assert_called_once_with(vae_info.compute_device, 20 * 2**30)
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)