Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix: close 34 findings from the PR 171-194 review (#241)
Alexander Eichhornb8fa42ff0ec2
diff --git a/docs/src/content/docs/configuration/invokeai-yaml.mdx b/docs/src/content/docs/configuration/invokeai-yaml.mdxindex 0984a019cf..289052025a 100644--- a/docs/src/content/docs/configuration/invokeai-yaml.mdx+++ b/docs/src/content/docs/configuration/invokeai-yaml.mdx@@ -231,12 +231,18 @@ db_synchronous: full # default value| Value | Behavior || -------- | ----------------------------------------------------------------------------------------------------------- |-| `full` | Every commit is flushed to disk before it is acknowledged. SQLite's own default, and InvokeAI's. |+| `full` | Every commit is flushed to disk before it is acknowledged. What InvokeAI has always used, and SQLite's default on standard builds. || `normal` | Commits are acknowledged without waiting for the flush. Much faster; a power loss may lose the last few. |The setting can also be given as the `INVOKEAI_DB_SYNCHRONOUS` environment variable.-**`normal` cannot corrupt the database.** InvokeAI runs SQLite in WAL mode, and WAL guarantees a consistent database either way. What `normal` gives up is the *most recent transactions* if the machine loses power or the OS crashes mid-write — a just-written image record or a queue status. The image file itself survives on disk, but nothing rebuilds the row, and the gallery is driven by the database: the image is simply gone from it. The gallery orphan scan does not heal this — it *archives* record-less files out of `outputs/` so you can delete them or re-import them, which takes the separate `invokeai/frontend/install/import_images.py` script.+**`normal` cannot corrupt the database, as long as WAL is in effect.** InvokeAI runs SQLite in WAL mode, and WAL guarantees a consistent database either way. What `normal` gives up is the *most recent transactions* if the machine loses power or the OS crashes mid-write — a just-written image record or a queue status. The image file itself survives on disk, but nothing rebuilds the row, and the gallery is driven by the database: the image is simply gone from it. The gallery orphan scan does not heal this — it *archives* record-less files out of `outputs/` so you can delete them or re-import them, which takes the separate `invokeai/frontend/install/import_images.py` script.++Running the database on a network share is not a supported configuration -- SQLite's locking is unreliable over NFS and SMB, and this is worth avoiding for reasons well beyond durability. Keep `db_dir` on local storage.++The safeguard exists anyway, because WAL needs shared memory and a few setups cannot provide it: a database on a network share, some container volume drivers, and SQLite builds compiled without WAL all leave a rollback journal in place instead — and on a rollback journal, `normal` *can* corrupt the database on power loss. InvokeAI reads back the journal mode it actually got, so in that case it ignores `normal`, uses `full`, and logs a warning naming the mode. An in-memory database (`use_memory_db`) has no durability to trade and is unaffected.++`db_synchronous` applies to the application's own database connection. The standalone scripts that open the database directly — `scripts/gallery_maintenance.py` and `invokeai/frontend/install/import_images.py` — leave SQLite's own default in place, so the measurements below describe the running app, not those scripts.Measured on a copy of a real library, 300 single-row inserts each committed on its own:@@ -247,7 +253,7 @@ Measured on a copy of a real library, 300 single-row inserts each committed on iThat is 12x shorter at the median. It matters more than the raw numbers suggest, because all database work is serialised through a single lock: a shorter write is also a shorter time during which every read is blocked.-The default stays at `full` so that upgrading never silently changes anyone's durability. If you generate in large batches on a machine with reliable power, `normal` is the cheaper setting.+The default stays at `full`, which is what InvokeAI has always run with, so upgrading does not weaken anyone's durability. It is now applied explicitly, which does tighten it on the uncommon SQLite build compiled with `SQLITE_DEFAULT_WAL_SYNCHRONOUS=1`, where WAL connections previously started at `normal`. If you generate in large batches on a machine with reliable power, `normal` is the cheaper setting.#### Loggingdiff --git a/docs/src/generated/settings.json b/docs/src/generated/settings.jsonindex f4267a71e6..96b70d9061 100644--- a/docs/src/generated/settings.json+++ b/docs/src/generated/settings.json@@ -205,7 +205,7 @@{"category": "PATHS","default": "full",- "description": "SQLite durability setting. `full` (the default) 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, because WAL guarantees consistency either way. What it 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.",+ "description": "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.","env_var": "INVOKEAI_DB_SYNCHRONOUS","literal_values": ["full",@@ -717,7 +717,7 @@{"category": "GENERATION","default": false,- "description": "Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty).",+ "description": "Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty). A tiled decode is not pixel-identical to a single-pass one: a VAE decoder normalises and attends over the whole image, so the difference is spread across it rather than confined to the tile seams. As of this release the setting also applies to FLUX.1, which previously ignored it.","env_var": "INVOKEAI_FORCE_TILED_DECODE","literal_values": [],"name": "force_tiled_decode",diff --git a/invokeai/app/invocations/anima_denoise.py b/invokeai/app/invocations/anima_denoise.pyindex 159be88311..aa975d78a6 100644--- a/invokeai/app/invocations/anima_denoise.py+++ b/invokeai/app/invocations/anima_denoise.py@@ -23,7 +23,7 @@ from typing import Callable, Iterator, Optionalimport torchimport torchvision.transforms as tv_transforms-from torch.nn.attention import SDPBackend, sdpa_kernel+from torch.nn.attention import SDPBackendfrom torchvision.transforms.functional import resize as tv_resizefrom torchvision.transforms.functional import to_tensorfrom tqdm import tqdm@@ -68,6 +68,7 @@ from invokeai.backend.rectified_flow.rectified_flow_inpaint_extension import (from invokeai.backend.stable_diffusion.diffusers_pipeline import PipelineIntermediateStatefrom invokeai.backend.stable_diffusion.diffusion.conditioning_data import AnimaConditioningInfo, Rangefrom invokeai.backend.util.devices import TorchDevice+from invokeai.backend.util.sdpa_scope import sdpa_policy# Anima uses 8x spatial compression (VAE downsamples by 2^3)ANIMA_LATENT_SCALE_FACTOR = 8@@ -676,7 +677,7 @@ class AnimaDenoiseInvocation(BaseInvocation):# CUDA — elsewhere torch's default backend is already fast.if device.type == "cuda" and sys.platform == "win32":exit_stack.enter_context(- sdpa_kernel(+ sdpa_policy([SDPBackend.CUDNN_ATTENTION,SDPBackend.FLASH_ATTENTION,diff --git a/invokeai/app/invocations/anima_latents_to_image.py b/invokeai/app/invocations/anima_latents_to_image.pyindex d457de3c2b..7ef766f048 100644--- a/invokeai/app/invocations/anima_latents_to_image.py+++ b/invokeai/app/invocations/anima_latents_to_image.py@@ -28,6 +28,7 @@ from invokeai.app.invocations.model import VAEFieldfrom invokeai.app.invocations.primitives import ImageOutputfrom invokeai.app.services.shared.invocation_context import InvocationContextfrom invokeai.backend.flux.modules.autoencoder import AutoEncoder as FluxAutoEncoder+from invokeai.backend.krea2.vae_compat import patch_qwen_image_vae_tilingfrom invokeai.backend.util.devices import TorchDevicefrom invokeai.backend.util.oom import is_oom_errorfrom invokeai.backend.util.vae_decode_diagnostics import (@@ -43,7 +44,9 @@ from invokeai.backend.util.vae_working_memory import (# Tile geometry for tiled Wan VAE decode. 512px tiles with a 384px stride (128px blended# overlap) cap peak decode working memory at ~1.7GB regardless of image size, while images-# <=512px still decode in a single pass.+# <=512px still decode in a single pass. `patch_qwen_image_vae_tiling` derives that same stride+# from the tile size (the VAE's stock 3/4 ratio); the stride is named here because the+# working-memory constant was calibrated against this exact geometry.ANIMA_VAE_TILE_SIZE = 512ANIMA_VAE_TILE_STRIDE = 384@@ -135,18 +138,6 @@ class AnimaLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):# FLUX VAE handles scaling internally, expects 4D [B, C, H, W]img = vae.decode(latents)else:- # The cached VAE instance is shared across invocations, so always set- # the tiling state explicitly rather than leaving it as-is.- if use_tiling:- vae.enable_tiling(- tile_sample_min_height=ANIMA_VAE_TILE_SIZE,- tile_sample_min_width=ANIMA_VAE_TILE_SIZE,- tile_sample_stride_height=ANIMA_VAE_TILE_STRIDE,- tile_sample_stride_width=ANIMA_VAE_TILE_STRIDE,- )- else:- vae.disable_tiling()-# Expects 5D latents [B, C, T, H, W]if latents.ndim == 4:latents = latents.unsqueeze(2) # [B, C, H, W] -> [B, C, 1, H, W]@@ -160,13 +151,31 @@ class AnimaLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):# upstream corruption from decode-side corruption.latents_finite = bool(torch.isfinite(latents).all())+ def decode_once() -> torch.Tensor:+ out = vae.decode(latents, return_dict=False)[0]+ if not bool(torch.isfinite(out).all()):+ # NaN survives clamp(-1, 1) and quantizes to 0: without this, the+ # failure renders as a silent black image. Diagnose and try to recover.+ out = self._recover_nonfinite_decode(context, vae, latents, out, latents_finite)+ return out++ # The cached VAE instance is shared across invocations and with the Qwen-Image+ # nodes, so the tile geometry is scoped: `enable_tiling` writes it onto the+ # module and `disable_tiling` restores only the flag, never the sizes.try:- decoded = vae.decode(latents, return_dict=False)[0]+ with patch_qwen_image_vae_tiling(vae, ANIMA_VAE_TILE_SIZE if use_tiling else None):+ decoded = decode_once()except RuntimeError as e:if use_tiling or not is_oom_error(e):raise# The working-memory estimate was insufficient on this system;# retry once with tiling, which caps the peak allocation.+ context.util.signal_progress("VAE decode ran out of memory, retrying tiled")+ context.logger.warning(+ "VAE decode ran out of memory; retrying with tiling. The tiled result is not identical to an "+ "untiled decode -- the decoder's normalisation and attention are global, so the difference is "+ "spread over the image rather than confined to the seams."+ )# Drop the failed attempt's traceback before retrying. It pins that# decode's frames, and their locals hold the full-resolution# activations -- exception/traceback/frame is a reference cycle rooted@@ -176,18 +185,8 @@ class AnimaLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):# `ModelConfigFactory._detach_traceback`.e.__traceback__ = NoneTorchDevice.empty_cache()- vae.enable_tiling(- tile_sample_min_height=ANIMA_VAE_TILE_SIZE,- tile_sample_min_width=ANIMA_VAE_TILE_SIZE,- tile_sample_stride_height=ANIMA_VAE_TILE_STRIDE,- tile_sample_stride_width=ANIMA_VAE_TILE_STRIDE,- )- decoded = vae.decode(latents, return_dict=False)[0]-- if not bool(torch.isfinite(decoded).all()):- # NaN survives clamp(-1, 1) and quantizes to 0: without this, the- # failure renders as a silent black image. Diagnose and try to recover.- decoded = self._recover_nonfinite_decode(context, vae, latents, decoded, latents_finite)+ with patch_qwen_image_vae_tiling(vae, ANIMA_VAE_TILE_SIZE):+ decoded = decode_once()# Output is 5D [B, C, T, H, W] — squeeze temporal dimif decoded.ndim == 5:diff --git a/invokeai/app/invocations/flux_vae_decode.py b/invokeai/app/invocations/flux_vae_decode.pyindex 6a234cda7c..69a59564aa 100644--- a/invokeai/app/invocations/flux_vae_decode.py+++ b/invokeai/app/invocations/flux_vae_decode.py@@ -42,13 +42,19 @@ class FluxVaeDecodeInvocation(BaseInvocation, WithMetadata, WithBoard):input=Input.Connection,)- def _vae_decode(self, vae_info: LoadedModel, latents: torch.Tensor) -> Image.Image:+ def _vae_decode(self, context: InvocationContext, vae_info: LoadedModel, latents: torch.Tensor) -> Image.Image:assert isinstance(vae_info.model, (AutoEncoder, AutoencoderKL))+ # This node has no tiling fields, so the config switch is the only way a user can ask for a+ # tiled decode here -- the same one the Z-Image, SD and Qwen-Image decode nodes honour. 0 is+ # the "use the VAE's default tile" sentinel shared by the estimator and `scoped_vae_tiling`.+ use_tiling = context.config.get().force_tiled_decode+ tile_size = 0 if use_tiling else None+# Only estimate working memory for BFL AutoEncoder (diffusers VAE handles this internally)if isinstance(vae_info.model, AutoEncoder):estimated_working_memory = estimate_vae_working_memory_flux(- operation="decode", image_tensor=latents, vae=vae_info.model+ operation="decode", image_tensor=latents, vae=vae_info.model, tile_size=tile_size)else:estimated_working_memory = 0@@ -80,17 +86,22 @@ class FluxVaeDecodeInvocation(BaseInvocation, WithMetadata, WithBoard):return vae.decode(latents)return vae.decode(latents, return_dict=False)[0]- # This node has no tiling controls, so it decodes untiled -- but says so explicitly- # rather than inheriting whatever the last node to touch this shared, cached VAE left- # behind, and restores that state afterwards.+ # The tiling state is set explicitly for this decode rather than inherited from whatever+ # the last node to touch this shared, cached VAE left behind, and restored afterwards.try:- with scoped_vae_tiling(vae, None):+ with scoped_vae_tiling(vae, tile_size):img = decode()except RuntimeError as e:- if not is_oom_error(e):+ if use_tiling or not is_oom_error(e):raise# The working-memory estimate was insufficient on this system. Retry once with# tiling, which caps the peak allocation regardless of resolution.+ context.util.signal_progress("VAE decode ran out of memory, retrying tiled")+ context.logger.warning(+ "VAE decode ran out of memory; retrying with tiling. The tiled result is not identical to an "+ "untiled decode -- the decoder's normalisation and attention are global, so the difference is "+ "spread over the image rather than confined to the seams."+ )# Drop the failed attempt's traceback before retrying. It pins that# decode's frames, and their locals hold the full-resolution# activations -- exception/traceback/frame is a reference cycle rooted@@ -113,7 +124,7 @@ class FluxVaeDecodeInvocation(BaseInvocation, WithMetadata, WithBoard):latents = context.tensors.load(self.latents.latents_name)vae_info = context.models.load(self.vae.vae)context.util.signal_progress("Running VAE")- image = self._vae_decode(vae_info=vae_info, latents=latents)+ image = self._vae_decode(context=context, vae_info=vae_info, latents=latents)TorchDevice.empty_cache()image_dto = context.images.save(image=image)diff --git a/invokeai/app/invocations/image_to_latents.py b/invokeai/app/invocations/image_to_latents.pyindex 8dc5ceba0b..bc8d140360 100644--- a/invokeai/app/invocations/image_to_latents.py+++ b/invokeai/app/invocations/image_to_latents.py@@ -14,7 +14,6 @@ from diffusers.models.autoencoders.autoencoder_kl import AutoencoderKLfrom diffusers.models.autoencoders.autoencoder_tiny import AutoencoderTinyfrom invokeai.app.invocations.baseinvocation import BaseInvocation, invocation-from invokeai.app.invocations.constants import LATENT_SCALE_FACTORfrom invokeai.app.invocations.fields import (FieldDescriptions,ImageField,@@ -121,7 +120,6 @@ class ImageToLatentsInvocation(BaseInvocation):tiling_context = patch_vae_tiling_params(vae,tile_sample_min_size=tile_size,- tile_latent_min_size=tile_size // LATENT_SCALE_FACTOR,tile_overlap_factor=0.25,)diff --git a/invokeai/app/invocations/krea2_denoise.py b/invokeai/app/invocations/krea2_denoise.pyindex 41dc83a082..fbf8baf4df 100644--- a/invokeai/app/invocations/krea2_denoise.py+++ b/invokeai/app/invocations/krea2_denoise.py@@ -27,6 +27,7 @@ from invokeai.app.invocations.fields import (from invokeai.app.invocations.model import TransformerFieldfrom invokeai.app.invocations.primitives import LatentsOutputfrom invokeai.app.services.shared.invocation_context import InvocationContext+from invokeai.app.util.startup_utils import log_attention_backendsfrom invokeai.backend.krea2.attention import (Krea2RegionalPromptingState,build_krea2_attention_processors,@@ -48,14 +49,18 @@ from invokeai.backend.krea2.sampling_utils import (prepare_position_ids,unpack_latents,)-from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat+from invokeai.backend.model_manager.taxonomy import BaseModelTypefrom invokeai.backend.patches.layer_patcher import LayerPatcher, PatchSpecfrom invokeai.backend.patches.lora_conversions.krea2_lora_constants import KREA2_LORA_TRANSFORMER_PREFIXfrom invokeai.backend.patches.model_patch_raw import ModelPatchRaw-from invokeai.backend.quantization.int8_convrot import requires_sidecar_patching+from invokeai.backend.quantization.int8_convrot import (+ peak_int8_dequant_transient_bytes,+ requires_sidecar_patching,+)from invokeai.backend.rectified_flow.rectified_flow_inpaint_extension import RectifiedFlowInpaintExtensionfrom invokeai.backend.stable_diffusion.diffusers_pipeline import PipelineIntermediateStatefrom invokeai.backend.stable_diffusion.diffusion.conditioning_data import Krea2ConditioningInfo+from invokeai.backend.util import sdpa_scopefrom invokeai.backend.util.devices import TorchDevicefrom invokeai.backend.util.logging import InvokeAILogger@@ -79,6 +84,10 @@ class _Krea2StepBenchmark:self._label = labelself._step_ms: list[float] = []self._step_started_at = 0.0+ # A window that did not own the process-global backend selection ran under someone else's+ # policy. For an exclusive override that voids the measurement, so the summary has to say it+ # rather than print a label for a kernel that may not have run.+ self._foreign_windows_at_start = sdpa_scope.foreign_window_entries()# Reset here, immediately before the loop, so the reported peak is the loop's and not the# model load's.torch.cuda.reset_peak_memory_stats(device)@@ -106,6 +115,12 @@ class _Krea2StepBenchmark:# The first step absorbs kernel selection and allocator warmup -- on a cold cuDNN run it has# been seen at 2606 ms against a 1451 ms steady mean -- so it is reported, not averaged in.steady = self._step_ms[1:] or self._step_ms+ foreign = sdpa_scope.foreign_window_entries() - self._foreign_windows_at_start+ if foreign:+ logger.warning(+ f"Krea-2 SDPA benchmark [{self._label}]: {foreign} attention window(s) ran under another "+ "session's backend policy, so these timings are not a measurement of the requested kernel."+ )logger.info(f"Krea-2 SDPA benchmark [{self._label}]: {len(self._step_ms)} steps | "f"first {first_ms:.0f} ms | "@@ -469,8 +484,6 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):)transformer_config = context.models.get_config(self.transformer.transformer)- # Refined against the loaded module tree below, once the transformer is in hand.- model_is_quantized = transformer_config.format in (ModelFormat.GGUFQuantized,)num_train_timesteps = scheduler.config.num_train_timesteps# Estimate the peak working memory (activations) the transformer forward needs and ask the model@@ -490,6 +503,18 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):pos_extension, neg_extension, inference_dtype),)+ # An int8_tensorwise build stores its linears quantized and materializes the dequantized,+ # derotated weight per forward call. That transient is alive alongside the activations above,+ # so it is added rather than compared -- and it is invisible to an activation estimate, which+ # is how a model that loaded comfortably OOMs in its first step. Zero for any other format.+ estimated_working_memory += peak_int8_dequant_transient_bytes(transformer_info.model, inference_dtype)++ # Once per device per process, and from here rather than from startup: the probe allocates,+ # so on the boot path it would create a CUDA context on an idle server -- and on `cuda:0`,+ # which need not be a device this session ever uses. Before the model is locked, because it+ # ends with `empty_cache()` and dropping the allocator's blocks is cheap now and expensive+ # once the transformer is resident.+ log_attention_backends(logger, device)with ExitStack() as exit_stack:(cached_weights, transformer) = exit_stack.enter_context(@@ -500,6 +525,8 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):# SDPA for enable_gqa=True, which PyTorch only supports on the math backend — that materializes the# full O(seq^2) score matrix (~5.7 GB per attention at 1280x720, ~40 GB at 2560x1440) and OOMs. Swap# in a memory-efficient processor that expands the KV heads and uses the O(seq) SDPA kernel instead.+ # Whether LoRA has to go on as a sidecar. Asked of the loaded module tree rather than the+ # format, which cannot see an int8_tensorwise build's Int8ConvrotLinear layers.model_is_quantized = requires_sidecar_patching(transformer, transformer_config.format)regional_prompting_state = Krea2RegionalPromptingState()diff --git a/invokeai/app/invocations/latents_to_image.py b/invokeai/app/invocations/latents_to_image.pyindex ebd3a93db9..482c808b35 100644--- a/invokeai/app/invocations/latents_to_image.py+++ b/invokeai/app/invocations/latents_to_image.py@@ -6,7 +6,6 @@ from diffusers.models.autoencoders.autoencoder_kl import AutoencoderKLfrom diffusers.models.autoencoders.autoencoder_tiny import AutoencoderTinyfrom invokeai.app.invocations.baseinvocation import BaseInvocation, invocation-from invokeai.app.invocations.constants import LATENT_SCALE_FACTORfrom invokeai.app.invocations.fields import (FieldDescriptions,Input,@@ -95,7 +94,6 @@ class LatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):tiling_context = patch_vae_tiling_params(vae,tile_sample_min_size=self.tile_size,- tile_latent_min_size=self.tile_size // LATENT_SCALE_FACTOR,tile_overlap_factor=0.25,)diff --git a/invokeai/app/invocations/minimax_h3_denoise.py b/invokeai/app/invocations/minimax_h3_denoise.pyindex a59259fdd0..89c9d81378 100644--- a/invokeai/app/invocations/minimax_h3_denoise.py+++ b/invokeai/app/invocations/minimax_h3_denoise.py@@ -74,7 +74,10 @@ from invokeai.backend.patches.lora_conversions.minimax_h3_lora_conversion_utilsis_minimax_h3_adaln_layer_path,)from invokeai.backend.patches.model_patch_raw import ModelPatchRaw-from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear+from invokeai.backend.quantization.int8_convrot import (+ peak_int8_dequant_transient_bytes,+ requires_sidecar_patching,+)from invokeai.backend.stable_diffusion.diffusers_pipeline import PipelineIntermediateStatefrom invokeai.backend.stable_diffusion.diffusion.conditioning_data import MiniMaxH3ConditioningInfofrom invokeai.backend.util.devices import TorchDevice@@ -467,7 +470,14 @@ class MiniMaxH3DenoiseInvocation(BaseInvocation):return step_callbackestimated_working_memory = self._estimate_working_memory(state.layout, num_loras=len(self.transformer.loras))+ transformer_config = context.models.get_config(self.transformer.transformer)transformer_info = context.models.load(self.transformer.transformer)+ # An int8_convrot build materializes each linear's dequantized, derotated weight per forward+ # (~620 MB for H3's fused-SwiGLU fc1), which the model's resident size does not account for.+ # Added to the activation estimate rather than compared against it: the transient is alive+ # inside the same forward. Zero on a bf16 build. Read from the unlocked model, before the+ # VRAM lock the reservation applies to.+ estimated_working_memory += peak_int8_dequant_transient_bytes(transformer_info.model, torch.bfloat16)# LoRA patches are materialized (RAM cache) before any VRAM locks. On the AdaLN-pruned# transformer the AdaLN layers cannot be weight patches (their 2688-dim input space was@@ -526,8 +536,9 @@ class MiniMaxH3DenoiseInvocation(BaseInvocation):if lora_patch_specs or adaln_patches:# Quantized (int8-convrot) layers cannot take direct weight patches; route every# patched module through the sidecar path when any are present. bf16 models keep- # the faster direct patching.- force_sidecar = any(isinstance(m, Int8ConvrotLinear) for m in transformer.modules())+ # the faster direct patching. Asked of the loaded module tree *and* the format,+ # through the one helper every architecture on this scheme shares.+ force_sidecar = requires_sidecar_patching(transformer, transformer_config.format)stack.enter_context(LayerPatcher.apply_smart_model_patches(model=transformer,diff --git a/invokeai/app/invocations/z_image_denoise.py b/invokeai/app/invocations/z_image_denoise.pyindex edd3174b2e..4c1d10814c 100644--- a/invokeai/app/invocations/z_image_denoise.py+++ b/invokeai/app/invocations/z_image_denoise.py@@ -32,7 +32,10 @@ from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormatfrom invokeai.backend.patches.layer_patcher import LayerPatcher, PatchSpecfrom invokeai.backend.patches.lora_conversions.z_image_lora_constants import Z_IMAGE_LORA_TRANSFORMER_PREFIXfrom invokeai.backend.patches.model_patch_raw import ModelPatchRaw-from invokeai.backend.quantization.int8_convrot import requires_sidecar_patching+from invokeai.backend.quantization.int8_convrot import (+ peak_int8_dequant_transient_bytes,+ requires_sidecar_patching,+)from invokeai.backend.rectified_flow.rectified_flow_inpaint_extension import RectifiedFlowInpaintExtensionfrom invokeai.backend.stable_diffusion.diffusers_pipeline import PipelineIntermediateStatefrom invokeai.backend.stable_diffusion.diffusion.conditioning_data import ZImageConditioningInfo@@ -443,8 +446,23 @@ class ZImageDenoiseInvocation(BaseInvocation):):raise ValueError(f"Unsupported Z-Image model format: {transformer_config.format}")+ # An int8_tensorwise build materializes each linear's dequantized, derotated weight per+ # forward. That transient is not part of the model's resident size, so the cache has to+ # be told to keep room for it or the first forward competes with weights it just placed.+ # Read from the unlocked model, before the VRAM lock the reservation applies to; zero+ # for every other build.+ #+ # Passed alone rather than added to an activation estimate because this node has none --+ # the cache's `device_working_mem_gb` floor is what covers activations here, as it did+ # before. That floor (3 GiB by default) is 20x Z-Image's largest int8 transient, so this+ # only ever raises the reservation; a node that grows a real activation estimate should+ # add the two, since the transient is alive alongside the activations.+ int8_dequant_bytes = peak_int8_dequant_transient_bytes(transformer_info.model, inference_dtype)+# Load transformer - always use base transformer, control is handled via extension- (cached_weights, transformer) = exit_stack.enter_context(transformer_info.model_on_device())+ (cached_weights, transformer) = exit_stack.enter_context(+ transformer_info.model_on_device(working_mem_bytes=int8_dequant_bytes)+ )# Whether LoRA has to go on as a sidecar. Asked of the loaded module tree, not the# format: a `checkpoint` Z-Image may be an int8_tensorwise build, whose Linears arediff --git a/invokeai/app/invocations/z_image_latents_to_image.py b/invokeai/app/invocations/z_image_latents_to_image.pyindex 107a4c9caf..91805d0a1d 100644--- a/invokeai/app/invocations/z_image_latents_to_image.py+++ b/invokeai/app/invocations/z_image_latents_to_image.py@@ -44,8 +44,8 @@ class ZImageLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):vae: VAEField = InputField(description=FieldDescriptions.vae, input=Input.Connection)tiled: bool = InputField(default=False, description=FieldDescriptions.tiled)# NOTE: tile_size = 0 is a special value. We use this rather than `int | None`, because the workflow UI does not- # offer a way to directly set None values. The size applies to InvokeAI's FLUX AutoEncoder; a diffusers- # AutoencoderKL tiles with its own geometry, which it does not expose as a single settable size.+ # offer a way to directly set None values. InvokeAI's FLUX AutoEncoder takes the size as given; on a diffusers+ # AutoencoderKL it is snapped down to a tile that VAE's own tiled decode can assemble -- see `scoped_vae_tiling`.tile_size: int = InputField(default=0, multiple_of=8, description=FieldDescriptions.vae_tile_size)@torch.no_grad()@@ -121,6 +121,11 @@ class ZImageLatentsToImageInvocation(BaseInvocation, WithMetadata, WithBoard):# The working-memory estimate was insufficient on this system. Retry once with# tiling, which caps the peak allocation regardless of resolution.context.util.signal_progress("VAE decode ran out of memory, retrying tiled")+ context.logger.warning(+ "VAE decode ran out of memory; retrying with tiling. The tiled result is not identical to an "+ "untiled decode -- the decoder's normalisation and attention are global, so the difference is "+ "spread over the image rather than confined to the seams."+ )# Drop the failed attempt's traceback before retrying. It pins that# decode's frames, and their locals hold the full-resolution# activations -- exception/traceback/frame is a reference cycle rooteddiff --git a/invokeai/app/run_app.py b/invokeai/app/run_app.pyindex fb2fcea33a..759c246b14 100644--- a/invokeai/app/run_app.py+++ b/invokeai/app/run_app.py@@ -85,9 +85,9 @@ def run_app() -> None:check_cudnn,enable_dev_reload,find_open_port,- log_attention_backends,register_mime_types,)+ from invokeai.backend.krea2.attention import resolve_krea2_sdpa_backends# Find an open port, and modify the config accordingly.first_open_port = find_open_port(app_config.port)@@ -100,7 +100,9 @@ def run_app() -> None:apply_monkeypatches()register_mime_types()check_cudnn(logger)- log_attention_backends(logger, TorchDevice.choose_torch_device())+ # Fail here rather than inside a generation: the value is read per generation, so a typo would+ # otherwise surface as a failed queue item minutes after the server came up.+ resolve_krea2_sdpa_backends()# Initialize the app and event loop.app, loop = get_app()diff --git a/invokeai/app/services/config/config_default.py b/invokeai/app/services/config/config_default.pyindex 0e35b1ec7c..154c55141c 100644--- a/invokeai/app/services/config/config_default.py+++ b/invokeai/app/services/config/config_default.py@@ -88,7 +88,7 @@ class InvokeAIAppConfig(BaseSettings):download_cache_dir: Path to the directory that contains dynamically downloaded models.legacy_conf_dir: Path to directory of legacy checkpoint config files.db_dir: Path to InvokeAI databases directory.- db_synchronous: SQLite durability setting. `full` (the default) 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, because WAL guarantees consistency either way. What it 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`+ 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`outputs_dir: Path to directory for outputs.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`custom_nodes_dir: Path to directory for custom nodes.@@ -124,7 +124,7 @@ class InvokeAIAppConfig(BaseSettings):pid_memory_optimization: Enable experimental PiD decode memory optimizations. Roughly halves the peak activation memory of a PiD decode; in exchange the decoded image changes slightly, because neither the chunked pixel pathway nor the float32 sampler intermediates are bit-exact with the default path.attention_type: Attention type.<br>Valid values: `auto`, `normal`, `xformers`, `sliced`, `torch-sdp`attention_slice_size: Slice size, valid when attention_type=="sliced".<br>Valid values: `auto`, `balanced`, `max`, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`- force_tiled_decode: Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty).+ force_tiled_decode: Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty). A tiled decode is not pixel-identical to a single-pass one: a VAE decoder normalises and attends over the whole image, so the difference is spread across it rather than confined to the tile seams. As of this release the setting also applies to FLUX.1, which previously ignored it.pil_compress_level: The compress_level setting of PIL.Image.save(), used for PNG encoding. All settings are lossless. 0 = no compression, 1 = fastest with slightly larger filesize, 9 = slowest with smallest filesize. 1 is typically the best setting.max_queue_size: Maximum number of items in the session queue.session_queue_mode: Session queue mode. Use 'FIFO' for traditional first-in-first-out, or 'round_robin' to serve each user's jobs in turn. In single-user mode, FIFO is always used regardless of this setting.<br>Valid values: `FIFO`, `round_robin`@@ -192,7 +192,7 @@ class InvokeAIAppConfig(BaseSettings):download_cache_dir: Path = Field(default=Path("models/.download_cache"), description="Path to the directory that contains dynamically downloaded models.")legacy_conf_dir: Path = Field(default=Path("configs"), description="Path to directory of legacy checkpoint config files.")db_dir: Path = Field(default=Path("databases"), description="Path to InvokeAI databases directory.")- db_synchronous: DB_SYNCHRONOUS = Field(default="full", description="SQLite durability setting. `full` (the default) 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, because WAL guarantees consistency either way. What it 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.")+ db_synchronous: DB_SYNCHRONOUS = Field(default="full", description="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.")outputs_dir: Path = Field(default=Path("outputs"), description="Path to directory for outputs.")fonts_dir: Path = Field(default=Path("fonts"), description="Path to directory for custom fonts.")fonts_storage_dir: Path = Field(default=Path("fonts-uploaded"), description="Path to application-managed uploaded fonts.")@@ -248,7 +248,7 @@ class InvokeAIAppConfig(BaseSettings):pid_memory_optimization: bool = Field(default=False, description="Enable experimental PiD decode memory optimizations. Roughly halves the peak activation memory of a PiD decode; in exchange the decoded image changes slightly, because neither the chunked pixel pathway nor the float32 sampler intermediates are bit-exact with the default path.")attention_type: ATTENTION_TYPE = Field(default="auto", description="Attention type.")attention_slice_size: ATTENTION_SLICE_SIZE = Field(default="auto", description='Slice size, valid when attention_type=="sliced".')- force_tiled_decode: bool = Field(default=False, description="Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty).")+ force_tiled_decode: bool = Field(default=False, description="Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty). A tiled decode is not pixel-identical to a single-pass one: a VAE decoder normalises and attends over the whole image, so the difference is spread across it rather than confined to the tile seams. As of this release the setting also applies to FLUX.1, which previously ignored it.")pil_compress_level: int = Field(default=1, description="The compress_level setting of PIL.Image.save(), used for PNG encoding. All settings are lossless. 0 = no compression, 1 = fastest with slightly larger filesize, 9 = slowest with smallest filesize. 1 is typically the best setting.")max_queue_size: int = Field(default=10000, gt=0, description="Maximum number of items in the session queue.")session_queue_mode: SESSION_QUEUE_MODE = Field(default="round_robin", description="Session queue mode. Use 'FIFO' for strict first-in-first-out, or 'round_robin' to serve each user's jobs in turn. In round-robin mode, priority orders each user's own jobs, but the user rotation takes precedence: one user's high-priority job does not preempt another user's turn. In single-user mode, jobs are served in submission order either way — except that on multi-GPU systems the default 'round_robin' allows same-priority jobs to be reordered slightly so a freed GPU prefers jobs whose models it already has loaded. Set 'FIFO' to disable that reordering and enforce strict submission order.")diff --git a/invokeai/app/services/shared/sqlite/sqlite_database.py b/invokeai/app/services/shared/sqlite/sqlite_database.pyindex cfd788888a..4cbb2e0e4c 100644--- a/invokeai/app/services/shared/sqlite/sqlite_database.py+++ b/invokeai/app/services/shared/sqlite/sqlite_database.py@@ -4,6 +4,7 @@ from collections.abc import Generatorfrom contextlib import contextmanagerfrom logging import Loggerfrom pathlib import Path+from typing import get_argsfrom invokeai.app.services.config.config_default import DB_SYNCHRONOUSfrom invokeai.app.services.shared.sqlite.sqlite_common import sqlite_memory@@ -16,7 +17,8 @@ class SqliteDatabase::param db_path: Path to the database file. If None, an in-memory database is used.:param logger: Logger to use for logging.:param verbose: Whether to log SQL statements. Provides `logger.debug` as the SQLite trace callback.- :param synchronous: SQLite `synchronous` setting. Defaults to `full`, SQLite's own default.+ :param synchronous: SQLite `synchronous` setting. Defaults to `full`, what InvokeAI has always used.+ `normal` is refused, with a warning, for a database file whose journal mode did not become WAL.This is a light wrapper around the `sqlite3` module, providing a few conveniences:- The database file is written to disk if it does not exist.@@ -37,10 +39,15 @@ class SqliteDatabase:synchronous: DB_SYNCHRONOUS = "full",) -> None:"""Initializes the database. This is used internally by the class constructor."""+ # This constructor is called directly (user management commands, tests), not only through the+ # validated config, and `synchronous` is interpolated into a PRAGMA below. `DB_SYNCHRONOUS` is+ # a static annotation, so the value is checked here, before anything is opened.+ if synchronous not in get_args(DB_SYNCHRONOUS):+ raise ValueError(f"Invalid synchronous setting {synchronous!r}, expected one of {get_args(DB_SYNCHRONOUS)}")+self._logger = loggerself._db_path = db_pathself._verbose = verbose- self._synchronous = synchronousself._lock = threading.RLock()if not self._db_path:@@ -58,20 +65,36 @@ class SqliteDatabase:# Enable foreign key constraintsself._conn.execute("PRAGMA foreign_keys = ON;")- # Enable Write-Ahead Logging (WAL) mode for better concurrency- self._conn.execute("PRAGMA journal_mode = WAL;")+ # Enable Write-Ahead Logging (WAL) mode for better concurrency. The statement reports the mode+ # that was actually established: WAL needs shared memory, so it can fail to engage -- quietly --+ # on network filesystems, some container volume drivers and `SQLITE_OMIT_WAL` builds.+ journal_mode = str(self._conn.execute("PRAGMA journal_mode = WAL;").fetchone()[0]).lower()# Set a busy timeout to prevent database lockups during writesself._conn.execute("PRAGMA busy_timeout = 5000;") # 5 seconds- # Durability. SQLite's own default is `full`, which fsyncs on every commit; `normal` under WAL- # trades the last transactions on a power loss or OS crash for roughly 12x shorter commits. It- # cannot corrupt the database -- that is WAL's guarantee either way. Shorter commits matter- # twice here, because every write holds the lock that serialises all database work.+ # Durability. SQLite's own default is `full`, which fsyncs on every commit; `normal` trades the+ # last transactions on a power loss or OS crash for roughly 12x shorter commits. Shorter commits+ # matter twice here, because every write holds the lock that serialises all database work.+ #+ # `normal` cannot corrupt the database only *because* of WAL; on a rollback journal it can, so a+ # database file that did not get WAL keeps `full` instead. In-memory databases report `memory`+ # and have no durability to trade, so the requirement does not apply to them.#- # The value is interpolated rather than parameterised: PRAGMA does not take bind parameters,- # and the type is a closed Literal, so no user input reaches this string.- self._conn.execute(f"PRAGMA synchronous = {self._synchronous.upper()};")+ # Refused rather than fatal: the setting is a performance preference, and starting with stronger+ # durability than asked for costs commit time, where starting with weaker durability than the+ # documented guarantee risks the user's database. A warning names the mode so the cause is+ # visible instead of merely slow.+ if synchronous == "normal" and self._db_path is not None and journal_mode != "wal":+ self._logger.warning(+ f"Journal mode is '{journal_mode}', not WAL, so db_synchronous='normal' was refused and "+ "'full' used instead: without WAL that setting can corrupt the database on power loss."+ )+ synchronous = "full"++ # PRAGMA does not take bind parameters, so the value is interpolated. It is checked against+ # DB_SYNCHRONOUS at the top of this constructor.+ self._conn.execute(f"PRAGMA synchronous = {synchronous.upper()};")def clean(self) -> None:"""diff --git a/invokeai/app/util/startup_utils.py b/invokeai/app/util/startup_utils.pyindex 509bfcf047..a0c760996f 100644--- a/invokeai/app/util/startup_utils.py+++ b/invokeai/app/util/startup_utils.py@@ -51,52 +51,73 @@ def probe_attention_backends(device: torch.device) -> dict[str, bool] | None:This asks about the *unmasked* case. A backend listed here can still be rejected for a specificcall -- flash refuses the additive padding mask the regional-prompting paths pass, for instance --so this is a diagnostic, not a dispatch table.++ It allocates on `device`, which creates that device's CUDA primary context if nothing has yet.+ That context's VRAM is held for the process lifetime and `empty_cache()` does not release it, so+ this belongs on a path that was going to touch the GPU anyway -- not on the boot path, where it+ would park a context on an idle server, and on `cuda:0` rather than on a configured+ `generation_devices` entry."""if device.type != "cuda":return None- probe = params = Nonetry:- probe = torch.empty(- 1,- _PROBE_HEADS,- _PROBE_SEQ_LEN,- _PROBE_HEAD_DIM,- device=device,- dtype=torch.float16,- )- params = torch.backends.cuda.SDPAParams(probe, probe, probe, None, 0.0, False, False)- return {- "cudnn": bool(torch.backends.cuda.can_use_cudnn_attention(params)),- "flash": bool(torch.backends.cuda.can_use_flash_attention(params)),- "efficient": bool(torch.backends.cuda.can_use_efficient_attention(params)),- # Always present -- it is the unfused fallback, not a kernel that can be missing.- "math": True,- }+ probe = params = None+ try:+ probe = torch.empty(+ 1,+ _PROBE_HEADS,+ _PROBE_SEQ_LEN,+ _PROBE_HEAD_DIM,+ device=device,+ dtype=torch.float16,+ )+ params = torch.backends.cuda.SDPAParams(probe, probe, probe, None, 0.0, False, False)+ return {+ "cudnn": bool(torch.backends.cuda.can_use_cudnn_attention(params)),+ "flash": bool(torch.backends.cuda.can_use_flash_attention(params)),+ "efficient": bool(torch.backends.cuda.can_use_efficient_attention(params)),+ # Always present -- it is the unfused fallback, not a kernel that can be missing.+ "math": True,+ }+ finally:+ # Do not leave the probe tensor sitting in the caching allocator for the first+ # generation. `empty_cache()` only releases blocks nothing references. Both locals still+ # hold the probe here -- `SDPAParams` keeps a reference of its own -- so dropping both is+ # what makes the call do anything at all. Measured: without this the segment stays+ # reserved for the process lifetime, which is the opposite of what the line above says.+ #+ # Nested inside the `except` below, not beside it: a `finally` on the same `try` is not+ # covered by that `try`'s handler, so a raise from `empty_cache()` would escape a+ # function whose whole contract is that it does not.+ del probe, params+ torch.cuda.empty_cache()except Exception:# A diagnostic must never be the reason the server does not start.return None- finally:- # Do not leave the probe tensor sitting in the caching allocator for the first generation.- # `empty_cache()` only releases blocks nothing references. Both locals still hold the probe- # here -- `SDPAParams` keeps a reference of its own -- so dropping both is what makes the- # call do anything at all. Measured: without this the segment stays reserved for the- # process lifetime, which is the opposite of what the line above says.- del probe, params- torch.cuda.empty_cache()+++# Devices already reported. The line answers a support question ("which kernels does this build+# have?"), so it is worth exactly once per device per process and nothing after that.+_logged_attention_backends: set[str] = set()def log_attention_backends(logger: logging.Logger, device: torch.device) -> None:- """Log the SDPA backend availability once at startup.+ """Log this device's SDPA backend availability, once per device.The point is support: a question about attention performance can then be answered by reading a- log line instead of asking the user to run a probe script.+ log line instead of asking the user to run a probe script. Call it from a generation path rather+ than from startup -- `probe_attention_backends` explains why."""+ key = str(device)+ if key in _logged_attention_backends:+ returnavailable = probe_attention_backends(device)if available is None:return+ _logged_attention_backends.add(key)summary = " ".join(f"{name}={'yes' if ok else 'no'}" for name, ok in available.items())logger.info(- f"SDPA attention backends "+ f"SDPA attention backends on {device} "f"(fp16, {_PROBE_HEADS} heads, seq {_PROBE_SEQ_LEN}, head_dim {_PROBE_HEAD_DIM}, no mask): {summary}")diff --git a/invokeai/backend/flux/modules/autoencoder.py b/invokeai/backend/flux/modules/autoencoder.pyindex 86cb7b78f6..135c362ed4 100644--- a/invokeai/backend/flux/modules/autoencoder.py+++ b/invokeai/backend/flux/modules/autoencoder.py@@ -349,13 +349,19 @@ class AutoEncoder(nn.Module):are in output pixels.`tile_overlap` defaults to DEFAULT_TILE_OVERLAP, shrunk to half the tile if the caller asked- for a tile that small. The alternative -- raising -- would turn a tile size the workflow UI- lets a user type into a failed generation.-- Note on accuracy: at the default 512/128 geometry a tiled decode reproduces the single-pass- one exactly (float32 epsilon, measured). It degrades as tiles get small relative to the- image, because more tiles mean the blend bands sit closer to the tiles' own zero-padded- borders. Prefer a large tile that fits over a small one that fits comfortably.+ for a tile that small, rather than raising: that would turn a tile size the workflow UI lets+ a user type into a failed generation. The shrink bottoms out at one `spatial_compression`+ step, below which there is no overlap left to blend and the geometry is rejected.++ Note on accuracy: a tiled decode does not reproduce the single-pass one. The decoder's+ GroupNorms normalise over the whole spatial extent and `mid.attn_1` is global, so a tile+ sees different statistics than the full latent does -- and the difference is spread over the+ whole image rather than confined to the seams. Measured on the tiny test fixture at the+ default 512/128 geometry: max |tiled - untiled| of 0.12 at 768px and 0.19 at 1536px, against+ an output range of about +/-3. What *is* exact is the tile geometry. Accuracy degrades+ further as tiles get small relative to the image, because more tiles mean the blend bands+ sit closer to the tiles' own zero-padded borders. Prefer a large tile that fits over a small+ one that fits comfortably."""if tile_overlap is None:tile_overlap = min(DEFAULT_TILE_OVERLAP, tile_sample_min_size // 2)@@ -366,6 +372,13 @@ class AutoEncoder(nn.Module):)if tile_overlap % self.spatial_compression != 0:raise ValueError(f"tile_overlap must be divisible by {self.spatial_compression}, got {tile_overlap}.")+ if tile_overlap <= 0:+ # Blending needs a band to blend over: `merge_tiles_with_linear_blending` builds its+ # gradient with `np.linspace(..., num=blend_amount)`, so a zero overlap yields no+ # gradient at all and the tiles butt together with a hard seam. Reachable only from a+ # direct call -- the nodes go through `resolve_tile_size`, which floors at 128 -- and+ # only for `tile_sample_min_size=8`, whose rounded-down automatic overlap is 0.+ raise ValueError(f"tile_overlap must be greater than 0, got {tile_overlap}.")if tile_overlap >= tile_sample_min_size:raise ValueError(f"tile_overlap ({tile_overlap}) must be smaller than tile_sample_min_size ({tile_sample_min_size})."@@ -406,8 +419,12 @@ class AutoEncoder(nn.Module):"""Decode `z` as overlapping tiles, blended back together linearly.`z` is expected to already be denormalised, i.e. this consumes what `decode()` hands to- `self.decoder`. Peak memory is bounded by one tile plus the destination image, because each- finished tile is moved to the CPU before the next one is decoded.+ `self.decoder`. *Device* memory is what tiling bounds, to one tile: every finished tile is+ moved to the CPU as soon as it is decoded. Host memory is not bounded -- the tiles+ accumulate there until the merge runs after the loop, and the stack at the end copies the+ merged image again. At 4096x4096 with the default geometry the host peak is 121 tiles of+ 512x512x3 float32 (~380MB) plus the merged array and the stacked copy of it (~200MB each),+ so ~780MB, against ~200MB of device memory for the result.The tile layout is computed in *latent* space and scaled up afterwards. Computing it in pixelspace would be wrong: `calc_tiles_min_overlap` distributes the leftover with integer@@ -424,6 +441,16 @@ class AutoEncoder(nn.Module):if latent_height <= latent_tile_size and latent_width <= latent_tile_size:return self.decoder(z)+ # `calc_tiles_min_overlap` clamps the tile down to the image on each axis and then divides+ # by `tile - min_overlap`, so an axis exactly as small as the overlap divides by zero -- a+ # 128x1024 image at the default 512/128 geometry, reachable from the node field, from+ # `force_tiled_decode`, and from the OOM retry, where it would replace the OOM with a+ # division-by-zero. Shrink the overlap to fit the smallest clamped tile; if nothing usable is+ # left the layout is degenerate, and at that size a single pass is both correct and cheap.+ latent_overlap = min(latent_overlap, min(latent_tile_size, latent_height, latent_width) - 1)+ if latent_overlap < 1:+ return self.decoder(z)+latent_tiles = calc_tiles_min_overlap(image_height=latent_height,image_width=latent_width,@@ -473,7 +500,10 @@ class AutoEncoder(nn.Module):dst_image=merged,tiles=pixel_tiles,tile_images=tile_images,- blend_amount=self.tile_overlap,+ # Derived from the overlap the layout was actually built with, not from+ # `self.tile_overlap`: the merge requires every non-edge tile overlap to be at least+ # `blend_amount`, and the shrink above can put the two below the configured value.+ blend_amount=latent_overlap * scale,)batch_images.append(torch.from_numpy(merged).permute(2, 0, 1))diff --git a/invokeai/backend/krea2/attention.py b/invokeai/backend/krea2/attention.pyindex 83e7f99f67..5f587715f1 100644--- a/invokeai/backend/krea2/attention.py+++ b/invokeai/backend/krea2/attention.py@@ -14,8 +14,9 @@ included, so where it is available the K/V heads can stay at 12 and the expansio``repeat_interleave`` allocates two tensors four times larger than the originals, every call. Where nofused kernel takes GQA (the memory-efficient kernel refuses it outright, flash refuses the additivemask, and ROCm has no cuDNN at all) the expansion is still the only thing standing between this-processor and the ~5.7 GB math path. So it is now conditional, decided per call shape by asking the-dispatcher rather than by assuming -- see ``_serves_grouped_query_attention``.+processor and the ~5.7 GB math path. So it is now conditional, decided per call by asking the+dispatcher rather than by assuming -- see ``_serves_grouped_query_attention``, which runs inside the+same SDPA window as the call it is answering for, because that is the state the answer depends on.The math is otherwise identical to ``Krea2AttnProcessor`` (q/k RMSNorm, rotary embeddings, sigmoid output gate)."""@@ -28,9 +29,10 @@ from typing import Protocolimport torchimport torch.nn.functional as Ffrom diffusers.models.embeddings import apply_rotary_emb-from torch.nn.attention import SDPBackend, sdpa_kernel+from torch.nn.attention import SDPBackendfrom invokeai.backend.util.logging import InvokeAILogger+from invokeai.backend.util.sdpa_scope import sdpa_policylogger = InvokeAILogger.get_logger(__name__)@@ -67,7 +69,9 @@ _KREA2_SDPA_BACKENDS = [# Opt-in override, for measuring one backend against another and for support questions. Unset -- the# only state a user ever sees by default -- is the ranked list above, unchanged.KREA2_SDPA_BACKEND_ENV_VAR = "INVOKE_KREA2_SDPA_BACKEND"-_PRIORITY_CUDNN = "priority-cudnn"+# The ranked list above, named so a benchmarking run can state which policy it used. It is NOT a+# request to rank cuDNN first -- the list is flash-first, because flash wins wherever a build has it.+_RANKED_DEFAULT = "default"_EXCLUSIVE_BACKENDS = {"cudnn": SDPBackend.CUDNN_ATTENTION,"efficient": SDPBackend.EFFICIENT_ATTENTION,@@ -86,26 +90,28 @@ class Krea2SdpaBackends:def describe(self) -> str:names = ", ".join(b.name for b in self.backends)- return f"sdpa_kernel([{names}], set_priority={self.set_priority})"+ return f"sdpa_policy([{names}], set_priority={self.set_priority})"def resolve_krea2_sdpa_backends(raw_override: str | None = None) -> Krea2SdpaBackends:"""Resolve the SDPA backend list, honouring KREA2_SDPA_BACKEND_ENV_VAR.- The exclusive modes are the point of the override: a run that completes proves that kernel was- actually used, because an unavailable backend raises visibly instead of quietly degrading to math.+ The exclusive modes are the point of the override: an unavailable backend raises visibly instead+ of quietly degrading to math, so a run that completes proves that kernel served it -- *provided*+ the policy actually applied. It does not when another session already holds the process-global+ window; see `sdpa_scope`, which counts those entries so the benchmark can say so."""raw = os.environ.get(KREA2_SDPA_BACKEND_ENV_VAR) if raw_override is None else raw_overrideif raw is None or not raw.strip():return Krea2SdpaBackends(backends=tuple(_KREA2_SDPA_BACKENDS), set_priority=True)value = raw.strip().lower()- if value == _PRIORITY_CUDNN:+ if value == _RANKED_DEFAULT:return Krea2SdpaBackends(backends=tuple(_KREA2_SDPA_BACKENDS), set_priority=True, override=value)if value in _EXCLUSIVE_BACKENDS:return Krea2SdpaBackends(backends=(_EXCLUSIVE_BACKENDS[value],), set_priority=False, override=value)- valid = ", ".join([*sorted(_EXCLUSIVE_BACKENDS), _PRIORITY_CUDNN])+ valid = ", ".join([*sorted(_EXCLUSIVE_BACKENDS), _RANKED_DEFAULT])raise ValueError(f"{KREA2_SDPA_BACKEND_ENV_VAR}={raw!r} is not a valid value. Valid values: {valid}.")@@ -130,8 +136,6 @@ class Krea2MemoryEfficientAttnProcessor:self.regional_prompting_state = regional_prompting_state# Resolved once per generation and handed down, not read per attention call.self.sdpa_backends = sdpa_backends if sdpa_backends is not None else resolve_krea2_sdpa_backends()- # Keyed by the call shape; see `_serves_grouped_query_attention`.- self._gqa_support: dict[tuple, bool] = {}def __call__(self,@@ -168,31 +172,23 @@ class Krea2MemoryEfficientAttnProcessor:key = key.transpose(1, 2)value = value.transpose(1, 2)- # Krea-2 has 48 query heads over 12 K/V heads. Passing them through as they are avoids- # allocating two tensors four times larger, but only some kernels serve that shape -- so ask,- # do not assume. Where the answer is no, expand as before: that is what keeps this off the- # math path, which materialises the full [heads, seq, seq] score matrix.- enable_gqa = attn.num_heads != attn.num_kv_heads and self._serves_grouped_query_attention(- query, key, value, attention_mask- )- if attn.num_heads != attn.num_kv_heads and not enable_gqa:- repeats = attn.num_heads // attn.num_kv_heads- key = key.repeat_interleave(repeats, dim=1)- value = value.repeat_interleave(repeats, dim=1)-- # `sdpa_kernel` sets process-global flags, not thread-local ones, and torch offers no- # thread-scoped variant. InvokeAI runs one generation session per GPU concurrently, so a- # session on another device inside this window is affected too. Measured, on both paths:- #- # - Default (the four-backend list): a foreign thread still sees all four enabled. Only the- # priority order moves, so a concurrent call flash cannot serve may land on cuDNN rather- # than efficient. Both are valid kernels; the effect is which one runs, not whether one- # is available.- # - Exclusive override (`INVOKE_KREA2_SDPA_BACKEND=cudnn` and friends): a foreign thread- # sees the other three *disabled* for the duration. That is opt-in, and the variable- # exists for measuring one kernel against another rather than for normal operation --- # worth knowing before reaching for it on a multi-GPU box.- with sdpa_kernel(list(self.sdpa_backends.backends), set_priority=self.sdpa_backends.set_priority):+ # Both of these belong inside the window, and in this order. `can_use_*` reads the same+ # process-global enable flags the window sets, so asking outside it answers for a different+ # policy than the call will run under -- and the expansion, if needed, has to happen after+ # the answer.+ with sdpa_policy(self.sdpa_backends.backends, set_priority=self.sdpa_backends.set_priority):+ # Krea-2 has 48 query heads over 12 K/V heads. Passing them through as they are avoids+ # allocating two tensors four times larger, but only some kernels serve that shape -- so+ # ask, do not assume. Where the answer is no, expand as before: that is what keeps this+ # off the math path, which materialises the full [heads, seq, seq] score matrix.+ enable_gqa = attn.num_heads != attn.num_kv_heads and self._serves_grouped_query_attention(+ query, key, value, attention_mask+ )+ if attn.num_heads != attn.num_kv_heads and not enable_gqa:+ repeats = attn.num_heads // attn.num_kv_heads+ key = key.repeat_interleave(repeats, dim=1)+ value = value.repeat_interleave(repeats, dim=1)+hidden_states = F.scaled_dot_product_attention(query, key, value, attn_mask=attention_mask, enable_gqa=enable_gqa)@@ -218,26 +214,16 @@ class Krea2MemoryEfficientAttnProcessor:drop it onto `math` at roughly 9 GB. That is the failure this whole processor exists toavoid, so the answer is asked of the dispatcher rather than inferred from the platform.- The answer depends only on the shape, dtype, device, whether a mask is present, and which- backends this processor permits -- all fixed for a given block within a generation -- so it is- cached, and the query costs nothing after the first call of each kind.+ Must be called inside the `sdpa_policy` window the attention call will run under, and is not+ cached: `can_use_*` gates on the process-global per-backend enable flags, which a cache key+ cannot honestly enumerate -- the same reasoning `util.attention` records for its own probe. A+ stale "no" costs the expansion this function exists to skip for the rest of the generation,+ with nothing logged. Measured at 1.7us per call on the real shape, against 3.5ms for the attention itself."""if not query.is_cuda:# SDPAParams is a CUDA-only interface, and no other backend offers a fused GQA path.return False- cache_key = (- query.shape,- key.shape,- query.dtype,- query.device,- None if attention_mask is None else (attention_mask.shape, attention_mask.dtype),- self.sdpa_backends.backends,- )- cached = self._gqa_support.get(cache_key)- if cached is not None:- return cached-try:params = torch.backends.cuda.SDPAParams(query, key, value, attention_mask, 0.0, False, True)permitted = self.sdpa_backends.backends@@ -253,7 +239,6 @@ class Krea2MemoryEfficientAttnProcessor:# correct everywhere and merely costs memory.supported = False- self._gqa_support[cache_key] = supportedreturn supporteddiff --git a/invokeai/backend/model_manager/load/model_loaders/krea2.py b/invokeai/backend/model_manager/load/model_loaders/krea2.pyindex 7a54b366e5..96ea1a0c70 100644--- a/invokeai/backend/model_manager/load/model_loaders/krea2.py+++ b/invokeai/backend/model_manager/load/model_loaders/krea2.py@@ -51,8 +51,11 @@ from invokeai.backend.quantization.int8_convrot import (cast_unquantized,drop_unconsumed_quantization_sidecars,extract_int8_convrot_markers,+ predict_int8_cast_size,+ reject_foreign_quantization_scales,reject_unmarked_int8_weights,resolve_quantized_module_paths,+ split_int8_convrot_layers,swap_in_int8_linears,)from invokeai.backend.util.devices import TorchDevice@@ -463,13 +466,27 @@ class Krea2CheckpointModel(ModelLoader):model = Krea2Transformer2DModel(**KREA2_TRANSFORMER_CONFIG)if int8_markers:- # int8 payloads are one byte, not two: reserving the compute dtype's width for them- # would ask the cache to free ~12 GB that this load never uses.- # `max(element_size, itemsize)` would charge the compute dtype's width for the int8- # payloads -- `max(1, 2)` is 2 -- which is the doubling this comment exists to avoid.- # `predict_cast_state_dict_size` charges each tensor what it will actually occupy.- new_sd_size = predict_cast_state_dict_size(sd, model_dtype, keep_fp8=False)- self._ram_cache.make_room(new_sd_size)+ # Honor the model's own precision-sensitive list here too, not only on the fp8 side.+ # Krea-2 declares `time_embed` and the `norm*` modules; `time_embed.linear_1/linear_2`+ # are ordinary quantized Linears in a ComfyUI export, and a module that reads its own+ # weight's dtype finds `torch.int8` on an `Int8ConvrotLinear`.+ skip_patterns = _model_declared_skip_patterns(model)++ # Before anything is cast: a scale left over from another scheme means its weight is+ # about to be cast without it, and the orphan disappears into `strict=False` below.+ # After the model exists, so a merged file's bundled submodels -- which this loader does+ # not prefix-filter out and never loads -- cannot fail a checkpoint that works.+ reject_foreign_quantization_scales(sd, quantized, "Krea-2", model)++ # Reserve before the split, not after: the split dequantizes the layers it widens, so+ # reserving afterwards lets that transient land on an unreserved cache. The prediction+ # is given the same inputs, so it charges those layers the compute dtype's width and+ # the int8 payloads their actual one byte -- reserving two would ask the cache to free+ # ~12 GB that this load never uses.+ self._ram_cache.make_room(+ predict_int8_cast_size(sd, model_dtype, quantized, model=model, skip_patterns=skip_patterns)+ )+ quantized = split_int8_convrot_layers(sd, quantized, model_dtype, model=model, skip_patterns=skip_patterns)cast_unquantized(sd, model_dtype, quantized)swap_in_int8_linears(model, sd, quantized)# The fp8 reporting below is keyed on these; an int8 checkpoint keeps neither.@@ -792,7 +809,7 @@ class Qwen3VLEncoderCheckpointLoader(ModelLoader):# Outside the branch on purpose -- see the helper, which explains why. Z-Image has always# had this; Krea-2 did not, so an int8 weight whose marker was missing or unparseable was# cast to the compute dtype as raw codes and loaded silently.- reject_unmarked_int8_weights(sd, int8_markers, "Krea-2")+ reject_unmarked_int8_weights(sd, int8_markers, "Qwen3-VL encoder")if int8_markers:sd = drop_unconsumed_quantization_sidecars(sd)@@ -802,9 +819,11 @@ class Qwen3VLEncoderCheckpointLoader(ModelLoader):source_is_fp8 = Falsefp8_layers = {}keep_matmul_fp8 = False- # An int8 encoder is dense bf16 after `cast_unquantized`, so neither fp8 consumer below- # applies: nothing is fp8-resident to keep, and re-quantizing to fp8 storage would undo- # the un-rotation this path just did.+ # An int8 encoder stays int8-resident, so there is nothing for the fp8 matmul path to+ # keep. The storage pass below is off for a different reason: `_apply_fp8_to_nn_module`+ # casts only `_FP8_SUPPORTED_PYTORCH_LAYERS`, and `Int8ConvrotLinear` is not one of them+ # (nor does it own parameters), so it would walk past every quantized layer and convert+ # only what this path already left dense -- work with no saving on the layers that matter.use_fp8_storage = Falseelse:metadata = read_safetensors_metadata(model_path, self._logger)@@ -840,12 +859,21 @@ class Qwen3VLEncoderCheckpointLoader(ModelLoader):model = Qwen3VLModel._from_config(te_config)if int8_markers:- # int8 payloads are one byte, not two.- # `max(element_size, itemsize)` would charge the compute dtype's width for the int8- # payloads -- `max(1, 2)` is 2 -- which is the doubling this comment exists to avoid.- # `predict_cast_state_dict_size` charges each tensor what it will actually occupy.- new_sd_size = predict_cast_state_dict_size(sd, model_dtype, keep_fp8=False)- self._ram_cache.make_room(new_sd_size)+ # `Qwen3VLModel` declares no precision-sensitive modules, but read them rather than+ # assume: the split is also what keeps a marker on a non-Linear (a "quantize+ # everything" repack's 1-D norms) out of `swap_in_int8_linears`.+ skip_patterns = _model_declared_skip_patterns(model)++ # Before anything is cast: a scale left over from another scheme means its weight is+ # about to be cast without it, and the orphan disappears into `strict=False` below.+ reject_foreign_quantization_scales(sd, quantized, "Qwen3-VL encoder", model)++ # Reserve before the split -- it dequantizes the layers it widens -- and charge the int8+ # payloads their actual one byte rather than the compute dtype's two.+ self._ram_cache.make_room(+ predict_int8_cast_size(sd, model_dtype, quantized, model=model, skip_patterns=skip_patterns)+ )+ quantized = split_int8_convrot_layers(sd, quantized, model_dtype, model=model, skip_patterns=skip_patterns)cast_unquantized(sd, model_dtype, quantized)swap_in_int8_linears(model, sd, quantized)else:diff --git a/invokeai/backend/model_manager/load/model_loaders/minimax_h3.py b/invokeai/backend/model_manager/load/model_loaders/minimax_h3.pyindex 57a60a118d..8483e5590d 100644--- a/invokeai/backend/model_manager/load/model_loaders/minimax_h3.py+++ b/invokeai/backend/model_manager/load/model_loaders/minimax_h3.py@@ -189,7 +189,10 @@ class MiniMaxH3CheckpointModel(ModelLoader):convert_minimax_h3_checkpoint_to_diffusers,read_comfy_quant_markers,)- from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear+ from invokeai.backend.quantization.int8_convrot import (+ INT8_TENSORWISE_FORMAT,+ swap_in_int8_linears,+ )model_path = Path(config.path)@@ -201,9 +204,9 @@ class MiniMaxH3CheckpointModel(ModelLoader):# the ~20 GiB tensor read (the fp8_scaled repacks share this key layout).unsupported = sorted({- str(marker.get("format"))+ str(marker.get("format") or "unreadable")for marker in read_comfy_quant_markers(model_path).values()- if marker.get("format") != "int8_tensorwise"+ if marker.get("format") != INT8_TENSORWISE_FORMAT})if unsupported:@@ -253,20 +256,14 @@ class MiniMaxH3CheckpointModel(ModelLoader):# Swap each quantized nn.Linear for an Int8ConvrotLinear sized from the state dict. Its# persistent buffers are named `weight`/`weight_scale`, so the strict load below consumes- # the quantized tensors directly.+ # the quantized tensors directly. Through the shared helper, not a second copy of it: that+ # is what applies the scale-layout check and reads each marker's own `convrot_groupsize`+ # instead of assuming 256 -- a 64-wide repack derotated with a 256-wide Hadamard runs and+ # generates noise.for module_name, marker in quant_markers.items():- if marker.get("format") != "int8_tensorwise":+ if marker.get("format") != INT8_TENSORWISE_FORMAT:raise ValueError(f"Unsupported comfy_quant format {marker!r} on {module_name}")- parent = model.get_submodule(module_name.rsplit(".", 1)[0])- setattr(- parent,- module_name.rsplit(".", 1)[1],- Int8ConvrotLinear(- weight=sd[module_name + ".weight"],- weight_scale=sd[module_name + ".weight_scale"],- convrot=bool(marker.get("convrot", False)),- ),- )+ swap_in_int8_linears(model, sd, quant_markers)model.load_state_dict(sd, strict=True, assign=True)@@ -274,7 +271,12 @@ class MiniMaxH3CheckpointModel(ModelLoader):# Match the modulation dtype to the LOADED block stack (bf16 from the file), not the# device's preferred compute dtype: on fp16-fallback devices the latter would emit# fp16 modulation into a bf16 stream and promote every block's activations to fp32.- set_curve_modulation_dtype(model, model.context_embedder.weight.dtype)+ #+ # Read off a block norm rather than `context_embedder`, which is an ordinary Linear and+ # so a legitimate quantization target: on an `Int8ConvrotLinear` that reads `torch.int8`+ # and every block would modulate in int8. A norm weight cannot be quantized here -- 1-D+ # weights are refused by the swap above -- so this one is float by the time it is read.+ set_curve_modulation_dtype(model, model.transformer_blocks[0].norm1.weight.dtype)return model@@ -333,7 +335,10 @@ class MiniMaxH3TextEncoderCheckpointModel(ModelLoader):convert_minimax_h3_text_encoder_checkpoint,read_comfy_quant_markers,)- from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear+ from invokeai.backend.quantization.int8_convrot import (+ INT8_TENSORWISE_FORMAT,+ swap_in_int8_linears,+ )model_path = Path(config.path)@@ -341,9 +346,9 @@ class MiniMaxH3TextEncoderCheckpointModel(ModelLoader):# tensor read (the nvfp4_awq repacks share this key layout).unsupported = sorted({- str(marker.get("format"))+ str(marker.get("format") or "unreadable")for marker in read_comfy_quant_markers(model_path).values()- if marker.get("format") != "int8_tensorwise"+ if marker.get("format") != INT8_TENSORWISE_FORMAT})if unsupported:@@ -392,19 +397,12 @@ class MiniMaxH3TextEncoderCheckpointModel(ModelLoader):# for this Identity before accepting a truncated encoder.model.model.language_model.norm = torch.nn.Identity()+ # Shared helper, not a second copy: it applies the scale-layout check and reads each+ # marker's own `convrot_groupsize` rather than assuming 256.for module_name, marker in quant_markers.items():- if marker.get("format") != "int8_tensorwise":+ if marker.get("format") != INT8_TENSORWISE_FORMAT:raise ValueError(f"Unsupported comfy_quant format {marker!r} on {module_name}")- parent = model.get_submodule(module_name.rsplit(".", 1)[0])- setattr(- parent,- module_name.rsplit(".", 1)[1],- Int8ConvrotLinear(- weight=sd[module_name + ".weight"],- weight_scale=sd[module_name + ".weight_scale"],- convrot=bool(marker.get("convrot", False)),- ),- )+ swap_in_int8_linears(model, sd, quant_markers)missing, unexpected = model.load_state_dict(sd, strict=False, assign=True)if unexpected:diff --git a/invokeai/backend/model_manager/load/model_loaders/minimax_h3_state_dict_utils.py b/invokeai/backend/model_manager/load/model_loaders/minimax_h3_state_dict_utils.pyindex 42069a7006..e5eed5ead4 100644--- a/invokeai/backend/model_manager/load/model_loaders/minimax_h3_state_dict_utils.py+++ b/invokeai/backend/model_manager/load/model_loaders/minimax_h3_state_dict_utils.py@@ -34,7 +34,7 @@ from typing import Anyimport torch-from invokeai.backend.quantization.int8_convrot import parse_comfy_quant_marker+from invokeai.backend.quantization.int8_convrot import parse_comfy_quant_bytes, parse_comfy_quant_markerdef read_comfy_quant_markers(path: Path) -> dict[str, dict[str, Any]]:@@ -43,6 +43,11 @@ def read_comfy_quant_markers(path: Path) -> dict[str, dict[str, Any]]:Lets the loader reject unsupported quantization formats (e.g. the fp8_scaled repacks, whichshare this key layout) before committing to a ~20 GiB read.++ Marker bytes go through the same tolerant parser the state-dict readers use. This reader runs+ FIRST, so a strict parse here is what a NUL-padded marker -- which Comfy writes, and which that+ parser exists to absorb -- would actually hit: a `JSONDecodeError` out of the middle of a load,+ naming neither the file nor the key."""markers: dict[str, dict[str, Any]] = {}with open(path, "rb") as f:@@ -54,7 +59,7 @@ def read_comfy_quant_markers(path: Path) -> dict[str, dict[str, Any]]:continuestart, end = entry["data_offsets"]f.seek(8 + header_len + start)- markers[key[: -len(".comfy_quant")]] = json.loads(f.read(end - start).decode("utf-8"))+ markers[key[: -len(".comfy_quant")]] = parse_comfy_quant_bytes(f.read(end - start))return markersdiff --git a/invokeai/backend/model_manager/load/model_loaders/z_image.py b/invokeai/backend/model_manager/load/model_loaders/z_image.pyindex 9ee8ec6ede..d008478129 100644--- a/invokeai/backend/model_manager/load/model_loaders/z_image.py+++ b/invokeai/backend/model_manager/load/model_loaders/z_image.py@@ -63,7 +63,9 @@ from invokeai.backend.quantization.int8_convrot import (cast_unquantized,drop_unconsumed_quantization_sidecars,extract_int8_convrot_markers,+ predict_int8_cast_size,reject_unmarked_int8_weights,+ split_int8_convrot_layers,swap_in_int8_linears,)from invokeai.backend.quantization.sdnq.detection import is_sdnq_folder@@ -569,16 +571,28 @@ class ZImageCheckpointModel(ModelLoader):sd.update(kept_sd)del kept_sd- # int8 payloads are one byte, not two: reserving the compute dtype's width for them- # would ask the cache to free memory this load never uses.- # `max(element_size, itemsize)` would charge the compute dtype's width for the int8- # payloads -- `max(1, 2)` is 2 -- which is the doubling this comment exists to avoid.- # `predict_cast_state_dict_size` charges each tensor what it will actually occupy.- new_sd_size = predict_cast_state_dict_size(sd, model_dtype, keep_fp8=False)- self._ram_cache.make_room(new_sd_size)+ # Honor the model's own precision-sensitive list here too, not only on the fp8 side.+ # Z-Image declares ["t_embedder", "cap_embedder"] because+ # `ZImageTimestepEmbedder.forward` reads `self.mlp[0].weight.dtype` to pick the dtype+ # it casts its activations to; on an `Int8ConvrotLinear` that reads `torch.int8`, the+ # forward falls through to a `compute_dtype` attribute these modules do not have, and+ # the timestep branch silently runs in float32 into a bf16 model.+ skip_patterns = _model_declared_skip_patterns(model)- cast_unquantized(sd, model_dtype, int8_markers)- swap_in_int8_linears(model, sd, int8_markers)+ # Reserve before the split, not after: the split dequantizes the layers it widens, so+ # reserving afterwards lets that transient land on an unreserved cache. The prediction+ # is given the same inputs, so it charges those layers the compute dtype's width and+ # the int8 payloads their actual one byte -- reserving two would ask the cache to free+ # memory this load never uses.+ self._ram_cache.make_room(+ predict_int8_cast_size(sd, model_dtype, int8_markers, model=model, skip_patterns=skip_patterns)+ )++ quantized = split_int8_convrot_layers(+ sd, int8_markers, model_dtype, model=model, skip_patterns=skip_patterns+ )+ cast_unquantized(sd, model_dtype, quantized)+ swap_in_int8_linears(model, sd, quantized)# The fp8 reporting below is keyed on these; an int8 checkpoint keeps neither.fp8_layers: dict[str, Any] = {}kept = 0diff --git a/invokeai/backend/quantization/fp8_scaled.py b/invokeai/backend/quantization/fp8_scaled.pyindex c14340fc88..b59a03a45e 100644--- a/invokeai/backend/quantization/fp8_scaled.py+++ b/invokeai/backend/quantization/fp8_scaled.py@@ -822,8 +822,13 @@ def survives_split_and_cast(return layer is None or is_matmul_usable_scale(tensor, layer.weight_scale)-def _is_castable_float(tensor: Any) -> bool:- """Whether ``tensor`` is a floating-point payload that may be cast to the compute dtype."""+def is_castable_float(tensor: Any) -> bool:+ """Whether ``tensor`` is a floating-point payload that may be cast to the compute dtype.++ Public because the int8 path's own cast (``int8_convrot.cast_unquantized``) owes the state dict+ the same guarantee and must not carry a second copy of this predicate: the two casts differ in+ which *quantized* payloads they pin, never in what counts as a float.+ """is_floating_point = getattr(tensor, "is_floating_point", None)if not callable(is_floating_point):return False@@ -861,7 +866,7 @@ def cast_state_dict(if keep_fp8 and can_stay_quantized(key, tensor, model, patterns):kept += 1continue- if not _is_castable_float(tensor):+ if not is_castable_float(tensor):# Integer payloads (embedding indices, packed buffers) are not weights and must keep# their dtype. Loaders used to guard this themselves; centralizing it here means a# loader that switches to `cast_state_dict` does not silently lose the guard.@@ -897,7 +902,7 @@ def predict_cast_state_dict_size(total = 0for key, tensor in sd.items():stays = keep_fp8 and survives_split_and_cast(key, tensor, model, patterns, scaled_layer_for(key, scaled_layers))- if stays or not _is_castable_float(tensor):+ if stays or not is_castable_float(tensor):total += tensor.nelement() * tensor.element_size()else:total += tensor.nelement() * dtype.itemsizediff --git a/invokeai/backend/quantization/int8_convrot.py b/invokeai/backend/quantization/int8_convrot.pyindex cbbfc579f8..a505661ebc 100644--- a/invokeai/backend/quantization/int8_convrot.py+++ b/invokeai/backend/quantization/int8_convrot.py@@ -29,17 +29,26 @@ weight and scale resident (4.6x smaller than bf16) and materializes thedequantized, derotated bf16 weight per forward call. The derotation is a``[out, in/256, 256] @ [256, 256]`` matmul — a rounding error next to thetransformer forward itself — and the transient bf16 weight (<= ~310 MB for H3's-largest layer) has to fit inside the calling node's working-memory reservation.+largest layer) has to fit inside the calling node's working-memory reservation:+``peak_int8_dequant_transient_bytes`` is what a denoise node adds to its estimate+for that, since the model's resident size does not account for it."""import json-from collections.abc import Mapping+from collections.abc import Iterable, Mappingfrom typing import Anyimport torchimport torch.nn.functional as Ffrom invokeai.backend.model_manager.taxonomy import ModelFormat+from invokeai.backend.quantization.fp8_scaled import (+ COMFY_QUANT_SUFFIX,+ FP8_WEIGHT_DTYPES,+ INPUT_SCALE_SUFFIXES,+ WEIGHT_SCALE_SUFFIXES,+ is_castable_float,+)CONVROT_GROUP_SIZE = 256@@ -47,11 +56,26 @@ _HADAMARD_SEED = ((1, 1, 1, -1), (1, 1, -1, 1), (1, -1, 1, 1), (-1, 1, 1, 1))INT8_TENSORWISE_FORMAT = "int8_tensorwise"+# Per-layer side-channel entries the int8 path reads elsewhere or cannot use at all; see+# `drop_unconsumed_quantization_sidecars`.+_UNCONSUMED_SIDECAR_SUFFIXES = (COMFY_QUANT_SUFFIX, *INPUT_SCALE_SUFFIXES)-def build_regular_hadamard(size: int, dtype: torch.dtype = torch.float32) -> torch.Tensor:- """Normalized regular Hadamard matrix of a power-of-4 size (CPU tensor)."""++def check_hadamard_size(size: int) -> None:+ """Refuse a rotation width this scheme has no Hadamard for.++ Called at *construction* as well as at build time. The matrix itself is now minted lazily on+ the first forward, so without this a checkpoint declaring, say, ``convrot_groupsize: 512`` --+ a power of 2, not of 4, and divisible into plenty of real layer widths -- would load, cache and+ reach VRAM, then raise out of the middle of generation with no layer or file named.+ """if size < 4 or (size & (size - 1)) != 0 or (size.bit_length() - 1) % 2 != 0:raise ValueError(f"Regular Hadamard size must be a power of 4, got {size}")+++def build_regular_hadamard(size: int, dtype: torch.dtype = torch.float32) -> torch.Tensor:+ """Normalized regular Hadamard matrix of a power-of-4 size (CPU tensor)."""+ check_hadamard_size(size)h4 = torch.tensor(_HADAMARD_SEED, dtype=torch.float64)h = h4while h.shape[0] < size:@@ -59,8 +83,46 @@ def build_regular_hadamard(size: int, dtype: torch.dtype = torch.float32) -> torreturn (h / (size**0.5)).to(dtype)-def parse_comfy_quant_marker(blob: torch.Tensor) -> dict:- """Decode a ``<layer>.comfy_quant`` uint8 tensor into its JSON dict, or ``{}``.+# One derotation matrix per (size, device, dtype), shared by every layer that needs it.+#+# The matrix is a constant of the scheme, so a per-module copy was pure duplication: Krea-2's+# transformer has 264 Linears and the Qwen3-VL encoder several hundred more, at a 256x256 fp32+# buffer (262144 bytes) each. That cost was paid three times over:+#+# - 69 MB / ~92 MB of byte-identical RAM, charged to the cache entry by `calc_module_size`, which+# sums `model.buffers()`;+# - the same again on the compute device and NOT charged, because `CachedModelWithPartialLoad`+# sizes itself from `model.state_dict()` and a non-persistent buffer is not in it -- while+# `_move_non_persistent_buffers_to_device` copies every one of them to the device on each lock;+# - a fresh `.to(dtype)` copy per layer per forward, since the buffer was fp32 and compute is+# bf16: tens of thousands of identical 128 KB allocations over a 50-step generation.+#+# Lifetime: entries are minted on demand and never evicted, and nothing here is tied to a model's+# lifetime -- an entry outliving the model that minted it is reused by the next load on the same+# device. The bound is the set of group sizes checkpoints actually declare (256 in every build+# seen; 64 is expressible) times the compute device and dtype, i.e. a handful of <=256 KB tensors+# for the life of the process. A checkpoint declaring an absurd group size would pin more, but it+# runs into `build_regular_hadamard` first, whose fp64 Kronecker build of the same matrix is the+# larger cost by far.+_HADAMARD_CACHE: dict[tuple[int, torch.device, torch.dtype], torch.Tensor] = {}+++def shared_regular_hadamard(size: int, device: torch.device, dtype: torch.dtype) -> torch.Tensor:+ """The derotation matrix for ``size``, shared across every layer using it on ``(device, dtype)``.++ Returned tensors are shared and must be treated as read-only. :func:`build_regular_hadamard`+ stays pure and is what callers building their own (e.g. a quantizer's forward rotation) use.+ """+ key = (size, device, dtype)+ matrix = _HADAMARD_CACHE.get(key)+ if matrix is None:+ matrix = build_regular_hadamard(size, dtype).to(device=device)+ _HADAMARD_CACHE[key] = matrix+ return matrix+++def parse_comfy_quant_bytes(raw: bytes) -> dict:+ """Decode the raw bytes of a ``<layer>.comfy_quant`` blob into its JSON dict, or ``{}``.Tolerant on purpose, and it has to be: this runs over *every* marker in the file before theloader knows which format it is dealing with, so a blob belonging to some other scheme decides@@ -70,15 +132,26 @@ def parse_comfy_quant_marker(blob: torch.Tensor) -> dict:A malformed marker is a lost hint, never a failed load: an int8 weight whose marker did notparse is then caught by the orphan check in the loaders, which says what is wrong.++ Takes bytes rather than a tensor so the safetensors *header* reader -- which seeks to a blob's+ offsets and never materializes a tensor -- reads markers the same way the state-dict readers do."""try:- text = bytes(blob.cpu().numpy().tobytes()).decode("utf-8", errors="replace").rstrip("\x00")- parsed = json.loads(text)+ parsed = json.loads(raw.decode("utf-8", errors="replace").rstrip("\x00"))except Exception:return {}return parsed if isinstance(parsed, dict) else {}+def parse_comfy_quant_marker(blob: torch.Tensor) -> dict:+ """Decode a ``<layer>.comfy_quant`` uint8 tensor into its JSON dict, or ``{}``."""+ try:+ raw = blob.cpu().numpy().tobytes()+ except Exception:+ return {}+ return parse_comfy_quant_bytes(raw)++def as_column_scale(weight: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:"""A per-output-channel scale shaped `[out, 1]`, so it multiplies down the rows.@@ -89,8 +162,13 @@ def as_column_scale(weight: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:mismatch that names neither the layer nor the cause.A scalar, `[1]` or `[1, 1]` is per-tensor and broadcasts correctly as it is.++ Only for a 2-D weight. On a 1-D one -- the quantized norms a "quantize everything" repack ships+ -- a `[N]` scale is already elementwise, and making it `[N, 1]` broadcasts `[N] * [N, 1]` into an+ `[N, N]` matrix: a weight the model cannot load and, before it gets there, an allocation the+ load never reserved for (a 3072-wide norm becomes 9.4M elements)."""- if scale.dim() == 1 and scale.shape[0] == weight.shape[0]:+ if weight.dim() == 2 and scale.dim() == 1 and scale.shape[0] == weight.shape[0]:return scale.unsqueeze(1)return scale@@ -108,7 +186,7 @@ def dequantize_convrot_weight(out_features, in_features = w.shapeif in_features % group_size != 0:raise ValueError(f"convrot weight in_features {in_features} not divisible by {group_size}")- h = build_regular_hadamard(group_size).to(device=w.device)+ h = shared_regular_hadamard(group_size, w.device, w.dtype)w = (w.view(out_features, in_features // group_size, group_size) @ h).view(out_features, in_features)return w.to(dtype)@@ -119,7 +197,9 @@ class Int8ConvrotLinear(torch.nn.Module):The int8 weight and fp32 scale are registered as PERSISTENT buffers named ``weight`` and``weight_scale`` — exactly the converted checkpoint's key names — so ``load_state_dict``consumes the quantized tensors directly and the model cache moves them between devices- like any other weight. The Hadamard matrix is computed, not loaded (non-persistent).+ like any other weight. The Hadamard matrix is neither loaded nor held per module: it is a+ constant of the scheme, so ``forward`` takes it from :func:`shared_regular_hadamard`, which+ keeps one per ``(size, device, dtype)`` for every layer in the model.The model cache wraps this module as ``CustomInt8ConvrotLinear`` (see``AUTOCAST_MODULE_TYPE_MAPPING``), which enables sidecar LoRA patches and lets a partial@@ -147,11 +227,9 @@ class Int8ConvrotLinear(torch.nn.Module):self.register_buffer("weight", weight)self.register_buffer("weight_scale", weight_scale.to(torch.float32))if convrot:+ check_hadamard_size(group_size)if self.in_features % group_size != 0:raise ValueError(f"convrot weight in_features {self.in_features} not divisible by {group_size}")- self.register_buffer("hadamard", build_regular_hadamard(group_size), persistent=False)- else:- self.hadamard = Noneif bias is not None:self.register_buffer("bias", bias)else:@@ -171,10 +249,9 @@ class Int8ConvrotLinear(torch.nn.Module):scale = as_column_scale(self.weight, self.weight_scale).to(device=device, dtype=dtype)w = self.weight.to(device=device, dtype=dtype) * scaleif self.convrot:- assert self.hadamard is not Nonew = (w.view(self.out_features, self.in_features // self.group_size, self.group_size)- @ self.hadamard.to(device=device, dtype=dtype)+ @ shared_regular_hadamard(self.group_size, device, dtype)).view(self.out_features, self.in_features)return w@@ -199,11 +276,11 @@ def extract_int8_convrot_markers(sd: dict[str, Any]) -> dict[str, dict[str, Any]:class:`Int8ConvrotLinear`, which is what every loader here does."""markers = {}- for key in [k for k in sd if isinstance(k, str) and k.endswith(".comfy_quant")]:+ for key in [k for k in sd if isinstance(k, str) and k.endswith(COMFY_QUANT_SUFFIX)]:marker = parse_comfy_quant_marker(sd[key])if marker.get("format") != INT8_TENSORWISE_FORMAT:continue- markers[key[: -len(".comfy_quant")]] = marker+ markers[key[: -len(COMFY_QUANT_SUFFIX)]] = markerdel sd[key]return markers@@ -216,11 +293,18 @@ def check_int8_scale_layout(path: str, weight: torch.Tensor, scale: torch.Tensorblockwise grid instead - a 6144x6144 weight with a ``[48, 48]`` scale is a 128x128 block grid -which needs a different multiply. Left to broadcasting that either raises somewhere lessinformative or, for an unlucky shape, silently scales the wrong axis.++ What counts as per-output-channel depends on the weight's rank, and getting that wrong is the+ same silent failure by another route. On a 1-D weight only ``[N]`` is elementwise; ``[N, 1]``+ broadcasts to ``[N, N]``. Above rank 2 there is no output-channel axis this decode can name, so+ only a per-tensor scale is accepted rather than guessing which axis the producer meant."""- rows = weight.shape[0] if weight.dim() else 1- if scale.dim() == 0 or tuple(scale.shape) in {(1,), (1, 1)}:- return- if tuple(scale.shape) in {(rows,), (rows, 1)}:+ per_channel: set[tuple[int, ...]] = set()+ if weight.dim() == 2:+ per_channel = {(weight.shape[0],), (weight.shape[0], 1)}+ elif weight.dim() == 1:+ per_channel = {(weight.shape[0],)}+ if scale.dim() == 0 or tuple(scale.shape) in {(1,), (1, 1)} or tuple(scale.shape) in per_channel:returnraise ValueError(f"'{path}' has a {tuple(scale.shape)} scale for a {tuple(weight.shape)} weight, which is "@@ -240,8 +324,19 @@ def reject_unmarked_int8_weights(sd: dict[str, Any], markers: Mapping[str, Any],That tolerance is deliberate and this is its other half: a malformed marker is a lost hint, andthis is what stops the loss from being silent.++ Only a ``<path>.weight`` a marker names is exempt. Slicing seven characters off every int8 key+ regardless of its suffix truncates unrelated ones: ``foo.qkv.scales`` becomes ``foo.qkv``, so a+ marker on the *weight* at ``foo.qkv`` exempted a packed sidecar the decode never places, and a+ key shorter than the suffix collapses to the empty string. An int8 tensor under any name but a+ marked ``.weight`` is a payload this decode cannot place, and saying so is the whole point."""- orphans = sorted(k for k, v in sd.items() if v.dtype is torch.int8 and k[: -len(".weight")] not in markers)+ orphans = sorted(+ k+ for k, v in sd.items()+ if v.dtype is torch.int8+ and not (isinstance(k, str) and k.endswith(".weight") and k[: -len(".weight")] in markers)+ )if orphans:raise ValueError(f"{architecture} checkpoint has {len(orphans)} int8 weight(s) with no `comfy_quant` marker, "@@ -278,12 +373,11 @@ def drop_unconsumed_quantization_sidecars(sd: dict[str, Any]) -> dict[str, Any]:`load_state_dict(strict=False)` would ignore them, but they are still cast and still countedagainst the RAM reservation - and a loader that later switches to strict would fail on them.++ Matched as whole suffixes, not substrings: a module legitimately named ``...input_scaler`` owns+ a real ``.weight``, and dropping it surfaces under Z-Image's strict load as a missing key."""- return {- k: v- for k, v in sd.items()- if not (isinstance(k, str) and (k.endswith(".comfy_quant") or "input_scale" in k or "scale_input" in k))- }+ return {k: v for k, v in sd.items() if not (isinstance(k, str) and k.endswith(_UNCONSUMED_SIDECAR_SUFFIXES))}def resolve_quantized_module_paths(@@ -303,6 +397,174 @@ def resolve_quantized_module_paths(return resolved+def _resolve_int8_target(model: torch.nn.Module, path: str) -> tuple[torch.nn.Module, str]:+ """The owner and attribute name of the module a marker names, as ``setattr`` needs them.++ Refuses anything an ``Int8ConvrotLinear`` cannot stand in for. Without this, a marker naming a+ module the built model lacks leaves ``get_submodule`` to raise a bare ``AttributeError`` out of+ the middle of a load, and a marker on a non-Linear (an ``nn.Embedding``, say) installs a linear+ in its place and only fails much later inside that module's forward.+ """+ parent_path, _, attribute = path.rpartition(".")+ try:+ parent = model.get_submodule(parent_path) if parent_path else model+ target = getattr(parent, attribute)+ except AttributeError:+ raise ValueError(+ f"'{path}' is marked int8_tensorwise but the built model has no such module. The "+ "checkpoint is misidentified, or its keys need a conversion this loader did not apply."+ ) from None+ if not isinstance(target, torch.nn.Linear):+ raise ValueError(+ f"'{path}' is marked int8_tensorwise but is a {type(target).__name__}, not an nn.Linear. "+ "Only a Linear weight can be kept in int8 storage."+ )+ return parent, attribute+++def _can_stay_int8(path: str, weight: Any, model: torch.nn.Module | None, skip_patterns: Iterable[str] = ()) -> bool:+ """Whether a marked layer may keep its int8 storage instead of being dequantized on load.++ Single source of truth for that decision, so :func:`split_int8_convrot_layers` and+ :func:`predict_int8_cast_size` cannot drift: the loaders reserve RAM against the prediction and+ then run the split, and a layer the split widens but the prediction charged 1 byte/element for+ is a reservation that is short by exactly that layer.++ Deliberately not shared with :func:`fp8_scaled._is_fp8_matmul_weight`, which asks a similar+ question: that one admits any weight of rank >= 2 (an fp8 Conv weight is usable), keys off the+ state-dict key rather than the module path, and treats a marker naming a module the model lacks+ as "cannot stay quantized". All three differ here, so sharing it would mean two policy+ parameters used once each.++ Two filters, both of which the fp8 path applies for the same reasons:++ - Only a 2-D ``nn.Linear`` weight. Repacks that "quantize everything" ship 1-D quantized norms;+ there is no linear for those to become, and an int8 norm weight would flow into the+ activations as raw codes.+ - Never a module the model declares precision-sensitive (``skip_patterns``, i.e. diffusers'+ ``_skip_layerwise_casting_patterns`` / ``_keep_in_fp32_modules``). Z-Image's+ ``ZImageTimestepEmbedder.forward`` reads ``self.mlp[0].weight.dtype`` to pick the dtype it+ casts its activations to; on an ``Int8ConvrotLinear`` that reads ``torch.int8``, the forward+ falls through to a ``compute_dtype`` attribute these modules do not have, and the timestep+ branch silently runs in float32 and hands a float32 embedding to a bf16 model.+ """+ if getattr(weight, "dim", None) is None or weight.dim() != 2:+ return False+ if any(pattern in path for pattern in skip_patterns):+ return False+ if model is None:+ # No model to resolve against: the 2-D test above is the safe subset. A marker naming a+ # module the model lacks is not silently dropped here — `swap_in_int8_linears` names it.+ return True+ try:+ return isinstance(model.get_submodule(path), torch.nn.Linear)+ except AttributeError:+ return True+++def split_int8_convrot_layers(+ sd: dict[str, Any],+ quantized: dict[str, dict[str, Any]],+ dtype: torch.dtype,+ *,+ model: torch.nn.Module | None = None,+ skip_patterns: Iterable[str] = (),+) -> dict[str, dict[str, Any]]:+ """Dequantize in place the marked layers that cannot stay int8; return the ones that can.++ Mirrors :func:`split_fp8_scaled_layers`. Every layer this widens is one+ :func:`swap_in_int8_linears` must not be handed: it would either install an+ ``Int8ConvrotLinear`` where the model wants something else, or leave a precision-sensitive+ module reporting ``torch.int8`` as its weight dtype to a forward that branches on it.++ Dequantizing rather than refusing is deliberate, and is what the fp8 path does: the scale and+ rotation are both present, so the decode is unambiguous, and the affected tensors are the small+ ones (norms, timestep MLPs). Refusing would reject a checkpoint that loads correctly for the+ sake of a saving measured in megabytes.+ """+ surviving = _surviving_int8_layers(sd, quantized, model, skip_patterns)+ for path, marker in quantized.items():+ if path in surviving:+ continue+ weight, scale = sd[f"{path}.weight"], sd[f"{path}.weight_scale"]+ check_int8_scale_layout(path, weight, scale)+ convrot = bool(marker.get("convrot", False))+ if convrot and weight.dim() != 2:+ raise ValueError(+ f"'{path}' is marked convrot but its weight is {tuple(weight.shape)}. The rotation is "+ "defined over a weight's input dimension, so there is nothing to un-rotate here."+ )+ sd[f"{path}.weight"] = dequantize_convrot_weight(+ weight, scale, convrot, dtype, int(marker.get("convrot_groupsize", CONVROT_GROUP_SIZE))+ )+ del sd[f"{path}.weight_scale"]+ return surviving+++def predict_int8_cast_size(+ sd: Mapping[str, Any],+ dtype: torch.dtype,+ quantized: dict[str, dict[str, Any]],+ *,+ model: torch.nn.Module | None = None,+ skip_patterns: Iterable[str] = (),+) -> int:+ """Bytes the state dict will occupy once the split and :func:`cast_unquantized` have run.++ Loaders call this to size their ``make_room()`` reservation, and call it *before* the split so+ that the tensors the split widens are already reserved for when they appear. (The split's own+ per-layer fp32 transient is absorbed by that reservation's slack rather than modelled: it runs+ one widened layer at a time, and the widened set is by construction the small one -- skip-pattern+ and non-Linear layers.)++ Three widths are in play and only one of them is ``dtype.itemsize``. A payload that stays int8+ occupies one byte, and charging it two asks the cache to free ~12 GB a Krea-2 build never uses.+ A pinned ``weight_scale`` stays fp32, and charging it two under-counts it by half. A payload the+ split is about to dequantize arrives at ``dtype.itemsize`` while its scale disappears into it,+ and charging that one byte is the direction that actually hurts: the reservation comes up short+ by exactly the layers the split widened.+ """+ surviving = _surviving_int8_layers(sd, quantized, model, skip_patterns)+ pinned = _pinned_quantized_keys(surviving)+ widening = {path: marker for path, marker in quantized.items() if path not in surviving}+ dequantized_weights = {f"{path}.weight" for path in widening}+ consumed_scales = {f"{path}.weight_scale" for path in widening}++ total = 0+ for key, tensor in sd.items():+ if key in consumed_scales:+ # Folded into its weight by the split and dropped from the dict.+ continue+ if key in pinned or (key not in dequantized_weights and not is_castable_float(tensor)):+ total += tensor.nelement() * tensor.element_size()+ else:+ total += tensor.nelement() * dtype.itemsize+ return total+++def _surviving_int8_layers(+ sd: Mapping[str, Any],+ quantized: dict[str, dict[str, Any]],+ model: torch.nn.Module | None,+ skip_patterns: Iterable[str],+) -> dict[str, dict[str, Any]]:+ """The marked layers the split will leave int8. Shared so the split and the prediction of what+ it costs are the same decision, evaluated twice."""+ patterns = tuple(skip_patterns)+ surviving: dict[str, dict[str, Any]] = {}+ for path, marker in quantized.items():+ weight, scale = sd.get(f"{path}.weight"), sd.get(f"{path}.weight_scale")+ # A missing half is not this decision to make: `swap_in_int8_linears` names which one.+ if weight is None or scale is None or _can_stay_int8(path, weight, model, patterns):+ surviving[path] = marker+ return surviving+++def _pinned_quantized_keys(quantized: Mapping[str, Any]) -> set[str]:+ """The state-dict keys that must reach ``load_state_dict`` exactly as stored."""+ return {key for path in quantized for key in (f"{path}.weight", f"{path}.weight_scale")}++def swap_in_int8_linears(model: torch.nn.Module, sd: dict[str, Any], quantized: dict[str, dict[str, Any]]) -> None:"""Replace each quantized ``nn.Linear`` with an ``Int8ConvrotLinear`` sized from the state dict.@@ -313,6 +575,9 @@ def swap_in_int8_linears(model: torch.nn.Module, sd: dict[str, Any], quantized:Its persistent buffers are named ``weight``/``weight_scale`` -- the checkpoint's own spelling --so the ``load_state_dict`` that follows assigns the quantized tensors straight into them.++ Pass only what :func:`split_int8_convrot_layers` returned: every layer refused below is one that+ split would have dequantized instead."""for path, marker in quantized.items():weight, scale = sd.get(f"{path}.weight"), sd.get(f"{path}.weight_scale")@@ -321,10 +586,15 @@ def swap_in_int8_linears(model: torch.nn.Module, sd: dict[str, Any], quantized:f"'{path}' is marked int8_tensorwise but is missing its "f"{'weight' if weight is None else 'weight_scale'}.")+ if weight.dim() != 2:+ raise ValueError(+ f"'{path}' is marked int8_tensorwise but its weight is {tuple(weight.shape)}, not 2-D. "+ "Only a Linear weight can be kept in int8 storage; dequantize this one instead."+ )check_int8_scale_layout(path, weight, scale)- parent_path, _, attribute = path.rpartition(".")+ parent, attribute = _resolve_int8_target(model, path)setattr(- model.get_submodule(parent_path) if parent_path else model,+ parent,attribute,Int8ConvrotLinear(weight=weight,@@ -337,12 +607,94 @@ def swap_in_int8_linears(model: torch.nn.Module, sd: dict[str, Any], quantized:def cast_unquantized(sd: dict[str, Any], dtype: torch.dtype, quantized: dict[str, dict[str, Any]]) -> None:- """Cast the dense tensors to the compute dtype, leaving the quantized payloads alone.+ """Cast the dense float tensors to the compute dtype, leaving the quantized payloads alone.An int8 weight cast to bf16 is no longer int8, and its float32 scale is what``Int8ConvrotLinear`` multiplies by -- both have to reach ``load_state_dict`` as stored.++ Integer payloads (embedding indices, packed buffers, bool masks) are not weights and keep their+ dtype, exactly as :func:`cast_state_dict` leaves them: an index buffer installed as a float+ raises ``IndexError: tensors used as indices must be long, byte or bool`` inside the forward,+ and a bool mask cast to bf16 changes what the mask means without raising at all."""- pinned = {key for path in quantized for key in (f"{path}.weight", f"{path}.weight_scale")}+ pinned = _pinned_quantized_keys(quantized)for key in sd:- if key not in pinned:+ if key not in pinned and is_castable_float(sd[key]):sd[key] = sd[key].to(dtype)+++def reject_foreign_quantization_scales(+ sd: Mapping[str, Any], quantized: Mapping[str, Any], architecture: str, model: torch.nn.Module+) -> None:+ """Refuse a weight scale belonging to a quantization scheme this branch does not run.++ The mirror image of :func:`reject_unmarked_int8_weights`, and the enforcement of the premise+ these loaders decide on once per file: ``int8_tensorwise`` and ComfyUI's scaled fp8 share this+ key layout, and a checkpoint carries one or the other. Inside the int8 branch the whole fp8+ pipeline is skipped, so a layer of the other scheme is cast to the compute dtype *without* its+ scale -- off by ``1/weight_scale`` -- while the orphaned scale is dropped by ``strict=False``+ and says nothing. The premise was documented and never checked.++ Checked here rather than against ``load_state_dict``'s unexpected keys, which would also reject+ the benign extras ``strict=False`` exists to tolerate. Two filters keep it to weights that are+ genuinely about to load wrong, because the failure is fatal and a false positive costs a user a+ checkpoint that worked:++ - The scale's weight must *actually* be float8. These loaders do not prefix-filter the state+ dict, so a merged single file's bundled text encoder is in ``sd`` too, and a dtype test is+ what tells a foreign quantized layer from a foreign dense one.+ - ``model`` must actually have the module. A merged file may bundle a scaled-fp8 *submodel*+ beside the int8 transformer -- an all-in-one ComfyUI export is exactly that -- and those keys+ are discarded by ``strict=False`` rather than loaded, so they cannot load unscaled and are not+ this loader's business. Only a weight this model consumes can be corrupted by the cast.++ A raw fp8 weight with no scale at all is not an orphan and needs none -- e4m3fn is a subset of+ bf16, so casting it is value-exact.++ Call with ``sd`` and ``quantized`` in the same key space as ``model``, i.e. after any key+ conversion and before the cast.+ """+ consumed = {name for name, _ in model.named_modules()}+ orphans = sorted(+ key+ for key in sd+ if isinstance(key, str)+ and key.endswith(WEIGHT_SCALE_SUFFIXES)+ and key.rsplit(".", 1)[0] not in quantized+ and key.rsplit(".", 1)[0] in consumed+ and getattr(sd.get(f"{key.rsplit('.', 1)[0]}.weight"), "dtype", None) in FP8_WEIGHT_DTYPES+ )+ if orphans:+ raise ValueError(+ f"{architecture} checkpoint has {len(orphans)} float8 weight scale(s) that no "+ f"`int8_tensorwise` marker claims, e.g. {orphans[:3]}. A file mixing int8_tensorwise "+ "with scaled fp8 is not supported: the fp8 weights would load unscaled."+ )+++def peak_int8_dequant_transient_bytes(model: torch.nn.Module, compute_dtype: torch.dtype) -> int:+ """Peak bytes one forward transiently needs to dequantize this model's int8 linears.++ ``Int8ConvrotLinear`` keeps its weight int8 and materializes the dequantized, derotated weight+ per forward, so that transient is *not* covered by the model's resident size and has to fit+ inside the calling node's working-memory reservation. Zero when the model holds no such layer.++ Two weight-sized tensors in the compute dtype, over the largest such layer. Both halves of+ ``_dequantized_weight`` peak at two: the dtype cast of the int8 weight is alive alongside the+ product it is multiplied into, and that product is then alive alongside the derotation matmul's+ output. Each pair is freed before the next allocates, and the layers run one at a time.++ Under partial load the int8 weight is additionally streamed to the device per call, adding up to+ half a weight again; the resident-model regime this scheme targets pays nothing for that.++ What it does not cover is the matmul's own cuBLAS workspace, which is not a property of this+ scheme -- a dense Linear of the same shape allocates it too, and the node's activation estimate+ is measured with it included. Verified against the real `z_image_turbo_int8_convrot` checkpoint:+ exact for most shapes, and 2 MiB under on the two that make cuBLAS take a workspace+ (10240x3840 and 3840x10240), against a 3 GiB reservation floor.+ """+ largest = 0+ for module in model.modules():+ if isinstance(module, Int8ConvrotLinear):+ largest = max(largest, module.in_features * module.out_features)+ return 2 * largest * compute_dtype.itemsizediff --git a/invokeai/backend/stable_diffusion/vae_tiling.py b/invokeai/backend/stable_diffusion/vae_tiling.pyindex d31cb331f4..24a0e868e9 100644--- a/invokeai/backend/stable_diffusion/vae_tiling.py+++ b/invokeai/backend/stable_diffusion/vae_tiling.py@@ -3,12 +3,13 @@ from contextlib import contextmanagerfrom diffusers.models.autoencoders.autoencoder_kl import AutoencoderKLfrom diffusers.models.autoencoders.autoencoder_tiny import AutoencoderTiny+from invokeai.backend.util.vae_tiling_scope import diffusers_latent_tile, diffusers_vae_downsample+@contextmanagerdef patch_vae_tiling_params(vae: AutoencoderKL | AutoencoderTiny,tile_sample_min_size: int,- tile_latent_min_size: int,tile_overlap_factor: float,):"""Patch the parameters that control the VAE tiling tile size and overlap.@@ -16,16 +17,31 @@ def patch_vae_tiling_params(These parameters are not explicitly exposed in the VAE's API, but they have a significant impact on the quality ofthe outputs. As a general rule, bigger tiles produce better results, but this comes at the cost of higher memoryusage.++ `tile_sample_min_size` is a request, in output pixels. The tile actually applied is the largest one at or below it+ that the VAE's tiled paths can assemble -- see `diffusers_latent_tile` for why that is not every value, and what+ setting `tile_latent_min_size` independently used to cost. That derivation is the reason this takes a single size+ rather than the pair it patches: the pair has a constraint between its members, so a caller must not be able to+ supply one.++ `AutoencoderTiny` has no such constraint -- its tiled encode reads only `tile_sample_min_size` and its tiled decode+ only `tile_latent_min_size`, so the two never meet -- but it takes the same derivation rather than a class branch.+ It therefore gets a tile the constraint would have required: measured across every `multiple_of=8` request from 64+ to 4088, up to 3 latent elements (24 output pixels) smaller than asked, worst case at 88px. Shape stays exact+ either way, so the cost is tile size, not correctness -- and a class branch to recover 24px is not worth it."""# Record initial config.orig_tile_sample_min_size = vae.tile_sample_min_sizeorig_tile_latent_min_size = vae.tile_latent_min_sizeorig_tile_overlap_factor = vae.tile_overlap_factor+ downsample = diffusers_vae_downsample(vae)+ latent_tile = diffusers_latent_tile(tile_sample_min_size, downsample, tile_overlap_factor)+try:# Apply target config.- vae.tile_sample_min_size = tile_sample_min_size- vae.tile_latent_min_size = tile_latent_min_size+ vae.tile_sample_min_size = latent_tile * downsample+ vae.tile_latent_min_size = latent_tilevae.tile_overlap_factor = tile_overlap_factoryieldfinally:diff --git a/invokeai/backend/util/sdpa_scope.py b/invokeai/backend/util/sdpa_scope.pynew file mode 100644index 0000000000..09ca7202cc--- /dev/null+++ b/invokeai/backend/util/sdpa_scope.py@@ -0,0 +1,122 @@+"""One process-wide owner for torch's SDPA backend selection.++``torch.nn.attention.sdpa_kernel`` reads and writes ``at::globalContext()`` -- process-global state,+not thread-local, and torch offers no thread-scoped variant. Its save/restore is also not atomic+across threads. With two overlapping windows (A enters, B enters, A exits, B exits) B restores the+snapshot it took *inside* A's window, so A's values become permanent. Measured on the Krea-2 list:+the global priority order went from ``[FLASH, EFFICIENT, MATH, CUDNN]`` to+``[FLASH, CUDNN, EFFICIENT, MATH]`` and stayed there for the life of the process; with an exclusive+override in one thread, the other three backends were left *disabled* process-wide.++That is reachable in ordinary operation -- InvokeAI runs one generation session per GPU+concurrently, and both the Krea-2 attention processor and the Anima denoise loop open windows -- and+it leaks well past the architecture that opened it: every other model in the process then picks+kernels by the leaked order, and `backend.util.attention` sizes working memory from that same order.++So the globals get a single owner. The outermost window is the only one that writes them; a window+opened while another is already active runs under the active policy instead of overwriting it. Two+concurrent sessions cannot hold different values of a process-global setting -- that is torch's+constraint, not a choice made here -- but the state is now saved once and restored once, which is+what stops the corruption.++The cost of that choice is that a window can silently not apply. For the default ranking that only+decides which of four enabled kernels runs first. For an *exclusive* policy it is load-bearing: the+whole point of ``INVOKE_KREA2_SDPA_BACKEND=cudnn`` is that a run which completes proves that kernel+served it, and a window that did not apply voids the measurement. So non-owning entries are counted+(:func:`foreign_window_entries`) for a benchmark to report against, and one is logged.+"""++import threading+from collections.abc import Iterator, Sequence+from contextlib import AbstractContextManager, contextmanager++from torch.nn.attention import SDPBackend, sdpa_kernel++from invokeai.backend.util.logging import InvokeAILogger++logger = InvokeAILogger.get_logger(__name__)++Policy = tuple[tuple[SDPBackend, ...], bool]++_lock = threading.Lock()+_depth = 0+_window: AbstractContextManager[object] | None = None+_policy: Policy | None = None+_foreign_entries = 0+_reported: set[tuple[Policy, Policy]] = set()+++def foreign_window_entries() -> int:+ """How many windows have so far run under a policy other than the one they asked for.++ Monotonic for the life of the process. Read it before and after a measured run: a difference+ means the run did not have the backend selection it asked for.+ """+ return _foreign_entries+++@contextmanager+def sdpa_policy(backends: Sequence[SDPBackend], set_priority: bool = True) -> Iterator[bool]:+ """Run the block with `backends` as torch's SDPA backend selection, if no other window owns it.++ A drop-in for ``sdpa_kernel(list(backends), set_priority=set_priority)`` that is safe to open+ from several threads. Entering while another window is open is a no-op for the duration of this+ block: the caller runs under the open policy, and the globals are restored once, by the window+ that set them.++ Yields whether this window owns the globals, so a caller whose correctness depends on its policy+ actually applying can tell.+ """+ global _depth, _window, _policy, _foreign_entries++ requested = (tuple(backends), set_priority)+ collision: tuple[Policy, Policy] | None = None+ with _lock:+ owned = _depth == 0+ if owned:+ # Published only once the enter has succeeded: a half-entered window must not be left+ # behind for the next caller to try to exit.+ window = sdpa_kernel(list(backends), set_priority=set_priority)+ window.__enter__()+ _window, _policy = window, requested+ elif requested != _policy:+ _foreign_entries += 1+ assert _policy is not None+ if (_policy, requested) not in _reported:+ _reported.add((_policy, requested))+ collision = (_policy, requested)+ _depth += 1++ # Outside the lock on purpose: `log_handlers` can be `http=` or `syslog=`, and a stalled handler+ # holding this lock would stall every session's attention path.+ if collision is not None:+ _report(*collision)++ try:+ yield owned+ finally:+ with _lock:+ _depth -= 1+ if _depth == 0 and _window is not None:+ window, _window, _policy = _window, None, None+ window.__exit__(None, None, None)+++def _report(active: Policy, requested: Policy) -> None:+ # Once per distinct pair, not once per process: a benign default-vs-default collision must not+ # swallow the line for an exclusive policy that did not apply.+ exclusive = len(requested[0]) < len(active[0])+ message = (+ f"SDPA backend policy {_describe(requested)} was not applied: another session already holds "+ f"the window with {_describe(active)}. torch's backend selection is process-global, so two "+ "concurrent sessions cannot both set it."+ )+ if exclusive:+ logger.warning(f"{message} A run measured under this override did not get the kernel it asked for.")+ else:+ logger.info(message)+++def _describe(policy: Policy) -> str:+ backends, set_priority = policy+ return f"[{', '.join(b.name for b in backends)}] set_priority={set_priority}"diff --git a/invokeai/backend/util/vae_tiling_scope.py b/invokeai/backend/util/vae_tiling_scope.pyindex 3fb92627aa..cb2725ca74 100644--- a/invokeai/backend/util/vae_tiling_scope.py+++ b/invokeai/backend/util/vae_tiling_scope.py@@ -10,6 +10,11 @@ Two siblings solve the same problem for their own classes: `patch_qwen_image_vaeQwen-Image VAE, and `stable_diffusion.vae_tiling.patch_vae_tiling_params` for SD's. Neither fitshere -- the SD one is typed to AutoencoderKL/AutoencoderTiny, patches three diffusers-specificattributes the FLUX autoencoder does not have, and leaves `use_tiling` to the caller.++`diffusers_latent_tile` and `diffusers_vae_downsample` state constraints of the diffusers VAE+classes rather than of this module, which is why they are public: the SD sibling derived the tile+geometry independently and produced wrong-sized images for it, and it now calls these instead. A+third copy of that arithmetic is the failure mode this module exists to stop."""from contextlib import contextmanager@@ -30,6 +35,11 @@ _TILING_ATTRS = (_MISSING = object()+# Floor for the latent tile `diffusers_latent_tile` picks, and the bottom of its search. Below this+# the tile stops being one: a 2-latent tile decodes a band narrower than the blend the overlap+# factor asks for, and a 1-latent one is a single feature column.+_MIN_DIFFUSERS_LATENT_TILE = 4+@contextmanagerdef scoped_vae_tiling(vae: Any, tile_size: int | None) -> Iterator[None]:@@ -53,11 +63,11 @@ def scoped_vae_tiling(vae: Any, tile_size: int | None) -> Iterator[None]:# the two attributes afterwards is how the rest of this codebase sizes a diffusers VAE's# tiles; see `flux2/ref_image_extension.py`, which forces 512 for the same reason. Both# are in `_TILING_ATTRS`, so the finally block puts them back.- resolved = resolve_tile_size(tile_size)+ downsample = diffusers_vae_downsample(vae)+ latent_tile = diffusers_latent_tile(resolve_tile_size(tile_size), downsample, vae.tile_overlap_factor)vae.enable_tiling()- vae.tile_sample_min_size = resolved- downsample = 2 ** (len(vae.config.block_out_channels) - 1)- vae.tile_latent_min_size = max(1, resolved // downsample)+ vae.tile_latent_min_size = latent_tile+ vae.tile_sample_min_size = latent_tile * downsampleyieldfinally:for name, value in original.items():@@ -68,3 +78,51 @@ def scoped_vae_tiling(vae: Any, tile_size: int | None) -> Iterator[None]:def _accepts_tile_size(vae: Any) -> bool:"""True if `enable_tiling` takes a tile size. Diffusers' AutoencoderKL takes no arguments."""return isinstance(vae, AutoEncoder)+++def diffusers_vae_downsample(vae: Any) -> int:+ """Output pixels per latent element along one axis, for the diffusers VAE classes.++ `AutoencoderTiny` names the ratio directly and uses that attribute in its own tiling; the+ `AutoencoderKL` family implies it from the number of blocks.+ """+ spatial_scale_factor = getattr(vae, "spatial_scale_factor", None)+ if spatial_scale_factor is not None:+ return int(spatial_scale_factor)+ return 2 ** (len(vae.config.block_out_channels) - 1)+++def diffusers_latent_tile(requested_sample_size: int, downsample: int, overlap_factor: float) -> int:+ """The latent tile to give a diffusers VAE, at or below the requested size in output pixels+ unless the request itself is under `_MIN_DIFFUSERS_LATENT_TILE` latents, which the floor wins.++ `tile_sample_min_size` and `tile_latent_min_size` are not two independent knobs. `AutoencoderKL`+ steps its latent loop by `int(tile_latent_min_size * (1 - tile_overlap_factor))` but crops each+ decoded tile to `tile_sample_min_size - int(tile_sample_min_size * tile_overlap_factor)` output+ pixels, and `_tiled_encode` mirrors that -- a pixel step against a latent crop. Those two+ distances describe the same span only for some tiles; for the rest the loop and the crop+ disagree and the assembled result is the wrong size. Measured on a 768x768 decode, 60 of the 84+ legal tile sizes from 128 to 792 came out between 770 and 810 pixels at the stock 0.25 factor,+ the 24 correct ones being exactly the multiples of 32.++ So the latent tile is chosen first -- the largest at or below the request for which the two+ agree -- and the caller derives the sample size from it. The expressions are evaluated as+ diffusers evaluates them rather than reasoned about, because which tiles agree depends on how+ the factor rounds in binary, not on its value as a fraction: at an 8x downsample 0.25 admits+ every multiple of 4, 0.3 only multiples of 10, and 0.35 only multiples of 20.++ Only the decode expression is evaluated. The encode one admits exactly the same tiles -- swept+ over 7 overlap factors x 4 downsample ratios x the first 300 latent tiles, the two agree on+ every single one -- so checking both would be the same question asked twice.+ """+ largest = max(_MIN_DIFFUSERS_LATENT_TILE, requested_sample_size // downsample)+ for latent_tile in range(largest, _MIN_DIFFUSERS_LATENT_TILE - 1, -1):+ sample_size = latent_tile * downsample+ if int(latent_tile * (1 - overlap_factor)) * downsample == sample_size - int(sample_size * overlap_factor):+ return latent_tile+ # No tile in range works: the smallest one this factor admits is above the request, if it+ # admits any at all. Unreachable for the 0.25 every AutoencoderKL ships, which admits every+ # multiple of 4; possible only for a hand-set factor -- 0.35 admits nothing below 20 latents,+ # so an 8x VAE finds nothing for a request of 128 to 152. Honour the request rather than+ # failing the decode over it.+ return largestdiff --git a/invokeai/backend/util/vae_working_memory.py b/invokeai/backend/util/vae_working_memory.pyindex 8cebba59d8..ec26765804 100644--- a/invokeai/backend/util/vae_working_memory.py+++ b/invokeai/backend/util/vae_working_memory.py@@ -77,6 +77,31 @@ def estimate_vae_working_memory_cogview4(return int(working_memory)+# What a tiled decode does *not* bound: the assembled image, several times over, per output pixel.+#+# `AutoEncoder._tiled_decode` moves each tile to the host and merges there, so it lands one stacked+# copy back on the device. Diffusers' `AutoencoderKL.tiled_decode` -- the other class this estimator+# serves, through the Z-Image node -- assembles entirely on the device: every decoded tile stays+# live in `rows` while the cropped rows and then the concatenated result are built. On top of+# either, a decode node runs `clamp(-1, 1)`, `+ 1.0` and `* 127.5` over the result and then+# `.byte()` it: more element-size RGB buffers plus the 8-bit one.+#+# Measured on this repo's fixtures (RTX 4090, fp32), device peak over baseline against one full+# image, at 1024px and 2048px:+#+# InvokeAI AutoEncoder 196.0 -> 200.0 MiB image 12 -> 48 MiB marginal slope 0.11+# diffusers AutoencoderKL 178.7 -> 235.1 MiB image 12 -> 48 MiB marginal slope 1.57+#+# The BFL class merges on the *host*, so almost nothing image-sized is on the device until the+# final `stack(...).to(device)`, by which point the tile activations have been freed; the diffusers+# class assembles on-device and grows at ~1.6 copies. Both peaks are dominated by the tile term+# above, which is why the earlier value of 7 -- derived rather than measured -- over-reserved by+# roughly 7x on the node it was named for. Four covers the measured slope plus the node's in-window+# post-processing, and one constant still covers both classes.+_FLUX_VAE_TILED_IMAGE_COPIES = 4+_IMAGE_CHANNELS = 3++def estimate_vae_working_memory_flux(operation: Literal["encode", "decode"],image_tensor: torch.Tensor,@@ -85,10 +110,14 @@ def estimate_vae_working_memory_flux() -> int:"""Estimate the working memory required by the invocation in bytes.- `tile_size` is in output pixels and defaults to None, i.e. a single-pass decode -- the six- existing call sites depend on that signature. When set, the estimate is bounded by one tile- instead of the whole image, because a tiled decode never holds more than that. `tile_size <= 0`- is the nodes' "use the default" sentinel; see `resolve_tile_size`.+ `tile_size` is in output pixels and defaults to None, i.e. a single-pass decode -- the existing+ call sites that pass no tile depend on that signature. When set, the decode term is bounded by+ one tile instead of the whole image, and the full-resolution assembly and post-processing that+ tiling does *not* bound are added on top. `tile_size <= 0` is the nodes' "use the default"+ sentinel; see `resolve_tile_size`.++ Only `decode` tiles: `AutoEncoder.encode` never consults `use_tiling`. So a `tile_size` with+ `operation="encode"` would price a tiled encode that cannot happen, and no call site passes one."""latent_scale_factor_for_operation = LATENT_SCALE_FACTOR if operation == "decode" else 1@@ -98,16 +127,28 @@ def estimate_vae_working_memory_flux(# Encoding uses ~45% the working memory as decoding.scaling_constant = 2200 if operation == "decode" else 1100- if tile_size is not None:- # Resolved against a module-level constant, never by reading `vae.tile_sample_min_size`: the- # VAE belongs to the model cache, so that attribute reflects whatever the previous- # invocation set rather than the default this node is asking for.- out_h = out_w = resolve_tile_size(tile_size)+ out_h = latent_scale_factor_for_operation * image_tensor.shape[-2]+ out_w = latent_scale_factor_for_operation * image_tensor.shape[-1]++ # Resolved against a module-level constant, never by reading `vae.tile_sample_min_size`: the VAE+ # belongs to the model cache, so that attribute reflects whatever the previous invocation set+ # rather than the default this node is asking for.+ tile = resolve_tile_size(tile_size) if tile_size is not None else None++ # `_tiled_decode` short-circuits to a single pass once the tile covers the image on both axes,+ # so a tile that large has to be priced as the untiled decode it will actually run. The node+ # field carries no upper bound: a 2048px tile on a 1024px image would otherwise reserve ~23GB+ # for a decode that needs ~4.6GB, evicting the transformer from the cache for nothing.+ if tile is not None and (tile < out_h or tile < out_w):+ # `calc_tiles_min_overlap` clamps the tile to the image *per axis*, so the largest tile the+ # decode builds is this, not `tile` squared. Without the clamp an 8192px tile on a+ # 1024x8200 image -- tiled, because one axis exceeds it -- prices 8192x8192.+ tile_h = min(tile, out_h)+ tile_w = min(tile, out_w)# A 25% margin for tile overlap and the number of tiles, mirroring the SD1/SDXL estimator.- working_memory = out_h * out_w * element_size * scaling_constant * 1.25+ working_memory = tile_h * tile_w * element_size * scaling_constant * 1.25+ working_memory += out_h * out_w * _IMAGE_CHANNELS * (_FLUX_VAE_TILED_IMAGE_COPIES * element_size + 1)else:- out_h = latent_scale_factor_for_operation * image_tensor.shape[-2]- out_w = latent_scale_factor_for_operation * image_tensor.shape[-1]working_memory = out_h * out_w * element_size * scaling_constantreturn int(working_memory)diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.jsonindex 26664d7f09..a64c8b9408 100644--- a/invokeai/frontend/web/openapi.json+++ b/invokeai/frontend/web/openapi.json@@ -53972,7 +53972,7 @@"type": "string","enum": ["full", "normal"],"title": "Db Synchronous",- "description": "SQLite durability setting. `full` (the default) 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, because WAL guarantees consistency either way. What it 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.",+ "description": "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.","default": "full"},"outputs_dir": {@@ -54297,7 +54297,7 @@"force_tiled_decode": {"type": "boolean","title": "Force Tiled Decode",- "description": "Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty).",+ "description": "Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty). A tiled decode is not pixel-identical to a single-pass one: a VAE decoder normalises and attends over the whole image, so the difference is spread across it rather than confined to the tile seams. As of this release the setting also applies to FLUX.1, which previously ignored it.","default": false},"pil_compress_level": {@@ -54594,7 +54594,7 @@"additionalProperties": false,"type": "object","title": "InvokeAIAppConfig",- "description": "Invoke's global app configuration.\n\nTypically, you won't need to interact with this class directly. Instead, use the `get_config` function from `invokeai.app.services.config` to get a singleton config object.\n\nAttributes:\n host: IP address to bind to. Use `0.0.0.0` to serve to your local network.\n port: Port to bind to.\n allow_origins: Allowed CORS origins.\n allow_credentials: Allow CORS credentials.\n allow_methods: Methods allowed for CORS.\n allow_headers: Headers allowed for CORS.\n ssl_certfile: SSL certificate file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n ssl_keyfile: SSL key file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n log_tokenization: Enable logging of parsed prompt tokens.\n patchmatch: Enable patchmatch inpaint code.\n models_dir: Path to the models directory.\n convert_cache_dir: Path to the converted models cache directory (DEPRECATED, but do not delete because it is needed for migration from previous versions).\n download_cache_dir: Path to the directory that contains dynamically downloaded models.\n legacy_conf_dir: Path to directory of legacy checkpoint config files.\n db_dir: Path to InvokeAI databases directory.\n db_synchronous: SQLite durability setting. `full` (the default) 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, because WAL guarantees consistency either way. What it gives up is the most recent transactions on a power loss or OS crash: a just-written image record or queue status, not the image file itself.<br>Valid values: `full`, `normal`\n outputs_dir: Path to directory for outputs.\n image_subfolder_strategy: Strategy for organizing images into subfolders. 'flat' stores all images in a single folder. 'date' organizes by YYYY/MM/DD. 'type' organizes by image category. 'hash' uses first 2 characters of UUID for filesystem performance.<br>Valid values: `flat`, `date`, `type`, `hash`\n custom_nodes_dir: Path to directory for custom nodes.\n style_presets_dir: Path to directory for style presets.\n workflow_thumbnails_dir: Path to directory for workflow thumbnails.\n log_handlers: Log handler. Valid options are \"console\", \"file=<path>\", \"syslog=path|address:host:port\", \"http=<url>\".\n log_format: Log format. Use \"plain\" for text-only, \"color\" for colorized output, \"legacy\" for 2.3-style logging and \"syslog\" for syslog-style.<br>Valid values: `plain`, `color`, `syslog`, `legacy`\n log_level: Emit logging messages at this level or higher.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n log_sql: Log SQL queries. `log_level` must be `debug` for this to do anything. Extremely verbose.\n log_level_network: Log level for network-related messages. 'info' and 'debug' are very verbose.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n use_memory_db: Use in-memory database. Useful for development.\n dev_reload: Automatically reload when Python sources are changed. Does not reload node definitions.\n profile_graphs: Enable graph profiling using `cProfile`.\n profile_prefix: An optional prefix for profile output files.\n profiles_dir: Path to profiles output directory.\n max_cache_ram_gb: The maximum amount of CPU RAM to use for model caching in GB. If unset, the limit will be configured based on the available RAM. In most cases, it is recommended to leave this unset.\n max_cache_vram_gb: The amount of VRAM to use for model caching in GB. If unset, the limit will be configured based on the available VRAM and the device_working_mem_gb. In most cases, it is recommended to leave this unset.\n log_memory_usage: If True, a memory snapshot will be captured before and after every model cache operation, and the result will be logged (at debug level). There is a time cost to capturing the memory snapshots, so it is recommended to only enable this feature if you are actively inspecting the model cache's behaviour.\n model_cache_keep_alive_min: How long to keep models in cache after last use, in minutes. A value of 0 (the default) means models are kept in cache indefinitely. If no model generations occur within the timeout period, the model cache is cleared using the same logic as the 'Clear Model Cache' button.\n device_working_mem_gb: The amount of working memory to keep available on the compute device (in GB). Has no effect if running on CPU. If you are experiencing OOM errors, try increasing this value.\n enable_partial_loading: Enable partial loading of models. This enables models to run with reduced VRAM requirements (at the cost of slower speed) by streaming the model from RAM to VRAM as its used. In some edge cases, partial loading can cause models to run more slowly if they were previously being fully loaded into VRAM.\n keep_ram_copy_of_weights: Whether to keep a full RAM copy of a model's weights when the model is loaded in VRAM. Keeping a RAM copy increases average RAM usage, but speeds up model switching and LoRA patching (assuming there is sufficient RAM). Set this to False if RAM pressure is consistently high.\n fp8_compute: Keep ComfyUI 'scaled fp8' checkpoints quantized instead of dequantizing them at load, and run their matmuls on the fp8 tensor cores (requires an Ada/SM 8.9 or newer NVIDIA GPU; falls back automatically otherwise). Roughly halves the transformer's VRAM and speeds up denoising, but quantizes activations as well, so images will differ from previous versions at the same seed. Reproducibility also requires the model to be FULLY resident in VRAM: a layer whose weights are still in RAM falls back to the dequantized path, and since which layers are resident shifts from run to run, the same seed then yields visibly different images. For repeatable output, ensure the model loads at 100% (e.g. enable_partial_loading=false with enough free VRAM).\n fp8_compute_full_precision_hints: Honor the per-layer 'full_precision_matrix_mult' flags that some scaled-fp8 checkpoints ship. Those layers then dequantize on every forward instead of using the fp8 tensor cores, which can cost a large part of the fp8_compute speedup - on checkpoints that mark many layers, most of it. Set to false to run every quantized layer on the fp8 tensor cores, ignoring the producer's instruction; faster, but the marked layers were flagged as numerically sensitive, so quality may suffer. Only has an effect when fp8_compute is enabled.\n ram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_ram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n vram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_vram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n lazy_offload: DEPRECATED: This setting is no longer used. Lazy-offloading is enabled by default. This config setting will be removed once the new model cache behavior is stable.\n pytorch_cuda_alloc_conf: Configure the Torch CUDA memory allocator. This will impact peak reserved VRAM usage and performance. Setting to \"backend:cudaMallocAsync\" works well on many systems. The optimal configuration is highly dependent on the system configuration (device type, VRAM, CUDA driver version, etc.), so must be tuned experimentally.\n device: Preferred execution device. `auto` will choose the device depending on the hardware platform and the installed torch capabilities.<br>Valid values: `auto`, `cpu`, `cuda`, `mps`, `xpu`, `cuda:N`, `xpu:N` (where N is a device number)\n precision: Floating point precision. `float16` will consume half the memory of `float32` but produce slightly lower-quality images. The `auto` setting will guess the proper precision based on your video card and operating system.<br>Valid values: `auto`, `float16`, `bfloat16`, `float32`\n sequential_guidance: Whether to calculate guidance in serial instead of in parallel, lowering memory requirements.\n wan_memory_optimization: Enable experimental Wan memory optimizations at the cost of slower generation.\n pid_memory_optimization: Enable experimental PiD decode memory optimizations. Roughly halves the peak activation memory of a PiD decode; in exchange the decoded image changes slightly, because neither the chunked pixel pathway nor the float32 sampler intermediates are bit-exact with the default path.\n attention_type: Attention type.<br>Valid values: `auto`, `normal`, `xformers`, `sliced`, `torch-sdp`\n attention_slice_size: Slice size, valid when attention_type==\"sliced\".<br>Valid values: `auto`, `balanced`, `max`, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`\n force_tiled_decode: Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty).\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, 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. 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 images embedded per batch by the image index worker.\n external_alibabacloud_api_key: API key for Alibaba Cloud DashScope image generation.\n external_alibabacloud_base_url: Base URL override for Alibaba Cloud DashScope image generation.\n external_gemini_api_key: API key for Gemini image generation.\n external_openai_api_key: API key for OpenAI image generation.\n external_gemini_base_url: Base URL override for Gemini image generation.\n external_openai_base_url: Base URL override for OpenAI image generation.\n external_seedream_api_key: API key for Seedream image generation.\n external_seedream_base_url: Base URL override for Seedream image generation.\n base_url: Public base path when running behind a reverse proxy under a sub-path, e.g. `/invoke`. Set only when the proxy PRESERVES the sub-path (the backend receives `/invoke/api/...`). Leave unset when the proxy strips the sub-path or when serving at the domain root.\n forwarded_allow_ips: Comma-separated list of IPs (or `*`) allowed to set X-Forwarded-* headers. Set to the reverse proxy's IP. Only used when `base_url` is set.\n http_compression_level: Compression level for gzipped HTTP API responses. 0 disables response compression entirely, 1 is fastest, 9 (the default) is smallest. Compression runs on the event loop and blocks the whole server while it works, and level 9 costs about 5.5x the time of level 1 for 0.4 percentage points of extra compression, so lowering this makes the app noticeably more responsive on large libraries. Set to 0 when a reverse proxy already compresses responses."+ "description": "Invoke's global app configuration.\n\nTypically, you won't need to interact with this class directly. Instead, use the `get_config` function from `invokeai.app.services.config` to get a singleton config object.\n\nAttributes:\n host: IP address to bind to. Use `0.0.0.0` to serve to your local network.\n port: Port to bind to.\n allow_origins: Allowed CORS origins.\n allow_credentials: Allow CORS credentials.\n allow_methods: Methods allowed for CORS.\n allow_headers: Headers allowed for CORS.\n ssl_certfile: SSL certificate file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n ssl_keyfile: SSL key file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n log_tokenization: Enable logging of parsed prompt tokens.\n patchmatch: Enable patchmatch inpaint code.\n models_dir: Path to the models directory.\n convert_cache_dir: Path to the converted models cache directory (DEPRECATED, but do not delete because it is needed for migration from previous versions).\n download_cache_dir: Path to the directory that contains dynamically downloaded models.\n legacy_conf_dir: Path to directory of legacy checkpoint config files.\n db_dir: Path to InvokeAI databases directory.\n db_synchronous: SQLite durability setting. `full`, the default and what InvokeAI has always used, flushes every commit to disk. `normal` acknowledges commits without waiting for that flush - measured at roughly 12x shorter commits on an SSD - and cannot corrupt the database under WAL, which is why it is refused, with a warning, when WAL is unavailable for the database file. What `normal` gives up is the most recent transactions on a power loss or OS crash: a just-written image record or queue status, not the image file itself.<br>Valid values: `full`, `normal`\n outputs_dir: Path to directory for outputs.\n image_subfolder_strategy: Strategy for organizing images into subfolders. 'flat' stores all images in a single folder. 'date' organizes by YYYY/MM/DD. 'type' organizes by image category. 'hash' uses first 2 characters of UUID for filesystem performance.<br>Valid values: `flat`, `date`, `type`, `hash`\n custom_nodes_dir: Path to directory for custom nodes.\n style_presets_dir: Path to directory for style presets.\n workflow_thumbnails_dir: Path to directory for workflow thumbnails.\n log_handlers: Log handler. Valid options are \"console\", \"file=<path>\", \"syslog=path|address:host:port\", \"http=<url>\".\n log_format: Log format. Use \"plain\" for text-only, \"color\" for colorized output, \"legacy\" for 2.3-style logging and \"syslog\" for syslog-style.<br>Valid values: `plain`, `color`, `syslog`, `legacy`\n log_level: Emit logging messages at this level or higher.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n log_sql: Log SQL queries. `log_level` must be `debug` for this to do anything. Extremely verbose.\n log_level_network: Log level for network-related messages. 'info' and 'debug' are very verbose.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n use_memory_db: Use in-memory database. Useful for development.\n dev_reload: Automatically reload when Python sources are changed. Does not reload node definitions.\n profile_graphs: Enable graph profiling using `cProfile`.\n profile_prefix: An optional prefix for profile output files.\n profiles_dir: Path to profiles output directory.\n max_cache_ram_gb: The maximum amount of CPU RAM to use for model caching in GB. If unset, the limit will be configured based on the available RAM. In most cases, it is recommended to leave this unset.\n max_cache_vram_gb: The amount of VRAM to use for model caching in GB. If unset, the limit will be configured based on the available VRAM and the device_working_mem_gb. In most cases, it is recommended to leave this unset.\n log_memory_usage: If True, a memory snapshot will be captured before and after every model cache operation, and the result will be logged (at debug level). There is a time cost to capturing the memory snapshots, so it is recommended to only enable this feature if you are actively inspecting the model cache's behaviour.\n model_cache_keep_alive_min: How long to keep models in cache after last use, in minutes. A value of 0 (the default) means models are kept in cache indefinitely. If no model generations occur within the timeout period, the model cache is cleared using the same logic as the 'Clear Model Cache' button.\n device_working_mem_gb: The amount of working memory to keep available on the compute device (in GB). Has no effect if running on CPU. If you are experiencing OOM errors, try increasing this value.\n enable_partial_loading: Enable partial loading of models. This enables models to run with reduced VRAM requirements (at the cost of slower speed) by streaming the model from RAM to VRAM as its used. In some edge cases, partial loading can cause models to run more slowly if they were previously being fully loaded into VRAM.\n keep_ram_copy_of_weights: Whether to keep a full RAM copy of a model's weights when the model is loaded in VRAM. Keeping a RAM copy increases average RAM usage, but speeds up model switching and LoRA patching (assuming there is sufficient RAM). Set this to False if RAM pressure is consistently high.\n fp8_compute: Keep ComfyUI 'scaled fp8' checkpoints quantized instead of dequantizing them at load, and run their matmuls on the fp8 tensor cores (requires an Ada/SM 8.9 or newer NVIDIA GPU; falls back automatically otherwise). Roughly halves the transformer's VRAM and speeds up denoising, but quantizes activations as well, so images will differ from previous versions at the same seed. Reproducibility also requires the model to be FULLY resident in VRAM: a layer whose weights are still in RAM falls back to the dequantized path, and since which layers are resident shifts from run to run, the same seed then yields visibly different images. For repeatable output, ensure the model loads at 100% (e.g. enable_partial_loading=false with enough free VRAM).\n fp8_compute_full_precision_hints: Honor the per-layer 'full_precision_matrix_mult' flags that some scaled-fp8 checkpoints ship. Those layers then dequantize on every forward instead of using the fp8 tensor cores, which can cost a large part of the fp8_compute speedup - on checkpoints that mark many layers, most of it. Set to false to run every quantized layer on the fp8 tensor cores, ignoring the producer's instruction; faster, but the marked layers were flagged as numerically sensitive, so quality may suffer. Only has an effect when fp8_compute is enabled.\n ram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_ram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n vram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_vram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n lazy_offload: DEPRECATED: This setting is no longer used. Lazy-offloading is enabled by default. This config setting will be removed once the new model cache behavior is stable.\n pytorch_cuda_alloc_conf: Configure the Torch CUDA memory allocator. This will impact peak reserved VRAM usage and performance. Setting to \"backend:cudaMallocAsync\" works well on many systems. The optimal configuration is highly dependent on the system configuration (device type, VRAM, CUDA driver version, etc.), so must be tuned experimentally.\n device: Preferred execution device. `auto` will choose the device depending on the hardware platform and the installed torch capabilities.<br>Valid values: `auto`, `cpu`, `cuda`, `mps`, `xpu`, `cuda:N`, `xpu:N` (where N is a device number)\n precision: Floating point precision. `float16` will consume half the memory of `float32` but produce slightly lower-quality images. The `auto` setting will guess the proper precision based on your video card and operating system.<br>Valid values: `auto`, `float16`, `bfloat16`, `float32`\n sequential_guidance: Whether to calculate guidance in serial instead of in parallel, lowering memory requirements.\n wan_memory_optimization: Enable experimental Wan memory optimizations at the cost of slower generation.\n pid_memory_optimization: Enable experimental PiD decode memory optimizations. Roughly halves the peak activation memory of a PiD decode; in exchange the decoded image changes slightly, because neither the chunked pixel pathway nor the float32 sampler intermediates are bit-exact with the default path.\n attention_type: Attention type.<br>Valid values: `auto`, `normal`, `xformers`, `sliced`, `torch-sdp`\n attention_slice_size: Slice size, valid when attention_type==\"sliced\".<br>Valid values: `auto`, `balanced`, `max`, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`\n force_tiled_decode: Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty). A tiled decode is not pixel-identical to a single-pass one: a VAE decoder normalises and attends over the whole image, so the difference is spread across it rather than confined to the tile seams. As of this release the setting also applies to FLUX.1, which previously ignored it.\n pil_compress_level: The compress_level setting of PIL.Image.save(), used for PNG encoding. All settings are lossless. 0 = no compression, 1 = fastest with slightly larger filesize, 9 = slowest with smallest filesize. 1 is typically the best setting.\n max_queue_size: Maximum number of items in the session queue.\n session_queue_mode: Session queue mode. Use 'FIFO' for traditional first-in-first-out, or 'round_robin' to serve each user's jobs in turn. In single-user mode, FIFO is always used regardless of this setting.<br>Valid values: `FIFO`, `round_robin`\n clear_queue_on_startup: Empties session queue on startup. If true, disables `max_queue_history`.\n max_queue_history: Keep the last N completed, failed, and canceled queue items. Older items are deleted on startup. Set to 0 to prune all terminal items. Ignored if `clear_queue_on_startup` is true.\n allow_nodes: List of nodes to allow. Omit to allow all.\n deny_nodes: List of nodes to deny. Omit to deny none.\n node_cache_size: How many cached nodes to keep in memory.\n hashing_algorithm: Model hashing algorthim for model installs. 'blake3_multi' is best for SSDs. 'blake3_single' is best for spinning disk HDDs. 'random' disables hashing, instead assigning a UUID to models. Useful when using a memory db to reduce model installation time, or if you don't care about storing stable hashes for models. Alternatively, any other hashlib algorithm is accepted, though these are not nearly as performant as blake3.<br>Valid values: `blake3_multi`, `blake3_single`, `random`, `md5`, `sha1`, `sha224`, `sha256`, `sha384`, `sha512`, `blake2b`, `blake2s`, `sha3_224`, `sha3_256`, `sha3_384`, `sha3_512`, `shake_128`, `shake_256`\n remote_api_tokens: List of regular expression and token pairs used when downloading models from URLs. The download URL is tested against the regex, and if it matches, the token is provided in as a Bearer token.\n scan_models_on_startup: Scan the models directory on startup, registering orphaned models. This is typically only used in conjunction with `use_memory_db` for testing purposes.\n allow_private_download_urls: Allow the download queue to fetch from loopback, link-local and private-network addresses. Disabled by default so that a download URL cannot be used to reach services that are only reachable from the server. Enable this only if you install models from a mirror on your own network.\n download_proxy: Optional HTTP proxy for model downloads. The proxy must enforce the public-address policy because proxy-side DNS cannot be checked by InvokeAI.\n unsafe_disable_picklescan: UNSAFE. Disable the picklescan security check during model installation. Recommended only for development and testing purposes. This will allow arbitrary code execution during model installation, so should never be used in production.\n allow_unknown_models: Allow installation of models that we are unable to identify. If enabled, models will be marked as `unknown` in the database, and will not have any metadata associated with them. If disabled, unknown models will be rejected during installation.\n multiuser: Enable multiuser support. When disabled, the application runs in single-user mode using a default system account with administrator privileges. When enabled, requires user authentication and authorization.\n strict_password_checking: Enforce strict password requirements. When True, passwords must contain uppercase, lowercase, and numbers. When False (default), any password is accepted but its strength (weak/moderate/strong) is reported to the user.\n image_index_enabled: Maintain a semantic embedding index of gallery images, 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. 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 images embedded per batch by the image index worker.\n external_alibabacloud_api_key: API key for Alibaba Cloud DashScope image generation.\n external_alibabacloud_base_url: Base URL override for Alibaba Cloud DashScope image generation.\n external_gemini_api_key: API key for Gemini image generation.\n external_openai_api_key: API key for OpenAI image generation.\n external_gemini_base_url: Base URL override for Gemini image generation.\n external_openai_base_url: Base URL override for OpenAI image generation.\n external_seedream_api_key: API key for Seedream image generation.\n external_seedream_base_url: Base URL override for Seedream image generation.\n base_url: Public base path when running behind a reverse proxy under a sub-path, e.g. `/invoke`. Set only when the proxy PRESERVES the sub-path (the backend receives `/invoke/api/...`). Leave unset when the proxy strips the sub-path or when serving at the domain root.\n forwarded_allow_ips: Comma-separated list of IPs (or `*`) allowed to set X-Forwarded-* headers. Set to the reverse proxy's IP. Only used when `base_url` is set.\n http_compression_level: Compression level for gzipped HTTP API responses. 0 disables response compression entirely, 1 is fastest, 9 (the default) is smallest. Compression runs on the event loop and blocks the whole server while it works, and level 9 costs about 5.5x the time of level 1 for 0.4 percentage points of extra compression, so lowering this makes the app noticeably more responsive on large libraries. Set to 0 when a reverse proxy already compresses responses."},"InvokeAIAppConfigWithSetFields": {"properties": {diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.tsindex 319960f469..8708d9b0d7 100644--- a/invokeai/frontend/web/src/services/api/schema.ts+++ b/invokeai/frontend/web/src/services/api/schema.ts@@ -20774,7 +20774,7 @@ export type components = {* download_cache_dir: Path to the directory that contains dynamically downloaded models.* legacy_conf_dir: Path to directory of legacy checkpoint config files.* db_dir: Path to InvokeAI databases directory.- * db_synchronous: SQLite durability setting. `full` (the default) 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, because WAL guarantees consistency either way. What it 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`+ * 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`* outputs_dir: Path to directory for outputs.* 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`* custom_nodes_dir: Path to directory for custom nodes.@@ -20810,7 +20810,7 @@ export type components = {* pid_memory_optimization: Enable experimental PiD decode memory optimizations. Roughly halves the peak activation memory of a PiD decode; in exchange the decoded image changes slightly, because neither the chunked pixel pathway nor the float32 sampler intermediates are bit-exact with the default path.* attention_type: Attention type.<br>Valid values: `auto`, `normal`, `xformers`, `sliced`, `torch-sdp`* attention_slice_size: Slice size, valid when attention_type=="sliced".<br>Valid values: `auto`, `balanced`, `max`, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`- * force_tiled_decode: Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty).+ * force_tiled_decode: Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty). A tiled decode is not pixel-identical to a single-pass one: a VAE decoder normalises and attends over the whole image, so the difference is spread across it rather than confined to the tile seams. As of this release the setting also applies to FLUX.1, which previously ignored it.* pil_compress_level: The compress_level setting of PIL.Image.save(), used for PNG encoding. All settings are lossless. 0 = no compression, 1 = fastest with slightly larger filesize, 9 = slowest with smallest filesize. 1 is typically the best setting.* max_queue_size: Maximum number of items in the session queue.* session_queue_mode: Session queue mode. Use 'FIFO' for traditional first-in-first-out, or 'round_robin' to serve each user's jobs in turn. In single-user mode, FIFO is always used regardless of this setting.<br>Valid values: `FIFO`, `round_robin`@@ -20972,7 +20972,7 @@ export type components = {db_dir?: string;/*** Db Synchronous- * @description SQLite durability setting. `full` (the default) 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, because WAL guarantees consistency either way. What it 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.+ * @description 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.* @default full* @enum {string}*/@@ -21235,7 +21235,7 @@ export type components = {attention_slice_size?: "auto" | "balanced" | "max" | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;/*** Force Tiled Decode- * @description Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty).+ * @description Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty). A tiled decode is not pixel-identical to a single-pass one: a VAE decoder normalises and attends over the whole image, so the difference is spread across it rather than confined to the tile seams. As of this release the setting also applies to FLUX.1, which previously ignored it.* @default false*/force_tiled_decode?: boolean;diff --git a/tests/app/invocations/test_anima_vae.py b/tests/app/invocations/test_anima_vae.pyindex e8d5740d49..1c803386ae 100644--- a/tests/app/invocations/test_anima_vae.py+++ b/tests/app/invocations/test_anima_vae.py@@ -24,6 +24,14 @@ def _mock_wan_vae(dtype: torch.dtype = torch.float16) -> MagicMock:param = torch.zeros(1, dtype=dtype)# Return a fresh iterator on every call so the estimator can be called repeatedly.vae.parameters.side_effect = lambda: iter([param])+ # `patch_qwen_image_vae_tiling` records and restores these; they are set in+ # `AutoencoderKLWan.__init__` rather than on the class, so a spec'd mock does not have them.+ # The stock values keep any assertion against them reading as real numbers.+ vae.use_tiling = False+ vae.tile_sample_min_height = 256+ vae.tile_sample_min_width = 256+ vae.tile_sample_stride_height = 192+ vae.tile_sample_stride_width = 192return vae@@ -143,6 +151,8 @@ class TestAnimaLatentsToImageOomFallback:tile_sample_stride_height=ANIMA_VAE_TILE_STRIDE,tile_sample_stride_width=ANIMA_VAE_TILE_STRIDE,)+ # The retry takes noticeably longer than the failed attempt; the user is told why.+ context.util.signal_progress.assert_any_call("VAE decode ran out of memory, retrying tiled")assert result.width == 64def test_non_oom_runtime_error_propagates_without_retry(self):diff --git a/tests/app/invocations/test_anima_vae_tiling.py b/tests/app/invocations/test_anima_vae_tiling.pynew file mode 100644index 0000000000..2ea82983a6--- /dev/null+++ b/tests/app/invocations/test_anima_vae_tiling.py@@ -0,0 +1,130 @@+"""Tiling state on the Anima latents-to-image node's shared, cached Wan VAE.++`enable_tiling` writes the tile geometry onto the module and `disable_tiling` restores only the+flag, never the sizes -- and the module is the model cache's own instance, shared with the+Qwen-Image nodes whenever a native-layout `qwen_image_vae` single file is loaded. A real+`AutoencoderKLWan` is used here rather than a mock precisely because that write-through is the+behaviour under test; a mocked `enable_tiling` would leave nothing behind to leak.+"""++from unittest.mock import MagicMock, patch++import torch+from diffusers.models.autoencoders import AutoencoderKLWan++from invokeai.app.invocations.anima_latents_to_image import (+ ANIMA_VAE_TILE_SIZE,+ ANIMA_VAE_TILE_STRIDE,+ AnimaLatentsToImageInvocation,+)+from invokeai.backend.util.devices import TorchDevice+++def _build_tiny_vae() -> AutoencoderKLWan:+ """The smallest Wan VAE that still decodes: 2 latent channels, 2x spatial, 3 output channels."""+ return AutoencoderKLWan(+ base_dim=2,+ z_dim=2,+ dim_mult=[1, 1],+ num_res_blocks=1,+ attn_scales=[],+ temperal_downsample=[True],+ latents_mean=[0.0, 0.0],+ latents_std=[1.0, 1.0],+ scale_factor_temporal=2,+ scale_factor_spatial=2,+ ).eval()+++def _tiling_state(vae: AutoencoderKLWan) -> tuple:+ return (+ vae.use_tiling,+ vae.tile_sample_min_height,+ vae.tile_sample_min_width,+ vae.tile_sample_stride_height,+ vae.tile_sample_stride_width,+ )+++def _build_context(vae: AutoencoderKLWan, latents: torch.Tensor):+ vae_info = MagicMock()+ vae_info.model = vae+ # The invocation places latents on the VAE's intended compute device (see #9373), so this must+ # be a real torch.device rather than a MagicMock for `latents.to(device=...)` to work.+ vae_info.compute_device = torch.device("cpu")+ cm = MagicMock()+ cm.__enter__ = MagicMock(return_value=(None, vae))+ cm.__exit__ = MagicMock(return_value=None)+ vae_info.model_on_device.return_value = cm++ context = MagicMock()+ context.models.load.return_value = vae_info+ context.tensors.load.return_value = latents+ image_dto = MagicMock()+ image_dto.image_name = "test.png"+ image_dto.width = latents.shape[-1] * 2+ image_dto.height = latents.shape[-2] * 2+ context.images.save.return_value = image_dto+ return context+++def _build_invocation() -> AnimaLatentsToImageInvocation:+ return AnimaLatentsToImageInvocation.model_construct(+ latents=MagicMock(latents_name="test_latents"),+ vae=MagicMock(vae=MagicMock()),+ )+++def test_the_oom_retry_does_not_leave_the_shared_vae_tiled():+ """The leak the scoped helper exists for, on the path that used to set the geometry twice.++ Without the scope the retry leaves `use_tiling` set and the 512/384 geometry written onto the+ cached module, so the next node to decode through it silently tiles at a geometry it never+ asked for -- including the Qwen-Image nodes, whose stock tile is 256/192.+ """+ vae = _build_tiny_vae()+ before = _tiling_state(vae)+ context = _build_context(vae, torch.zeros(1, 2, 8, 8))++ real_decode = vae.decode+ attempts: list[bool] = []++ def flaky_decode(*args, **kwargs):+ attempts.append(vae.use_tiling)+ if len(attempts) == 1:+ raise torch.cuda.OutOfMemoryError("CUDA out of memory. Tried to allocate 5.9 GiB")+ return real_decode(*args, **kwargs)++ vae.decode = flaky_decode+ with patch.object(TorchDevice, "choose_torch_device", return_value=torch.device("cpu")):+ _build_invocation().invoke(context)++ # The first attempt was untiled and the retry was tiled -- otherwise nothing was restored.+ assert attempts == [False, True]+ assert vae.use_tiling is False+ assert _tiling_state(vae) == before+++def test_a_tiled_decode_applies_the_calibrated_geometry_and_restores_it():+ """The tiling decision is made against a working-memory estimate calibrated at 512/384, so the+ decode has to run at that geometry -- and hand the cached module back unchanged."""+ vae = _build_tiny_vae()+ before = _tiling_state(vae)+ context = _build_context(vae, torch.zeros(1, 2, 8, 8))++ real_decode = vae.decode+ during: list[tuple] = []++ def spy_decode(*args, **kwargs):+ during.append(_tiling_state(vae))+ return real_decode(*args, **kwargs)++ vae.decode = spy_decode+ with (+ patch.object(TorchDevice, "choose_torch_device", return_value=torch.device("cpu")),+ patch.object(AnimaLatentsToImageInvocation, "_use_tiled_decode", return_value=True),+ ):+ _build_invocation().invoke(context)++ assert during == [(True, ANIMA_VAE_TILE_SIZE, ANIMA_VAE_TILE_SIZE, ANIMA_VAE_TILE_STRIDE, ANIMA_VAE_TILE_STRIDE)]+ assert _tiling_state(vae) == beforediff --git a/tests/app/invocations/test_flux_vae_decode.py b/tests/app/invocations/test_flux_vae_decode.pyindex 8f52ae794d..24ade4f55a 100644--- a/tests/app/invocations/test_flux_vae_decode.py+++ b/tests/app/invocations/test_flux_vae_decode.py@@ -39,6 +39,13 @@ def _loaded_vae(shift_factor: float | None, scaling_factor: float = 0.3611) -> Mreturn vae_info+def _context() -> MagicMock:+ """An invocation context whose `force_tiled_decode` reads False rather than truthy-by-mock."""+ context = MagicMock()+ context.config.get.return_value.force_tiled_decode = False+ return context++@pytest.mark.parametrize("shift_factor", [None, 0.1159])def test_decode_handles_a_config_with_or_without_a_shift_factor(shift_factor: float | None) -> None:"""A config lacking `shift_factor` used to raise `TypeError: unsupported operand ... NoneType`."""@@ -46,7 +53,7 @@ def test_decode_handles_a_config_with_or_without_a_shift_factor(shift_factor: fllatents = torch.ones(1, 16, 1, 1)image = FluxVaeDecodeInvocation._vae_decode(- FluxVaeDecodeInvocation.model_construct(), vae_info=vae_info, latents=latents+ FluxVaeDecodeInvocation.model_construct(), context=_context(), vae_info=vae_info, latents=latents)assert image.size == (8, 8)@@ -62,7 +69,9 @@ def test_decode_treats_an_explicit_none_shift_factor_as_no_shift() -> None:vae_info.model.config.shift_factor = Nonelatents = torch.ones(1, 16, 1, 1)- FluxVaeDecodeInvocation._vae_decode(FluxVaeDecodeInvocation.model_construct(), vae_info=vae_info, latents=latents)+ FluxVaeDecodeInvocation._vae_decode(+ FluxVaeDecodeInvocation.model_construct(), context=_context(), vae_info=vae_info, latents=latents+ )passed = vae_info.model.decode.call_args.args[0]assert torch.allclose(passed, latents / 0.3611)diff --git a/tests/app/invocations/test_flux_vae_decode_tiling.py b/tests/app/invocations/test_flux_vae_decode_tiling.pynew file mode 100644index 0000000000..3d048bf3b9--- /dev/null+++ b/tests/app/invocations/test_flux_vae_decode_tiling.py@@ -0,0 +1,106 @@+"""`force_tiled_decode` on the FLUX.1 latents-to-image node, and its OOM fallback.++The node exposes no tiling fields -- adding any would change the invocation schema -- so the app+config switch is the only way a user can ask it for a tiled decode. It used to be ignored here+while the Z-Image, SD and Qwen-Image decode nodes all honoured it.+"""++from unittest.mock import MagicMock, patch++import pytest+import torch++from invokeai.app.invocations.flux_vae_decode import FluxVaeDecodeInvocation+from invokeai.backend.flux.modules.autoencoder import DEFAULT_TILE_SAMPLE_MIN_SIZE+from invokeai.backend.flux.modules.autoencoder import AutoEncoder as FluxAutoEncoder+++def _build_decode_mocks(latents: torch.Tensor, decoded: torch.Tensor, force_tiled_decode: bool = False):+ """Wire FluxVaeDecodeInvocation.invoke to run end-to-end on CPU against a mocked FLUX VAE."""+ vae = MagicMock(spec=FluxAutoEncoder)+ # A fresh iterator per call: the decode path reads `parameters()` after the estimator already+ # has, and a single stored iterator would be exhausted by then.+ vae.parameters.side_effect = lambda: iter([torch.zeros(1, dtype=torch.float16)])+ vae.decode.return_value = decoded++ vae_info = MagicMock()+ vae_info.model = vae+ vae_info.compute_device = torch.device("cpu")+ cm = MagicMock()+ cm.__enter__ = MagicMock(return_value=(None, vae))+ cm.__exit__ = MagicMock(return_value=None)+ vae_info.model_on_device.return_value = cm++ context = MagicMock()+ context.models.load.return_value = vae_info+ context.tensors.load.return_value = latents+ # A bare MagicMock config would read as truthy and silently tile everything.+ context.config.get.return_value.force_tiled_decode = force_tiled_decode+ image_dto = MagicMock()+ image_dto.image_name = "test.png"+ image_dto.width = decoded.shape[-1]+ image_dto.height = decoded.shape[-2]+ context.images.save.return_value = image_dto+ return vae, vae_info, context+++def _build_invocation() -> FluxVaeDecodeInvocation:+ return FluxVaeDecodeInvocation.model_construct(+ latents=MagicMock(latents_name="test_latents"),+ vae=MagicMock(vae=MagicMock()),+ )+++class TestForceTiledDecode:+ def test_the_default_decodes_untiled(self):+ vae, _, context = _build_decode_mocks(torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512))+ _build_invocation().invoke(context)+ vae.disable_tiling.assert_called_once()+ vae.enable_tiling.assert_not_called()++ def test_the_config_flag_reaches_the_tiled_path(self):+ vae, _, context = _build_decode_mocks(+ torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512), force_tiled_decode=True+ )+ _build_invocation().invoke(context)+ vae.enable_tiling.assert_called_once_with(tile_sample_min_size=DEFAULT_TILE_SAMPLE_MIN_SIZE)+ vae.disable_tiling.assert_not_called()++ @pytest.mark.parametrize("force_tiled_decode,expected_tile_size", [(False, None), (True, 0)])+ def test_the_reservation_matches_the_decode_that_will_run(self, force_tiled_decode, expected_tile_size):+ """A tiled decode reserved for a single pass is the OOM the retry exists to avoid, and an+ untiled decode reserved for a tile evicts models it did not need to."""+ path = "invokeai.app.invocations.flux_vae_decode.estimate_vae_working_memory_flux"+ _, _, context = _build_decode_mocks(+ torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512), force_tiled_decode=force_tiled_decode+ )+ with patch(path, return_value=1024) as estimate:+ _build_invocation().invoke(context)+ assert estimate.call_args.kwargs["tile_size"] == expected_tile_size+++class TestOomFallback:+ def test_an_untiled_oom_retries_once_tiled_and_says_so(self):+ decoded = torch.zeros(1, 3, 512, 512)+ vae, _, context = _build_decode_mocks(torch.zeros(1, 16, 64, 64), decoded)+ vae.decode.side_effect = [torch.cuda.OutOfMemoryError("CUDA out of memory"), decoded]++ result = _build_invocation().invoke(context)++ assert vae.decode.call_count == 2+ vae.enable_tiling.assert_called_once_with(tile_sample_min_size=DEFAULT_TILE_SAMPLE_MIN_SIZE)+ # The retry takes noticeably longer than the failed attempt; the user is told why.+ context.util.signal_progress.assert_any_call("VAE decode ran out of memory, retrying tiled")+ assert result.width == 512++ def test_an_oom_while_already_tiled_reraises(self):+ vae, _, context = _build_decode_mocks(+ torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512), force_tiled_decode=True+ )+ vae.decode.side_effect = torch.cuda.OutOfMemoryError("CUDA out of memory")++ with pytest.raises(torch.cuda.OutOfMemoryError):+ _build_invocation().invoke(context)++ assert vae.decode.call_count == 1+ vae.enable_tiling.assert_called_once()diff --git a/tests/app/invocations/test_int8_denoise_working_memory.py b/tests/app/invocations/test_int8_denoise_working_memory.pynew file mode 100644index 0000000000..4d4ad685d5--- /dev/null+++ b/tests/app/invocations/test_int8_denoise_working_memory.py@@ -0,0 +1,113 @@+"""The per-forward int8 dequant transient has to reach `model_on_device()`.++`Int8ConvrotLinear` keeps its weight int8 and materializes the dequantized, derotated weight per+forward. That allocation is not part of the model's resident size, so unless the node asks the+cache to hold room for it, the cache is free to pack the device with weights right up to the+default working memory and the first forward competes with what it just placed.++`peak_int8_dequant_transient_bytes` is unit-tested next to the module it belongs to. What is+pinned here is the wire: deleting the `working_mem_bytes=` argument from the node leaves every+other test green. Z-Image only -- MiniMax H3 adds the same term; reaching its `model_on_device()` call needs a packed sequence.+Krea-2's wiring is pinned separately, in `tests/app/invocations/test_krea2_denoise.py`.+"""++from types import SimpleNamespace+from unittest.mock import MagicMock, patch++import pytest+import torch++from invokeai.app.invocations.fields import ZImageConditioningField+from invokeai.app.invocations.z_image_denoise import ZImageDenoiseInvocation+from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, ModelType+from invokeai.backend.quantization.int8_convrot import CONVROT_GROUP_SIZE, Int8ConvrotLinear+++class _StopBeforeLoad(Exception):+ """Raised out of the mocked `model_on_device()` so the node stops at the reservation."""+++def _int8_model(out_features: int, in_features: int) -> torch.nn.Module:+ model = torch.nn.Module()+ model.proj = Int8ConvrotLinear(+ torch.zeros(out_features, in_features, dtype=torch.int8),+ torch.ones(out_features, 1),+ convrot=False,+ )+ return model+++class TestZImage:+ """Z-Image has no activation estimate, so the transient is the whole request; the cache floors+ it at `device_working_mem_gb`, which is what covers activations there."""++ def _reserved_by(self, transformer: torch.nn.Module) -> int:+ from invokeai.backend.stable_diffusion.diffusion.conditioning_data import (+ ConditioningFieldData,+ ZImageConditioningInfo,+ )++ transformer_info = MagicMock()+ transformer_info.model = transformer+ transformer_info.model_on_device = MagicMock(side_effect=_StopBeforeLoad)++ context = MagicMock()+ context.models.load.return_value = transformer_info+ context.models.get_config.return_value = SimpleNamespace(+ base=BaseModelType.ZImage, type=ModelType.Main, format=ModelFormat.Checkpoint+ )+ context.conditioning.load.return_value = ConditioningFieldData(+ conditionings=[ZImageConditioningInfo(prompt_embeds=torch.zeros(1, 8, 2560))]+ )++ invocation = ZImageDenoiseInvocation.model_construct(+ latents=None,+ noise=None,+ denoise_mask=None,+ denoising_start=0.0,+ denoising_end=1.0,+ add_noise=True,+ transformer=MagicMock(transformer=MagicMock(), loras=[]),+ positive_conditioning=ZImageConditioningField(conditioning_name="pos"),+ negative_conditioning=None,+ control=None,+ vae=None,+ guidance_scale=1.0,+ width=256,+ height=256,+ steps=2,+ scheduler="euler",+ seed=0,+ cfg_scale_start_step=0,+ cfg_scale_end_step=-1,+ )++ with (+ patch(+ "invokeai.app.invocations.z_image_denoise.TorchDevice.choose_torch_device",+ return_value=torch.device("cpu"),+ ),+ patch(+ "invokeai.app.invocations.z_image_denoise.TorchDevice.choose_bfloat16_safe_dtype",+ return_value=torch.bfloat16,+ ),+ patch.object(ZImageDenoiseInvocation, "_get_noise", return_value=torch.zeros(1, 16, 32, 32)),+ pytest.raises(_StopBeforeLoad),+ ):+ invocation._run_diffusion(context)++ transformer_info.model_on_device.assert_called_once()+ return transformer_info.model_on_device.call_args.kwargs["working_mem_bytes"]++ def test_the_transient_reaches_the_model_cache(self) -> None:+ """Two weight-sized bf16 tensors of the largest int8 layer."""+ reserved = self._reserved_by(_int8_model(1024, CONVROT_GROUP_SIZE))++ assert reserved == 2 * 1024 * CONVROT_GROUP_SIZE * torch.bfloat16.itemsize++ def test_an_unquantized_transformer_asks_for_nothing_extra(self) -> None:+ """Zero falls through the cache's `or`, leaving the configured default exactly as before."""+ dense = torch.nn.Module()+ dense.proj = torch.nn.Linear(CONVROT_GROUP_SIZE, 8)++ assert self._reserved_by(dense) == 0diff --git a/tests/app/invocations/test_krea2_denoise.py b/tests/app/invocations/test_krea2_denoise.pyindex 4bbde4cffe..bca7420cab 100644--- a/tests/app/invocations/test_krea2_denoise.py+++ b/tests/app/invocations/test_krea2_denoise.py@@ -13,7 +13,7 @@ from invokeai.app.invocations.krea2_denoise import ()from invokeai.app.invocations.model import ModelIdentifierField, TransformerFieldfrom invokeai.backend.model_manager.taxonomy import BaseModelType, Krea2VariantType, ModelFormat, ModelType-from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear+from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear, peak_int8_dequant_transient_bytesfrom invokeai.backend.stable_diffusion.diffusion.conditioning_data import ConditioningFieldData, Krea2ConditioningInfo@@ -346,8 +346,18 @@ class _TransformerInfo:def __init__(self, transformer: _Transformer) -> None:self.transformer = transformer+ @property+ def model(self):+ """`LoadedModel.model` -- the model without locking it.++ Several denoise nodes read it to size their working-memory reservation, which has to happen+ before `model_on_device` is entered.+ """+ return self.transformer+@contextmanager- def model_on_device(self, **_kwargs):+ def model_on_device(self, **kwargs):+ self.working_mem_bytes = kwargs.get("working_mem_bytes")yield ({}, self.transformer)@@ -796,3 +806,39 @@ class TestRequiresSidecarPatching:)tree = self._Tree(torch.nn.Linear(2, 2), int8_linear)assert requires_sidecar_patching(tree, ModelFormat.Checkpoint)+++class TestTheInt8DequantTransientReachesTheReservation:+ """An int8_tensorwise build materializes the dequantized, derotated weight per forward call.++ The activation estimate cannot see it -- the weights are buffers, and the transient is allocated+ inside the layer -- so without this the cache reserves for the activations alone and a model that+ loaded comfortably OOMs in its first step. A helper existing is not the same as it being called,+ which is the regression worth catching here rather than in the helper's own unit test.+ """++ def _reservation_for(self, monkeypatch, tmp_path, transformer: _Transformer) -> int:+ info = _TransformerInfo(transformer)+ context = _runtime_context(tmp_path, transformer)+ context.models.load = lambda _identifier: info+ _patch_runtime(monkeypatch)+ _runtime_invocation(cfg_scale=1.0)._run_diffusion(context)+ return info.working_mem_bytes++ def test_an_int8_model_reserves_the_transient_on_top_of_the_activations(self, monkeypatch, tmp_path) -> None:+ dense = _Transformer()+ quantized = _Transformer()+ layer = Int8ConvrotLinear(+ weight=torch.zeros(1024, 512, dtype=torch.int8),+ weight_scale=torch.ones(1024, 1),+ convrot=False,+ )+ quantized.modules = lambda: iter((quantized, layer))++ dense_bytes = self._reservation_for(monkeypatch, tmp_path, dense)+ quantized_bytes = self._reservation_for(monkeypatch, tmp_path, quantized)++ # `_patch_runtime` pins the compute dtype to float32, which is what the node passes on.+ transient = peak_int8_dequant_transient_bytes(quantized, torch.float32)+ assert transient > 0+ assert quantized_bytes == dense_bytes + transientdiff --git a/tests/app/invocations/test_z_image_tiled_decode.py b/tests/app/invocations/test_z_image_tiled_decode.pyindex 255cc88ac3..04380b022b 100644--- a/tests/app/invocations/test_z_image_tiled_decode.py+++ b/tests/app/invocations/test_z_image_tiled_decode.py@@ -30,50 +30,132 @@ class TestFluxWorkingMemoryEstimate:actual = estimate_vae_working_memory_flux(operation="decode", image_tensor=latents, vae=_mock_flux_vae())assert actual == expected- @pytest.mark.parametrize("latent_hw", [(128, 128), (192, 192), (256, 256)])- def test_a_tiled_estimate_does_not_grow_with_the_image(self, latent_hw):- """The point of the bound: peak memory is one tile, whatever the resolution."""- h, w = latent_hw+ def test_the_tiled_estimate_is_a_tile_bounded_decode_plus_the_assembled_image(self):+ """The magnitude of both tiled terms, at one resolution, derived independently.++ Everything else about the tiled branch is a comparison against another call of the same+ function, which tracks the shape of the estimate but not its size. Dropping the 25% tile+ margin or halving the per-pixel image cost would be a several-hundred-megabyte+ under-reservation that no other assertion here can see.+ """+ # 512px tiles, fp16, over a 1536x1536 output.+ decode_term = 512 * 512 * 2 * 2200 * 1.25+ # 4 RGB buffers at the VAE's element size, plus the 8-bit one the node hands to PIL. Four+ # is measured, not assumed: the assembled image grows the device peak by ~1.6 copies on a+ # diffusers VAE and ~0.1 on the host-merging BFL one, and the node adds its in-window+ # clamp/scale copies on top. See the constant's comment for the measurements.+ image_term = 1536 * 1536 * 3 * (4 * 2 + 1)estimate = estimate_vae_working_memory_flux(- operation="decode", image_tensor=torch.zeros(1, 16, h, w), vae=_mock_flux_vae(), tile_size=512+ operation="decode", image_tensor=torch.zeros(1, 16, 192, 192), vae=_mock_flux_vae(), tile_size=512+ )+ assert estimate == int(decode_term + image_term)++ def test_both_tiled_terms_scale_with_the_vaes_element_size(self):+ """An fp32 VAE costs twice the bytes per pixel, in the tile and in the assembled image+ alike. Only the 8-bit buffer is fixed, which is why this is a little under 2x."""+ latents = torch.zeros(1, 16, 192, 192)+ fp16 = estimate_vae_working_memory_flux(+ operation="decode", image_tensor=latents, vae=_mock_flux_vae(element_size_bytes=2), tile_size=512+ )+ fp32 = estimate_vae_working_memory_flux(+ operation="decode", image_tensor=latents, vae=_mock_flux_vae(element_size_bytes=4), tile_size=512)- assert estimate == int(512 * 512 * 2 * 2200 * 1.25)+ assert 1.95 < fp32 / fp16 < 2.0- def test_a_tiled_estimate_is_smaller_than_the_untiled_one_where_it_matters(self):- latents = torch.zeros(1, 16, 192, 192) # 1536px, the resolution that OOMs on 16GB+ @pytest.mark.parametrize("latent_hw", [(128, 128), (192, 192), (256, 256)])+ def test_a_tiled_estimate_stays_a_fraction_of_the_untiled_one(self, latent_hw):+ """The point of the bound: the decode itself costs one tile, whatever the resolution.++ Not a flat number -- the assembled image and the node's post-processing are full-resolution+ however small the tile is, so an O(image) term rides along. That term is small next to the+ decode the bound removes, and this pins how small across a 4x span of image area. (It holds+ because a 512px tile is well under these images; a tile near the image size is priced at+ the clamped tile plus the same image term, which can land above the single-pass estimate.)+ """+ latents = torch.zeros(1, 16, *latent_hw)untiled = estimate_vae_working_memory_flux(operation="decode", image_tensor=latents, vae=_mock_flux_vae())tiled = estimate_vae_working_memory_flux(operation="decode", image_tensor=latents, vae=_mock_flux_vae(), tile_size=512)+ assert tiled < untiled / 2++ def test_a_tile_larger_than_the_image_is_not_estimated_as_tiled(self):+ """`_tiled_decode` short-circuits once the tile covers the image, so the reservation has to.++ `tile_size` has no upper bound, and the quadratic tile term ran away from the decode that+ would actually happen: a 4096px tile on a 1024px image reserved ~23GB for a single-pass+ decode needing ~4.6GB, evicting the transformer from the cache to make room for nothing.+ """+ latents = torch.zeros(1, 16, 128, 128) # 1024px+ untiled = estimate_vae_working_memory_flux(operation="decode", image_tensor=latents, vae=_mock_flux_vae())+ oversized = estimate_vae_working_memory_flux(+ operation="decode", image_tensor=latents, vae=_mock_flux_vae(), tile_size=4096+ )+ assert oversized == untiled++ def test_a_tile_wider_than_one_axis_is_priced_at_the_clamped_tile(self):+ """`calc_tiles_min_overlap` clamps the tile to the image on each axis independently.++ A 1024x8192 image tiled with a 4096px tile therefore decodes 1024x4096 tiles, never+ 4096x4096 ones. Pricing the requested tile squared put the reservation 2.5x *above* the+ single-pass decode that tiling is there to avoid -- ~92GB against ~37GB.+ """+ latents = torch.zeros(1, 16, 128, 1024) # 1024 x 8192 px: only the long axis exceeds the tile+ tiled = estimate_vae_working_memory_flux(+ operation="decode", image_tensor=latents, vae=_mock_flux_vae(), tile_size=4096+ )+ untiled = estimate_vae_working_memory_flux(operation="decode", image_tensor=latents, vae=_mock_flux_vae())assert tiled < untiled+ def test_a_tiled_estimate_still_covers_the_assembled_image(self):+ """The other half of the bound: tiling caps the decode, not the assembly.++ The assembled output is one full-resolution device tensor, and the node then runs `clamp`,+ `+ 1.0`, `* 127.5` and `.byte()` over it. At 8192x8192 in fp16 a single one of those RGB+ buffers is 402MB, so a tile-only estimate is short by more than it reserves. This is the+ second resolution the image term is checked at, so a term that did not scale with area+ would fail here even if it matched at 1536px.+ """+ estimate = estimate_vae_working_memory_flux(+ operation="decode", image_tensor=torch.zeros(1, 16, 1024, 1024), vae=_mock_flux_vae(), tile_size=512+ )+ tile_term = int(512 * 512 * 2 * 2200 * 1.25)+ one_full_resolution_buffer = 8192 * 8192 * 3 * 2+ # The assembled output plus at least one of the post-processing copies.+ assert estimate >= tile_term + 2 * one_full_resolution_buffer+def test_the_sentinel_does_not_read_the_size_off_the_vae(self):"""Upstream #9427 found this exact shape of bug in the Qwen estimator: reading`vae.tile_sample_min_size` returns whatever the *previous* invocation left on the cachedmodule, not the default this node is asking for."""+ latents = torch.zeros(1, 16, 192, 192)vae = _mock_flux_vae()vae.tile_sample_min_size = 384 # as if a previous run had set it- estimate = estimate_vae_working_memory_flux(- operation="decode", image_tensor=torch.zeros(1, 16, 192, 192), vae=vae, tile_size=0+ estimate = estimate_vae_working_memory_flux(operation="decode", image_tensor=latents, vae=vae, tile_size=0)+ assert estimate == estimate_vae_working_memory_flux(+ operation="decode", image_tensor=latents, vae=_mock_flux_vae(), tile_size=DEFAULT_TILE_SAMPLE_MIN_SIZE)- assert estimate == int(DEFAULT_TILE_SAMPLE_MIN_SIZE**2 * 2 * 2200 * 1.25)def test_the_sentinel_works_on_a_vae_without_that_attribute_at_all(self):# The Z-Image nodes also hand a diffusers AutoencoderKL to this estimator; the SD1/SDXL# sibling dereferences `vae.tile_sample_min_size` directly and would raise here.+ latents = torch.zeros(1, 16, 192, 192)vae = MagicMock(spec=AutoencoderKL)vae.parameters.side_effect = lambda: iter([torch.zeros(1, dtype=torch.float16)])del vae.tile_sample_min_size- estimate = estimate_vae_working_memory_flux(- operation="decode", image_tensor=torch.zeros(1, 16, 192, 192), vae=vae, tile_size=0+ estimate = estimate_vae_working_memory_flux(operation="decode", image_tensor=latents, vae=vae, tile_size=0)+ assert estimate == estimate_vae_working_memory_flux(+ operation="decode", image_tensor=latents, vae=_mock_flux_vae(), tile_size=DEFAULT_TILE_SAMPLE_MIN_SIZE)- assert estimate == int(DEFAULT_TILE_SAMPLE_MIN_SIZE**2 * 2 * 2200 * 1.25)def test_a_tile_below_the_cost_floor_is_estimated_at_the_floor(self):+ latents = torch.zeros(1, 16, 192, 192)estimate = estimate_vae_working_memory_flux(- operation="decode", image_tensor=torch.zeros(1, 16, 192, 192), vae=_mock_flux_vae(), tile_size=8+ operation="decode", image_tensor=latents, vae=_mock_flux_vae(), tile_size=8+ )+ assert estimate == estimate_vae_working_memory_flux(+ operation="decode", image_tensor=latents, vae=_mock_flux_vae(), tile_size=MIN_TILE_SAMPLE_SIZE)- assert estimate == int(MIN_TILE_SAMPLE_SIZE**2 * 2 * 2200 * 1.25)def _build_decode_mocks(latents: torch.Tensor, decoded: torch.Tensor, force_tiled_decode: bool = False):@@ -118,16 +200,6 @@ class TestTilingIsWired:vae.disable_tiling.assert_called_once()vae.enable_tiling.assert_not_called()- def test_the_tiling_state_is_restored_after_the_invocation(self):- """The VAE belongs to the model cache and is shared with nodes that never touch the flag --- FLUX.1 encode, PiD, Anima's FLUX branch. A tiled run must not leave them tiled."""- vae, _, context = _build_decode_mocks(torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512))- vae.use_tiling = False- vae.tile_sample_min_size = DEFAULT_TILE_SAMPLE_MIN_SIZE- _build_invocation(tiled=True, tile_size=256).invoke(context)- assert vae.use_tiling is False- assert vae.tile_sample_min_size == DEFAULT_TILE_SAMPLE_MIN_SIZE-def test_the_node_field_reaches_the_tiled_path(self):vae, _, context = _build_decode_mocks(torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512))_build_invocation(tiled=True).invoke(context)@@ -176,6 +248,10 @@ class TestOomFallback:assert vae.decode.call_count == 2vae.enable_tiling.assert_called_once_with(tile_sample_min_size=DEFAULT_TILE_SAMPLE_MIN_SIZE)assert result.width == 512+ # The user gets a different image than they asked for, so both channels have to carry it: the+ # progress line while it happens, and a log line a bug report can still be read off afterwards.+ context.util.signal_progress.assert_any_call("VAE decode ran out of memory, retrying tiled")+ assert "not identical to an untiled decode" in context.logger.warning.call_args[0][0]def test_a_non_oom_error_propagates_without_a_retry(self):vae, _, context = _build_decode_mocks(torch.zeros(1, 16, 64, 64), torch.zeros(1, 3, 512, 512))diff --git a/tests/app/services/shared/sqlite/test_sqlite_synchronous.py b/tests/app/services/shared/sqlite/test_sqlite_synchronous.pyindex 703d88efd5..d51116dee5 100644--- a/tests/app/services/shared/sqlite/test_sqlite_synchronous.py+++ b/tests/app/services/shared/sqlite/test_sqlite_synchronous.py@@ -1,10 +1,13 @@"""The `synchronous` PRAGMA, and the config field that sets it.-`full` fsyncs on every commit and is SQLite's own default; `normal` under WAL trades the most recent-transactions on a power loss for much shorter commits. The default must not move, because that would-change the durability of every existing install without anyone asking for it.+`full` fsyncs on every commit and is what InvokeAI has always run with; `normal` trades the most+recent transactions on a power loss for much shorter commits, and is only safe from corruption+under WAL. The default must not move, because that would change the durability of every existing+install without anyone asking for it."""+import logging+import sqlite3from unittest.mock import Mockimport pytest@@ -23,6 +26,33 @@ def _synchronous_of(db: SqliteDatabase) -> int:return int(db._conn.execute("PRAGMA synchronous;").fetchone()[0])+def _journal_mode_of(db: SqliteDatabase) -> str:+ return str(db._conn.execute("PRAGMA journal_mode;").fetchone()[0]).lower()+++def _warnings_about_durability(caplog: pytest.LogCaptureFixture) -> list[str]:+ """Warnings this setting is responsible for, so an unrelated one from elsewhere cannot decide a test."""+ messages = [record.getMessage().lower() for record in caplog.records if record.levelno >= logging.WARNING]+ return [message for message in messages if "journal" in message or "synchronous" in message]+++def sqlite_cannot_use_wal(monkeypatch: pytest.MonkeyPatch) -> None:+ """Makes WAL genuinely unavailable, the way a network filesystem or an `SQLITE_OMIT_WAL` build does.++ SQLite refuses to move a transient database into WAL mode, so the connection opened here answers+ `PRAGMA journal_mode = WAL;` with a rollback-journal mode instead -- a real refusal from real+ SQLite. The interception is at the `sqlite3.connect` boundary; everything `SqliteDatabase` does+ after it is the production path.+ """+ real_connect = sqlite3.connect++ def connect_to_a_database_that_refuses_wal(database: object, **kwargs: object) -> sqlite3.Connection:+ return real_connect("", **kwargs) # type: ignore[arg-type]++ monkeypatch.setattr(sqlite3, "connect", connect_to_a_database_that_refuses_wal)++class TestTheConfigField:def test_the_default_is_full(self):# Anything else would silently reduce durability for every existing install on upgrade.@@ -40,8 +70,24 @@ class TestTheConfigField:InvokeAIAppConfig(db_synchronous=value)+class TestTheConstructorValidatesTheSetting:+ """`SqliteDatabase` is a public constructor -- `user_management.py` and tests call it directly --+ and the value ends up interpolated into a PRAGMA statement, which takes no bind parameters. The+ `Literal` annotation is checked by a type checker, not at runtime, so the constructor checks it."""++ @pytest.mark.parametrize("value", ["normal; DROP TABLE x", "off", "NORMAL", "", "1"])+ def test_a_value_outside_the_literal_never_reaches_sql(self, tmp_path, value):+ db_path = tmp_path / "rejected.db"++ with pytest.raises(ValueError, match="synchronous"):+ SqliteDatabase(db_path=db_path, logger=InvokeAILogger.get_logger(), synchronous=value)++ # Rejected before anything was opened, so there is nothing for the statement to have run against.+ assert not db_path.exists()++class TestThePragmaIsApplied:- def test_the_default_leaves_sqlites_own_default_in_place(self, tmp_path):+ def test_the_default_setting_uses_full(self, tmp_path):db = SqliteDatabase(db_path=tmp_path / "default.db", logger=InvokeAILogger.get_logger())assert _synchronous_of(db) == PRAGMA_VALUES["full"]@@ -54,16 +100,46 @@ class TestThePragmaIsApplied:)assert _synchronous_of(db) == PRAGMA_VALUES[setting]- def test_it_applies_to_an_in_memory_database_too(self):- # The migrator and several tests use the in-memory path; it must not diverge.+ def test_an_in_memory_database_keeps_normal_despite_having_no_journal(self):+ """An in-memory database reports journal mode `memory`, never `wal`, but it has no durability+ to trade away in the first place -- so the WAL requirement below must not reach it. The+ migrator and several tests run on this path."""db = SqliteDatabase(db_path=None, logger=InvokeAILogger.get_logger(), synchronous="normal")++ assert _journal_mode_of(db) != "wal"assert _synchronous_of(db) == PRAGMA_VALUES["normal"]def test_wal_is_still_on(self, tmp_path):"""`normal` is only safe against corruption *because* of WAL. If journal mode ever stopped- being WAL, this setting would become a different trade than the one documented."""+ being WAL for an ordinary database file, this setting would become a different trade than the+ one documented."""db = SqliteDatabase(db_path=tmp_path / "wal.db", logger=InvokeAILogger.get_logger(), synchronous="normal")- assert db._conn.execute("PRAGMA journal_mode;").fetchone()[0].lower() == "wal"+ assert _journal_mode_of(db) == "wal"++ def test_normal_is_refused_when_wal_did_not_engage(self, tmp_path, caplog, sqlite_cannot_use_wal):+ """WAL needs shared memory, which NFS/SMB shares, some container volume drivers and+ `SQLITE_OMIT_WAL` builds do not provide; `PRAGMA journal_mode = WAL` then quietly leaves a+ rollback journal in place. `normal` on a rollback journal *can* corrupt the database on power+ loss, which is the opposite of what the setting is documented to do, so it is refused."""+ logger = InvokeAILogger.get_logger()++ with caplog.at_level(logging.WARNING):+ db = SqliteDatabase(db_path=tmp_path / "no-wal.db", logger=logger, synchronous="normal")++ journal_mode = _journal_mode_of(db)+ assert journal_mode != "wal"+ assert _synchronous_of(db) == PRAGMA_VALUES["full"]+ assert any(journal_mode in message and "normal" in message for message in _warnings_about_durability(caplog))++ def test_full_is_applied_without_a_warning_when_wal_did_not_engage(self, tmp_path, caplog, sqlite_cannot_use_wal):+ # Nothing to refuse: `full` is already the stricter setting, so a warning would be noise.+ logger = InvokeAILogger.get_logger()++ with caplog.at_level(logging.WARNING):+ db = SqliteDatabase(db_path=tmp_path / "no-wal-full.db", logger=logger)++ assert _synchronous_of(db) == PRAGMA_VALUES["full"]+ assert _warnings_about_durability(caplog) == []class TestTheSettingReachesTheDatabase:diff --git a/tests/app/util/test_attention_backend_probe.py b/tests/app/util/test_attention_backend_probe.pyindex 8e9043a1cb..e97634781e 100644--- a/tests/app/util/test_attention_backend_probe.py+++ b/tests/app/util/test_attention_backend_probe.py@@ -11,9 +11,18 @@ from unittest.mock import MagicMock, patchimport pytestimport torch+import invokeai.app.util.startup_utils as startup_utilsfrom invokeai.app.util.startup_utils import log_attention_backends, probe_attention_backends[email protected](autouse=True)+def _forget_logged_devices():+ """The log is once per device per process, so a leftover entry would silently pass the next test."""+ startup_utils._logged_attention_backends.clear()+ yield+ startup_utils._logged_attention_backends.clear()++class TestProbe:@pytest.mark.parametrize("device_type", ["cpu", "mps"])def test_a_non_cuda_device_is_not_probed(self, device_type):@@ -25,6 +34,20 @@ class TestProbe:with patch.object(torch, "empty", side_effect=RuntimeError("no CUDA driver")):assert probe_attention_backends(torch.device("cuda")) is None+ def test_a_failure_in_the_cleanup_does_not_propagate_either(self):+ """The cleanup used to sit in a `finally` on the same `try` as the handler, which does not+ cover it -- so a raise from `empty_cache()` escaped a function whose contract is that it+ never does."""+ with (+ patch.object(torch, "empty", return_value=MagicMock()),+ patch.object(torch.backends.cuda, "SDPAParams", return_value=MagicMock()),+ patch.object(torch.backends.cuda, "can_use_cudnn_attention", return_value=True),+ patch.object(torch.backends.cuda, "can_use_flash_attention", return_value=True),+ patch.object(torch.backends.cuda, "can_use_efficient_attention", return_value=True),+ patch.object(torch.cuda, "empty_cache", side_effect=RuntimeError("allocator is gone")),+ ):+ assert probe_attention_backends(torch.device("cuda")) is None+def test_math_is_reported_as_always_available(self):# It is the unfused fallback, not a kernel that can be missing -- so it is never probed for.with (@@ -79,3 +102,30 @@ class TestLogLine:assert "head_dim 128" in message# And the caveat that keeps it from being read as a dispatch table.assert "no mask" in message++ def test_it_is_logged_once_per_device(self, caplog):+ """The probe allocates, which creates that device's CUDA context. Repeating it per generation+ would pay that on a device the session may not even be using."""+ logger = logging.getLogger("test_probe_once")+ probe = MagicMock(return_value={"cudnn": True, "flash": False, "efficient": True, "math": True})+ with patch("invokeai.app.util.startup_utils.probe_attention_backends", probe):+ with caplog.at_level(logging.INFO, logger=logger.name):+ log_attention_backends(logger, torch.device("cuda:0"))+ log_attention_backends(logger, torch.device("cuda:0"))+ log_attention_backends(logger, torch.device("cuda:1"))++ assert probe.call_count == 2+ assert [r.message.split(" (fp16")[0] for r in caplog.records] == [+ "SDPA attention backends on cuda:0",+ "SDPA attention backends on cuda:1",+ ]++ def test_a_device_that_could_not_be_probed_is_not_remembered(self):+ """Answering None is not an answer. Remembering it would suppress the line for good on a+ device whose first probe happened to land before the driver was ready."""+ logger = logging.getLogger("test_probe_retry")+ probe = MagicMock(side_effect=[None, {"cudnn": True, "flash": True, "efficient": True, "math": True}])+ with patch("invokeai.app.util.startup_utils.probe_attention_backends", probe):+ log_attention_backends(logger, torch.device("cuda:0"))+ log_attention_backends(logger, torch.device("cuda:0"))+ assert probe.call_count == 2diff --git a/tests/backend/flux/modules/test_autoencoder_tiling.py b/tests/backend/flux/modules/test_autoencoder_tiling.pyindex fc21697c54..79cc2c6218 100644--- a/tests/backend/flux/modules/test_autoencoder_tiling.py+++ b/tests/backend/flux/modules/test_autoencoder_tiling.py@@ -4,8 +4,10 @@ The reference numbers for tiled-vs-untiled agreement come from measurement, notown tiling of this VAE gives max 0.082 / mean 0.0022 per pixel at 1536px on a +/-1 image. A tileddecode of this architecture can never be exact, because the decoder's GroupNorms normalise over thewhole spatial extent and its mid-block attention is global -- both see a different input when the-image arrives in tiles. What *is* exact is the tile geometry, and `test_geometry_is_exact_without_-the_global_operators` pins it by removing those two operators and demanding equality.+image arrives in tiles. `test_the_full_decoder_lands_in_the_measured_accuracy_band` pins that gap+from both sides on the shipping decoder. What *is* exact is the tile geometry, and+`test_geometry_is_exact_without_the_global_operators` pins it by removing those two operators and+demanding equality."""import numpy as np@@ -86,16 +88,42 @@ class TestTilingState:({"tile_sample_min_size": 500}, "divisible by 8"),({"tile_overlap": 100}, "divisible by 8"),({"tile_sample_min_size": 128, "tile_overlap": 128}, "must be smaller than"),+ ({"tile_overlap": 0}, "greater than 0"),+ # The automatic overlap for an 8px tile is min(128, 4) rounded down to a multiple of+ # 8, i.e. 0. `merge_tiles_with_linear_blending` would take that as a blend band of+ # zero pixels and butt the tiles together with a hard seam instead of blending.+ ({"tile_sample_min_size": 8}, "greater than 0"),],)def test_geometry_that_cannot_be_sliced_is_rejected(self, kwargs, message):# A tile edge that is not a multiple of the compression factor has no exact latent slice,- # and an overlap at least as large as the tile makes the layout degenerate.+ # and an overlap at least as large as the tile -- or no overlap at all -- makes the layout+ # degenerate.with pytest.raises(ValueError, match=message):_build_autoencoder().enable_tiling(**kwargs)class TestTiledDecode:+ def test_the_full_decoder_lands_in_the_measured_accuracy_band(self):+ """The counterweight to the test below: exactness is a property of the *geometry* only.++ With the GroupNorms and the mid-block attention left in place -- i.e. the decoder that+ actually ships -- a tiled decode differs from a single-pass one everywhere, because both+ operators see the whole spatial extent and a tile is not the whole image. Measured on this+ fixture at 768px: 0.113 at the shipped 512/128 geometry, against an output range of about+ +/-2.7. The floor rules out the `enable_tiling` docstring's since-corrected claim of float32+ epsilon; the ceiling has ~2.7x headroom over the measurement and rules out a blend band,+ tile offset or slice that is merely plausible rather than right (a 128px tile, four times+ the seams, already drifts to 0.67).+ """+ ae = _build_autoencoder()+ z = torch.randn(1, 16, 96, 96)+ with torch.no_grad():+ untiled = ae.decode(z)+ ae.enable_tiling()+ tiled = ae.decode(z)+ assert 1e-3 < (untiled - tiled).abs().max() < 0.3+def test_geometry_is_exact_without_the_global_operators(self):ae = _build_autoencoder()_make_purely_convolutional(ae)@@ -115,6 +143,20 @@ class TestTiledDecode:(128, 128), # 2x2 tiles, evenly divided(100, 77), # odd on both axes(64, 160), # tiling on one axis only+ # One axis exactly as small as the latent overlap (128px / 8 = 16). `calc_tiles_min_+ # overlap` clamps the tile down to the image there and then divides by+ # `tile - min_overlap`, which used to raise ZeroDivisionError -- including on the OOM+ # retry, where it replaced the out-of-memory error with a division by zero.+ (16, 96),+ (96, 16),+ # Same clamp, but the long axis now lands on a 15-latent (120px) tile overlap rather+ # than a comfortable 32-latent one. That is *below* the configured 128px overlap, so+ # the blend amount has to come from the clamped overlap; the configured one trips+ # `merge_tiles_with_linear_blending`'s `tile.overlap >= blend_amount` assertion.+ (16, 113),+ # A 1-latent axis leaves no overlap at all once clamped, so the layout is degenerate+ # and the decode falls back to a single pass.+ (1, 96),],)def test_shape_and_dtype_survive_every_layout(self, latent_hw):@@ -182,19 +224,23 @@ class TestTiledDecode:with torch.no_grad():assert ae.decode(torch.randn(1, 16, 96, 96)).shape == (1, 3, 768, 768)- def test_finished_tiles_do_not_stay_on_the_decode_device(self):- # Bounding the peak is the entire point: a tile is moved off the device as soon as it is- # decoded, so what the merge sees is numpy on the host.+ def test_every_tile_reaches_the_merge_as_a_host_array(self):+ """What tiling bounds and what it does not.++ A tile leaves the decode device as soon as it is decoded, which is what bounds *device*+ memory to one tile. Host memory is a different story: the merge runs after the loop, so it+ receives all of them at once and the host holds the whole image in tiles. The decoder's+ docstring has to say both, and this is the observation behind it.+ """ae = _build_autoencoder()- seen: list[type] = []- real_merge = None+ seen: list[tuple[list[type], int]] = []import invokeai.backend.flux.modules.autoencoder as autoencoder_modulereal_merge = autoencoder_module.merge_tiles_with_linear_blendingdef spy(dst_image, tiles, tile_images, blend_amount):- seen.extend(type(t) for t in tile_images)+ seen.append(([type(t) for t in tile_images], blend_amount))return real_merge(dst_image, tiles, tile_images, blend_amount)autoencoder_module.merge_tiles_with_linear_blending = spy@@ -205,4 +251,38 @@ class TestTiledDecode:finally:autoencoder_module.merge_tiles_with_linear_blending = real_merge- assert seen and all(t is np.ndarray for t in seen)+ # 96 latents against a 64-latent tile with a 16-latent minimum overlap needs two tiles per+ # axis, so four in total -- and the merge is handed all four in one call. The blend band is+ # the configured overlap here, because nothing about this layout forces the clamp.+ assert seen == [([np.ndarray] * 4, DEFAULT_TILE_OVERLAP)]++ def test_a_clamped_overlap_shrinks_the_blend_band_with_it(self):+ """The blend band has to come from the overlap the layout was built with.++ On a 128x904 image the clamp drops the latent overlap from 16 to 15, and the tiler then+ lays the two columns out with exactly 15 latents (120px) of overlap. The configured 128px+ would exceed that, and `merge_tiles_with_linear_blending` asserts every non-edge overlap is+ at least the blend amount -- so passing `self.tile_overlap` here is an AssertionError deep+ in the tiling utility, not a seam.+ """+ ae = _build_autoencoder()+ seen: list[int] = []++ import invokeai.backend.flux.modules.autoencoder as autoencoder_module++ real_merge = autoencoder_module.merge_tiles_with_linear_blending++ def spy(dst_image, tiles, tile_images, blend_amount):+ seen.append(blend_amount)+ return real_merge(dst_image, tiles, tile_images, blend_amount)++ autoencoder_module.merge_tiles_with_linear_blending = spy+ try:+ ae.enable_tiling()+ with torch.no_grad():+ decoded = ae.decode(torch.randn(1, 16, 16, 113))+ finally:+ autoencoder_module.merge_tiles_with_linear_blending = real_merge++ assert seen == [120]+ assert decoded.shape == (1, 3, 128, 904)diff --git a/tests/backend/krea2/test_attention.py b/tests/backend/krea2/test_attention.pyindex d68302e508..e6305febb1 100644--- a/tests/backend/krea2/test_attention.py+++ b/tests/backend/krea2/test_attention.py@@ -145,3 +145,45 @@ def test_cuda_fused_sdpa_accepts_dense_regional_mask(monkeypatch: pytest.MonkeyPassert output.is_cudaassert torch.isfinite(output).all()++[email protected](not torch.cuda.is_available(), reason="the fused kernels are the thing under test")+def test_the_ranked_backends_agree_numerically() -> None:+ """Every backend in the ranked list must produce the same image.++ Ranking cuDNN above the memory-efficient kernel changed which kernel serves a Krea-2 block on+ builds without flash -- i.e. every Windows CUDA build. Nothing pinned that the kernels agree, so+ a kernel that is merely *fast* could have been ranked in. The comparison is against MATH, the+ unfused reference, because that is the one implementation whose result is not in question.+ """+ attn = _build_gqa_attention().to(device="cuda", dtype=torch.bfloat16)+ hidden_states = torch.randn(1, 64, attn.hidden_size, device="cuda", dtype=torch.bfloat16)++ def run(backend: SDPBackend) -> torch.Tensor:+ processor = Krea2MemoryEfficientAttnProcessor(+ sdpa_backends=krea2_attention.Krea2SdpaBackends(backends=(backend,), set_priority=False)+ )+ attn.set_processor(processor)+ with torch.no_grad():+ return attn(hidden_states, attention_mask=None, image_rotary_emb=None)++ reference = run(SDPBackend.MATH)+ head_dim = attn.hidden_size // attn.num_heads+ probe = torch.empty(1, attn.num_heads, 64, head_dim, device="cuda", dtype=torch.bfloat16)+ params = torch.backends.cuda.SDPAParams(probe, probe, probe, None, 0.0, False, False)+ can_use = {+ SDPBackend.CUDNN_ATTENTION: torch.backends.cuda.can_use_cudnn_attention,+ SDPBackend.FLASH_ATTENTION: torch.backends.cuda.can_use_flash_attention,+ SDPBackend.EFFICIENT_ATTENTION: torch.backends.cuda.can_use_efficient_attention,+ }++ compared = []+ for backend, probe_fn in can_use.items():+ if not probe_fn(params):+ continue+ compared.append(backend.name)+ # bf16 accumulates in fp32 inside every one of these kernels, so the spread between them is+ # the output dtype's own resolution, not the kernels'.+ torch.testing.assert_close(run(backend), reference, rtol=1.6e-2, atol=1e-2)++ assert compared, "no fused backend could serve the probe shape, so nothing was compared"diff --git a/tests/backend/krea2/test_grouped_query_attention.py b/tests/backend/krea2/test_grouped_query_attention.pyindex 28491d879b..8975f53919 100644--- a/tests/backend/krea2/test_grouped_query_attention.py+++ b/tests/backend/krea2/test_grouped_query_attention.py@@ -7,6 +7,7 @@ dispatcher. Getting that answer wrong in the optimistic direction is not a slowthe math backend materialises the full [heads, seq, seq] score matrix."""+import contextlibfrom unittest.mock import MagicMockimport pytest@@ -72,32 +73,86 @@ class TestTheDecisionIsConservative:assert proc._serves_grouped_query_attention(q, k, v, mask) is False-class TestTheAnswerIsCached:- def test_the_dispatcher_is_asked_once_per_call_shape(self, monkeypatch):- """Dozens of attention calls per step share one shape; querying every time would be waste."""+class TestTheHeadsAreOnlyPassedThroughWhenTheyDiffer:+ def test_a_block_with_equal_head_counts_never_asks_and_never_sets_the_flag(self, monkeypatch):+ """Krea-2's text-fusion blocks have num_heads == num_kv_heads, so there is nothing to expand+ and nothing to ask. Asking anyway would pay the probe per call for a `False` the shapes+ already settle -- and setting `enable_gqa` on equal head counts is a claim about the tensors+ that is not this processor's to make."""+ asked = MagicMock(return_value=True)+ monkeypatch.setattr(torch.backends.cuda, "SDPAParams", MagicMock(return_value=MagicMock()))+ monkeypatch.setattr(torch.backends.cuda, "can_use_cudnn_attention", asked)+ monkeypatch.setattr(torch.backends.cuda, "can_use_flash_attention", asked)++ seen: dict[str, object] = {}+ real_sdpa = attention_module.F.scaled_dot_product_attention++ def spy(query, key, value, attn_mask=None, enable_gqa=False, **kwargs):+ seen["enable_gqa"] = enable_gqa+ seen["kv_heads"] = key.shape[1]+ return real_sdpa(query, key, value, attn_mask=attn_mask, enable_gqa=enable_gqa, **kwargs)++ monkeypatch.setattr(attention_module.F, "scaled_dot_product_attention", spy)++ attn = Krea2Attention(hidden_size=HQ * 16, num_heads=HQ, num_kv_heads=HQ, eps=1e-5).eval()+ attn.set_processor(Krea2MemoryEfficientAttnProcessor())+ with torch.no_grad():+ attn(torch.randn(1, 24, attn.hidden_size), attention_mask=None, image_rotary_emb=None)++ assert seen["enable_gqa"] is False+ assert seen["kv_heads"] == HQ+ assert asked.call_count == 0+++class TestTheAnswerIsNotCached:+ """The answer turns on process-global state a cache key cannot enumerate.++ `can_use_*` gates on the per-backend enable flags, which any `sdpa_policy` window in the process+ can move. A cached "no" costs the expansion this function exists to skip for the rest of the+ generation, with nothing logged -- the same reasoning `backend.util.attention` records for its+ own dispatcher probe.+ """++ def test_a_changed_answer_is_seen_rather_than_remembered(self, monkeypatch):proc = Krea2MemoryEfficientAttnProcessor()q, k, v, mask = _tensors("cpu")monkeypatch.setattr(type(q), "is_cuda", property(lambda self: True), raising=False)monkeypatch.setattr(torch.backends.cuda, "SDPAParams", MagicMock(return_value=object()))- can_use = MagicMock(return_value=True)- monkeypatch.setattr(torch.backends.cuda, "can_use_cudnn_attention", can_use)+ monkeypatch.setattr(torch.backends.cuda, "can_use_flash_attention", MagicMock(return_value=False))- for _ in range(5):- assert proc._serves_grouped_query_attention(q, k, v, mask) is True- assert can_use.call_count == 1+ answers = iter([False, True])+ monkeypatch.setattr(torch.backends.cuda, "can_use_cudnn_attention", lambda params: next(answers))- def test_a_different_mask_state_is_a_different_question(self, monkeypatch):- """Flash takes the unmasked call and refuses the masked one, so the two cannot share an- answer."""- proc = Krea2MemoryEfficientAttnProcessor()+ assert proc._serves_grouped_query_attention(q, k, v, mask) is False+ assert proc._serves_grouped_query_attention(q, k, v, mask) is True++ def test_the_probe_is_asked_under_the_policy_the_call_will_run_with(self, monkeypatch):+ """Asked outside the window, `can_use_*` answers for whatever policy is installed at that+ moment -- which on a busy multi-GPU box is another session's, not this call's."""+ from torch.nn.attention import _cur_sdpa_kernel_backends++ exclusive = Krea2SdpaBackends(backends=(SDPBackend.CUDNN_ATTENTION,), set_priority=False)+ proc = Krea2MemoryEfficientAttnProcessor(sdpa_backends=exclusive)+ enabled_when_asked: list[set[SDPBackend]] = []++ monkeypatch.setattr(torch.backends.cuda, "SDPAParams", MagicMock(return_value=MagicMock()))+ monkeypatch.setattr(+ torch.backends.cuda,+ "can_use_cudnn_attention",+ lambda params: enabled_when_asked.append(set(_cur_sdpa_kernel_backends())) or False,+ )monkeypatch.setattr(torch.Tensor, "is_cuda", property(lambda self: True), raising=False)- monkeypatch.setattr(torch.backends.cuda, "SDPAParams", MagicMock(return_value=object()))- can_use = MagicMock(return_value=True)- monkeypatch.setattr(torch.backends.cuda, "can_use_cudnn_attention", can_use)- proc._serves_grouped_query_attention(*_tensors("cpu", masked=False))- proc._serves_grouped_query_attention(*_tensors("cpu", masked=True))- assert can_use.call_count == 2+ attn = Krea2Attention(hidden_size=HQ * 16, num_heads=HQ, num_kv_heads=HKV, eps=1e-5).eval()+ attn.set_processor(proc)+ # The call itself cannot complete: an exclusive cuDNN policy leaves a CPU tensor with no+ # viable kernel. That is downstream of what is being asserted -- the probe has already run by+ # then, and moving it back outside the window makes the assertion below fail either way.+ with torch.no_grad(), contextlib.suppress(RuntimeError):+ attn(torch.randn(1, 24, attn.hidden_size), attention_mask=None, image_rotary_emb=None)++ # Outside the window every backend is enabled, so this set is only reachable from inside it.+ assert enabled_when_asked == [{SDPBackend.CUDNN_ATTENTION}]class TestTheExpansionStillHappensWhenItMust:diff --git a/tests/backend/krea2/test_sdpa_backend_selection.py b/tests/backend/krea2/test_sdpa_backend_selection.pyindex 811be497fe..cb71eab09f 100644--- a/tests/backend/krea2/test_sdpa_backend_selection.py+++ b/tests/backend/krea2/test_sdpa_backend_selection.py@@ -112,15 +112,19 @@ class TestTheOverride:assert choice.set_priority is Falseassert choice.override == value- def test_priority_cudnn_reproduces_the_default_list(self):- # This is the value the sm_86 pre-merge check runs with, so it must be the shipped list.- explicit = resolve_krea2_sdpa_backends(raw_override="priority-cudnn")+ def test_default_names_the_shipped_list_without_changing_it(self):+ """The value a benchmarking run exports to say "no override"; it must be the shipped list.++ It used to be spelled `priority-cudnn`, which asserted an ordering it did not produce -- the+ list is flash-first, because flash wins wherever a build has it."""+ explicit = resolve_krea2_sdpa_backends(raw_override="default")default = resolve_krea2_sdpa_backends(raw_override=None)assert explicit.backends == default.backendsassert explicit.set_priority == default.set_priority- assert explicit.override == "priority-cudnn"+ assert explicit.override == "default"+ assert explicit.backends[0] is SDPBackend.FLASH_ATTENTION- @pytest.mark.parametrize("value", [" CUDNN ", "Priority-CuDNN", "EFFICIENT"])+ @pytest.mark.parametrize("value", [" CUDNN ", "Default", "EFFICIENT"])def test_values_are_stripped_and_lowercased(self, value):assert resolve_krea2_sdpa_backends(raw_override=value).override == value.strip().lower()@@ -129,7 +133,7 @@ class TestTheOverride:resolve_krea2_sdpa_backends(raw_override="cudnn-attention")message = str(excinfo.value)assert KREA2_SDPA_BACKEND_ENV_VAR in message- for valid in ("cudnn", "efficient", "flash", "math", "priority-cudnn"):+ for valid in ("cudnn", "efficient", "flash", "math", "default"):assert valid in messagedef test_the_environment_is_read_when_no_value_is_passed(self, monkeypatch):@@ -200,7 +204,7 @@ class TestTheFallbackIsReal:class TestTheDispatchSite:- """That the resolved choice actually reaches `sdpa_kernel`.+ """That the resolved choice actually reaches the SDPA window.Everything above asserts what `resolve_krea2_sdpa_backends` *returns*. None of it survives theprocessor ignoring that value: drop `set_priority=` from the call, or read the module constant@@ -208,7 +212,7 @@ class TestTheDispatchSite:the entire measured win -- with all 31 tests still green.Spying on the context manager is the only place the effect is observable: torch exposes no way- to read back the priority order a `sdpa_kernel` window installed.+ to read back the priority order a window installed."""def _run_with_spy(self, monkeypatch, processor):@@ -219,7 +223,7 @@ class TestTheDispatchSite:seen["set_priority"] = set_priorityreturn contextlib.nullcontext()- monkeypatch.setattr(krea2_attention, "sdpa_kernel", spy)+ monkeypatch.setattr(krea2_attention, "sdpa_policy", spy)attn = Krea2Attention(hidden_size=256, num_heads=8, num_kv_heads=2, eps=1e-5).eval()attn.set_processor(processor)diff --git a/tests/backend/minimax_h3/test_text_encoder_checkpoint.py b/tests/backend/minimax_h3/test_text_encoder_checkpoint.pyindex dc4de8de88..e3b0dcf059 100644--- a/tests/backend/minimax_h3/test_text_encoder_checkpoint.py+++ b/tests/backend/minimax_h3/test_text_encoder_checkpoint.py@@ -203,7 +203,7 @@ def test_te_converted_keys_match_real_model_exactly() -> None:from transformers.models.qwen3_vl.configuration_qwen3_vl import Qwen3VLConfigfrom invokeai.backend.model_manager.util.qwen3_vl import normalize_qwen3vl_rope_config- from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear+ from invokeai.backend.quantization.int8_convrot import swap_in_int8_linearsfrom tests.model_identification.stripped_model_on_disk import StrippedModelOnDiskfixture_dir = (@@ -235,20 +235,11 @@ def test_te_converted_keys_match_real_model_exactly() -> None:with torch.device("meta"):model = Qwen3VLForConditionalGeneration._from_config(te_config)model.model.language_model.norm = torch.nn.Identity()- for module_name in markers:- parent = model.get_submodule(module_name.rsplit(".", 1)[0])- weight = converted[module_name + ".weight"]- setattr(- parent,- module_name.rsplit(".", 1)[1],- Int8ConvrotLinear(- # Meta tensors: only keys and shapes are compared below, and real int8 zeros at the- # 32B model's shapes allocate ~24 GB - enough to get a CI runner OOM-killed.- weight=torch.zeros(weight.shape, dtype=torch.int8, device="meta"),- weight_scale=torch.zeros(weight.shape[0], 1, device="meta"),- convrot=True,- ),- )+ # Through the loader's own swap, not a copy of it: the keys this test pins are the ones+ # `Int8ConvrotLinear` registers, so a change to which buffers it carries has to reach here.+ # The fixture's tensors are meta, which is also what keeps this affordable -- real int8 zeros at+ # the 32B model's shapes allocate ~24 GB, enough to get a CI runner OOM-killed.+ swap_in_int8_linears(model, converted, markers)expected = set(model.state_dict().keys()) - {"lm_head.weight"}got = set(converted.keys())diff --git a/tests/backend/model_manager/load/test_krea2_loader_boundaries.py b/tests/backend/model_manager/load/test_krea2_loader_boundaries.pyindex 87326010ae..c247cf6402 100644--- a/tests/backend/model_manager/load/test_krea2_loader_boundaries.py+++ b/tests/backend/model_manager/load/test_krea2_loader_boundaries.py@@ -21,7 +21,6 @@ from invokeai.backend.model_manager.load.model_loaders.krea2 import (Qwen3VLEncoderLoader,)from invokeai.backend.model_manager.taxonomy import Krea2VariantType, SubModelType-from invokeai.backend.quantization.fp8_scaled import predict_cast_state_dict_sizefrom invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear@@ -99,6 +98,11 @@ def test_single_file_loader_decodes_an_int8_convrot_checkpoint(monkeypatch, tmp_def __init__(self, **_kwargs) -> None:super().__init__()self.proj = torch.nn.Linear(CONVROT_GROUP_SIZE, 4, bias=False)+ self.dense = torch.nn.Linear(8, 4, bias=False)++ # An unquantized neighbour, stored narrower than the compute dtype, so the reservation below+ # has to get three widths right rather than one.+ state_dict["dense.weight"] = torch.ones(4, 8, dtype=torch.float16)checkpoint_path = tmp_path / "krea2_int8_convrot.safetensors"checkpoint_path.touch()@@ -123,11 +127,14 @@ def test_single_file_loader_decodes_an_int8_convrot_checkpoint(monkeypatch, tmp_model = loader._load_from_singlefile(config)- # The reservation must be what the load actually occupies. `max(element_size, itemsize)` charged- # the compute dtype's width for the int8 payloads -- `max(1, 2)` is 2 -- so every int8 load asked- # the cache to free twice what it needed, evicting other models for room nobody used.+ # The reservation must be what the load actually occupies, counted by hand rather than by the+ # function under test: the int8 weight at one byte (charging it the compute dtype's width asked+ # the cache to free twice what this load needs, evicting other models for room nobody used),+ # its scale at the fp32 it is pinned at, and the dense fp16 neighbour at the compute width it+ # is cast to. Summing `state_dict` instead would be summing the wrong object -- the loader+ # rebinds `sd` at `drop_unconsumed_quantization_sidecars` and mutates the copy.(reserved,), _ = loader._ram_cache.make_room.call_args- assert reserved == predict_cast_state_dict_size(state_dict, torch.float32, keep_fp8=False)+ assert reserved == 4 * CONVROT_GROUP_SIZE * 1 + 4 * 1 * 4 + 4 * 8 * torch.float32.itemsize# This is also what pins the one-or-the-other split in the loader: the fixture's int8 weight# carries a `.weight_scale`, which is exactly what an fp8 scaled layer looks like from outside.@@ -379,3 +386,235 @@ def test_an_int8_weight_without_a_marker_is_refused(monkeypatch, tmp_path) -> Noloader._load_from_singlefile(config)assert "unmarked.weight" in str(excinfo.value)+++def _int8_convrot_pair(weight: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:+ """Mirror of comfy-quants: rotate along the input dim, then per-output-channel int8."""+ from invokeai.backend.quantization.int8_convrot import CONVROT_GROUP_SIZE, build_regular_hadamard++ out_features, in_features = weight.shape+ hadamard = build_regular_hadamard(CONVROT_GROUP_SIZE, dtype=weight.dtype)+ rotated = (weight.view(out_features, in_features // CONVROT_GROUP_SIZE, CONVROT_GROUP_SIZE) @ hadamard.T).view(+ out_features, in_features+ )+ scale = rotated.abs().amax(dim=1, keepdim=True) / 127.0+ return torch.clamp(torch.round(rotated / scale), -128, 127).to(torch.int8), scale.to(torch.float32)+++def _int8_marker_blob(**overrides) -> torch.Tensor:+ import json++ from invokeai.backend.quantization.int8_convrot import CONVROT_GROUP_SIZE++ marker = {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": CONVROT_GROUP_SIZE, **overrides}+ return torch.frombuffer(bytearray(json.dumps(marker).encode("utf-8")), dtype=torch.uint8).clone()+++def _int8_transformer_driver(monkeypatch, tmp_path, model_class, state_dict):+ import diffusers+ import safetensors.torch++ checkpoint_path = tmp_path / "krea2_int8_convrot.safetensors"+ checkpoint_path.touch()+ config = Main_Checkpoint_Krea2_Config.model_construct(+ path=str(checkpoint_path), variant=Krea2VariantType.Turbo, fp8_storage=None+ )+ loader = object.__new__(Krea2CheckpointModel)+ loader._ram_cache = SimpleNamespace(make_room=MagicMock())+ loader._logger = MagicMock()+ loader._apply_fp8_layerwise_casting = lambda model, _config, _submodel: model++ monkeypatch.setattr(diffusers, "Krea2Transformer2DModel", model_class, raising=False)+ monkeypatch.setattr(safetensors.torch, "load_file", lambda _path: state_dict)+ monkeypatch.setattr(+ "invokeai.backend.model_manager.load.model_loaders.krea2.TorchDevice.choose_torch_device",+ lambda: torch.device("cpu"),+ )+ monkeypatch.setattr(+ "invokeai.backend.model_manager.load.model_loaders.krea2.TorchDevice.choose_bfloat16_safe_dtype",+ lambda _device: torch.float32,+ )+ return loader, config+++def test_a_precision_sensitive_layer_is_not_left_int8(monkeypatch, tmp_path) -> None:+ """Krea-2 declares `time_embed` (and the norms), and `time_embed.linear_1/linear_2` are+ ordinary quantized Linears in a ComfyUI export. The fp8 branch has always dequantized those;+ the int8 branch never consulted the list, so they stayed int8 and reported `torch.int8` as+ their weight dtype to anything that reads it."""+ from invokeai.backend.quantization.int8_convrot import CONVROT_GROUP_SIZE++ class _TinyKrea2WithTimeEmbed(torch.nn.Module):+ _skip_layerwise_casting_patterns = ["time_embed", "norm"]++ def __init__(self, **_kwargs) -> None:+ super().__init__()+ self.time_embed = torch.nn.Module()+ self.time_embed.linear_1 = torch.nn.Linear(CONVROT_GROUP_SIZE, 4, bias=False)+ self.proj = torch.nn.Linear(CONVROT_GROUP_SIZE, 4, bias=False)++ torch.manual_seed(5)+ sensitive = torch.randn(4, CONVROT_GROUP_SIZE)+ sensitive_q, sensitive_scale = _int8_convrot_pair(sensitive)+ ordinary_q, ordinary_scale = _int8_convrot_pair(torch.randn(4, CONVROT_GROUP_SIZE))+ state_dict = {+ "time_embed.linear_1.weight": sensitive_q,+ "time_embed.linear_1.weight_scale": sensitive_scale,+ "time_embed.linear_1.comfy_quant": _int8_marker_blob(),+ "proj.weight": ordinary_q,+ "proj.weight_scale": ordinary_scale,+ "proj.comfy_quant": _int8_marker_blob(),+ }+ loader, config = _int8_transformer_driver(monkeypatch, tmp_path, _TinyKrea2WithTimeEmbed, state_dict)++ model = loader._load_from_singlefile(config)++ assert not isinstance(model.time_embed.linear_1, Int8ConvrotLinear)+ assert model.time_embed.linear_1.weight.dtype is torch.float32+ assert torch.corrcoef(torch.stack([model.time_embed.linear_1.weight.flatten(), sensitive.flatten()]))[0, 1] > 0.999+ assert isinstance(model.proj, Int8ConvrotLinear)+ assert model.proj.weight.dtype is torch.int8+++def test_a_checkpoint_mixing_int8_and_fp8_is_refused(monkeypatch, tmp_path) -> None:+ """The int8 branch skips the whole fp8 pipeline, so a layer belonging to the other scheme is+ cast to the compute dtype without its scale while its orphaned `weight_scale` is swallowed by+ `strict=False`. With a scale of 4.0 that weight loads a factor 4 low, in silence. The+ "a checkpoint carries one format or the other" premise was documented and never enforced."""+ from invokeai.backend.quantization.int8_convrot import CONVROT_GROUP_SIZE++ class _TinyMixedKrea2(torch.nn.Module):+ def __init__(self, **_kwargs) -> None:+ super().__init__()+ self.proj = torch.nn.Linear(CONVROT_GROUP_SIZE, 4, bias=False)+ self.fp8_proj = torch.nn.Linear(CONVROT_GROUP_SIZE, 4, bias=False)++ torch.manual_seed(6)+ quantized, scale = _int8_convrot_pair(torch.randn(4, CONVROT_GROUP_SIZE))+ state_dict = {+ "proj.weight": quantized,+ "proj.weight_scale": scale,+ "proj.comfy_quant": _int8_marker_blob(),+ "fp8_proj.weight": torch.ones(4, CONVROT_GROUP_SIZE).to(torch.float8_e4m3fn),+ "fp8_proj.weight_scale": torch.tensor(4.0),+ "fp8_proj.comfy_quant": torch.frombuffer(bytearray(b'{"format": "float8_e4m3fn"}'), dtype=torch.uint8).clone(),+ }+ loader, config = _int8_transformer_driver(monkeypatch, tmp_path, _TinyMixedKrea2, state_dict)++ with pytest.raises(ValueError, match=r"weight scale\(s\) that no `int8_tensorwise` marker claims"):+ loader._load_from_singlefile(config)+++def test_the_encoder_names_itself_when_refusing_an_unmarked_int8_weight(monkeypatch, tmp_path) -> None:+ """The refusal quoted "Krea-2" and `model.layers.*` keys for an encoder file -- an architecture+ the message names and keys that do not exist in a transformer, pointing at the wrong file."""+ import transformers+ from safetensors import torch as safetensors_torch++ from invokeai.backend.quantization.int8_convrot import CONVROT_GROUP_SIZE++ state_dict = {"model.layers.0.self_attn.q_proj.weight": torch.zeros(4, CONVROT_GROUP_SIZE, dtype=torch.int8)}++ class _TinyEncoder(torch.nn.Module):+ @classmethod+ def _from_config(cls, _config):+ return cls()++ checkpoint_path = tmp_path / "qwen3vl_int8_convrot.safetensors"+ checkpoint_path.touch()+ config = Qwen3VLEncoder_Checkpoint_Config.model_construct(path=str(checkpoint_path), name="encoder")++ loader = object.__new__(Qwen3VLEncoderCheckpointLoader)+ loader._ram_cache = SimpleNamespace(make_room=MagicMock())+ loader._torch_device = torch.device("cpu")+ loader._logger = MagicMock()+ loader._load_hf_config = lambda: SimpleNamespace()++ monkeypatch.setattr(transformers, "Qwen3VLModel", _TinyEncoder, raising=False)+ monkeypatch.setattr(safetensors_torch, "load_file", lambda _path: state_dict)+ monkeypatch.setattr(+ "invokeai.backend.model_manager.load.model_loaders.krea2.TorchDevice.choose_torch_device",+ lambda: torch.device("cpu"),+ )+ monkeypatch.setattr(+ "invokeai.backend.model_manager.load.model_loaders.krea2.TorchDevice.choose_bfloat16_safe_dtype",+ lambda _device: torch.float32,+ )++ with pytest.raises(ValueError, match=r"Qwen3-VL encoder checkpoint has 1 int8 weight\(s\)"):+ loader._load_text_encoder(config)++[email protected]("bundled_dtype", [torch.bfloat16, torch.float8_e4m3fn], ids=["dense", "scaled-fp8"])+def test_a_merged_encoder_checkpoint_is_not_mistaken_for_a_mixed_format_one(+ monkeypatch, tmp_path, bundled_dtype+) -> None:+ """These loaders do not prefix-filter the state dict, so a merged single file's bundled+ submodel is in `sd` too and `strict=False` is what discards it. The mixed-format refusal has to+ key on a weight *this model consumes*, not on any stray key that ends in a scale.++ The `scaled-fp8` case is the one an all-in-one ComfyUI export actually produces: an int8+ transformer beside an fp8 text encoder. Those keys are never loaded, so they cannot load+ unscaled -- refusing them would fail a checkpoint that works."""+ import json++ import transformers+ from safetensors import torch as safetensors_torch++ from invokeai.backend.quantization.int8_convrot import CONVROT_GROUP_SIZE, build_regular_hadamard++ torch.manual_seed(7)+ original = torch.randn(4, CONVROT_GROUP_SIZE)+ hadamard = build_regular_hadamard(CONVROT_GROUP_SIZE)+ rotated = (original.view(4, 1, CONVROT_GROUP_SIZE) @ hadamard.T).view(4, CONVROT_GROUP_SIZE)+ scale = rotated.abs().amax(dim=1, keepdim=True) / 127.0+ marker = json.dumps({"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": CONVROT_GROUP_SIZE})+ state_dict = {+ "proj.weight": torch.clamp(torch.round(rotated / scale), -128, 127).to(torch.int8),+ "proj.weight_scale": scale.to(torch.float32),+ "proj.comfy_quant": torch.frombuffer(bytearray(marker.encode("utf-8")), dtype=torch.uint8).clone(),+ # A bundled submodel: not this model's, discarded by `strict=False`, and not a reason to+ # refuse -- whether it is dense or carries a quantization scheme of its own.+ "bundled.block.weight": torch.ones(4, 4).to(bundled_dtype),+ "bundled.block.weight_scale": torch.ones(4, 1),+ }++ class _TinyLanguageModel(torch.nn.Module):+ def __init__(self) -> None:+ super().__init__()+ self.proj = torch.nn.Linear(CONVROT_GROUP_SIZE, 4, bias=False)++ class _TinyEncoder(torch.nn.Module):+ def __init__(self) -> None:+ super().__init__()+ self.language_model = _TinyLanguageModel()++ @classmethod+ def _from_config(cls, _config):+ return cls()++ checkpoint_path = tmp_path / "qwen3vl_int8_convrot.safetensors"+ checkpoint_path.touch()+ config = Qwen3VLEncoder_Checkpoint_Config.model_construct(path=str(checkpoint_path), name="encoder")++ loader = object.__new__(Qwen3VLEncoderCheckpointLoader)+ loader._ram_cache = SimpleNamespace(make_room=MagicMock())+ loader._torch_device = torch.device("cpu")+ loader._logger = MagicMock()+ loader._load_hf_config = lambda: SimpleNamespace()+ loader._apply_fp8_to_nn_module = lambda *a, **k: None++ monkeypatch.setattr(transformers, "Qwen3VLModel", _TinyEncoder, raising=False)+ monkeypatch.setattr(safetensors_torch, "load_file", lambda _path: state_dict)+ monkeypatch.setattr(+ "invokeai.backend.model_manager.load.model_loaders.krea2.TorchDevice.choose_torch_device",+ lambda: torch.device("cpu"),+ )+ monkeypatch.setattr(+ "invokeai.backend.model_manager.load.model_loaders.krea2.TorchDevice.choose_bfloat16_safe_dtype",+ lambda _device: torch.float32,+ )++ model = loader._load_text_encoder(config)++ assert isinstance(model.language_model.proj, Int8ConvrotLinear)diff --git a/tests/backend/model_manager/load/test_minimax_h3_int8_loading.py b/tests/backend/model_manager/load/test_minimax_h3_int8_loading.pynew file mode 100644index 0000000000..05536e605c--- /dev/null+++ b/tests/backend/model_manager/load/test_minimax_h3_int8_loading.py@@ -0,0 +1,180 @@+"""MiniMax H3's int8_tensorwise single-file path, driven through the loader over a real file.++H3 is where this scheme entered the codebase, and it kept its own copy of the call site: the+marker's ``convrot_groupsize`` was never read and the scale layout was never checked. Both are+things a checkpoint can vary and neither fails loudly, so they are pinned here against the loader+rather than against the shared helper they now go through.++The fixture is a real safetensors file because the loader reads the markers twice by two different+routes -- once from the header before committing to the tensor read, once from the tensors -- and+the header route is only exercised by an actual file.+"""++import json+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import MagicMock++import pytest+import torch+from safetensors.torch import save_file++from invokeai.backend.minimax_h3.transformer_minimax_h3 import MiniMaxH3AttnProcessor+from invokeai.backend.model_manager.configs.main import Main_Checkpoint_MiniMaxH3_Config+from invokeai.backend.model_manager.load.model_loaders.minimax_h3 import MiniMaxH3CheckpointModel+from invokeai.backend.model_manager.load.model_loaders.minimax_h3_state_dict_utils import read_comfy_quant_markers+from invokeai.backend.model_manager.taxonomy import MiniMaxH3VariantType+from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear, build_regular_hadamard++[email protected](autouse=True)+def _restore_attention_processor():+ """The loader installs H3's contiguous-QKV attention patch, which rebinds+ `MiniMaxH3AttnProcessor.__call__` for the whole process.++ `test_contiguous_attention.py` compares the patched call against the *unpatched* one, so a+ worker that ran this file first would have it comparing the patch to itself -- passing, and+ checking nothing. Under `--dist loadfile` which file a worker gets is arbitrary, so restore.+ """+ original = MiniMaxH3AttnProcessor.__call__+ was_marked = "_invokeai_contiguous_qkv" in vars(MiniMaxH3AttnProcessor)+ yield+ MiniMaxH3AttnProcessor.__call__ = original+ if not was_marked and "_invokeai_contiguous_qkv" in vars(MiniMaxH3AttnProcessor):+ delattr(MiniMaxH3AttnProcessor, "_invokeai_contiguous_qkv")+++# Hidden/inner/ffn all 64 so every quantized in_features is divisible by the 64-wide group the+# marker below declares. Curve grid 5 x 3, one block and one refiner block: the AdaLN-pruned+# layout, whose converted keys are known to match the model exactly.+HIDDEN = INNER = FFN = 64+HEAD_DIM = 32+CURVE_DIM = 3+GROUP_SIZE = 64++QUANTIZED_SOURCE_KEY = "blocks.0.attn.out_proj.weight"+QUANTIZED_MODULE_PATH = ("transformer_blocks", 0, "attn", "to_out", 0)+++def _tiny_remote_code_state_dict() -> dict[str, torch.Tensor]:+ """A minimal AdaLN-pruned H3 checkpoint in MiniMax's remote-code key layout."""+ sd: dict[str, torch.Tensor] = {+ "video_patch_proj.weight": torch.randn(HIDDEN, 4),+ "video_patch_proj.bias": torch.randn(HIDDEN),+ "audio_patch_proj.weight": torch.randn(HIDDEN, 4),+ "audio_patch_proj.bias": torch.randn(HIDDEN),+ "condition_proj.weight": torch.randn(HIDDEN, 6),+ "condition_proj.bias": torch.randn(HIDDEN),+ "adaln_t_table": torch.randn(5, CURVE_DIM),+ "rope.inv_freq": torch.randn(2),+ "token_refiner.final_norm.weight": torch.randn(HIDDEN),+ "final_layer.norm.weight": torch.randn(HIDDEN),+ "final_layer.adaln_proj.linear.weight": torch.randn(2 * HIDDEN, CURVE_DIM),+ "final_layer.adaln_proj.linear.bias": torch.randn(2 * HIDDEN),+ "final_layer.video_out.weight": torch.randn(4, HIDDEN),+ "final_layer.video_out.bias": torch.randn(4),+ "final_layer.audio_out.weight": torch.randn(4, HIDDEN),+ "final_layer.audio_out.bias": torch.randn(4),+ }+ for prefix in ("token_refiner.blocks.0.", "blocks.0."):+ sd[prefix + "norm1.weight"] = torch.randn(HIDDEN)+ sd[prefix + "norm2.weight"] = torch.randn(HIDDEN)+ sd[prefix + "attn.qkv_proj.weight"] = torch.randn(3 * INNER, HIDDEN)+ sd[prefix + "attn.q_norm.weight"] = torch.randn(HEAD_DIM)+ sd[prefix + "attn.k_norm.weight"] = torch.randn(HEAD_DIM)+ sd[prefix + "attn.out_proj.weight"] = torch.randn(HIDDEN, INNER)+ sd[prefix + "mlp.fc1.weight"] = torch.randn(2 * FFN, HIDDEN)+ sd[prefix + "mlp.fc2.weight"] = torch.randn(HIDDEN, FFN)+ sd["blocks.0.adaln_proj.linear.weight"] = torch.randn(6 * HIDDEN * 3, CURVE_DIM)+ sd["blocks.0.adaln_proj.linear.bias"] = torch.randn(6 * HIDDEN * 3)+ return sd+++def _quantize_convrot(weight: torch.Tensor, group_size: int) -> tuple[torch.Tensor, torch.Tensor]:+ """Mirror of comfy-quants: rotate along the input dim in groups, then per-output-channel int8."""+ out_features, in_features = weight.shape+ hadamard = build_regular_hadamard(group_size, dtype=weight.dtype)+ rotated = (weight.view(out_features, in_features // group_size, group_size) @ hadamard.T).view(+ out_features, in_features+ )+ scale = rotated.abs().amax(dim=1, keepdim=True) / 127.0+ return torch.clamp(torch.round(rotated / scale), -128, 127).to(torch.int8), scale.to(torch.float32)+++def _marker_blob(marker: dict, *, pad: int = 0) -> torch.Tensor:+ """Comfy pads these to a fixed width with NUL bytes; `pad` reproduces that."""+ raw = json.dumps(marker).encode("utf-8") + b"\x00" * pad+ return torch.frombuffer(bytearray(raw), dtype=torch.uint8).clone()+++def _write_checkpoint(+ tmp_path: Path, *, scale: torch.Tensor | None = None, marker: dict | None = None, pad: int = 16+) -> tuple[Path, torch.Tensor]:+ """A tiny pruned H3 checkpoint with `blocks.0.attn.out_proj` quantized; returns its true weight."""+ torch.manual_seed(0)+ sd = _tiny_remote_code_state_dict()+ original = sd[QUANTIZED_SOURCE_KEY]+ quantized, derived_scale = _quantize_convrot(original, GROUP_SIZE)+ sd[QUANTIZED_SOURCE_KEY] = quantized+ sd["blocks.0.attn.out_proj.weight_scale"] = derived_scale if scale is None else scale+ sd["blocks.0.attn.out_proj.comfy_quant"] = _marker_blob(+ marker or {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": GROUP_SIZE}, pad=pad+ )+ path = tmp_path / "minimax_h3_int8_convrot.safetensors"+ save_file(sd, str(path))+ return path, original+++def _load(path: Path) -> torch.nn.Module:+ config = Main_Checkpoint_MiniMaxH3_Config.model_construct(+ path=str(path), variant=MiniMaxH3VariantType.FL2VA, pruned=True, name="h3"+ )+ loader = object.__new__(MiniMaxH3CheckpointModel)+ loader._ram_cache = SimpleNamespace(make_room=MagicMock())+ loader._logger = MagicMock()+ return loader._load_transformer_from_singlefile(config)+++def _quantized_module(model: torch.nn.Module) -> torch.nn.Module:+ module: torch.nn.Module = model+ for step in QUANTIZED_MODULE_PATH:+ module = module[step] if isinstance(step, int) else getattr(module, step)+ return module+++def test_the_marker_group_size_reaches_the_module(tmp_path) -> None:+ """The rotation width is per tensor, and H3 assumed it. A 64-wide repack derotated with a+ 256-wide Hadamard is not a subtle error -- the shapes do not even divide -- but a producer+ varying it the other way (a wider group on a wide layer) would run and generate noise."""+ path, original = _write_checkpoint(tmp_path)++ model = _load(path)++ module = _quantized_module(model)+ assert isinstance(module, Int8ConvrotLinear)+ assert module.group_size == GROUP_SIZE+ # And the weight it computes is the un-rotated original, not the still-rotated one.+ dequantized = module._dequantized_weight(torch.device("cpu"), torch.float32).flatten()+ assert torch.corrcoef(torch.stack([dequantized, original.flatten()]))[0, 1] > 0.999+++def test_a_blockwise_scale_grid_is_refused_by_name(tmp_path) -> None:+ """H3 constructed its modules without the scale-layout check, so a block grid broadcast+ against the weight instead of raising: for a square weight that is silent."""+ path, _ = _write_checkpoint(tmp_path, scale=torch.ones(HIDDEN // 8, INNER // 8))++ with pytest.raises(ValueError, match=r"Blockwise scale grids"):+ _load(path)+++def test_a_nul_padded_header_marker_is_read(tmp_path) -> None:+ """The header reader runs before the tensor read, so its strict parse was what a padded marker+ actually hit -- a JSONDecodeError out of the middle of a load, naming neither file nor key.+ The tolerant parser the state-dict readers use was written for exactly this."""+ path, _ = _write_checkpoint(tmp_path, pad=16)++ markers = read_comfy_quant_markers(path)++ assert markers == {+ "blocks.0.attn.out_proj": {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": GROUP_SIZE}+ }diff --git a/tests/backend/model_manager/load/test_z_image_loader_boundaries.py b/tests/backend/model_manager/load/test_z_image_loader_boundaries.pyindex d111199bd1..4270597076 100644--- a/tests/backend/model_manager/load/test_z_image_loader_boundaries.py+++ b/tests/backend/model_manager/load/test_z_image_loader_boundaries.py@@ -123,3 +123,63 @@ def test_an_unquantized_checkpoint_is_unaffected(monkeypatch, tmp_path) -> None:assert isinstance(model.layers[0].proj, torch.nn.Linear)assert not isinstance(model.layers[0].proj, Int8ConvrotLinear)assert torch.equal(model.layers[0].proj.weight, weight)+++class _TinyTimestepEmbedder(torch.nn.Module):+ """Z-Image's `t_embedder` in miniature. Its real forward reads `self.mlp[0].weight.dtype` to+ pick the dtype it casts its activations to, which is why the model declares it+ precision-sensitive -- and why an `Int8ConvrotLinear` there (weight dtype `torch.int8`,+ `is_floating_point()` False, no `compute_dtype` attribute) sends that branch somewhere the+ model was never meant to run."""++ def __init__(self) -> None:+ super().__init__()+ self.mlp = torch.nn.ModuleList([torch.nn.Linear(CONVROT_GROUP_SIZE, 4, bias=False)])+++class _TinyZImageWithTimestepEmbedder(_TinyZImage):+ _skip_layerwise_casting_patterns = ["t_embedder", "cap_embedder"]++ def __init__(self, **kwargs) -> None:+ super().__init__(**kwargs)+ self.t_embedder = _TinyTimestepEmbedder()+++def test_a_precision_sensitive_layer_is_not_left_int8(monkeypatch, tmp_path) -> None:+ """The model's own `_skip_layerwise_casting_patterns` has to be honored on the int8 branch too.+ The fp8 branch always read it; the int8 branch did not, so Z-Image's timestep embedder stayed+ quantized and its forward picked its activation dtype off a `torch.int8` weight."""+ torch.manual_seed(3)+ sensitive = torch.randn(4, CONVROT_GROUP_SIZE)+ ordinary = torch.randn(4, CONVROT_GROUP_SIZE)+ sensitive_q, sensitive_scale = _quantize_convrot(sensitive)+ ordinary_q, ordinary_scale = _quantize_convrot(ordinary)+ state_dict = {+ "t_embedder.mlp.0.weight": sensitive_q,+ "t_embedder.mlp.0.weight_scale": sensitive_scale,+ "t_embedder.mlp.0.comfy_quant": _marker_blob(MARKER),+ "layers.0.proj.weight": ordinary_q,+ "layers.0.proj.weight_scale": ordinary_scale,+ "layers.0.proj.comfy_quant": _marker_blob(MARKER),+ }+ loader, config = _driver(monkeypatch, tmp_path, state_dict)+ import diffusers++ monkeypatch.setattr(diffusers, "ZImageTransformer2DModel", _TinyZImageWithTimestepEmbedder, raising=False)++ model = loader._load_from_singlefile(config)++ embedder_linear = model.t_embedder.mlp[0]+ assert not isinstance(embedder_linear, Int8ConvrotLinear)+ assert embedder_linear.weight.dtype is torch.float32+ # Dequantized *with* its scale and derotation, not merely cast: the whole point of widening it+ # here rather than dropping the marker.+ assert torch.corrcoef(torch.stack([embedder_linear.weight.flatten(), sensitive.flatten()]))[0, 1] > 0.999++ # Everything else still pays the one byte per weight this scheme exists for.+ assert isinstance(model.layers[0].proj, Int8ConvrotLinear)+ assert model.layers[0].proj.weight.dtype is torch.int8++ # And the reservation covers the widened layer at its post-split width, not at one byte.+ (reserved,), _ = loader._ram_cache.make_room.call_args+ assert reserved >= sensitive.nelement() * 4 + ordinary_q.nelement()diff --git a/tests/backend/quantization/test_int8_convrot.py b/tests/backend/quantization/test_int8_convrot.pyindex 290d7e9c5c..5f74717467 100644--- a/tests/backend/quantization/test_int8_convrot.py+++ b/tests/backend/quantization/test_int8_convrot.py@@ -19,7 +19,9 @@ from invokeai.backend.quantization.int8_convrot import (dequantize_convrot_weight,extract_int8_convrot_markers,parse_comfy_quant_marker,+ peak_int8_dequant_transient_bytes,requires_sidecar_patching,+ shared_regular_hadamard,)@@ -87,18 +89,96 @@ def test_int8_convrot_linear_matches_dequantized_f_linear() -> None:def test_int8_convrot_linear_state_dict_contract() -> None:"""Persistent buffers must be named exactly `weight` / `weight_scale` (+ optional `bias`)- so the converted checkpoint's keys load directly and strict load_state_dict holds; the- Hadamard is computed, never loaded, but must still move with the module."""+ so the converted checkpoint's keys load directly and strict load_state_dict holds. Nothing+ else is registered: the derotation matrix is a constant of the scheme, taken from the shared+ cache per forward rather than held once per layer."""torch.manual_seed(3)w = torch.randn(16, CONVROT_GROUP_SIZE)q, scale = _quantize_reference(w, convrot=True)bias = torch.randn(16)lin = Int8ConvrotLinear(q, scale, convrot=True, bias=bias)assert set(lin.state_dict().keys()) == {"weight", "weight_scale", "bias"}- assert {n for n, _ in lin.named_buffers()} == {"weight", "weight_scale", "hadamard", "bias"}+ assert {n for n, _ in lin.named_buffers()} == {"weight", "weight_scale", "bias"}assert lin.state_dict()["weight"].dtype == torch.int8+class TestTheDerotationMatrixIsSharedNotPerLayer:+ """It is byte-identical across every layer of a given group size, and a model has hundreds of+ them: Krea-2's transformer is 264 Linears, so a per-module 256x256 fp32 buffer is 69 MB of+ duplicate resident weight, summed into the cache entry's size by `calc_module_size`."""++ @staticmethod+ def _layer(out_features: int) -> Int8ConvrotLinear:+ torch.manual_seed(out_features)+ weight, scale = _quantize_reference(torch.randn(out_features, CONVROT_GROUP_SIZE), convrot=True)+ return Int8ConvrotLinear(weight, scale, convrot=True)++ def test_layers_of_the_same_group_size_share_one_hadamard(self) -> None:+ """The regression this guards is resident bytes, so it is measured in resident bytes: a+ per-module buffer is what `calc_module_size` sums out of `model.buffers()`."""+ model = torch.nn.Module()+ model.a, model.b = self._layer(8), self._layer(16)+ probe = torch.randn(2, CONVROT_GROUP_SIZE)+ model.a(probe)+ model.b(probe)++ assert sum(b.nelement() * b.element_size() for b in model.buffers()) == sum(+ t.nelement() * t.element_size() for t in (*model.a.state_dict().values(), *model.b.state_dict().values())+ )++ def test_one_matrix_is_kept_per_size_device_and_dtype(self) -> None:+ """Keyed on all three. A cache keyed on size alone would hand a bf16 forward the fp32+ matrix (or the reverse), and `@` would raise -- or, worse, a layer on another device would+ be handed a matrix that is not there."""+ cpu = torch.device("cpu")++ assert shared_regular_hadamard(CONVROT_GROUP_SIZE, cpu, torch.float32) is shared_regular_hadamard(+ CONVROT_GROUP_SIZE, cpu, torch.float32+ )+ assert shared_regular_hadamard(CONVROT_GROUP_SIZE, cpu, torch.float32) is not shared_regular_hadamard(+ CONVROT_GROUP_SIZE, cpu, torch.float64+ )+ assert shared_regular_hadamard(CONVROT_GROUP_SIZE, cpu, torch.float32) is not shared_regular_hadamard(+ 4, cpu, torch.float32+ )++ def test_a_forward_gets_a_matrix_in_the_inputs_dtype(self) -> None:+ """The matrix is no longer a buffer the module carries in one dtype; it is fetched for the+ dtype the forward is running in, and the result must stay in that dtype."""+ layer = self._layer(8)+ probe = torch.randn(3, CONVROT_GROUP_SIZE, dtype=torch.float64)++ out = layer(probe)++ assert out.dtype is torch.float64+ assert torch.allclose(out, layer(probe.to(torch.float32)).to(torch.float64), atol=1e-5)++ @pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a CUDA device to move between")+ def test_a_device_round_trip_still_produces_the_same_output(self) -> None:+ """The matrix used to move with the module; now it is fetched per forward for the input's+ device, so moving the layer to another device and back must not change what it computes.+ A CPU-only `.to('cpu')` is a no-op and would pass either way, hence the real device."""+ layer = self._layer(8)+ probe = torch.randn(3, CONVROT_GROUP_SIZE)+ before = layer(probe)++ layer.to(torch.device("cuda"))+ on_device = layer(probe.to("cuda")).cpu()+ layer.to(torch.device("cpu"))++ assert torch.allclose(on_device, before, atol=1e-5)+ assert torch.equal(layer(probe), before)++ def test_the_group_size_a_marker_declares_is_validated_at_construction(self) -> None:+ """The matrix is built lazily now, so without a check here a checkpoint declaring a+ power-of-2-but-not-4 width loads, caches, reaches VRAM, and raises mid-generation from a+ forward that names neither the layer nor the file."""+ weight = torch.zeros(8, 512, dtype=torch.int8)++ with pytest.raises(ValueError, match=r"power of 4, got 512"):+ Int8ConvrotLinear(weight, torch.ones(8, 1), convrot=True, group_size=512)++def test_parse_comfy_quant_marker() -> None:blob = torch.frombuffer(b'{"format": "int8_tensorwise", "convrot": true, "convrot_groupsize": 256}', dtype=torch.uint8@@ -232,3 +312,35 @@ class TestWhetherLoraNeedsASidecar:@pytest.mark.parametrize("fmt", [ModelFormat.GGUFQuantized, ModelFormat.SDNQQuantized])def test_a_format_that_is_quantized_by_definition_needs_one(self, fmt):assert requires_sidecar_patching(self._model(int8=False), fmt) is True+++class TestThePerForwardDequantTransient:+ """`Int8ConvrotLinear` materializes its dequantized weight per forward, so that allocation is+ not part of the model's resident size and the calling node has to reserve for it."""++ @staticmethod+ def _model(*shapes: tuple[int, int]) -> torch.nn.Module:+ model = torch.nn.Module()+ for index, (out_features, in_features) in enumerate(shapes):+ model.add_module(+ str(index),+ Int8ConvrotLinear(+ torch.zeros(out_features, in_features, dtype=torch.int8),+ torch.ones(out_features, 1),+ convrot=False,+ ),+ )+ return model++ def test_it_is_two_weights_of_the_largest_layer_in_the_compute_dtype(self) -> None:+ """Two, not one: the dtype cast of the int8 weight is alive alongside the product it is+ multiplied into, and that product is alive alongside the derotation matmul's output."""+ model = self._model((4, CONVROT_GROUP_SIZE), (16, CONVROT_GROUP_SIZE))++ assert peak_int8_dequant_transient_bytes(model, torch.bfloat16) == 2 * 16 * CONVROT_GROUP_SIZE * 2++ def test_a_model_with_no_quantized_layers_needs_nothing(self) -> None:+ model = torch.nn.Module()+ model.dense = torch.nn.Linear(8, 8)++ assert peak_int8_dequant_transient_bytes(model, torch.bfloat16) == 0diff --git a/tests/backend/quantization/test_int8_convrot_state_dict.py b/tests/backend/quantization/test_int8_convrot_state_dict.pyindex fea15c6818..09f0fa8769 100644--- a/tests/backend/quantization/test_int8_convrot_state_dict.py+++ b/tests/backend/quantization/test_int8_convrot_state_dict.py@@ -13,8 +13,14 @@ import torchfrom invokeai.backend.quantization.int8_convrot import (CONVROT_GROUP_SIZE,+ cast_unquantized,check_int8_scale_layout,+ drop_unconsumed_quantization_sidecars,extract_int8_convrot_markers,+ predict_int8_cast_size,+ reject_unmarked_int8_weights,+ split_int8_convrot_layers,+ swap_in_int8_linears,)MARKER = {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": CONVROT_GROUP_SIZE}@@ -95,3 +101,232 @@ class TestTheScaleLayoutsSeenInRealCheckpoints:def test_the_message_names_the_layer_and_both_shapes(self) -> None:with pytest.raises(ValueError, match=r"'last\.up' has a \(4, 4\) scale for a \(512, 512\) weight"):check_int8_scale_layout("last.up", torch.zeros(512, 512, dtype=torch.int8), torch.ones(4, 4))+++class TestCastUnquantized:+ """The cast that runs over an int8 state dict, and what it must leave alone.++ Two kinds of tensor must survive it unchanged: the quantized payloads, which+ `Int8ConvrotLinear` reads as stored, and every integer payload, which is not a weight at all.+ """++ def test_an_ordinary_float_weight_is_cast(self) -> None:+ sd = {"dense.weight": torch.ones(4, 4, dtype=torch.float32)}++ cast_unquantized(sd, torch.bfloat16, {})++ assert sd["dense.weight"].dtype is torch.bfloat16++ def test_the_pinned_int8_weight_and_its_scale_are_left_as_stored(self) -> None:+ """An int8 weight cast to bf16 is no longer int8, and an fp32 scale rounded to bf16 is a+ different scale."""+ sd = {+ "q.weight": torch.ones(4, CONVROT_GROUP_SIZE, dtype=torch.int8),+ "q.weight_scale": torch.full((4, 1), 0.1, dtype=torch.float32),+ }++ cast_unquantized(sd, torch.bfloat16, {"q": MARKER})++ assert sd["q.weight"].dtype is torch.int8+ assert sd["q.weight_scale"].dtype is torch.float32++ @pytest.mark.parametrize(+ ("label", "tensor"),+ [+ ("index_buffer", torch.arange(5, dtype=torch.int64)),+ ("packed_uint8_buffer", torch.zeros(8, dtype=torch.uint8)),+ ("bool_mask", torch.tensor([True, False, True])),+ ],+ )+ def test_an_integer_payload_keeps_its_dtype(self, label, tensor) -> None:+ """Not weights. An index buffer installed as a float raises `IndexError: tensors used as+ indices must be long, byte or bool` inside the forward; a bool mask cast to bf16 changes+ what the mask means and raises nothing at all."""+ sd = {f"module.{label}": tensor}++ cast_unquantized(sd, torch.bfloat16, {})++ assert sd[f"module.{label}"].dtype is tensor.dtype+++class TestWhichMarkedLayersMayStayInt8:+ """The int8 branch skips the whole fp8 pipeline, so every filter that pipeline applies before+ leaving a weight quantized has to exist here too, or the int8 path is the lenient one."""++ @staticmethod+ def _model() -> torch.nn.Module:+ model = torch.nn.Module()+ model.t_embedder = torch.nn.Module()+ model.t_embedder.mlp = torch.nn.ModuleList([torch.nn.Linear(CONVROT_GROUP_SIZE, 4, bias=False)])+ model.proj = torch.nn.Linear(CONVROT_GROUP_SIZE, 4, bias=False)+ return model++ @staticmethod+ def _sd() -> dict:+ return {+ "t_embedder.mlp.0.weight": torch.ones(4, CONVROT_GROUP_SIZE, dtype=torch.int8),+ "t_embedder.mlp.0.weight_scale": torch.full((4, 1), 0.5),+ "proj.weight": torch.ones(4, CONVROT_GROUP_SIZE, dtype=torch.int8),+ "proj.weight_scale": torch.full((4, 1), 0.5),+ }++ def test_a_precision_sensitive_layer_is_dequantized_and_dropped_from_the_swap(self) -> None:+ """Diffusers models declare these because their forwards *read their own weight's dtype*.+ On an `Int8ConvrotLinear` that reads `torch.int8`, and the branch that follows has no idea+ what to do with it."""+ sd = self._sd()+ markers = {"t_embedder.mlp.0": dict(MARKER, convrot=False), "proj": dict(MARKER, convrot=False)}++ surviving = split_int8_convrot_layers(+ sd, markers, torch.float32, model=self._model(), skip_patterns=("t_embedder",)+ )++ assert set(surviving) == {"proj"}+ assert sd["t_embedder.mlp.0.weight"].dtype is torch.float32+ assert torch.allclose(sd["t_embedder.mlp.0.weight"], torch.full((4, CONVROT_GROUP_SIZE), 0.5))+ # Its scale is consumed by the dequantization, not left behind as an orphan key.+ assert "t_embedder.mlp.0.weight_scale" not in sd+ assert sd["proj.weight"].dtype is torch.int8++ def test_a_one_dimensional_quantized_weight_is_dequantized_rather_than_refused(self) -> None:+ """Repacks that quantize everything ship 1-D norms. There is no linear for those to become,+ but the scale is right there, so the decode is unambiguous -- the fp8 path makes the same+ call for the same reason."""+ sd = {+ "norm.weight": torch.ones(CONVROT_GROUP_SIZE, dtype=torch.int8),+ "norm.weight_scale": torch.tensor(0.25),+ }+ markers = {"norm": {"format": "int8_tensorwise", "convrot": False}}++ surviving = split_int8_convrot_layers(sd, markers, torch.float32, model=self._model())++ assert surviving == {}+ assert torch.allclose(sd["norm.weight"], torch.full((CONVROT_GROUP_SIZE,), 0.25))++ def test_a_one_dimensional_weight_marked_convrot_is_refused_by_name(self) -> None:+ """The rotation is defined over a weight's input dimension. A 1-D weight claiming it is a+ marker this decode cannot honor either way, and the shape unpack alone said nothing."""+ sd = {"norm.weight": torch.ones(CONVROT_GROUP_SIZE, dtype=torch.int8), "norm.weight_scale": torch.tensor(0.25)}++ with pytest.raises(ValueError, match=r"'norm' is marked convrot but its weight is \(256,\)"):+ split_int8_convrot_layers(sd, {"norm": dict(MARKER, convrot=True)}, torch.float32, model=self._model())++ def test_a_marker_on_a_non_linear_is_dequantized_rather_than_installed(self) -> None:+ """An `Int8ConvrotLinear` cannot stand in for an Embedding: the swap would succeed and the+ failure would surface much later, inside that module's forward."""+ model = self._model()+ model.embed = torch.nn.Embedding(8, CONVROT_GROUP_SIZE)+ sd = {+ "embed.weight": torch.ones(8, CONVROT_GROUP_SIZE, dtype=torch.int8),+ "embed.weight_scale": torch.tensor(0.5),+ }++ surviving = split_int8_convrot_layers(sd, {"embed": dict(MARKER, convrot=False)}, torch.float32, model=model)++ assert surviving == {}+ assert sd["embed.weight"].dtype is torch.float32++ def test_the_reservation_charges_what_the_split_and_the_cast_will_leave_behind(self) -> None:+ """Reserving happens before the split, so the prediction has to apply the same filters:+ a layer the split widens but the prediction charged one byte for is a reservation short by+ exactly that layer, and the widening transient lands on an unreserved cache."""+ sd = self._sd()+ markers = {"t_embedder.mlp.0": dict(MARKER, convrot=False), "proj": dict(MARKER, convrot=False)}++ reserved = predict_int8_cast_size(+ sd, torch.bfloat16, markers, model=self._model(), skip_patterns=("t_embedder",)+ )+ surviving = split_int8_convrot_layers(+ sd, markers, torch.bfloat16, model=self._model(), skip_patterns=("t_embedder",)+ )+ cast_unquantized(sd, torch.bfloat16, surviving)++ assert reserved == sum(t.nelement() * t.element_size() for t in sd.values())++ def test_a_pinned_float32_scale_is_charged_at_float32(self) -> None:+ """`cast_unquantized` pins the scale as stored, so charging it the compute dtype's width+ under-counts it by half."""+ sd = {"proj.weight": torch.ones(4, 8, dtype=torch.int8), "proj.weight_scale": torch.ones(4, 1)}++ reserved = predict_int8_cast_size(sd, torch.bfloat16, {"proj": dict(MARKER, convrot=False)})++ assert reserved == 4 * 8 * 1 + 4 * 1 * 4+++class TestWhatTheSwapRefuses:+ """Its preconditions, each of which used to fail somewhere that named neither the layer nor+ the cause. Everything refused here is something `split_int8_convrot_layers` dequantizes, so a+ loader that runs the split never reaches these."""++ @staticmethod+ def _model() -> torch.nn.Module:+ model = torch.nn.Module()+ model.proj = torch.nn.Linear(CONVROT_GROUP_SIZE, 4, bias=False)+ model.embed = torch.nn.Embedding(8, CONVROT_GROUP_SIZE)+ return model++ def test_a_one_dimensional_weight_is_named(self) -> None:+ sd = {"norm.weight": torch.ones(8, dtype=torch.int8), "norm.weight_scale": torch.tensor(0.5)}++ with pytest.raises(ValueError, match=r"'norm'.*\(8,\), not 2-D"):+ swap_in_int8_linears(self._model(), sd, {"norm": dict(MARKER, convrot=False)})++ def test_a_marker_naming_a_module_the_model_lacks_is_named(self) -> None:+ sd = {"absent.weight": torch.ones(4, 8, dtype=torch.int8), "absent.weight_scale": torch.ones(4, 1)}++ with pytest.raises(ValueError, match=r"'absent'.*no such module"):+ swap_in_int8_linears(self._model(), sd, {"absent": dict(MARKER, convrot=False)})++ def test_a_marker_on_a_non_linear_is_named(self) -> None:+ sd = {+ "embed.weight": torch.ones(8, CONVROT_GROUP_SIZE, dtype=torch.int8),+ "embed.weight_scale": torch.ones(8, 1),+ }++ with pytest.raises(ValueError, match=r"'embed'.*Embedding, not an nn\.Linear"):+ swap_in_int8_linears(self._model(), sd, {"embed": dict(MARKER, convrot=False)})++ def test_the_scale_layout_check_is_reached(self) -> None:+ """Nothing else asserted that the swap consults it: deleting the call left every test green+ while a blockwise grid broadcast against the weight."""+ sd = {+ "proj.weight": torch.ones(4, CONVROT_GROUP_SIZE, dtype=torch.int8),+ "proj.weight_scale": torch.ones(2, 2),+ }++ with pytest.raises(ValueError, match=r"Blockwise scale grids"):+ swap_in_int8_linears(self._model(), sd, {"proj": dict(MARKER, convrot=False)})+++class TestTheKeysTheOrphanCheckAndTheSidecarDropActOn:+ """Both used to match by substring or by a blind suffix slice, which is wrong in both+ directions: it exempts keys it should flag and drops keys it should keep."""++ def test_an_int8_tensor_whose_suffix_merely_has_the_right_length_is_an_orphan(self) -> None:+ """Seven characters came off every int8 key, so `foo.qkv.scales` read as `foo.qkv` -- and+ the marker on the *weight* at `foo.qkv` then exempted a packed sidecar nothing decodes."""+ sd = {"foo.qkv.scales": torch.zeros(4, 4, dtype=torch.int8)}++ with pytest.raises(ValueError, match=r"foo\.qkv\.scales"):+ reject_unmarked_int8_weights(sd, {"foo.qkv": MARKER}, "Krea-2")++ def test_an_int8_key_shorter_than_the_suffix_is_an_orphan(self) -> None:+ """It collapsed to the empty string, which a stray marker on the model's own root matches."""+ sd = {"w": torch.zeros(4, 4, dtype=torch.int8)}++ with pytest.raises(ValueError, match=r"'w'"):+ reject_unmarked_int8_weights(sd, {"": MARKER}, "Krea-2")++ def test_a_claimed_weight_is_not_an_orphan(self) -> None:+ reject_unmarked_int8_weights({"foo.weight": torch.zeros(4, 4, dtype=torch.int8)}, {"foo": MARKER}, "Krea-2")++ def test_a_module_whose_name_merely_contains_input_scale_is_kept(self) -> None:+ """`"input_scale" in k` is a substring test, so `...input_scaler.weight` was dropped -- and+ under Z-Image's strict load that surfaces as a missing key, not as a dropped sidecar."""+ sd = {+ "blocks.0.input_scaler.weight": torch.ones(4, 4),+ "blocks.0.attn.input_scale": torch.ones(1),+ "blocks.0.attn.comfy_quant": _marker_blob({"format": "float8_e4m3fn"}),+ }++ assert set(drop_unconsumed_quantization_sidecars(sd)) == {"blocks.0.input_scaler.weight"}diff --git a/tests/backend/stable_diffusion/test_vae_tiling.py b/tests/backend/stable_diffusion/test_vae_tiling.pyindex 4d97a8869b..edd0f67a2a 100644--- a/tests/backend/stable_diffusion/test_vae_tiling.py+++ b/tests/backend/stable_diffusion/test_vae_tiling.py@@ -1,13 +1,137 @@+"""Tile geometry for the SD1.5/SDXL VAE nodes.++`patch_vae_tiling_params` used to take `tile_sample_min_size` and `tile_latent_min_size` as two free+parameters, and both call sites derived the latter as `tile_size // 8`. Those two attributes are not+independent on `AutoencoderKL`: its tiled decode steps the latent loop by one of them and crops each+decoded tile by the other, and its tiled encode mirrors that. Deriving them separately produced a+wrong-sized image for every tile size the two disagree on -- which, at the stock 0.25 overlap+factor, is every value the `multiple_of=8` node field accepts that is not also a multiple of 32.+"""++import pytest+import torchfrom diffusers.models.autoencoders.autoencoder_kl import AutoencoderKL+from diffusers.models.autoencoders.autoencoder_tiny import AutoencoderTinyfrom invokeai.backend.stable_diffusion.vae_tiling import patch_vae_tiling_params+# What both nodes pass, and what the stock AutoencoderKL uses.+OVERLAP_FACTOR = 0.25++# Every value the `tile_size` field accepts between its practical floor and a 512px canvas. The+# node treats 0 as "leave the VAE's own geometry alone" and never enters this path.+FIELD_VALUES = range(128, 520, 8)++[email protected](scope="module")+def vae() -> AutoencoderKL:+ """A structurally faithful SD VAE: four blocks, so the real 8x latent grid, with the channel+ counts cut to what keeps ~100 decodes cheap on CPU."""+ return AutoencoderKL(+ in_channels=3,+ out_channels=3,+ latent_channels=4,+ block_out_channels=(4, 8, 16, 16),+ down_block_types=("DownEncoderBlock2D",) * 4,+ up_block_types=("UpDecoderBlock2D",) * 4,+ layers_per_block=1,+ norm_num_groups=4,+ sample_size=512,+ ).eval()++[email protected](scope="module")+def tiny_vae() -> AutoencoderTiny:+ return AutoencoderTiny(+ encoder_block_out_channels=(4, 4, 4, 4),+ decoder_block_out_channels=(4, 4, 4, 4),+ ).eval()+++class TestEveryFieldValueProducesTheRightShape:+ def test_tiled_decode_keeps_the_full_image_size(self, vae):+ """Before the derivation was shared, 36 of these 49 values assembled an image between 518+ and 542 pixels wide instead of 512 -- silently, and on the most-used decode path."""+ vae.enable_tiling()+ latents = torch.zeros(1, 4, 64, 64)++ wrong: list[tuple[int, int]] = []+ for tile_size in FIELD_VALUES:+ with torch.no_grad(), patch_vae_tiling_params(vae, tile_size, OVERLAP_FACTOR):+ decoded = vae.decode(latents, return_dict=False)[0]+ if decoded.shape != (1, 3, 512, 512):+ wrong.append((tile_size, decoded.shape[-1]))++ assert not wrong++ def test_tiled_encode_keeps_the_full_latent_size(self, vae):+ """The encode path is affected too, and not symmetrically: `_tiled_encode` steps a *pixel*+ loop and crops a *latent* tile, so the same inconsistency shows up as a latent one or two+ elements too large -- which then propagates into denoising -- or as a conv size error.+ Measured before the fix: 14 of 49 values wrong, plus one RuntimeError at 136.+ """+ vae.enable_tiling()+ image = torch.zeros(1, 3, 512, 512)++ wrong: list[tuple[int, int]] = []+ for tile_size in FIELD_VALUES:+ with torch.no_grad(), patch_vae_tiling_params(vae, tile_size, OVERLAP_FACTOR):+ latents = vae.encode(image).latent_dist.mode()+ if latents.shape != (1, 4, 64, 64):+ wrong.append((tile_size, latents.shape[-1]))++ assert not wrong++ @pytest.mark.parametrize("requested,applied", [(128, 128), (136, 128), (160, 160), (200, 192), (512, 512)])+ def test_the_applied_tile_is_the_largest_usable_one_at_or_below_the_request(self, vae, requested, applied):+ """The user-visible part of the fix: a request the VAE cannot assemble is rounded *down* to+ one it can, never up and never honoured literally. At the stock factor that is the nearest+ multiple of 32, so the tile shrinks by at most 24 output pixels."""+ with patch_vae_tiling_params(vae, requested, OVERLAP_FACTOR):+ assert vae.tile_sample_min_size == applied+ assert vae.tile_latent_min_size == applied // 8+++class TestTheTinyVaeIsUnaffected:+ """`AutoencoderTiny` reads only `tile_sample_min_size` in its tiled encode and only+ `tile_latent_min_size` in its tiled decode, so the two never meet and it had no bug to fix. It+ goes through the same derivation rather than a class branch; this pins that that is harmless."""++ def test_tiled_decode_and_encode_keep_their_shapes(self, tiny_vae):+ tiny_vae.enable_tiling()+ for tile_size in FIELD_VALUES:+ with torch.no_grad(), patch_vae_tiling_params(tiny_vae, tile_size, OVERLAP_FACTOR):+ decoded = tiny_vae.decode(torch.zeros(1, 4, 64, 64), return_dict=False)[0]+ encoded = tiny_vae.encode(torch.zeros(1, 3, 512, 512), return_dict=False)[0]+ assert decoded.shape == (1, 3, 512, 512)+ assert encoded.shape == (1, 4, 64, 64)++ def test_its_own_downsample_ratio_is_used_rather_than_a_constant(self, tiny_vae):+ """It names the ratio `spatial_scale_factor` instead of implying it from the block count,+ and that is the attribute its own tiling reads."""+ with patch_vae_tiling_params(tiny_vae, 256, OVERLAP_FACTOR):+ assert tiny_vae.tile_sample_min_size == tiny_vae.tile_latent_min_size * tiny_vae.spatial_scale_factor+++class TestTheVaesOwnGeometryIsRestored:+ """The VAE belongs to the model cache and outlives the invocation, so a tile size set for one+ decode must not become the default for the next."""++ @pytest.mark.parametrize("factory", ["vae", "tiny_vae"])+ def test_all_three_attributes_come_back(self, request, factory):+ subject = request.getfixturevalue(factory)+ before = (subject.tile_sample_min_size, subject.tile_latent_min_size, subject.tile_overlap_factor)++ with patch_vae_tiling_params(subject, 256, 0.5):+ assert subject.tile_overlap_factor == 0.5++ assert (subject.tile_sample_min_size, subject.tile_latent_min_size, subject.tile_overlap_factor) == before++ def test_an_exception_still_restores(self, vae):+ before = (vae.tile_sample_min_size, vae.tile_latent_min_size, vae.tile_overlap_factor)-def test_patch_vae_tiling_params():- """Smoke test the patch_vae_tiling_params(...) context manager. The main purpose of this unit test is to detect if- diffusers ever changes the attributes of the AutoencoderKL class that we expect to exist.- """- vae = AutoencoderKL()+ with pytest.raises(RuntimeError, match="boom"):+ with patch_vae_tiling_params(vae, 256, OVERLAP_FACTOR):+ raise RuntimeError("boom")- with patch_vae_tiling_params(vae, 1, 2, 3):- pass+ assert (vae.tile_sample_min_size, vae.tile_latent_min_size, vae.tile_overlap_factor) == beforediff --git a/tests/backend/util/test_sdpa_scope.py b/tests/backend/util/test_sdpa_scope.pynew file mode 100644index 0000000000..ef6082a1a4--- /dev/null+++ b/tests/backend/util/test_sdpa_scope.py@@ -0,0 +1,189 @@+"""The process-wide owner of torch's SDPA backend selection.++torch's own `sdpa_kernel` saves and restores process-global state non-atomically, so two threads+whose windows overlap leave it permanently changed. These pin that `sdpa_policy` does not, because+the leak escapes the architecture that caused it: every other model in the process then picks+kernels by the leaked order, and `backend.util.attention` sizes working memory from that order.+"""++import logging+import threading++import pytest+import torch+from torch.nn.attention import SDPBackend, sdpa_kernel++import invokeai.backend.util.sdpa_scope as sdpa_scope+from invokeai.backend.util.sdpa_scope import foreign_window_entries, sdpa_policy++KREA2 = (+ SDPBackend.FLASH_ATTENTION,+ SDPBackend.CUDNN_ATTENTION,+ SDPBackend.EFFICIENT_ATTENTION,+ SDPBackend.MATH,+)+ANIMA = (+ SDPBackend.CUDNN_ATTENTION,+ SDPBackend.FLASH_ATTENTION,+ SDPBackend.EFFICIENT_ATTENTION,+ SDPBackend.MATH,+)+EXCLUSIVE = (SDPBackend.MATH,)+++def _global_state() -> tuple[list[int], set[SDPBackend]]:+ """Everything `sdpa_kernel` mutates: the priority order and the per-backend enable flags."""+ from torch.nn.attention import _cur_sdpa_kernel_backends++ return list(torch._C._get_sdp_priority_order()), set(_cur_sdpa_kernel_backends())++[email protected](autouse=True)+def _restore_global_sdpa_state():+ """These mutate process-global torch state, and pytest-xdist gives a worker arbitrary files.++ Without this, a leak here would be indistinguishable from the bug under test in whatever file+ the worker runs next.+ """+ priority, backends = _global_state()+ yield+ torch._C._set_sdp_priority_order(priority)+ sdpa_kernel(list(backends)).__enter__()+++def _run_interleaved(scope, outer: tuple[SDPBackend, ...], inner: tuple[SDPBackend, ...], set_priority: bool = True):+ """A enters, B enters, A exits, B exits -- the ordering torch's save/restore gets wrong.++ Returns what each thread saw while it was inside its own window.+ """+ a_inside, b_inside, a_left = threading.Event(), threading.Event(), threading.Event()+ seen: dict[str, tuple[list[int], set[SDPBackend]]] = {}++ def a():+ with scope(outer, set_priority=set_priority):+ a_inside.set()+ b_inside.wait(timeout=5)++ def b():+ a_inside.wait(timeout=5)+ with scope(inner, set_priority=set_priority):+ b_inside.set()+ a_left.wait(timeout=5)+ seen["b"] = _global_state()++ ta, tb = threading.Thread(target=a), threading.Thread(target=b)+ ta.start()+ tb.start()+ ta.join(timeout=10)+ a_left.set()+ tb.join(timeout=10)+ assert not ta.is_alive() and not tb.is_alive()+ return seen+++class TestTheLeakIsClosed:+ def test_torchs_own_scope_leaks_when_two_windows_overlap(self):+ """The defect this module exists for, pinned against torch so the fix is not mistaken for one.++ If a future torch makes `sdpa_kernel` thread-safe this fails, and `sdpa_policy` can go.+ """+ before = _global_state()+ _run_interleaved(lambda b, set_priority: sdpa_kernel(list(b), set_priority=set_priority), KREA2, ANIMA)+ assert _global_state() != before++ def test_interleaved_windows_restore_the_global_state(self):+ before = _global_state()+ _run_interleaved(sdpa_policy, KREA2, ANIMA)+ assert _global_state() == before++ def test_an_exclusive_policy_does_not_leave_backends_disabled(self):+ """The expensive half: an exclusive override leaks three *disabled* backends, not an order.++ Every later attention in the process then falls to math, which is the O(seq^2) path the+ Krea-2 processor exists to avoid.+ """+ before = _global_state()+ _run_interleaved(sdpa_policy, KREA2, EXCLUSIVE, set_priority=False)+ assert _global_state() == before+++class TestWhileAWindowIsOpen:+ def test_the_open_policy_wins_over_a_later_one(self):+ """Two concurrent sessions cannot hold different values of a process-global setting.++ That is torch's constraint; what this module chooses is *which* one applies and that it is+ restored exactly once. A later window must not overwrite the open one -- overwriting is how+ the leak happens.+ """+ seen = _run_interleaved(sdpa_policy, KREA2, ANIMA)+ krea2_order = [int(b) for b in KREA2]+ assert seen["b"][0][: len(krea2_order)] == krea2_order++ def test_a_single_window_applies_its_policy_and_restores_it(self):+ before = _global_state()+ with sdpa_policy(EXCLUSIVE, set_priority=False):+ _, enabled = _global_state()+ assert enabled == set(EXCLUSIVE)+ assert _global_state() == before++ def test_nesting_in_one_thread_restores_once(self):+ before = _global_state()+ with sdpa_policy(KREA2) as outer_owns:+ inside_outer = _global_state()+ with sdpa_policy(ANIMA) as inner_owns:+ # The inner window must neither apply its own policy nor restore anything: the outer+ # one is still open and owns the globals.+ assert _global_state() == inside_outer+ # And exiting it must not have restored either -- that is how the leak used to happen.+ assert _global_state() == inside_outer+ assert (outer_owns, inner_owns) == (True, False)+ assert _global_state() == before++ def test_an_exception_inside_the_window_still_restores(self):+ before = _global_state()+ with pytest.raises(RuntimeError, match="boom"):+ with sdpa_policy(EXCLUSIVE, set_priority=False):+ raise RuntimeError("boom")+ assert _global_state() == before+++class TestAWindowThatDidNotApply:+ """An exclusive override exists so that a completed run proves which kernel served it.++ A window that did not own the globals voids that, and the benchmark reads this counter to say+ so rather than print a label for a kernel that may not have run.+ """++ def test_a_non_owning_window_is_counted(self):+ before = foreign_window_entries()+ with sdpa_policy(KREA2):+ with sdpa_policy(EXCLUSIVE, set_priority=False) as owned:+ assert owned is False+ assert foreign_window_entries() == before + 1++ def test_a_window_that_asked_for_what_is_already_set_is_not_counted(self):+ before = foreign_window_entries()+ with sdpa_policy(KREA2):+ with sdpa_policy(KREA2):+ pass+ assert foreign_window_entries() == before++ def test_an_override_that_did_not_apply_is_reported_loudly(self, caplog, monkeypatch):+ """At WARNING, and once per distinct pair: reporting once per process would let a benign+ default-vs-default collision swallow the line that invalidates a measurement."""+ monkeypatch.setattr(sdpa_scope, "_reported", set())+ with caplog.at_level(logging.WARNING, logger=sdpa_scope.logger.name):+ with sdpa_policy(KREA2):+ with sdpa_policy(EXCLUSIVE, set_priority=False):+ pass+ assert len(caplog.records) == 1+ assert "did not get the kernel it asked for" in caplog.records[0].message+ assert "MATH" in caplog.records[0].message++ def test_a_default_ranking_collision_is_not_a_warning(self, caplog, monkeypatch):+ monkeypatch.setattr(sdpa_scope, "_reported", set())+ with caplog.at_level(logging.INFO, logger=sdpa_scope.logger.name):+ with sdpa_policy(KREA2):+ with sdpa_policy(ANIMA):+ pass+ assert [r.levelno for r in caplog.records] == [logging.INFO]diff --git a/tests/backend/util/test_vae_tiling_scope.py b/tests/backend/util/test_vae_tiling_scope.pyindex be53fa2ba2..ce9717e829 100644--- a/tests/backend/util/test_vae_tiling_scope.py+++ b/tests/backend/util/test_vae_tiling_scope.py@@ -139,7 +139,7 @@ class TestDiffusersVaesAreHandledToo:"""@staticmethod- def _vae(block_out_channels=(32, 64, 128, 128), sample_size=1024) -> AutoencoderKL:+ def _vae(block_out_channels=(32, 64, 128, 128), sample_size=1024, norm_num_groups=32) -> AutoencoderKL:return AutoencoderKL(in_channels=3,out_channels=3,@@ -148,12 +148,21 @@ class TestDiffusersVaesAreHandledToo:down_block_types=("DownEncoderBlock2D",) * len(block_out_channels),up_block_types=("UpDecoderBlock2D",) * len(block_out_channels),layers_per_block=1,- norm_num_groups=32,+ norm_num_groups=norm_num_groups,sample_size=sample_size,)@pytest.mark.parametrize(- ("requested", "expected_sample"), [(384, 384), (256, 256), (0, DEFAULT_TILE_SAMPLE_MIN_SIZE)]+ ("requested", "expected_sample"),+ [+ (384, 384),+ (256, 256),+ (0, DEFAULT_TILE_SAMPLE_MIN_SIZE),+ # Not a multiple of 32, so the latent tile (25) is snapped down to 24: this VAE's+ # tiled decode cannot assemble a correct image from a latent tile the overlap factor+ # does not divide. See `test_every_tile_size_the_field_accepts_assembles_the_full_image`.+ (200, 192),+ ],)def test_the_requested_size_reaches_the_vae(self, requested, expected_sample):vae = self._vae()@@ -174,6 +183,48 @@ class TestDiffusersVaesAreHandledToo:assert (vae.use_tiling, vae.tile_sample_min_size, vae.tile_latent_min_size) == before+ def test_every_tile_size_the_field_accepts_assembles_the_full_image(self):+ """The sweep the FLUX sibling above runs, pointed at the class that can actually fail it.++ `tiled_decode` steps the latent loop by one quantity and crops each decoded tile by another,+ and the two agree only for some tile sizes. Setting `tile_sample_min_size` and+ `tile_latent_min_size` independently got that wrong for every `multiple_of=8` field value+ that is not a multiple of 32: measured over this range, 36 of the 84 values assembled an+ image between 514 and 542 pixels wide instead of 512.+ """+ # Four blocks for the real 8x latent grid; the widths only have to be legal, so they are+ # cut to what keeps 84 decodes cheap on CPU.+ vae = self._vae(block_out_channels=(4, 8, 16, 16), norm_num_groups=4).eval()+ latent = torch.zeros(1, 4, 64, 64)++ wrong: list[tuple[int, tuple[int, ...]]] = []+ for tile_size in range(128, 800, 8):+ with torch.no_grad(), scoped_vae_tiling(vae, tile_size):+ decoded = vae.decode(latent, return_dict=False)[0]+ if decoded.shape != (1, 3, 512, 512):+ wrong.append((tile_size, tuple(decoded.shape)))++ assert not wrong++ @pytest.mark.parametrize("overlap_factor", [0.125, 0.2, 0.3, 1 / 3, 0.35])+ def test_a_non_stock_overlap_factor_is_honoured_rather_than_assumed(self, overlap_factor):+ """Which tiles a factor admits depends on how it rounds in binary, not on its value.++ 0.25 is the only factor diffusers ships, and at an 8x downsample it admits every multiple+ of 4 -- exactly what treating the factor as the fraction it looks like would also pick. The+ other factors are where that shortcut breaks: 0.3 admits only multiples of 10, and 0.35 only+ multiples of 20, neither of which is the denominator of any nearby simple fraction. Reading+ the answer out of diffusers' own two expressions is what gets those right; approximating+ 0.35 as 5/14 picks a wrong tile for every size below.+ """+ vae = self._vae(block_out_channels=(4, 8, 16, 16), norm_num_groups=4).eval()+ vae.tile_overlap_factor = overlap_factor+ latent = torch.zeros(1, 4, 64, 64)++ for tile_size in (168, 200, 264, 328, 392):+ with torch.no_grad(), scoped_vae_tiling(vae, tile_size):+ assert vae.decode(latent, return_dict=False)[0].shape == (1, 3, 512, 512)+def test_a_decode_at_the_vaes_default_resolution_actually_tiles(self):"""The case the missing size costs: a 1024px decode against a VAE whose default tile is also1024 stays in the single-pass path, which is the one the reservation was sized against."""