Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(attention): let attention_backend pin an SDPA kernel (#9956)
Alexander Eichhornda59eb7e20d5
diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/krea-2.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/krea-2.mdxindex f88125e397..25fb254ed9 100644--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/krea-2.mdx+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/krea-2.mdx@@ -127,11 +127,11 @@ Canvas regional negative prompts, auto-negative, and regional reference images a:::caution[Regional prompting memory]Regional prompting builds a dense boolean attention mask whose memory grows quadratically with the combinedtext and image token count. Invoke reserves memory for retained masks, construction scratch space, and the-dtype-sized additive attention bias created by SDPA. Fused memory-efficient attention support for dense masks-still depends on the GPU, PyTorch build, dtype, and sequence shape. When no fused kernel is available, PyTorch-falls back to math attention, which may use substantially more VRAM and can cause an out-of-memory error.-Reducing image resolution or disabling regional prompting is the practical fallback. Automated CUDA coverage-is skipped on unsupported hardware and cannot exercise every GPU/backend combination.+dtype-sized additive attention bias created by SDPA. Whether a fused kernel (cuDNN or memory-efficient) accepts+a dense mask still depends on the GPU, PyTorch build, dtype, and sequence shape. When no fused kernel is+available, PyTorch falls back to math attention, which may use substantially more VRAM and can cause an+out-of-memory error. Reducing image resolution or disabling regional prompting is the practical fallback.+Automated CUDA coverage is skipped on unsupported hardware and cannot exercise every GPU/backend combination.:::## Style reference@@ -278,11 +278,16 @@ figures with reference images can mean the LoRA was trained with isolated refere## Attention backend-On CUDA, Krea-2 picks the fastest available attention kernel by itself (Flash Attention where the PyTorch-build has it, then cuDNN, then memory-efficient attention). For benchmarking or support questions you-can force one kernel with the environment variable `INVOKE_KREA2_SDPA_BACKEND`: `flash`, `cudnn`,-`efficient` or `math`, or `default` for the automatic order. A forced kernel that the GPU or build does-not support raises an error instead of quietly falling back, and an unknown value stops InvokeAI at startup.+Krea-2 uses InvokeAI's attention kernel order, the same as every other model: Flash Attention where the+PyTorch build has it, then cuDNN, then memory-efficient attention, unless+[`attention_backend`](/configuration/invokeai-yaml/#attention-kernel) ranks another kernel first. A+pinned kernel applies to Krea-2 as well: where it does not take Krea-2's grouped-query heads as they are —+memory-efficient attention does not — InvokeAI expands them so that it can. With `attention_backend: sage`, its+unmasked attention runs on [SageAttention](/configuration/optimization/sage-attention/) instead. For+benchmarking or support questions you can force one kernel with the environment variable+`INVOKE_KREA2_SDPA_BACKEND`: `flash`, `cudnn`, `efficient` or `math`, or `default` for InvokeAI's order.+A forced kernel that the GPU or build does not support raises an error instead of quietly falling back,+and an unknown value stops InvokeAI at startup.Any value, `default` included, also turns on per-step timing in the log, which synchronizes the GPU after-every step and slows generation slightly. Unset the variable for normal use.+every step and slows generation slightly, and keeps SageAttention off. Unset the variable for normal use.diff --git a/docs/src/content/docs/configuration/01.invokeai-yaml.mdx b/docs/src/content/docs/configuration/01.invokeai-yaml.mdxindex 2c1dfa1186..0af7fe60db 100644--- a/docs/src/content/docs/configuration/01.invokeai-yaml.mdx+++ b/docs/src/content/docs/configuration/01.invokeai-yaml.mdx@@ -195,6 +195,33 @@ Notes:Background indexing of new images already waits until no generation is running, so it simply takes the first idle GPU; it is search by image that benefits during a generation.+#### Attention Kernel++`attention_backend` decides how attention runs. The default, `auto`, uses PyTorch's exact attention kernels ranked flash, cuDNN, memory-efficient, math: each call takes the first one the GPU and the PyTorch build support for it. `sage` uses [SageAttention](/configuration/optimization/sage-attention/) for the models listed there.++For measurements and support questions you can rank one of PyTorch's kernels first instead, for the attention of every model on CUDA and ROCm GPUs. It takes effect after restarting InvokeAI:++```yaml+attention_backend: cudnn+```++| Value | Kernel ranked first |+| ----------- | ------------------------------------------------------------------------------------------------------------------------------------- |+| `cudnn` | cuDNN attention. ROCm builds of PyTorch do not have it. |+| `flash` | Flash attention. PyTorch's Windows builds do not have it. |+| `efficient` | Memory-efficient attention. |+| `math` | PyTorch's unfused fallback. It builds the full attention score matrix, so it is much slower and needs far more memory. For debugging. |++The working-memory estimates of most model families do not include the score matrix `math` builds, so with `math` generations can run out of memory; startup logs a warning saying so.++A pinned kernel is never exclusive. A call it cannot serve — the build or GPU has no such kernel, or the call's precision, head size, mask or grouped-query heads rule it out — runs on the next kernel of the default order, and the log says so once per node type and reason:++```+attention_backend 'flash' is not possible for attention in flux_denoise: this PyTorch build or GPU (cuda:0) has no flash kernel; it runs on CUDNN_ATTENTION.+```++The PiD decoder's attention is ranked the same way, but not reported. Images can differ slightly between kernels at the same seed. On the CPU and on Apple Silicon, PyTorch picks its kernels itself and the ranking does not apply.+#### Image Subfolder StrategyBy default, generated images are stored in a single flat directory under `outputs/images/`. The `image_subfolder_strategy` setting lets you organize newly-created images into subfolders automatically. You can edit this setting in `invokeai.yaml` or, as an admin user, under **Settings → Server → Image storage**.diff --git a/docs/src/content/docs/configuration/Optimization/sage-attention.mdx b/docs/src/content/docs/configuration/Optimization/sage-attention.mdxindex 5e9152254f..76f34f20ff 100644--- a/docs/src/content/docs/configuration/Optimization/sage-attention.mdx+++ b/docs/src/content/docs/configuration/Optimization/sage-attention.mdx@@ -21,23 +21,23 @@ the video models were checked against PyTorch's attention for picture changes anSageAttention is enabled per model family once that family has been measured with it. All other models keep PyTorch'sattention.-Whole generation (text encoding, denoising and decoding) with the model already loaded, on an RTX 4090 under Windows,-compared with PyTorch's default attention there:+Denoising time with the model already loaded, on an RTX 4090 under Windows, compared with InvokeAI's default attention+there, which ranks PyTorch's cuDNN kernel ahead of memory-efficient attention:| Model (as measured) | 1024×1024 | 2048×2048 | Notes || --- | --- | --- | --- |-| FLUX.1 dev (FP8) | 16.1 s → 14.0 s (−13 %) | 84.2 s → 54.8 s (−35 %) | Also serves ControlNets inside the denoising loop. |-| FLUX.2 Klein 9B (FP8) | 15.6 s → 15.1 s (−3 %) | 27.1 s → 23.1 s (−15 %) | |-| Z-Image (FP8) | 10.4 s → 10.0 s (−5 %) | 33.7 s → 25.9 s (−23 %) | Also serves ControlNets inside the denoising loop. |-| Qwen-Image 2512 (GGUF Q4_K_M) | 78.8 s → 73.5 s (−7 %) | 208.9 s → 150.3 s (−28 %) | One block reaches about 17 % error per call; images were still judged equivalent. |-| Krea-2 Turbo (GGUF Q4_K_M) | 11.5 s → 11.0 s (−4 %) | 42.7 s → 36.2 s (−15 %) | Off while `INVOKE_KREA2_SDPA_BACKEND` pins a PyTorch kernel. |-| SDXL | 4.4 s → 4.2 s (−5 %) | 19.6 s → 16.1 s (−18 %) | Text cross-attention stays on PyTorch (too short to gain). Also serves ControlNets. |--| Video model (as measured) | Resolution | Generation | Notes |+| FLUX.1 dev (FP8) | 13.8 s → 12.7 s (−8 %) | 64.8 s → 48.6 s (−25 %) | Also serves ControlNets inside the denoising loop. |+| FLUX.2 Klein 9B (FP8) | 2.6 s → 2.5 s (−4 %) | 11.8 s → 9.5 s (−19 %) | |+| Z-Image (FP8) | 4.0 s → 3.8 s (−5 %) | 23.1 s → 18.8 s (−19 %) | Also serves ControlNets inside the denoising loop. |+| Qwen-Image 2512 (GGUF Q4_K_M) | 52.9 s → 50.1 s (−5 %) | 159.1 s → 126.2 s (−21 %) | One block reaches about 17 % error per call; images were still judged equivalent. |+| Krea-2 Turbo (GGUF Q4_K_M) | 10.1 s → 9.8 s (−3 %) | 40.0 s → 33.6 s (−16 %) | Off while `INVOKE_KREA2_SDPA_BACKEND` is set. |+| SDXL | 3.2 s → 3.1 s (−3 %) | 14.5 s → 12.4 s (−14 %) | Text cross-attention stays on PyTorch (too short to gain). Also serves ControlNets. |++| Video model (as measured) | Resolution | Denoising | Notes || --- | --- | --- | --- |-| LTX-2.5 distilled (int8) | 1248×704, 121 frames | 72.0 s → 63.4 s (−12 %) | Video self-attention only; text cross-attention and the audio streams stay on PyTorch. The audio reads the video through cross-attention, so it changes too, but measured no more than with an exact kernel swap: no shift against the picture, same loudness. |-| Wan 2.2 TI2V-5B (GGUF Q8) | 1280×704, 121 frames | 380.9 s → 247.9 s (−35 %) | |-| Wan 2.2 T2V A14B (GGUF Q4_K_M, 4-step Lightning LoRA) | 832×480, 81 frames | Denoising 121.5 s → 60.9 s (−50 %) | Measured with `device_working_mem_gb: 10`. At 1280×720 a 24 GB GPU is already full with PyTorch's attention, and SageAttention made denoising slower: 293 s → 662 s. |+| LTX-2.5 distilled (int8) | 1248×704, 121 frames | 37.2 s → 32.9 s (−12 %) | Video self-attention only; text cross-attention and the audio streams stay on PyTorch. The audio reads the video through cross-attention, so it changes too, but measured no more than with an exact kernel swap: no shift against the picture, same loudness. |+| Wan 2.2 TI2V-5B (GGUF Q8) | 1280×704, 121 frames | 286.1 s → 216.8 s (−24 %) | |+| Wan 2.2 T2V A14B (GGUF Q4_K_M, 4-step Lightning LoRA) | 832×480, 81 frames | 61.3 s → 46.5 s (−24 %) | Measured with `device_working_mem_gb: 10`. At 1280×720 a 24 GB GPU is already full with PyTorch's attention, and SageAttention made denoising slower: 293 s → 662 s, measured against the memory-efficient kernel. |At 1024×1024 most of a step is spent outside attention, so the gain is small; at high resolutions and for video,attention dominates. GGUF models spend much of each step dequantizing weights, which SageAttention does not touch.diff --git a/docs/src/generated/settings.json b/docs/src/generated/settings.jsonindex 4755ca5fc0..ef0184b18d 100644--- a/docs/src/generated/settings.json+++ b/docs/src/generated/settings.json@@ -823,15 +823,19 @@{"category": "GENERATION","default": "auto",- "description": "Attention kernel for the attention inside diffusion models. `auto` lets PyTorch choose among its exact SDPA kernels and never selects a quantized one. `sage` uses SageAttention 2 for the models listed in the SageAttention docs: faster, most at high resolutions and for video, but quantized, so images differ slightly from `auto` at the same seed. SageAttention is installed separately and needs an NVIDIA GPU with compute capability 8.0 or newer; masked attention, text encoders and VAEs keep PyTorch SDPA.",+ "description": "Attention kernel for the attention inside diffusion models. `auto` uses PyTorch's exact SDPA kernels ranked flash, cuDNN, memory-efficient, math, taking the first one the GPU and build support for each call; it never selects a quantized one. `sage` uses SageAttention 2 for the models listed in the SageAttention docs: faster, most at high resolutions and for video, but quantized, so images differ slightly from `auto` at the same seed. SageAttention is installed separately and needs an NVIDIA GPU with compute capability 8.0 or newer; masked attention, text encoders and VAEs keep PyTorch SDPA. `cudnn`, `flash`, `efficient` and `math` rank that PyTorch kernel first for all attention on CUDA and ROCm GPUs, ahead of the `auto` order. That is never exclusive: a call the kernel cannot serve runs on the next kernel, and the log reports that once per node type and reason (not for the PiD decoder, whose attention is ranked the same but not reported). `math` materializes the full attention score matrix, so it is slow and needs much more memory, which the working-memory estimates of most model families do not reserve, so generations can run out of memory; it is meant for debugging. Images can differ slightly between kernels.","env_var": "INVOKEAI_ATTENTION_BACKEND","literal_values": ["auto",- "sage"+ "sage",+ "cudnn",+ "flash",+ "efficient",+ "math"],"name": "attention_backend","required": false,- "type": "typing.Literal['auto', 'sage']",+ "type": "typing.Literal['auto', 'sage', 'cudnn', 'flash', 'efficient', 'math']","validation": {}},{diff --git a/invokeai/app/invocations/anima/anima_denoise.py b/invokeai/app/invocations/anima/anima_denoise.pyindex 0d7519e17a..ea044b59b2 100644--- a/invokeai/app/invocations/anima/anima_denoise.py+++ b/invokeai/app/invocations/anima/anima_denoise.py@@ -17,13 +17,11 @@ Key differences from Z-Image denoise:"""import math-import sysfrom contextlib import ExitStackfrom typing import Callable, Iterator, Optionalimport torchimport torchvision.transforms as tv_transforms-from torch.nn.attention import SDPBackendfrom torchvision.transforms.functional import resize as tv_resizefrom torchvision.transforms.functional import to_tensorfrom tqdm import tqdm@@ -74,7 +72,6 @@ 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@@ -767,29 +764,6 @@ class AnimaDenoiseInvocation(BaseInvocation):)with ExitStack() as exit_stack:- # On Windows + CUDA, opt into cuDNN's flash-attention kernel. torch on- # Windows does not ship the native flash-attention backend, so SDPA falls- # back to the slower memory-efficient kernel; cuDNN's kernel is ~1.7x faster- # for Anima's attention shapes (~6% per denoising step at 1024x1024). The- # cuDNN SDP backend sits low in torch's default priority and is never- # selected, so we opt in explicitly.- #- # This is a priority *list*, not a forced kernel: torch picks the first- # eligible backend per call, and MATH is always eligible, so it degrades- # safely on any GPU/dtype where cuDNN is unavailable. Scoped to Windows +- # CUDA — elsewhere torch's default backend is already fast.- if device.type == "cuda" and sys.platform == "win32":- exit_stack.enter_context(- sdpa_policy(- [- SDPBackend.CUDNN_ATTENTION,- SDPBackend.FLASH_ATTENTION,- SDPBackend.EFFICIENT_ATTENTION,- SDPBackend.MATH,- ],- set_priority=True,- )- )# A GGUF or int8_tensorwise build dequantizes each quantized Linear per forward, a transient its# resident size does not cover. Passed alone because this node has no activation estimate, so the# cache floors it at `device_working_mem_gb`; zero for other builds. Read from the unlocked model.diff --git a/invokeai/app/invocations/krea2/krea2_denoise.py b/invokeai/app/invocations/krea2/krea2_denoise.pyindex 0f88f445b9..11df13a668 100644--- a/invokeai/app/invocations/krea2/krea2_denoise.py+++ b/invokeai/app/invocations/krea2/krea2_denoise.py@@ -28,7 +28,6 @@ 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,@@ -70,7 +69,6 @@ from invokeai.backend.rectified_flow.rectified_flow_inpaint_extension import Recfrom invokeai.backend.rectified_flow.schedule_shift import ShiftFit, load_schedulerfrom 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.attention import sdpa_score_matrix_bytesfrom invokeai.backend.util.devices import TorchDevicefrom invokeai.backend.util.logging import InvokeAILogger@@ -96,10 +94,6 @@ 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)@@ -127,12 +121,6 @@ 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 | "@@ -731,13 +719,6 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):# is how a model that loaded comfortably OOMs in its first step. Zero for any other format.estimated_working_memory += peak_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(transformer_info.model_on_device(working_mem_bytes=estimated_working_memory)@@ -789,8 +770,8 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):reference_kv,)- # An INVOKE_KREA2_SDPA_BACKEND override pins one PyTorch kernel to measure it; SageAttention must not- # serve those calls instead.+ # An INVOKE_KREA2_SDPA_BACKEND override measures PyTorch's kernels -- one pinned kernel, or the+ # process-wide order for `default` -- so SageAttention must not serve those calls instead.if resolve_krea2_sdpa_backends().override is None:exit_stack.enter_context(sage_attention_scope())@@ -1029,10 +1010,10 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):"""The score matrix the main blocks' joint attention materializes, where it does (0 on a fused kernel).One call is alive at a time: the blocks run in sequence, and so do the conditional and unconditional passes.- The K/V heads are expanded to the query heads before the call on any build without a fused grouped-query- kernel (`backend/krea2/attention.py`), so the query head count is the one that counts. Heads come from the- loaded model's config. The probe answers for torch's default policy, so forcing the math kernel through the- `INVOKE_KREA2_SDPA_BACKEND` debugging switch is not priced.+ The K/V heads are expanded to the query heads before the call unless a fused kernel takes them grouped+ (`backend/krea2/attention.py`), so the query head count is the one that counts. Heads come from the loaded+ model's config. The probe answers for the process-wide policy the call runs under (`attention_backend: math`+ included), so forcing the math kernel through the `INVOKE_KREA2_SDPA_BACKEND` debugging switch is not priced."""config = getattr(transformer, "config", None)num_heads = getattr(config, "num_attention_heads", None)diff --git a/invokeai/app/invocations/qwen_image_2_1/qwen_image_2_1_denoise.py b/invokeai/app/invocations/qwen_image_2_1/qwen_image_2_1_denoise.pyindex 79c7f0ac39..d2110b6aa1 100644--- a/invokeai/app/invocations/qwen_image_2_1/qwen_image_2_1_denoise.py+++ b/invokeai/app/invocations/qwen_image_2_1/qwen_image_2_1_denoise.py@@ -25,7 +25,6 @@ from invokeai.app.invocations.fields import (from invokeai.app.invocations.metadata_linked import LatentsMetaOutputfrom invokeai.app.invocations.model import TransformerFieldfrom invokeai.app.services.shared.invocation_context import InvocationContext-from invokeai.app.util.startup_utils import log_attention_backendsfrom invokeai.backend.flux.sampling_utils import clip_timestep_schedule_fractionalfrom invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, QwenImage21VariantTypefrom invokeai.backend.patches.layer_patcher import LayerPatcher, PatchSpec@@ -476,7 +475,6 @@ class QwenImage21DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):image_seq_len + max(pos_prefix, neg_prefix or 0),dtype,)- log_attention_backends(logger, device)total_steps = len(sigmas) - 1step_callback = self._step_callback(context)diff --git a/invokeai/app/services/config/config_default.py b/invokeai/app/services/config/config_default.pyindex e5e2c2743b..99ea642ee7 100644--- a/invokeai/app/services/config/config_default.py+++ b/invokeai/app/services/config/config_default.py@@ -28,7 +28,7 @@ DB_FILE = Path("invokeai.db")LEGACY_INIT_FILE = Path("invokeai.init")PRECISION = Literal["auto", "float16", "bfloat16", "float32"]ATTENTION_TYPE = Literal["auto", "normal", "xformers", "sliced", "torch-sdp"]-ATTENTION_BACKEND = Literal["auto", "sage"]+ATTENTION_BACKEND = Literal["auto", "sage", "cudnn", "flash", "efficient", "math"]NOISE_DTYPE = Literal["float32", "float16"]ROCM_AOTRITON = Literal["auto", "on", "off"]ATTENTION_SLICE_SIZE = Literal["auto", "balanced", "max", 1, 2, 3, 4, 5, 6, 7, 8]@@ -138,7 +138,7 @@ class InvokeAIAppConfig(BaseSettings):tiny_autoencoder_previews: Render denoising previews with an installed Tiny AutoEncoder instead of the linear latent projection. Install the matching Tiny AutoEncoder starter model; families without one keep linear previews. A preview costs about 25 ms and 0.65 GB of transient VRAM on an RTX 4090; not recommended on CPU-only installs, where one takes about 2 s.attention_type: Attention type.<br>Valid values: `auto`, `normal`, `xformers`, `sliced`, `torch-sdp`attention_slice_size: Slice size, valid when attention_type=="sliced".<br>Valid values: `auto`, `balanced`, `max`, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`- attention_backend: Attention kernel for the attention inside diffusion models. `auto` lets PyTorch choose among its exact SDPA kernels and never selects a quantized one. `sage` uses SageAttention 2 for the models listed in the SageAttention docs: faster, most at high resolutions and for video, but quantized, so images differ slightly from `auto` at the same seed. SageAttention is installed separately and needs an NVIDIA GPU with compute capability 8.0 or newer; masked attention, text encoders and VAEs keep PyTorch SDPA.<br>Valid values: `auto`, `sage`+ attention_backend: Attention kernel for the attention inside diffusion models. `auto` uses PyTorch's exact SDPA kernels ranked flash, cuDNN, memory-efficient, math, taking the first one the GPU and build support for each call; it never selects a quantized one. `sage` uses SageAttention 2 for the models listed in the SageAttention docs: faster, most at high resolutions and for video, but quantized, so images differ slightly from `auto` at the same seed. SageAttention is installed separately and needs an NVIDIA GPU with compute capability 8.0 or newer; masked attention, text encoders and VAEs keep PyTorch SDPA. `cudnn`, `flash`, `efficient` and `math` rank that PyTorch kernel first for all attention on CUDA and ROCm GPUs, ahead of the `auto` order. That is never exclusive: a call the kernel cannot serve runs on the next kernel, and the log reports that once per node type and reason (not for the PiD decoder, whose attention is ranked the same but not reported). `math` materializes the full attention score matrix, so it is slow and needs much more memory, which the working-memory estimates of most model families do not reserve, so generations can run out of memory; it is meant for debugging. Images can differ slightly between kernels.<br>Valid values: `auto`, `sage`, `cudnn`, `flash`, `efficient`, `math`force_tiled_decode: Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty). A tiled decode is not pixel-identical to a single-pass one: a VAE decoder normalises and attends over the whole image, so the difference is spread across it rather than confined to the tile seams. Also tiles the encode. Read by the SD1.5/SDXL, FLUX.1, FLUX.2, Z-Image, Qwen-Image and Qwen-Image-2.1 VAE nodes, the Anima encode, the Z-Image control encode and the Krea-2 style reference; other model families ignore it.auto_tiled_decode: Decode large images in tiles when an untiled decode's estimated working memory would take most of the GPU's memory (FLUX.1, FLUX.2, Z-Image, Qwen-Image, Qwen-Image-2.1, Krea-2 and Wan decodes, and Qwen-Image-2.1 encodes). Turn off to decode untiled unless tiling is requested; the FLUX.1, FLUX.2 and Z-Image decodes then still retry tiled after running out of memory. Anima keeps tiling a decode too large for its GPU either way, because tiling is what makes that case fast there.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.@@ -275,7 +275,7 @@ class InvokeAIAppConfig(BaseSettings):tiny_autoencoder_previews: bool = Field(default=False, description="Render denoising previews with an installed Tiny AutoEncoder instead of the linear latent projection. Install the matching Tiny AutoEncoder starter model; families without one keep linear previews. A preview costs about 25 ms and 0.65 GB of transient VRAM on an RTX 4090; not recommended on CPU-only installs, where one takes about 2 s.")attention_type: ATTENTION_TYPE = Field(default="auto", description="Attention type.")attention_slice_size: ATTENTION_SLICE_SIZE = Field(default="auto", description='Slice size, valid when attention_type=="sliced".')- attention_backend: ATTENTION_BACKEND = Field(default="auto", description="Attention kernel for the attention inside diffusion models. `auto` lets PyTorch choose among its exact SDPA kernels and never selects a quantized one. `sage` uses SageAttention 2 for the models listed in the SageAttention docs: faster, most at high resolutions and for video, but quantized, so images differ slightly from `auto` at the same seed. SageAttention is installed separately and needs an NVIDIA GPU with compute capability 8.0 or newer; masked attention, text encoders and VAEs keep PyTorch SDPA.")+ attention_backend: ATTENTION_BACKEND = Field(default="auto", description="Attention kernel for the attention inside diffusion models. `auto` uses PyTorch's exact SDPA kernels ranked flash, cuDNN, memory-efficient, math, taking the first one the GPU and build support for each call; it never selects a quantized one. `sage` uses SageAttention 2 for the models listed in the SageAttention docs: faster, most at high resolutions and for video, but quantized, so images differ slightly from `auto` at the same seed. SageAttention is installed separately and needs an NVIDIA GPU with compute capability 8.0 or newer; masked attention, text encoders and VAEs keep PyTorch SDPA. `cudnn`, `flash`, `efficient` and `math` rank that PyTorch kernel first for all attention on CUDA and ROCm GPUs, ahead of the `auto` order. That is never exclusive: a call the kernel cannot serve runs on the next kernel, and the log reports that once per node type and reason (not for the PiD decoder, whose attention is ranked the same but not reported). `math` materializes the full attention score matrix, so it is slow and needs much more memory, which the working-memory estimates of most model families do not reserve, so generations can run out of memory; it is meant for debugging. Images can differ slightly between kernels.")force_tiled_decode: bool = Field(default=False, description="Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty). A tiled decode is not pixel-identical to a single-pass one: a VAE decoder normalises and attends over the whole image, so the difference is spread across it rather than confined to the tile seams. Also tiles the encode. Read by the SD1.5/SDXL, FLUX.1, FLUX.2, Z-Image, Qwen-Image and Qwen-Image-2.1 VAE nodes, the Anima encode, the Z-Image control encode and the Krea-2 style reference; other model families ignore it.")auto_tiled_decode: bool = Field(default=True, description="Decode large images in tiles when an untiled decode's estimated working memory would take most of the GPU's memory (FLUX.1, FLUX.2, Z-Image, Qwen-Image, Qwen-Image-2.1, Krea-2 and Wan decodes, and Qwen-Image-2.1 encodes). Turn off to decode untiled unless tiling is requested; the FLUX.1, FLUX.2 and Z-Image decodes then still retry tiled after running out of memory. Anima keeps tiling a decode too large for its GPU either way, because tiling is what makes that case fast there.")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.")diff --git a/invokeai/app/services/session_processor/session_processor_default.py b/invokeai/app/services/session_processor/session_processor_default.pyindex d807c191bb..647d26a688 100644--- a/invokeai/app/services/session_processor/session_processor_default.py+++ b/invokeai/app/services/session_processor/session_processor_default.py@@ -49,6 +49,8 @@ from invokeai.app.services.shared.graph import CollectInvocation, IterateInvocatfrom invokeai.app.services.shared.invocation_context import InvocationContextData, build_invocation_contextfrom invokeai.app.services.working_memory_calibration.working_memory_calibration_common import calibration_run_idfrom invokeai.app.util.profiler import Profiler+from invokeai.app.util.startup_utils import log_attention_backends+from invokeai.backend.util.attention import attention_callerfrom invokeai.backend.util.device_pool import (GENERATION_DEVICE_POOL,idle_device_borrowed,@@ -498,9 +500,14 @@ class DefaultSessionRunner(SessionRunnerBase):self.workflow_call_coordinator.begin_workflow_call_boundary(invocation, queue_item, workflow_record)return- # Invoke the node, optionally on a borrowed idle GPU (text encoders only).+ # Invoke the node, optionally on a borrowed idle GPU (text encoders only). Its attention calls are+ # attributed to its type, which the pinned-kernel report (`attention_backend`) names.# Leaving `invocation_resources` releases what the context held for the run, however it ended.- with self._maybe_offload_to_idle_gpu(invocation), data.invocation_resources:+ with (+ self._maybe_offload_to_idle_gpu(invocation),+ attention_caller(invocation.get_type()),+ data.invocation_resources,+ ):run_result = invocation.invoke_internal_with_effects(context=context, services=self._services)output = run_result.outputcontrol_collection = None@@ -1244,6 +1251,21 @@ class DefaultSessionProcessor(SessionProcessorBase):f"Could not release cached VRAM after the session on {worker.label}", exc_info=True)+ def _log_attention_backends(self, worker: _SessionWorker) -> None:+ """Log which SDPA kernels this worker's device has and the order they are tried in, once per device.++ Asked for each item about to run, rather than at startup: the probe allocates, so on the boot path it would+ create a CUDA context on an idle server, and so would an item that is skipped before it runs in single-device+ mode. `log_attention_backends` remembers the device, so the probe runs on the first such item, before models are+ resident; it ends with `empty_cache()`. A diagnostic: it must not fail the item.+ """+ try:+ log_attention_backends(self._invoker.services.logger, worker.device or TorchDevice.choose_torch_device())+ except Exception:+ self._invoker.services.logger.debug(+ f"Could not probe the attention backends on {worker.label}", exc_info=True+ )+def _warn_if_vram_paged(self, worker: _SessionWorker) -> None:"""Say so when Windows keeps part of this worker's GPU memory in shared system memory across sessions.@@ -1496,6 +1518,8 @@ class DefaultSessionProcessor(SessionProcessorBase):# allocation is well worth it.gc.collect()+ self._log_attention_backends(worker)+self._invoker.services.logger.info(f"Executing queue item {worker.queue_item.item_id}, session {worker.queue_item.session_id} "f"on {worker.label}"diff --git a/invokeai/app/util/startup_utils.py b/invokeai/app/util/startup_utils.pyindex 8f3cd25a13..9d13c0be87 100644--- a/invokeai/app/util/startup_utils.py+++ b/invokeai/app/util/startup_utils.py@@ -10,6 +10,7 @@ from pathlib import Pathimport torchfrom invokeai.app.services.config.config_default import ATTENTION_BACKEND+from invokeai.backend.util.sdpa_scope import SDPA_KERNELS, describe_sdpa_priority_order, install_default_sdpa_prioritydef find_open_port(port: int) -> int:@@ -167,29 +168,31 @@ def probe_attention_backends(device: torch.device) -> dict[str, bool] | None:return None-# 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()+# Devices already probed, whatever the outcome. 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 --+# and a probe that failed must not allocate and flush the allocator again on every later item.+_probed_attention_devices: set[str] = set()def log_attention_backends(logger: logging.Logger, device: torch.device) -> None:- """Log this device's SDPA backend availability, once per device.+ """Log this device's SDPA backend availability and the priority order torch picks by, once per device.The point is support: a question about attention performance can then be answered by reading alog line instead of asking the user to run a probe script. Call it from a generation path ratherthan from startup -- `probe_attention_backends` explains why."""key = str(device)- if key in _logged_attention_backends:+ if key in _probed_attention_devices:return+ _probed_attention_devices.add(key)available = 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 on {device} "- f"(fp16, {_PROBE_HEADS} heads, seq {_PROBE_SEQ_LEN}, head_dim {_PROBE_HEAD_DIM}, no mask): {summary}"+ f"(fp16, {_PROBE_HEADS} heads, seq {_PROBE_SEQ_LEN}, head_dim {_PROBE_HEAD_DIM}, no mask): {summary}; "+ f"priority {describe_sdpa_priority_order()}")@@ -241,6 +244,22 @@ def apply_monkeypatches(attention_backend: ATTENTION_BACKEND = "auto") -> None:install_rocm_sdpa_guard()+ # Rank torch's exact SDPA kernels flash, cuDNN, memory-efficient, math for every model in the process, with a+ # pinned kernel ahead of them. The calls SageAttention does not serve use this order too.+ pinned = SDPA_KERNELS.get(attention_backend)+ if install_default_sdpa_priority(pinned) and pinned is not None:+ # A pinned kernel is never exclusive: log the attention it does not serve. Outside the ROCm guard, so it sees+ # the heads the guard sends to math; inside the cuDNN fallback, so a retry is reported on its kernel.+ from invokeai.backend.util.attention import install_pinned_sdpa_kernel_report++ install_pinned_sdpa_kernel_report(pinned)++ # cuDNN's eligibility is checked statically, so a cuDNN attention call can still fail at run time. Demote cuDNN+ # and retry instead of failing the generation. Before SageAttention, so its own fallback calls are covered too.+ from invokeai.backend.util.attention import install_cudnn_sdpa_fallback++ install_cudnn_sdpa_fallback()+# Opt-in SageAttention for diffusion-model attention. Installs nothing unless asked for, and never on ROCm.if attention_backend == "sage":from invokeai.backend.util.sage_attention import install_sage_attentiondiff --git a/invokeai/backend/krea2/attention.py b/invokeai/backend/krea2/attention.pyindex cecae07d99..d0c614d7bb 100644--- a/invokeai/backend/krea2/attention.py+++ b/invokeai/backend/krea2/attention.py@@ -6,25 +6,29 @@ kernels do **not** support ``enable_gqa``, so this forces the *math* backend, wh``[heads, seq, seq]`` score matrix. At 1280x720 (3600 image tokens) that is ~5.7 GB **per attention**, and itgrows O(seq^2) — ~40 GB at 2560x1440 — so generation OOMs or the cache offloads the transformer to RAM.-This processor runs under a ranked list of fused SDPA backends instead, which are O(seq) in memory.-Measured: the same 3600-token attention drops from ~5.7 GB to ~0.19 GB.+This processor lets a fused SDPA kernel take the call instead; those are O(seq) in memory, and InvokeAI's+process-wide priority order (`util.sdpa_scope.DEFAULT_SDPA_PRIORITY`) decides which one runs. Measured: the same+3600-token attention drops from ~5.7 GB to ~0.19 GB.The premise above has since become build-dependent. **cuDNN does serve grouped-query attention**, maskincluded, so where it is available the K/V heads can stay at 12 and the expansion is pure waste --``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 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.+processor and the ~5.7 GB math path. And where the kernel ``attention_backend`` pins serves only the+expanded call, expanding is what lets it run. So it is conditional, decided per call by asking the+dispatcher rather than by assuming -- see+``_serves_grouped_query_attention``, which reads the same backend selection the call it answers for will run+under, because that is the state the answer depends on.The math is otherwise identical to ``Krea2AttnProcessor`` (q/k RMSNorm, rotary embeddings, sigmoid output gate)."""import osimport re+from contextlib import nullcontextfrom dataclasses import dataclass-from typing import Iterable, Protocol+from typing import Iterable, Protocol, Sequenceimport torchimport torch.nn.functional as F@@ -38,87 +42,54 @@ from invokeai.backend.krea2.style_reference import (apply_style_reference,capture_style_reference,)+from invokeai.backend.util.attention import sdpa_backend_choice, sdpa_kernel_is_fused, sdpa_runs_fusedfrom invokeai.backend.util.logging import InvokeAILogger-from invokeai.backend.util.sdpa_scope import sdpa_policy+from invokeai.backend.util.sdpa_scope import SDPA_KERNELS, sdpa_flash_ranks_first, sdpa_policy, sdpa_priority_orderlogger = InvokeAILogger.get_logger(__name__)-# Measured on the real Krea-2 attention shape ([1, 48, 4608, 128], bf16), per call:-#-# RTX 4090 / Windows RTX 30-series / Linux-# flash not compiled in 19.74 ms-# cudnn 3.72 ms 21.27 ms-# efficient 5.92 ms 31.45 ms-# math 51.23 ms 168.48 ms-#-# Two things follow, and the order below encodes both.-#-# **Flash first.** Where the build has it, flash is the fastest kernel and is *already* what runs-# today: without `set_priority` torch picks by its own order, in which flash outranks efficient. On-# the 30-series card an unprefixed call lands at 20.15 ms, i.e. on flash, not on efficient. Ranking-# cuDNN above it would therefore be a small regression on every flash-capable build.-#-# **cuDNN second, and it is not a formality.** Flash refuses the additive padding mask that the-# regional-prompting blocks pass, so on exactly those blocks it is skipped and cuDNN takes over ---# where it beats efficient by 1.6x-2.0x. Windows CUDA builds have no flash at all, so there cuDNN is-# what every block gets. Both are the cases the win comes from; flash-first does not give either up.-#-# Everything here is a fallback, never an exclusive choice: an unavailable backend is skipped by the-# dispatcher, so the list degrades on its own -- to efficient on ROCm, where cuDNN is absent and-# flash rejects the mask, and to efficient anywhere neither fused kernel can serve the call.-_KREA2_SDPA_BACKENDS = [- SDPBackend.FLASH_ATTENTION,- SDPBackend.CUDNN_ATTENTION,- SDPBackend.EFFICIENT_ATTENTION,- SDPBackend.MATH,-]-# 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.+# only state a user ever sees by default -- opens no SDPA window: attention runs under the process-wide order.KREA2_SDPA_BACKEND_ENV_VAR = "INVOKE_KREA2_SDPA_BACKEND"-# 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,- "flash": SDPBackend.FLASH_ATTENTION,- "math": SDPBackend.MATH,-}+# Names the process-wide order, so a benchmarking run can state which policy it used. Like unset, it opens no+# window; unlike unset, it counts as an override, which turns on the per-step timing and keeps SageAttention off.+_PROCESS_ORDER = "default"+# Tokens in the probe that stands in for the expanded call (`_expanded_call_choice`). Which kernel serves a call+# depends on its dtype, head_dim and mask kind, not its length; 64 also meets the length rules cuDNN had before 9.+_PROBE_TOKENS = 64@dataclass(frozen=True)class Krea2SdpaBackends:- """Which SDPA backends a Krea-2 attention call may use, and in what order."""+ """The one SDPA backend Krea-2 attention is pinned to, or None to run under the process-wide order."""- backends: tuple[SDPBackend, ...]- set_priority: bool+ exclusive: SDPBackend | None = Noneoverride: str | None = Nonedef describe(self) -> str:- names = ", ".join(b.name for b in self.backends)- return f"sdpa_policy([{names}], set_priority={self.set_priority})"+ if self.exclusive is None:+ return "the process-wide SDPA priority order"+ return f"sdpa_policy([{self.exclusive.name}])"def resolve_krea2_sdpa_backends(raw_override: str | None = None) -> Krea2SdpaBackends:- """Resolve the SDPA backend list, honouring KREA2_SDPA_BACKEND_ENV_VAR.+ """Resolve the SDPA backend choice, honouring KREA2_SDPA_BACKEND_ENV_VAR.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.+ of quietly degrading to math, so a run that completes proves that kernel served it. The value is+ read from the process environment, so every session in the process asks for the same window."""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)+ return Krea2SdpaBackends()value = raw.strip().lower()- 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)+ if value == _PROCESS_ORDER:+ return Krea2SdpaBackends(override=value)+ if value in SDPA_KERNELS:+ return Krea2SdpaBackends(exclusive=SDPA_KERNELS[value], override=value)- valid = ", ".join([*sorted(_EXCLUSIVE_BACKENDS), _RANKED_DEFAULT])+ valid = ", ".join([*sorted(SDPA_KERNELS), _PROCESS_ORDER])raise ValueError(f"{KREA2_SDPA_BACKEND_ENV_VAR}={raw!r} is not a valid value. Valid values: {valid}.")@@ -208,11 +179,13 @@ class Krea2MemoryEfficientAttnProcessor:elif style_mode is Krea2StyleReferenceMode.INJECT:injection = apply_style_reference(style_state, self.block_index, query, key, value)- # 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):+ # Only an exclusive override opens a window; otherwise the call runs under the process-wide order.+ # Both of these belong inside it, and in this order. `_serves_grouped_query_attention` asks the+ # dispatcher about the process-global selection 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.+ exclusive = self.sdpa_backends.exclusive+ with nullcontext() if exclusive is None else sdpa_policy([exclusive]):def attend(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, mask: torch.Tensor | None) -> torch.Tensor:# Krea-2 has 48 query heads over 12 K/V heads. Passing them through as they are avoids@@ -261,7 +234,8 @@ class Krea2MemoryEfficientAttnProcessor:value: torch.Tensor,attention_mask: torch.Tensor | None,) -> bool:- """Whether a fused kernel will take the unexpanded K/V heads for this exact call.+ """Whether a fused kernel takes the unexpanded K/V heads for this exact call, ranked no lower than the kernel the+ expanded call would get.Measured on the Krea-2 shape ([1, 48q/12kv, 4608, 128], bf16): cuDNN serves it, masked andunmasked alike; the memory-efficient kernel refuses grouped-query attention outright, and@@ -270,32 +244,77 @@ 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.- 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.+ Math never gets the heads grouped, not even where it is the only kernel left: its grouped-query+ path expands K/V itself, on every call -- and on every chunk where the ROCm guard splits a long+ call by query rows: simulated for Krea-2 at 4608 tokens, 17 chunks and about 1.8 GiB of copies+ per attention call, against 108 MiB for one explicit expansion. With equal heads math copies+ nothing.++ Asked as the dispatcher's own choice (`util.attention.sdpa_backend_choice`), not as "can some+ kernel serve it": which kernel the call gets depends on the enable flags *and* the priority+ order. A kernel that can serve the call but ranks below math -- cuDNN under torch's own order,+ or after a cuDNN failure demoted it -- leaves the unexpanded call on math. The choice covers+ both, whichever window is open: this processor's exclusive override, or a foreign one, which+ the call honours just the same.++ A fused grouped call is not always enough. Where ``attention_backend`` pins a kernel other than+ flash, the grouped call can run on a lower-ranked one: under ``efficient`` it runs on cuDNN --+ the kernel an admin may have pinned away from -- while the expanded call runs on memory-efficient+ attention, as pinned. So there the grouped kernel must also rank at least as high as the expanded+ call's (`_grouped_ranks_first`), which is asked on a probe (`_expanded_call_choice`) rather than+ on 4x larger K/V. With flash first -- nothing pinned, flash pinned, which is the same order, or+ either after a cuDNN demotion -- that question is not asked and the decision is the one+ dispatcher query it always was.++ Must be called inside the window the attention call will run under, when there is one, and is+ not cached: that state is process-global and a cache key cannot honestly enumerate it. A stale+ "no" costs the expansion this function exists to skip for the rest of the generation, with+ nothing logged. Measured on CPU for this shape, against ~3.5ms for the attention itself: with+ flash first 4.1us per call, 0.1us above the single dispatcher query it was; with another kernel+ pinned first 14.2us (16.4us with a mask). It stays silent under an exclusive override that+ leaves the call no kernel (see `sdpa_backend_choice`)."""if not query.is_cuda:- # SDPAParams is a CUDA-only interface, and no other backend offers a fused GQA path.+ # The grouped path is measured on CUDA (ROCm included) only. Elsewhere the expansion is+ # correct and merely costs memory.+ return False+ flash_first = sdpa_flash_ranks_first()+ if flash_first or flash_first is None:+ return sdpa_runs_fused(query, key, value, attention_mask, enable_gqa=True)+ grouped = sdpa_backend_choice(query, key, value, attention_mask, enable_gqa=True)+ if not sdpa_kernel_is_fused(grouped):+ return False+ order = sdpa_priority_order()+ if order is None:return False+ return grouped == order[0] or _grouped_ranks_first(grouped, _expanded_call_choice(query, attention_mask), order)- try:- params = torch.backends.cuda.SDPAParams(query, key, value, attention_mask, 0.0, False, True)- permitted = self.sdpa_backends.backends- # Only the backends this call will actually permit count. Asking about cuDNN while the- # resolved list excludes it -- which the `efficient` override does -- would answer for a- # kernel the dispatcher is not allowed to reach, and the call would fail outright.- supported = bool(- (SDPBackend.CUDNN_ATTENTION in permitted and torch.backends.cuda.can_use_cudnn_attention(params))- or (SDPBackend.FLASH_ATTENTION in permitted and torch.backends.cuda.can_use_flash_attention(params))- )- except Exception: # noqa: BLE001- # A torch build whose SDPAParams signature differs: fall back to the expansion, which is- # correct everywhere and merely costs memory.- supported = False- return supported+def _grouped_ranks_first(grouped: SDPBackend, expanded: SDPBackend | None, order: Sequence[SDPBackend]) -> bool:+ """Whether `grouped` ranks in `order` at least as high as `expanded`. None -- no kernel, or the dispatcher cannot+ tell -- and a kernel the order does not list rank last."""++ def rank(backend: SDPBackend | None) -> int:+ return order.index(backend) if backend in order else len(order)++ return rank(grouped) <= rank(expanded)+++def _expanded_call_choice(query: torch.Tensor, attention_mask: torch.Tensor | None) -> SDPBackend | None:+ """The kernel the dispatcher would pick for this call with the K/V heads expanded to the query's.++ Asked on a probe of `_PROBE_TOKENS` tokens and one head, in the call's dtype, head_dim and device, with a mask of+ the same dtype and broadcast pattern: which kernel serves a call depends on those, not on its length or head+ count -- the reasoning `util.attention`'s working-memory probe rests on. Allocated per call rather than kept, so it+ pins no allocator block between generations.+ """+ probe = torch.empty((1, 1, _PROBE_TOKENS, query.shape[-1]), dtype=query.dtype, device=query.device)+ mask = None+ if attention_mask is not None:+ broadcast = [1] * (attention_mask.dim() - 2)+ tokens = [_PROBE_TOKENS if size > 1 else 1 for size in attention_mask.shape[-2:]]+ mask = torch.empty(broadcast + tokens, dtype=attention_mask.dtype, device=attention_mask.device)+ return sdpa_backend_choice(probe, probe, probe, mask)class _Krea2AttentionProcessorContainer(Protocol):diff --git a/invokeai/backend/pid/_src/networks/pixeldit_official.py b/invokeai/backend/pid/_src/networks/pixeldit_official.pyindex f71b15176f..4a5577e6d6 100644--- a/invokeai/backend/pid/_src/networks/pixeldit_official.py+++ b/invokeai/backend/pid/_src/networks/pixeldit_official.py@@ -15,7 +15,6 @@ import torchimport torch.nn as nnimport torch.nn.functional as Ffrom torch.distributed import ProcessGroup-from torch.nn.functional import scaled_dot_product_attentionfrom invokeai.backend.pid._src.utils.context_parallel import cat_outputs_cp_with_grad@@ -269,7 +268,7 @@ class RotaryAttention(nn.Module):k = k.view(B, -1, self.num_heads, C // self.num_heads).transpose(1, 2).contiguous()v = v.view(B, -1, self.num_heads, C // self.num_heads).transpose(1, 2).contiguous()- x = scaled_dot_product_attention(q, k, v, attn_mask=mask, dropout_p=0.0)+ x = F.scaled_dot_product_attention(q, k, v, attn_mask=mask, dropout_p=0.0)x = x.transpose(1, 2).reshape(B, N, C)x = self.proj(x)diff --git a/invokeai/backend/util/attention.py b/invokeai/backend/util/attention.pyindex 202fbf979e..8a23219402 100644--- a/invokeai/backend/util/attention.py+++ b/invokeai/backend/util/attention.py@@ -5,7 +5,9 @@ for attention mechanism.import osimport threading-import warnings+from collections.abc import Iterator+from contextlib import contextmanager+from contextvars import ContextVarfrom functools import lru_cache, wrapsfrom typing import Any, Callable@@ -15,6 +17,14 @@ from torch.nn.attention import SDPBackendfrom invokeai.backend.util.devices import TorchDevicefrom invokeai.backend.util.logging import InvokeAILogger+from invokeai.backend.util.oom import is_oom_error+from invokeai.backend.util.sdpa_scope import (+ SDPA_KERNELS,+ cudnn_attention_demoted,+ demote_cudnn_attention,+ describe_sdpa_priority_order,+ sdpa_priority_order,+)def auto_detect_slice_size(latents: torch.Tensor) -> str:@@ -83,9 +93,6 @@ _FUSED_SDP_CHOICES = frozenset(if hasattr(SDPBackend, name))-# Guards the process-global warning filter list that `catch_warnings` swaps; see the probe below.-_WARNING_FILTER_LOCK = threading.Lock()-# Widest head the fused SDPA kernels are trusted with on ROCm. torch 2.13.0+rocm7.2 (ROCm 7.2.4,# gfx1100) returns wrong output from `F.scaled_dot_product_attention` at head_dim 512: the flash# kernel is pure garbage at 16k tokens, the memory-efficient kernel is garbage or NaN depending on@@ -194,27 +201,85 @@ def _chunkable_kv(query: torch.Tensor, key: torch.Tensor, value: torch.Tensor) -return key.dim() == value.dim() == 4 and key.shape[0] == value.shape[0] == batch-def _materializes(+def sdpa_backend_choice(query: torch.Tensor,key: torch.Tensor,value: torch.Tensor,- attn_mask: torch.Tensor | None,- scale: float | None,- enable_gqa: bool,-) -> bool:- """Whether torch would run this exact call on the math kernel, under whatever backend policy is active now.-- `_fused_sdp_choice` is the dispatcher query `F.scaled_dot_product_attention` itself runs, so an `sdpa_policy`- window or diffusers' pinned `sdpa_kernel` is honoured. Anything but a clear fused answer counts as math: when no- backend is eligible at all the probe raises, and the chunks then raise the same error the whole call would have.+ attn_mask: torch.Tensor | None = None,+ dropout_p: float = 0.0,+ is_causal: bool = False,+ *,+ scale: float | None = None,+ enable_gqa: bool = False,+) -> SDPBackend | None:+ """The kernel `F.scaled_dot_product_attention` would run this exact call on, under the backend selection in force+ now; None when no kernel would, or it cannot be told.++ The one wrapper around torch's private dispatch query, so it is torch's own answer rather than a reimplementation+ of its eligibility rules: it honours the per-backend enable flags and the priority order alike, whichever+ `sdpa_policy` window is open -- this thread's or another session's. Not cached: that state is process-global and a+ cache key cannot honestly enumerate it (`sdpa_kernel(..., set_priority=True)` reorders with every flag unchanged:+ measured, `EFFICIENT` before and `MATH` inside). It costs 2.5us, measured on CPU for the Krea-2 shape.++ With math enabled `_fused_sdp_choice` is asked directly: math is then always eligible, so torch never finds nothing+ and stays silent. With math disabled -- only inside an exclusive window -- a call no permitted kernel takes makes+ torch re-run every check in debug mode, printing C++ warnings straight to stderr that no Python warning filter+ reaches, and raise; on a per-attention-call path that is thousands of lines a generation. There the per-kernel+ `can_use_*` checks, asked silently in the dispatcher's own priority order, give its answer. They exist for CUDA+ tensors only, so elsewhere a math-disabled call answers None.++ It is the dispatcher's choice, before InvokeAI's SDPA wrappers act on it: on ROCm the wide-head guard+ (`rocm_sdpa_uses_math_kernel`) sends heads wider than `ROCM_FUSED_SDPA_MAX_HEAD_DIM` to math whatever this says, so+ a caller asking about such heads consults that first."""try:- choice = torch.ops.aten._fused_sdp_choice(- query, key, value, attn_mask, 0.0, False, scale=scale, enable_gqa=enable_gqa- )+ if torch.backends.cuda.math_sdp_enabled():+ choice = SDPBackend(+ int(+ torch.ops.aten._fused_sdp_choice(+ query, key, value, attn_mask, dropout_p, is_causal, scale=scale, enable_gqa=enable_gqa+ )+ )+ )+ return None if choice == SDPBackend.ERROR else choice+ if not query.is_cuda:+ return None+ cuda = torch.backends.cuda+ params = cuda.SDPAParams(query, key, value, attn_mask, dropout_p, is_causal, enable_gqa)+ permitted = {+ SDPBackend.FLASH_ATTENTION: lambda: cuda.flash_sdp_enabled() and cuda.can_use_flash_attention(params),+ SDPBackend.EFFICIENT_ATTENTION: lambda: (+ cuda.mem_efficient_sdp_enabled() and cuda.can_use_efficient_attention(params)+ ),+ SDPBackend.CUDNN_ATTENTION: lambda: cuda.cudnn_sdp_enabled() and cuda.can_use_cudnn_attention(params),+ }+ for backend in sdpa_priority_order() or ():+ if backend in permitted and permitted[backend]():+ return backend+ return Noneexcept Exception:- return True- return int(choice) not in _FUSED_SDP_CHOICES+ return None+++def sdpa_runs_fused(+ query: torch.Tensor,+ key: torch.Tensor,+ value: torch.Tensor,+ attn_mask: torch.Tensor | None = None,+ *,+ scale: float | None = None,+ enable_gqa: bool = False,+) -> bool:+ """Whether `sdpa_backend_choice` names a fused kernel, one that does not build the O(S^2) score matrix.++ "No kernel" and "cannot tell" answer False: the conservative case for every caller.+ """+ return sdpa_kernel_is_fused(sdpa_backend_choice(query, key, value, attn_mask, scale=scale, enable_gqa=enable_gqa))+++def sdpa_kernel_is_fused(choice: SDPBackend | None) -> bool:+ """Whether a `sdpa_backend_choice` answer is a fused kernel. None -- no kernel, or cannot tell -- is not."""+ return choice is not None and int(choice) in _FUSED_SDP_CHOICESdef _chunked_sdpa(@@ -353,7 +418,7 @@ def install_rocm_sdpa_guard() -> None:and not kwargsand _math_score_bytes(query, key) > SDPA_MATH_CHUNK_BYTESand _chunkable_kv(query, key, value)- and (wide_head or _materializes(query, key, value, attn_mask, scale, enable_gqa))+ and (wide_head or not sdpa_runs_fused(query, key, value, attn_mask, scale=scale, enable_gqa=enable_gqa)))if wide_head:if not chunk:@@ -388,6 +453,456 @@ def install_rocm_sdpa_guard() -> None:)+_CUDNN_FALLBACK_SENTINEL = "_invokeai_cudnn_sdpa_fallback"+# Serialises the decision to demote cuDNN, so of two GPU workers whose cuDNN calls fail at once exactly one demotes it+# and warns, and the other retries.+_CUDNN_FALLBACK_LOCK = threading.Lock()+# Bumped once per demotion and read before every call: a call that failed while another session demoted cuDNN can then+# tell, and retry, although by the time it asks, the dispatcher no longer names cuDNN for it.+_cudnn_demotions = 0+++def install_cudnn_sdpa_fallback() -> None:+ """Rebind ``torch.nn.functional.scaled_dot_product_attention`` on CUDA builds so attention that fails inside cuDNN+ is retried on the next kernel instead of failing the generation.++ Under the process-wide order (`sdpa_scope`) cuDNN serves most CUDA attention, and torch checks its eligibility+ statically: a failure at run time -- a plan the cuDNN frontend cannot build, an old cuDNN library swapped in by hand,+ a GPU generation it mishandles -- raises instead of falling back. When a call raises a RuntimeError that is not an+ out-of-memory error (VRAM is the model cache's business), math is enabled, and the dispatcher names cuDNN for that+ exact call -- which, with math eligible, means cuDNN was ranked ahead of math -- cuDNN is ranked behind math for the+ rest of the process (`demote_cudnn_attention`), one warning is logged, and the call is retried once. An error from+ the retry propagates. Math is disabled only inside an exclusive window, such as ``INVOKE_KREA2_SDPA_BACKEND=cudnn``:+ there cuDNN was asked for explicitly, so its error propagates too. A ``torch.AcceleratorError`` is no cuDNN failure+ either: an asynchronous CUDA error from earlier work surfaces at whatever launch comes next and poisons the context,+ so it propagates rather than blaming cuDNN. The enable flags are never touched.++ A grouped-query call (``enable_gqa`` with fewer K/V heads than query heads) is retried with K/V expanded to the+ query heads, which is the same attention: it only reached the kernel unexpanded because cuDNN took it, and with+ cuDNN demoted no fused kernel takes grouped-query attention (memory-efficient refuses it, flash refuses masks and is+ absent on Windows), so the unchanged call would build the full score matrix on math -- gigabytes per call, priced+ nowhere. Expanded, memory-efficient serves it.++ The cost is one Python frame and a ``try`` per call: 0.2-0.35us, measured on CPU against a bare 5.5us call.++ Callers that resolve the function through the module at call time inherit it: InvokeAI's own models, diffusers'+ attention processors and dispatcher, transformers' SDPA attention, and ``torch.nn.functional``'s own callers such+ as ``MultiheadAttention``. Code that bound the function before startup patching bypasses it, as it bypasses the+ ROCm guard: the vendored PiD network (``pid/_src/networks/pixeldit_official.py``) imports the bare name and is+ loaded with ``invokeai.app.invocations.baseinvocation``, before ``apply_monkeypatches`` runs, so a cuDNN failure in+ PiD decode attention still fails the decode.++ Idempotent; a no-op on builds without CUDA, ROCm included, which have no cuDNN attention. Installed once at startup+ via ``apply_monkeypatches``, before SageAttention, so that SageAttention's own fallback calls go through it too.+ """+ if torch.version.cuda is None or torch.version.hip is not None:+ return+ functional = torch.nn.functional+ if getattr(functional.scaled_dot_product_attention, _CUDNN_FALLBACK_SENTINEL, False):+ return+ original = functional.scaled_dot_product_attention++ @wraps(original)+ def scaled_dot_product_attention_with_cudnn_fallback(+ query: torch.Tensor,+ key: torch.Tensor,+ value: torch.Tensor,+ attn_mask: torch.Tensor | None = None,+ dropout_p: float = 0.0,+ is_causal: bool = False,+ *args: Any,+ scale: float | None = None,+ enable_gqa: bool = False,+ **kwargs: Any,+ ) -> torch.Tensor:+ demotions = _cudnn_demotions+ try:+ return original(+ query, key, value, attn_mask, dropout_p, is_causal, *args, scale=scale, enable_gqa=enable_gqa, **kwargs+ )+ except RuntimeError as error:+ if not _cudnn_failed_and_is_demoted(+ error, demotions, query, key, value, attn_mask, dropout_p, is_causal, scale, enable_gqa+ ):+ raise+ if enable_gqa and key.dim() >= 3 and key.shape[-3] != query.shape[-3]:+ # See the docstring: unchanged, the grouped call would now run on math.+ key = key.repeat_interleave(query.shape[-3] // key.shape[-3], dim=-3)+ value = value.repeat_interleave(query.shape[-3] // value.shape[-3], dim=-3)+ enable_gqa = False+ return original(+ query, key, value, attn_mask, dropout_p, is_causal, *args, scale=scale, enable_gqa=enable_gqa, **kwargs+ )++ setattr(scaled_dot_product_attention_with_cudnn_fallback, _CUDNN_FALLBACK_SENTINEL, True)+ functional.scaled_dot_product_attention = scaled_dot_product_attention_with_cudnn_fallback+++def _cudnn_failed_and_is_demoted(+ error: RuntimeError,+ demotions: int,+ query: torch.Tensor,+ key: torch.Tensor,+ value: torch.Tensor,+ attn_mask: torch.Tensor | None,+ dropout_p: float,+ is_causal: bool,+ scale: float | None,+ enable_gqa: bool,+) -> bool:+ """Whether a failed SDPA call was cuDNN's and cuDNN now ranks behind math, so a retry runs on another kernel."""+ global _cudnn_demotions++ if is_oom_error(error) or _is_sticky_cuda_error(error) or not torch.backends.cuda.math_sdp_enabled():+ return False+ with _CUDNN_FALLBACK_LOCK:+ if _cudnn_demotions != demotions:+ return True+ choice = sdpa_backend_choice(+ query, key, value, attn_mask, dropout_p, is_causal, scale=scale, enable_gqa=enable_gqa+ )+ if choice != SDPBackend.CUDNN_ATTENTION or not demote_cudnn_attention():+ return False+ _cudnn_demotions += 1+ # Outside the lock: a stalled log handler must not hold up the other worker's attention.+ _warn_cudnn_demoted(error, query.device)+ return True+++def _is_sticky_cuda_error(error: RuntimeError) -> bool:+ # A torch without the class raises such errors as plain RuntimeErrors, which this cannot tell apart.+ accelerator_error = getattr(torch, "AcceleratorError", None)+ return accelerator_error is not None and isinstance(error, accelerator_error)+++def _warn_cudnn_demoted(error: RuntimeError, device: torch.device) -> None:+ try:+ gpu = torch.cuda.get_device_name(device)+ except Exception:+ gpu = str(device)+ try:+ cudnn = torch.backends.cudnn.version()+ except Exception:+ cudnn = None+ InvokeAILogger.get_logger(__name__).warning(+ f"cuDNN attention failed on {gpu} (torch {torch.__version__}, cuDNN {cudnn}): {error}. InvokeAI now ranks "+ "cuDNN behind PyTorch's other attention kernels for the rest of this run, and generation continues on the next "+ "kernel; images may differ slightly from those cuDNN produced. Please report this at "+ "https://github.com/invoke-ai/InvokeAI/issues, including this message."+ )+++# The code whose attention calls this thread makes, for reports about them: a node's invocation type.+_attention_caller: ContextVar[str | None] = ContextVar("invokeai_attention_caller", default=None)+++@contextmanager+def attention_caller(name: str) -> Iterator[None]:+ """Attribute the attention calls this thread makes inside the block to `name`.++ The session processor enters it around every node's execution with the invocation type (``flux_denoise``,+ ``z_image_text_encoder``), so a report about attention names the node it concerns, for every model family alike. A+ ContextVar, so per thread: sessions on other GPUs keep their own. Calls on threads a node starts itself are not+ attributed.+ """+ token = _attention_caller.set(name)+ try:+ yield+ finally:+ _attention_caller.reset(token)+++_PINNED_REPORT_SENTINEL = "_invokeai_pinned_sdpa_report"+_PINNED_NAMES = {kernel: name for name, kernel in SDPA_KERNELS.items()}+_KERNEL_LABELS = {+ SDPBackend.FLASH_ATTENTION: "flash",+ SDPBackend.CUDNN_ATTENTION: "cuDNN",+ SDPBackend.EFFICIENT_ATTENTION: "memory-efficient",+ SDPBackend.MATH: "math",+}+_KERNEL_ENABLED = {+ SDPBackend.FLASH_ATTENTION: "flash_sdp_enabled",+ SDPBackend.CUDNN_ATTENTION: "cudnn_sdp_enabled",+ SDPBackend.EFFICIENT_ATTENTION: "mem_efficient_sdp_enabled",+ SDPBackend.MATH: "math_sdp_enabled",+}+# torch's per-kernel eligibility checks, in `torch.backends.cuda`. Math has none: it takes every call.+_KERNEL_CHECKS = {+ SDPBackend.FLASH_ATTENTION: "can_use_flash_attention",+ SDPBackend.CUDNN_ATTENTION: "can_use_cudnn_attention",+ SDPBackend.EFFICIENT_ATTENTION: "can_use_efficient_attention",+}+# Reports logged so far, each once. Past this many, new ones are dropped, and that is said once.+_MAX_PINNED_REPORTS = 256+_pinned_reports: set[tuple[Any, ...]] = set()+_pinned_reports_dropped = False+_PINNED_REPORTS_LOCK = threading.Lock()+# (device, kernel) -> whether the kernel serves a plain call on that GPU at all, asked once per GPU.+_plain_call_served: dict[tuple[str, SDPBackend], bool] = {}+# The device types the report asks about. torch registers `_fused_sdp_choice` for these and the CPU; on any other --+# MPS -- the query raises, with about 7.7 KB of message and 79us a call (measured on CPU for an equally raising query).+# The CPU is left out because the ranking never applies there: on a CPU-only install, or for CPU attention on a GPU+# install, every node type would be reported with nothing to act on.+_REPORTED_DEVICE_TYPES = frozenset({"cuda", "xpu"})+++def install_pinned_sdpa_kernel_report(pinned: SDPBackend) -> None:+ """Rebind ``torch.nn.functional.scaled_dot_product_attention`` so that attention the pinned kernel does not serve is+ logged, once per node type, kernel and reason.++ ``attention_backend`` pins a kernel by ranking it first (`sdpa_scope`). That is never exclusive: a call the kernel+ cannot serve runs on the next one, and torch says nothing. Before each call the wrapper asks the dispatcher which+ kernel will serve it (`sdpa_backend_choice`); when that is not the pinned one, it logs one warning per distinct+ (node type from `attention_caller`, pinned kernel, kernel that serves the call, reason), and the call runs+ unchanged. The reasons are torch's answers, not a reimplementation of its eligibility rules:++ * The tensors are on an XPU, where torch picks the kernel without the ranking.+ * The pinned kernel's enable flag is off, as inside an exclusive window such as ``INVOKE_KREA2_SDPA_BACKEND``'s.+ * The kernel serves no plain call on this GPU at all -- flash in Windows CUDA builds, cuDNN on ROCm. Asked once per+ GPU, with torch's ``can_use_*`` check on an fp16, unmasked, head_dim 64 call.+ * cuDNN is pinned, and was demoted after failing at run time (`install_cudnn_sdpa_fallback`).+ * On ROCm, a head wider than ``ROCM_FUSED_SDPA_MAX_HEAD_DIM``, which the guard runs on math.+ * Otherwise the kernel cannot serve this call. The warning lists the call's properties, and then torch's own check+ runs once in debug mode, which prints torch's exact reason to stderr (as C++ warnings, not Python ones).++ A call on the CPU, where torch picks the kernel without the ranking (flash wherever it can, math otherwise), or on a+ device the dispatcher cannot answer for -- MPS -- is not asked about at all, and one it names no kernel+ for, which inside an exclusive window can happen, is not reported. At most ``_MAX_PINNED_REPORTS`` reports are+ kept.++ Callers that resolve the function through the module at call time are covered: InvokeAI's own models, diffusers'+ attention processors and dispatcher, transformers' SDPA attention. Code that bound the function before startup+ patching bypasses the report, as it bypasses the cuDNN fallback: the vendored PiD network+ (``pid/_src/networks/pixeldit_official.py``) runs under the ranking like everything else, but what its attention+ runs on is not reported.++ The cost is the dispatcher query on every call, plus a small key for a call the pinned kernel does not serve.+ Measured on CPU, one thread, against a bare 8.3us call (fp32, [1, 2, 8, 16]): +5.6us on a call the pinned kernel+ serves, 3.5us of it the dispatcher query, and +7.6us on one already reported.++ Installed by ``apply_monkeypatches`` while a kernel is pinned, after the ROCm guard and before the cuDNN fallback.+ Outside the guard, it sees the wide heads the guard sends to math; inside the fallback, the retry after a cuDNN+ demotion is reported with the kernel that serves it. It stays a frame of its own rather than part of the fallback's:+ that one exists on CUDA builds only, this one on every build. Idempotent. Logs the order in force, and warns when+ the build is known to lack the pinned kernel without asking a GPU (no CUDA context is created): flash in a CUDA+ build where ``torch.backends.cuda.is_flash_attention_available()`` is False, cuDNN on ROCm.+ """+ functional = torch.nn.functional+ if getattr(functional.scaled_dot_product_attention, _PINNED_REPORT_SENTINEL, False):+ return+ original = functional.scaled_dot_product_attention+ guarded = bool(getattr(original, _ROCM_SDPA_GUARD_SENTINEL, False))++ @wraps(original)+ def scaled_dot_product_attention_reporting_pinned_kernel(+ query: torch.Tensor,+ key: torch.Tensor,+ value: torch.Tensor,+ attn_mask: torch.Tensor | None = None,+ dropout_p: float = 0.0,+ is_causal: bool = False,+ *args: Any,+ scale: float | None = None,+ enable_gqa: bool = False,+ **kwargs: Any,+ ) -> torch.Tensor:+ try:+ _report_unpinned_call(+ pinned, guarded, query, key, value, attn_mask, dropout_p, is_causal, scale, enable_gqa+ )+ except Exception:+ # A diagnostic must never be what fails attention.+ _warn_pinned_report_failed()+ return original(+ query, key, value, attn_mask, dropout_p, is_causal, *args, scale=scale, enable_gqa=enable_gqa, **kwargs+ )++ setattr(scaled_dot_product_attention_reporting_pinned_kernel, _PINNED_REPORT_SENTINEL, True)+ functional.scaled_dot_product_attention = scaled_dot_product_attention_reporting_pinned_kernel++ logger = InvokeAILogger.get_logger(__name__)+ logger.info(+ f"attention_backend '{_PINNED_NAMES[pinned]}': PyTorch SDPA kernels ranked {describe_sdpa_priority_order()}. "+ f"Attention the {_KERNEL_LABELS[pinned]} kernel cannot serve runs on the next one, logged once per node type "+ "and reason."+ )+ if missing := _build_lacks_kernel(pinned):+ logger.warning(+ f"attention_backend '{_PINNED_NAMES[pinned]}': {missing}, so GPU attention runs on the next kernel in "+ "that order. `attention_backend: auto` is the default."+ )+ if pinned == SDPBackend.MATH:+ logger.warning(+ "attention_backend 'math' is a debugging mode: the math kernel materializes the full attention score "+ "matrix, and the working-memory estimates of most model families do not include it, so generations may "+ "run out of memory. On ROCm the SDPA guard splits large non-causal math-kernel calls into bounded chunks. "+ "`attention_backend: auto` is the default."+ )+++def _build_lacks_kernel(kernel: SDPBackend) -> str | None:+ """Why this build has no `kernel` for its GPUs, where the build alone tells; else None. On ROCm flash depends on the+ GPU as well, which the per-call check answers."""+ if torch.version.hip is not None:+ return "ROCm builds of PyTorch have no cuDNN attention kernel" if kernel == SDPBackend.CUDNN_ATTENTION else None+ if torch.version.cuda is None:+ return None+ if kernel == SDPBackend.FLASH_ATTENTION and not torch.backends.cuda.is_flash_attention_available():+ return "this PyTorch build has no flash-attention kernel for GPUs"+ return None+++@lru_cache(maxsize=1)+def _warn_pinned_report_failed() -> None:+ """Say once, with the traceback, that the pinned-kernel report broke. Called from the handler, so it has one."""+ InvokeAILogger.get_logger(__name__).warning(+ "Could not tell which SDPA kernel serves an attention call; attention_backend reports may be missing.",+ exc_info=True,+ )+++def _report_unpinned_call(+ pinned: SDPBackend,+ guarded: bool,+ query: torch.Tensor,+ key: torch.Tensor,+ value: torch.Tensor,+ attn_mask: torch.Tensor | None,+ dropout_p: float,+ is_causal: bool,+ scale: float | None,+ enable_gqa: bool,+) -> None:+ global _pinned_reports_dropped++ device_type = query.device.type+ if device_type not in _REPORTED_DEVICE_TYPES:+ return+ if guarded and rocm_sdpa_uses_math_kernel(device_type, query.shape[-1]):+ if pinned == SDPBackend.MATH:+ return+ served: SDPBackend | None = SDPBackend.MATH+ reason: tuple[Any, ...] = ("rocm_guard",)+ else:+ served = sdpa_backend_choice(+ query, key, value, attn_mask, dropout_p, is_causal, scale=scale, enable_gqa=enable_gqa+ )+ if served is None or served == pinned:+ return+ reason = _pinned_kernel_bypass(pinned, query, key, attn_mask, dropout_p, is_causal, enable_gqa)+ report = (_attention_caller.get(), pinned, served, reason)+ if report in _pinned_reports or _pinned_reports_dropped:+ return+ with _PINNED_REPORTS_LOCK:+ if report in _pinned_reports or _pinned_reports_dropped:+ return+ dropped = len(_pinned_reports) >= _MAX_PINNED_REPORTS+ if dropped:+ _pinned_reports_dropped = True+ else:+ _pinned_reports.add(report)+ # Outside the lock: a stalled log handler must not hold up the other worker's attention.+ logger = InvokeAILogger.get_logger(__name__)+ name = _PINNED_NAMES[pinned]+ if dropped:+ logger.warning(+ f"attention_backend '{name}': {_MAX_PINNED_REPORTS} kinds of attention calls were reported that the kernel "+ "does not serve; further ones are not logged."+ )+ return+ caller = report[0]+ torch_check = reason[0] == "call" and query.is_cuda and pinned in _KERNEL_CHECKS+ logger.warning(+ f"attention_backend '{name}' is not possible for "+ f"{f'attention in {caller}' if caller else 'attention outside a node'}: "+ f"{_describe_bypass(pinned, reason)}; it runs on {served.name}."+ + (" PyTorch's own check follows on stderr." if torch_check else "")+ )+ if torch_check:+ cuda = torch.backends.cuda+ getattr(cuda, _KERNEL_CHECKS[pinned])(+ cuda.SDPAParams(query, key, value, attn_mask, dropout_p, is_causal, enable_gqa), True+ )+++def _pinned_kernel_bypass(+ pinned: SDPBackend,+ query: torch.Tensor,+ key: torch.Tensor,+ attn_mask: torch.Tensor | None,+ dropout_p: float,+ is_causal: bool,+ enable_gqa: bool,+) -> tuple[Any, ...]:+ """Why a call the dispatcher sends past the pinned kernel goes there, as a small hashable key."""+ device = query.device+ if device.type != "cuda":+ return ("device", device.type)+ if not getattr(torch.backends.cuda, _KERNEL_ENABLED[pinned])():+ return ("disabled",)+ if not _serves_plain_calls(pinned, device):+ return ("build", str(device))+ if pinned == SDPBackend.CUDNN_ATTENTION and cudnn_attention_demoted():+ return ("demoted",)+ mask = "no" if attn_mask is None else "bool" if attn_mask.dtype == torch.bool else "float"+ heads = (query.shape[-3], key.shape[-3]) if query.dim() >= 3 and key.dim() >= 3 else None+ return ("call", query.dtype, query.shape[-1], mask, heads, enable_gqa, is_causal, dropout_p, query.dim())+++def _serves_plain_calls(kernel: SDPBackend, device: torch.device) -> bool:+ """Whether `kernel` serves a plain call on this CUDA device: fp16, no mask, head_dim 64. False means the build or+ the GPU has no such kernel. torch's own check, asked once per device and kernel."""+ check = _KERNEL_CHECKS.get(kernel)+ if check is None:+ return True+ cache_key = (str(device), kernel)+ served = _plain_call_served.get(cache_key)+ if served is None:+ cuda = torch.backends.cuda+ enabled = getattr(cuda, _KERNEL_ENABLED[kernel])+ enabled_before = enabled()+ probe = torch.empty((1, 1, 128, 64), device=device, dtype=torch.float16)+ served = bool(getattr(cuda, check)(cuda.SDPAParams(probe, probe, probe, None, 0.0, False, False), False))+ # The check also reads the enable flag, so an answer given while a window had the kernel switched off is about+ # the window, not the build. It is kept only when the flag was on before the check and is still on after it.+ if enabled_before and enabled():+ _plain_call_served[cache_key] = served+ return served+++def _describe_bypass(pinned: SDPBackend, reason: tuple[Any, ...]) -> str:+ label = _KERNEL_LABELS[pinned]+ kind = reason[0]+ if kind == "device":+ return f"on {reason[1]} PyTorch picks the kernel itself, without the ranking"+ if kind == "disabled":+ return (+ f"the {label} kernel is switched off for this call (by an exclusive window, such as "+ "INVOKE_KREA2_SDPA_BACKEND's)"+ )+ if kind == "build":+ return f"this PyTorch build or GPU ({reason[1]}) has no {label} kernel"+ if kind == "demoted":+ return "cuDNN attention failed earlier in this run and now ranks behind math"+ if kind == "rocm_guard":+ return (+ f"on ROCm, heads wider than {ROCM_FUSED_SDPA_MAX_HEAD_DIM} run on math "+ f"({_ROCM_FUSED_SDPA_MAX_HEAD_DIM_ENV} sets the width)"+ )+ _, dtype, head_dim, mask, heads, enable_gqa, is_causal, dropout_p, ndim = reason+ properties = [str(dtype).removeprefix("torch."), f"head_dim {head_dim}", f"{mask} mask"]+ if heads is not None and (heads[0] != heads[1] or enable_gqa):+ gqa = "enable_gqa" if enable_gqa else "without enable_gqa"+ properties.append(f"{heads[0]} query / {heads[1]} key-value heads, {gqa}")+ if is_causal:+ properties.append("causal")+ if dropout_p:+ properties.append(f"dropout {dropout_p:g}")+ if ndim != 4:+ properties.append(f"{ndim}-D inputs")+ return f"the {label} kernel cannot serve this call ({', '.join(properties)})"++_DISPATCH_TORCH = "torch"_DISPATCH_FUSED = "fused"_DISPATCH_MATH = "math"@@ -453,16 +968,9 @@ def _torch_sdpa_materializes_score_matrix() -> bool:"""Ask torch whether `F.scaled_dot_product_attention` would build the O(S^2) score matrix.- `_fused_sdp_choice` is the same dispatch query torch's own `scaled_dot_product_attention` runs- to pick a kernel, so this is its real answer rather than a reimplementation of its rules.Eligibility depends on the dtype, the head dim and the presence of a mask, not on the sequence- length, so a tiny probe answers for the real forward.-- Not cached. The answer turns on global torch state a cache key cannot honestly enumerate: the- per-backend enable flags, but also the *priority order*, which `sdpa_kernel(..., set_priority=- True)` reorders while leaving every flag untouched -- measured, same flags, `EFFICIENT` before- and `MATH` inside. Each item added to such a key is one more thing to get wrong later, and the- probe costs ~6us against a multi-second forward, so it just runs every time.+ length, so a tiny probe answers for the real forward. Not cached, for the reasons+ `sdpa_backend_choice` gives; it costs microseconds against a multi-second forward.Anything that goes wrong reports the materializing path, which is both the conservative answerand, for the most common cause, the correct one: torch registers `_fused_sdp_choice` for CPU,@@ -477,21 +985,9 @@ def _torch_sdpa_materializes_score_matrix(device = torch.device(device_type) if device_index is None else torch.device(device_type, device_index)q = torch.empty((1, 1, 8, head_dim), device=device, dtype=dtype)mask = torch.empty((1, 1, 8, 8), device=device, dtype=dtype) if has_attn_mask else None- with _WARNING_FILTER_LOCK, warnings.catch_warnings():- # When no fused kernel is eligible, torch re-runs every check in debug mode to warn why- # each one was rejected. That is the case we are deliberately probing for; we do not- # want a wall of warnings every time an estimate is priced.- #- # `catch_warnings` swaps the process-global filter list, and this probe is deliberately- # uncached, so with concurrent session workers two estimates could interleave their- # enter/exit and leave a stale filter set behind. The lock makes the swap atomic against- # other probes; it costs nothing at ~6us of hold time.- warnings.simplefilter("ignore")- choice = int(torch.ops.aten._fused_sdp_choice(q, q, q, mask, 0.0, False))except Exception:return True-- return choice not in _FUSED_SDP_CHOICES+ return not sdpa_runs_fused(q, q, q, mask)def sdpa_score_matrix_bytes(diff --git a/invokeai/backend/util/sdpa_scope.py b/invokeai/backend/util/sdpa_scope.pyindex 09ca7202cc..7e7f5e9d75 100644--- a/invokeai/backend/util/sdpa_scope.py+++ b/invokeai/backend/util/sdpa_scope.py@@ -1,122 +1,217 @@-"""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.+"""One process-wide owner for torch's SDPA backend selection: the kernel priority order, and the per-backend enable+flags while an exclusive window is open.++**The order.** :data:`DEFAULT_SDPA_PRIORITY` is the baseline, written into torch once at startup by+:func:`install_default_sdpa_priority`, before any generation runs. It is one order for the whole process rather than+one per architecture because torch's selection is process-global: per-architecture orders cannot hold while two GPUs+run sessions concurrently, and no measured architecture wants a different one. The server admin can pin one kernel+(``attention_backend: cudnn | flash | efficient | math``, named as in :data:`SDPA_KERNELS`): it is then ranked first,+ahead of the rest of the baseline in its order. A pinned kernel is a ranking too, never an exclusive choice, so a call+it cannot serve runs on the next kernel; `backend.util.attention.install_pinned_sdpa_kernel_report` logs those calls.+Windows never touch the order. One thing changes it afterwards: when an attention call fails inside cuDNN at run time+-- torch checks cuDNN's eligibility statically, so a plan the cuDNN frontend cannot build, an old cuDNN library swapped+in by hand or a GPU generation it mishandles raises instead of falling back -- the SDPA wrapper from+`backend.util.attention.install_cudnn_sdpa_fallback` calls :func:`demote_cudnn_attention`, which ranks cuDNN behind math+for the rest of the process, pinned or not, and retries the call on the next kernel.++The dispatcher honours the order for CUDA and ROCm tensors. On the CPU torch picks flash wherever it can and math+otherwise, whatever the order says (measured on torch 2.13).++**The flags.** ``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, an exclusive override left the other backends *disabled* process-wide. Every+other model in the process then picks kernels by the leaked flags, and `backend.util.attention` sizes working memory+from them. That is reachable whenever two sessions run under the ``INVOKE_KREA2_SDPA_BACKEND`` override at once.++So windows get a single owner, :func:`sdpa_policy`. The outermost window is the only one that writes the flags; a+window opened while another is open runs under that one, and the flags are restored once, by the window that set+them. The override's choice is fixed for the process, so nested windows ask for what is already in force."""import threadingfrom collections.abc import Iterator, Sequencefrom contextlib import AbstractContextManager, contextmanager+from functools import lru_cache+import torchfrom torch.nn.attention import SDPBackend, sdpa_kernelfrom invokeai.backend.util.logging import InvokeAILoggerlogger = InvokeAILogger.get_logger(__name__)-Policy = tuple[tuple[SDPBackend, ...], bool]--_lock = threading.Lock()+# The process-wide SDPA priority order, ranked ahead of anything else torch lists (OVERRIDEABLE today), which keeps+# torch's relative order behind it. torch's own order is [FLASH, EFFICIENT, MATH, CUDNN, ...]: cuDNN ranks behind the+# always-eligible math kernel, so it is practically never chosen.+#+# Flash first: where the build has it (Linux CUDA) it is the fastest kernel and already what torch's order picks, so+# there this order only changes the calls flash refuses -- any attention mask, such as the regional-prompting blocks+# pass, or heads wider than 256 -- which cuDNN now takes instead of memory-efficient. Measured on the Krea-2 attention+# shape ([1, 48, 4608, 128], bf16), per call:+#+# RTX 4090 / Windows RTX 30-series / Linux+# flash not compiled in 19.74 ms+# cudnn 3.72 ms 21.27 ms+# efficient 5.92 ms 31.45 ms+# math 51.23 ms 168.48 ms+#+# cuDNN second: Windows CUDA builds have no flash, so there cuDNN serves every call it accepts. Denoise time per+# generation on the RTX 4090 under Windows, against torch's order: FLUX.1 -7 % / -17 % (1024 / 2048 px), FLUX.2 Klein+# -7 / -14, Z-Image -7 / -13, Qwen-Image -4 / -14, SDXL +/-0 / -8, LTX-2 video -10, Wan 2.2 5B -18, Wan 2.2 A14B -16,+# Anima about -6 per step at 1024; peak VRAM unchanged. Images at the same seed change slightly, as with any kernel+# swap (bf16 accumulation order).+#+# Every entry is a fallback, never an exclusive choice: the dispatcher skips a kernel that cannot serve a call, so the+# order degrades on its own. ROCm builds have no cuDNN attention, so there it selects exactly what torch's order did.+DEFAULT_SDPA_PRIORITY = (+ SDPBackend.FLASH_ATTENTION,+ SDPBackend.CUDNN_ATTENTION,+ SDPBackend.EFFICIENT_ATTENTION,+ SDPBackend.MATH,+)++# The kernels by the names a user writes: `attention_backend` pins one of them, `INVOKE_KREA2_SDPA_BACKEND` opens an+# exclusive window on one.+SDPA_KERNELS: dict[str, SDPBackend] = {+ "cudnn": SDPBackend.CUDNN_ATTENTION,+ "efficient": SDPBackend.EFFICIENT_ATTENTION,+ "flash": SDPBackend.FLASH_ATTENTION,+ "math": SDPBackend.MATH,+}++# Serialises writes to the priority order: startup, and two GPU workers whose cuDNN calls fail at once.+_order_lock = threading.Lock()++_window_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.+def install_default_sdpa_priority(pinned: SDPBackend | None = None) -> bool:+ """Make :data:`DEFAULT_SDPA_PRIORITY` torch's SDPA priority order for the rest of the process, with `pinned`, when+ given, ranked ahead of it.++ Backends torch lists beyond the ranking keep their relative order behind it, and the per-backend+ enable flags are left alone. Idempotent. Writing the order creates no CUDA context.- 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.+ Uses the private calls ``sdpa_kernel`` itself makes. If a torch release renames, removes or changes+ them, this logs that, leaves torch's own order rather than stopping the server, and returns False."""- return _foreign_entries+ ranking = DEFAULT_SDPA_PRIORITY if pinned is None else (pinned, *(b for b in DEFAULT_SDPA_PRIORITY if b != pinned))+ with _order_lock:+ try:+ ranked = [int(backend) for backend in ranking]+ order = torch._C._get_sdp_priority_order()+ torch._C._set_sdp_priority_order(ranked + [backend for backend in order if backend not in ranked])+ except Exception as error:+ logger.warning(+ f"Could not set the SDPA kernel priority order ({error!r}): torch's private priority-order API "+ "(torch._C._get_sdp_priority_order / _set_sdp_priority_order) is missing or has changed in this "+ "release. Attention keeps PyTorch's own order, which practically never picks the cuDNN kernel"+ + (", and attention_backend cannot rank a kernel first." if pinned is not None else ".")+ )+ return False+ return True+++def demote_cudnn_attention() -> bool:+ """Rank cuDNN directly behind math for the rest of the process, if it ranks ahead of math now.++ Returns whether this call moved it, so of two GPU workers whose cuDNN calls fail at once exactly one+ does. The enable flags are left alone: an exclusive window restores them on exit, and the order is+ what is demoted. Nothing ranks cuDNN ahead again afterwards.+ """+ with _order_lock:+ try:+ order = list(torch._C._get_sdp_priority_order())+ cudnn, math = int(SDPBackend.CUDNN_ATTENTION), int(SDPBackend.MATH)+ if order.index(cudnn) > order.index(math):+ return False+ order.remove(cudnn)+ order.insert(order.index(math) + 1, cudnn)+ torch._C._set_sdp_priority_order(order)+ except Exception:+ return False+ return True+++def cudnn_attention_demoted() -> bool:+ """Whether cuDNN ranks behind math now, as :func:`demote_cudnn_attention` leaves it."""+ try:+ order = list(torch._C._get_sdp_priority_order())+ return order.index(int(SDPBackend.CUDNN_ATTENTION)) > order.index(int(SDPBackend.MATH))+ except Exception:+ return False-@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.+def sdpa_priority_order() -> list[SDPBackend] | None:+ """torch's SDPA priority order as it stands now, or None where this torch cannot report it.++ Read per attention call where another kernel than flash ranks first (Krea-2's grouped-query decision) and inside+ an exclusive window (`backend.util.attention.sdpa_backend_choice`). torch's getter costs 0.07us, converting its+ answer to `SDPBackend`s 2.1us (measured on CPU), so the conversion is remembered for each order torch reports.+ """+ try:+ return list(_as_backends(tuple(torch._C._get_sdp_priority_order())))+ except Exception:+ return None+- 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.+def sdpa_flash_ranks_first() -> bool | None:+ """Whether flash leads torch's SDPA priority order now, as it does unless `attention_backend` pins another kernel;+ None where this torch cannot report its order.- Yields whether this window owns the globals, so a caller whose correctness depends on its policy- actually applying can tell.+ Reads the first slot only, as an int: 0.08us, where reading the order and comparing an `SDPBackend` costs 0.65us+ (measured on CPU). Krea-2 asks it on every attention call."""- global _depth, _window, _policy, _foreign_entries+ try:+ return torch._C._get_sdp_priority_order()[0] == _FLASH+ except Exception:+ return None+++_FLASH = int(SDPBackend.FLASH_ATTENTION)+++@lru_cache(maxsize=8)+def _as_backends(order: tuple[int, ...]) -> tuple[SDPBackend, ...]:+ return tuple(SDPBackend(backend) for backend in order)- requested = (tuple(backends), set_priority)- collision: tuple[Policy, Policy] | None = None- with _lock:- owned = _depth == 0- if owned:++def describe_sdpa_priority_order() -> str:+ """torch's SDPA priority order for a log line, "unknown" where this torch cannot report it.++ Each backend is named once, where it first appears: torch 2.7 fills the last of its five slots with MATH again. A+ repeat is never reached, and naming it would read as a kernel tried twice.+ """+ order = sdpa_priority_order()+ return "unknown" if order is None else " > ".join(dict.fromkeys(backend.name for backend in order))+++@contextmanager+def sdpa_policy(backends: Sequence[SDPBackend]) -> Iterator[None]:+ """Run the block with only `backends` enabled, unless another window is already open.++ A drop-in for ``sdpa_kernel(list(backends))`` that is safe to open from several threads: entering while another+ window is open runs the block under that one, and the flags are restored once, by the window that set them. Only+ the flags: the priority order is the process's, not a window's.+ """+ global _depth, _window++ with _window_lock:+ if _depth == 0:# 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 = sdpa_kernel(list(backends))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)+ _window = window_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+ yieldfinally:- with _lock:+ with _window_lock:_depth -= 1if _depth == 0 and _window is not None:- window, _window, _policy = _window, None, None+ window, _window = _window, Nonewindow.__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/frontend/api/openapi.json b/invokeai/frontend/api/openapi.jsonindex 47ee8d7349..0fa9363672 100644--- a/invokeai/frontend/api/openapi.json+++ b/invokeai/frontend/api/openapi.json@@ -63238,9 +63238,9 @@},"attention_backend": {"type": "string",- "enum": ["auto", "sage"],+ "enum": ["auto", "sage", "cudnn", "flash", "efficient", "math"],"title": "Attention Backend",- "description": "Attention kernel for the attention inside diffusion models. `auto` lets PyTorch choose among its exact SDPA kernels and never selects a quantized one. `sage` uses SageAttention 2 for the models listed in the SageAttention docs: faster, most at high resolutions and for video, but quantized, so images differ slightly from `auto` at the same seed. SageAttention is installed separately and needs an NVIDIA GPU with compute capability 8.0 or newer; masked attention, text encoders and VAEs keep PyTorch SDPA.",+ "description": "Attention kernel for the attention inside diffusion models. `auto` uses PyTorch's exact SDPA kernels ranked flash, cuDNN, memory-efficient, math, taking the first one the GPU and build support for each call; it never selects a quantized one. `sage` uses SageAttention 2 for the models listed in the SageAttention docs: faster, most at high resolutions and for video, but quantized, so images differ slightly from `auto` at the same seed. SageAttention is installed separately and needs an NVIDIA GPU with compute capability 8.0 or newer; masked attention, text encoders and VAEs keep PyTorch SDPA. `cudnn`, `flash`, `efficient` and `math` rank that PyTorch kernel first for all attention on CUDA and ROCm GPUs, ahead of the `auto` order. That is never exclusive: a call the kernel cannot serve runs on the next kernel, and the log reports that once per node type and reason (not for the PiD decoder, whose attention is ranked the same but not reported). `math` materializes the full attention score matrix, so it is slow and needs much more memory, which the working-memory estimates of most model families do not reserve, so generations can run out of memory; it is meant for debugging. Images can differ slightly between kernels.","default": "auto"},"force_tiled_decode": {@@ -63573,7 +63573,7 @@"additionalProperties": false,"type": "object","title": "InvokeAIAppConfig",- "description": "Invoke's global app configuration.\n\nTypically, you won't need to interact with this class directly. Instead, use the `get_config` function from `invokeai.app.services.config` to get a singleton config object.\n\nAttributes:\n host: IP address to bind to. Use `0.0.0.0` to serve to your local network.\n port: Port to bind to.\n allow_origins: Allowed CORS origins.\n allow_credentials: Allow CORS credentials.\n allow_methods: Methods allowed for CORS.\n allow_headers: Headers allowed for CORS.\n ssl_certfile: SSL certificate file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n ssl_keyfile: SSL key file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n show_donation_link: Show the Donate to InvokeAI link in the frontend menus.\n log_tokenization: Enable logging of parsed prompt tokens.\n patchmatch: Enable patchmatch inpaint code.\n models_dir: Path to the models directory.\n convert_cache_dir: Path to the converted models cache directory (DEPRECATED, but do not delete because it is needed for migration from previous versions).\n download_cache_dir: Path to the directory that contains dynamically downloaded models.\n legacy_conf_dir: Path to directory of legacy checkpoint config files.\n db_dir: Path to InvokeAI databases directory.\n db_url: URL of a MySQL 8.4+ or MariaDB 10.11+ database to use instead of the SQLite database in `db_dir`, e.g. `mariadb+pymysql://invokeai:[email protected]/invokeai`. Needs the `mysql` extra. One InvokeAI process uses a database at a time. Read at startup only.\n db_synchronous: SQLite durability setting. `full`, the default and what InvokeAI has always used, flushes every commit to disk. `normal` acknowledges commits without waiting for that flush - measured at roughly 12x shorter commits on an SSD - and cannot corrupt the database under WAL, which is why it is refused, with a warning, when WAL is unavailable for the database file. What `normal` gives up is the most recent transactions on a power loss or OS crash: a just-written image record or queue status, not the image file itself.<br>Valid values: `full`, `normal`\n outputs_dir: Path to directory for outputs.\n image_subfolder_strategy: Strategy for organizing images into subfolders. 'flat' stores all images in a single folder. 'date' organizes by YYYY/MM/DD. 'type' organizes by image category. 'hash' uses first 2 characters of UUID for filesystem performance.<br>Valid values: `flat`, `date`, `type`, `hash`\n custom_nodes_dir: Path to directory for custom nodes.\n style_presets_dir: Path to directory for style presets.\n workflow_thumbnails_dir: Path to directory for workflow thumbnails.\n log_handlers: Log handler. Valid options are \"console\", \"file=<path>\", \"syslog=path|address:host:port\", \"http=<url>\".\n log_format: Log format. Use \"plain\" for text-only, \"color\" for colorized output, \"legacy\" for 2.3-style logging and \"syslog\" for syslog-style.<br>Valid values: `plain`, `color`, `syslog`, `legacy`\n log_level: Emit logging messages at this level or higher.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n log_sql: Log SQL queries. `log_level` must be `debug` for this to do anything. Extremely verbose.\n log_level_network: Log level for network-related messages. 'info' and 'debug' are very verbose.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n use_memory_db: Use in-memory database. Useful for development.\n dev_reload: Automatically reload when Python sources are changed. Does not reload node definitions.\n profile_graphs: Enable graph profiling using `cProfile`.\n profile_prefix: An optional prefix for profile output files.\n profiles_dir: Path to profiles output directory.\n max_cache_ram_gb: The maximum amount of CPU RAM to use for model caching in GB. If unset, the limit will be configured based on the available RAM. In most cases, it is recommended to leave this unset.\n max_cache_vram_gb: The amount of VRAM to use for model caching in GB. If unset, the limit will be configured based on the available VRAM and the device_working_mem_gb. In most cases, it is recommended to leave this unset.\n reserve_vram_gb: The amount of VRAM (in GB) to subtract from the model cache's available memory budget. Defaults to 0.\n log_memory_usage: If True, a memory snapshot will be captured before and after every model cache operation, and the result will be logged (at debug level). There is a time cost to capturing the memory snapshots, so it is recommended to only enable this feature if you are actively inspecting the model cache's behaviour.\n model_cache_keep_alive_min: How long to keep models in cache after last use, in minutes. A value of 0 (the default) means models are kept in cache indefinitely. If no model generations occur within the timeout period, the model cache is cleared using the same logic as the 'Clear Model Cache' button.\n device_working_mem_gb: The amount of working memory to keep available on the compute device (in GB). Has no effect if running on CPU. If you are experiencing OOM errors, try increasing this value.\n enable_partial_loading: Enable partial loading of models. This enables models to run with reduced VRAM requirements (at the cost of slower speed) by streaming the model from RAM to VRAM as its used. In some edge cases, partial loading can cause models to run more slowly if they were previously being fully loaded into VRAM.\n keep_ram_copy_of_weights: Whether to keep a full RAM copy of a model's weights when the model is loaded in VRAM. Keeping a RAM copy increases average RAM usage, but speeds up model switching and LoRA patching (assuming there is sufficient RAM). Set this to False if RAM pressure is consistently high.\n offload_on_architecture_switch: When a session uses main models of another architecture than the previous one on the same GPU, move every model it does not use from VRAM to RAM before it runs. Models both sessions use stay. Switching back reloads the moved models from RAM, which costs a few seconds per switch when both architectures would have fit in VRAM together; turn this off if you alternate between such models.\n clear_vram_after_session: After every queue item (each image of a batch), move the models held in VRAM to RAM and return the freed memory to the GPU driver. The models stay cached in RAM; the next item reloads them from there, which costs a few seconds (more with keep_ram_copy_of_weights off). Changes nothing where VRAM is system memory (CPU, MPS, integrated GPUs). Turn this on if a generation that runs fine the first time runs out of memory, or slows down sharply because the GPU spills into shared memory, when it is repeated.\n fp8_compute: Keep ComfyUI 'scaled fp8' checkpoints quantized instead of dequantizing them at load, and run their matmuls on the fp8 tensor cores (requires an Ada/SM 8.9 or newer NVIDIA GPU, or a ROCm GPU that passes an fp8 matmul probe; falls back automatically otherwise). Speeds up denoising and keeps the transformer at fp8 size - FP8 Storage alone also keeps it at that size, without the speedup - but quantizes activations as well, so images will differ from previous versions at the same seed. Reproducibility also requires the model to be FULLY resident in VRAM: a layer whose weights are still in RAM falls back to the dequantized path, and since which layers are resident shifts from run to run, the same seed then yields visibly different images. For repeatable output, ensure the model loads at 100% (e.g. enable_partial_loading=false with enough free VRAM).\n fp8_compute_full_precision_hints: Honor the per-layer 'full_precision_matrix_mult' flags that some scaled-fp8 checkpoints ship. Those layers then dequantize on every forward instead of using the fp8 tensor cores, which can cost a large part of the fp8_compute speedup - on checkpoints that mark many layers, most of it. Set to false to run every quantized layer on the fp8 tensor cores, ignoring the producer's instruction; faster, but the marked layers were flagged as numerically sensitive, so quality may suffer. Only has an effect when fp8_compute is enabled.\n int8_compute: Run the matmuls of ComfyUI int8 builds quantized with convrot ('int8_tensorwise' with 'convrot') on the int8 tensor cores instead of dequantizing their weights on every forward (requires an NVIDIA GPU with compute capability 8.0 or newer and Triton; falls back automatically otherwise, including on AMD, Apple and Intel GPUs and the CPU). Speeds up denoising with these builds, but quantizes activations per token as well, so images will differ from the dequantized path at the same seed. The kernels are tuned once per layer shape and token-count bucket: about 35 seconds for the first image after enabling it, about 1-5 seconds for a later size in a new token-count bucket, cached on disk across restarts.\n ram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_ram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n vram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_vram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n lazy_offload: DEPRECATED: This setting is no longer used. Lazy-offloading is enabled by default. This config setting will be removed once the new model cache behavior is stable.\n pytorch_cuda_alloc_conf: Configure the Torch CUDA memory allocator. This will impact peak reserved VRAM usage and performance. Setting to \"backend:cudaMallocAsync\" works well on many systems. The optimal configuration is highly dependent on the system configuration (device type, VRAM, CUDA driver version, etc.), so must be tuned experimentally. Unset on a ROCm build of PyTorch on Windows, \"expandable_segments:True\" is used.\n device: Preferred execution device. `auto` will choose the device depending on the hardware platform and the installed torch capabilities.<br>Valid values: `auto`, `cpu`, `cuda`, `mps`, `xpu`, `cuda:N`, `xpu:N` (where N is a device number)\n precision: Floating point precision. `float16` will consume half the memory of `float32` but produce slightly lower-quality images. The `auto` setting will guess the proper precision based on your video card and operating system.<br>Valid values: `auto`, `float16`, `bfloat16`, `float32`\n rocm_aotriton_experimental: Use AOTriton's fused (flash and memory-efficient) attention kernels on AMD GPUs that PyTorch marks experimental for them, such as the RX 7600/7700/7800 series, Ryzen AI 300/Max and the RX 9060 series, by setting TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL. Without them, attention on those GPUs runs on the slower math kernel, which also needs far more memory. `auto` turns them on only with a ROCm 10 build of PyTorch, and only when every GPU used for generation is one they were measured correct on (so far gfx1200, the RX 9060 series); `on` and `off` decide for any build and GPU. A TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL value already set in the environment takes precedence. Has no effect on other GPUs.<br>Valid values: `auto`, `on`, `off`\n sequential_guidance: Whether to calculate guidance in serial instead of in parallel, lowering memory requirements.\n noise_dtype: The dtype seeded noise is drawn in for SD1.5/SDXL, SD3, FLUX.1, FLUX.2, CogView4 and the Z-Image seed variance enhancer. `float32` draws the same noise on every platform. `float16` is the half-precision draw of earlier versions: on macOS it keeps the images your seeds gave before this update; on Windows and Linux both values give (nearly) the same images, and images made before the update cannot be reproduced there.<br>Valid values: `float32`, `float16`\n wan_memory_optimization: Enable experimental Wan memory optimizations at the cost of slower generation.\n pid_memory_optimization: Enable experimental PiD decode memory optimizations. Roughly halves the peak activation memory of a PiD decode; in exchange the decoded image changes slightly, because neither the chunked pixel pathway nor the float32 sampler intermediates are bit-exact with the default path.\n tiny_autoencoder_previews: Render denoising previews with an installed Tiny AutoEncoder instead of the linear latent projection. Install the matching Tiny AutoEncoder starter model; families without one keep linear previews. A preview costs about 25 ms and 0.65 GB of transient VRAM on an RTX 4090; not recommended on CPU-only installs, where one takes about 2 s.\n attention_type: Attention type.<br>Valid values: `auto`, `normal`, `xformers`, `sliced`, `torch-sdp`\n attention_slice_size: Slice size, valid when attention_type==\"sliced\".<br>Valid values: `auto`, `balanced`, `max`, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`\n attention_backend: Attention kernel for the attention inside diffusion models. `auto` lets PyTorch choose among its exact SDPA kernels and never selects a quantized one. `sage` uses SageAttention 2 for the models listed in the SageAttention docs: faster, most at high resolutions and for video, but quantized, so images differ slightly from `auto` at the same seed. SageAttention is installed separately and needs an NVIDIA GPU with compute capability 8.0 or newer; masked attention, text encoders and VAEs keep PyTorch SDPA.<br>Valid values: `auto`, `sage`\n force_tiled_decode: Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty). A tiled decode is not pixel-identical to a single-pass one: a VAE decoder normalises and attends over the whole image, so the difference is spread across it rather than confined to the tile seams. Also tiles the encode. Read by the SD1.5/SDXL, FLUX.1, FLUX.2, Z-Image, Qwen-Image and Qwen-Image-2.1 VAE nodes, the Anima encode, the Z-Image control encode and the Krea-2 style reference; other model families ignore it.\n auto_tiled_decode: Decode large images in tiles when an untiled decode's estimated working memory would take most of the GPU's memory (FLUX.1, FLUX.2, Z-Image, Qwen-Image, Qwen-Image-2.1, Krea-2 and Wan decodes, and Qwen-Image-2.1 encodes). Turn off to decode untiled unless tiling is requested; the FLUX.1, FLUX.2 and Z-Image decodes then still retry tiled after running out of memory. Anima keeps tiling a decode too large for its GPU either way, because tiling is what makes that case fast there.\n pil_compress_level: The compress_level setting of PIL.Image.save(), used for PNG encoding. All settings are lossless. 0 = no compression, 1 = fastest with slightly larger filesize, 9 = slowest with smallest filesize. 1 is typically the best setting.\n max_queue_size: Maximum number of items in the session queue.\n session_queue_mode: Session queue mode. Use 'FIFO' for traditional first-in-first-out, or 'round_robin' to serve each user's jobs in turn. In single-user mode, FIFO is always used regardless of this setting.<br>Valid values: `FIFO`, `round_robin`\n clear_queue_on_startup: Empties session queue on startup. If true, disables `max_queue_history`.\n max_queue_history: Keep the last N completed, failed, and canceled queue items. Older items are deleted on startup. Set to 0 to prune all terminal items. Ignored if `clear_queue_on_startup` is true.\n allow_nodes: List of nodes to allow. Omit to allow all.\n deny_nodes: List of nodes to deny. Omit to deny none.\n node_cache_size: How many cached nodes to keep in memory.\n hashing_algorithm: Model hashing algorthim for model installs. 'blake3_multi' is best for SSDs. 'blake3_single' is best for spinning disk HDDs. 'random' disables hashing, instead assigning a UUID to models. Useful when using a memory db to reduce model installation time, or if you don't care about storing stable hashes for models. Alternatively, any other hashlib algorithm is accepted, though these are not nearly as performant as blake3.<br>Valid values: `blake3_multi`, `blake3_single`, `random`, `md5`, `sha1`, `sha224`, `sha256`, `sha384`, `sha512`, `blake2b`, `blake2s`, `sha3_224`, `sha3_256`, `sha3_384`, `sha3_512`, `shake_128`, `shake_256`\n remote_api_tokens: List of regular expression and token pairs used when downloading models from URLs. The download URL is tested against the regex, and if it matches, the token is provided in as a Bearer token.\n scan_models_on_startup: Scan the models directory on startup, registering orphaned models. This is typically only used in conjunction with `use_memory_db` for testing purposes.\n allow_private_download_urls: Allow the download queue to fetch from loopback, link-local and private-network addresses. Disabled by default so that a download URL cannot be used to reach services that are only reachable from the server. Enable this only if you install models from a mirror on your own network.\n download_proxy: Optional HTTP proxy for model downloads. The proxy must enforce the public-address policy because proxy-side DNS cannot be checked by InvokeAI.\n unsafe_disable_picklescan: UNSAFE. Disable the picklescan security check during model installation. Recommended only for development and testing purposes. This will allow arbitrary code execution during model installation, so should never be used in production.\n allow_unknown_models: Allow installation of models that we are unable to identify. If enabled, models will be marked as `unknown` in the database, and will not have any metadata associated with them. If disabled, unknown models will be rejected during installation.\n multiuser: Enable multiuser support. When disabled, the application runs in single-user mode using a default system account with administrator privileges. When enabled, requires user authentication and authorization.\n strict_password_checking: Enforce strict password requirements. When True, passwords must contain uppercase, lowercase, and numbers. When False (default), any password is accepted but its strength (weak/moderate/strong) is reported to the user.\n image_index_enabled: Maintain a semantic embedding index of gallery images and videos, used by the image map and semantic search features.\n image_index_model: Name of the installed CLIP Vision or SigLIP model used to embed gallery images and video thumbnails. Changing the model discards embeddings computed by the previous model.\n image_index_device: Set to `cpu` to compute image embeddings on the CPU with a service-local copy of the model - avoids VRAM use and lets indexing run during generations. Any other value is ignored: embeddings otherwise run on the model cache's device, pausing while generations are in progress.\n image_index_batch_size: Number of gallery items embedded per batch by the image index worker.\n external_alibabacloud_api_key: API key for Alibaba Cloud DashScope image generation.\n external_alibabacloud_base_url: Base URL override for Alibaba Cloud DashScope image generation.\n external_atlascloud_api_key: API key for Atlas Cloud image generation.\n external_atlascloud_base_url: Base URL override for Atlas Cloud image generation.\n external_gemini_api_key: API key for Gemini image generation.\n external_openai_api_key: API key for OpenAI image generation.\n external_gemini_base_url: Base URL override for Gemini image generation.\n external_openai_base_url: Base URL override for OpenAI image generation.\n external_seedream_api_key: API key for Seedream image generation.\n external_seedream_base_url: Base URL override for Seedream image generation.\n base_url: Public base path when running behind a reverse proxy under a sub-path, e.g. `/invoke`. Set only when the proxy PRESERVES the sub-path (the backend receives `/invoke/api/...`). Leave unset when the proxy strips the sub-path or when serving at the domain root.\n forwarded_allow_ips: Comma-separated list of IPs (or `*`) allowed to set X-Forwarded-* headers. Set to the reverse proxy's IP. Only used when `base_url` is set.\n http_compression_level: Compression level for gzipped HTTP API responses. 0 disables response compression entirely, 1 is fastest, 9 (the default) is smallest. Compression runs on the event loop and blocks the whole server while it works, and level 9 costs about 5.5x the time of level 1 for 0.4 percentage points of extra compression, so lowering this makes the app noticeably more responsive on large libraries. Set to 0 when a reverse proxy already compresses responses."+ "description": "Invoke's global app configuration.\n\nTypically, you won't need to interact with this class directly. Instead, use the `get_config` function from `invokeai.app.services.config` to get a singleton config object.\n\nAttributes:\n host: IP address to bind to. Use `0.0.0.0` to serve to your local network.\n port: Port to bind to.\n allow_origins: Allowed CORS origins.\n allow_credentials: Allow CORS credentials.\n allow_methods: Methods allowed for CORS.\n allow_headers: Headers allowed for CORS.\n ssl_certfile: SSL certificate file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n ssl_keyfile: SSL key file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n show_donation_link: Show the Donate to InvokeAI link in the frontend menus.\n log_tokenization: Enable logging of parsed prompt tokens.\n patchmatch: Enable patchmatch inpaint code.\n models_dir: Path to the models directory.\n convert_cache_dir: Path to the converted models cache directory (DEPRECATED, but do not delete because it is needed for migration from previous versions).\n download_cache_dir: Path to the directory that contains dynamically downloaded models.\n legacy_conf_dir: Path to directory of legacy checkpoint config files.\n db_dir: Path to InvokeAI databases directory.\n db_url: URL of a MySQL 8.4+ or MariaDB 10.11+ database to use instead of the SQLite database in `db_dir`, e.g. `mariadb+pymysql://invokeai:[email protected]/invokeai`. Needs the `mysql` extra. One InvokeAI process uses a database at a time. Read at startup only.\n db_synchronous: SQLite durability setting. `full`, the default and what InvokeAI has always used, flushes every commit to disk. `normal` acknowledges commits without waiting for that flush - measured at roughly 12x shorter commits on an SSD - and cannot corrupt the database under WAL, which is why it is refused, with a warning, when WAL is unavailable for the database file. What `normal` gives up is the most recent transactions on a power loss or OS crash: a just-written image record or queue status, not the image file itself.<br>Valid values: `full`, `normal`\n outputs_dir: Path to directory for outputs.\n image_subfolder_strategy: Strategy for organizing images into subfolders. 'flat' stores all images in a single folder. 'date' organizes by YYYY/MM/DD. 'type' organizes by image category. 'hash' uses first 2 characters of UUID for filesystem performance.<br>Valid values: `flat`, `date`, `type`, `hash`\n custom_nodes_dir: Path to directory for custom nodes.\n style_presets_dir: Path to directory for style presets.\n workflow_thumbnails_dir: Path to directory for workflow thumbnails.\n log_handlers: Log handler. Valid options are \"console\", \"file=<path>\", \"syslog=path|address:host:port\", \"http=<url>\".\n log_format: Log format. Use \"plain\" for text-only, \"color\" for colorized output, \"legacy\" for 2.3-style logging and \"syslog\" for syslog-style.<br>Valid values: `plain`, `color`, `syslog`, `legacy`\n log_level: Emit logging messages at this level or higher.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n log_sql: Log SQL queries. `log_level` must be `debug` for this to do anything. Extremely verbose.\n log_level_network: Log level for network-related messages. 'info' and 'debug' are very verbose.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n use_memory_db: Use in-memory database. Useful for development.\n dev_reload: Automatically reload when Python sources are changed. Does not reload node definitions.\n profile_graphs: Enable graph profiling using `cProfile`.\n profile_prefix: An optional prefix for profile output files.\n profiles_dir: Path to profiles output directory.\n max_cache_ram_gb: The maximum amount of CPU RAM to use for model caching in GB. If unset, the limit will be configured based on the available RAM. In most cases, it is recommended to leave this unset.\n max_cache_vram_gb: The amount of VRAM to use for model caching in GB. If unset, the limit will be configured based on the available VRAM and the device_working_mem_gb. In most cases, it is recommended to leave this unset.\n reserve_vram_gb: The amount of VRAM (in GB) to subtract from the model cache's available memory budget. Defaults to 0.\n log_memory_usage: If True, a memory snapshot will be captured before and after every model cache operation, and the result will be logged (at debug level). There is a time cost to capturing the memory snapshots, so it is recommended to only enable this feature if you are actively inspecting the model cache's behaviour.\n model_cache_keep_alive_min: How long to keep models in cache after last use, in minutes. A value of 0 (the default) means models are kept in cache indefinitely. If no model generations occur within the timeout period, the model cache is cleared using the same logic as the 'Clear Model Cache' button.\n device_working_mem_gb: The amount of working memory to keep available on the compute device (in GB). Has no effect if running on CPU. If you are experiencing OOM errors, try increasing this value.\n enable_partial_loading: Enable partial loading of models. This enables models to run with reduced VRAM requirements (at the cost of slower speed) by streaming the model from RAM to VRAM as its used. In some edge cases, partial loading can cause models to run more slowly if they were previously being fully loaded into VRAM.\n keep_ram_copy_of_weights: Whether to keep a full RAM copy of a model's weights when the model is loaded in VRAM. Keeping a RAM copy increases average RAM usage, but speeds up model switching and LoRA patching (assuming there is sufficient RAM). Set this to False if RAM pressure is consistently high.\n offload_on_architecture_switch: When a session uses main models of another architecture than the previous one on the same GPU, move every model it does not use from VRAM to RAM before it runs. Models both sessions use stay. Switching back reloads the moved models from RAM, which costs a few seconds per switch when both architectures would have fit in VRAM together; turn this off if you alternate between such models.\n clear_vram_after_session: After every queue item (each image of a batch), move the models held in VRAM to RAM and return the freed memory to the GPU driver. The models stay cached in RAM; the next item reloads them from there, which costs a few seconds (more with keep_ram_copy_of_weights off). Changes nothing where VRAM is system memory (CPU, MPS, integrated GPUs). Turn this on if a generation that runs fine the first time runs out of memory, or slows down sharply because the GPU spills into shared memory, when it is repeated.\n fp8_compute: Keep ComfyUI 'scaled fp8' checkpoints quantized instead of dequantizing them at load, and run their matmuls on the fp8 tensor cores (requires an Ada/SM 8.9 or newer NVIDIA GPU, or a ROCm GPU that passes an fp8 matmul probe; falls back automatically otherwise). Speeds up denoising and keeps the transformer at fp8 size - FP8 Storage alone also keeps it at that size, without the speedup - but quantizes activations as well, so images will differ from previous versions at the same seed. Reproducibility also requires the model to be FULLY resident in VRAM: a layer whose weights are still in RAM falls back to the dequantized path, and since which layers are resident shifts from run to run, the same seed then yields visibly different images. For repeatable output, ensure the model loads at 100% (e.g. enable_partial_loading=false with enough free VRAM).\n fp8_compute_full_precision_hints: Honor the per-layer 'full_precision_matrix_mult' flags that some scaled-fp8 checkpoints ship. Those layers then dequantize on every forward instead of using the fp8 tensor cores, which can cost a large part of the fp8_compute speedup - on checkpoints that mark many layers, most of it. Set to false to run every quantized layer on the fp8 tensor cores, ignoring the producer's instruction; faster, but the marked layers were flagged as numerically sensitive, so quality may suffer. Only has an effect when fp8_compute is enabled.\n int8_compute: Run the matmuls of ComfyUI int8 builds quantized with convrot ('int8_tensorwise' with 'convrot') on the int8 tensor cores instead of dequantizing their weights on every forward (requires an NVIDIA GPU with compute capability 8.0 or newer and Triton; falls back automatically otherwise, including on AMD, Apple and Intel GPUs and the CPU). Speeds up denoising with these builds, but quantizes activations per token as well, so images will differ from the dequantized path at the same seed. The kernels are tuned once per layer shape and token-count bucket: about 35 seconds for the first image after enabling it, about 1-5 seconds for a later size in a new token-count bucket, cached on disk across restarts.\n ram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_ram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n vram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_vram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n lazy_offload: DEPRECATED: This setting is no longer used. Lazy-offloading is enabled by default. This config setting will be removed once the new model cache behavior is stable.\n pytorch_cuda_alloc_conf: Configure the Torch CUDA memory allocator. This will impact peak reserved VRAM usage and performance. Setting to \"backend:cudaMallocAsync\" works well on many systems. The optimal configuration is highly dependent on the system configuration (device type, VRAM, CUDA driver version, etc.), so must be tuned experimentally. Unset on a ROCm build of PyTorch on Windows, \"expandable_segments:True\" is used.\n device: Preferred execution device. `auto` will choose the device depending on the hardware platform and the installed torch capabilities.<br>Valid values: `auto`, `cpu`, `cuda`, `mps`, `xpu`, `cuda:N`, `xpu:N` (where N is a device number)\n precision: Floating point precision. `float16` will consume half the memory of `float32` but produce slightly lower-quality images. The `auto` setting will guess the proper precision based on your video card and operating system.<br>Valid values: `auto`, `float16`, `bfloat16`, `float32`\n rocm_aotriton_experimental: Use AOTriton's fused (flash and memory-efficient) attention kernels on AMD GPUs that PyTorch marks experimental for them, such as the RX 7600/7700/7800 series, Ryzen AI 300/Max and the RX 9060 series, by setting TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL. Without them, attention on those GPUs runs on the slower math kernel, which also needs far more memory. `auto` turns them on only with a ROCm 10 build of PyTorch, and only when every GPU used for generation is one they were measured correct on (so far gfx1200, the RX 9060 series); `on` and `off` decide for any build and GPU. A TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL value already set in the environment takes precedence. Has no effect on other GPUs.<br>Valid values: `auto`, `on`, `off`\n sequential_guidance: Whether to calculate guidance in serial instead of in parallel, lowering memory requirements.\n noise_dtype: The dtype seeded noise is drawn in for SD1.5/SDXL, SD3, FLUX.1, FLUX.2, CogView4 and the Z-Image seed variance enhancer. `float32` draws the same noise on every platform. `float16` is the half-precision draw of earlier versions: on macOS it keeps the images your seeds gave before this update; on Windows and Linux both values give (nearly) the same images, and images made before the update cannot be reproduced there.<br>Valid values: `float32`, `float16`\n wan_memory_optimization: Enable experimental Wan memory optimizations at the cost of slower generation.\n pid_memory_optimization: Enable experimental PiD decode memory optimizations. Roughly halves the peak activation memory of a PiD decode; in exchange the decoded image changes slightly, because neither the chunked pixel pathway nor the float32 sampler intermediates are bit-exact with the default path.\n tiny_autoencoder_previews: Render denoising previews with an installed Tiny AutoEncoder instead of the linear latent projection. Install the matching Tiny AutoEncoder starter model; families without one keep linear previews. A preview costs about 25 ms and 0.65 GB of transient VRAM on an RTX 4090; not recommended on CPU-only installs, where one takes about 2 s.\n attention_type: Attention type.<br>Valid values: `auto`, `normal`, `xformers`, `sliced`, `torch-sdp`\n attention_slice_size: Slice size, valid when attention_type==\"sliced\".<br>Valid values: `auto`, `balanced`, `max`, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`\n attention_backend: Attention kernel for the attention inside diffusion models. `auto` uses PyTorch's exact SDPA kernels ranked flash, cuDNN, memory-efficient, math, taking the first one the GPU and build support for each call; it never selects a quantized one. `sage` uses SageAttention 2 for the models listed in the SageAttention docs: faster, most at high resolutions and for video, but quantized, so images differ slightly from `auto` at the same seed. SageAttention is installed separately and needs an NVIDIA GPU with compute capability 8.0 or newer; masked attention, text encoders and VAEs keep PyTorch SDPA. `cudnn`, `flash`, `efficient` and `math` rank that PyTorch kernel first for all attention on CUDA and ROCm GPUs, ahead of the `auto` order. That is never exclusive: a call the kernel cannot serve runs on the next kernel, and the log reports that once per node type and reason (not for the PiD decoder, whose attention is ranked the same but not reported). `math` materializes the full attention score matrix, so it is slow and needs much more memory, which the working-memory estimates of most model families do not reserve, so generations can run out of memory; it is meant for debugging. Images can differ slightly between kernels.<br>Valid values: `auto`, `sage`, `cudnn`, `flash`, `efficient`, `math`\n force_tiled_decode: Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty). A tiled decode is not pixel-identical to a single-pass one: a VAE decoder normalises and attends over the whole image, so the difference is spread across it rather than confined to the tile seams. Also tiles the encode. Read by the SD1.5/SDXL, FLUX.1, FLUX.2, Z-Image, Qwen-Image and Qwen-Image-2.1 VAE nodes, the Anima encode, the Z-Image control encode and the Krea-2 style reference; other model families ignore it.\n auto_tiled_decode: Decode large images in tiles when an untiled decode's estimated working memory would take most of the GPU's memory (FLUX.1, FLUX.2, Z-Image, Qwen-Image, Qwen-Image-2.1, Krea-2 and Wan decodes, and Qwen-Image-2.1 encodes). Turn off to decode untiled unless tiling is requested; the FLUX.1, FLUX.2 and Z-Image decodes then still retry tiled after running out of memory. Anima keeps tiling a decode too large for its GPU either way, because tiling is what makes that case fast there.\n pil_compress_level: The compress_level setting of PIL.Image.save(), used for PNG encoding. All settings are lossless. 0 = no compression, 1 = fastest with slightly larger filesize, 9 = slowest with smallest filesize. 1 is typically the best setting.\n max_queue_size: Maximum number of items in the session queue.\n session_queue_mode: Session queue mode. Use 'FIFO' for traditional first-in-first-out, or 'round_robin' to serve each user's jobs in turn. In single-user mode, FIFO is always used regardless of this setting.<br>Valid values: `FIFO`, `round_robin`\n clear_queue_on_startup: Empties session queue on startup. If true, disables `max_queue_history`.\n max_queue_history: Keep the last N completed, failed, and canceled queue items. Older items are deleted on startup. Set to 0 to prune all terminal items. Ignored if `clear_queue_on_startup` is true.\n allow_nodes: List of nodes to allow. Omit to allow all.\n deny_nodes: List of nodes to deny. Omit to deny none.\n node_cache_size: How many cached nodes to keep in memory.\n hashing_algorithm: Model hashing algorthim for model installs. 'blake3_multi' is best for SSDs. 'blake3_single' is best for spinning disk HDDs. 'random' disables hashing, instead assigning a UUID to models. Useful when using a memory db to reduce model installation time, or if you don't care about storing stable hashes for models. Alternatively, any other hashlib algorithm is accepted, though these are not nearly as performant as blake3.<br>Valid values: `blake3_multi`, `blake3_single`, `random`, `md5`, `sha1`, `sha224`, `sha256`, `sha384`, `sha512`, `blake2b`, `blake2s`, `sha3_224`, `sha3_256`, `sha3_384`, `sha3_512`, `shake_128`, `shake_256`\n remote_api_tokens: List of regular expression and token pairs used when downloading models from URLs. The download URL is tested against the regex, and if it matches, the token is provided in as a Bearer token.\n scan_models_on_startup: Scan the models directory on startup, registering orphaned models. This is typically only used in conjunction with `use_memory_db` for testing purposes.\n allow_private_download_urls: Allow the download queue to fetch from loopback, link-local and private-network addresses. Disabled by default so that a download URL cannot be used to reach services that are only reachable from the server. Enable this only if you install models from a mirror on your own network.\n download_proxy: Optional HTTP proxy for model downloads. The proxy must enforce the public-address policy because proxy-side DNS cannot be checked by InvokeAI.\n unsafe_disable_picklescan: UNSAFE. Disable the picklescan security check during model installation. Recommended only for development and testing purposes. This will allow arbitrary code execution during model installation, so should never be used in production.\n allow_unknown_models: Allow installation of models that we are unable to identify. If enabled, models will be marked as `unknown` in the database, and will not have any metadata associated with them. If disabled, unknown models will be rejected during installation.\n multiuser: Enable multiuser support. When disabled, the application runs in single-user mode using a default system account with administrator privileges. When enabled, requires user authentication and authorization.\n strict_password_checking: Enforce strict password requirements. When True, passwords must contain uppercase, lowercase, and numbers. When False (default), any password is accepted but its strength (weak/moderate/strong) is reported to the user.\n image_index_enabled: Maintain a semantic embedding index of gallery images and videos, used by the image map and semantic search features.\n image_index_model: Name of the installed CLIP Vision or SigLIP model used to embed gallery images and video thumbnails. Changing the model discards embeddings computed by the previous model.\n image_index_device: Set to `cpu` to compute image embeddings on the CPU with a service-local copy of the model - avoids VRAM use and lets indexing run during generations. Any other value is ignored: embeddings otherwise run on the model cache's device, pausing while generations are in progress.\n image_index_batch_size: Number of gallery items embedded per batch by the image index worker.\n external_alibabacloud_api_key: API key for Alibaba Cloud DashScope image generation.\n external_alibabacloud_base_url: Base URL override for Alibaba Cloud DashScope image generation.\n external_atlascloud_api_key: API key for Atlas Cloud image generation.\n external_atlascloud_base_url: Base URL override for Atlas Cloud image generation.\n external_gemini_api_key: API key for Gemini image generation.\n external_openai_api_key: API key for OpenAI image generation.\n external_gemini_base_url: Base URL override for Gemini image generation.\n external_openai_base_url: Base URL override for OpenAI image generation.\n external_seedream_api_key: API key for Seedream image generation.\n external_seedream_base_url: Base URL override for Seedream image generation.\n base_url: Public base path when running behind a reverse proxy under a sub-path, e.g. `/invoke`. Set only when the proxy PRESERVES the sub-path (the backend receives `/invoke/api/...`). Leave unset when the proxy strips the sub-path or when serving at the domain root.\n forwarded_allow_ips: Comma-separated list of IPs (or `*`) allowed to set X-Forwarded-* headers. Set to the reverse proxy's IP. Only used when `base_url` is set.\n http_compression_level: Compression level for gzipped HTTP API responses. 0 disables response compression entirely, 1 is fastest, 9 (the default) is smallest. Compression runs on the event loop and blocks the whole server while it works, and level 9 costs about 5.5x the time of level 1 for 0.4 percentage points of extra compression, so lowering this makes the app noticeably more responsive on large libraries. Set to 0 when a reverse proxy already compresses responses."},"InvokeAIAppConfigWithSetFields": {"properties": {diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.tsindex 772d03fbb3..4d39bba208 100644--- a/invokeai/frontend/api/schema.ts+++ b/invokeai/frontend/api/schema.ts@@ -23992,7 +23992,7 @@ export type components = {* tiny_autoencoder_previews: Render denoising previews with an installed Tiny AutoEncoder instead of the linear latent projection. Install the matching Tiny AutoEncoder starter model; families without one keep linear previews. A preview costs about 25 ms and 0.65 GB of transient VRAM on an RTX 4090; not recommended on CPU-only installs, where one takes about 2 s.* attention_type: Attention type.<br>Valid values: `auto`, `normal`, `xformers`, `sliced`, `torch-sdp`* attention_slice_size: Slice size, valid when attention_type=="sliced".<br>Valid values: `auto`, `balanced`, `max`, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`- * attention_backend: Attention kernel for the attention inside diffusion models. `auto` lets PyTorch choose among its exact SDPA kernels and never selects a quantized one. `sage` uses SageAttention 2 for the models listed in the SageAttention docs: faster, most at high resolutions and for video, but quantized, so images differ slightly from `auto` at the same seed. SageAttention is installed separately and needs an NVIDIA GPU with compute capability 8.0 or newer; masked attention, text encoders and VAEs keep PyTorch SDPA.<br>Valid values: `auto`, `sage`+ * attention_backend: Attention kernel for the attention inside diffusion models. `auto` uses PyTorch's exact SDPA kernels ranked flash, cuDNN, memory-efficient, math, taking the first one the GPU and build support for each call; it never selects a quantized one. `sage` uses SageAttention 2 for the models listed in the SageAttention docs: faster, most at high resolutions and for video, but quantized, so images differ slightly from `auto` at the same seed. SageAttention is installed separately and needs an NVIDIA GPU with compute capability 8.0 or newer; masked attention, text encoders and VAEs keep PyTorch SDPA. `cudnn`, `flash`, `efficient` and `math` rank that PyTorch kernel first for all attention on CUDA and ROCm GPUs, ahead of the `auto` order. That is never exclusive: a call the kernel cannot serve runs on the next kernel, and the log reports that once per node type and reason (not for the PiD decoder, whose attention is ranked the same but not reported). `math` materializes the full attention score matrix, so it is slow and needs much more memory, which the working-memory estimates of most model families do not reserve, so generations can run out of memory; it is meant for debugging. Images can differ slightly between kernels.<br>Valid values: `auto`, `sage`, `cudnn`, `flash`, `efficient`, `math`* force_tiled_decode: Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty). A tiled decode is not pixel-identical to a single-pass one: a VAE decoder normalises and attends over the whole image, so the difference is spread across it rather than confined to the tile seams. Also tiles the encode. Read by the SD1.5/SDXL, FLUX.1, FLUX.2, Z-Image, Qwen-Image and Qwen-Image-2.1 VAE nodes, the Anima encode, the Z-Image control encode and the Krea-2 style reference; other model families ignore it.* auto_tiled_decode: Decode large images in tiles when an untiled decode's estimated working memory would take most of the GPU's memory (FLUX.1, FLUX.2, Z-Image, Qwen-Image, Qwen-Image-2.1, Krea-2 and Wan decodes, and Qwen-Image-2.1 encodes). Turn off to decode untiled unless tiling is requested; the FLUX.1, FLUX.2 and Z-Image decodes then still retry tiled after running out of memory. Anima keeps tiling a decode too large for its GPU either way, because tiling is what makes that case fast there.* 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.@@ -24476,11 +24476,11 @@ export type components = {attention_slice_size?: "auto" | "balanced" | "max" | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;/*** Attention Backend- * @description Attention kernel for the attention inside diffusion models. `auto` lets PyTorch choose among its exact SDPA kernels and never selects a quantized one. `sage` uses SageAttention 2 for the models listed in the SageAttention docs: faster, most at high resolutions and for video, but quantized, so images differ slightly from `auto` at the same seed. SageAttention is installed separately and needs an NVIDIA GPU with compute capability 8.0 or newer; masked attention, text encoders and VAEs keep PyTorch SDPA.+ * @description Attention kernel for the attention inside diffusion models. `auto` uses PyTorch's exact SDPA kernels ranked flash, cuDNN, memory-efficient, math, taking the first one the GPU and build support for each call; it never selects a quantized one. `sage` uses SageAttention 2 for the models listed in the SageAttention docs: faster, most at high resolutions and for video, but quantized, so images differ slightly from `auto` at the same seed. SageAttention is installed separately and needs an NVIDIA GPU with compute capability 8.0 or newer; masked attention, text encoders and VAEs keep PyTorch SDPA. `cudnn`, `flash`, `efficient` and `math` rank that PyTorch kernel first for all attention on CUDA and ROCm GPUs, ahead of the `auto` order. That is never exclusive: a call the kernel cannot serve runs on the next kernel, and the log reports that once per node type and reason (not for the PiD decoder, whose attention is ranked the same but not reported). `math` materializes the full attention score matrix, so it is slow and needs much more memory, which the working-memory estimates of most model families do not reserve, so generations can run out of memory; it is meant for debugging. Images can differ slightly between kernels.* @default auto* @enum {string}*/- attention_backend?: "auto" | "sage";+ attention_backend?: "auto" | "sage" | "cudnn" | "flash" | "efficient" | "math";/*** Force Tiled Decode* @description Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty). A tiled decode is not pixel-identical to a single-pass one: a VAE decoder normalises and attends over the whole image, so the difference is spread across it rather than confined to the tile seams. Also tiles the encode. Read by the SD1.5/SDXL, FLUX.1, FLUX.2, Z-Image, Qwen-Image and Qwen-Image-2.1 VAE nodes, the Anima encode, the Z-Image control encode and the Krea-2 style reference; other model families ignore it.diff --git a/scripts/calibrate_flux2_working_memory.py b/scripts/calibrate_flux2_working_memory.pyindex 32368e5c13..51e1dc0f50 100644--- a/scripts/calibrate_flux2_working_memory.py+++ b/scripts/calibrate_flux2_working_memory.py@@ -36,6 +36,7 @@ import torch.nn.functional as Ffrom torch.nn.attention import SDPBackend, sdpa_kernelfrom invokeai.backend.util.attention import SDPA_MATH_BYTES_PER_SCORE_ELEMENT+from invokeai.backend.util.sdpa_scope import install_default_sdpa_priorityGIB = 1024**3@@ -240,6 +241,9 @@ def main() -> None:if not torch.cuda.is_available():raise SystemExit("No CUDA/HIP device available.")+ # The app ranks SDPA kernels by this order (`apply_monkeypatches`), and it decides the kernel `dispatch` reports.+ # Every point, measured in this process or a child, runs under it.+ install_default_sdpa_priority()if args.single:kind, rest = args.single[0], args.single[1:]diff --git a/tests/app/services/session_processor/conftest.py b/tests/app/services/session_processor/conftest.pyindex 4353cdda6a..5a6949972e 100644--- a/tests/app/services/session_processor/conftest.py+++ b/tests/app/services/session_processor/conftest.py@@ -28,3 +28,13 @@ def _no_full_collection_per_claimed_item(monkeypatch: pytest.MonkeyPatch) -> Nonmonkeypatch.setattr("invokeai.app.services.session_processor.session_processor_default.gc", SimpleNamespace(collect=lambda: 0))++[email protected](autouse=True)+def _no_real_attention_probe(monkeypatch: pytest.MonkeyPatch) -> None:+ """A worker's first claimed item probes its device's SDPA kernels, which allocates on that device. These workers+ run on faked or configured devices, so on a machine with a GPU the probe would touch the real one."""+ monkeypatch.setattr(+ "invokeai.app.services.session_processor.session_processor_default.log_attention_backends",+ lambda logger, device: None,+ )diff --git a/tests/app/services/session_processor/test_node_attention_caller.py b/tests/app/services/session_processor/test_node_attention_caller.pynew file mode 100644index 0000000000..a0e5aed8e6--- /dev/null+++ b/tests/app/services/session_processor/test_node_attention_caller.py@@ -0,0 +1,82 @@+"""Attention inside a node is attributed to the node's type, so the pinned-kernel report (`attention_backend`) can say+which node a kernel was not possible for, whatever the model family."""++from contextlib import nullcontext+from threading import Event+from types import SimpleNamespace+from unittest.mock import Mock++import pytest++import invokeai.backend.util.attention as attention+from invokeai.app.invocations.math import AddInvocation+from invokeai.app.invocations.primitives import IntegerOutput+from invokeai.app.services.invocation_cache.invocation_cache_memory import MemoryInvocationCache+from invokeai.app.services.progress_previews.progress_previews_default import MemoryProgressPreviews+from invokeai.app.services.session_processor.session_processor_default import DefaultSessionRunner+from invokeai.app.services.shared.execution_effects import ExecutionEffectsRecorder+from invokeai.app.services.shared.graph import Graph, GraphExecutionState+++def _run_one_node(monkeypatch: pytest.MonkeyPatch, invoke) -> Mock:+ """Run an `add` node whose `invoke` is replaced, through the runner's own `run_node`. Returns the queue double."""+ monkeypatch.setattr(AddInvocation, "invoke", invoke)+ graph = Graph()+ graph.add_node(AddInvocation(id="add", a=1, b=2, use_cache=False))+ session = GraphExecutionState(graph=graph)+ invocation = session.next()++ services = SimpleNamespace(+ configuration=SimpleNamespace(node_cache_size=0, offload_text_encoders_to_idle_gpus=False),+ progress_previews=MemoryProgressPreviews(),+ events=Mock(),+ logger=Mock(),+ performance_statistics=Mock(),+ invocation_cache=MemoryInvocationCache(max_cache_size=0),+ session_queue=Mock(),+ )+ services.performance_statistics.collect_stats.return_value = nullcontext()+ monkeypatch.setattr(+ "invokeai.app.services.session_processor.session_processor_default.build_invocation_context",+ lambda data, services, is_canceled: SimpleNamespace(+ execution_effects=ExecutionEffectsRecorder(+ source_node_id=data.invocation.id, frame_path=data.execution_frame+ )+ ),+ )+ runner = DefaultSessionRunner()+ runner.start(services=services, cancel_event=Event())+ runner.run_node(invocation, Mock(session=session, session_id="session", item_id=1))+ return services.session_queue+++def test_a_nodes_attention_is_attributed_to_its_type_and_only_while_it_runs(monkeypatch):+ seen: list[str | None] = []+ original = AddInvocation.invoke++ # Annotated: the session checks a node's output against the return type `invoke` declares.+ def invoke(self, context) -> IntegerOutput:+ seen.append(attention._attention_caller.get())+ return original(self, context)++ queue = _run_one_node(monkeypatch, invoke)++ assert seen == ["add"]+ assert attention._attention_caller.get() is None+ queue.fail_queue_item.assert_not_called()+++def test_a_failing_node_leaves_no_caller_behind(monkeypatch):+ """The next node, or attention outside any node on this worker thread, must not be blamed on it."""+ seen: list[str | None] = []++ def invoke(self, context) -> IntegerOutput:+ seen.append(attention._attention_caller.get())+ raise RuntimeError("boom")++ queue = _run_one_node(monkeypatch, invoke)++ assert seen == ["add"]+ queue.fail_queue_item.assert_called_once()+ assert queue.fail_queue_item.call_args.args[1:3] == ("RuntimeError", "boom"), "the node's own error"+ assert attention._attention_caller.get() is Nonediff --git a/tests/app/services/session_processor/test_session_processor_cancel_guard.py b/tests/app/services/session_processor/test_session_processor_cancel_guard.pyindex 6b9971176b..9406fa121f 100644--- a/tests/app/services/session_processor/test_session_processor_cancel_guard.py+++ b/tests/app/services/session_processor/test_session_processor_cancel_guard.py@@ -8,6 +8,7 @@ worker recording `queue_item` (so the status-changed handler can't set the workefrom types import SimpleNamespaceimport pytest+import torchfrom invokeai.app.services.session_processor.session_processor_default import DefaultSessionProcessorfrom invokeai.app.services.session_queue.session_queue_common import SessionQueueItemNotFoundError@@ -51,16 +52,18 @@ def test_is_queue_item_terminal_treats_missing_as_terminal():assert processor._is_queue_item_terminal(1) is True-def _run_guard_scenario(statuses: list[str], set_cancel_event: bool, set_stop_on_claim: bool = False):+def _run_guard_scenario(+ statuses: list[str], set_cancel_event: bool, set_stop_on_claim: bool = False, device: torch.device | None = None+):"""Drives one _process claim through the post-dequeue guard.`statuses` is the sequence of statuses returned by successive get_queue_item calls for theclaimed row (the last value repeats). `set_cancel_event` simulates the delayed handler for the- PREVIOUS item firing between cancel_event.clear() and the guard. Returns- (canceled_ids, run_items, worker).+ PREVIOUS item firing between cancel_event.clear() and the guard. `device` makes it a multi-GPU+ worker on that device; there is no real GPU behind it. Returns (canceled_ids, run_items, worker)."""from threading import BoundedSemaphore, Event- from unittest.mock import MagicMock+ from unittest.mock import MagicMock, patchfrom invokeai.app.services.session_processor.session_processor_default import _SessionWorker@@ -71,7 +74,7 @@ def _run_guard_scenario(statuses: list[str], set_cancel_event: bool, set_stop_onrun_items: list[int] = []runner = MagicMock()runner.workflow_call_queue_lifecycle.run_queue_item.side_effect = lambda item: run_items.append(item.item_id)- worker = _SessionWorker(device=None, runner=runner)+ worker = _SessionWorker(device=device, runner=runner)canceled: list[int] = []claimed = SimpleNamespace(item_id=42, session_id="sess", queue_id="default")@@ -116,7 +119,8 @@ def _run_guard_scenario(statuses: list[str], set_cancel_event: bool, set_stop_onprocessor._polling_interval = 0.001processor._thread_semaphore = BoundedSemaphore(1)- processor._process(worker=worker, stop_event=stop_event, resume_event=resume_event)+ with patch("invokeai.app.services.session_processor.session_processor_default.torch.cuda.set_device"):+ processor._process(worker=worker, stop_event=stop_event, resume_event=resume_event)return canceled, run_items, worker@@ -271,3 +275,48 @@ def test_cuda_device_pin_is_deferred_until_first_claim_and_runs_once():assert events == ["dequeue:empty", "dequeue:1", "pin:cuda:1", "run:1", "dequeue:2", "run:2"]mock_set_device.assert_called_once_with(torch.device("cuda:1"))+++def _record_attention_logs(monkeypatch) -> list[object]:+ """Replace the conftest's no-op stub with a recorder of the device each call asks about."""+ import invokeai.app.services.session_processor.session_processor_default as processor_module++ devices: list[object] = []+ monkeypatch.setattr(processor_module, "log_attention_backends", lambda logger, device: devices.append(device))+ return devices+++def test_an_item_about_to_run_logs_the_attention_backends_of_the_workers_own_device(monkeypatch):+ """On a multi-GPU box each worker reports its own GPU, not the configured default device."""+ devices = _record_attention_logs(monkeypatch)++ _canceled, run_items, _worker = _run_guard_scenario(+ statuses=["in_progress"], set_cancel_event=False, device=torch.device("cuda", 1)+ )++ assert run_items == [42]+ assert devices == [torch.device("cuda", 1)]+++def test_an_item_skipped_before_it_runs_does_not_probe(monkeypatch):+ """The probe allocates, and in single-device mode resolving the device creates a CUDA context: an+ item canceled before it started must not pay that."""+ devices = _record_attention_logs(monkeypatch)++ _canceled, run_items, _worker = _run_guard_scenario(statuses=["canceled"], set_cancel_event=False)++ assert run_items == []+ assert devices == []+++def test_a_probe_that_raises_does_not_fail_the_item(monkeypatch):+ import invokeai.app.services.session_processor.session_processor_default as processor_module++ def broken(logger, device):+ raise RuntimeError("CUDA driver gone")++ monkeypatch.setattr(processor_module, "log_attention_backends", broken)++ _canceled, run_items, _worker = _run_guard_scenario(statuses=["in_progress"], set_cancel_event=False)++ assert run_items == [42]diff --git a/tests/app/util/test_attention_backend_probe.py b/tests/app/util/test_attention_backend_probe.pyindex e97634781e..52c16aeeb6 100644--- a/tests/app/util/test_attention_backend_probe.py+++ b/tests/app/util/test_attention_backend_probe.py@@ -10,6 +10,7 @@ from unittest.mock import MagicMock, patchimport pytestimport torch+from torch.nn.attention import SDPBackendimport invokeai.app.util.startup_utils as startup_utilsfrom invokeai.app.util.startup_utils import log_attention_backends, probe_attention_backends@@ -18,9 +19,9 @@ from invokeai.app.util.startup_utils import log_attention_backends, probe_attent@pytest.fixture(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()+ startup_utils._probed_attention_devices.clear()yield- startup_utils._logged_attention_backends.clear()+ startup_utils._probed_attention_devices.clear()class TestProbe:@@ -84,8 +85,18 @@ class TestLogLine:log_attention_backends(logger, torch.device("cpu"))assert caplog.records == []- def test_the_line_names_every_backend_and_its_answer(self, caplog):+ def test_the_line_names_every_backend_and_its_answer(self, caplog, preserve_sdpa_priority_order):logger = logging.getLogger("test_probe_line")+ # An order neither torch nor InvokeAI uses, so the line can only have read it from torch.+ torch._C._set_sdp_priority_order(+ [+ int(SDPBackend.MATH),+ int(SDPBackend.CUDNN_ATTENTION),+ int(SDPBackend.FLASH_ATTENTION),+ int(SDPBackend.EFFICIENT_ATTENTION),+ int(SDPBackend.OVERRIDEABLE),+ ]+ )with patch("invokeai.app.util.startup_utils.probe_attention_backends",return_value={"cudnn": True, "flash": False, "efficient": True, "math": True},@@ -102,6 +113,35 @@ 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+ # Which of the available kernels a call gets is decided by the order, so the line states the one+ # in force.+ assert "priority MATH > CUDNN_ATTENTION > FLASH_ATTENTION > EFFICIENT_ATTENTION > OVERRIDEABLE" in message++ def test_a_backend_the_order_repeats_is_named_once_where_it_first_appears(+ self, caplog, preserve_sdpa_priority_order+ ):+ """torch 2.7's order has a fifth slot it never fills, so MATH appears twice. The repeat is never+ reached; naming it would read as a kernel tried twice."""+ logger = logging.getLogger("test_probe_repeat")+ torch._C._set_sdp_priority_order(+ [+ int(SDPBackend.FLASH_ATTENTION),+ int(SDPBackend.CUDNN_ATTENTION),+ int(SDPBackend.EFFICIENT_ATTENTION),+ int(SDPBackend.MATH),+ int(SDPBackend.MATH),+ ]+ )+ with patch(+ "invokeai.app.util.startup_utils.probe_attention_backends",+ return_value={"cudnn": True, "flash": False, "efficient": True, "math": True},+ ):+ with caplog.at_level(logging.INFO, logger=logger.name):+ log_attention_backends(logger, torch.device("cuda"))++ assert caplog.records[0].message.endswith(+ "priority FLASH_ATTENTION > CUDNN_ATTENTION > EFFICIENT_ATTENTION > MATH"+ )def test_it_is_logged_once_per_device(self, caplog):"""The probe allocates, which creates that device's CUDA context. Repeating it per generation@@ -120,12 +160,13 @@ class TestLogLine:"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."""+ def test_a_device_whose_probe_failed_is_not_probed_again(self):+ """Every claimed item asks. A probe allocates and ends with `empty_cache()`, and on a multi-GPU+ box that flush is deferred to a busy peer's step boundary -- retrying a failed probe would pay+ that on every item for a line that does not come."""logger = logging.getLogger("test_probe_retry")- probe = MagicMock(side_effect=[None, {"cudnn": True, "flash": True, "efficient": True, "math": True}])+ probe = MagicMock(return_value=None)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 == 2+ assert probe.call_count == 1diff --git a/tests/backend/krea2/test_attention.py b/tests/backend/krea2/test_attention.pyindex b54306c5e4..63634a6628 100644--- a/tests/backend/krea2/test_attention.py+++ b/tests/backend/krea2/test_attention.py@@ -18,10 +18,10 @@ from invokeai.backend.krea2.style_reference import (@pytest.fixture(autouse=True)def _no_ambient_override(monkeypatch):- """These assert the default ranking, so they have to own the default rather than inherit it.+ """These assert the default behaviour, so they have to own the default rather than inherit it.- Four of the six fail in a shell where `INVOKE_KREA2_SDPA_BACKEND` is exported -- which is the- shell the PR asks users and its own A/B workflow to run in.+ A shell where `INVOKE_KREA2_SDPA_BACKEND` pins a backend -- which is the shell the docs ask+ benchmarking runs to use -- changes the kernel they run on."""monkeypatch.delenv(krea2_attention.KREA2_SDPA_BACKEND_ENV_VAR, raising=False)@@ -126,10 +126,10 @@ def test_processor_without_regional_state_ignores_the_shared_mask() -> None:],ids=["efficient", "cudnn"],)-def test_cuda_fused_sdpa_accepts_dense_regional_mask(monkeypatch: pytest.MonkeyPatch, backend, can_use) -> None:+def test_cuda_fused_sdpa_accepts_dense_regional_mask(backend, can_use) -> None:"""Both fused kernels that can serve this path, not just the one that used to.- Flash refuses the mask the regional blocks pass, so after the ranking change cuDNN is what+ Flash refuses the mask the regional blocks pass, so under the process-wide order cuDNN is whatactually serves them -- and on a build without flash it serves every block. Pinning onlyefficient here would guard a kernel the product no longer reaches first."""@@ -140,7 +140,6 @@ def test_cuda_fused_sdpa_accepts_dense_regional_mask(monkeypatch: pytest.MonkeyPtorch.ones(12, 12, device="cuda", dtype=torch.bool),)state = Krea2RegionalPromptingState(attention_mask=mask)- monkeypatch.setattr(krea2_attention, "_KREA2_SDPA_BACKENDS", [backend])head_dim = attn.hidden_size // attn.num_headssdpa_tensor = torch.empty(1, attn.num_heads, 24, head_dim, device="cuda", dtype=torch.float16)@@ -149,7 +148,11 @@ def test_cuda_fused_sdpa_accepts_dense_regional_mask(monkeypatch: pytest.MonkeyPpytest.skip(f"This CUDA device/build cannot serve a dense mask with {backend.name}")with torch.no_grad():- attn.set_processor(Krea2MemoryEfficientAttnProcessor(regional_prompting_state=state))+ attn.set_processor(+ Krea2MemoryEfficientAttnProcessor(+ regional_prompting_state=state, sdpa_backends=krea2_attention.Krea2SdpaBackends(exclusive=backend)+ )+ )output = attn(hidden_states, attention_mask=None, image_rotary_emb=None)assert output.is_cuda@@ -158,7 +161,7 @@ def test_cuda_fused_sdpa_accepts_dense_regional_mask(monkeypatch: pytest.MonkeyP@pytest.mark.skipif(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.+ """Every backend in the process-wide order must produce the same image.Ranking cuDNN above the memory-efficient kernel changed which kernel serves a Krea-2 block onbuilds without flash -- i.e. every Windows CUDA build. Nothing pinned that the kernels agree, so@@ -170,7 +173,7 @@ def test_the_ranked_backends_agree_numerically() -> None:def run(backend: SDPBackend) -> torch.Tensor:processor = Krea2MemoryEfficientAttnProcessor(- sdpa_backends=krea2_attention.Krea2SdpaBackends(backends=(backend,), set_priority=False)+ sdpa_backends=krea2_attention.Krea2SdpaBackends(exclusive=backend))attn.set_processor(processor)with torch.no_grad():diff --git a/tests/backend/krea2/test_grouped_query_attention.py b/tests/backend/krea2/test_grouped_query_attention.pyindex 8975f53919..c8616447e3 100644--- a/tests/backend/krea2/test_grouped_query_attention.py+++ b/tests/backend/krea2/test_grouped_query_attention.py@@ -3,8 +3,11 @@Krea-2 has 48 query heads over 12 K/V heads. `repeat_interleave` makes them match, which lets anyfused kernel take the call — at the price of allocating two tensors four times larger, every call.Only some kernels serve the unexpanded shape, so the choice is made per call by asking the-dispatcher. Getting that answer wrong in the optimistic direction is not a slow path but a ~9 GB one:-the math backend materialises the full [heads, seq, seq] score matrix.+dispatcher, keeping the heads grouped only where a fused kernel takes them -- and, with another+kernel than flash pinned first, only where that kernel ranks no lower than the expanded call's.+Getting that answer wrong in the optimistic direction is not a slow path but a ~9 GB one -- the math+backend materialises the full [heads, seq, seq] score matrix -- or a kernel the admin pinned that+never gets the call."""import contextlib@@ -21,9 +24,19 @@ from invokeai.backend.krea2.attention import (Krea2RegionalPromptingState,Krea2SdpaBackends,)+from invokeai.backend.util.attention import sdpa_backend_choice+from invokeai.backend.util.sdpa_scope import demote_cudnn_attention, install_default_sdpa_priority, sdpa_policyHQ, HKV, HEAD_DIM = 48, 12, 128+FLASH, CUDNN, EFFICIENT, MATH, OVERRIDEABLE = (+ SDPBackend.FLASH_ATTENTION,+ SDPBackend.CUDNN_ATTENTION,+ SDPBackend.EFFICIENT_ATTENTION,+ SDPBackend.MATH,+ SDPBackend.OVERRIDEABLE,+)+def _tensors(device: str, seq: int = 64, kv_heads: int = HKV, masked: bool = False):q = torch.randn(1, HQ, seq, HEAD_DIM, device=device, dtype=torch.bfloat16)@@ -32,46 +45,18 @@ def _tensors(device: str, seq: int = 64, kv_heads: int = HKV, masked: bool = Falreturn q, kv, kv.clone(), mask+def _fake_cuda(monkeypatch) -> None:+ """Get past the processor's CUDA gate on a runner without a GPU; the dispatcher then answers for CPU."""+ monkeypatch.setattr(torch.Tensor, "is_cuda", property(lambda self: True), raising=False)++class TestTheDecisionIsConservative:def test_a_non_cuda_tensor_never_takes_the_gqa_path(self):- """`SDPAParams` is CUDA-only, and no other backend offers a fused grouped-query path.- Answering yes here would drop the call onto math."""+ """The grouped path is measured on CUDA only. CPU's own dispatcher would say yes -- its flash+ kernel serves grouped-query attention -- so this pins the gate itself."""proc = Krea2MemoryEfficientAttnProcessor()assert proc._serves_grouped_query_attention(*_tensors("cpu")) is False- def test_it_answers_no_when_the_permitted_list_excludes_the_capable_kernels(self, monkeypatch):- """The trap: cuDNN may well serve the shape, but if this call is not permitted to reach it —- which `INVOKE_KREA2_SDPA_BACKEND=efficient` does — then answering yes makes the call fail- outright with `No available kernel`, because the memory-efficient kernel refuses GQA.-- Both capability probes are forced to yes, so membership in the permitted list is the only- thing left that can produce a no. CPU tensors alone would not reach that far: the function- returns at the `is_cuda` guard, and this assertion would hold with the whole membership test- deleted. The device is faked the same way `test_a_torch_build_with_a_different_sdpaparams`- does it, so the branch is genuinely exercised on a runner without a GPU.- """- 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=MagicMock()))- monkeypatch.setattr(torch.backends.cuda, "can_use_cudnn_attention", lambda params: True)- monkeypatch.setattr(torch.backends.cuda, "can_use_flash_attention", lambda params: True)-- permitted = Krea2MemoryEfficientAttnProcessor()- assert permitted._serves_grouped_query_attention(q, k, v, mask) is True-- excluded = Krea2MemoryEfficientAttnProcessor(- sdpa_backends=Krea2SdpaBackends(backends=(SDPBackend.EFFICIENT_ATTENTION,), set_priority=False)- )- assert excluded._serves_grouped_query_attention(q, k, v, mask) is False-- def test_a_torch_build_with_a_different_sdpaparams_answers_no(self, monkeypatch):- # Falling back to the expansion is correct everywhere; it merely costs memory.- 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(side_effect=TypeError("signature changed")))- assert proc._serves_grouped_query_attention(q, k, v, mask) is False-class TestTheHeadsAreOnlyPassedThroughWhenTheyDiffer:def test_a_block_with_equal_head_counts_never_asks_and_never_sets_the_flag(self, monkeypatch):@@ -79,10 +64,9 @@ class TestTheHeadsAreOnlyPassedThroughWhenTheyDiffer:and nothing to ask. Asking anyway would pay the probe per call for a `False` the shapesalready settle -- and setting `enable_gqa` on equal head counts is a claim about the tensorsthat 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)+ asked = MagicMock(return_value=SDPBackend.FLASH_ATTENTION)+ monkeypatch.setattr(attention_module, "sdpa_runs_fused", asked)+ monkeypatch.setattr(attention_module, "sdpa_backend_choice", asked)seen: dict[str, object] = {}real_sdpa = attention_module.F.scaled_dot_product_attention@@ -107,41 +91,65 @@ class TestTheHeadsAreOnlyPassedThroughWhenTheyDiffer: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.+ The dispatcher reads the per-backend enable flags and the priority order, 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):+ def test_the_answer_follows_the_selection_in_force(+ self, monkeypatch, cpu_flash_serves_grouped_query_attention, preserve_sdpa_priority_order+ ):+ """Against the real dispatcher, under real windows. A window here stands in for this+ processor's exclusive override and for another session's alike: the dispatcher cannot tell+ them apart, and neither should the answer. Under the default order, which decides with one+ question; a pinned order asks more (`TestAPinnedKernel`).++ Where this torch's CPU flash kernel does not take grouped-query attention (torch 2.7), the K/V+ heads match the query's instead: mismatched, every answer would be no, and the test would no+ longer see the window at all."""+ install_default_sdpa_priority()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()))- monkeypatch.setattr(torch.backends.cuda, "can_use_flash_attention", MagicMock(return_value=False))-- answers = iter([False, True])- monkeypatch.setattr(torch.backends.cuda, "can_use_cudnn_attention", lambda params: next(answers))+ q, k, v, mask = _tensors("cpu", kv_heads=HKV if cpu_flash_serves_grouped_query_attention else HQ)+ _fake_cuda(monkeypatch)- assert proc._serves_grouped_query_attention(q, k, v, mask) is False+ assert proc._serves_grouped_query_attention(q, k, v, mask) is True+ with sdpa_policy([SDPBackend.MATH]):+ # Math's grouped-query path expands K/V itself on every call (and every chunk the ROCm guard cuts),+ # where one explicit expansion copies once and math copies nothing for equal heads.+ assert proc._serves_grouped_query_attention(q, k, v, mask) is False+ with sdpa_policy([SDPBackend.EFFICIENT_ATTENTION]):+ # Nothing this window permits serves the call -- the `efficient` override's case. Answering+ # yes would fail it outright; no sends it to the expansion, which efficient takes.+ assert proc._serves_grouped_query_attention(q, k, v, mask) is Falseassert 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."""+ @pytest.mark.parametrize(+ ("pinned", "questions"),+ [(None, 1), (SDPBackend.EFFICIENT_ATTENTION, 2)],+ ids=["default-order", "efficient-pinned"],+ )+ def test_the_dispatcher_is_asked_under_the_policy_the_call_will_run_with(+ self, monkeypatch, preserve_sdpa_priority_order, pinned, questions+ ):+ """Asked outside the window, the dispatcher answers for whatever policy is installed at that+ moment -- which on a busy multi-GPU box is another session's, not this call's. Under the default+ order that is one question, as it always was; with another kernel pinned first two: the grouped+ call's kernel, and -- cuDNN not ranking first -- the expanded call's."""from torch.nn.attention import _cur_sdpa_kernel_backends- exclusive = Krea2SdpaBackends(backends=(SDPBackend.CUDNN_ATTENTION,), set_priority=False)+ install_default_sdpa_priority(pinned)+ exclusive = Krea2SdpaBackends(exclusive=SDPBackend.CUDNN_ATTENTION)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)+ def choice(*args, **kwargs):+ enabled_when_asked.append(set(_cur_sdpa_kernel_backends()))+ return SDPBackend.CUDNN_ATTENTION++ monkeypatch.setattr(attention_module, "sdpa_backend_choice", choice)+ monkeypatch.setattr(attention_module, "sdpa_runs_fused", lambda *args, **kwargs: choice() is not None)+ _fake_cuda(monkeypatch)attn = Krea2Attention(hidden_size=HQ * 16, num_heads=HQ, num_kv_heads=HKV, eps=1e-5).eval()attn.set_processor(proc)@@ -152,7 +160,7 @@ class TestTheAnswerIsNotCached: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}]+ assert enabled_when_asked == [{SDPBackend.CUDNN_ATTENTION}] * questionsclass TestTheExpansionStillHappensWhenItMust:@@ -179,9 +187,12 @@ class TestTheExpansionStillHappensWhenItMust:@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA is required to reach a fused GQA kernel")class TestTheTwoPathsAgreeOnCuda:@pytest.mark.parametrize("masked", [False, True])- def test_grouped_query_output_matches_the_expanded_one(self, masked, monkeypatch):+ def test_grouped_query_output_matches_the_expanded_one(self, masked, monkeypatch, preserve_sdpa_priority_order):"""The saving is only worth having if the result is the same. Anything else would be asilent change to every Krea-2 image."""+ # The order a generation runs under; torch's own ranks math above cuDNN, so the grouped call+ # would not reach the kernel that serves it in production.+ install_default_sdpa_priority()torch.manual_seed(0)attn = (Krea2Attention(hidden_size=HQ * HEAD_DIM, num_heads=HQ, num_kv_heads=HKV, eps=1e-5)@@ -228,7 +239,7 @@ class TestTheTwoPathsAgreeOnCuda:proc = Krea2MemoryEfficientAttnProcessor(regional_prompting_state=state)q, k, v, mask = _tensors("cuda", seq=256, masked=masked)if not proc._serves_grouped_query_attention(q, k, v, mask):- pytest.skip("no permitted fused kernel on this device serves grouped-query attention here")+ pytest.skip("no fused kernel on this device serves grouped-query attention here")assert seen[1] == HKV, "the dispatcher serves this shape, so the grouped path must have run"# bf16 kernels differ in accumulation order, so the two are close rather than identical. The@@ -238,12 +249,29 @@ class TestTheTwoPathsAgreeOnCuda:assert (expanded - grouped).abs().max() < 0.05[email protected](not torch.cuda.is_available(), reason="only CUDA's chooser honours the priority order")+class TestTheOrderDecidesToo:+ def test_a_capable_kernel_ranked_below_math_does_not_count(self, preserve_sdpa_priority_order):+ """The ~9 GB case. Under torch's own order -- which is also the order after a cuDNN failure+ demoted it -- math ranks above cuDNN, and with a mask flash refuses the call and+ memory-efficient refuses grouped-query attention, so the unexpanded call would run on math even+ where cuDNN could serve it. Asking only whether a kernel *can* serve the call would answer yes."""+ proc = Krea2MemoryEfficientAttnProcessor()+ q, k, v, mask = _tensors("cuda", seq=256, masked=True)++ install_default_sdpa_priority()+ if not proc._serves_grouped_query_attention(q, k, v, mask):+ pytest.skip("no fused kernel on this device serves masked grouped-query attention")+ assert demote_cudnn_attention() is True+ assert proc._serves_grouped_query_attention(q, k, v, mask) is False++class TestTheClaimHoldsWithoutCuda:"""The saving rests on grouped output equalling expanded output, and that does not need a GPU.`_serves_grouped_query_attention` returns False for CPU tensors, so on a runner without oneevery other test in this file exercises the expansion path and the change itself is unobserved.- `enable_gqa` is served on CPU by the math backend, so the numerical claim can be pinned there —+ `enable_gqa` is served on CPU by torch's own kernels, so the numerical claim can be pinned there —which is the half that would silently change every Krea-2 image if it were wrong."""@@ -268,10 +296,12 @@ class TestTheClaimHoldsWithoutCuda:assert grouped.shape == expanded.shapeassert torch.allclose(grouped, expanded, atol=1e-5)- def test_the_processor_passes_the_grouped_heads_through_when_the_answer_is_yes(self, monkeypatch):+ def test_the_processor_passes_the_grouped_heads_through_when_the_answer_is_yes(+ self, monkeypatch, preserve_sdpa_priority_order+ ):"""That the decision reaches SDPA — the half the CUDA tests cover only where there is a GPU.- With the device and both capability probes faked, the answer is yes, so the processor must+ With the device and the dispatcher's answer faked, the answer is yes, so the processor musthand SDPA the unexpanded K/V heads and `enable_gqa=True`. Pinning it here is what makes apermanently-False `enable_gqa` fail on a runner without CUDA, where every other test in thisfile legitimately exercises the expansion path instead.@@ -284,10 +314,9 @@ class TestTheClaimHoldsWithoutCuda:seen["enable_gqa"] = enable_gqareturn real(query, key, value, attn_mask=attn_mask, enable_gqa=enable_gqa, **kwargs)- monkeypatch.setattr(torch.Tensor, "is_cuda", property(lambda self: True), raising=False)- monkeypatch.setattr(torch.backends.cuda, "SDPAParams", MagicMock(return_value=MagicMock()))- monkeypatch.setattr(torch.backends.cuda, "can_use_cudnn_attention", lambda params: True)- monkeypatch.setattr(torch.backends.cuda, "can_use_flash_attention", lambda params: True)+ install_default_sdpa_priority()+ _fake_cuda(monkeypatch)+ monkeypatch.setattr(attention_module, "sdpa_runs_fused", lambda *args, **kwargs: True)monkeypatch.setattr(attention_module.F, "scaled_dot_product_attention", spy)torch.manual_seed(0)@@ -298,3 +327,173 @@ class TestTheClaimHoldsWithoutCuda:assert seen["enable_gqa"] is Trueassert seen["kv_heads"] == HKV, "the K/V heads were expanded despite the dispatcher serving them"+++PINNED_EFFICIENT = [EFFICIENT, FLASH, CUDNN, MATH, OVERRIDEABLE]+PINNED_CUDNN = [CUDNN, FLASH, EFFICIENT, MATH, OVERRIDEABLE]+++def _run_processor(monkeypatch, answer) -> list[tuple[int, bool]]:+ """Run a small grouped-query attention through the processor with the device faked and the dispatcher's answers+ scripted by `answer(enable_gqa)`, and record the K/V heads and `enable_gqa` each SDPA call gets."""+ _fake_cuda(monkeypatch)+ monkeypatch.setattr(+ attention_module, "sdpa_backend_choice", lambda *args, enable_gqa=False, **kwargs: answer(enable_gqa)+ )+ seen: list[tuple[int, bool]] = []+ real = attention_module.F.scaled_dot_product_attention++ def spy(query, key, value, attn_mask=None, enable_gqa=False, **kwargs):+ seen.append((key.shape[1], enable_gqa))+ return real(query, key, value, attn_mask=attn_mask, enable_gqa=enable_gqa, **kwargs)++ monkeypatch.setattr(attention_module.F, "scaled_dot_product_attention", spy)+ torch.manual_seed(0)+ attn = Krea2Attention(hidden_size=256, num_heads=8, num_kv_heads=2, eps=1e-5).eval()+ attn.set_processor(Krea2MemoryEfficientAttnProcessor())+ with torch.no_grad():+ attn(torch.randn(1, 16, 256), attention_mask=None, image_rotary_emb=None)+ return seen+++class TestAPinnedKernel:+ """With another kernel than flash first, a fused grouped call keeps the heads grouped only where its kernel ranks no+ lower than the expanded call's.++ The answers are the dispatcher's, per build and GPU; CPU's dispatcher ignores the order, so they are scripted here+ with what each platform gives (measured or documented in `backend/krea2/attention.py`). The order is real.+ """++ @pytest.mark.parametrize(+ ("grouped", "expanded", "order", "keeps_grouped"),+ [+ # Windows: the kernel pinned away from would take the grouped call; the pinned one takes the expanded call.+ pytest.param(CUDNN, EFFICIENT, PINNED_EFFICIENT, False, id="pinned-efficient"),+ # Linux: flash takes the grouped call, still below the pinned kernel.+ pytest.param(FLASH, EFFICIENT, PINNED_EFFICIENT, False, id="pinned-efficient-flash-takes-it-grouped"),+ # A call memory-efficient attention cannot take expanded either: cuDNN either way.+ pytest.param(CUDNN, CUDNN, PINNED_EFFICIENT, True, id="pinned-efficient-cudnn-either-way"),+ # Expanded, the call would build the full score matrix; grouped, a fused kernel takes it.+ pytest.param(CUDNN, MATH, PINNED_EFFICIENT, True, id="pinned-efficient-expanded-on-math"),+ pytest.param(CUDNN, None, PINNED_EFFICIENT, True, id="expanded-call-has-no-kernel"),+ pytest.param(CUDNN, FLASH, PINNED_CUDNN, True, id="pinned-cudnn"),+ ],+ )+ def test_the_grouped_heads_are_kept_only_where_they_lose_no_rank(self, grouped, expanded, order, keeps_grouped):+ assert attention_module._grouped_ranks_first(grouped, expanded, order) is keeps_grouped++ def test_the_processor_expands_the_heads_for_a_pinned_kernel_that_needs_it(+ self, monkeypatch, preserve_sdpa_priority_order+ ):+ """The rule reaching SDPA: as on an RTX 4090 under Windows with `efficient` pinned -- cuDNN for the grouped+ call, memory-efficient attention for the expanded one."""+ install_default_sdpa_priority(SDPBackend.EFFICIENT_ATTENTION)++ seen = _run_processor(monkeypatch, lambda enable_gqa: CUDNN if enable_gqa else EFFICIENT)++ assert seen == [(8, False)], "expanded to the query heads, without enable_gqa"++ def test_a_grouped_call_math_would_serve_is_expanded(self, monkeypatch, preserve_sdpa_priority_order):+ """`attention_backend: math`: math is first and takes every call. Its grouped-query path would copy the+ expanded K/V on every call, and on every chunk where the ROCm guard splits a long one."""+ install_default_sdpa_priority(SDPBackend.MATH)++ seen = _run_processor(monkeypatch, lambda enable_gqa: MATH)++ assert seen == [(8, False)], "expanded to the query heads, without enable_gqa"+++class TestTheExpandedCallIsAskedOnAProbe:+ @pytest.mark.parametrize(+ "device",+ ["cpu", pytest.param("cuda", marks=pytest.mark.skipif(not torch.cuda.is_available(), reason="needs CUDA"))],+ )+ @pytest.mark.parametrize("mask_kind", ["none", "bool", "float", "padding"])+ def test_the_probe_gets_the_answer_the_expanded_call_gets(self, device, mask_kind):+ """Instead of K/V four times larger, a probe of the call's dtype, head_dim, device and mask kind. That is+ only sound where it answers as the real expanded call does, under any selection in force."""+ seq = 256+ query = torch.empty(1, HQ, seq, HEAD_DIM, device=device, dtype=torch.bfloat16)+ expanded = torch.empty(1, HQ, seq, HEAD_DIM, device=device, dtype=torch.bfloat16)+ mask = {+ "none": None,+ "bool": torch.ones(seq, seq, device=device, dtype=torch.bool),+ "float": torch.zeros(1, 1, seq, seq, device=device, dtype=torch.bfloat16),+ "padding": torch.ones(1, 1, 1, seq, device=device, dtype=torch.bool),+ }[mask_kind]++ for selection in (contextlib.nullcontext(), sdpa_policy([SDPBackend.MATH])):+ with selection:+ answer = sdpa_backend_choice(query, expanded, expanded, mask)+ assert answer is not None+ assert attention_module._expanded_call_choice(query, mask) == answer+++def _cuda_attention() -> tuple[Krea2Attention, torch.Tensor]:+ torch.manual_seed(0)+ attn = (+ Krea2Attention(hidden_size=HQ * HEAD_DIM, num_heads=HQ, num_kv_heads=HKV, eps=1e-5)+ .eval()+ .to("cuda", torch.bfloat16)+ )+ return attn, torch.randn(1, 256, HQ * HEAD_DIM, device="cuda", dtype=torch.bfloat16)+++def _run_on_cuda(attn: Krea2Attention, hidden: torch.Tensor, monkeypatch) -> tuple[torch.Tensor, list[tuple]]:+ """Run the processor; for each SDPA call record the K/V heads, `enable_gqa` and the kernel that serves it."""+ real = attention_module.F.scaled_dot_product_attention+ calls: list[tuple] = []++ def spy(q, k, v, attn_mask=None, enable_gqa=False, **kwargs):+ calls.append((k.shape[1], enable_gqa, sdpa_backend_choice(q, k, v, attn_mask, enable_gqa=enable_gqa)))+ return real(q, k, v, attn_mask=attn_mask, enable_gqa=enable_gqa, **kwargs)++ attn.set_processor(Krea2MemoryEfficientAttnProcessor())+ with monkeypatch.context() as patch, torch.no_grad():+ patch.setattr(attention_module.F, "scaled_dot_product_attention", spy)+ out = attn(hidden, attention_mask=None, image_rotary_emb=None).float()+ return out, calls++[email protected](not torch.cuda.is_available(), reason="only CUDA's chooser honours the priority order")+class TestAPinnedKernelGetsTheCall:+ """Measured on an RTX 4090 under Windows; any CUDA GPU with the kernels answers them."""++ def test_pinned_efficient_expands_the_heads_and_runs_on_it(self, monkeypatch, preserve_sdpa_priority_order):+ """Pinning memory-efficient attention is how an admin keeps attention off cuDNN. It refuses grouped-query+ calls, so the heads are expanded for it rather than left to cuDNN -- and the result is the same image."""+ equal = torch.empty(1, HQ, 256, HEAD_DIM, device="cuda", dtype=torch.bfloat16)+ params = torch.backends.cuda.SDPAParams(equal, equal, equal, None, 0.0, False, False)+ if not torch.backends.cuda.can_use_efficient_attention(params):+ pytest.skip("this GPU has no memory-efficient kernel for the Krea-2 shape")+ attn, hidden = _cuda_attention()++ install_default_sdpa_priority(SDPBackend.EFFICIENT_ATTENTION)+ pinned, calls = _run_on_cuda(attn, hidden, monkeypatch)+ install_default_sdpa_priority()+ default, _ = _run_on_cuda(attn, hidden, monkeypatch)++ assert calls == [(HQ, False, SDPBackend.EFFICIENT_ATTENTION)]+ # The bound the two-paths comparison above uses: bf16 kernels differ in accumulation order.+ corr = torch.corrcoef(torch.stack([pinned.flatten(), default.flatten()]))[0, 1]+ assert corr > 0.9999, f"correlation {corr}"+ assert (pinned - default).abs().max() < 0.05++ @pytest.mark.skipif(+ torch.backends.cuda.is_flash_attention_available(), reason="with flash in the build, flash leads the order"+ )+ def test_the_default_order_keeps_the_heads_grouped_on_cudnn(self, monkeypatch, preserve_sdpa_priority_order):+ """Windows CUDA builds have no flash, so cuDNN serves the grouped call and the expanded one alike; the+ expansion would only cost memory."""+ q = torch.empty(1, HQ, 256, HEAD_DIM, device="cuda", dtype=torch.bfloat16)+ kv = torch.empty(1, HKV, 256, HEAD_DIM, device="cuda", dtype=torch.bfloat16)+ if not torch.backends.cuda.can_use_cudnn_attention(+ torch.backends.cuda.SDPAParams(q, kv, kv, None, 0.0, False, True)+ ):+ pytest.skip("this GPU's cuDNN does not serve grouped-query attention")+ attn, hidden = _cuda_attention()++ install_default_sdpa_priority()+ _, calls = _run_on_cuda(attn, hidden, monkeypatch)++ assert calls == [(HKV, True, SDPBackend.CUDNN_ATTENTION)]diff --git a/tests/backend/krea2/test_sdpa_backend_selection.py b/tests/backend/krea2/test_sdpa_backend_selection.pyindex cb71eab09f..e63afdbc11 100644--- a/tests/backend/krea2/test_sdpa_backend_selection.py+++ b/tests/backend/krea2/test_sdpa_backend_selection.py@@ -1,14 +1,9 @@-"""Which SDPA backends the Krea-2 attention processors run under, and the opt-in override.+"""Which SDPA backend selection the Krea-2 attention processors run under, and the opt-in override.-The ranking is a measurement, not a preference. On the real Krea-2 attention shape, per call: on a-Windows 4090 (no flash in the build) cuDNN runs at 3.72ms against efficient's 5.92ms; on a Linux-30-series card flash runs at 19.74ms, cuDNN at 21.27ms, efficient at 31.45ms. So flash leads where it-exists and cuDNN takes the blocks it cannot serve -- the masked ones, and every block on a build-without flash.--These tests pin what makes that reachable at all: the order, and `set_priority=True`. Without the-latter the list only *permits* backends and torch picks by its own order, so the ranking would be a-silent no-op.+By default Krea-2 opens no SDPA window: its attention runs under InvokeAI's process-wide priority order+(`util.sdpa_scope`), like every other model's. The override exists for benchmarking and support: a+named backend is pinned exclusively, so a run that completes proves which kernel served it, and+`default` names the process-wide order so a benchmarking run can state which policy it used."""import contextlib@@ -33,65 +28,33 @@ from invokeai.backend.krea2.attention import (def _no_ambient_override(monkeypatch):"""Decide the override here, never inherit it from the shell.- The PR tells users -- and its own A/B workflow -- to export this variable, so the suite is run- in exactly the shell where it is set. Reading it made 11 of these 24 tests fail there, including- the fallback test the design rests on. A test that asserts what the default ranking is has to- own that default; one that wants an override sets it explicitly.+ The docs tell users -- and benchmarking runs -- to export this variable, so the suite is run in+ exactly the shell where it is set. A test that asserts what the default is has to own that+ default; one that wants an override sets it explicitly."""monkeypatch.delenv(KREA2_SDPA_BACKEND_ENV_VAR, raising=False)-class TestTheDefaultRanking:- def test_flash_leads_and_cudnn_follows(self):- """Flash is the fastest kernel where the build has it -- and is already what runs today,- because torch's own order puts it above efficient. Ranking cuDNN over it would be a small- regression on every flash-capable build."""- backends = resolve_krea2_sdpa_backends(raw_override=None).backends- assert backends[0] is SDPBackend.FLASH_ATTENTION- assert backends[1] is SDPBackend.CUDNN_ATTENTION-- def test_cudnn_outranks_efficient(self):- """This is where the win actually comes from: flash refuses the additive mask the- regional-prompting blocks pass, so on those blocks it is skipped and cuDNN takes over --- 1.6x-2.0x over efficient. On a build without flash, that is every block."""- backends = resolve_krea2_sdpa_backends(raw_override=None).backends- assert backends.index(SDPBackend.CUDNN_ATTENTION) < backends.index(SDPBackend.EFFICIENT_ATTENTION)-- def test_math_is_last(self):- # The unfused fallback: correct everywhere, and ~35x slower at ~35x the memory.- assert resolve_krea2_sdpa_backends(raw_override=None).backends[-1] is SDPBackend.MATH-- def test_priority_is_set(self):- """Load-bearing: without set_priority the list only *permits* backends and torch picks by- its own order, in which cuDNN ranks last and would never be chosen. The ranking would be a- no-op."""- assert resolve_krea2_sdpa_backends(raw_override=None).set_priority is True-- def test_the_fallbacks_are_all_still_there(self):- # A ranked list, never an exclusive backend: an unavailable entry is skipped by the- # dispatcher, so the list degrades to today's behaviour on its own.- assert set(resolve_krea2_sdpa_backends(raw_override=None).backends) == {- SDPBackend.CUDNN_ATTENTION,- SDPBackend.EFFICIENT_ATTENTION,- SDPBackend.FLASH_ATTENTION,- SDPBackend.MATH,- }-- def test_flash_is_kept_even_where_a_probe_would_call_it_dead(self):- """A sibling plan proposed dropping FLASH where a probe shows it absent. That would be wrong- twice over: on ROCm flash is available and cuDNN is not, and on Linux CUDA it is the fastest- kernel of the four. A dead entry in a ranked list costs nothing; a missing one costs a- platform."""- assert SDPBackend.FLASH_ATTENTION in resolve_krea2_sdpa_backends(raw_override=None).backends-- def test_no_override_is_recorded_by_default(self):+class TestTheDefault:+ def test_unset_pins_no_backend_and_records_no_override(self):# `override is None` is what keeps the benchmark instrumentation, and its synchronize()- # calls, entirely off the default path.- assert resolve_krea2_sdpa_backends(raw_override=None).override is None+ # calls, entirely off the default path -- and what lets SageAttention serve Krea-2.+ choice = resolve_krea2_sdpa_backends(raw_override=None)+ assert choice.exclusive is None+ assert choice.override is None@pytest.mark.parametrize("blank", ["", " ", "\t"])def test_a_blank_value_is_the_default_not_an_error(self, blank):- assert resolve_krea2_sdpa_backends(raw_override=blank).override is None+ choice = resolve_krea2_sdpa_backends(raw_override=blank)+ assert choice.exclusive is None+ assert choice.override is None++ def test_default_names_the_process_order_and_pins_nothing(self):+ """The value a benchmarking run exports to measure the shipped behaviour. It must run the+ same kernels as unset -- no window -- while still counting as an override."""+ choice = resolve_krea2_sdpa_backends(raw_override="default")+ assert choice.exclusive is None+ assert choice.override == "default"class TestTheOverride:@@ -104,26 +67,13 @@ class TestTheOverride:("math", SDPBackend.MATH),],)- def test_a_named_backend_is_exclusive_with_no_fallback(self, value, expected):+ def test_a_named_backend_is_pinned_exclusively(self, value, expected):"""The point of the exclusive modes: a run that completes proves that kernel was used,because an unavailable backend raises visibly instead of degrading to math unnoticed."""choice = resolve_krea2_sdpa_backends(raw_override=value)- assert choice.backends == (expected,)- assert choice.set_priority is False+ assert choice.exclusive is expectedassert choice.override == value- 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.backends- assert explicit.set_priority == default.set_priority- assert explicit.override == "default"- assert explicit.backends[0] is SDPBackend.FLASH_ATTENTION-@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()@@ -138,15 +88,16 @@ class TestTheOverride:def test_the_environment_is_read_when_no_value_is_passed(self, monkeypatch):monkeypatch.setenv(KREA2_SDPA_BACKEND_ENV_VAR, "math")- assert resolve_krea2_sdpa_backends().backends == (SDPBackend.MATH,)+ assert resolve_krea2_sdpa_backends().exclusive is SDPBackend.MATHmonkeypatch.delenv(KREA2_SDPA_BACKEND_ENV_VAR)assert resolve_krea2_sdpa_backends().override is Noneclass TestProcessorsCarryTheChoice:- def test_every_processor_gets_the_same_resolved_choice(self):+ def test_every_processor_gets_the_same_resolved_choice(self, monkeypatch):"""Resolved once per generation and handed down -- not re-read per attention call, of whichthere are dozens per step."""+ monkeypatch.setenv(KREA2_SDPA_BACKEND_ENV_VAR, "cudnn")transformer = MagicMock()transformer.attn_processors = {"transformer_blocks.0.attn.processor": object(),@@ -158,69 +109,46 @@ class TestProcessorsCarryTheChoice:choices = {id(p.sdpa_backends) for p in processors.values()}assert len(choices) == 1- assert next(iter(processors.values())).sdpa_backends.backends[0] is SDPBackend.FLASH_ATTENTION+ assert next(iter(processors.values())).sdpa_backends.exclusive is SDPBackend.CUDNN_ATTENTION- def test_a_standalone_processor_resolves_for_itself(self):+ def test_a_standalone_processor_resolves_for_itself(self, monkeypatch):# Constructed directly in tests and by custom code; it must not depend on the builder.- assert Krea2MemoryEfficientAttnProcessor().sdpa_backends.backends[0] is SDPBackend.FLASH_ATTENTION+ monkeypatch.setenv(KREA2_SDPA_BACKEND_ENV_VAR, "math")+ assert Krea2MemoryEfficientAttnProcessor().sdpa_backends.exclusive is SDPBackend.MATH@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA is required to exercise the SDPA dispatcher")-class TestTheFallbackIsReal:- """The whole design rests on one dispatcher property: an unusable backend in a *ranked* list is- skipped, while an *exclusively* selected one raises.-- This is what makes cuDNN-first safe on hardware where cuDNN cannot serve the call, and it is- worth pinning: if a future torch made a ranked list raise instead, the ranking would turn every- such device from "today's behaviour" into a failed generation, silently as far as our tests go.- """-- @staticmethod- def _unservable_by_cudnn():+class TestAnExclusiveOverrideHasNoFallback:+ def test_the_call_raises_where_the_pinned_backend_cannot_serve_it(self):+ """The likely explanation of the sm_86 report: that measurement was taken with+ `sdpa_kernel([backend])` -- exclusive, no fallback -- which is exactly the mode that raises+ `No available kernel` when the backend is unusable. The process-wide order skips it instead+ (`test_sdpa_scope`)."""# fp32 is refused by the fused kernels, which is a portable way to make cuDNN unusable on a# card where it otherwise works -- i.e. to stand in for the sm_86 report.t = torch.randn(1, 24, 512, 128, device="cuda", dtype=torch.float32)params = torch.backends.cuda.SDPAParams(t, t, t, None, 0.0, False, False)if torch.backends.cuda.can_use_cudnn_attention(params):pytest.skip("This build serves fp32 with cuDNN, so it cannot stand in for an unusable backend")- return t- def test_a_ranked_list_completes_where_cudnn_cannot_serve(self):- t = self._unservable_by_cudnn()- choice = resolve_krea2_sdpa_backends(raw_override=None)- with sdpa_kernel(list(choice.backends), set_priority=choice.set_priority):- out = torch.nn.functional.scaled_dot_product_attention(t, t, t)- assert torch.isfinite(out).all()-- def test_the_same_call_raises_when_cudnn_is_selected_exclusively(self):- """The counterpart, and the likely explanation of the sm_86 report: that measurement was- taken with `sdpa_kernel([backend])` -- exclusive, no fallback -- which is exactly the mode- that raises `No available kernel` when the backend is unusable."""- t = self._unservable_by_cudnn()choice = resolve_krea2_sdpa_backends(raw_override="cudnn")with pytest.raises(RuntimeError, match="No available kernel"):- with sdpa_kernel(list(choice.backends), set_priority=choice.set_priority):+ with sdpa_kernel([choice.exclusive]):torch.nn.functional.scaled_dot_product_attention(t, t, t)class TestTheDispatchSite:- """That the resolved choice actually reaches the SDPA window.+ """That the resolved choice actually reaches the SDPA window -- or that no window is opened.Everything above asserts what `resolve_krea2_sdpa_backends` *returns*. None of it survives the- processor ignoring that value: drop `set_priority=` from the call, or read the module constant- instead of `self.sdpa_backends`, and Krea-2 falls back to torch's own order on every block --- 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 window installed.+ processor ignoring that value, and spying on the window is the only place that is observable."""def _run_with_spy(self, monkeypatch, processor):- seen: dict[str, object] = {}+ windows: list[list[SDPBackend]] = []- def spy(backends, set_priority=False):- seen["backends"] = list(backends)- seen["set_priority"] = set_priority+ def spy(backends):+ windows.append(list(backends))return contextlib.nullcontext()monkeypatch.setattr(krea2_attention, "sdpa_policy", spy)@@ -228,22 +156,19 @@ class TestTheDispatchSite:attn = Krea2Attention(hidden_size=256, num_heads=8, num_kv_heads=2, eps=1e-5).eval()attn.set_processor(processor)with torch.no_grad():- attn(torch.randn(1, 24, attn.hidden_size), attention_mask=None, image_rotary_emb=None)- return seen-- def test_the_default_ranking_reaches_the_dispatcher_with_priority_on(self, monkeypatch):- seen = self._run_with_spy(monkeypatch, Krea2MemoryEfficientAttnProcessor())-- assert seen["backends"] == list(resolve_krea2_sdpa_backends(raw_override=None).backends)- # Without this the list only *permits* backends and torch picks by its own order, which is- # what the ranking exists to override.- assert seen["set_priority"] is True-- def test_the_processors_own_choice_is_used_not_the_module_default(self, monkeypatch):- """An exclusive override differs from the shipped list in both fields, so a processor that- reads the module constant instead of its own attribute fails here on either one."""+ out = attn(torch.randn(1, 24, attn.hidden_size), attention_mask=None, image_rotary_emb=None)+ assert out.shape == (1, 24, attn.hidden_size)+ return windows++ @pytest.mark.parametrize("raw", [None, "default"])+ def test_the_default_opens_no_window(self, monkeypatch, raw):+ """A window here would replace the process-wide order for the block -- and, being process-global,+ for every other session's attention while it is open."""+ processor = Krea2MemoryEfficientAttnProcessor(sdpa_backends=resolve_krea2_sdpa_backends(raw_override=raw))+ assert self._run_with_spy(monkeypatch, processor) == []++ def test_an_exclusive_override_pins_its_backend(self, monkeypatch):exclusive = resolve_krea2_sdpa_backends(raw_override="math")- seen = self._run_with_spy(monkeypatch, Krea2MemoryEfficientAttnProcessor(sdpa_backends=exclusive))+ windows = self._run_with_spy(monkeypatch, Krea2MemoryEfficientAttnProcessor(sdpa_backends=exclusive))- assert seen["backends"] == [SDPBackend.MATH]- assert seen["set_priority"] is False+ assert windows == [[SDPBackend.MATH]]diff --git a/tests/backend/util/test_cudnn_sdpa_fallback.py b/tests/backend/util/test_cudnn_sdpa_fallback.pynew file mode 100644index 0000000000..4f5e34ed62--- /dev/null+++ b/tests/backend/util/test_cudnn_sdpa_fallback.py@@ -0,0 +1,269 @@+"""The automatic fallback from a cuDNN attention call that fails at run time.++torch checks cuDNN's eligibility statically, so a call can still fail inside it; the fallback demotes+cuDNN behind math in the process order and retries. A real cuDNN failure cannot be produced on CPU, so+the kernel is a double that raises, and the dispatcher's choice is forced to cuDNN for the failing+case only. The priority order and the enable flags are torch's real ones; the orders expected of them+come from `sdpa_orders`, written out per layout of torch's own order.+"""++import logging+import threading++import pytest+import torch+import torch.nn.functional as F+from torch.nn.attention import SDPBackend++import invokeai.backend.util.attention as attention+from invokeai.backend.util.attention import install_cudnn_sdpa_fallback+from invokeai.backend.util.logging import InvokeAILogger+from invokeai.backend.util.sdpa_scope import install_default_sdpa_priority, sdpa_policy++LOGGER = InvokeAILogger.get_logger(attention.__name__).name+# torch's own function, whatever the tests rebind: the grouped-query retry is checked against it.+TORCH_SDPA = F.scaled_dot_product_attention+++class _Kernel:+ """Stands in for torch's SDPA: raises the scripted errors in call order, then returns a tensor+ that says which call produced it."""++ def __init__(self, *errors: BaseException | None) -> None:+ self.errors = list(errors)+ self.calls = 0++ def __call__(+ self, query, key, value, attn_mask=None, dropout_p=0.0, is_causal=False, *, scale=None, enable_gqa=False+ ):+ self.calls += 1+ error = self.errors.pop(0) if self.errors else None+ if error is not None:+ raise error+ return torch.full_like(query, float(self.calls))+++def _priority() -> list[SDPBackend]:+ return [SDPBackend(backend) for backend in torch._C._get_sdp_priority_order()]+++def _dispatcher_names(monkeypatch, backend: SDPBackend) -> None:+ monkeypatch.setattr(torch.ops.aten, "_fused_sdp_choice", lambda *args, **kwargs: int(backend))+++def install(monkeypatch, preserve_sdpa_priority_order, sdpa_orders):+ """Install the fallback over `kernel` on a build that looks like CUDA, under the process order."""+ monkeypatch.setattr(torch.version, "cuda", "13.0")+ monkeypatch.setattr(torch.version, "hip", None)+ monkeypatch.setattr(attention, "_cudnn_demotions", 0)+ torch._C._set_sdp_priority_order([int(backend) for backend in sdpa_orders.torch_own])+ install_default_sdpa_priority()++ def _install(kernel: _Kernel) -> None:+ monkeypatch.setattr(F, "scaled_dot_product_attention", kernel)+ install_cudnn_sdpa_fallback()++ return _install+++def _qkv() -> torch.Tensor:+ return torch.randn(1, 2, 8, 16)+++def test_a_cudnn_failure_demotes_cudnn_warns_once_and_returns_the_retry(install, monkeypatch, caplog, sdpa_orders):+ kernel = _Kernel(RuntimeError("cuDNN Frontend error: no valid execution plan"))+ install(kernel)+ _dispatcher_names(monkeypatch, SDPBackend.CUDNN_ATTENTION)+ q = _qkv()++ with caplog.at_level(logging.WARNING, logger=LOGGER):+ out = F.scaled_dot_product_attention(q, q, q)+ F.scaled_dot_product_attention(q, q, q)++ assert torch.equal(out, torch.full_like(q, 2.0)), "the retry's result"+ assert _priority() == sdpa_orders.torch_own+ assert len(caplog.records) == 1+ assert "no valid execution plan" in caplog.records[0].message+ assert kernel.calls == 3+++ "error",+ [+ torch.OutOfMemoryError("CUDA out of memory"),+ RuntimeError("cuDNN error: CUDNN_STATUS_ALLOC_FAILED"),+ pytest.param(+ getattr(torch, "AcceleratorError", RuntimeError)("CUDA error: an illegal memory access was encountered"),+ marks=pytest.mark.skipif(not hasattr(torch, "AcceleratorError"), reason="this torch has no such class"),+ ),+ ],+ ids=["allocator", "cudnn workspace", "sticky cuda error"],+)+def test_an_error_that_is_not_cudnns_propagates_untouched(install, monkeypatch, error, sdpa_orders):+ """Out of memory is the model cache's business, and another kernel would not make room. A sticky CUDA+ error from earlier work surfaces at whatever launch comes next and poisons the context: demoting cuDNN+ would announce a recovery the retry cannot make, and the report it asks for would blame cuDNN."""+ kernel = _Kernel(error)+ install(kernel)+ _dispatcher_names(monkeypatch, SDPBackend.CUDNN_ATTENTION)+ q = _qkv()++ with pytest.raises(type(error)) as raised:+ F.scaled_dot_product_attention(q, q, q)++ assert raised.value is error+ assert _priority() == sdpa_orders.installed+ assert kernel.calls == 1+++def test_a_failure_on_another_kernel_propagates_untouched(install, monkeypatch, sdpa_orders):+ error = RuntimeError("memory-efficient attention failed")+ kernel = _Kernel(error)+ install(kernel)+ _dispatcher_names(monkeypatch, SDPBackend.EFFICIENT_ATTENTION)+ q = _qkv()++ with pytest.raises(RuntimeError) as raised:+ F.scaled_dot_product_attention(q, q, q)++ assert raised.value is error+ assert _priority() == sdpa_orders.installed+ assert kernel.calls == 1+++def test_cudnn_asked_for_exclusively_propagates_untouched(install, monkeypatch, sdpa_orders):+ """`INVOKE_KREA2_SDPA_BACKEND=cudnn`: math is disabled, and the user wanted to see cuDNN fail.++ The choice is forced to cuDNN here too -- on CPU tensors the math-disabled branch would otherwise+ answer None by itself -- so that disabled math is the only thing that can make it propagate.+ """+ error = RuntimeError("cuDNN Frontend error")+ kernel = _Kernel(error)+ install(kernel)+ monkeypatch.setattr(attention, "sdpa_backend_choice", lambda *args, **kwargs: SDPBackend.CUDNN_ATTENTION)+ q = _qkv()++ with sdpa_policy([SDPBackend.CUDNN_ATTENTION]), pytest.raises(RuntimeError) as raised:+ F.scaled_dot_product_attention(q, q, q)++ assert raised.value is error+ assert _priority() == sdpa_orders.installed+++def test_a_retry_that_fails_too_propagates(install, monkeypatch, sdpa_orders):+ retry_error = RuntimeError("memory-efficient attention failed as well")+ kernel = _Kernel(RuntimeError("cuDNN Frontend error"), retry_error)+ install(kernel)+ _dispatcher_names(monkeypatch, SDPBackend.CUDNN_ATTENTION)+ q = _qkv()++ with pytest.raises(RuntimeError) as raised:+ F.scaled_dot_product_attention(q, q, q)++ assert raised.value is retry_error+ assert _priority() == sdpa_orders.torch_own+ assert kernel.calls == 2+++def test_two_workers_failing_at_once_both_recover_and_warn_once(install, monkeypatch, caplog, sdpa_orders):+ """Both calls are inside the kernel before either fails. The second to reach the fallback finds+ cuDNN already demoted -- the dispatcher no longer names it for the call -- and must retry anyway."""+ both_inside = threading.Barrier(2, timeout=5)+ failed: set[int] = set()++ def kernel(query, key, value, attn_mask=None, dropout_p=0.0, is_causal=False, *, scale=None, enable_gqa=False):+ if threading.get_ident() not in failed:+ failed.add(threading.get_ident())+ both_inside.wait()+ raise RuntimeError("cuDNN Frontend error")+ return query.clone()++ install(kernel)+ _dispatcher_names(monkeypatch, SDPBackend.CUDNN_ATTENTION)+ results: list[torch.Tensor] = []++ def worker() -> None:+ q = _qkv()+ results.append(F.scaled_dot_product_attention(q, q, q))++ with caplog.at_level(logging.WARNING, logger=LOGGER):+ threads = [threading.Thread(target=worker) for _ in range(2)]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join(timeout=10)++ assert len(results) == 2+ assert len(caplog.records) == 1+ assert _priority() == sdpa_orders.torch_own+++def test_installing_twice_wraps_once(install, monkeypatch):+ kernel = _Kernel(RuntimeError("cuDNN Frontend error"), RuntimeError("still failing"))+ install(kernel)+ wrapped = F.scaled_dot_product_attention+ install_cudnn_sdpa_fallback()+ assert F.scaled_dot_product_attention is wrapped++ _dispatcher_names(monkeypatch, SDPBackend.CUDNN_ATTENTION)+ q = _qkv()+ with pytest.raises(RuntimeError, match="still failing"):+ F.scaled_dot_product_attention(q, q, q)+ assert kernel.calls == 2, "one retry, not one per layer"+++def test_nothing_is_installed_where_there_is_no_cudnn_attention(install, monkeypatch):+ monkeypatch.setattr(torch.version, "hip", "7.2")+ kernel = _Kernel()+ install(kernel)+ assert F.scaled_dot_product_attention is kernel+++HQ, HKV = 8, 2+++def _grouped_qkv() -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:+ torch.manual_seed(0)+ return torch.randn(1, HQ, 8, 16), torch.randn(1, HKV, 8, 16), torch.randn(1, HKV, 8, 16)+++def test_a_grouped_query_call_is_retried_with_expanded_heads(install, monkeypatch):+ """Krea-2 hands SDPA unexpanded K/V only because cuDNN took them. With cuDNN demoted no fused kernel+ takes grouped-query attention, so the unchanged call would build the full score matrix on math --+ gigabytes per call, priced nowhere. The retry must not be that call."""+ seen: list[tuple[int, bool]] = []++ def kernel(query, key, value, attn_mask=None, dropout_p=0.0, is_causal=False, *, scale=None, enable_gqa=False):+ seen.append((key.shape[1], enable_gqa))+ if len(seen) == 1:+ raise RuntimeError("cuDNN Frontend error")+ return query.clone()++ install(kernel)+ _dispatcher_names(monkeypatch, SDPBackend.CUDNN_ATTENTION)+ q, k, v = _grouped_qkv()++ F.scaled_dot_product_attention(q, k, v, enable_gqa=True)++ assert seen == [(HKV, True), (HQ, False)], "first as asked, then expanded without enable_gqa"+++def test_the_expanded_retry_is_the_same_attention(install, monkeypatch):+ """Against torch's own grouped-query result, so the expansion's axis and head order are proven rather+ than assumed: query head h attends to K/V head h // (HQ // HKV)."""+ failed = []++ def kernel(*args, **kwargs):+ if not failed:+ failed.append(True)+ raise RuntimeError("cuDNN Frontend error")+ return TORCH_SDPA(*args, **kwargs)++ install(kernel)+ _dispatcher_names(monkeypatch, SDPBackend.CUDNN_ATTENTION)+ q, k, v = _grouped_qkv()++ retried = F.scaled_dot_product_attention(q, k, v, enable_gqa=True)++ torch.testing.assert_close(retried, TORCH_SDPA(q, k, v, enable_gqa=True))diff --git a/tests/backend/util/test_pinned_sdpa_kernel_report.py b/tests/backend/util/test_pinned_sdpa_kernel_report.pynew file mode 100644index 0000000000..800e53fa64--- /dev/null+++ b/tests/backend/util/test_pinned_sdpa_kernel_report.py@@ -0,0 +1,548 @@+"""The report for `attention_backend: cudnn | flash | efficient | math`.++A pinned kernel is ranked first and never exclusive, so attention it cannot serve runs on the next kernel without a word+from torch. The report logs that once per node type, kernel and reason. These run real `F.scaled_dot_product_attention`+calls against torch's real dispatcher and priority order; the CUDA-only reasons need a GPU.+"""++import logging+import subprocess+import sys+from typing import get_args++import pytest+import torch+import torch.nn.functional as F+from torch.nn.attention import SDPBackend++import invokeai.backend.util.attention as attention+from invokeai.app.services.config.config_default import ATTENTION_BACKEND+from invokeai.backend.util.attention import (+ attention_caller,+ install_cudnn_sdpa_fallback,+ install_pinned_sdpa_kernel_report,+ install_rocm_sdpa_guard,+ sdpa_backend_choice,+ sdpa_score_matrix_bytes,+)+from invokeai.backend.util.sdpa_scope import install_default_sdpa_priority, sdpa_policy++LOGGER = attention.__name__+# torch's own function, whatever the tests rebind.+TORCH_SDPA = F.scaled_dot_product_attention+CPU_RANKING = "on cpu PyTorch picks the kernel itself, without the ranking"+# An exclusive window on math, which takes every call: the one way to fix the kernel serving a CPU call on any torch.+MATH_ONLY = [SDPBackend.MATH]+# The kernel each `attention_backend` value pins, written out rather than read from `SDPA_KERNELS`.+PINNED_BY_VALUE = {+ "cudnn": SDPBackend.CUDNN_ATTENTION,+ "efficient": SDPBackend.EFFICIENT_ATTENTION,+ "flash": SDPBackend.FLASH_ATTENTION,+ "math": SDPBackend.MATH,+}++[email protected](autouse=True)+def _forget_reports():+ """Reports are once per process; a leftover one would silently pass the next test."""++ def forget():+ attention._pinned_reports.clear()+ attention._pinned_reports_dropped = False+ attention._plain_call_served.clear()++ forget()+ yield+ forget()+++def pin(monkeypatch, caplog, preserve_sdpa_priority_order):+ """Pin a kernel the way startup does: its order, then the report over torch's own function. What installing+ logs is the startup tests' business, so it is dropped here."""+ monkeypatch.setattr(F, "scaled_dot_product_attention", TORCH_SDPA)++ def _pin(kernel: SDPBackend) -> None:+ assert install_default_sdpa_priority(kernel)+ install_pinned_sdpa_kernel_report(kernel)+ caplog.clear()++ return _pin+++def _reports(caplog) -> list[str]:+ return [r.getMessage() for r in caplog.records if r.name == LOGGER and r.levelno == logging.WARNING]+++def _priority() -> list[SDPBackend]:+ return [SDPBackend(backend) for backend in torch._C._get_sdp_priority_order()]+++def _set_priority(order: list[SDPBackend]) -> None:+ torch._C._set_sdp_priority_order([int(backend) for backend in order])+++# Run in a fresh interpreter. After each step of pinning a kernel at startup it records whether CUDA is in use: torch's+# own flag, or a primary context on any device, which C++ code can create without setting the flag. Prints the steps+# after which it was.+_PINNED_STARTUP_CUDA_PROBE = """+import torch++has_primary_context = getattr(torch._C, "_cuda_hasPrimaryContext", lambda index: False)+++def cuda_in_use():+ contexts = [index for index in range(torch.cuda.device_count()) if has_primary_context(index)]+ return torch.cuda.is_initialized() or bool(contexts)+++steps = [("import torch", cuda_in_use())]+from invokeai.backend.util.sdpa_scope import SDPA_KERNELS, install_default_sdpa_priority++steps.append(("import invokeai.backend.util.sdpa_scope", cuda_in_use()))+from invokeai.backend.util.attention import install_pinned_sdpa_kernel_report++steps.append(("import invokeai.backend.util.attention", cuda_in_use()))+torch_sdpa = torch.nn.functional.scaled_dot_product_attention+for name, kernel in SDPA_KERNELS.items():+ install_default_sdpa_priority(kernel)+ steps.append((f"{name}: the order", cuda_in_use()))+ # A fresh report each time: installing over an installed one is a no-op.+ torch.nn.functional.scaled_dot_product_attention = torch_sdpa+ install_pinned_sdpa_kernel_report(kernel)+ steps.append((f"{name}: the report and the build check", cuda_in_use()))+print([step for step, in_use in steps if in_use])+"""+++def _qkv(*shape: int, dtype: torch.dtype = torch.float32, device: str = "cpu") -> torch.Tensor:+ torch.manual_seed(0)+ return torch.randn(*shape, dtype=dtype, device=device)+++class TestCpuAttention:+ """The ranking never applies on the CPU, so a CPU-only install, or CPU attention on a GPU install, is not reported+ on -- and not asked about, which costs the dispatcher query."""++ def test_attention_on_the_cpu_is_not_asked_about(self, pin, caplog, monkeypatch):+ pin(SDPBackend.CUDNN_ATTENTION)+ asked: list[str] = []+ monkeypatch.setattr(attention, "sdpa_backend_choice", lambda query, *args, **kwargs: asked.append("asked"))+ q = _qkv(1, 2, 8, 16)++ with caplog.at_level(logging.WARNING, logger=LOGGER), attention_caller("flux_denoise"):+ out = F.scaled_dot_product_attention(q, q, q)++ assert asked == []+ assert _reports(caplog) == []+ assert torch.equal(out, TORCH_SDPA(q, q, q))+++class TestOnCpu:+ """The report's decisions, run on the CPU standing in for a reported GPU device.++ Which kernel torch's CPU dispatcher gives a call changes between releases -- torch 2.14's flash takes 3-D+ inputs and 2.13's does not, 2.7's refuses grouped-query calls -- so these force the serving kernel: math takes every+ call, so an exclusive math window makes it serve on any torch. Where flash has to serve, torch is asked first."""++ @pytest.fixture(autouse=True)+ def _cpu_stands_in_for_a_gpu(self, monkeypatch):+ monkeypatch.setattr(attention, "_REPORTED_DEVICE_TYPES", frozenset({"cpu", "cuda", "xpu"}))++ def test_each_node_type_is_reported_once(self, pin, caplog):+ pin(SDPBackend.CUDNN_ATTENTION)+ q = _qkv(1, 8, 32, 64)++ with caplog.at_level(logging.WARNING, logger=LOGGER), sdpa_policy(MATH_ONLY):+ with attention_caller("flux_denoise"):+ out = F.scaled_dot_product_attention(q, q, q)+ F.scaled_dot_product_attention(q, q, q)+ with attention_caller("z_image_text_encoder"):+ F.scaled_dot_product_attention(q, q, q)+ F.scaled_dot_product_attention(q, q, q)+ unreported = TORCH_SDPA(q, q, q)++ assert _reports(caplog) == [+ f"attention_backend 'cudnn' is not possible for attention in flux_denoise: {CPU_RANKING}; it runs on MATH.",+ f"attention_backend 'cudnn' is not possible for attention in z_image_text_encoder: {CPU_RANKING}; "+ "it runs on MATH.",+ ]+ assert torch.equal(out, unreported), "the call itself runs unchanged"++ def test_another_serving_kernel_is_reported_again(self, pin, caplog):+ q = _qkv(1, 8, 32, 64)+ if SDPBackend(int(torch.ops.aten._fused_sdp_choice(q, q, q))) != SDPBackend.FLASH_ATTENTION:+ pytest.skip("this torch's CPU dispatcher does not give a plain call to flash")+ pin(SDPBackend.CUDNN_ATTENTION)++ with caplog.at_level(logging.WARNING, logger=LOGGER), attention_caller("flux_denoise"):+ F.scaled_dot_product_attention(q, q, q)+ with sdpa_policy(MATH_ONLY):+ F.scaled_dot_product_attention(q, q, q)+ F.scaled_dot_product_attention(q, q, q)+ F.scaled_dot_product_attention(q, q, q)++ assert _reports(caplog) == [+ f"attention_backend 'cudnn' is not possible for attention in flux_denoise: {CPU_RANKING}; "+ "it runs on FLASH_ATTENTION.",+ f"attention_backend 'cudnn' is not possible for attention in flux_denoise: {CPU_RANKING}; it runs on MATH.",+ ]++ def test_attention_outside_a_node_says_so(self, pin, caplog):+ pin(SDPBackend.EFFICIENT_ATTENTION)+ q = _qkv(1, 2, 8, 16)++ with caplog.at_level(logging.WARNING, logger=LOGGER), sdpa_policy(MATH_ONLY):+ F.scaled_dot_product_attention(q, q, q)++ assert _reports(caplog) == [+ f"attention_backend 'efficient' is not possible for attention outside a node: {CPU_RANKING}; "+ "it runs on MATH."+ ]++ def test_a_call_the_pinned_kernel_serves_is_not_reported(self, pin, caplog):+ """Math pinned, and the only kernel the window permits: it serves the call, so there is nothing to report."""+ pin(SDPBackend.MATH)+ q = _qkv(1, 2, 8, 16)++ with caplog.at_level(logging.WARNING, logger=LOGGER), attention_caller("flux_denoise"):+ with sdpa_policy(MATH_ONLY):+ F.scaled_dot_product_attention(q, q, q)++ assert _reports(caplog) == []++ def test_reports_stop_at_the_cap_and_say_so_once(self, pin, caplog, monkeypatch):+ monkeypatch.setattr(attention, "_MAX_PINNED_REPORTS", 2)+ pin(SDPBackend.CUDNN_ATTENTION)+ q = _qkv(1, 2, 8, 16)++ with caplog.at_level(logging.WARNING, logger=LOGGER), sdpa_policy(MATH_ONLY):+ for caller in ("a", "b", "c", "d"):+ with attention_caller(caller):+ F.scaled_dot_product_attention(q, q, q)++ reports = _reports(caplog)+ assert [report.split(":")[0] for report in reports] == [+ "attention_backend 'cudnn' is not possible for attention in a",+ "attention_backend 'cudnn' is not possible for attention in b",+ "attention_backend 'cudnn'",+ ]+ assert reports[2].endswith("further ones are not logged.")+ assert len(attention._pinned_reports) == 2++ def test_a_failing_report_never_fails_the_call(self, pin, caplog, monkeypatch):+ pin(SDPBackend.CUDNN_ATTENTION)+ attention._warn_pinned_report_failed.cache_clear()+ monkeypatch.setattr(attention, "_pinned_kernel_bypass", lambda *args: 1 / 0)+ q = _qkv(1, 2, 8, 16)++ with caplog.at_level(logging.WARNING, logger=LOGGER), sdpa_policy(MATH_ONLY):+ out = F.scaled_dot_product_attention(q, q, q)+ F.scaled_dot_product_attention(q, q, q)+ unreported = TORCH_SDPA(q, q, q)++ assert torch.equal(out, unreported)+ assert [r.exc_info is not None for r in caplog.records if r.levelno == logging.WARNING] == [True], "said once"+ attention._warn_pinned_report_failed.cache_clear()++ @pytest.mark.skipif(not torch.backends.mps.is_available(), reason="needs Apple Silicon")+ def test_attention_on_mps_is_not_asked_about(self, pin, caplog, monkeypatch):+ pin(SDPBackend.CUDNN_ATTENTION)+ asked: list[str] = []+ real = attention.sdpa_backend_choice+ monkeypatch.setattr(+ attention, "sdpa_backend_choice", lambda *args, **kwargs: asked.append("asked") or real(*args, **kwargs)+ )+ q = _qkv(1, 2, 8, 16, device="mps")++ with caplog.at_level(logging.WARNING, logger=LOGGER):+ F.scaled_dot_product_attention(q, q, q)++ assert asked == []+ assert _reports(caplog) == []++ def test_installing_twice_wraps_once(self, pin):+ pin(SDPBackend.MATH)+ wrapped = F.scaled_dot_product_attention+ install_pinned_sdpa_kernel_report(SDPBackend.MATH)+ assert F.scaled_dot_product_attention is wrapped+ assert wrapped.__wrapped__ is TORCH_SDPA+++class TestAtStartup:+ @pytest.fixture+ def startup(self, monkeypatch, preserve_sdpa_priority_order):+ from invokeai.app.util.startup_utils import apply_monkeypatches++ # Pin the entry points apply_monkeypatches rebinds so monkeypatch restores them afterwards.+ monkeypatch.setattr(F, "scaled_dot_product_attention", TORCH_SDPA)+ monkeypatch.setattr(torch.cuda, "empty_cache", torch.cuda.empty_cache)+ monkeypatch.setattr(torch.cuda, "is_current_stream_capturing", torch.cuda.is_current_stream_capturing)+ return apply_monkeypatches++ def test_every_kernel_value_of_the_setting_is_covered_here(self):+ """The config accepts these values and startup maps them to kernels; a value it does not map would quietly+ run as `auto`. The next test pins each one."""+ assert set(get_args(ATTENTION_BACKEND)) == {"auto", "sage", *PINNED_BY_VALUE}++ @pytest.mark.parametrize("value", sorted(PINNED_BY_VALUE))+ def test_a_pinned_kernel_installs_its_order_and_the_report(self, startup, sdpa_orders, value):+ _set_priority(sdpa_orders.torch_own)++ startup(value)++ assert _priority() == sdpa_orders.pinned[PINNED_BY_VALUE[value]]+ assert getattr(F.scaled_dot_product_attention, attention._PINNED_REPORT_SENTINEL, False)++ def test_the_startup_line_names_the_order_with_each_kernel_once(self, startup, caplog):+ """torch 2.7's own order repeats MATH in its fifth slot, which the four ranked slots leave in place. Set+ here on any torch, so the line meets the repeat wherever the suite runs."""+ _set_priority(+ [+ SDPBackend.FLASH_ATTENTION,+ SDPBackend.EFFICIENT_ATTENTION,+ SDPBackend.MATH,+ SDPBackend.CUDNN_ATTENTION,+ SDPBackend.MATH,+ ]+ )++ with caplog.at_level(logging.INFO, logger=LOGGER):+ startup("efficient")++ assert (+ "attention_backend 'efficient': PyTorch SDPA kernels ranked EFFICIENT_ATTENTION > FLASH_ATTENTION > "+ "CUDNN_ATTENTION > MATH. Attention the memory-efficient kernel cannot serve runs on the next one"+ in caplog.text+ )++ @pytest.mark.parametrize("backend", ["auto", "sage"])+ def test_no_pinned_kernel_installs_no_report(self, startup, backend, sdpa_orders):+ _set_priority(sdpa_orders.torch_own)++ startup(backend)++ assert not getattr(F.scaled_dot_product_attention, attention._PINNED_REPORT_SENTINEL, False)+ assert _priority() == sdpa_orders.installed++ def test_a_torch_that_cannot_rank_installs_no_report(self, startup, monkeypatch):+ """The report reads 'not first' as 'not possible'; without the ranking every call would be reported."""+ with monkeypatch.context() as patch:+ patch.delattr(torch._C, "_set_sdp_priority_order")+ startup("math")++ assert not getattr(F.scaled_dot_product_attention, attention._PINNED_REPORT_SENTINEL, False)++ @pytest.mark.parametrize(+ ("backend", "hip", "missing"),+ [+ ("flash", None, "this PyTorch build has no flash-attention kernel for GPUs"),+ ("cudnn", "7.2", "ROCm builds of PyTorch have no cuDNN attention kernel"),+ ],+ )+ def test_a_build_known_to_lack_the_kernel_is_warned_about(+ self, startup, monkeypatch, caplog, backend, hip, missing+ ):+ monkeypatch.setattr(torch.version, "cuda", None if hip else "13.0")+ monkeypatch.setattr(torch.version, "hip", hip)+ monkeypatch.setattr(torch.backends.cuda, "is_flash_attention_available", lambda: False)++ with caplog.at_level(logging.WARNING, logger=LOGGER):+ startup(backend)++ assert _reports(caplog) == [+ f"attention_backend '{backend}': {missing}, so GPU attention runs on the next kernel in that order. "+ "`attention_backend: auto` is the default."+ ]++ @pytest.mark.parametrize("value", sorted(PINNED_BY_VALUE))+ def test_pinning_math_warns_that_working_memory_does_not_cover_it(self, startup, caplog, value):+ """Most estimators reserve nothing for the score matrix the math kernel builds."""+ with caplog.at_level(logging.WARNING, logger=LOGGER):+ startup(value)+ attention.install_pinned_sdpa_kernel_report(PINNED_BY_VALUE[value])++ warnings = [message for message in _reports(caplog) if "working-memory estimates" in message]+ assert len(warnings) == (1 if value == "math" else 0)++ @pytest.mark.skipif(not torch.cuda.is_available(), reason="only a machine with a CUDA device can create a context")+ def test_pinning_a_kernel_at_startup_creates_no_cuda_context(self):+ """A context parks VRAM for the process lifetime on a server that may stay idle. Checked for what pinning adds+ to startup -- the modules holding it, the order, the report and the build check -- and not for the whole of+ `apply_monkeypatches`, whose first step, importing `invokeai.backend.util.hotfixes`, initializes CUDA by itself.+ In a fresh interpreter, because whether CUDA is initialized is process state an earlier test may have+ changed."""+ result = subprocess.run(+ [sys.executable, "-c", _PINNED_STARTUP_CUDA_PROBE], capture_output=True, text=True, timeout=300+ )++ assert result.returncode == 0, result.stderr+ initialized_by = result.stdout.strip().splitlines()[-1]+ assert initialized_by == "[]", f"CUDA was initialized by: {initialized_by}"++[email protected](not torch.cuda.is_available(), reason="the CUDA reasons need a CUDA or ROCm GPU")+class TestOnAGpu:+ """Measured on an RTX 4090 under Windows; any CUDA or ROCm GPU answers them."""++ @staticmethod+ def _first_accepting(params, kernels: list[SDPBackend]) -> SDPBackend:+ checks = {+ SDPBackend.FLASH_ATTENTION: torch.backends.cuda.can_use_flash_attention,+ SDPBackend.CUDNN_ATTENTION: torch.backends.cuda.can_use_cudnn_attention,+ SDPBackend.EFFICIENT_ATTENTION: torch.backends.cuda.can_use_efficient_attention,+ }+ return next((kernel for kernel in kernels if checks[kernel](params)), SDPBackend.MATH)++ def test_grouped_query_attention_pinned_to_efficient_names_the_reason_and_the_kernel(self, pin, caplog, capfd):+ """A grouped-query call that reaches SDPA unexpanded: memory-efficient attention refuses it, and the next+ kernel takes it. (Krea-2 expands its heads for a pinned kernel that needs that; see its processor.)"""+ q = _qkv(1, 8, 256, 64, dtype=torch.bfloat16, device="cuda")+ kv = _qkv(1, 2, 256, 64, dtype=torch.bfloat16, device="cuda")+ params = torch.backends.cuda.SDPAParams(q, kv, kv, None, 0.0, False, True)+ if torch.backends.cuda.can_use_efficient_attention(params):+ pytest.skip("this build's memory-efficient kernel serves grouped-query attention")+ served = self._first_accepting(params, [SDPBackend.FLASH_ATTENTION, SDPBackend.CUDNN_ATTENTION])+ pin(SDPBackend.EFFICIENT_ATTENTION)+ capfd.readouterr()++ with caplog.at_level(logging.WARNING, logger=LOGGER), attention_caller("grouped_query_node"):+ F.scaled_dot_product_attention(q, kv, kv, enable_gqa=True)+ first = capfd.readouterr().err+ F.scaled_dot_product_attention(q, kv, kv, enable_gqa=True)+ second = capfd.readouterr().err++ assert _reports(caplog) == [+ "attention_backend 'efficient' is not possible for attention in grouped_query_node: the memory-efficient "+ "kernel cannot serve this call (bfloat16, head_dim 64, no mask, 8 query / 2 key-value heads, enable_gqa); "+ f"it runs on {served.name}. PyTorch's own check follows on stderr."+ ]+ assert first != "", "torch's debug check printed its reason"+ assert second == "", "and only for the first call of its kind"++ @pytest.mark.skipif(+ torch.backends.cuda.is_flash_attention_available(), reason="this build has a flash-attention kernel"+ )+ def test_flash_pinned_on_a_build_without_it_says_so(self, pin, caplog):+ q = _qkv(1, 4, 128, 64, dtype=torch.float16, device="cuda")+ params = torch.backends.cuda.SDPAParams(q, q, q, None, 0.0, False, False)+ served = self._first_accepting(params, [SDPBackend.CUDNN_ATTENTION, SDPBackend.EFFICIENT_ATTENTION])+ pin(SDPBackend.FLASH_ATTENTION)++ with caplog.at_level(logging.WARNING, logger=LOGGER), attention_caller("flux_denoise"):+ F.scaled_dot_product_attention(q, q, q)++ assert _reports(caplog) == [+ f"attention_backend 'flash' is not possible for attention in flux_denoise: this PyTorch build or GPU "+ f"({q.device}) has no flash kernel; it runs on {served.name}."+ ]++ def test_a_pinned_kernel_an_exclusive_window_switched_off_says_so(self, pin, caplog):+ """`INVOKE_KREA2_SDPA_BACKEND=efficient` with cuDNN pinned: the window wins, and the report blames it."""+ q = _qkv(1, 4, 128, 64, dtype=torch.float16, device="cuda")+ if not torch.backends.cuda.can_use_efficient_attention(+ torch.backends.cuda.SDPAParams(q, q, q, None, 0.0, False, False)+ ):+ pytest.skip("this GPU has no memory-efficient kernel for the call")+ pin(SDPBackend.CUDNN_ATTENTION)++ with caplog.at_level(logging.WARNING, logger=LOGGER), attention_caller("krea2_denoise"):+ with sdpa_policy([SDPBackend.EFFICIENT_ATTENTION]):+ F.scaled_dot_product_attention(q, q, q)++ assert _reports(caplog) == [+ "attention_backend 'cudnn' is not possible for attention in krea2_denoise: the cuDNN kernel is switched "+ "off for this call (by an exclusive window, such as INVOKE_KREA2_SDPA_BACKEND's); it runs on "+ "EFFICIENT_ATTENTION."+ ]++ def test_pinned_math_is_priced_in_working_memory(self, preserve_sdpa_priority_order):+ """The estimators ask the dispatcher, so the score matrix math builds is reserved without being told."""+ device = torch.device("cuda", torch.cuda.current_device())+ args = {"device": device, "dtype": torch.float16, "num_heads": 24, "head_dim": 128, "seq_len": 4096}+ install_default_sdpa_priority()+ if sdpa_score_matrix_bytes(**args) != 0:+ pytest.skip("no fused kernel serves the plain call on this GPU, so math is priced either way")++ install_default_sdpa_priority(SDPBackend.MATH)++ assert sdpa_score_matrix_bytes(**args) == 24 * 4096 * 4096 * 17+++class _FailsOnceInCudnn:+ """Stands in for torch's SDPA: the first call fails the way a cuDNN plan does at run time, later ones run torch's+ own function."""++ def __init__(self) -> None:+ self.calls = 0++ def __call__(+ self, query, key, value, attn_mask=None, dropout_p=0.0, is_causal=False, *, scale=None, enable_gqa=False+ ):+ self.calls += 1+ if self.calls == 1:+ raise RuntimeError("cuDNN Frontend error: no valid execution plan")+ return TORCH_SDPA(query, key, value, attn_mask, dropout_p, is_causal, scale=scale, enable_gqa=enable_gqa)+++class TestWithTheOtherSdpaWrappers:+ """The report sits outside the ROCm guard and inside the cuDNN fallback, as `apply_monkeypatches` installs them.+ Each order is visible only in what gets reported, so a reordered startup fails here."""++ @pytest.mark.skipif(+ torch.version.cuda is None or torch.version.hip is not None or not torch.cuda.is_available(),+ reason="the cuDNN fallback exists on CUDA builds, and the reason needs a GPU",+ )+ def test_the_retry_after_a_cudnn_failure_is_reported_with_the_demotion(+ self, monkeypatch, caplog, preserve_sdpa_priority_order+ ):+ """Inside the fallback, the report sees the retry, which runs on the next kernel. The first call's failure+ is a double; the order, the demotion and the dispatcher are real. Measured on an RTX 4090 under Windows."""+ q = _qkv(1, 4, 128, 64, dtype=torch.float16, device="cuda")+ if not torch.backends.cuda.can_use_cudnn_attention(+ torch.backends.cuda.SDPAParams(q, q, q, None, 0.0, False, False)+ ):+ pytest.skip("this GPU has no cuDNN kernel for the call")+ kernel = _FailsOnceInCudnn()+ monkeypatch.setattr(F, "scaled_dot_product_attention", kernel)+ monkeypatch.setattr(attention, "_cudnn_demotions", 0)+ install_default_sdpa_priority(SDPBackend.CUDNN_ATTENTION)+ install_pinned_sdpa_kernel_report(SDPBackend.CUDNN_ATTENTION)+ install_cudnn_sdpa_fallback()+ caplog.clear()++ with caplog.at_level(logging.WARNING, logger=LOGGER), attention_caller("flux_denoise"):+ F.scaled_dot_product_attention(q, q, q)+ served = sdpa_backend_choice(q, q, q)++ reports = _reports(caplog)+ assert kernel.calls == 2, "the call and its retry"+ assert len(reports) == 2+ assert reports[0].startswith("cuDNN attention failed on")+ assert reports[1] == (+ "attention_backend 'cudnn' is not possible for attention in flux_denoise: cuDNN attention failed earlier "+ f"in this run and now ranks behind math; it runs on {served.name}."+ )++ @pytest.mark.skipif(+ torch.version.hip is None or not torch.cuda.is_available(),+ reason="the wide-head guard exists on ROCm builds, and the reason needs a GPU",+ )+ def test_a_wide_head_the_rocm_guard_sends_to_math_says_so(self, monkeypatch, caplog, preserve_sdpa_priority_order):+ """Outside the guard, the report sees the heads it sends to math whatever the dispatcher would pick. To be+ run on an RX 9060 XT."""+ monkeypatch.setattr(F, "scaled_dot_product_attention", TORCH_SDPA)+ monkeypatch.setattr(attention, "ROCM_FUSED_SDPA_MAX_HEAD_DIM", 256)+ install_rocm_sdpa_guard()+ install_default_sdpa_priority(SDPBackend.EFFICIENT_ATTENTION)+ install_pinned_sdpa_kernel_report(SDPBackend.EFFICIENT_ATTENTION)+ caplog.clear()+ q = _qkv(1, 1, 64, 512, dtype=torch.float16, device="cuda")++ with caplog.at_level(logging.WARNING, logger=LOGGER), attention_caller("flux_vae_decode"):+ F.scaled_dot_product_attention(q, q, q)++ assert _reports(caplog) == [+ "attention_backend 'efficient' is not possible for attention in flux_vae_decode: on ROCm, heads wider "+ "than 256 run on math (INVOKE_ROCM_FUSED_SDPA_MAX_HEAD_DIM sets the width); it runs on MATH."+ ]diff --git a/tests/backend/util/test_rocm_sdpa_head_dim_guard.py b/tests/backend/util/test_rocm_sdpa_head_dim_guard.pyindex 80df996e5f..7cc02e9f9c 100644--- a/tests/backend/util/test_rocm_sdpa_head_dim_guard.py+++ b/tests/backend/util/test_rocm_sdpa_head_dim_guard.py@@ -150,7 +150,7 @@ class TestGuard:assert F.scaled_dot_product_attention is originalassert any("NOT installed" in r.message for r in caplog.records)- def test_apply_monkeypatches_installs_the_guard(self, monkeypatch):+ def test_apply_monkeypatches_installs_the_guard(self, monkeypatch, preserve_sdpa_priority_order):from invokeai.app.util.startup_utils import apply_monkeypatchesoriginal = F.scaled_dot_product_attention@@ -192,7 +192,7 @@ def _install_chunking(monkeypatch.setattr(attention, "_rocm_cuda", lambda device_type: True)monkeypatch.setattr(attention, "SDPA_MATH_CHUNK_BYTES", budget)if materializes is not None:- monkeypatch.setattr(attention, "_materializes", lambda *args: materializes)+ monkeypatch.setattr(attention, "sdpa_runs_fused", lambda *args, **kwargs: not materializes)install_rocm_sdpa_guard()shapes.clear() # the install probe's own math callreturn shapesdiff --git a/tests/backend/util/test_sage_attention.py b/tests/backend/util/test_sage_attention.pyindex 3aef9f35c2..492fb60a61 100644--- a/tests/backend/util/test_sage_attention.py+++ b/tests/backend/util/test_sage_attention.py@@ -652,7 +652,9 @@ class TestInstall:assert any("no SageAttention kernel for cuda:1" in r.message for r in caplog.records)@pytest.mark.parametrize("backend", ["sage", "auto"])- def test_apply_monkeypatches_installs_sageattention_only_when_configured(self, monkeypatch, backend):+ def test_apply_monkeypatches_installs_sageattention_only_when_configured(+ self, monkeypatch, backend, preserve_sdpa_priority_order+ ):from invokeai.app.util.startup_utils import apply_monkeypatches_cuda_build(monkeypatch, {0: (8, 9)})diff --git a/tests/backend/util/test_sdpa_backend_choice.py b/tests/backend/util/test_sdpa_backend_choice.pynew file mode 100644index 0000000000..5a1b113ad4--- /dev/null+++ b/tests/backend/util/test_sdpa_backend_choice.py@@ -0,0 +1,86 @@+"""`sdpa_backend_choice`: the dispatcher's own answer to "which kernel would run this exact call?".++These run against torch's real CPU chooser, whose one fused kernel is flash. That chooser ignores the+priority order, so the order's part in the answer is pinned on CUDA, in the Krea-2 grouped-query tests+and the working-memory probe tests.+"""++import pytest+import torch+from torch.nn.attention import SDPBackend++from invokeai.backend.util.attention import sdpa_backend_choice, sdpa_runs_fused+from invokeai.backend.util.sdpa_scope import sdpa_policy++HQ, HKV, SEQ, HEAD_DIM = 8, 2, 32, 64+++def _qkv(kv_heads: int = HQ, device: str = "cpu", dtype: torch.dtype = torch.float32):+ q = torch.randn(1, HQ, SEQ, HEAD_DIM, device=device, dtype=dtype)+ kv = torch.randn(1, kv_heads, SEQ, HEAD_DIM, device=device, dtype=dtype)+ return q, kv, kv+++def test_a_plain_call_gets_the_fused_kernel_under_the_default_selection():+ assert sdpa_backend_choice(*_qkv()) == SDPBackend.FLASH_ATTENTION+ assert sdpa_runs_fused(*_qkv()) is True+++def test_a_window_in_force_is_part_of_the_answer_and_nothing_is_remembered():+ with sdpa_policy([SDPBackend.MATH]):+ assert sdpa_backend_choice(*_qkv()) == SDPBackend.MATH+ assert sdpa_runs_fused(*_qkv()) is False+ assert sdpa_backend_choice(*_qkv()) == SDPBackend.FLASH_ATTENTION+++def test_enable_gqa_is_part_of_the_question(cpu_flash_serves_grouped_query_attention):+ """Mismatched head counts reach a fused kernel only as grouped-query attention; asked without+ the flag, torch answers math for the same tensors."""+ if not cpu_flash_serves_grouped_query_attention:+ pytest.skip(+ "this torch's CPU flash kernel does not take grouped-query attention, so on CPU both answers are math"+ )+ q, k, v = _qkv(HKV)+ assert sdpa_backend_choice(q, k, v, enable_gqa=True) == SDPBackend.FLASH_ATTENTION+ assert sdpa_backend_choice(q, k, v, enable_gqa=False) == SDPBackend.MATH+++def test_with_math_enabled_the_query_is_silent(capfd):+ """It runs on every Krea-2 attention call and inside every guarded ROCm one, so it must not print."""+ q, k, v = _qkv(HKV)+ sdpa_backend_choice(*_qkv())+ sdpa_backend_choice(q, k, v, enable_gqa=False)+ assert capfd.readouterr().err == ""+++def test_with_math_disabled_a_call_no_kernel_takes_answers_none_without_torchs_noise(capfd):+ """Under an exclusive window torch's own query, finding nothing, re-runs every check in debug mode+ -- C++ warnings straight to stderr, which no Python filter reaches -- and raises. Asked once per+ attention call, that was thousands of lines a generation."""+ q, k, v = _qkv(HKV)+ with sdpa_policy([SDPBackend.FLASH_ATTENTION]):+ with pytest.raises(RuntimeError):+ torch.ops.aten._fused_sdp_choice(q, k, v, None, 0.0, False)+ assert capfd.readouterr().err != "", "pins why the helper must not ask torch directly here"++ assert sdpa_backend_choice(q, k, v) is None+ assert sdpa_runs_fused(q, k, v) is False+ assert capfd.readouterr().err == ""++[email protected](not torch.cuda.is_available(), reason="the per-kernel checks exist for CUDA tensors only")+class TestWithMathDisabledOnCuda:+ def test_the_first_permitted_kernel_that_takes_the_call_is_named(self):+ q, k, v = _qkv(device="cuda", dtype=torch.bfloat16)+ params = torch.backends.cuda.SDPAParams(q, k, v, None, 0.0, False, False)+ if not torch.backends.cuda.can_use_efficient_attention(params):+ pytest.skip("this build has no memory-efficient kernel for the shape")+ with sdpa_policy([SDPBackend.EFFICIENT_ATTENTION]):+ assert sdpa_backend_choice(q, k, v) == SDPBackend.EFFICIENT_ATTENTION++ def test_grouped_query_attention_no_permitted_kernel_takes_is_none_and_silent(self, capfd):+ """The `INVOKE_KREA2_SDPA_BACKEND=efficient` case: memory-efficient refuses grouped-query attention."""+ q, k, v = _qkv(HKV, device="cuda", dtype=torch.bfloat16)+ with sdpa_policy([SDPBackend.EFFICIENT_ATTENTION]):+ assert sdpa_backend_choice(q, k, v, enable_gqa=True) is None+ assert capfd.readouterr().err == ""diff --git a/tests/backend/util/test_sdpa_scope.py b/tests/backend/util/test_sdpa_scope.pyindex ef6082a1a4..c82d031c8f 100644--- a/tests/backend/util/test_sdpa_scope.py+++ b/tests/backend/util/test_sdpa_scope.py@@ -1,9 +1,11 @@"""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.+It sets the priority order every model runs under, once at startup, and demotes cuDNN in it when a+cuDNN call fails. Windows only set the enable flags, and torch's own `sdpa_kernel` saves and restores+those non-atomically, so two threads whose windows overlap leave them permanently changed. These pin+that `sdpa_policy` does not, because the leak escapes the code that caused it: every other model in+the process then picks kernels by the leaked flags, and `backend.util.attention` sizes working memory+from them."""import logging@@ -11,33 +13,33 @@ import threadingimport pytestimport torch-from torch.nn.attention import SDPBackend, sdpa_kernel+import torch.nn.functional as F+from torch.nn.attention import SDPBackend, _cur_sdpa_kernel_backends, _sdpa_kernel, sdpa_kernelimport 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,)+from invokeai.backend.util.sdpa_scope import demote_cudnn_attention, install_default_sdpa_priority, sdpa_policy+MATH_ONLY = (SDPBackend.MATH,)+EFFICIENT_ONLY = (SDPBackend.EFFICIENT_ATTENTION,)++# The orders a test expects depend on the layout of torch's own order, which differs by release; the+# `sdpa_orders` fixture (tests/conftest.py) writes them out per layout rather than reading them from the+# module under test.-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+def _global_state() -> tuple[list[int], set[SDPBackend]]:+ """Everything `sdpa_kernel` can mutate: the priority order and the per-backend enable flags."""return list(torch._C._get_sdp_priority_order()), set(_cur_sdpa_kernel_backends())+def _priority() -> list[SDPBackend]:+ return [SDPBackend(backend) for backend in torch._C._get_sdp_priority_order()]+++def _set_priority(order: list[SDPBackend]) -> None:+ torch._C._set_sdp_priority_order([int(backend) for backend in order])++@pytest.fixture(autouse=True)def _restore_global_sdpa_state():"""These mutate process-global torch state, and pytest-xdist gives a worker arbitrary files.@@ -48,25 +50,27 @@ def _restore_global_sdpa_state():priority, backends = _global_state()yieldtorch._C._set_sdp_priority_order(priority)- sdpa_kernel(list(backends)).__enter__()+ # The setter `sdpa_kernel` uses, not `sdpa_kernel` itself: an entered window that is then dropped is+ # finalized at once, and its exit puts back the very flags this is meant to undo.+ _sdpa_kernel(list(backends))-def _run_interleaved(scope, outer: tuple[SDPBackend, ...], inner: tuple[SDPBackend, ...], set_priority: bool = True):+def _run_interleaved(scope, outer: tuple[SDPBackend, ...], inner: tuple[SDPBackend, ...]):"""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.+ Returns what B 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):+ with scope(outer):a_inside.set()b_inside.wait(timeout=5)def b():a_inside.wait(timeout=5)- with scope(inner, set_priority=set_priority):+ with scope(inner):b_inside.set()a_left.wait(timeout=5)seen["b"] = _global_state()@@ -88,102 +92,220 @@ class TestTheLeakIsClosed: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)+ _run_interleaved(lambda backends: sdpa_kernel(list(backends)), MATH_ONLY, EFFICIENT_ONLY)assert _global_state() != before- def test_interleaved_windows_restore_the_global_state(self):+ def test_interleaved_windows_do_not_leave_backends_disabled(self):+ """The expensive leak: every later attention in the process falls to whatever the window left+ enabled -- math, the O(seq^2) path, for an exclusive MATH override."""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)+ _run_interleaved(sdpa_policy, MATH_ONLY, EFFICIENT_ONLY)assert _global_state() == beforeclass TestWhileAWindowIsOpen:- def test_the_open_policy_wins_over_a_later_one(self):+ def test_the_open_window_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 isrestored exactly once. A later window must not overwrite the open one -- overwriting is howthe 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+ seen = _run_interleaved(sdpa_policy, MATH_ONLY, EFFICIENT_ONLY)+ assert seen["b"][1] == set(MATH_ONLY)- def test_a_single_window_applies_its_policy_and_restores_it(self):+ def test_a_single_window_applies_its_backends_and_restores_them(self):before = _global_state()- with sdpa_policy(EXCLUSIVE, set_priority=False):- _, enabled = _global_state()- assert enabled == set(EXCLUSIVE)+ with sdpa_policy(MATH_ONLY):+ assert set(_cur_sdpa_kernel_backends()) == set(MATH_ONLY)assert _global_state() == beforedef test_nesting_in_one_thread_restores_once(self):before = _global_state()- with sdpa_policy(KREA2) as outer_owns:+ with sdpa_policy(MATH_ONLY):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.+ with sdpa_policy(EFFICIENT_ONLY):+ # The inner window must neither apply its own backends nor restore anything: the outer+ # one is still open and owns the flags.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() == beforedef 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):+ with sdpa_policy(MATH_ONLY):raise RuntimeError("boom")assert _global_state() == before+ def test_a_window_leaves_the_order_alone(self, sdpa_orders):+ """The order is the process's: a window that restored it would undo a cuDNN demotion that+ happened while it was open."""+ _set_priority(sdpa_orders.torch_own)+ install_default_sdpa_priority()+ with sdpa_policy(MATH_ONLY):+ assert demote_cudnn_attention() is True+ assert _priority() == sdpa_orders.torch_own+-class TestAWindowThatDidNotApply:- """An exclusive override exists so that a completed run proves which kernel served it.+class TestTheProcessDefault:+ """The order every model in the process runs under, installed once at startup.- 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.+ torch's own order ranks cuDNN behind the always-eligible math kernel, so it practically never runs;+ this one puts it second, behind flash, which leads wherever a build has it."""- 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+ def test_it_ranks_flash_cudnn_efficient_math_ahead_of_the_rest(self, sdpa_orders):+ _set_priority(sdpa_orders.torch_own)+ install_default_sdpa_priority()+ assert _priority() == sdpa_orders.installed++ def test_a_backend_outside_the_ranking_is_kept_behind_it(self):+ """OVERRIDEABLE is the backend torch 2.8 and newer list beyond the four ranked ones. Starting it+ at the front shows it moved behind the ranking rather than happening to be last already."""+ _set_priority(+ [+ SDPBackend.OVERRIDEABLE,+ SDPBackend.MATH,+ SDPBackend.EFFICIENT_ATTENTION,+ SDPBackend.CUDNN_ATTENTION,+ SDPBackend.FLASH_ATTENTION,+ ]+ )+ install_default_sdpa_priority()+ assert _priority() == [+ SDPBackend.FLASH_ATTENTION,+ SDPBackend.CUDNN_ATTENTION,+ SDPBackend.EFFICIENT_ATTENTION,+ SDPBackend.MATH,+ SDPBackend.OVERRIDEABLE,+ ]++ def test_installing_it_twice_is_the_same_as_once(self, sdpa_orders):+ _set_priority(sdpa_orders.torch_own)+ install_default_sdpa_priority()+ install_default_sdpa_priority()+ assert _priority() == sdpa_orders.installed++ def test_the_enable_flags_are_left_alone(self):+ torch.backends.cuda.enable_cudnn_sdp(False)+ before = set(_cur_sdpa_kernel_backends())+ install_default_sdpa_priority()+ assert set(_cur_sdpa_kernel_backends()) == before+ assert SDPBackend.CUDNN_ATTENTION not in before++ @pytest.mark.parametrize("change", ["removed", "signature changed"])+ def test_a_torch_whose_private_priority_api_changed_keeps_its_order_and_says_so(+ self, change, monkeypatch, caplog, sdpa_orders+ ):+ def changed_signature(order, extra):+ raise AssertionError("never reached: the call itself fails on the signature")++ _set_priority(sdpa_orders.torch_own)+ # Scoped, not test-wide: this file's teardown restores the order through the very call replaced here.+ with monkeypatch.context() as patch, caplog.at_level(logging.WARNING, logger=sdpa_scope.logger.name):+ if change == "removed":+ patch.delattr(torch._C, "_set_sdp_priority_order")+ else:+ patch.setattr(torch._C, "_set_sdp_priority_order", changed_signature)+ install_default_sdpa_priority()++ assert _priority() == sdpa_orders.torch_ownassert 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]+ assert "_set_sdp_priority_order" in caplog.records[0].message++ def test_startup_installs_it_and_the_cudnn_fallback(self, monkeypatch, sdpa_orders):+ import invokeai.backend.util.attention as attention+ from invokeai.app.util.startup_utils import apply_monkeypatches++ # Pin the entry points apply_monkeypatches rebinds so monkeypatch restores them afterwards.+ monkeypatch.setattr(F, "scaled_dot_product_attention", F.scaled_dot_product_attention)+ monkeypatch.setattr(torch.cuda, "empty_cache", torch.cuda.empty_cache)+ # The fallback installs on CUDA builds only; look like one on a CPU-only runner as well.+ monkeypatch.setattr(torch.version, "cuda", "13.0")+ monkeypatch.setattr(torch.version, "hip", None)+ _set_priority(sdpa_orders.torch_own)++ apply_monkeypatches()++ assert _priority() == sdpa_orders.installed+ assert getattr(F.scaled_dot_product_attention, attention._CUDNN_FALLBACK_SENTINEL, False)++ @pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA is required to exercise the SDPA dispatcher")+ def test_a_call_cudnn_cannot_serve_falls_through_to_the_next_kernel(self):+ """The property the whole order rests on: a kernel that cannot serve a call is skipped, not+ raised on. If a future torch made a ranked order raise instead, ranking cuDNN second would turn+ every call it cannot serve into a failed generation."""+ # fp32 is refused by the fused kernels, which is a portable way to make cuDNN unusable on a card+ # where it otherwise works.+ t = torch.randn(1, 24, 512, 128, device="cuda", dtype=torch.float32)+ params = torch.backends.cuda.SDPAParams(t, t, t, None, 0.0, False, False)+ if torch.backends.cuda.can_use_cudnn_attention(params):+ pytest.skip("This build serves fp32 with cuDNN, so it cannot stand in for an unusable backend")++ install_default_sdpa_priority()+ out = F.scaled_dot_product_attention(t, t, t)++ assert torch.isfinite(out).all()+++class TestAPinnedKernel:+ """`attention_backend: cudnn | flash | efficient | math` ranks that kernel first, ahead of the process order.++ Never exclusive: the rest of the order stays behind it, so a call the pinned kernel cannot serve still has every+ other kernel to go to.+ """++ @pytest.mark.parametrize(+ "pinned",+ [SDPBackend.EFFICIENT_ATTENTION, SDPBackend.MATH, SDPBackend.CUDNN_ATTENTION, SDPBackend.FLASH_ATTENTION],+ ids=["efficient", "math", "cudnn", "flash"],+ )+ def test_it_ranks_first_and_the_process_order_follows(self, pinned, sdpa_orders):+ """The expected order per pinned kernel and torch layout is written out in `sdpa_orders`. Flash already+ leads the process order, so pinning it changes nothing but the report."""+ _set_priority(sdpa_orders.torch_own)+ assert install_default_sdpa_priority(pinned) is True+ assert _priority() == sdpa_orders.pinned[pinned]++ def test_pinning_twice_is_the_same_as_once_and_leaves_the_flags_alone(self, sdpa_orders):+ _set_priority(sdpa_orders.torch_own)+ torch.backends.cuda.enable_cudnn_sdp(False)+ flags = set(_cur_sdpa_kernel_backends())+ install_default_sdpa_priority(SDPBackend.MATH)+ install_default_sdpa_priority(SDPBackend.MATH)+ assert _priority() == sdpa_orders.pinned[SDPBackend.MATH]+ assert set(_cur_sdpa_kernel_backends()) == flags++ def test_a_pinned_cudnn_that_fails_is_demoted_behind_math_like_the_default(self, sdpa_orders):+ _set_priority(sdpa_orders.torch_own)+ install_default_sdpa_priority(SDPBackend.CUDNN_ATTENTION)+ assert sdpa_scope.cudnn_attention_demoted() is False+ assert demote_cudnn_attention() is True+ assert sdpa_scope.cudnn_attention_demoted() is True+ assert _priority() == sdpa_orders.torch_own+++class TestDemotingCudnn:+ """Demoting cuDNN moves it directly behind math, which gives back torch's own order."""++ def test_cudnn_moves_directly_behind_math_and_nothing_else_moves(self, sdpa_orders):+ _set_priority(sdpa_orders.torch_own)+ install_default_sdpa_priority()+ assert demote_cudnn_attention() is True+ assert _priority() == sdpa_orders.torch_own++ def test_only_the_first_of_two_demotions_moves_it(self, sdpa_orders):+ """Two GPU workers whose cuDNN calls fail at once: exactly one of them demotes, and warns."""+ _set_priority(sdpa_orders.torch_own)+ install_default_sdpa_priority()+ assert [demote_cudnn_attention(), demote_cudnn_attention()] == [True, False]+ assert _priority() == sdpa_orders.torch_own++ def test_the_enable_flags_are_left_alone(self):+ install_default_sdpa_priority()+ torch.backends.cuda.enable_flash_sdp(False)+ before = set(_cur_sdpa_kernel_backends())+ demote_cudnn_attention()+ assert set(_cur_sdpa_kernel_backends()) == beforediff --git a/tests/conftest.py b/tests/conftest.pyindex 87a7e61040..dadf66d749 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -7,9 +7,13 @@import loggingimport shutilimport sys+import warningsfrom pathlib import Path+from typing import NamedTupleimport pytest+import torch+from torch.nn.attention import SDPBackend, sdpa_kernelfrom invokeai.app.services.auth import password_utilsfrom invokeai.app.services.board_image_records.board_image_records_default import BoardImageRecordStorage@@ -66,6 +70,47 @@ from tests.test_nodes import TestEventServiceif is_windows_arm64():install_cuda_stream_capture_shim()+# torch's own SDPA priority order, read as the session starts and before anything in it installs one. It is torch's+# state, not code under test, and its layout differs by release, so `sdpa_orders` picks literal expectations by it.+try:+ _TORCH_SDPA_ORDER_AT_START: tuple[SDPBackend, ...] | None = tuple(+ SDPBackend(backend) for backend in torch._C._get_sdp_priority_order()+ )+except Exception: # a torch that renamed its private priority API; `sdpa_orders` skips+ _TORCH_SDPA_ORDER_AT_START = None++_FLASH, _EFFICIENT, _MATH, _CUDNN, _OVERRIDEABLE = (+ SDPBackend.FLASH_ATTENTION,+ SDPBackend.EFFICIENT_ATTENTION,+ SDPBackend.MATH,+ SDPBackend.CUDNN_ATTENTION,+ SDPBackend.OVERRIDEABLE,+)+# Each layout of torch's own order the suite knows -> the order once InvokeAI's ranking is installed on it.+_INSTALLED_SDPA_ORDER_BY_TORCH_ORDER = {+ # torch 2.8 and newer: all five backends.+ (_FLASH, _EFFICIENT, _MATH, _CUDNN, _OVERRIDEABLE): (_FLASH, _CUDNN, _EFFICIENT, _MATH, _OVERRIDEABLE),+ # torch 2.7 (macOS, Linux aarch64): a five-slot array initialised with four backends, so the last slot is 0,+ # which is MATH again. The four ranked entries are written over the first four slots and the fifth stays.+ (_FLASH, _EFFICIENT, _MATH, _CUDNN, _MATH): (_FLASH, _CUDNN, _EFFICIENT, _MATH, _MATH),+}+# The same layouts -> the order once `attention_backend` pins each kernel ahead of InvokeAI's ranking.+_PINNED_SDPA_ORDERS_BY_TORCH_ORDER = {+ (_FLASH, _EFFICIENT, _MATH, _CUDNN, _OVERRIDEABLE): {+ _FLASH: (_FLASH, _CUDNN, _EFFICIENT, _MATH, _OVERRIDEABLE),+ _CUDNN: (_CUDNN, _FLASH, _EFFICIENT, _MATH, _OVERRIDEABLE),+ _EFFICIENT: (_EFFICIENT, _FLASH, _CUDNN, _MATH, _OVERRIDEABLE),+ _MATH: (_MATH, _FLASH, _CUDNN, _EFFICIENT, _OVERRIDEABLE),+ },+ # Here, too, only the four ranked slots are written, and the fifth stays MATH.+ (_FLASH, _EFFICIENT, _MATH, _CUDNN, _MATH): {+ _FLASH: (_FLASH, _CUDNN, _EFFICIENT, _MATH, _MATH),+ _CUDNN: (_CUDNN, _FLASH, _EFFICIENT, _MATH, _MATH),+ _EFFICIENT: (_EFFICIENT, _FLASH, _CUDNN, _MATH, _MATH),+ _MATH: (_MATH, _FLASH, _CUDNN, _EFFICIENT, _MATH),+ },+}+# Fixtures that put a test on the backend under test, which `-m uses_database` selects._DATABASE_FIXTURES = {"empty_database", "database"}@@ -92,6 +137,63 @@ def _clear_deferred_empty_cache():TorchDevice._empty_cache_deferred.clear()+def preserve_sdpa_priority_order():+ """torch's SDPA priority order is process-global, and an xdist worker runs arbitrary files in one process.++ For tests that change it -- `apply_monkeypatches` and `install_default_sdpa_priority` do -- so a later test does+ not pick kernels by an order it never asked for.+ """+ saved = torch._C._get_sdp_priority_order()+ yield+ torch._C._set_sdp_priority_order(saved)+++class SdpaOrders(NamedTuple):+ # torch's own order, which demoting cuDNN gives back.+ torch_own: list[SDPBackend]+ # The order once `install_default_sdpa_priority` has ranked flash, cuDNN, memory-efficient and math first.+ installed: list[SDPBackend]+ # The order once `install_default_sdpa_priority(pinned)` has ranked each kernel ahead of that.+ pinned: dict[SDPBackend, list[SDPBackend]]+++def sdpa_orders() -> SdpaOrders:+ """The literal SDPA priority orders a test expects on this torch, chosen by the layout of torch's own order."""+ installed = _INSTALLED_SDPA_ORDER_BY_TORCH_ORDER.get(_TORCH_SDPA_ORDER_AT_START)+ pinned = _PINNED_SDPA_ORDERS_BY_TORCH_ORDER.get(_TORCH_SDPA_ORDER_AT_START)+ if _TORCH_SDPA_ORDER_AT_START is None or installed is None or pinned is None:+ layout = None if _TORCH_SDPA_ORDER_AT_START is None else [b.name for b in _TORCH_SDPA_ORDER_AT_START]+ pytest.skip(+ f"torch {torch.__version__} has an SDPA priority order the suite has no expectations for ({layout}); "+ "add its layout to _INSTALLED_SDPA_ORDER_BY_TORCH_ORDER and _PINNED_SDPA_ORDERS_BY_TORCH_ORDER in "+ "tests/conftest.py"+ )+ return SdpaOrders(+ torch_own=list(_TORCH_SDPA_ORDER_AT_START),+ installed=list(installed),+ pinned={kernel: list(order) for kernel, order in pinned.items()},+ )++[email protected](scope="session")+def cpu_flash_serves_grouped_query_attention() -> bool:+ """Whether this torch's CPU flash kernel takes grouped-query attention. torch 2.7's does not.++ Asked by running it, with only flash enabled, so the answer comes from torch and not from the code under+ test. A refusal arrives as warnings ahead of the error; they are this probe's own, so they are muted.+ """+ query, key_value = torch.zeros(1, 4, 8, 16), torch.zeros(1, 2, 8, 16)+ try:+ with warnings.catch_warnings(), sdpa_kernel(SDPBackend.FLASH_ATTENTION):+ warnings.simplefilter("ignore")+ torch._C._nn.scaled_dot_product_attention(query, key_value, key_value, enable_gqa=True)+ except RuntimeError:+ return False+ return True++_PRODUCTION_BCRYPT_ROUNDS = password_utils.BCRYPT_ROUNDSdiff --git a/tests/test_config.py b/tests/test_config.pyindex 041bd7835b..d61f70a854 100644--- a/tests/test_config.py+++ b/tests/test_config.py@@ -127,6 +127,21 @@ def test_attention_backend_defaults_to_auto_and_loads_from_yaml(tmp_path: Path,assert load_and_migrate_config(temp_config_file).attention_backend == "sage"[email protected]("kernel", ["cudnn", "flash", "efficient", "math"])+def test_attention_backend_pins_a_pytorch_kernel_from_yaml(tmp_path: Path, patch_rootdir: None, kernel: str) -> None:+ temp_config_file = tmp_path / "temp_invokeai.yaml"+ temp_config_file.write_text(f'schema_version: "4.0.3"\nattention_backend: {kernel}\n')++ assert load_and_migrate_config(temp_config_file).attention_backend == kernel+++def test_attention_backend_rejects_a_kernel_it_does_not_know() -> None:+ # `default` is an INVOKE_KREA2_SDPA_BACKEND value, not an attention_backend one.+ for value in ("xformers", "default"):+ with pytest.raises(ValidationError):+ InvokeAIAppConfig(attention_backend=value)++def test_load_config_from_root_reads_that_roots_file_and_writes_nothing(tmp_path: Path, patch_rootdir: None) -> None:root = tmp_path / "install"root.mkdir()