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
perf(rocm): compute math-kernel attention in bounded chunks
Alexander Eichhornace24360ec37
diff --git a/docs/src/content/docs/start-here/system-requirements.mdx b/docs/src/content/docs/start-here/system-requirements.mdxindex 4ddc9d50fc..6a62a5efe6 100644--- a/docs/src/content/docs/start-here/system-requirements.mdx+++ b/docs/src/content/docs/start-here/system-requirements.mdx@@ -159,10 +159,18 @@ If, after restarting the app, this doesn't improve your performance, either restOn 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), whichshowed 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.+ head. The math kernel builds the whole attention matrix (about 4 GB for a 1024px VAE decode, 21 GB+ at 1536px), so Invoke computes it in pieces of at most 1 GB. The result can differ from a single+ math call in the last bit of a bf16 value, and each such call is roughly 10% slower. Export+ `INVOKE_ROCM_FUSED_SDPA_MAX_HEAD_DIM` to raise the threshold on a build whose fused kernels are+ known to be correct.+:::++:::note[Attention without a fused kernel]+ Where PyTorch has no fused attention kernel for a call, it runs on the math kernel as well, and+ Invoke computes that in pieces of at most 1 GB too. That is what makes large models and+ resolutions usable on such builds: Z-Image at 1024px would otherwise build 8 GB of attention+ scores per call, Krea-2 almost 13 GB.:::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.diff --git a/invokeai/app/util/startup_utils.py b/invokeai/app/util/startup_utils.pyindex 8a5c49399c..6d3c41306a 100644--- a/invokeai/app/util/startup_utils.py+++ b/invokeai/app/util/startup_utils.py@@ -162,10 +162,11 @@ 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+ # attention), turning decodes into noise or black images. Route those calls to the math kernel,+ # and compute math-kernel attention -- the only kernel ROCm on Windows has -- in bounded chunks.+ from invokeai.backend.util.attention import install_rocm_sdpa_guard- install_rocm_sdpa_head_dim_guard()+ install_rocm_sdpa_guard()def register_mime_types() -> None:diff --git a/invokeai/backend/util/attention.py b/invokeai/backend/util/attention.pyindex 6be3a663d8..18e8d8ca48 100644--- a/invokeai/backend/util/attention.py+++ b/invokeai/backend/util/attention.py@@ -8,7 +8,7 @@ import osimport threadingimport warningsfrom functools import lru_cache, wraps-from typing import Any+from typing import Any, Callableimport psutilimport torch@@ -100,8 +100,9 @@ _WARNING_FILTER_LOCK = threading.Lock()## 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+# known to be fixed. The cost is the math kernel for those calls: slower, and a materialized score+# matrix (~4.3 GiB for a 1024px VAE decode, ~21 GiB at 1536px), which the guard computes in chunks of+# `SDPA_MATH_CHUNK_BYTES` and the working-memory estimators price accordingly. 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@@ -125,7 +126,19 @@ def _read_rocm_fused_sdpa_max_head_dim() -> int: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"+_ROCM_SDPA_GUARD_SENTINEL = "_invokeai_rocm_sdpa_guard"++# Largest score matrix one math-kernel SDPA call may materialize on ROCm; larger calls run in chunks of at most this+# (`_chunked_sdpa`). Where no fused kernel exists -- ROCm on Windows has none, measured on an RX 9060 XT with torch+# 2.12+rocm7.14 -- an unchunked call costs heads x seq^2 x ~12-17 bytes: 8 GiB for Z-Image at 1024px, 12.9 GiB for+# Krea-2, 40 GiB for Z-Image at 1536px, against a 16 GB card. Measured per call at 1 GiB, against unchunked: Z-Image+# shape +8 % time, bitwise identical output; FLUX VAE mid-block (one 512-wide head, 1024px) +12 %, within one bf16+# ulp. Read at call time, so tests can lower it.+SDPA_MATH_CHUNK_BYTES = 1 << 30+++def _rocm_cuda(device_type: str) -> bool:+ return _IS_ROCM and device_type == "cuda"def rocm_sdpa_uses_math_kernel(device_type: str, head_dim: int) -> bool:@@ -134,7 +147,19 @@ def rocm_sdpa_uses_math_kernel(device_type: str, head_dim: int) -> bool:The single rule shared by the guard itself and by the working-memory estimators, so a reservedscore 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+ return _rocm_cuda(device_type) and head_dim > ROCM_FUSED_SDPA_MAX_HEAD_DIM+++def rocm_sdpa_chunks_math(device_type: str) -> bool:+ """True when math-kernel attention on this device runs in chunks of at most `SDPA_MATH_CHUNK_BYTES`.++ That is a ROCm device with the guard installed on the live binding -- not a guard that failed to install, and not+ a process that never installed it (scripts and tests that skip `apply_monkeypatches`), where the whole score+ matrix is still built and must be budgeted in full.+ """+ return _rocm_cuda(device_type) and getattr(+ torch.nn.functional.scaled_dot_product_attention, _ROCM_SDPA_GUARD_SENTINEL, False+ )def _math_sdpa(@@ -157,9 +182,102 @@ def _math_sdpa()[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.+def _math_score_bytes(query: torch.Tensor, key: torch.Tensor) -> int:+ """Upper bound on the score matrix a math-kernel call over these (4-D) inputs materializes."""+ batch, heads, query_len, _ = query.shape+ return batch * heads * query_len * key.shape[-2] * SDPA_MATH_BYTES_PER_SCORE_ELEMENT+++def _materializes(+ 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.+ """+ try:+ choice = torch.ops.aten._fused_sdp_choice(+ query, key, value, attn_mask, 0.0, False, scale=scale, enable_gqa=enable_gqa+ )+ except Exception:+ return True+ return int(choice) not in _FUSED_SDP_CHOICES+++def _chunked_sdpa(+ call: Callable[[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor | None], torch.Tensor],+ query: torch.Tensor,+ key: torch.Tensor,+ value: torch.Tensor,+ attn_mask: torch.Tensor | None,+ enable_gqa: bool,+) -> torch.Tensor:+ """Run a 4-D `(batch, heads, seq, dim)` attention as calls whose score matrices stay within `SDPA_MATH_CHUNK_BYTES`.++ Softmax normalizes each query row over all keys, so splitting heads or query rows is exact. Head groups come+ first: every call keeps its full `query x key` shape, so the result is bitwise the unchunked one. Query rows are+ split only when a single head (or GQA group) alone exceeds the budget -- the one-head VAE mid-block -- or when K/V+ are broadcast across heads rather than grouped; there the GEMM tiling changes by up to one bf16 ulp. A mask is+ sliced along the axis being split wherever it is not broadcast there. The output is allocated from the first+ chunk's result, which carries the dtype autocast chose.+ """+ budget = SDPA_MATH_CHUNK_BYTES+ batch, heads, query_len, _ = query.shape+ key_len, kv_heads = key.shape[-2], key.shape[-3]+ per_head = batch * query_len * key_len * SDPA_MATH_BYTES_PER_SCORE_ELEMENT++ if kv_heads == heads:+ ratio: int | None = 1+ elif enable_gqa and kv_heads > 0 and heads % kv_heads == 0:+ ratio = heads // kv_heads+ else:+ ratio = None+ group = 0 if ratio is None else (budget // per_head) // ratio * ratio++ out: torch.Tensor | None = None+ if group > 0:+ mask_per_head = attn_mask is not None and attn_mask.dim() >= 3 and attn_mask.shape[-3] == heads+ assert ratio is not None+ for start in range(0, heads, group):+ end = min(start + group, heads)+ mask = attn_mask[..., start:end, :, :] if mask_per_head else attn_mask+ kv = slice(start // ratio, end // ratio)+ part = call(query[:, start:end], key[:, kv], value[:, kv], mask)+ if out is None:+ out = part.new_empty((*query.shape[:-1], part.shape[-1]))+ out[:, start:end] = part+ else:+ rows = max(1, budget // (batch * heads * key_len * SDPA_MATH_BYTES_PER_SCORE_ELEMENT))+ mask_per_row = attn_mask is not None and attn_mask.dim() >= 2 and attn_mask.shape[-2] == query_len+ for start in range(0, query_len, rows):+ end = min(start + rows, query_len)+ mask = attn_mask[..., start:end, :] if mask_per_row else attn_mask+ part = call(query[:, :, start:end], key, value, mask)+ if out is None:+ out = part.new_empty((*query.shape[:-1], part.shape[-1]))+ out[:, :, start:end] = part+ assert out is not None+ return out+++def install_rocm_sdpa_guard() -> None:+ """Rebind ``torch.nn.functional.scaled_dot_product_attention`` on ROCm so that attention runs on a kernel that is+ both correct and bounded in memory.++ Two rules, both only for ROCm devices:++ * A call whose head_dim exceeds ``ROCM_FUSED_SDPA_MAX_HEAD_DIM`` runs the math kernel instead of a fused one, which+ returns wrong output there.+ * A call that runs on the math kernel -- routed by the first rule, or chosen by torch because no fused kernel takes+ it (all of them, on ROCm under Windows) -- and would materialize more than ``SDPA_MATH_CHUNK_BYTES`` of scores+ runs in chunks (`_chunked_sdpa`). Causal and dropout calls, and anything but 4-D inputs, are left whole.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@@ -168,10 +286,11 @@ def install_rocm_sdpa_head_dim_guard() -> None:Callers that resolve the function through the module at call time inherit the guard -- that isdiffusers' `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+ Two differences from the fused path for the wide-head calls only: torch's argument validation isskipped (an invalid mask dtype is not rejected up front), and the aten op is not on autocast'scast list, so fp32 inputs under ``torch.autocast`` compute in fp32 instead of the autocast- dtype. No current wide-head caller runs under autocast.+ dtype. No current wide-head caller runs under autocast. Chunks of narrower heads go through the+ original function, keeping its semantics.Idempotent; a no-op on non-ROCm builds. If the aten op is missing or rejects the call shapethis wrapper relies on, the guard is not installed and the log says so, rather than failing@@ -188,8 +307,9 @@ def install_rocm_sdpa_head_dim_guard() -> None:_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."+ f"ROCm 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, and "+ "math-kernel attention builds its whole score matrix.")returnoriginal = functional.scaled_dot_product_attention@@ -207,24 +327,55 @@ def install_rocm_sdpa_head_dim_guard() -> 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:+ wide_head = rocm_sdpa_uses_math_kernel(query.device.type, query.shape[-1])+ if wide_head and (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"scaled_dot_product_attention received arguments the ROCm SDPA 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)+ chunk = (+ _rocm_cuda(query.device.type)+ and query.dim() == 4+ and not query.is_nested+ and not is_causal+ and dropout_p == 0.0+ and not args+ and not kwargs+ and _math_score_bytes(query, key) > SDPA_MATH_CHUNK_BYTES+ and (wide_head or _materializes(query, key, value, attn_mask, scale, enable_gqa))+ )+ if wide_head:+ if not chunk:+ return _math_sdpa(query, key, value, attn_mask, dropout_p, is_causal, scale, enable_gqa)+ return _chunked_sdpa(+ lambda q, k, v, m: _math_sdpa(q, k, v, m, 0.0, False, scale, enable_gqa),+ query,+ key,+ value,+ attn_mask,+ enable_gqa,+ )+ if chunk:+ return _chunked_sdpa(+ lambda q, k, v, m: original(q, k, v, m, 0.0, False, scale=scale, enable_gqa=enable_gqa),+ query,+ key,+ value,+ attn_mask,+ enable_gqa,+ )+ return original(+ query, key, value, attn_mask, dropout_p, is_causal, *args, scale=scale, enable_gqa=enable_gqa, **kwargs+ )setattr(guarded_scaled_dot_product_attention, _ROCM_SDPA_GUARD_SENTINEL, True)functional.scaled_dot_product_attention = guarded_scaled_dot_product_attentionlogger.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)."+ f"(the fused kernels return wrong output there; {_ROCM_FUSED_SDPA_MAX_HEAD_DIM_ENV} overrides the threshold), "+ f"and math-kernel attention runs in chunks of at most {SDPA_MATH_CHUNK_BYTES / 2**30:g} GiB of scores.")@@ -360,27 +511,34 @@ def sdpa_score_matrix_bytes(`F.scaled_dot_product_attention` directly through `AttnProcessor2_0`). It consults theprocess-wide default backend, which is the one that applies here: estimates are priced beforethe model is loaded and outside any `attention_backend()` scope.++ Where the ROCm guard computes math attention in chunks (`rocm_sdpa_chunks_math`), one chunk is+ what is alive at a time, so the term is capped at ``SDPA_MATH_CHUNK_BYTES``."""if seq_len <= 0 or num_heads <= 0:return 0score_matrix_bytes = num_heads * seq_len * seq_len * SDPA_MATH_BYTES_PER_SCORE_ELEMENT+ chunked = rocm_sdpa_chunks_math(device.type)+ if chunked:+ score_matrix_bytes = min(score_matrix_bytes, SDPA_MATH_CHUNK_BYTES)+ suffix = ", in chunks" if chunked else ""if via_diffusers_dispatch:dispatch = _diffusers_attention_dispatch()if dispatch == _DISPATCH_FUSED:return 0if dispatch == _DISPATCH_MATH:- return _log_and_return(score_matrix_bytes, device, head_dim, "the diffusers backend")+ return _log_and_return(score_matrix_bytes, device, head_dim, f"the diffusers backend{suffix}")# _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")+ # `install_rocm_sdpa_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, f"the ROCm SDPA guard{suffix}")if not _torch_sdpa_materializes_score_matrix(device.type, device.index, dtype, head_dim, has_attn_mask):return 0- return _log_and_return(score_matrix_bytes, device, head_dim, "this torch build")+ return _log_and_return(score_matrix_bytes, device, head_dim, f"this torch build{suffix}")@lru_cache(maxsize=None)diff --git a/tests/backend/util/test_rocm_sdpa_head_dim_guard.py b/tests/backend/util/test_rocm_sdpa_head_dim_guard.pyindex 6dd8805879..0b3419d373 100644--- a/tests/backend/util/test_rocm_sdpa_head_dim_guard.py+++ b/tests/backend/util/test_rocm_sdpa_head_dim_guard.py@@ -1,25 +1,31 @@-"""The ROCm head-dim guard for `F.scaled_dot_product_attention`.+"""The ROCm SDPA 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 guardmust send exactly those calls to the math kernel, leave every other call on the original functionwith its arguments intact, install once, and make the working-memory estimator budget the score-matrix the math kernel materializes.+matrix the math kernel materializes. Math-kernel calls whose score matrix exceeds+`SDPA_MATH_CHUNK_BYTES` must run in chunks that each stay within it and together give the unchunked+result."""import pytestimport torchimport torch.nn.functional as F+from torch.nn.attention import SDPBackendimport invokeai.backend.util.attention as attentionfrom invokeai.backend.util.attention import (ROCM_FUSED_SDPA_MAX_HEAD_DIM,- install_rocm_sdpa_head_dim_guard,+ install_rocm_sdpa_guard,rocm_sdpa_uses_math_kernel,sdpa_score_matrix_bytes,)WIDE = ROCM_FUSED_SDPA_MAX_HEAD_DIM + 1NARROW = ROCM_FUSED_SDPA_MAX_HEAD_DIM+BYTES = attention.SDPA_MATH_BYTES_PER_SCORE_ELEMENT+# torch's own function, captured before any test installs the guard: the unchunked oracle.+TORCH_SDPA = F.scaled_dot_product_attentiondef _reference(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor) -> torch.Tensor:@@ -60,10 +66,8 @@ def _install_as_if_rocm(monkeypatch) -> list[tuple]: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()+ monkeypatch.setattr(attention, "_rocm_cuda", lambda device_type: True)+ install_rocm_sdpa_guard()return calls@@ -123,12 +127,12 @@ class TestGuard: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()+ install_rocm_sdpa_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()+ install_rocm_sdpa_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):@@ -138,7 +142,7 @@ class TestGuard: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()+ install_rocm_sdpa_guard()assert F.scaled_dot_product_attention is originalassert any("NOT installed" in r.message for r in caplog.records)@@ -157,6 +161,155 @@ class TestGuard:assert getattr(F.scaled_dot_product_attention, attention._ROCM_SDPA_GUARD_SENTINEL, False)+def _install_chunking(+ monkeypatch, budget: int, materializes: bool | None = True, torch_error: str | None = None+) -> list[tuple[torch.Size, torch.Size]]:+ """Install the guard as if on ROCm with a small chunk budget; record (query, key) shapes of every call that reaches+ torch's function or the math op. ``materializes`` pins the dispatch probe (None leaves it real); ``torch_error``+ makes torch's function raise it, as a build without an eligible kernel does."""+ shapes: list[tuple[torch.Size, torch.Size]] = []++ def spy(query, key, value, attn_mask=None, dropout_p=0.0, is_causal=False, *, scale=None, enable_gqa=False):+ shapes.append((query.shape, key.shape))+ if torch_error is not None:+ raise RuntimeError(torch_error)+ return TORCH_SDPA(query, key, value, attn_mask, dropout_p, is_causal, scale=scale, enable_gqa=enable_gqa)++ real_math = attention._math_sdpa++ def math_spy(query, key, value, *args):+ shapes.append((query.shape, key.shape))+ return real_math(query, key, value, *args)++ monkeypatch.setattr(F, "scaled_dot_product_attention", spy)+ monkeypatch.setattr(attention, "_math_sdpa", math_spy)+ monkeypatch.setattr(attention, "_IS_ROCM", True)+ 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)+ install_rocm_sdpa_guard()+ shapes.clear() # the install probe's own math call+ return shapes+++def _scores(shape_pair: tuple[torch.Size, torch.Size]) -> int:+ query_shape, key_shape = shape_pair+ return query_shape[0] * query_shape[1] * query_shape[2] * key_shape[-2] * BYTES+++class TestChunking:+ """Math-kernel attention over the budget runs in chunks; every chunk stays within it, together they are exact."""++ def test_heads_are_split_first_and_the_result_is_bitwise_unchunked(self, monkeypatch):+ per_head = 64 * 48 * BYTES+ shapes = _install_chunking(monkeypatch, budget=2 * per_head)+ torch.manual_seed(0)+ q = torch.randn(1, 6, 64, 32)+ k, v = torch.randn(1, 6, 48, 32), torch.randn(1, 6, 48, 32)++ out = F.scaled_dot_product_attention(q, k, v)++ assert [s[0][1] for s in shapes] == [2, 2, 2], "three head groups, each with every query row"+ assert torch.equal(out, TORCH_SDPA(q, k, v))++ def test_a_single_oversized_head_is_split_by_query_rows(self, monkeypatch):+ """The one-head VAE mid-block: only query rows are left to split, on the wide-head math path."""+ per_row = 96 * BYTES+ shapes = _install_chunking(monkeypatch, budget=20 * per_row)+ torch.manual_seed(1)+ q, k, v = (torch.randn(1, 1, 96, WIDE) for _ in range(3))++ out = F.scaled_dot_product_attention(q, k, v)++ assert [s[0][2] for s in shapes] == [20, 20, 20, 20, 16]+ torch.testing.assert_close(out, _reference(q, k, v), atol=1e-5, rtol=1e-4)++ @pytest.mark.parametrize(+ ("heads", "kv_heads", "budget_heads", "kwargs"),+ [+ (4, 4, 2, {"attn_mask": torch.rand(64, 48) > 0.3}),+ (4, 4, 2, {"attn_mask": torch.randn(2, 1, 64, 48)}),+ (4, 4, 2, {"attn_mask": torch.randn(2, 4, 64, 48)}),+ (4, 4, 2, {"attn_mask": torch.rand(1, 1, 1, 48) > 0.2}),+ (4, 4, 2, {"attn_mask": torch.randn(4, 64, 48)}),+ (4, 4, 2, {"scale": 0.3}),+ (6, 2, 3, {"enable_gqa": True}),+ (6, 2, 2, {"enable_gqa": True}),+ (4, 1, 2, {}),+ ],+ ids=[+ "bool-2d",+ "additive-broadcast-heads",+ "additive-per-head",+ "bool-broadcast-rows",+ "3d-per-head",+ "scale",+ "gqa-whole-groups",+ "gqa-group-over-budget",+ "kv-broadcast",+ ],+ )+ def test_masks_scale_and_grouped_heads_keep_torchs_result(self, monkeypatch, heads, kv_heads, budget_heads, kwargs):+ budget = budget_heads * 2 * 64 * 48 * BYTES+ shapes = _install_chunking(monkeypatch, budget=budget)+ torch.manual_seed(2)+ q = torch.randn(2, heads, 64, 32)+ k, v = torch.randn(2, kv_heads, 48, 32), torch.randn(2, kv_heads, 48, 32)++ out = F.scaled_dot_product_attention(q, k, v, **kwargs)++ assert len(shapes) > 1, "the call must actually have been split"+ assert all(_scores(pair) <= budget for pair in shapes), "a chunk exceeded the budget"+ torch.testing.assert_close(out, TORCH_SDPA(q, k, v, **kwargs), atol=1e-5, rtol=1e-4)++ @pytest.mark.parametrize("kwargs", [{"is_causal": True}, {"dropout_p": 0.1}], ids=["causal", "dropout"])+ def test_causal_and_dropout_calls_stay_whole(self, monkeypatch, kwargs):+ shapes = _install_chunking(monkeypatch, budget=BYTES)+ q = torch.randn(1, 2, 16, 8)++ F.scaled_dot_product_attention(q, q, q, **kwargs)++ assert shapes == [(q.shape, q.shape)]++ def test_a_call_torch_serves_with_a_fused_kernel_stays_whole(self, monkeypatch):+ shapes = _install_chunking(monkeypatch, budget=BYTES, materializes=None)+ monkeypatch.setattr(torch.ops.aten, "_fused_sdp_choice", lambda *a, **k: int(SDPBackend.FLASH_ATTENTION))+ q = torch.randn(1, 2, 16, 8)++ F.scaled_dot_product_attention(q, q, q)++ assert shapes == [(q.shape, q.shape)]++ def test_no_eligible_kernel_raises_the_same_error_as_the_whole_call(self, monkeypatch):+ """The probe raising means torch has no backend for the call (an exclusive policy, say): chunking must neither+ hide that nor route around it onto a kernel the policy forbids."""+ message = "No available kernel. Aborting execution."+ shapes = _install_chunking(monkeypatch, budget=16 * 16 * BYTES, materializes=None, torch_error=message)++ def no_backend(*args, **kwargs):+ raise RuntimeError("No viable backend for scaled_dot_product_attention was found.")++ monkeypatch.setattr(torch.ops.aten, "_fused_sdp_choice", no_backend)+ q = torch.randn(1, 2, 16, 8)++ with pytest.raises(RuntimeError, match=message):+ F.scaled_dot_product_attention(q, q, q)+ assert shapes[0][0][1] == 1, "the first chunk, run through torch's own function, raised"++ def test_the_output_dtype_follows_autocast(self, monkeypatch):+ per_head = 32 * 32 * BYTES+ _install_chunking(monkeypatch, budget=per_head)+ q = torch.randn(1, 4, 32, 16)++ with torch.autocast("cpu", dtype=torch.bfloat16):+ chunked = F.scaled_dot_product_attention(q, q, q)+ whole = TORCH_SDPA(q, q, q)++ assert chunked.dtype == whole.dtype+ torch.testing.assert_close(chunked.float(), whole.float(), atol=1e-2, rtol=1e-2)++class TestEstimator:def test_wide_heads_on_rocm_reserve_the_score_matrix_without_asking_torch(self, monkeypatch):monkeypatch.setattr(attention, "_IS_ROCM", True)@@ -193,6 +346,28 @@ class TestEstimator:== 0)+ def test_the_estimate_is_capped_at_one_chunk_only_while_the_guard_chunks(self, monkeypatch):+ """With the guard installed, one chunk is alive at a time; without it -- install failed, or a script that+ never installs it -- the whole matrix is built and must be budgeted in full."""+ monkeypatch.setattr(attention, "_IS_ROCM", True)+ monkeypatch.setattr(F, "scaled_dot_product_attention", TORCH_SDPA)+ device = torch.device("cuda", 0)+ full = 16384 * 16384 * BYTES++ def estimate() -> int:+ return sdpa_score_matrix_bytes(+ device=device, dtype=torch.bfloat16, num_heads=1, head_dim=WIDE, seq_len=16384+ )++ assert estimate() == full++ install_rocm_sdpa_guard()+ assert estimate() == attention.SDPA_MATH_CHUNK_BYTES+ assert (+ sdpa_score_matrix_bytes(device=device, dtype=torch.bfloat16, num_heads=1, head_dim=WIDE, seq_len=64)+ == 64 * 64 * BYTES+ ), "a matrix within one chunk is priced as it is"+needs_rocm = pytest.mark.skipif(torch.version.hip is None or not torch.cuda.is_available(), reason="needs a ROCm GPU")@@ -229,12 +404,19 @@ class TestOnRocmHardware: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):+ def test_the_guard_is_exact_under_allocation_churn(self, monkeypatch):+ """The fused kernels' failure depended on allocator state; the guarded path must not. The shape is over one+ chunk, so the reference is the guarded result itself (query chunks differ from one unchunked call by up to a+ bf16 ulp) -- what must hold is that it never changes."""import random- install_rocm_sdpa_head_dim_guard()+ monkeypatch.setattr(F, "scaled_dot_product_attention", F.scaled_dot_product_attention)+ install_rocm_sdpa_guard()q, k, v = self._inputs()- reference = attention._math_sdpa(q, k, v, None, 0.0, False, None, False)+ reference = F.scaled_dot_product_attention(q, k, v)+ torch.testing.assert_close(+ reference.float(), attention._math_sdpa(q, k, v, None, 0.0, False, None, False).float(), atol=2e-3, rtol=0+ )rnd = random.Random(0)for _ in range(20):junk = [@@ -247,6 +429,29 @@ class TestOnRocmHardware:torch.cuda.empty_cache()assert torch.equal(out, reference)+ @pytest.mark.parametrize(+ "shape",+ [(1, 30, 4128, 128), (1, 1, 36864, 512)],+ ids=["z-image-1024", "flux-vae-mid-block-1536"],+ )+ def test_math_attention_peaks_within_one_chunk(self, monkeypatch, shape):+ """Z-Image at 1024px would build 8 GiB of scores, a 1536px VAE decode 21 GiB. Where torch has a fused kernel+ for the narrow head, the call is not chunked and peaks far lower anyway."""+ monkeypatch.setattr(F, "scaled_dot_product_attention", F.scaled_dot_product_attention)+ install_rocm_sdpa_guard()+ torch.manual_seed(0)+ q, k, v = (torch.randn(shape, device="cuda", dtype=torch.bfloat16) for _ in range(3))+ F.scaled_dot_product_attention(q, k, v) # warm-up: kernel selection and allocator growth+ torch.cuda.synchronize()+ base = torch.cuda.memory_allocated()+ torch.cuda.reset_peak_memory_stats()++ out = F.scaled_dot_product_attention(q, k, v)+ torch.cuda.synchronize()++ peak = torch.cuda.max_memory_allocated() - base+ assert peak <= attention.SDPA_MATH_CHUNK_BYTES + out.numel() * out.element_size()+class TestClassicVaeEstimators:"""The SD/SDXL and FLUX.1 VAE estimators price the mid-block score matrix the guard forces."""