Skip to content

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.

test(krea2): cover the dispatch site, and cuDNN on the masked path

Alexander Eichhorna15a5a624c9c
diff --git a/invokeai/backend/krea2/attention.py b/invokeai/backend/krea2/attention.py
index 2bbdb63ab7..9af02edc68 100644
--- a/invokeai/backend/krea2/attention.py
+++ b/invokeai/backend/krea2/attention.py
@@ -165,6 +165,18 @@ class Krea2MemoryEfficientAttnProcessor:
key = key.repeat_interleave(repeats, dim=1)
value = value.repeat_interleave(repeats, dim=1)
+ # `sdpa_kernel` sets process-global flags, not thread-local ones, and torch offers no
+ # thread-scoped variant. InvokeAI runs one generation session per GPU concurrently, so a
+ # session on another device inside this window is affected too. Measured, on both paths:
+ #
+ # - Default (the four-backend list): a foreign thread still sees all four enabled. Only the
+ # priority order moves, so a concurrent call flash cannot serve may land on cuDNN rather
+ # than efficient. Both are valid kernels; the effect is which one runs, not whether one
+ # is available.
+ # - Exclusive override (`INVOKE_KREA2_SDPA_BACKEND=cudnn` and friends): a foreign thread
+ # sees the other three *disabled* for the duration. That is opt-in, and the variable
+ # exists for measuring one kernel against another rather than for normal operation --
+ # worth knowing before reaching for it on a multi-GPU box.
with sdpa_kernel(list(self.sdpa_backends.backends), set_priority=self.sdpa_backends.set_priority):
hidden_states = F.scaled_dot_product_attention(query, key, value, attn_mask=attention_mask)
diff --git a/tests/backend/krea2/test_attention.py b/tests/backend/krea2/test_attention.py
index 14a23a31f4..d68302e508 100644
--- a/tests/backend/krea2/test_attention.py
+++ b/tests/backend/krea2/test_attention.py
@@ -109,7 +109,21 @@ def test_processor_without_regional_state_ignores_the_shared_mask() -> None:
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA is required to exercise fused SDPA")
-def test_cuda_memory_efficient_sdpa_accepts_dense_regional_mask(monkeypatch: pytest.MonkeyPatch) -> None:
+ ("backend", "can_use"),
+ [
+ (SDPBackend.EFFICIENT_ATTENTION, torch.backends.cuda.can_use_efficient_attention),
+ (SDPBackend.CUDNN_ATTENTION, torch.backends.cuda.can_use_cudnn_attention),
+ ],
+ ids=["efficient", "cudnn"],
+)
+def test_cuda_fused_sdpa_accepts_dense_regional_mask(monkeypatch: pytest.MonkeyPatch, 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
+ actually serves them -- and on a build without flash it serves every block. Pinning only
+ efficient here would guard a kernel the product no longer reaches first.
+ """
attn = _build_gqa_attention().to(device="cuda", dtype=torch.float16)
hidden_states = torch.randn(1, 24, attn.hidden_size, device="cuda", dtype=torch.float16)
mask = torch.block_diag(
@@ -117,13 +131,13 @@ def test_cuda_memory_efficient_sdpa_accepts_dense_regional_mask(monkeypatch: pyt
torch.ones(12, 12, device="cuda", dtype=torch.bool),
)
state = Krea2RegionalPromptingState(attention_mask=mask)
- monkeypatch.setattr(krea2_attention, "_KREA2_SDPA_BACKENDS", [SDPBackend.EFFICIENT_ATTENTION])
+ monkeypatch.setattr(krea2_attention, "_KREA2_SDPA_BACKENDS", [backend])
head_dim = attn.hidden_size // attn.num_heads
sdpa_tensor = torch.empty(1, attn.num_heads, 24, head_dim, device="cuda", dtype=torch.float16)
sdpa_params = torch.backends.cuda.SDPAParams(sdpa_tensor, sdpa_tensor, sdpa_tensor, mask, 0.0, False, False)
- if not torch.backends.cuda.can_use_efficient_attention(sdpa_params):
- pytest.skip("This CUDA device/build does not support dense masks with memory-efficient SDPA")
+ if not can_use(sdpa_params):
+ pytest.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))
diff --git a/tests/backend/krea2/test_sdpa_backend_selection.py b/tests/backend/krea2/test_sdpa_backend_selection.py
index ed86e34ea9..811be497fe 100644
--- a/tests/backend/krea2/test_sdpa_backend_selection.py
+++ b/tests/backend/krea2/test_sdpa_backend_selection.py
@@ -11,12 +11,15 @@ latter the list only *permits* backends and torch picks by its own order, so the
silent no-op.
"""
+import contextlib
from unittest.mock import MagicMock
import pytest
import torch
+from diffusers.models.transformers.transformer_krea2 import Krea2Attention
from torch.nn.attention import SDPBackend, sdpa_kernel
+import invokeai.backend.krea2.attention as krea2_attention
from invokeai.backend.krea2.attention import (
KREA2_SDPA_BACKEND_ENV_VAR,
Krea2MemoryEfficientAttnProcessor,
@@ -194,3 +197,49 @@ class TestTheFallbackIsReal:
with pytest.raises(RuntimeError, match="No available kernel"):
with sdpa_kernel(list(choice.backends), set_priority=choice.set_priority):
torch.nn.functional.scaled_dot_product_attention(t, t, t)
+
+
+class TestTheDispatchSite:
+ """That the resolved choice actually reaches `sdpa_kernel`.
+
+ 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 `sdpa_kernel` window installed.
+ """
+
+ def _run_with_spy(self, monkeypatch, processor):
+ seen: dict[str, object] = {}
+
+ def spy(backends, set_priority=False):
+ seen["backends"] = list(backends)
+ seen["set_priority"] = set_priority
+ return contextlib.nullcontext()
+
+ monkeypatch.setattr(krea2_attention, "sdpa_kernel", spy)
+
+ 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."""
+ exclusive = resolve_krea2_sdpa_backends(raw_override="math")
+ seen = self._run_with_spy(monkeypatch, Krea2MemoryEfficientAttnProcessor(sdpa_backends=exclusive))
+
+ assert seen["backends"] == [SDPBackend.MATH]
+ assert seen["set_priority"] is False