Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(rocm): route wide-head attention to the math SDPA kernel
Lincoln Stein198d9853c651
diff --git a/docs/src/content/docs/start-here/system-requirements.mdx b/docs/src/content/docs/start-here/system-requirements.mdxindex 7874158ecb..2488357c93 100644--- a/docs/src/content/docs/start-here/system-requirements.mdx+++ b/docs/src/content/docs/start-here/system-requirements.mdx@@ -155,6 +155,16 @@ If, after restarting the app, this doesn't improve your performance, either rest(for example `MIOPEN_FIND_MODE=NORMAL` to let MIOpen re-tune its kernel database).:::+:::note[Wide-head attention runs on the math kernel]+ On ROCm builds Invoke routes attention whose head dimension exceeds 256 to PyTorch's math kernel.+ The fused kernels return wrong output there on torch 2.13 / ROCm 7.2 (measured on a W7900), which+ showed up as black or noisy images from the image VAEs - their mid-block attention is one 512-wide+ head. The math kernel materializes the attention matrix, so large untiled VAE decodes reserve+ more VRAM (about 4 GB at 1024px, 21 GB at 1536px) and may push other models out of the cache;+ tiled decoding keeps that bounded. Export `INVOKE_ROCM_FUSED_SDPA_MAX_HEAD_DIM` to raise the+ threshold on a build whose fused kernels are known to be correct.+:::+Run `rocm-smi` on your system's command line verify that drivers and ROCm are installed. If this command fails, or doesn't report versions, you will need to install them.Go to the [ROCm Documentation] and carefully follow the instructions for your system to get everything installed.diff --git a/invokeai/app/util/startup_utils.py b/invokeai/app/util/startup_utils.pyindex a0c760996f..8a5c49399c 100644--- a/invokeai/app/util/startup_utils.py+++ b/invokeai/app/util/startup_utils.py@@ -161,6 +161,12 @@ def apply_monkeypatches() -> None:install_peer_aware_empty_cache()+ # ROCm's fused SDPA kernels return wrong output for heads wider than 256 (the VAE mid-block+ # attention), turning decodes into noise or black images. Route those calls to the math kernel.+ from invokeai.backend.util.attention import install_rocm_sdpa_head_dim_guard++ install_rocm_sdpa_head_dim_guard()+def register_mime_types() -> None:"""Register additional mime types for windows."""diff --git a/invokeai/backend/util/attention.py b/invokeai/backend/util/attention.pyindex 1ffa8abef7..6be3a663d8 100644--- a/invokeai/backend/util/attention.py+++ b/invokeai/backend/util/attention.py@@ -4,9 +4,11 @@ Utility routine used for autodetection of optimal slice sizefor attention mechanism."""+import osimport threadingimport warnings-from functools import lru_cache+from functools import lru_cache, wraps+from typing import Anyimport psutilimport torch@@ -48,11 +50,12 @@ def auto_detect_slice_size(latents: torch.Tensor) -> str:# not a property of FLUX.2 -- it is a property of the build, the device, the dtype, the head dim and# whether an attention mask was passed, and the rules differ per build in ways that are not worth# hard-coding. Measured, for the FLUX.2 VAE's 512-wide mid-block head: CUDA takes it on the-# memory-efficient kernel, ROCm/gfx1100 drops to `math`, and ROCm/gfx1201 takes it on flash. Two-# cards of the same vendor on the same torch disagree -- so "ROCm materializes" is not a fact to-# hard-code either. Masks are not a discriminator anywhere measured. A working-memory estimate that-# assumes the fused path is only correct on the build it was measured on, which is why the helpers-# below ask instead of assuming.+# memory-efficient kernel; on ROCm the answer varied by card and torch build (gfx1100 on torch 2.10+# reported `math` from a probe, gfx1201 took it on flash) -- and on torch 2.13 the fused kernels+# that do accept it return wrong output, see `ROCM_FUSED_SDPA_MAX_HEAD_DIM`. So on ROCm the wide+# head is decided by policy (`rocm_sdpa_uses_math_kernel`), and everywhere else, and for every+# narrower head, the helpers below ask torch instead of assuming. Masks are not a discriminator+# anywhere measured.# Peak *reserved* bytes per element of the materialized score matrix, with `SDPBackend.MATH` forced,# each point in a fresh process. The same figures hold for bf16, fp16 and fp32 inputs, because the@@ -84,6 +87,147 @@ _FUSED_SDP_CHOICES = frozenset(# 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+# the inputs' alignment, and the default dispatch lands on one of them. head_dim 256 and below is+# correct in every backend, and the math backend is correct at any width. 512 is exactly the+# mid-block self-attention of the FLUX.2 VAE, the SD/SDXL AutoencoderKL and the FLUX.1 autoencoder:+# one head over the full channel width -- which is why the failure looked like a broken VAE. Because+# which kernel runs depends on the caching allocator's state, a decode that was fine turns into+# noise or a black image after enough allocation churn (measured: 14 of 30 decodes of the same+# latents in a fresh single-GPU process) and stays that way until the memory layout changes again.+#+# The guard keys on the torch build, not the card: only gfx1100 was measured, and a wrong image is+# the worse failure, so every ROCm device takes the math kernel for wide heads until a build is+# known to be fixed. The cost is a materialized score matrix for those calls (~4.3 GiB for a 1024px+# VAE decode, ~21 GiB at 1536px; the working-memory estimators price it). A user on a build where+# the fused kernels are correct can raise the threshold, or switch the guard off with a large value:+# INVOKE_ROCM_FUSED_SDPA_MAX_HEAD_DIM=100000+_ROCM_FUSED_SDPA_MAX_HEAD_DIM_DEFAULT = 256+_ROCM_FUSED_SDPA_MAX_HEAD_DIM_ENV = "INVOKE_ROCM_FUSED_SDPA_MAX_HEAD_DIM"+++def _read_rocm_fused_sdpa_max_head_dim() -> int:+ raw = os.environ.get(_ROCM_FUSED_SDPA_MAX_HEAD_DIM_ENV)+ if raw is None:+ return _ROCM_FUSED_SDPA_MAX_HEAD_DIM_DEFAULT+ try:+ return int(raw)+ except ValueError:+ InvokeAILogger.get_logger(__name__).warning(+ f"{_ROCM_FUSED_SDPA_MAX_HEAD_DIM_ENV}={raw!r} is not an integer; "+ f"keeping the default of {_ROCM_FUSED_SDPA_MAX_HEAD_DIM_DEFAULT}."+ )+ return _ROCM_FUSED_SDPA_MAX_HEAD_DIM_DEFAULT+++ROCM_FUSED_SDPA_MAX_HEAD_DIM = _read_rocm_fused_sdpa_max_head_dim()++_IS_ROCM = torch.version.hip is not None+_ROCM_SDPA_GUARD_SENTINEL = "_invokeai_rocm_head_dim_guard"+++def rocm_sdpa_uses_math_kernel(device_type: str, head_dim: int) -> bool:+ """True when the ROCm guard sends an SDPA call of this shape to the math kernel.++ The single rule shared by the guard itself and by the working-memory estimators, so a reserved+ score matrix always corresponds to a kernel that really runs.+ """+ return _IS_ROCM and device_type == "cuda" and head_dim > ROCM_FUSED_SDPA_MAX_HEAD_DIM+++def _math_sdpa(+ 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,+) -> torch.Tensor:+ """`F.scaled_dot_product_attention` on the math kernel, without touching torch's global backend flags."""+ if attn_mask is not None and attn_mask.dtype == torch.bool:+ # The Python entry point turns a boolean mask (True = attend) into an additive one before+ # dispatching; the aten op expects the additive form.+ attn_mask = torch.zeros_like(attn_mask, dtype=query.dtype).masked_fill(~attn_mask, float("-inf"))+ return torch.ops.aten._scaled_dot_product_attention_math(+ query, key, value, attn_mask, dropout_p, is_causal, None, scale=scale, enable_gqa=enable_gqa+ )[0]+++def install_rocm_sdpa_head_dim_guard() -> None:+ """Rebind ``torch.nn.functional.scaled_dot_product_attention`` so that, on ROCm, a call whose+ head_dim exceeds ``ROCM_FUSED_SDPA_MAX_HEAD_DIM`` runs the math kernel instead of a fused one.++ The math kernel is invoked as the aten op directly rather than through ``sdpa_kernel(MATH)``:+ that context manager writes torch's process-global backend flags, so on a multi-GPU install it+ would also decide the kernel for whatever the other worker is running (see `sdpa_scope`). The+ op call touches no shared state, so two sessions can take different paths at once.++ Callers that resolve the function through the module at call time inherit the guard -- that is+ diffusers' `AttnProcessor2_0` and its attention dispatcher, and every autoencoder in this repo.+ Two differences from the fused path for the routed calls only: torch's argument validation is+ skipped (an invalid mask dtype is not rejected up front), and the aten op is not on autocast's+ cast list, so fp32 inputs under ``torch.autocast`` compute in fp32 instead of the autocast+ dtype. No current wide-head caller runs under autocast.++ Idempotent; a no-op on non-ROCm builds. If the aten op is missing or rejects the call shape+ this wrapper relies on, the guard is not installed and the log says so, rather than failing+ inside the first generation. Installed once at startup via ``apply_monkeypatches``.+ """+ if not _IS_ROCM:+ return+ functional = torch.nn.functional+ if getattr(functional.scaled_dot_product_attention, _ROCM_SDPA_GUARD_SENTINEL, False):+ return+ logger = InvokeAILogger.get_logger(__name__)+ try:+ probe = torch.zeros((1, 1, 2, 4))+ _math_sdpa(probe, probe, probe, torch.ones((2, 2), dtype=torch.bool), 0.0, False, None, False)+ except Exception as e:+ logger.warning(+ f"ROCm head-dim SDPA guard NOT installed: the math attention op rejected the call shape ({e!r}). "+ f"Attention with head_dim > {ROCM_FUSED_SDPA_MAX_HEAD_DIM} may return wrong output on this build."+ )+ return+ original = functional.scaled_dot_product_attention++ @wraps(original)+ def guarded_scaled_dot_product_attention(+ 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:+ if not rocm_sdpa_uses_math_kernel(query.device.type, query.shape[-1]):+ return original(+ query, key, value, attn_mask, dropout_p, is_causal, *args, scale=scale, enable_gqa=enable_gqa, **kwargs+ )+ if args or kwargs:+ # A torch that grew new SDPA arguments would need the math call updated to match;+ # refuse rather than silently drop them.+ raise TypeError(+ f"scaled_dot_product_attention received arguments the ROCm head-dim guard does not forward: "+ f"{args!r}, {sorted(kwargs)!r}"+ )+ return _math_sdpa(query, key, value, attn_mask, dropout_p, is_causal, scale, enable_gqa)++ setattr(guarded_scaled_dot_product_attention, _ROCM_SDPA_GUARD_SENTINEL, True)+ functional.scaled_dot_product_attention = guarded_scaled_dot_product_attention+ logger.info(+ f"ROCm: attention with head_dim > {ROCM_FUSED_SDPA_MAX_HEAD_DIM} runs on the math SDPA kernel "+ f"(the fused kernels return wrong output there; {_ROCM_FUSED_SDPA_MAX_HEAD_DIM_ENV} overrides the threshold)."+ )++_DISPATCH_TORCH = "torch"_DISPATCH_FUSED = "fused"_DISPATCH_MATH = "math"@@ -230,6 +374,10 @@ def sdpa_score_matrix_bytes(return _log_and_return(score_matrix_bytes, device, head_dim, "the diffusers backend")# _DISPATCH_TORCH: diffusers forwards to `F.scaled_dot_product_attention`, so torch decides.+ if rocm_sdpa_uses_math_kernel(device.type, head_dim):+ # `install_rocm_sdpa_head_dim_guard` sends these calls to the math kernel regardless of+ # what torch's dispatch would pick, so the probe would answer for a kernel that never runs.+ return _log_and_return(score_matrix_bytes, device, head_dim, "the ROCm head-dim guard")if not _torch_sdpa_materializes_score_matrix(device.type, device.index, dtype, head_dim, has_attn_mask):return 0return _log_and_return(score_matrix_bytes, device, head_dim, "this torch build")diff --git a/invokeai/backend/util/vae_working_memory.py b/invokeai/backend/util/vae_working_memory.pyindex ec26765804..176f7ab669 100644--- a/invokeai/backend/util/vae_working_memory.py+++ b/invokeai/backend/util/vae_working_memory.py@@ -12,11 +12,33 @@ from invokeai.backend.flux.modules.autoencoder import AutoEncoder, resolve_tile_from invokeai.backend.util.attention import sdpa_score_matrix_bytesfrom invokeai.backend.util.devices import TorchDevice+# The diffusers AutoencoderKL (SD1/SDXL, SD3, CogView4) and the FLUX.1 AutoEncoder run the same+# mid-block self-attention as the FLUX.2 VAE: one head over the 512-channel width, on the+# 8x-downsampled grid. Where that attention runs on the math kernel (see `sdpa_score_matrix_bytes`)+# its score matrix is the dominant term for a large untiled image, exactly as it is for FLUX.2;+# `_vae_mid_block_score_matrix_bytes` prices it for those estimators the same way. The video VAEs+# (Wan, Qwen-Image) need no such term: their ROCm constants below were measured with math attention.+_CLASSIC_VAE_MID_BLOCK_HEADS = 1+_CLASSIC_VAE_MID_BLOCK_HEAD_DIM = 512+_WAN_VAE_SINGLE_FRAME_DECODE_SCALING_CONSTANT = 2900_WAN_VAE_VIDEO_DECODE_SCALING_CONSTANT_A14B = 6500_WAN_VAE_VIDEO_DECODE_SCALING_CONSTANT_TI2V = 7000+def _vae_mid_block_score_matrix_bytes(+ out_h: int, out_w: int, dtype: torch.dtype, batch_size: int = 1, device: torch.device | None = None+) -> int:+ """Score-matrix bytes for a classic VAE's mid-block attention over an `out_h` x `out_w` output."""+ return sdpa_score_matrix_bytes(+ device=device if device is not None else TorchDevice.choose_torch_device(),+ dtype=dtype,+ num_heads=_CLASSIC_VAE_MID_BLOCK_HEADS * batch_size,+ head_dim=_CLASSIC_VAE_MID_BLOCK_HEAD_DIM,+ seq_len=(out_h // LATENT_SCALE_FACTOR) * (out_w // LATENT_SCALE_FACTOR),+ )++def estimate_vae_working_memory_sd15_sdxl(operation: Literal["encode", "decode"],image_tensor: torch.Tensor,@@ -52,6 +74,12 @@ def estimate_vae_working_memory_sd15_sdxl(w = latent_scale_factor_for_operation * image_tensor.shape[-1]working_memory = h * w * element_size * scaling_constant+ if isinstance(vae, AutoencoderKL):+ # max, not sum: the mid-block attention and the full-resolution convolutions peak in+ # different phases of the forward (see the FLUX.2 estimator for the measurements).+ score_dtype = torch.float32 if fp32 else next(vae.parameters()).dtype+ working_memory = max(working_memory, _vae_mid_block_score_matrix_bytes(h, w, score_dtype))+if fp32:# If we are running in FP32, then we should account for the likely increase in model size (~250MB).working_memory += 250 * 2**20@@ -74,7 +102,9 @@ def estimate_vae_working_memory_cogview4(scaling_constant = 2200 if operation == "decode" else 1100working_memory = h * w * element_size * scaling_constant- return int(working_memory)+ # max, not sum: the mid-block attention and the full-resolution convolutions peak in different+ # phases of the forward (see the FLUX.2 estimator for the measurements).+ return int(max(working_memory, _vae_mid_block_score_matrix_bytes(h, w, next(vae.parameters()).dtype)))# What a tiled decode does *not* bound: the assembled image, several times over, per output pixel.@@ -148,10 +178,15 @@ def estimate_vae_working_memory_flux(# A 25% margin for tile overlap and the number of tiles, mirroring the SD1/SDXL estimator.working_memory = tile_h * tile_w * element_size * scaling_constant * 1.25working_memory += out_h * out_w * _IMAGE_CHANNELS * (_FLUX_VAE_TILED_IMAGE_COPIES * element_size + 1)+ score_h, score_w = tile_h, tile_welse:working_memory = out_h * out_w * element_size * scaling_constant+ score_h, score_w = out_h, out_w- return int(working_memory)+ # max, not sum: the mid-block attention and the full-resolution convolutions peak in different+ # phases of the forward (see the FLUX.2 estimator for the measurements).+ dtype = next(vae.parameters()).dtype+ return int(max(working_memory, _vae_mid_block_score_matrix_bytes(score_h, score_w, dtype)))# The FLUX.2 VAE runs one attention block at the bottom of the encoder and one at the top of the@@ -226,14 +261,15 @@ def estimate_vae_working_memory_flux2(That linear term holds only while ``AutoencoderKLFlux2``'s mid-block attention runs through afused SDPA kernel, which is what CUDA does (verified: the memory-efficient kernel takes the- 512-wide head, and measured peak stays linear from 512 to 1536px). A build with no fused kernel- for the shapes -- ROCm/gfx1100 reports ``math`` for this 512-wide head, though gfx1201 takes it- on flash, and MPS has no fused kernel at all -- materializes a (pixels/8)^2 score matrix, which- grows quadratically and overtakes the linear term somewhere past 1280px. We ask torch which path- applies rather than assuming, so the estimate is right on all of them.+ 512-wide head, and measured peak stays linear from 512 to 1536px). Where the math kernel runs+ instead -- every ROCm build, by policy, because its fused kernels return wrong output for this+ head width (see ``rocm_sdpa_uses_math_kernel``), and MPS, which has no fused kernel at all -- it+ materializes a (pixels/8)^2 score matrix, which grows quadratically and overtakes the linear+ term somewhere past 1280px. ``sdpa_score_matrix_bytes`` applies the ROCm rule and asks torch+ for everything else, so the estimate is right on all of them.The two terms are independent: a build can have a fused kernel and still need the larger- convolution constant, which is exactly what gfx1201 does. They also do not add -- see the+ convolution constant (gfx1201 did, before the ROCm rule above). They also do not add -- see the``max`` at the end of this function for why, and for the measurements behind it. (Unlike the transformer, this attention does not go throughdiffusers' attention dispatcher -- ``AttnProcessor2_0`` calls ``F.scaled_dot_product_attention``itself -- so torch's own answer is the whole answer here.)@@ -553,4 +589,6 @@ def estimate_vae_working_memory_sd3(working_memory = h * w * element_size * scaling_constant- return int(working_memory)+ # max, not sum: the mid-block attention and the full-resolution convolutions peak in different+ # phases of the forward (see the FLUX.2 estimator for the measurements).+ return int(max(working_memory, _vae_mid_block_score_matrix_bytes(h, w, next(vae.parameters()).dtype)))diff --git a/tests/app/invocations/test_flux2_working_memory.py b/tests/app/invocations/test_flux2_working_memory.pyindex 9cdbc695c2..1f102ee4e7 100644--- a/tests/app/invocations/test_flux2_working_memory.py+++ b/tests/app/invocations/test_flux2_working_memory.py@@ -1046,10 +1046,11 @@ class TestSdpaBackendProbe:@pytest.mark.skipif(not torch.cuda.is_available(), reason="asks the real CUDA/ROCm dispatcher")def test_this_build_reports_its_own_dispatch(self):"""The head dim is the discriminator that actually holds: CUDA's memory-efficient kernel- takes the VAE's 512-wide head, ROCm caps at 128 and reports `math` for it. Masks are not a- discriminator -- gfx1100 reports the memory-efficient kernel for a masked 128-wide head just- as CUDA does -- so the masked case only has to agree with whatever torch says, which is the- whole point of asking it."""+ takes the VAE's 512-wide head, and on ROCm the head-dim guard sends it to `math` by policy+ (its fused kernels return wrong output there). Masks are not a discriminator -- gfx1100+ reports the memory-efficient kernel for a masked 128-wide head just as CUDA does -- so the+ masked case only has to agree with whatever torch says, which is the whole point of asking+ it."""vae_bytes = sdpa_score_matrix_bytes(device=torch.device("cuda"), dtype=torch.bfloat16, num_heads=1, head_dim=512, seq_len=16384)diff --git a/tests/backend/util/test_rocm_sdpa_head_dim_guard.py b/tests/backend/util/test_rocm_sdpa_head_dim_guard.pynew file mode 100644index 0000000000..6dd8805879--- /dev/null+++ b/tests/backend/util/test_rocm_sdpa_head_dim_guard.py@@ -0,0 +1,326 @@+"""The ROCm head-dim guard for `F.scaled_dot_product_attention`.++The fused ROCm kernels are wrong above head_dim 256 (see `ROCM_FUSED_SDPA_MAX_HEAD_DIM`). The guard+must send exactly those calls to the math kernel, leave every other call on the original function+with its arguments intact, install once, and make the working-memory estimator budget the score+matrix the math kernel materializes.+"""++import pytest+import torch+import torch.nn.functional as F++import invokeai.backend.util.attention as attention+from invokeai.backend.util.attention import (+ ROCM_FUSED_SDPA_MAX_HEAD_DIM,+ install_rocm_sdpa_head_dim_guard,+ rocm_sdpa_uses_math_kernel,+ sdpa_score_matrix_bytes,+)++WIDE = ROCM_FUSED_SDPA_MAX_HEAD_DIM + 1+NARROW = ROCM_FUSED_SDPA_MAX_HEAD_DIM+++def _reference(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor) -> torch.Tensor:+ return torch.softmax(q @ k.transpose(-1, -2) / q.shape[-1] ** 0.5, dim=-1) @ v+++class TestPredicate:+ """The one rule the guard and the estimators share, tested against real device objects."""++ def test_only_wide_heads_on_a_rocm_cuda_device(self, monkeypatch):+ monkeypatch.setattr(attention, "_IS_ROCM", True)+ assert rocm_sdpa_uses_math_kernel("cuda", WIDE)+ assert not rocm_sdpa_uses_math_kernel("cuda", NARROW), "the threshold itself is trusted"+ assert not rocm_sdpa_uses_math_kernel("cpu", WIDE)+ assert not rocm_sdpa_uses_math_kernel("mps", WIDE)++ def test_never_off_rocm(self, monkeypatch):+ monkeypatch.setattr(attention, "_IS_ROCM", False)+ assert not rocm_sdpa_uses_math_kernel("cuda", WIDE)++ def test_threshold_override_from_the_environment(self, monkeypatch):+ monkeypatch.setenv(attention._ROCM_FUSED_SDPA_MAX_HEAD_DIM_ENV, "100000")+ assert attention._read_rocm_fused_sdpa_max_head_dim() == 100000+ monkeypatch.setenv(attention._ROCM_FUSED_SDPA_MAX_HEAD_DIM_ENV, "wide")+ assert attention._read_rocm_fused_sdpa_max_head_dim() == attention._ROCM_FUSED_SDPA_MAX_HEAD_DIM_DEFAULT+++def _install_as_if_rocm(monkeypatch) -> list[tuple]:+ """Install the guard on a CPU build, treating CPU tensors as the ROCm device, and record the+ full argument tuple of every call that reaches the original function."""+ calls: list[tuple] = []+ original = F.scaled_dot_product_attention++ def spy(query, key, value, attn_mask=None, dropout_p=0.0, is_causal=False, *, scale=None, enable_gqa=False):+ calls.append((query.shape[-1], attn_mask, dropout_p, is_causal, scale, enable_gqa))+ return original(query, key, value, attn_mask, dropout_p, is_causal, scale=scale, enable_gqa=enable_gqa)++ monkeypatch.setattr(F, "scaled_dot_product_attention", spy)+ monkeypatch.setattr(attention, "_IS_ROCM", True)+ # CPU tensors stand in for the ROCm device; the real predicate is covered by TestPredicate.+ monkeypatch.setattr(+ attention, "rocm_sdpa_uses_math_kernel", lambda device_type, head_dim: head_dim > ROCM_FUSED_SDPA_MAX_HEAD_DIM+ )+ install_rocm_sdpa_head_dim_guard()+ return calls+++class TestGuard:+ def test_wide_heads_take_the_math_kernel_and_match_the_reference(self, monkeypatch):+ calls = _install_as_if_rocm(monkeypatch)+ torch.manual_seed(0)+ q, k, v = (torch.randn(1, 1, 64, ROCM_FUSED_SDPA_MAX_HEAD_DIM * 2) for _ in range(3))++ out = F.scaled_dot_product_attention(q, k, v)++ assert calls == [], "a wide head must not reach the fused entry point"+ torch.testing.assert_close(out, _reference(q, k, v), atol=1e-5, rtol=1e-4)++ @pytest.mark.parametrize(+ "kwargs",+ [+ {"attn_mask": torch.rand(16, 16) > 0.3, "scale": 0.5, "enable_gqa": True},+ {"attn_mask": torch.randn(1, 1, 16, 16), "enable_gqa": True},+ {"attn_mask": torch.randn(16, 16).to(torch.bfloat16), "enable_gqa": True},+ {"is_causal": True, "enable_gqa": True},+ ],+ ids=["bool-mask+scale", "float-broadcast-mask", "bf16-mask", "causal"],+ )+ def test_wide_heads_keep_torchs_semantics_for_masks_scale_causal_and_gqa(self, monkeypatch, kwargs):+ _install_as_if_rocm(monkeypatch)+ original = F.scaled_dot_product_attention.__wrapped__+ torch.manual_seed(1)+ q = torch.randn(1, 4, 16, WIDE)+ k, v = (torch.randn(1, 2, 16, WIDE) for _ in range(2))+ mask = kwargs.get("attn_mask")+ if mask is not None and mask.dtype == torch.bfloat16:+ q, k, v = (t.to(torch.bfloat16) for t in (q, k, v))++ out = F.scaled_dot_product_attention(q, k, v, **kwargs)++ # torch's own (CPU, unguarded) semantics are the oracle.+ expected = original(q, k, v, **kwargs)+ torch.testing.assert_close(out, expected, atol=1e-2 if out.dtype == torch.bfloat16 else 1e-5, rtol=1e-2)++ def test_narrow_heads_pass_through_with_every_argument(self, monkeypatch):+ calls = _install_as_if_rocm(monkeypatch)+ torch.manual_seed(2)+ q, k, v = (torch.randn(1, 2, 8, NARROW) for _ in range(3))+ mask = torch.ones(8, 8, dtype=torch.bool)++ F.scaled_dot_product_attention(q, k, v, mask, 0.0, True, scale=0.25)++ assert calls == [(NARROW, mask, 0.0, True, 0.25, False)]++ def test_wide_heads_refuse_arguments_the_math_call_cannot_forward(self, monkeypatch):+ _install_as_if_rocm(monkeypatch)+ q = torch.randn(1, 1, 8, WIDE)+ with pytest.raises(TypeError, match="does not forward"):+ F.scaled_dot_product_attention(q, q, q, some_future_flag=True)++ def test_install_is_idempotent_and_inert_off_rocm(self, monkeypatch):+ _install_as_if_rocm(monkeypatch)+ guarded = F.scaled_dot_product_attention+ install_rocm_sdpa_head_dim_guard()+ assert F.scaled_dot_product_attention is guarded, "a second install must not wrap the wrapper"++ monkeypatch.setattr(F, "scaled_dot_product_attention", guarded.__wrapped__)+ monkeypatch.setattr(attention, "_IS_ROCM", False)+ install_rocm_sdpa_head_dim_guard()+ assert F.scaled_dot_product_attention is guarded.__wrapped__, "no guard on a non-ROCm build"++ def test_install_backs_off_when_the_math_op_rejects_the_probe(self, monkeypatch, caplog):+ """A torch whose aten op changed must fail at startup, visibly, not inside a generation."""+ original = F.scaled_dot_product_attention+ monkeypatch.setattr(attention, "_IS_ROCM", True)+ monkeypatch.setattr(attention, "_math_sdpa", lambda *a, **kw: (_ for _ in ()).throw(RuntimeError("no such op")))+ caplog.set_level("WARNING", logger=attention.__name__)++ install_rocm_sdpa_head_dim_guard()++ assert F.scaled_dot_product_attention is original+ assert any("NOT installed" in r.message for r in caplog.records)++ def test_apply_monkeypatches_installs_the_guard(self, monkeypatch):+ from invokeai.app.util.startup_utils import apply_monkeypatches++ original = F.scaled_dot_product_attention+ # Pin both entry points apply_monkeypatches rebinds so monkeypatch restores them afterwards.+ monkeypatch.setattr(F, "scaled_dot_product_attention", original)+ monkeypatch.setattr(torch.cuda, "empty_cache", torch.cuda.empty_cache)+ monkeypatch.setattr(attention, "_IS_ROCM", True)++ apply_monkeypatches()++ assert getattr(F.scaled_dot_product_attention, attention._ROCM_SDPA_GUARD_SENTINEL, False)+++class TestEstimator:+ def test_wide_heads_on_rocm_reserve_the_score_matrix_without_asking_torch(self, monkeypatch):+ monkeypatch.setattr(attention, "_IS_ROCM", True)+ probed: list[int] = []++ def fused_choice(q, *args, **kwargs):+ probed.append(q.shape[-1])+ return next(iter(attention._FUSED_SDP_CHOICES))++ monkeypatch.setattr(torch.ops.aten, "_fused_sdp_choice", fused_choice)+ # On a CPU-only build the probe cannot even allocate on "cuda" and would report the+ # materializing path for the wrong reason; make it run so the test discriminates everywhere.+ real_empty = torch.empty+ monkeypatch.setattr(torch, "empty", lambda *a, device=None, **kw: real_empty(*a, **kw))+ device = torch.device("cuda", 0)++ wide = sdpa_score_matrix_bytes(device=device, dtype=torch.bfloat16, num_heads=1, head_dim=WIDE, seq_len=64)+ assert wide == 64 * 64 * attention.SDPA_MATH_BYTES_PER_SCORE_ELEMENT+ assert probed == []++ narrow = sdpa_score_matrix_bytes(device=device, dtype=torch.bfloat16, num_heads=1, head_dim=NARROW, seq_len=64)+ assert narrow == 0, "a narrow head still asks torch, and a fused answer means no score matrix"+ assert probed == [NARROW]++ def test_wide_heads_off_rocm_still_ask_torch(self, monkeypatch):+ monkeypatch.setattr(attention, "_IS_ROCM", False)+ monkeypatch.setattr(+ torch.ops.aten, "_fused_sdp_choice", lambda q, *a, **k: next(iter(attention._FUSED_SDP_CHOICES))+ )+ assert (+ sdpa_score_matrix_bytes(+ device=torch.device("cpu"), dtype=torch.float32, num_heads=1, head_dim=WIDE, seq_len=64+ )+ == 0+ )+++needs_rocm = pytest.mark.skipif(torch.version.hip is None or not torch.cuda.is_available(), reason="needs a ROCm GPU")+++@needs_rocm+class TestOnRocmHardware:+ """The upstream defect and the guard, on the real device. `slow`: a dev-machine lane, not CI."""++ SHAPE = (1, 1, 16384, 512) # the FLUX.2 VAE mid-block at a 1024px decode++ def _inputs(self):+ torch.manual_seed(0)+ return (torch.randn(self.SHAPE, device="cuda", dtype=torch.bfloat16) for _ in range(3))++ def test_a_fused_kernel_is_still_wrong_for_the_wide_head(self):+ """Pins the reason the guard exists. When this passes on a new torch, the guard can go."""+ from torch.nn.attention import SDPBackend++ from invokeai.backend.util.sdpa_scope import sdpa_policy++ q, k, v = self._inputs()+ reference = attention._math_sdpa(q, k, v, None, 0.0, False, None, False).float()+ # The unguarded entry point, whether or not the guard is installed in this process.+ unguarded = getattr(F.scaled_dot_product_attention, "__wrapped__", F.scaled_dot_product_attention)+ wrong = 0+ for backend in (SDPBackend.FLASH_ATTENTION, SDPBackend.EFFICIENT_ATTENTION):+ with sdpa_policy([backend]):+ try:+ out = unguarded(q, k, v).float()+ except RuntimeError:+ continue # the backend refused the shape: not wrong, just absent+ err = (out - reference).abs().max().item() / reference.abs().max().item()+ wrong += int(not torch.isfinite(out).all() or err > 0.05)+ assert wrong > 0, "every fused kernel now agrees with math: the ROCm head-dim guard may be unnecessary"++ def test_the_guard_is_exact_under_allocation_churn(self):+ import random++ install_rocm_sdpa_head_dim_guard()+ q, k, v = self._inputs()+ reference = attention._math_sdpa(q, k, v, None, 0.0, False, None, False)+ rnd = random.Random(0)+ for _ in range(20):+ junk = [+ torch.empty(rnd.randint(1, 400) * 2**20, device="cuda", dtype=torch.uint8)+ for _ in range(rnd.randint(1, 4))+ ]+ out = F.scaled_dot_product_attention(q, k, v)+ del junk+ if rnd.random() < 0.5:+ torch.cuda.empty_cache()+ assert torch.equal(out, reference)+++class TestClassicVaeEstimators:+ """The SD/SDXL and FLUX.1 VAE estimators price the mid-block score matrix the guard forces."""++ @pytest.fixture(autouse=True)+ def _rocm_cuda(self, monkeypatch):+ import invokeai.backend.util.vae_working_memory as vwm++ monkeypatch.setattr(attention, "_IS_ROCM", True)+ monkeypatch.setattr(vwm.TorchDevice, "choose_torch_device", classmethod(lambda cls: torch.device("cuda", 0)))++ @staticmethod+ def _vae(spec):+ from unittest.mock import MagicMock++ vae = MagicMock(spec=spec)+ vae.parameters.side_effect = lambda: iter([torch.zeros(1, dtype=torch.bfloat16)])+ return vae++ @staticmethod+ def _score_bytes(px: int) -> int:+ tokens = (px // 8) ** 2+ return tokens * tokens * attention.SDPA_MATH_BYTES_PER_SCORE_ELEMENT++ def test_sdxl_untiled_decode_reserves_the_score_matrix_when_it_dominates(self, monkeypatch):+ from diffusers.models.autoencoders.autoencoder_kl import AutoencoderKL++ from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_sd15_sdxl++ latents = torch.zeros(1, 4, 2048 // 8, 2048 // 8)+ linear = 2048 * 2048 * 2 * 2200+ with_guard = estimate_vae_working_memory_sd15_sdxl(+ "decode", latents, self._vae(AutoencoderKL), None, fp32=False+ )+ assert with_guard == self._score_bytes(2048) > linear++ monkeypatch.setattr(attention, "_IS_ROCM", False)+ monkeypatch.setattr(+ torch.ops.aten, "_fused_sdp_choice", lambda q, *a, **k: next(iter(attention._FUSED_SDP_CHOICES))+ )+ real_empty = torch.empty+ monkeypatch.setattr(torch, "empty", lambda *a, device=None, **kw: real_empty(*a, **kw))+ assert (+ estimate_vae_working_memory_sd15_sdxl("decode", latents, self._vae(AutoencoderKL), None, fp32=False)+ == linear+ )++ @pytest.mark.parametrize("estimator", ["estimate_vae_working_memory_sd3", "estimate_vae_working_memory_cogview4"])+ def test_the_other_autoencoder_kl_estimators_price_it_too(self, estimator):+ from diffusers.models.autoencoders.autoencoder_kl import AutoencoderKL++ import invokeai.backend.util.vae_working_memory as vwm++ latents = torch.zeros(1, 16, 2048 // 8, 2048 // 8)+ assert getattr(vwm, estimator)("decode", latents, self._vae(AutoencoderKL)) == self._score_bytes(2048)++ def test_a_tiny_autoencoder_has_no_attention_to_price(self):+ from diffusers.models.autoencoders.autoencoder_tiny import AutoencoderTiny++ from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_sd15_sdxl++ latents = torch.zeros(1, 4, 2048 // 8, 2048 // 8)+ assert estimate_vae_working_memory_sd15_sdxl(+ "decode", latents, self._vae(AutoencoderTiny), None, fp32=False+ ) == (2048 * 2048 * 2 * 2200)++ def test_flux1_decode_prices_the_score_matrix_by_tile_when_tiled(self):+ from invokeai.backend.flux.modules.autoencoder import AutoEncoder+ from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_flux++ latents = torch.zeros(1, 16, 2048 // 8, 2048 // 8)+ untiled = estimate_vae_working_memory_flux("decode", latents, self._vae(AutoEncoder))+ assert untiled == self._score_bytes(2048)++ tiled = estimate_vae_working_memory_flux("decode", latents, self._vae(AutoEncoder), tile_size=1024)+ assert tiled < self._score_bytes(2048)+ assert tiled >= self._score_bytes(1024), "a 1024px tile still materializes its own 16384-token score matrix"