Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(previews): decode Tiny AutoEncoder previews on the CPU (#10231)
Alexander Eichhorn078004e4e916
diff --git a/docs/src/content/docs/Users Guide/03.Models/01.introduction.mdx b/docs/src/content/docs/Users Guide/03.Models/01.introduction.mdxindex b86d6162de..73b1c64dca 100644--- a/docs/src/content/docs/Users Guide/03.Models/01.introduction.mdx+++ b/docs/src/content/docs/Users Guide/03.Models/01.introduction.mdx@@ -149,7 +149,7 @@ Click a model in the library to open it. Its **⋯** menu, and right-clicking it| Trigger phrases | **Trigger Phrases** (main models, LoRAs, embeddings) | Offered in the prompt editor. || Cover image | Click the model's image | Shown in the library and pickers. PNG, JPEG or WebP. || Related models | **Related Models** | Linked models are suggested together elsewhere in the app. |-| Run on CPU | **Run on CPU** (text encoders, VAEs, CLIP Vision, SigLIP, LLaVA OneVision, Text LLMs) | Saves VRAM; may be slower. |+| Run on CPU | **Run on CPU** (text encoders, VAEs, CLIP Vision, SigLIP, LLaVA OneVision, Text LLMs); **Decode previews on CPU** (Tiny AutoEncoders) | Saves VRAM; may be slower. || Moved file | **Update path** beside the path (models installed in place outside the models folder, or whose files are missing) | Points Invoke at the file's new location. Nothing is moved or copied. || Convert to diffusers | **Convert to diffusers** (checkpoint main models of supported families) | Replaces the checkpoint file with a diffusers folder. || Re-identify | **Re-identify model** in the menu | Re-reads the files to detect base, type, format and variant again. |@@ -214,7 +214,7 @@ Invoke identifies a model from its files, and falls back to its name only where| `name`, `description`, `source_url` | The model's name, description and Source URL. || `default_settings` | Default steps, CFG or guidance, scheduler, size, FP8 storage, VAE precision and the other defaults. || `trigger_phrases` | Trigger phrases. |-| `cpu_only` | The **Run on CPU** choice. |+| `cpu_only` | The **Run on CPU** choice, or **Decode previews on CPU** for a Tiny AutoEncoder. || `cover_image` | The cover image, embedded as a data URL. |Fields you haven't set are left out. On import, top-level fields Invoke doesn't recognize are skipped, a field the model doesn't have is skipped and named in a notice, and the rest is applied. A default setting the receiving version doesn't know makes that model's import fail. A file is rejected if `source_url` is not an `http://` or `https://` URL or `cover_image` is not an image data URL.diff --git a/docs/src/content/docs/Users Guide/04.Image Generation/Advanced Topics/tiny-autoencoder-previews.mdx b/docs/src/content/docs/Users Guide/04.Image Generation/Advanced Topics/tiny-autoencoder-previews.mdxindex 04040b5464..09e4908f36 100644--- a/docs/src/content/docs/Users Guide/04.Image Generation/Advanced Topics/tiny-autoencoder-previews.mdx+++ b/docs/src/content/docs/Users Guide/04.Image Generation/Advanced Topics/tiny-autoencoder-previews.mdx@@ -1,6 +1,6 @@---title: Tiny AutoEncoder Previews-lastUpdated: 2026-10-28+lastUpdated: 2026-11-10sidebar:order: 13---@@ -10,8 +10,8 @@ import { Steps, Aside } from '@astrojs/starlight/components'While a model denoises, InvokeAI shows a preview of the image after each step. By default the preview is a linearprojection of the latents: one pixel per latent, upscaled, so it is blurry and its colours are approximate. A**Tiny AutoEncoder** (TAE) is a small decoder by [madebyollin](https://github.com/madebyollin/taesd) (MIT license)-that turns the same latents into a preview close to the final image, in a few tens of milliseconds on an RTX 4090. It needs a GPU:-on CPU-only installs it is not recommended (see [Cost and fallback](#cost-and-fallback)).+that turns the same latents into a preview close to the final image, in a few tens of milliseconds on an RTX 4090. It is meant for+a GPU; decoding on the CPU is possible but slower (see [Running the decoder on the CPU](#running-the-decoder-on-the-cpu)).TAE previews change only what you see while a generation runs. The finished image is decoded by the model's VAE asalways and is identical with the setting on or off.@@ -79,8 +79,8 @@ Measured on an RTX 4090 in fp16, decoding one latent at the cap:| TAELTX2.3 | 1024 pixels | about 29 ms | about 0.27 GB |A Wan 2.2 video preview, which decodes two latent frames, takes under about 32 ms. InvokeAI reserves up to 617 MiB-of VRAM for it from 832×480 to 1280×720 and 1093 MiB at 1024×1024; on an RTX 4090 it used up to 599 and 1064 MiB. Without a GPU a preview takes about 2 seconds, so TAE-previews are not recommended on CPU-only installs.+of VRAM for it from 832×480 to 1280×720 and 1093 MiB at 1024×1024; on an RTX 4090 it used up to 599 and 1064 MiB. On a CPU a preview takes+from about 0.3 to 1.1 seconds for one frame (see [Running the decoder on the CPU](#running-the-decoder-on-the-cpu)).InvokeAI spaces TAE preview frames so that previews cost at most about a tenth of the denoising time. On fast modelsthe preview therefore updates a few times per second rather than after every step. In practice the cost is lower: on@@ -92,10 +92,41 @@ InvokeAI falls back to the linear preview by itself, and the generation always c- **No matching TAE installed:** linear previews. The server log says once which starter model to install, andunder which family the starter list shows it.- **The TAE does not fit in VRAM** next to the running model: linear previews for that generation, noted once in- the server log. This is the case whenever the main model is only partially loaded into VRAM, as on low-VRAM cards.+ the server log (`Tiny AutoEncoder '...' does not fit in VRAM next to the running model`). This is the case whenever+ the main model is only partially loaded into VRAM, as on low-VRAM cards. To get TAE previews there anyway, run the+ decoder on the CPU.- **Loading or decoding the TAE fails:** a warning with the error in the server log, once per kind of failure,then linear previews for the rest of that generation.+## Running the decoder on the CPU++The switch only matters while `tiny_autoencoder_previews` is on. If the log line above appears, or your GPU is busy+enough that you would rather keep its memory for the model, open the TAE in **Model Manager** and switch on+**Decode previews on CPU**. The setting is saved at once. The decoder then lives in system RAM, never needs VRAM, and+decodes in float32 on the CPU, so it also works while the generation model fills the GPU. The change applies from the+next generation.++Decoding on a CPU costs more time, so InvokeAI limits the work:++- The preview is decoded at no more than 512 pixels on its long edge, whatever the TAE's usual cap, and shown at full+ size.+- Measured on a Ryzen 9 7900 (8 threads, float32): TAESDXL and TAEF2 take about 0.3 to 0.4 s per frame at 512 pixels+ (1.7 s at 1024 pixels, which is why the cap exists). TAEW2.1 takes about 0.8 to 1.1 s for a single frame (Anima,+ Qwen-Image, Krea-2); a Wan two-frame window takes about 1.9 s at 1024×1024 and about 1.0 s at 832×480. TAEW2.2 and+ TAELTX2.3 were not measured on a CPU. Slower CPUs take longer.+- Frames are still spaced by their measured cost, so with a CPU decoder previews update less often: a frame costing+ 0.4 s is followed by roughly 8 s without a new one. The last (100%) frame is always decoded, whatever the spacing.+ Each frame is decoded between two denoise steps, so the GPU waits for it: on an RTX 4090 with the model only partly+ in VRAM (1024×1024, 30 steps), a CPU decoder added about 7% (SDXL, a frame every 5 s) and 9% (Anima, a frame every+ 12 s) to the denoise compared with linear previews.+- With several GPUs, a CPU decode competes with the other generation threads' CPU work.+- A CPU decode needs transient RAM that the model cache does not count: about 0.3 GB for TAESDXL at 512 pixels and+ about 1.2 GB for a TAEW2.1 two-frame window. If PyTorch reports that the allocation failed, previews fall back to+ linear for the rest of that generation; on a Linux host that overcommits memory, the system's out-of-memory killer+ may end the process instead.++CPU-only installs decode on the CPU in any case and are subject to the same 512-pixel cap.+<Aside type="note">If more than one installed TAE fits a family, InvokeAI uses the one that is alphabetically first by name.</Aside>diff --git a/docs/src/generated/settings.json b/docs/src/generated/settings.jsonindex 6ba1e1609e..141579491c 100644--- a/docs/src/generated/settings.json+++ b/docs/src/generated/settings.json@@ -805,7 +805,7 @@{"category": "GENERATION","default": false,- "description": "Render denoising previews with an installed Tiny AutoEncoder instead of the linear latent projection. Install the matching Tiny AutoEncoder starter model; families without one keep linear previews. A preview costs a few tens of ms and up to about 1.1 GB of transient VRAM on an RTX 4090 (image decoders 0.15-0.65 GB, Wan video windows up to 1.1 GB); not recommended on CPU-only installs, where one takes about 2 s.",+ "description": "Render denoising previews with an installed Tiny AutoEncoder instead of the linear latent projection. Install the matching Tiny AutoEncoder starter model; families without one keep linear previews. A preview costs a few tens of ms and up to about 1.1 GB of transient VRAM on an RTX 4090 (image decoders 0.15-0.65 GB, Wan video windows up to 1.1 GB); a TAE that does not fit in VRAM next to the running model can instead run on the CPU (its `Decode previews on CPU` setting in the model manager): previews are capped at 512 px there and a frame takes about 0.3-0.4 s (TAESDXL, TAEF2), 0.8-1.1 s (TAEW2.1, one frame) or 1.0-1.9 s (Wan two-frame window) on a Ryzen 9 7900 with 8 threads in float32, so previews update less often.","env_var": "INVOKEAI_TINY_AUTOENCODER_PREVIEWS","literal_values": [],"name": "tiny_autoencoder_previews",diff --git a/invokeai/app/services/config/config_default.py b/invokeai/app/services/config/config_default.pyindex ef3fdfa333..aadd328ac5 100644--- a/invokeai/app/services/config/config_default.py+++ b/invokeai/app/services/config/config_default.py@@ -137,7 +137,7 @@ class InvokeAIAppConfig(BaseSettings):noise_dtype: The dtype seeded noise is drawn in for SD1.5/SDXL, SD3, FLUX.1, FLUX.2, CogView4 and the Z-Image seed variance enhancer. `float32` draws the same noise on every platform. `float16` is the half-precision draw of earlier versions: on macOS it keeps the images your seeds gave before this update; on Windows and Linux both values give (nearly) the same images, and images made before the update cannot be reproduced there.<br>Valid values: `float32`, `float16`wan_memory_optimization: Enable experimental Wan memory optimizations at the cost of slower generation.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.- tiny_autoencoder_previews: Render denoising previews with an installed Tiny AutoEncoder instead of the linear latent projection. Install the matching Tiny AutoEncoder starter model; families without one keep linear previews. A preview costs a few tens of ms and up to about 1.1 GB of transient VRAM on an RTX 4090 (image decoders 0.15-0.65 GB, Wan video windows up to 1.1 GB); not recommended on CPU-only installs, where one takes about 2 s.+ tiny_autoencoder_previews: Render denoising previews with an installed Tiny AutoEncoder instead of the linear latent projection. Install the matching Tiny AutoEncoder starter model; families without one keep linear previews. A preview costs a few tens of ms and up to about 1.1 GB of transient VRAM on an RTX 4090 (image decoders 0.15-0.65 GB, Wan video windows up to 1.1 GB); a TAE that does not fit in VRAM next to the running model can instead run on the CPU (its `Decode previews on CPU` setting in the model manager): previews are capped at 512 px there and a frame takes about 0.3-0.4 s (TAESDXL, TAEF2), 0.8-1.1 s (TAEW2.1, one frame) or 1.0-1.9 s (Wan two-frame window) on a Ryzen 9 7900 with 8 threads in float32, so previews update less often.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`attention_backend: Attention kernel for the attention inside diffusion models. `auto` uses PyTorch's exact SDPA kernels ranked flash, cuDNN, memory-efficient, math, taking the first one the GPU and build support for each call; it never selects a quantized one. `sage` uses SageAttention 2 for the models listed in the SageAttention docs: faster, most at high resolutions and for video, but quantized, so images differ slightly from `auto` at the same seed. SageAttention is installed separately and needs an NVIDIA GPU with compute capability 8.0 or newer; masked attention, text encoders and VAEs keep PyTorch SDPA. `cudnn`, `flash`, `efficient` and `math` rank that PyTorch kernel first for all attention on CUDA and ROCm GPUs, ahead of the `auto` order. That is never exclusive: a call the kernel cannot serve runs on the next kernel, and the log reports that once per node type and reason (not for the PiD decoder, whose attention is ranked the same but not reported). `math` materializes the full attention score matrix, so it is slow and needs much more memory, which the working-memory estimates of most model families do not reserve, so generations can run out of memory; it is meant for debugging. Images can differ slightly between kernels.<br>Valid values: `auto`, `sage`, `cudnn`, `flash`, `efficient`, `math`@@ -277,7 +277,7 @@ class InvokeAIAppConfig(BaseSettings):noise_dtype: NOISE_DTYPE = Field(default="float32", description="The dtype seeded noise is drawn in for SD1.5/SDXL, SD3, FLUX.1, FLUX.2, CogView4 and the Z-Image seed variance enhancer. `float32` draws the same noise on every platform. `float16` is the half-precision draw of earlier versions: on macOS it keeps the images your seeds gave before this update; on Windows and Linux both values give (nearly) the same images, and images made before the update cannot be reproduced there.")wan_memory_optimization: bool = Field(default=False, description="Enable experimental Wan memory optimizations at the cost of slower generation.")pid_memory_optimization: bool = Field(default=False, description="Enable experimental PiD decode memory optimizations. Roughly halves the peak activation memory of a PiD decode; in exchange the decoded image changes slightly, because neither the chunked pixel pathway nor the float32 sampler intermediates are bit-exact with the default path.")- tiny_autoencoder_previews: bool = Field(default=False, description="Render denoising previews with an installed Tiny AutoEncoder instead of the linear latent projection. Install the matching Tiny AutoEncoder starter model; families without one keep linear previews. A preview costs a few tens of ms and up to about 1.1 GB of transient VRAM on an RTX 4090 (image decoders 0.15-0.65 GB, Wan video windows up to 1.1 GB); not recommended on CPU-only installs, where one takes about 2 s.")+ tiny_autoencoder_previews: bool = Field(default=False, description="Render denoising previews with an installed Tiny AutoEncoder instead of the linear latent projection. Install the matching Tiny AutoEncoder starter model; families without one keep linear previews. A preview costs a few tens of ms and up to about 1.1 GB of transient VRAM on an RTX 4090 (image decoders 0.15-0.65 GB, Wan video windows up to 1.1 GB); a TAE that does not fit in VRAM next to the running model can instead run on the CPU (its `Decode previews on CPU` setting in the model manager): previews are capped at 512 px there and a frame takes about 0.3-0.4 s (TAESDXL, TAEF2), 0.8-1.1 s (TAEW2.1, one frame) or 1.0-1.9 s (Wan two-frame window) on a Ryzen 9 7900 with 8 threads in float32, so previews update less often.")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".')attention_backend: ATTENTION_BACKEND = Field(default="auto", description="Attention kernel for the attention inside diffusion models. `auto` uses PyTorch's exact SDPA kernels ranked flash, cuDNN, memory-efficient, math, taking the first one the GPU and build support for each call; it never selects a quantized one. `sage` uses SageAttention 2 for the models listed in the SageAttention docs: faster, most at high resolutions and for video, but quantized, so images differ slightly from `auto` at the same seed. SageAttention is installed separately and needs an NVIDIA GPU with compute capability 8.0 or newer; masked attention, text encoders and VAEs keep PyTorch SDPA. `cudnn`, `flash`, `efficient` and `math` rank that PyTorch kernel first for all attention on CUDA and ROCm GPUs, ahead of the `auto` order. That is never exclusive: a call the kernel cannot serve runs on the next kernel, and the log reports that once per node type and reason (not for the PiD decoder, whose attention is ranked the same but not reported). `math` materializes the full attention score matrix, so it is slow and needs much more memory, which the working-memory estimates of most model families do not reserve, so generations can run out of memory; it is meant for debugging. Images can differ slightly between kernels.")diff --git a/invokeai/app/util/tiny_autoencoder_previews.py b/invokeai/app/util/tiny_autoencoder_previews.pyindex 85ac0e3e76..101cd3824d 100644--- a/invokeai/app/util/tiny_autoencoder_previews.py+++ b/invokeai/app/util/tiny_autoencoder_previews.py@@ -61,6 +61,11 @@ def tiny_autoencoder_starters(space: LatentSpace) -> list[StarterModel]:return starters+def _normalized(device: torch.device | None) -> torch.device | None:+ """`device` with its index, so `cuda` and `cuda:0` compare equal."""+ return None if device is None else TorchDevice.normalize(device)++def _first_report(key: Hashable) -> bool:with _reported_lock:first = key not in _reported@@ -101,7 +106,10 @@ class TinyAutoencoderPreviews:self._tae_frames = 0self._render_cost_s: float | None = Noneself._decoded_on: torch.device | None = None # where this frame's TAE decode ran; None if linear+ self._sample_on: torch.device | None = None # where this frame's latents lived+ self._first_frame_overhead_s = 0.0 # lookup, load, lock and queued-step wait of a first CPU TAE frameself._last_tae_device: torch.device | None = None+ self._last_sample_device: torch.device | None = None # where the latents of the last TAE frame lived@propertydef min_frame_interval_s(self) -> float | None:@@ -115,22 +123,36 @@ class TinyAutoencoderPreviews:def measure_frame(self) -> Iterator[None]:"""Time one emitted frame, from its render through its encode, into the render-cost estimate.- The TAE's device is synchronized first, so denoise work still queued on it is not counted as the- frame's. After that, wall time is the frame's whole cost: the decode copies its image to the CPU,- which waits for the decode. The first TAE frame is not counted, because it also looks the TAE up,- loads and locks it.+ The TAE's device and the one the latents live on are synchronized first, so denoise work still queued+ on either is not counted as the frame's: a CPU TAE's decode would otherwise wait for the GPU step that+ produced its latents when it copies them over. After that, wall time is the frame's whole cost: the+ decode copies its image to the CPU, which waits for the decode.++ The first TAE frame also looks the TAE up, loads and locks it, so on a GPU it is not counted: cuDNN's+ first-call algorithm selection can make it unrepresentative too, and a GPU frame costs about 25 ms anyway.+ A CPU decode has no cold-start outlier, and its frames cost 0.3 s and more: leaving the first one uncounted+ would let the second go out unpaced. It is counted without the lookup, load, lock and the wait for the+ queued step (`_first_frame_overhead_s`). The final frame is always rendered, and it is one frame."""if self._last_tae_device is not None:TorchDevice.synchronize(self._last_tae_device)+ if self._last_sample_device is not None and _normalized(self._last_sample_device) != _normalized(+ self._last_tae_device+ ):+ TorchDevice.synchronize(self._last_sample_device)self._decoded_on = None+ self._first_frame_overhead_s = 0.0start = monotonic()yieldcost = monotonic() - startif self._decoded_on is None or self._disabled:returnself._last_tae_device = self._decoded_on+ self._last_sample_device = self._sample_onself._tae_frames += 1if self._tae_frames == 1:+ if self._decoded_on.type == "cpu":+ self._render_cost_s = cost - self._first_frame_overhead_sreturnif self._render_cost_s is None:self._render_cost_s = cost@@ -141,10 +163,16 @@ class TinyAutoencoderPreviews:space = resolve_latent_space(base_model, preview_frame(sample))if not self._disabled:try:+ started = monotonic()held = self._decoder_for(base_model, space, sample)if held is not None:+ if held.device.type == "cpu" and self._tae_frames == 0:+ # The decode's copy of the latents would wait for the queued step; wait here, outside the cost.+ TorchDevice.synchronize(sample.device)+ self._first_frame_overhead_s = monotonic() - startedimage = decode_preview(held.decoder, sample, device=held.device)self._decoded_on = held.device+ self._sample_on = sample.devicesize = (sample.shape[-1] * space.spatial_compression, sample.shape[-2] * space.spatial_compression)return image, sizeexcept Exception as error:@@ -167,6 +195,7 @@ class TinyAutoencoderPreviews:def _disable(self) -> None:self._disabled = Trueself._last_tae_device = None+ self._last_sample_device = Noneself._decoders.clear()self._locks.close()@@ -201,7 +230,7 @@ class TinyAutoencoderPreviews:if not isinstance(decoder, TinyAutoencoderDecoder):raise TypeError(f"expected a TinyAutoencoderDecoder, the loader returned {type(decoder).__name__}")# Reserved once, with the lock: a denoise keeps its size, so every later frame decodes the same.- working_mem_bytes = decode_working_memory_bytes(decoder, sample)+ working_mem_bytes = decode_working_memory_bytes(decoder, sample, loaded.compute_device)if not self._fits_in_vram(loaded, working_mem_bytes):self._report_not_resident(config)return None@@ -266,7 +295,8 @@ class TinyAutoencoderPreviews:("not resident", config.key),logging.INFO,f"Tiny AutoEncoder '{config.name}' does not fit in VRAM next to the running model; "- "using linear previews for this invocation.",+ 'using linear previews for this invocation. Enable "Decode previews on CPU" for it in the model manager '+ "to decode previews on the CPU instead.",)def _log_once(self, key: Hashable, level: int, message: str, exc_info: bool | None = None) -> None:diff --git a/invokeai/backend/model_manager/configs/tiny_autoencoder.py b/invokeai/backend/model_manager/configs/tiny_autoencoder.pyindex b8a727da9e..ac1c697978 100644--- a/invokeai/backend/model_manager/configs/tiny_autoencoder.py+++ b/invokeai/backend/model_manager/configs/tiny_autoencoder.py@@ -177,6 +177,7 @@ class TinyAutoencoder_Checkpoint_Config_Base(Checkpoint_Config_Base):type: Literal[ModelType.TinyAutoencoder] = Field(default=ModelType.TinyAutoencoder)format: Literal[ModelFormat.Checkpoint] = Field(default=ModelFormat.Checkpoint)latent_channels: int = Field(description="Latent channels the decoder consumes.")+ cpu_only: bool | None = Field(default=None, description="Whether this model should run on CPU only")ARCH: ClassVar[TinyAutoencoderArch]"""The decoder architecture this base's TAEs use."""diff --git a/invokeai/backend/model_manager/load/model_loaders/tiny_autoencoder.py b/invokeai/backend/model_manager/load/model_loaders/tiny_autoencoder.pyindex b7248a000a..ba3fdd2297 100644--- a/invokeai/backend/model_manager/load/model_loaders/tiny_autoencoder.py+++ b/invokeai/backend/model_manager/load/model_loaders/tiny_autoencoder.py@@ -60,4 +60,8 @@ class TinyAutoencoderLoader(ModelLoader):raise ValueError(f"'{config.name}' is not a supported Tiny AutoEncoder checkpoint.")decoder = build_tiny_autoencoder_decoder(layout)decoder.load_state_dict(tiny_autoencoder_state_dict(checkpoint, layout), strict=True)- return decoder.to(self._torch_dtype).eval().requires_grad_(False)+ # float32 for CPU-only decoders, the policy of CPU-only text LLMs (`text_llm.py`): CPU float16 is emulated+ # and slow, CPU bfloat16 is fast only with native support (about 4.7x slower than float32 without it), and+ # torch's CPU bfloat16 kernels fault with an illegal instruction on some CPUs.+ dtype = torch.float32 if config.cpu_only is True else self._torch_dtype+ return decoder.to(dtype).eval().requires_grad_(False)diff --git a/invokeai/backend/tiny_autoencoder/preview.py b/invokeai/backend/tiny_autoencoder/preview.pyindex 2c01a5b8ee..988635a6e7 100644--- a/invokeai/backend/tiny_autoencoder/preview.py+++ b/invokeai/backend/tiny_autoencoder/preview.py@@ -16,27 +16,36 @@ _POOLING_NEEDS_DIVISIBLE_SIZES: Final = frozenset({"mps"})"""Device types whose adaptive average pooling, behind `F.interpolate(mode="area")`, refuses an output size that doesnot divide the input ("input sizes must be divisible by output sizes", pytorch#96056); macOS stays on torch 2.7."""+CPU_MAX_PREVIEW_EDGE: Final = 512+"""Longest preview edge, in pixels, decoded on a CPU, whatever the decoder's own `max_preview_edge`. On a Ryzen 9 7900+(8 threads, float32) a full `decode_preview` of TAESDXL or TAEF2 took 1.70 s at 1024x1024 and 0.38-0.40 s at 512x512;+TAEW2.1, already capped at 512, took 1.07 s."""+TinyAutoencoderConfig = TypeVar("TinyAutoencoderConfig", bound=TinyAutoencoder_Checkpoint_Config_Base)-def _preview_latent_size(decoder: TinyAutoencoderDecoder, height: int, width: int) -> tuple[int, int]:- """The latent size a `(height, width)` latent is decoded at: downsampled until the image fits the decoder's- `max_preview_edge`."""+def _preview_latent_size(+ decoder: TinyAutoencoderDecoder, device: torch.device, height: int, width: int+) -> tuple[int, int]:+ """The latent size a `(height, width)` latent is decoded at on `device`: downsampled until the image fits the+ decoder's `max_preview_edge`, and on a CPU `CPU_MAX_PREVIEW_EDGE`."""+ max_edge = decoder.max_preview_edge if device.type != "cpu" else min(decoder.max_preview_edge, CPU_MAX_PREVIEW_EDGE)longest_edge = max(height, width) * decoder.spatial_compression- if longest_edge <= decoder.max_preview_edge:+ if longest_edge <= max_edge:return height, width- scale = decoder.max_preview_edge / longest_edge+ scale = max_edge / longest_edgereturn max(1, math.floor(height * scale)), max(1, math.floor(width * scale))-def decode_working_memory_bytes(decoder: TinyAutoencoderDecoder, sample: torch.Tensor) -> int:- """The working memory `decode_preview(decoder, sample)` needs on its device besides the decoder's weights: the- decoder's own bound (`preview_working_memory_bytes`) at the capped size, for every latent frame of a window.+def decode_working_memory_bytes(decoder: TinyAutoencoderDecoder, sample: torch.Tensor, device: torch.device) -> int:+ """The working memory `decode_preview(decoder, sample, device)` needs on its device besides the decoder's+ weights: the decoder's own bound (`preview_working_memory_bytes`) at the capped size, for every latent frame of a+ window.The cache's working-memory floor (`device_working_mem_gb`, 3 GB by default) covers every supported decoder's, sothe reservation matters only where that floor is set lower."""- height, width = _preview_latent_size(decoder, *sample.shape[-2:])+ height, width = _preview_latent_size(decoder, device, *sample.shape[-2:])frames = sample.shape[2] if sample.dim() == 5 else 1return decoder.preview_working_memory_bytes(height, width, frames)@@ -53,7 +62,8 @@ def _area_downsample(latents: torch.Tensor, size: tuple[int, int]) -> torch.Tensdef decode_preview(decoder: TinyAutoencoderDecoder, sample: torch.Tensor, device: torch.device | None = None) -> Image.Image:- """Decode the first latent of `sample` into an RGB preview no larger than `decoder.max_preview_edge`.+ """Decode the first latent of `sample` into an RGB preview no larger than `decoder.max_preview_edge` (on a CPU,+ no larger than `CPU_MAX_PREVIEW_EDGE`).`sample` is `(C, h, w)` or `(B, C, h, w)` in the decoder's latent space, or a `(B, C, T, h, w)` windowof latent frames, which a video decoder renders as its last frame with the earlier ones as temporal@@ -78,9 +88,10 @@ def decode_preview()parameter = next(decoder.parameters())+ device = device or parameter.devicewith torch.inference_mode():- latents = sample[0:1].to(device=device or parameter.device, dtype=parameter.dtype)- size = _preview_latent_size(decoder, *latents.shape[-2:])+ latents = sample[0:1].to(device=device, dtype=parameter.dtype)+ size = _preview_latent_size(decoder, device, *latents.shape[-2:])if size != tuple(latents.shape[-2:]):if latents.dim() == 5:# A window's frames are folded into the batch, so they are pooled in space only and throughdiff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.jsonindex b89a51929c..74f6b9d6ab 100644--- a/invokeai/frontend/api/openapi.json+++ b/invokeai/frontend/api/openapi.json@@ -65933,7 +65933,7 @@"tiny_autoencoder_previews": {"type": "boolean","title": "Tiny Autoencoder Previews",- "description": "Render denoising previews with an installed Tiny AutoEncoder instead of the linear latent projection. Install the matching Tiny AutoEncoder starter model; families without one keep linear previews. A preview costs a few tens of ms and up to about 1.1 GB of transient VRAM on an RTX 4090 (image decoders 0.15-0.65 GB, Wan video windows up to 1.1 GB); not recommended on CPU-only installs, where one takes about 2 s.",+ "description": "Render denoising previews with an installed Tiny AutoEncoder instead of the linear latent projection. Install the matching Tiny AutoEncoder starter model; families without one keep linear previews. A preview costs a few tens of ms and up to about 1.1 GB of transient VRAM on an RTX 4090 (image decoders 0.15-0.65 GB, Wan video windows up to 1.1 GB); a TAE that does not fit in VRAM next to the running model can instead run on the CPU (its `Decode previews on CPU` setting in the model manager): previews are capped at 512 px there and a frame takes about 0.3-0.4 s (TAESDXL, TAEF2), 0.8-1.1 s (TAEW2.1, one frame) or 1.0-1.9 s (Wan two-frame window) on a Ryzen 9 7900 with 8 threads in float32, so previews update less often.","default": false},"attention_type": {@@ -66286,7 +66286,7 @@"additionalProperties": false,"type": "object","title": "InvokeAIAppConfig",- "description": "Invoke's global app configuration.\n\nTypically, you won't need to interact with this class directly. Instead, use the `get_config` function from `invokeai.app.services.config` to get a singleton config object.\n\nAttributes:\n host: IP address to bind to. Use `0.0.0.0` to serve to your local network.\n port: Port to bind to.\n allow_origins: Allowed CORS origins.\n allow_credentials: Allow CORS credentials.\n allow_methods: Methods allowed for CORS.\n allow_headers: Headers allowed for CORS.\n ssl_certfile: SSL certificate file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n ssl_keyfile: SSL key file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n show_donation_link: Show the Donate to InvokeAI link in the frontend menus.\n log_tokenization: Enable logging of parsed prompt tokens.\n patchmatch: Enable patchmatch inpaint code.\n models_dir: Path to the models directory.\n convert_cache_dir: Path to the converted models cache directory (DEPRECATED, but do not delete because it is needed for migration from previous versions).\n download_cache_dir: Path to the directory that contains dynamically downloaded models.\n legacy_conf_dir: Path to directory of legacy checkpoint config files.\n db_dir: Path to InvokeAI databases directory.\n db_url: URL of a MySQL 8.4+ or MariaDB 10.11+ database to use instead of the SQLite database in `db_dir`, e.g. `mariadb+pymysql://invokeai:[email protected]/invokeai`. Needs the `mysql` extra. One InvokeAI process uses a database at a time. Read at startup only.\n db_synchronous: SQLite durability setting. `full`, the default and what InvokeAI has always used, flushes every commit to disk. `normal` acknowledges commits without waiting for that flush - measured at roughly 12x shorter commits on an SSD - and cannot corrupt the database under WAL, which is why it is refused, with a warning, when WAL is unavailable for the database file. What `normal` gives up is the most recent transactions on a power loss or OS crash: a just-written image record or queue status, not the image file itself.<br>Valid values: `full`, `normal`\n outputs_dir: Path to directory for outputs.\n image_subfolder_strategy: Strategy for organizing images into subfolders. 'flat' stores all images in a single folder. 'date' organizes by YYYY/MM/DD. 'type' organizes by image category. 'hash' uses first 2 characters of UUID for filesystem performance.<br>Valid values: `flat`, `date`, `type`, `hash`\n custom_nodes_dir: Path to directory for custom nodes.\n style_presets_dir: Path to directory for style presets.\n prompt_files_dir: Path to the directory holding prompt list files readable by the Prompts from File node. The node cannot read outside this directory.\n workflow_thumbnails_dir: Path to directory for workflow thumbnails.\n log_handlers: Log handler. Valid options are \"console\", \"file=<path>\", \"syslog=path|address:host:port\", \"http=<url>\".\n log_format: Log format. Use \"plain\" for text-only, \"color\" for colorized output, \"legacy\" for 2.3-style logging and \"syslog\" for syslog-style.<br>Valid values: `plain`, `color`, `syslog`, `legacy`\n log_level: Emit logging messages at this level or higher.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n log_sql: Log SQL queries. `log_level` must be `debug` for this to do anything. Extremely verbose.\n log_level_network: Log level for network-related messages. 'info' and 'debug' are very verbose.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n use_memory_db: Use in-memory database. Useful for development.\n dev_reload: Automatically reload when Python sources are changed. Does not reload node definitions.\n profile_graphs: Enable graph profiling using `cProfile`.\n profile_prefix: An optional prefix for profile output files.\n profiles_dir: Path to profiles output directory.\n max_cache_ram_gb: The maximum amount of CPU RAM to use for model caching in GB. If unset, the limit will be configured based on the available RAM. In most cases, it is recommended to leave this unset.\n max_cache_vram_gb: The amount of VRAM to use for model caching in GB. If unset, the limit will be configured based on the available VRAM and the device_working_mem_gb. In most cases, it is recommended to leave this unset.\n reserve_vram_gb: The amount of VRAM (in GB) to subtract from the model cache's available memory budget. Defaults to 0.\n log_memory_usage: If True, a memory snapshot will be captured before and after every model cache operation, and the result will be logged (at debug level). There is a time cost to capturing the memory snapshots, so it is recommended to only enable this feature if you are actively inspecting the model cache's behaviour.\n model_cache_keep_alive_min: How long to keep models in cache after last use, in minutes. A value of 0 (the default) means models are kept in cache indefinitely. If no model generations occur within the timeout period, the model cache is cleared using the same logic as the 'Clear Model Cache' button.\n device_working_mem_gb: The amount of working memory to keep available on the compute device (in GB). Has no effect if running on CPU. If you are experiencing OOM errors, try increasing this value.\n enable_partial_loading: Enable partial loading of models. This enables models to run with reduced VRAM requirements (at the cost of slower speed) by streaming the model from RAM to VRAM as its used. In some edge cases, partial loading can cause models to run more slowly if they were previously being fully loaded into VRAM.\n keep_ram_copy_of_weights: Whether to keep a full RAM copy of a model's weights when the model is loaded in VRAM. Keeping a RAM copy increases average RAM usage, but speeds up model switching and LoRA patching (assuming there is sufficient RAM). Set this to False if RAM pressure is consistently high.\n offload_on_architecture_switch: When a session uses main models of another architecture than the previous one on the same GPU, move every model it does not use from VRAM to RAM before it runs. Models both sessions use stay. Switching back reloads the moved models from RAM, which costs a few seconds per switch when both architectures would have fit in VRAM together; turn this off if you alternate between such models.\n clear_vram_after_session: After every queue item (each image of a batch), move the models held in VRAM to RAM and return the freed memory to the GPU driver. The models stay cached in RAM; the next item reloads them from there, which costs a few seconds (more with keep_ram_copy_of_weights off). Changes nothing where VRAM is system memory (CPU, MPS, integrated GPUs). Turn this on if a generation that runs fine the first time runs out of memory, or slows down sharply because the GPU spills into shared memory, when it is repeated.\n fp8_compute: Keep ComfyUI 'scaled fp8' checkpoints quantized instead of dequantizing them at load, and run their matmuls on the fp8 tensor cores (requires an Ada/SM 8.9 or newer NVIDIA GPU, or a ROCm GPU that passes an fp8 matmul probe; falls back automatically otherwise). Speeds up denoising and keeps the transformer at fp8 size - FP8 Storage alone also keeps it at that size, without the speedup - but quantizes activations as well, so images will differ from previous versions at the same seed. Reproducibility also requires the model to be FULLY resident in VRAM: a layer whose weights are still in RAM falls back to the dequantized path, and since which layers are resident shifts from run to run, the same seed then yields visibly different images. For repeatable output, ensure the model loads at 100% (e.g. enable_partial_loading=false with enough free VRAM).\n fp8_compute_full_precision_hints: Honor the per-layer 'full_precision_matrix_mult' flags that some scaled-fp8 checkpoints ship. Those layers then dequantize on every forward instead of using the fp8 tensor cores, which can cost a large part of the fp8_compute speedup - on checkpoints that mark many layers, most of it. Set to false to run every quantized layer on the fp8 tensor cores, ignoring the producer's instruction; faster, but the marked layers were flagged as numerically sensitive, so quality may suffer. Only has an effect when fp8_compute is enabled.\n int8_compute: Run the matmuls of ComfyUI int8 builds quantized with convrot ('int8_tensorwise' with 'convrot') on the int8 tensor cores instead of dequantizing their weights on every forward (requires an NVIDIA GPU with compute capability 8.0 or newer and Triton; falls back automatically otherwise, including on AMD, Apple and Intel GPUs and the CPU). Speeds up denoising with these builds, but quantizes activations per token as well, so images will differ from the dequantized path at the same seed. The kernels are tuned once per layer shape and token-count bucket: about 35 seconds for the first image after enabling it, about 1-5 seconds for a later size in a new token-count bucket, cached on disk across restarts.\n ram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_ram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n vram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_vram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n lazy_offload: DEPRECATED: This setting is no longer used. Lazy-offloading is enabled by default. This config setting will be removed once the new model cache behavior is stable.\n pytorch_cuda_alloc_conf: Configure the Torch CUDA memory allocator. This will impact peak reserved VRAM usage and performance. Setting to \"backend:cudaMallocAsync\" works well on many systems. The optimal configuration is highly dependent on the system configuration (device type, VRAM, CUDA driver version, etc.), so must be tuned experimentally. Unset on a ROCm build of PyTorch on Windows, \"expandable_segments:True\" is used.\n device: Preferred execution device. `auto` will choose the device depending on the hardware platform and the installed torch capabilities.<br>Valid values: `auto`, `cpu`, `cuda`, `mps`, `xpu`, `cuda:N`, `xpu:N` (where N is a device number)\n precision: Floating point precision. `float16` will consume half the memory of `float32` but produce slightly lower-quality images. The `auto` setting will guess the proper precision based on your video card and operating system.<br>Valid values: `auto`, `float16`, `bfloat16`, `float32`\n rocm_aotriton_experimental: Use AOTriton's fused (flash and memory-efficient) attention kernels on AMD GPUs that PyTorch marks experimental for them, such as the RX 7600/7700/7800 series, Ryzen AI 300/Max and the RX 9060 series, by setting TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL. Without them, attention on those GPUs runs on the slower math kernel, which also needs far more memory. `auto` turns them on only with a ROCm 10 build of PyTorch, and only when every GPU used for generation is one they were measured correct on (so far gfx1200, the RX 9060 series); `on` and `off` decide for any build and GPU. A TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL value already set in the environment takes precedence. Has no effect on other GPUs.<br>Valid values: `auto`, `on`, `off`\n sequential_guidance: Whether to calculate guidance in serial instead of in parallel, lowering memory requirements.\n noise_dtype: The dtype seeded noise is drawn in for SD1.5/SDXL, SD3, FLUX.1, FLUX.2, CogView4 and the Z-Image seed variance enhancer. `float32` draws the same noise on every platform. `float16` is the half-precision draw of earlier versions: on macOS it keeps the images your seeds gave before this update; on Windows and Linux both values give (nearly) the same images, and images made before the update cannot be reproduced there.<br>Valid values: `float32`, `float16`\n wan_memory_optimization: Enable experimental Wan memory optimizations at the cost of slower generation.\n pid_memory_optimization: Enable experimental PiD decode memory optimizations. Roughly halves the peak activation memory of a PiD decode; in exchange the decoded image changes slightly, because neither the chunked pixel pathway nor the float32 sampler intermediates are bit-exact with the default path.\n tiny_autoencoder_previews: Render denoising previews with an installed Tiny AutoEncoder instead of the linear latent projection. Install the matching Tiny AutoEncoder starter model; families without one keep linear previews. A preview costs a few tens of ms and up to about 1.1 GB of transient VRAM on an RTX 4090 (image decoders 0.15-0.65 GB, Wan video windows up to 1.1 GB); not recommended on CPU-only installs, where one takes about 2 s.\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 attention_backend: Attention kernel for the attention inside diffusion models. `auto` uses PyTorch's exact SDPA kernels ranked flash, cuDNN, memory-efficient, math, taking the first one the GPU and build support for each call; it never selects a quantized one. `sage` uses SageAttention 2 for the models listed in the SageAttention docs: faster, most at high resolutions and for video, but quantized, so images differ slightly from `auto` at the same seed. SageAttention is installed separately and needs an NVIDIA GPU with compute capability 8.0 or newer; masked attention, text encoders and VAEs keep PyTorch SDPA. `cudnn`, `flash`, `efficient` and `math` rank that PyTorch kernel first for all attention on CUDA and ROCm GPUs, ahead of the `auto` order. That is never exclusive: a call the kernel cannot serve runs on the next kernel, and the log reports that once per node type and reason (not for the PiD decoder, whose attention is ranked the same but not reported). `math` materializes the full attention score matrix, so it is slow and needs much more memory, which the working-memory estimates of most model families do not reserve, so generations can run out of memory; it is meant for debugging. Images can differ slightly between kernels.<br>Valid values: `auto`, `sage`, `cudnn`, `flash`, `efficient`, `math`\n force_tiled_decode: Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty). A tiled decode is not pixel-identical to a single-pass one: a VAE decoder normalises and attends over the whole image, so the difference is spread across it rather than confined to the tile seams. Also tiles the encode. Read by the SD1.5/SDXL, FLUX.1, FLUX.2, Z-Image, Qwen-Image and Qwen-Image-2.1 VAE nodes, the Anima encode, the Z-Image control encode and the Krea-2 style reference; other model families ignore it.\n auto_tiled_decode: Decode large images in tiles when an untiled decode's estimated working memory would take most of the GPU's memory (FLUX.1, FLUX.2, Z-Image, Qwen-Image, Qwen-Image-2.1, Krea-2 and Wan decodes, and Qwen-Image-2.1 encodes). Turn off to decode untiled unless tiling is requested; the FLUX.1, FLUX.2 and Z-Image decodes then still retry tiled after running out of memory. Anima keeps tiling a decode too large for its GPU either way, because tiling is what makes that case fast there.\n pil_compress_level: The compress_level setting of PIL.Image.save(), used for PNG encoding. All settings are lossless. 0 = no compression, 1 = fastest with slightly larger filesize, 9 = slowest with smallest filesize. 1 is typically the best setting.\n max_queue_size: Maximum number of items in the session queue.\n session_queue_mode: Session queue mode. Use 'FIFO' for traditional first-in-first-out, or 'round_robin' to serve each user's jobs in turn. In single-user mode, FIFO is always used regardless of this setting.<br>Valid values: `FIFO`, `round_robin`\n clear_queue_on_startup: Empties session queue on startup. If true, disables `max_queue_history`.\n max_queue_history: Keep the last N completed, failed, and canceled queue items. Older items are deleted on startup. Set to 0 to prune all terminal items. Ignored if `clear_queue_on_startup` is true.\n allow_nodes: List of nodes to allow. Omit to allow all.\n deny_nodes: List of nodes to deny. Omit to deny none.\n node_cache_size: How many cached nodes to keep in memory.\n hashing_algorithm: Model hashing algorthim for model installs. 'blake3_multi' is best for SSDs. 'blake3_single' is best for spinning disk HDDs. 'random' disables hashing, instead assigning a UUID to models. Useful when using a memory db to reduce model installation time, or if you don't care about storing stable hashes for models. Alternatively, any other hashlib algorithm is accepted, though these are not nearly as performant as blake3.<br>Valid values: `blake3_multi`, `blake3_single`, `random`, `md5`, `sha1`, `sha224`, `sha256`, `sha384`, `sha512`, `blake2b`, `blake2s`, `sha3_224`, `sha3_256`, `sha3_384`, `sha3_512`, `shake_128`, `shake_256`\n remote_api_tokens: List of regular expression and token pairs used when downloading models from URLs. The download URL is tested against the regex, and if it matches, the token is provided in as a Bearer token.\n scan_models_on_startup: Scan the models directory on startup, registering orphaned models. This is typically only used in conjunction with `use_memory_db` for testing purposes.\n allow_private_download_urls: Allow the download queue to fetch from loopback, link-local and private-network addresses. Disabled by default so that a download URL cannot be used to reach services that are only reachable from the server. Enable this only if you install models from a mirror on your own network.\n download_proxy: Optional HTTP proxy for model downloads. The proxy must enforce the public-address policy because proxy-side DNS cannot be checked by InvokeAI.\n unsafe_disable_picklescan: UNSAFE. Disable the picklescan security check during model installation. Recommended only for development and testing purposes. This will allow arbitrary code execution during model installation, so should never be used in production.\n allow_unknown_models: Allow installation of models that we are unable to identify. If enabled, models will be marked as `unknown` in the database, and will not have any metadata associated with them. If disabled, unknown models will be rejected during installation.\n multiuser: Enable multiuser support. When disabled, the application runs in single-user mode using a default system account with administrator privileges. When enabled, requires user authentication and authorization.\n strict_password_checking: Enforce strict password requirements. When True, passwords must contain uppercase, lowercase, and numbers. When False (default), any password is accepted but its strength (weak/moderate/strong) is reported to the user.\n image_index_enabled: Maintain a semantic embedding index of gallery images and videos, used by the image map and semantic search features.\n image_index_model: Name of the installed CLIP Vision or SigLIP model used to embed gallery images and video thumbnails. Changing the model discards embeddings computed by the previous model.\n image_index_device: Set to `cpu` to compute image embeddings on the CPU with a service-local copy of the model - avoids VRAM use and lets indexing run during generations. Any other value is ignored: embeddings otherwise run on the model cache's device, pausing while generations are in progress.\n image_index_batch_size: Number of gallery items embedded per batch by the image index worker.\n external_alibabacloud_api_key: API key for Alibaba Cloud DashScope image generation.\n external_alibabacloud_base_url: Base URL override for Alibaba Cloud DashScope image generation.\n external_atlascloud_api_key: API key for Atlas Cloud image generation.\n external_atlascloud_base_url: Base URL override for Atlas Cloud image generation.\n external_gemini_api_key: API key for Gemini image generation.\n external_openai_api_key: API key for OpenAI image generation.\n external_gemini_base_url: Base URL override for Gemini image generation.\n external_openai_base_url: Base URL override for OpenAI image generation.\n external_seedream_api_key: API key for Seedream image generation.\n external_seedream_base_url: Base URL override for Seedream image generation.\n base_url: Public base path when running behind a reverse proxy under a sub-path, e.g. `/invoke`. Set only when the proxy PRESERVES the sub-path (the backend receives `/invoke/api/...`). Leave unset when the proxy strips the sub-path or when serving at the domain root.\n forwarded_allow_ips: Comma-separated list of IPs (or `*`) allowed to set X-Forwarded-* headers. Set to the reverse proxy's IP. Only used when `base_url` is set.\n http_compression_level: Compression level for gzipped HTTP API responses. 0 disables response compression entirely, 1 is fastest, 9 (the default) is smallest. Compression runs on the event loop and blocks the whole server while it works, and level 9 costs about 5.5x the time of level 1 for 0.4 percentage points of extra compression, so lowering this makes the app noticeably more responsive on large libraries. Set to 0 when a reverse proxy already compresses responses."+ "description": "Invoke's global app configuration.\n\nTypically, you won't need to interact with this class directly. Instead, use the `get_config` function from `invokeai.app.services.config` to get a singleton config object.\n\nAttributes:\n host: IP address to bind to. Use `0.0.0.0` to serve to your local network.\n port: Port to bind to.\n allow_origins: Allowed CORS origins.\n allow_credentials: Allow CORS credentials.\n allow_methods: Methods allowed for CORS.\n allow_headers: Headers allowed for CORS.\n ssl_certfile: SSL certificate file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n ssl_keyfile: SSL key file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n show_donation_link: Show the Donate to InvokeAI link in the frontend menus.\n log_tokenization: Enable logging of parsed prompt tokens.\n patchmatch: Enable patchmatch inpaint code.\n models_dir: Path to the models directory.\n convert_cache_dir: Path to the converted models cache directory (DEPRECATED, but do not delete because it is needed for migration from previous versions).\n download_cache_dir: Path to the directory that contains dynamically downloaded models.\n legacy_conf_dir: Path to directory of legacy checkpoint config files.\n db_dir: Path to InvokeAI databases directory.\n db_url: URL of a MySQL 8.4+ or MariaDB 10.11+ database to use instead of the SQLite database in `db_dir`, e.g. `mariadb+pymysql://invokeai:[email protected]/invokeai`. Needs the `mysql` extra. One InvokeAI process uses a database at a time. Read at startup only.\n db_synchronous: SQLite durability setting. `full`, the default and what InvokeAI has always used, flushes every commit to disk. `normal` acknowledges commits without waiting for that flush - measured at roughly 12x shorter commits on an SSD - and cannot corrupt the database under WAL, which is why it is refused, with a warning, when WAL is unavailable for the database file. What `normal` gives up is the most recent transactions on a power loss or OS crash: a just-written image record or queue status, not the image file itself.<br>Valid values: `full`, `normal`\n outputs_dir: Path to directory for outputs.\n image_subfolder_strategy: Strategy for organizing images into subfolders. 'flat' stores all images in a single folder. 'date' organizes by YYYY/MM/DD. 'type' organizes by image category. 'hash' uses first 2 characters of UUID for filesystem performance.<br>Valid values: `flat`, `date`, `type`, `hash`\n custom_nodes_dir: Path to directory for custom nodes.\n style_presets_dir: Path to directory for style presets.\n prompt_files_dir: Path to the directory holding prompt list files readable by the Prompts from File node. The node cannot read outside this directory.\n workflow_thumbnails_dir: Path to directory for workflow thumbnails.\n log_handlers: Log handler. Valid options are \"console\", \"file=<path>\", \"syslog=path|address:host:port\", \"http=<url>\".\n log_format: Log format. Use \"plain\" for text-only, \"color\" for colorized output, \"legacy\" for 2.3-style logging and \"syslog\" for syslog-style.<br>Valid values: `plain`, `color`, `syslog`, `legacy`\n log_level: Emit logging messages at this level or higher.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n log_sql: Log SQL queries. `log_level` must be `debug` for this to do anything. Extremely verbose.\n log_level_network: Log level for network-related messages. 'info' and 'debug' are very verbose.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n use_memory_db: Use in-memory database. Useful for development.\n dev_reload: Automatically reload when Python sources are changed. Does not reload node definitions.\n profile_graphs: Enable graph profiling using `cProfile`.\n profile_prefix: An optional prefix for profile output files.\n profiles_dir: Path to profiles output directory.\n max_cache_ram_gb: The maximum amount of CPU RAM to use for model caching in GB. If unset, the limit will be configured based on the available RAM. In most cases, it is recommended to leave this unset.\n max_cache_vram_gb: The amount of VRAM to use for model caching in GB. If unset, the limit will be configured based on the available VRAM and the device_working_mem_gb. In most cases, it is recommended to leave this unset.\n reserve_vram_gb: The amount of VRAM (in GB) to subtract from the model cache's available memory budget. Defaults to 0.\n log_memory_usage: If True, a memory snapshot will be captured before and after every model cache operation, and the result will be logged (at debug level). There is a time cost to capturing the memory snapshots, so it is recommended to only enable this feature if you are actively inspecting the model cache's behaviour.\n model_cache_keep_alive_min: How long to keep models in cache after last use, in minutes. A value of 0 (the default) means models are kept in cache indefinitely. If no model generations occur within the timeout period, the model cache is cleared using the same logic as the 'Clear Model Cache' button.\n device_working_mem_gb: The amount of working memory to keep available on the compute device (in GB). Has no effect if running on CPU. If you are experiencing OOM errors, try increasing this value.\n enable_partial_loading: Enable partial loading of models. This enables models to run with reduced VRAM requirements (at the cost of slower speed) by streaming the model from RAM to VRAM as its used. In some edge cases, partial loading can cause models to run more slowly if they were previously being fully loaded into VRAM.\n keep_ram_copy_of_weights: Whether to keep a full RAM copy of a model's weights when the model is loaded in VRAM. Keeping a RAM copy increases average RAM usage, but speeds up model switching and LoRA patching (assuming there is sufficient RAM). Set this to False if RAM pressure is consistently high.\n offload_on_architecture_switch: When a session uses main models of another architecture than the previous one on the same GPU, move every model it does not use from VRAM to RAM before it runs. Models both sessions use stay. Switching back reloads the moved models from RAM, which costs a few seconds per switch when both architectures would have fit in VRAM together; turn this off if you alternate between such models.\n clear_vram_after_session: After every queue item (each image of a batch), move the models held in VRAM to RAM and return the freed memory to the GPU driver. The models stay cached in RAM; the next item reloads them from there, which costs a few seconds (more with keep_ram_copy_of_weights off). Changes nothing where VRAM is system memory (CPU, MPS, integrated GPUs). Turn this on if a generation that runs fine the first time runs out of memory, or slows down sharply because the GPU spills into shared memory, when it is repeated.\n fp8_compute: Keep ComfyUI 'scaled fp8' checkpoints quantized instead of dequantizing them at load, and run their matmuls on the fp8 tensor cores (requires an Ada/SM 8.9 or newer NVIDIA GPU, or a ROCm GPU that passes an fp8 matmul probe; falls back automatically otherwise). Speeds up denoising and keeps the transformer at fp8 size - FP8 Storage alone also keeps it at that size, without the speedup - but quantizes activations as well, so images will differ from previous versions at the same seed. Reproducibility also requires the model to be FULLY resident in VRAM: a layer whose weights are still in RAM falls back to the dequantized path, and since which layers are resident shifts from run to run, the same seed then yields visibly different images. For repeatable output, ensure the model loads at 100% (e.g. enable_partial_loading=false with enough free VRAM).\n fp8_compute_full_precision_hints: Honor the per-layer 'full_precision_matrix_mult' flags that some scaled-fp8 checkpoints ship. Those layers then dequantize on every forward instead of using the fp8 tensor cores, which can cost a large part of the fp8_compute speedup - on checkpoints that mark many layers, most of it. Set to false to run every quantized layer on the fp8 tensor cores, ignoring the producer's instruction; faster, but the marked layers were flagged as numerically sensitive, so quality may suffer. Only has an effect when fp8_compute is enabled.\n int8_compute: Run the matmuls of ComfyUI int8 builds quantized with convrot ('int8_tensorwise' with 'convrot') on the int8 tensor cores instead of dequantizing their weights on every forward (requires an NVIDIA GPU with compute capability 8.0 or newer and Triton; falls back automatically otherwise, including on AMD, Apple and Intel GPUs and the CPU). Speeds up denoising with these builds, but quantizes activations per token as well, so images will differ from the dequantized path at the same seed. The kernels are tuned once per layer shape and token-count bucket: about 35 seconds for the first image after enabling it, about 1-5 seconds for a later size in a new token-count bucket, cached on disk across restarts.\n ram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_ram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n vram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_vram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n lazy_offload: DEPRECATED: This setting is no longer used. Lazy-offloading is enabled by default. This config setting will be removed once the new model cache behavior is stable.\n pytorch_cuda_alloc_conf: Configure the Torch CUDA memory allocator. This will impact peak reserved VRAM usage and performance. Setting to \"backend:cudaMallocAsync\" works well on many systems. The optimal configuration is highly dependent on the system configuration (device type, VRAM, CUDA driver version, etc.), so must be tuned experimentally. Unset on a ROCm build of PyTorch on Windows, \"expandable_segments:True\" is used.\n device: Preferred execution device. `auto` will choose the device depending on the hardware platform and the installed torch capabilities.<br>Valid values: `auto`, `cpu`, `cuda`, `mps`, `xpu`, `cuda:N`, `xpu:N` (where N is a device number)\n precision: Floating point precision. `float16` will consume half the memory of `float32` but produce slightly lower-quality images. The `auto` setting will guess the proper precision based on your video card and operating system.<br>Valid values: `auto`, `float16`, `bfloat16`, `float32`\n rocm_aotriton_experimental: Use AOTriton's fused (flash and memory-efficient) attention kernels on AMD GPUs that PyTorch marks experimental for them, such as the RX 7600/7700/7800 series, Ryzen AI 300/Max and the RX 9060 series, by setting TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL. Without them, attention on those GPUs runs on the slower math kernel, which also needs far more memory. `auto` turns them on only with a ROCm 10 build of PyTorch, and only when every GPU used for generation is one they were measured correct on (so far gfx1200, the RX 9060 series); `on` and `off` decide for any build and GPU. A TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL value already set in the environment takes precedence. Has no effect on other GPUs.<br>Valid values: `auto`, `on`, `off`\n sequential_guidance: Whether to calculate guidance in serial instead of in parallel, lowering memory requirements.\n noise_dtype: The dtype seeded noise is drawn in for SD1.5/SDXL, SD3, FLUX.1, FLUX.2, CogView4 and the Z-Image seed variance enhancer. `float32` draws the same noise on every platform. `float16` is the half-precision draw of earlier versions: on macOS it keeps the images your seeds gave before this update; on Windows and Linux both values give (nearly) the same images, and images made before the update cannot be reproduced there.<br>Valid values: `float32`, `float16`\n wan_memory_optimization: Enable experimental Wan memory optimizations at the cost of slower generation.\n pid_memory_optimization: Enable experimental PiD decode memory optimizations. Roughly halves the peak activation memory of a PiD decode; in exchange the decoded image changes slightly, because neither the chunked pixel pathway nor the float32 sampler intermediates are bit-exact with the default path.\n tiny_autoencoder_previews: Render denoising previews with an installed Tiny AutoEncoder instead of the linear latent projection. Install the matching Tiny AutoEncoder starter model; families without one keep linear previews. A preview costs a few tens of ms and up to about 1.1 GB of transient VRAM on an RTX 4090 (image decoders 0.15-0.65 GB, Wan video windows up to 1.1 GB); a TAE that does not fit in VRAM next to the running model can instead run on the CPU (its `Decode previews on CPU` setting in the model manager): previews are capped at 512 px there and a frame takes about 0.3-0.4 s (TAESDXL, TAEF2), 0.8-1.1 s (TAEW2.1, one frame) or 1.0-1.9 s (Wan two-frame window) on a Ryzen 9 7900 with 8 threads in float32, so previews update less often.\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 attention_backend: Attention kernel for the attention inside diffusion models. `auto` uses PyTorch's exact SDPA kernels ranked flash, cuDNN, memory-efficient, math, taking the first one the GPU and build support for each call; it never selects a quantized one. `sage` uses SageAttention 2 for the models listed in the SageAttention docs: faster, most at high resolutions and for video, but quantized, so images differ slightly from `auto` at the same seed. SageAttention is installed separately and needs an NVIDIA GPU with compute capability 8.0 or newer; masked attention, text encoders and VAEs keep PyTorch SDPA. `cudnn`, `flash`, `efficient` and `math` rank that PyTorch kernel first for all attention on CUDA and ROCm GPUs, ahead of the `auto` order. That is never exclusive: a call the kernel cannot serve runs on the next kernel, and the log reports that once per node type and reason (not for the PiD decoder, whose attention is ranked the same but not reported). `math` materializes the full attention score matrix, so it is slow and needs much more memory, which the working-memory estimates of most model families do not reserve, so generations can run out of memory; it is meant for debugging. Images can differ slightly between kernels.<br>Valid values: `auto`, `sage`, `cudnn`, `flash`, `efficient`, `math`\n force_tiled_decode: Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty). A tiled decode is not pixel-identical to a single-pass one: a VAE decoder normalises and attends over the whole image, so the difference is spread across it rather than confined to the tile seams. Also tiles the encode. Read by the SD1.5/SDXL, FLUX.1, FLUX.2, Z-Image, Qwen-Image and Qwen-Image-2.1 VAE nodes, the Anima encode, the Z-Image control encode and the Krea-2 style reference; other model families ignore it.\n auto_tiled_decode: Decode large images in tiles when an untiled decode's estimated working memory would take most of the GPU's memory (FLUX.1, FLUX.2, Z-Image, Qwen-Image, Qwen-Image-2.1, Krea-2 and Wan decodes, and Qwen-Image-2.1 encodes). Turn off to decode untiled unless tiling is requested; the FLUX.1, FLUX.2 and Z-Image decodes then still retry tiled after running out of memory. Anima keeps tiling a decode too large for its GPU either way, because tiling is what makes that case fast there.\n pil_compress_level: The compress_level setting of PIL.Image.save(), used for PNG encoding. All settings are lossless. 0 = no compression, 1 = fastest with slightly larger filesize, 9 = slowest with smallest filesize. 1 is typically the best setting.\n max_queue_size: Maximum number of items in the session queue.\n session_queue_mode: Session queue mode. Use 'FIFO' for traditional first-in-first-out, or 'round_robin' to serve each user's jobs in turn. In single-user mode, FIFO is always used regardless of this setting.<br>Valid values: `FIFO`, `round_robin`\n clear_queue_on_startup: Empties session queue on startup. If true, disables `max_queue_history`.\n max_queue_history: Keep the last N completed, failed, and canceled queue items. Older items are deleted on startup. Set to 0 to prune all terminal items. Ignored if `clear_queue_on_startup` is true.\n allow_nodes: List of nodes to allow. Omit to allow all.\n deny_nodes: List of nodes to deny. Omit to deny none.\n node_cache_size: How many cached nodes to keep in memory.\n hashing_algorithm: Model hashing algorthim for model installs. 'blake3_multi' is best for SSDs. 'blake3_single' is best for spinning disk HDDs. 'random' disables hashing, instead assigning a UUID to models. Useful when using a memory db to reduce model installation time, or if you don't care about storing stable hashes for models. Alternatively, any other hashlib algorithm is accepted, though these are not nearly as performant as blake3.<br>Valid values: `blake3_multi`, `blake3_single`, `random`, `md5`, `sha1`, `sha224`, `sha256`, `sha384`, `sha512`, `blake2b`, `blake2s`, `sha3_224`, `sha3_256`, `sha3_384`, `sha3_512`, `shake_128`, `shake_256`\n remote_api_tokens: List of regular expression and token pairs used when downloading models from URLs. The download URL is tested against the regex, and if it matches, the token is provided in as a Bearer token.\n scan_models_on_startup: Scan the models directory on startup, registering orphaned models. This is typically only used in conjunction with `use_memory_db` for testing purposes.\n allow_private_download_urls: Allow the download queue to fetch from loopback, link-local and private-network addresses. Disabled by default so that a download URL cannot be used to reach services that are only reachable from the server. Enable this only if you install models from a mirror on your own network.\n download_proxy: Optional HTTP proxy for model downloads. The proxy must enforce the public-address policy because proxy-side DNS cannot be checked by InvokeAI.\n unsafe_disable_picklescan: UNSAFE. Disable the picklescan security check during model installation. Recommended only for development and testing purposes. This will allow arbitrary code execution during model installation, so should never be used in production.\n allow_unknown_models: Allow installation of models that we are unable to identify. If enabled, models will be marked as `unknown` in the database, and will not have any metadata associated with them. If disabled, unknown models will be rejected during installation.\n multiuser: Enable multiuser support. When disabled, the application runs in single-user mode using a default system account with administrator privileges. When enabled, requires user authentication and authorization.\n strict_password_checking: Enforce strict password requirements. When True, passwords must contain uppercase, lowercase, and numbers. When False (default), any password is accepted but its strength (weak/moderate/strong) is reported to the user.\n image_index_enabled: Maintain a semantic embedding index of gallery images and videos, used by the image map and semantic search features.\n image_index_model: Name of the installed CLIP Vision or SigLIP model used to embed gallery images and video thumbnails. Changing the model discards embeddings computed by the previous model.\n image_index_device: Set to `cpu` to compute image embeddings on the CPU with a service-local copy of the model - avoids VRAM use and lets indexing run during generations. Any other value is ignored: embeddings otherwise run on the model cache's device, pausing while generations are in progress.\n image_index_batch_size: Number of gallery items embedded per batch by the image index worker.\n external_alibabacloud_api_key: API key for Alibaba Cloud DashScope image generation.\n external_alibabacloud_base_url: Base URL override for Alibaba Cloud DashScope image generation.\n external_atlascloud_api_key: API key for Atlas Cloud image generation.\n external_atlascloud_base_url: Base URL override for Atlas Cloud image generation.\n external_gemini_api_key: API key for Gemini image generation.\n external_openai_api_key: API key for OpenAI image generation.\n external_gemini_base_url: Base URL override for Gemini image generation.\n external_openai_base_url: Base URL override for OpenAI image generation.\n external_seedream_api_key: API key for Seedream image generation.\n external_seedream_base_url: Base URL override for Seedream image generation.\n base_url: Public base path when running behind a reverse proxy under a sub-path, e.g. `/invoke`. Set only when the proxy PRESERVES the sub-path (the backend receives `/invoke/api/...`). Leave unset when the proxy strips the sub-path or when serving at the domain root.\n forwarded_allow_ips: Comma-separated list of IPs (or `*`) allowed to set X-Forwarded-* headers. Set to the reverse proxy's IP. Only used when `base_url` is set.\n http_compression_level: Compression level for gzipped HTTP API responses. 0 disables response compression entirely, 1 is fastest, 9 (the default) is smallest. Compression runs on the event loop and blocks the whole server while it works, and level 9 costs about 5.5x the time of level 1 for 0.4 percentage points of extra compression, so lowering this makes the app noticeably more responsive on large libraries. Set to 0 when a reverse proxy already compresses responses."},"InvokeAIAppConfigWithSetFields": {"properties": {@@ -119089,6 +119089,18 @@"title": "Latent Channels","description": "Latent channels the decoder consumes."},+ "cpu_only": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ],+ "title": "Cpu Only",+ "description": "Whether this model should run on CPU only"+ },"base": {"type": "string","const": "flux",@@ -119113,6 +119125,7 @@"type","format","latent_channels",+ "cpu_only","base"],"title": "TinyAutoencoder_Checkpoint_FLUX_Config"@@ -119230,6 +119243,18 @@"title": "Latent Channels","description": "Latent channels the decoder consumes."},+ "cpu_only": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ],+ "title": "Cpu Only",+ "description": "Whether this model should run on CPU only"+ },"base": {"type": "string","const": "flux2",@@ -119254,6 +119279,7 @@"type","format","latent_channels",+ "cpu_only","base"],"title": "TinyAutoencoder_Checkpoint_Flux2_Config"@@ -119371,6 +119397,18 @@"title": "Latent Channels","description": "Latent channels the decoder consumes."},+ "cpu_only": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ],+ "title": "Cpu Only",+ "description": "Whether this model should run on CPU only"+ },"base": {"type": "string","const": "ltx-2",@@ -119395,6 +119433,7 @@"type","format","latent_channels",+ "cpu_only","base"],"title": "TinyAutoencoder_Checkpoint_LTX2_Config"@@ -119512,6 +119551,18 @@"title": "Latent Channels","description": "Latent channels the decoder consumes."},+ "cpu_only": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ],+ "title": "Cpu Only",+ "description": "Whether this model should run on CPU only"+ },"base": {"type": "string","const": "qwen-image-2-1",@@ -119536,6 +119587,7 @@"type","format","latent_channels",+ "cpu_only","base"],"title": "TinyAutoencoder_Checkpoint_QwenImage21_Config"@@ -119653,6 +119705,18 @@"title": "Latent Channels","description": "Latent channels the decoder consumes."},+ "cpu_only": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ],+ "title": "Cpu Only",+ "description": "Whether this model should run on CPU only"+ },"base": {"type": "string","const": "sd-1",@@ -119677,6 +119741,7 @@"type","format","latent_channels",+ "cpu_only","base"],"title": "TinyAutoencoder_Checkpoint_SD1_Config"@@ -119794,6 +119859,18 @@"title": "Latent Channels","description": "Latent channels the decoder consumes."},+ "cpu_only": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ],+ "title": "Cpu Only",+ "description": "Whether this model should run on CPU only"+ },"base": {"type": "string","const": "sd-3",@@ -119818,6 +119895,7 @@"type","format","latent_channels",+ "cpu_only","base"],"title": "TinyAutoencoder_Checkpoint_SD3_Config"@@ -119935,6 +120013,18 @@"title": "Latent Channels","description": "Latent channels the decoder consumes."},+ "cpu_only": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ],+ "title": "Cpu Only",+ "description": "Whether this model should run on CPU only"+ },"base": {"type": "string","const": "sdxl",@@ -119959,6 +120049,7 @@"type","format","latent_channels",+ "cpu_only","base"],"title": "TinyAutoencoder_Checkpoint_SDXL_Config"@@ -120076,6 +120167,18 @@"title": "Latent Channels","description": "Latent channels the decoder consumes."},+ "cpu_only": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ],+ "title": "Cpu Only",+ "description": "Whether this model should run on CPU only"+ },"base": {"type": "string","const": "wan",@@ -120100,6 +120203,7 @@"type","format","latent_channels",+ "cpu_only","base"],"title": "TinyAutoencoder_Checkpoint_Wan_Config",diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.tsindex db11f9f449..00ca4d21fc 100644--- a/invokeai/frontend/api/schema.ts+++ b/invokeai/frontend/api/schema.ts@@ -25084,7 +25084,7 @@ export type components = {* noise_dtype: The dtype seeded noise is drawn in for SD1.5/SDXL, SD3, FLUX.1, FLUX.2, CogView4 and the Z-Image seed variance enhancer. `float32` draws the same noise on every platform. `float16` is the half-precision draw of earlier versions: on macOS it keeps the images your seeds gave before this update; on Windows and Linux both values give (nearly) the same images, and images made before the update cannot be reproduced there.<br>Valid values: `float32`, `float16`* wan_memory_optimization: Enable experimental Wan memory optimizations at the cost of slower generation.* 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.- * tiny_autoencoder_previews: Render denoising previews with an installed Tiny AutoEncoder instead of the linear latent projection. Install the matching Tiny AutoEncoder starter model; families without one keep linear previews. A preview costs a few tens of ms and up to about 1.1 GB of transient VRAM on an RTX 4090 (image decoders 0.15-0.65 GB, Wan video windows up to 1.1 GB); not recommended on CPU-only installs, where one takes about 2 s.+ * tiny_autoencoder_previews: Render denoising previews with an installed Tiny AutoEncoder instead of the linear latent projection. Install the matching Tiny AutoEncoder starter model; families without one keep linear previews. A preview costs a few tens of ms and up to about 1.1 GB of transient VRAM on an RTX 4090 (image decoders 0.15-0.65 GB, Wan video windows up to 1.1 GB); a TAE that does not fit in VRAM next to the running model can instead run on the CPU (its `Decode previews on CPU` setting in the model manager): previews are capped at 512 px there and a frame takes about 0.3-0.4 s (TAESDXL, TAEF2), 0.8-1.1 s (TAEW2.1, one frame) or 1.0-1.9 s (Wan two-frame window) on a Ryzen 9 7900 with 8 threads in float32, so previews update less often.* 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`* attention_backend: Attention kernel for the attention inside diffusion models. `auto` uses PyTorch's exact SDPA kernels ranked flash, cuDNN, memory-efficient, math, taking the first one the GPU and build support for each call; it never selects a quantized one. `sage` uses SageAttention 2 for the models listed in the SageAttention docs: faster, most at high resolutions and for video, but quantized, so images differ slightly from `auto` at the same seed. SageAttention is installed separately and needs an NVIDIA GPU with compute capability 8.0 or newer; masked attention, text encoders and VAEs keep PyTorch SDPA. `cudnn`, `flash`, `efficient` and `math` rank that PyTorch kernel first for all attention on CUDA and ROCm GPUs, ahead of the `auto` order. That is never exclusive: a call the kernel cannot serve runs on the next kernel, and the log reports that once per node type and reason (not for the PiD decoder, whose attention is ranked the same but not reported). `math` materializes the full attention score matrix, so it is slow and needs much more memory, which the working-memory estimates of most model families do not reserve, so generations can run out of memory; it is meant for debugging. Images can differ slightly between kernels.<br>Valid values: `auto`, `sage`, `cudnn`, `flash`, `efficient`, `math`@@ -25570,7 +25570,7 @@ export type components = {pid_memory_optimization?: boolean;/*** Tiny Autoencoder Previews- * @description Render denoising previews with an installed Tiny AutoEncoder instead of the linear latent projection. Install the matching Tiny AutoEncoder starter model; families without one keep linear previews. A preview costs a few tens of ms and up to about 1.1 GB of transient VRAM on an RTX 4090 (image decoders 0.15-0.65 GB, Wan video windows up to 1.1 GB); not recommended on CPU-only installs, where one takes about 2 s.+ * @description Render denoising previews with an installed Tiny AutoEncoder instead of the linear latent projection. Install the matching Tiny AutoEncoder starter model; families without one keep linear previews. A preview costs a few tens of ms and up to about 1.1 GB of transient VRAM on an RTX 4090 (image decoders 0.15-0.65 GB, Wan video windows up to 1.1 GB); a TAE that does not fit in VRAM next to the running model can instead run on the CPU (its `Decode previews on CPU` setting in the model manager): previews are capped at 512 px there and a frame takes about 0.3-0.4 s (TAESDXL, TAEF2), 0.8-1.1 s (TAEW2.1, one frame) or 1.0-1.9 s (Wan two-frame window) on a Ryzen 9 7900 with 8 threads in float32, so previews update less often.* @default false*/tiny_autoencoder_previews?: boolean;@@ -52776,6 +52776,11 @@ export type components = {* @description Latent channels the decoder consumes.*/latent_channels: number;+ /**+ * Cpu Only+ * @description Whether this model should run on CPU only+ */+ cpu_only: boolean | null;/*** Base* @default flux@@ -52859,6 +52864,11 @@ export type components = {* @description Latent channels the decoder consumes.*/latent_channels: number;+ /**+ * Cpu Only+ * @description Whether this model should run on CPU only+ */+ cpu_only: boolean | null;/*** Base* @default flux2@@ -52942,6 +52952,11 @@ export type components = {* @description Latent channels the decoder consumes.*/latent_channels: number;+ /**+ * Cpu Only+ * @description Whether this model should run on CPU only+ */+ cpu_only: boolean | null;/*** Base* @default ltx-2@@ -53025,6 +53040,11 @@ export type components = {* @description Latent channels the decoder consumes.*/latent_channels: number;+ /**+ * Cpu Only+ * @description Whether this model should run on CPU only+ */+ cpu_only: boolean | null;/*** Base* @default qwen-image-2-1@@ -53108,6 +53128,11 @@ export type components = {* @description Latent channels the decoder consumes.*/latent_channels: number;+ /**+ * Cpu Only+ * @description Whether this model should run on CPU only+ */+ cpu_only: boolean | null;/*** Base* @default sd-1@@ -53191,6 +53216,11 @@ export type components = {* @description Latent channels the decoder consumes.*/latent_channels: number;+ /**+ * Cpu Only+ * @description Whether this model should run on CPU only+ */+ cpu_only: boolean | null;/*** Base* @default sd-3@@ -53274,6 +53304,11 @@ export type components = {* @description Latent channels the decoder consumes.*/latent_channels: number;+ /**+ * Cpu Only+ * @description Whether this model should run on CPU only+ */+ cpu_only: boolean | null;/*** Base* @default sdxl@@ -53360,6 +53395,11 @@ export type components = {* @description Latent channels the decoder consumes.*/latent_channels: number;+ /**+ * Cpu Only+ * @description Whether this model should run on CPU only+ */+ cpu_only: boolean | null;/*** Base* @default wandiff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 92ddd33cb1..09093d0023 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -1784,6 +1784,8 @@"retryInstall": "Retry install","runOnCpu": "Run on CPU","runOnCpuHelp": "Run this encoder on CPU only to reduce VRAM usage. This may be slower.",+ "runTaeOnCpu": "Decode previews on CPU",+ "runTaeOnCpuHelp": "When Tiny AutoEncoder previews are enabled, decode them on the CPU so they also work when the generation model fills the VRAM. Each preview takes longer on the CPU, so previews update less often.","runVaeOnCpu": "Run on CPU","runVaeOnCpuHelp": "Run this VAE on CPU only to reduce VRAM usage. This may be slower.","saveDefaults": "Save Defaults",diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/CpuOnlySetting.browser.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/CpuOnlySetting.browser.test.tsxindex 227797a3aa..8d3d13f92f 100644--- a/invokeai/frontend/webv2/src/features/models/ui/detail/CpuOnlySetting.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/CpuOnlySetting.browser.test.tsx@@ -37,6 +37,8 @@ const vae = {type: 'vae',} as ModelConfig;+const taesdxl = { cpu_only: null, key: 'taesdxl', name: 'TAESDXL', type: 'tiny_autoencoder' } as const;+const deferred = <T,>() => {let reject!: (reason?: unknown) => void;let resolve!: (value: T) => void;@@ -160,6 +162,22 @@ describe('CpuOnlySetting', () => {expect(help?.textContent).toBe('models.runVaeOnCpuHelp');});+ it('labels the switch of a tiny autoencoder for previews', async () => {+ await act(() => {+ root.render(+ <ChakraProvider value={system}>+ <CpuOnlySetting model={taesdxl} onError={onError} onSaved={onSaved} />+ </ChakraProvider>+ );+ });++ const input = host.querySelector<HTMLInputElement>('input[type="checkbox"]')!;+ expect(input.labels?.[0]?.textContent).toBe('models.runTaeOnCpu');+ expect(document.getElementById(input.getAttribute('aria-describedby') ?? '')?.textContent).toBe(+ 'models.runTaeOnCpuHelp'+ );+ });+it('does not commit a late response from account A into account B', async () => {const request = deferred<ModelConfig>();api.updateModel.mockReturnValue(request.promise);diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/CpuOnlySetting.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/CpuOnlySetting.tsxindex dde8166d0a..7bc606f2a8 100644--- a/invokeai/frontend/webv2/src/features/models/ui/detail/CpuOnlySetting.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/CpuOnlySetting.tsx@@ -30,6 +30,7 @@ export const CpuOnlySetting = ({const { t } = useTranslation();const { isBusy: isPending, run } = useScopedAction();const isVae = model.type === 'vae';+ const isTae = model.type === 'tiny_autoencoder';const helpId = useId();const handleCheckedChange = useCallback(@@ -73,11 +74,11 @@ export const CpuOnlySetting = ({<Switch.Thumb /></Switch.Control><Switch.Label fontSize="md" fontWeight="600">- {isVae ? t('models.runVaeOnCpu') : t('models.runOnCpu')}+ {isVae ? t('models.runVaeOnCpu') : isTae ? t('models.runTaeOnCpu') : t('models.runOnCpu')}</Switch.Label></Switch.Root><Text color="fg.subtle" fontSize="xs" id={helpId}>- {isVae ? t('models.runVaeOnCpuHelp') : t('models.runOnCpuHelp')}+ {isVae ? t('models.runVaeOnCpuHelp') : isTae ? t('models.runTaeOnCpuHelp') : t('models.runOnCpuHelp')}</Text></Stack>);diff --git a/invokeai/frontend/webv2/src/workbench/palette/docsSearchIndex.json b/invokeai/frontend/webv2/src/workbench/palette/docsSearchIndex.jsonindex 27ccc16bc4..aad5c520fd 100644--- a/invokeai/frontend/webv2/src/workbench/palette/docsSearchIndex.json+++ b/invokeai/frontend/webv2/src/workbench/palette/docsSearchIndex.json@@ -21,7 +21,7 @@{"s":"users-guide/image-generation/advanced-topics/diffusion","t":"Diffusion","c":1,"h":[["image-space-vs-latent-space","Image Space vs. Latent Space"],["core-components","Core Components"],["the-generation-process","The Generation Process"],["summary","Summary"]]},{"s":"users-guide/image-generation/advanced-topics/hidiffusion","t":"HiDiffusion","c":1,"h":[["where-to-find-the-switches","Where to find the switches"],["what-the-switches-do","What the switches do"],["manual-ratio-constraint","Manual ratio constraint"],["tips","Tips"]]},{"s":"users-guide/image-generation/advanced-topics/pid-decode","t":"PiD Super-Resolution Decode","c":1,"h":[["supported-models","Supported models"],["what-you-need-to-install","What you need to install"],["enabling-pid","Enabling PiD"],["running-pid-on-an-existing-image","Running PiD on an existing image"],["tips--limitations","Tips & limitations"]]},-{"s":"users-guide/image-generation/advanced-topics/tiny-autoencoder-previews","t":"Tiny AutoEncoder Previews","c":1,"h":[["enabling-tae-previews","Enabling TAE previews"],["cost-and-fallback","Cost and fallback"]]},+{"s":"users-guide/image-generation/advanced-topics/tiny-autoencoder-previews","t":"Tiny AutoEncoder Previews","c":1,"h":[["enabling-tae-previews","Enabling TAE previews"],["cost-and-fallback","Cost and fallback"],["running-the-decoder-on-the-cpu","Running the decoder on the CPU"]]},{"s":"users-guide/image-generation/generate-panel","t":"Generate Panel Reference","d":"Every section of the Generate panel in detail — size, render settings, negative prompts, advanced options, resetting to defaults, concepts, reference images and the prompt tools.","c":1,"h":[["setting-the-image-size","Setting the image size"],["render-settings","Render settings"],["steps","Steps"],["cfg-and-guidance","CFG and Guidance"],["scheduler","Scheduler"],["seed","Seed"],["model-specific-options","Model-specific options"],["negative-prompt","Negative prompt"],["refiner","Refiner"],["advanced-settings","Advanced settings"],["resetting-to-defaults","Resetting to defaults"],["adding-concepts","Adding concepts"],["adding-reference-images","Adding reference images"],["prompt-tools","Prompt tools"],["prompt-enhancement","Prompt enhancement"],["image-to-prompt","Image to prompt"],["prompt-history","Prompt history"],["more-prompting-features","More prompting features"]]},{"s":"users-guide/image-generation/image-generation","t":"Concepts and Terms","d":"A short glossary of the ideas and terms you meet when generating images — models, prompts, steps, CFG, schedulers, seeds, latents, LoRAs, ControlNets and more — with links to the guides that cover them.","c":1,"h":[["how-an-image-is-made","How an image is made"],["glossary","Glossary"],["learn-more","Learn more"]]},{"s":"users-guide/image-generation/intermediates","t":"Intermediates","d":"Reclaim disk space by deleting the temporary images and videos generation leaves behind, per project and per account.","c":1,"h":[["the-intermediates-section","The Intermediates section"],["clean-up","Clean up"],["what-a-normal-delete-always-keeps","What a normal delete always keeps"],["permissions","Permissions"],["limits-and-edge-cases","Limits and edge cases"]]},diff --git a/tests/app/services/model_manager/test_model_record_changes.py b/tests/app/services/model_manager/test_model_record_changes.pyindex abc1db7ce8..c3a4996f3e 100644--- a/tests/app/services/model_manager/test_model_record_changes.py+++ b/tests/app/services/model_manager/test_model_record_changes.py@@ -609,6 +609,24 @@ def test_reidentify_keeps_the_base_of_a_tiny_autoencoder_starter(harness: _Harneassert harness.manager.reidentify_model(KEY).base is starter.base+def test_a_tiny_autoencoders_cpu_only_switch_is_stored_and_drops_its_cached_instances(harness: _Harness) -> None:+ """Toggling "Decode previews on CPU" must reach the next preview: the cached decoder was built for the old device and dtype."""+ path = harness.models_path / KEY / "taesdxl.safetensors"+ _write_tae(path, TAESD, combined=False)+ harness.store.add_model(_identify(path, {"key": KEY}))+ harness.cache_model()++ updated = harness.manager.update_model_record(KEY, ModelRecordChanges(cpu_only=True))++ assert updated.cpu_only is True and harness.store.get_model(KEY).cpu_only is True+ assert not harness.is_cached()++ harness.cache_model()+ harness.manager.update_model_record(KEY, ModelRecordChanges(cpu_only=None))+ assert harness.store.get_model(KEY).cpu_only is None+ assert not harness.is_cached()++def test_reidentify_of_files_no_config_accepts_raises_and_keeps_the_record(harness: _Harness) -> None:keys = dict(clip_g_comfy_keys.state_dict_keys)del keys["text_projection.weight"]diff --git a/tests/app/util/test_tiny_autoencoder_previews.py b/tests/app/util/test_tiny_autoencoder_previews.pyindex a4f71812f8..71efd622f8 100644--- a/tests/app/util/test_tiny_autoencoder_previews.py+++ b/tests/app/util/test_tiny_autoencoder_previews.py@@ -7,6 +7,7 @@ from types import SimpleNamespaceimport numpy as npimport pytestimport torch+from PIL import Imagefrom invokeai.app.services.progress_previews.progress_previews_default import MemoryProgressPreviewsfrom invokeai.app.services.session_processor.session_processor_common import ProgressImage@@ -395,7 +396,8 @@ def test_tae_that_would_not_fit_in_vram_is_never_locked(caplog: pytest.LogCapturassert all(_is_linear(frame, sample) for frame in frames)assert (load.loads, loaded.locks_taken) == (1, 0)- assert len(_messages(caplog, logging.INFO)) == 1+ (message,) = _messages(caplog, logging.INFO)+ assert "Decode previews on CPU" in messagedef test_tae_whose_decode_would_not_fit_next_to_it_is_never_locked(caplog: pytest.LogCaptureFixture) -> None:@@ -483,14 +485,14 @@ def test_tae_frames_are_spaced_by_their_render_cost_and_the_final_frame_still_reclock.now += seconds_step(util, _sample(step), step=step)- step_after(0.0, 0) # warm-up frame: lookup, load and lock are not a frame cost- step_after(0.2, 1) # first measured frame; until now the store's 0.1 s interval applied- step_after(0.2, 2) # 0.25 s after the last frame, inside k x 0.05 s = 1 s: not rendered- step_after(0.8, 3) # 1.05 s after it: rendered+ step_after(0.0, 0) # first frame: a CPU decode is counted, without the lookup, load and lock+ step_after(0.2, 1) # 0.2 s after the last frame, inside k x 0.05 s = 1 s: not rendered+ step_after(0.85, 2) # 1.05 s after it: rendered+ step_after(0.3, 3) # not renderedstep_after(0.01, 10) # the final frame passes any interval- assert [call["percentage"] for call in services.events.emitted] == [0.0, 0.1, 0.3, 1.0]- assert len(decodes) == 4+ assert [call["percentage"] for call in services.events.emitted] == [0.0, 0.2, 1.0]+ assert len(decodes) == 3def test_linear_previews_keep_the_stores_interval(clock: _Clock) -> None:@@ -516,6 +518,89 @@ def test_a_cpu_tae_is_used_although_its_lock_leaves_nothing_resident() -> None:assert image.size == (192, 128)+def test_a_cpu_tae_renders_where_the_same_tae_on_the_gpu_is_refused_for_vram() -> None:+ """No VRAM is free next to the running model. A TAE with "Decode previews on CPU" gets the cache's CPU execution device, so+ it needs none, and its decode is reserved at the 512-pixel CPU cap, not the decoder's own."""+ sample = _sample(height=100, width=100) # an 800-pixel image+ gpu = _LoadedModel(_decoder(), device="cuda") # only read by the residency decision+ gpu_previews = _previews(_services(_Store([_tae_config()]), _Load(gpu, vram_available=0)))+ cpu = _LoadedModel(_decoder(), device="cpu")+ cpu_previews = _previews(_services(_Store([_tae_config()]), _Load(cpu, vram_available=0)))++ assert _is_linear(gpu_previews.render(BaseModelType.StableDiffusion1, sample), sample)+ image, size = cpu_previews.render(BaseModelType.StableDiffusion1, sample)++ assert (gpu.locks_taken, cpu.locks_taken) == (0, 1)+ assert image.size == (512, 512) and size == (800, 800)+ assert cpu.working_mem_requests == [(3 + 2) * 64 * (512 * 512) * 4 + 5 * 2**20]+++def test_a_cpu_tae_is_paced_from_its_first_frame_without_the_step_still_queued_on_the_latents_device(+ clock: _Clock, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Latents on another device (`meta` stands in for the GPU) with a 5 s denoise step still queued: the CPU decode's+ copy of them waits for it, and that wait is not the preview's cost. The first frame, which also looks the TAE up,+ already sets the interval, so the frame after it is paced."""+ decode_cost, queued_step = 0.3, 5.0+ queued = [0.0]++ def synchronize(device: torch.device) -> None:+ if device.type == "meta":+ clock.now += queued[0]+ queued[0] = 0.0++ def decode(_decoder, _sample, device=None):+ clock.now += queued[0] + decode_cost # the copy to the CPU waits for whatever is still queued+ queued[0] = 0.0+ return Image.new("RGB", (8, 8))++ monkeypatch.setattr(tiny_autoencoder_previews.TorchDevice, "synchronize", synchronize)+ monkeypatch.setattr(tiny_autoencoder_previews, "decode_preview", decode)+ previews = _previews(_services(_Store([_tae_config()]), _load()))+ sample = torch.empty(1, 4, 16, 24, device="meta")+ intervals = []+ for _frame in range(3):+ queued[0] = queued_step+ with previews.measure_frame():+ previews.render(BaseModelType.StableDiffusion1, sample)+ intervals.append(previews.min_frame_interval_s)++ expected = tiny_autoencoder_previews.RENDER_COST_INTERVAL_FACTOR * decode_cost+ assert intervals == [pytest.approx(expected)] * 3+++def test_a_gpu_tae_is_paced_only_from_its_second_frame(clock: _Clock, monkeypatch: pytest.MonkeyPatch) -> None:+ """The first GPU frame also loads the TAE and makes the first cuDNN call, so its cost is not representative."""+ frame_costs = iter([1.0, 0.05, 0.05])++ def decode(_decoder, _sample, device=None):+ clock.now += next(frame_costs)+ return Image.new("RGB", (8, 8))++ monkeypatch.setattr(tiny_autoencoder_previews.TorchDevice, "synchronize", lambda _device: None)+ monkeypatch.setattr(tiny_autoencoder_previews, "decode_preview", decode)+ loaded = _LoadedModel(_decoder(), device="cuda") # only read by the residency decision; nothing runs on it+ previews = _previews(_services(_Store([_tae_config()]), _Load(loaded, vram_available=2**40)))+ intervals = []+ for _frame in range(2):+ with previews.measure_frame():+ previews.render(BaseModelType.StableDiffusion1, _sample())+ intervals.append(previews.min_frame_interval_s)++ assert intervals == [None, pytest.approx(tiny_autoencoder_previews.RENDER_COST_INTERVAL_FACTOR * 0.05)]+++def test_a_gpu_tae_above_its_cap_is_reserved_at_its_own_cap_not_the_cpu_cap(monkeypatch: pytest.MonkeyPatch) -> None:+ """An 800-pixel preview fits TAESD's own 1024-pixel cap; only a CPU decode is limited to 512."""+ monkeypatch.setattr(tiny_autoencoder_previews, "decode_preview", lambda *_a, **_k: Image.new("RGB", (8, 8)))+ loaded = _LoadedModel(_decoder(), device="cuda") # only read by the residency decision; nothing runs on it+ previews = _previews(_services(_Store([_tae_config()]), _Load(loaded, vram_available=2**40)))++ previews.render(BaseModelType.StableDiffusion1, _sample(height=100, width=100))++ assert loaded.working_mem_requests == [(3 + 2) * 64 * (800 * 800) * 4 + 5 * 2**20]++def _slow_linear_frames(monkeypatch: pytest.MonkeyPatch, clock: _Clock, seconds: float) -> None:"""A linear frame whose `.cpu()` waits out a long denoise step still queued on the GPU."""render = tiny_autoencoder_previews.render_linear_preview@@ -560,7 +645,7 @@ def test_frames_after_the_tae_fell_back_to_linear_return_to_the_stores_interval(services = _services(_Store([_tae_config()]), _load(decoder), previews=MemoryProgressPreviews(clock=clock))util, _data = _invocation(services)- for step, after in enumerate([0.0, 0.2, 1.1, 0.15, 0.15]):+ for step, after in enumerate([0.0, 1.1, 1.1, 0.15, 0.15]):clock.now += after_step(util, _sample(step), step=step)@@ -568,8 +653,9 @@ def test_frames_after_the_tae_fell_back_to_linear_return_to_the_stores_interval(# it are 0.15 s apart again, with each linear frame's 1 s of waiting not counted as a cost.assert [call["percentage"] for call in services.events.emitted] == [0.0, 0.1, 0.2, 0.3, 0.4]assert len(decodes) == 3- # Only the frames after a TAE frame wait for the TAE's device; once it fell back, there is none to wait for.- assert len(syncs) == 2+ # The first frame waits for the latents' device, the frames after a TAE frame for the TAE's; once it fell back,+ # there is none to wait for.+ assert len(syncs) == 3def _wan_window(frames: int = 2) -> torch.Tensor:diff --git a/tests/backend/model_manager/load/test_tiny_autoencoder_loader.py b/tests/backend/model_manager/load/test_tiny_autoencoder_loader.pyindex 16c0e638b5..338b4b889f 100644--- a/tests/backend/model_manager/load/test_tiny_autoencoder_loader.py+++ b/tests/backend/model_manager/load/test_tiny_autoencoder_loader.py@@ -27,11 +27,12 @@ def _load(path: Path,config_class: type[TinyAutoencoder_Checkpoint_Config_Base] = TinyAutoencoder_Checkpoint_SD1_Config,dtype: torch.dtype = torch.float32,+ cpu_only: bool | None = None,) -> TinyAutoencoderDecoder:loader = object.__new__(TinyAutoencoderLoader)loader._torch_dtype = dtypeloader._logger = SimpleNamespace(info=lambda *_a, **_k: None, warning=lambda *_a, **_k: None)- config = config_class.model_construct(path=str(path), name=path.name)+ config = config_class.model_construct(path=str(path), name=path.name, cpu_only=cpu_only)return loader._load_model(config)@@ -106,6 +107,33 @@ def test_the_decoder_takes_the_loaders_dtype(tmp_path: Path) -> None:assert all(p.dtype == torch.float16 for p in decoder.parameters())+ ("cpu_only", "expected"), [(True, torch.float32), (False, torch.float16), (None, torch.float16)]+)+def test_a_cpu_only_decoder_is_float32_whatever_the_loader_dtype(+ tmp_path: Path, cpu_only: bool | None, expected: torch.dtype+) -> None:+ save_file(native_weights(TAESD), tmp_path / "taesd_decoder.safetensors")++ decoder = _load(tmp_path / "taesd_decoder.safetensors", dtype=torch.float16, cpu_only=cpu_only)++ assert all(p.dtype == expected for p in decoder.parameters())+++def test_a_cpu_only_decoder_executes_on_the_cpu_and_a_default_one_on_the_cache_device(tmp_path: Path) -> None:+ path = tmp_path / "taesd_decoder.safetensors"+ save_file(native_weights(TAESD), path)+ config = ModelConfigFactory.from_model_on_disk(+ path, {"hash": "blake3:fake", "file_size": 1, "source": str(path), "source_type": "path"}+ ).config+ assert isinstance(config, TinyAutoencoder_Checkpoint_Config_Base)+ loader = object.__new__(TinyAutoencoderLoader)++ assert config.cpu_only is None+ assert loader._get_execution_device(config) is None+ assert loader._get_execution_device(config.model_copy(update={"cpu_only": True})) == torch.device("cpu")++@pytest.mark.parametrize("change", ["missing", "extra"])def test_a_checkpoint_that_is_not_exactly_the_decoder_is_refused(tmp_path: Path, change: str) -> None:sd = native_weights(TAESD)diff --git a/tests/backend/tiny_autoencoder/test_preview.py b/tests/backend/tiny_autoencoder/test_preview.pyindex 6165782e0a..3df309b62b 100644--- a/tests/backend/tiny_autoencoder/test_preview.py+++ b/tests/backend/tiny_autoencoder/test_preview.py@@ -37,6 +37,7 @@ def taesd() -> TaesdDecoder:MIB = 2**20+CPU = torch.device("cpu")def _latent(*shape: int, seed: int = 1) -> torch.Tensor:@@ -139,10 +140,22 @@ def test_a_decode_reserves_its_full_resolution_activations_at_the_capped_size(ta# Three live 64-channel activations and two of convolution workspace per output pixel, at the element size, and# the fixed 5 MiB allowance.- assert decode_working_memory_bytes(taesd, _latent(4, 3, 5)) == (3 + 2) * 64 * (24 * 40) * 4 + 5 * MIB- assert decode_working_memory_bytes(half, _latent(4, 3, 5)) == (3 + 2) * 64 * (24 * 40) * 2 + 5 * MIB+ assert decode_working_memory_bytes(taesd, _latent(4, 3, 5), CPU) == (3 + 2) * 64 * (24 * 40) * 4 + 5 * MIB+ assert decode_working_memory_bytes(half, _latent(4, 3, 5), CPU) == (3 + 2) * 64 * (24 * 40) * 2 + 5 * MIB# 12 x 18 latents exceed the cap and are decoded at 4 x 6.- assert decode_working_memory_bytes(taesd, _latent(1, 4, 12, 18)) == (3 + 2) * 64 * (32 * 48) * 4 + 5 * MIB+ assert decode_working_memory_bytes(taesd, _latent(1, 4, 12, 18), CPU) == (3 + 2) * 64 * (32 * 48) * 4 + 5 * MIB+++def test_a_cpu_decode_is_capped_at_512_pixels_where_a_gpu_decode_is_not(taesd: TaesdDecoder) -> None:+ """A 544 x 512 image is within TAESD's own 1024 cap, so only the device decides. Decoding on a CPU is slow enough+ (1.7 s against 0.4 s at 512 pixels on a Ryzen 9 7900) to be worth the lower resolution."""+ latent = _latent(4, 68, 64)+ per_pixel = (3 + 2) * 64 * 4++ assert decode_preview(taesd, latent).size == (480, 512) # the decoder's own device is the CPU+ # The reservation follows the same size, so the VRAM a lock keeps is that of the image a GPU renders.+ assert decode_working_memory_bytes(taesd, latent, torch.device("cuda")) == per_pixel * (544 * 512) + 5 * MIB+ assert decode_working_memory_bytes(taesd, latent, torch.device("cpu")) == per_pixel * (512 * 480) + 5 * MIB@pytest.fixture(scope="module")@@ -298,7 +311,8 @@ class _Stop(Exception):def _first_conv_input(decoder: TinyAutoencoderDecoder, latent: torch.Tensor) -> tuple[int, ...]:- """The latent shape the decoder's first convolution receives, without paying for the decode."""+ """The latent shape the decoder's first convolution receives on a device that is not a CPU, without paying for the+ decode: the sample is moved to `meta`, which the hook stops at."""seen: list[tuple[int, ...]] = []def record(_module: torch.nn.Module, args: tuple[torch.Tensor, ...]) -> None:@@ -309,7 +323,7 @@ def _first_conv_input(decoder: TinyAutoencoderDecoder, latent: torch.Tensor) ->handle = first_conv.register_forward_pre_hook(record)try:with pytest.raises(_Stop):- decode_preview(decoder, latent)+ decode_preview(decoder, latent, device=torch.device("meta"))finally:handle.remove()return seen[0]@@ -405,12 +419,12 @@ def test_a_video_decode_reserves_its_live_activations_and_workspace_per_output_f# 2.25 live 64-channel float32 activations and 2 of workspace per output frame of the full-resolution stage, and# the fixed 5 MiB allowance.per_output_frame = (2.25 + 2) * 64 * stage_pixels * 4- assert decode_working_memory_bytes(decoder, _latent(*latent)) == per_output_frame * frames_per_latent + 5 * MIB+ assert decode_working_memory_bytes(decoder, _latent(*latent), CPU) == per_output_frame * frames_per_latent + 5 * MIBwindow = _latent(latent[0], latent[1], 2, *latent[2:])- assert decode_working_memory_bytes(decoder, window) == per_output_frame * frames_per_latent * 2 + 5 * MIB+ assert decode_working_memory_bytes(decoder, window, CPU) == per_output_frame * frames_per_latent * 2 + 5 * MIBdef test_a_video_decode_is_priced_at_its_own_cap(taew2_1: TinyAutoencoderDecoder) -> None:- """taew2_1's 512-pixel cap decodes a 128 x 128 latent (1024 pixels) at 64 x 64."""+ """taew2_1's 512-pixel cap decodes a 128 x 128 latent (1024 pixels) at 64 x 64, on a GPU as on a CPU."""expected = (2.25 + 2) * 64 * 512 * 512 * 4 * 4 + 5 * MIB- assert decode_working_memory_bytes(taew2_1, _latent(1, 16, 128, 128)) == expected+ assert decode_working_memory_bytes(taew2_1, _latent(1, 16, 128, 128), torch.device("cuda")) == expected