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
test(krea2): make the grouped-query change observable without a GPU
Alexander Eichhorn5cc4e9c90a16
diff --git a/tests/backend/krea2/test_grouped_query_attention.py b/tests/backend/krea2/test_grouped_query_attention.pyindex 9b4cfe4e7d..28491d879b 100644--- a/tests/backend/krea2/test_grouped_query_attention.py+++ b/tests/backend/krea2/test_grouped_query_attention.py@@ -38,15 +38,30 @@ class TestTheDecisionIsConservative: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):+ 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."""- proc = Krea2MemoryEfficientAttnProcessor(+ 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))- q, k, v, mask = _tensors("cpu")- assert proc._serves_grouped_query_attention(q, k, v, mask) is False+ assert excluded._serves_grouped_query_attention(q, k, v, mask) is Falsedef test_a_torch_build_with_a_different_sdpaparams_answers_no(self, monkeypatch):# Falling back to the expansion is correct everywhere; it merely costs memory.@@ -150,11 +165,81 @@ class TestTheTwoPathsAgreeOnCuda:grouped = run(False)assert seen[0] == HQ, "the forced run should have expanded the K/V heads"- if seen[1] != HKV:- pytest.skip("no fused kernel on this device serves grouped-query attention for this shape")++ # Skip only where the dispatcher genuinely refuses the shape. Skipping on `seen[1] != HKV`+ # alone turns "the change stopped taking effect" into a green run: an inverted condition or+ # a permanently-False `enable_gqa` restores the per-call expansion, removes the entire+ # benefit, and nothing fails anywhere.+ 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")+ 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# bound is the one used for the backend comparison elsewhere.corr = torch.corrcoef(torch.stack([expanded.flatten(), grouped.flatten()]))[0, 1]assert corr > 0.9999, f"correlation {corr}"assert (expanded - grouped).abs().max() < 0.05+++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 one+ every 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 —+ which is the half that would silently change every Krea-2 image if it were wrong.+ """++ @pytest.mark.parametrize("masked", [False, True])+ def test_grouped_and_expanded_sdpa_agree(self, masked):+ torch.manual_seed(0)+ seq = 32+ q = torch.randn(1, HQ, seq, HEAD_DIM, dtype=torch.float32)+ k = torch.randn(1, HKV, seq, HEAD_DIM, dtype=torch.float32)+ v = torch.randn(1, HKV, seq, HEAD_DIM, dtype=torch.float32)+ mask = None+ if masked:+ mask = torch.zeros(1, 1, seq, seq, dtype=torch.float32)+ mask[..., seq // 2 :, : seq // 2] = float("-inf")++ grouped = torch.nn.functional.scaled_dot_product_attention(q, k, v, attn_mask=mask, enable_gqa=True)+ repeats = HQ // HKV+ expanded = torch.nn.functional.scaled_dot_product_attention(+ q, k.repeat_interleave(repeats, dim=1), v.repeat_interleave(repeats, dim=1), attn_mask=mask+ )++ assert grouped.shape == expanded.shape+ assert torch.allclose(grouped, expanded, atol=1e-5)++ def test_the_processor_passes_the_grouped_heads_through_when_the_answer_is_yes(self, monkeypatch):+ """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+ hand SDPA the unexpanded K/V heads and `enable_gqa=True`. Pinning it here is what makes a+ permanently-False `enable_gqa` fail on a runner without CUDA, where every other test in this+ file legitimately exercises the expansion path instead.+ """+ seen: dict[str, object] = {}+ real = attention_module.F.scaled_dot_product_attention++ def spy(query, key, value, attn_mask=None, enable_gqa=False, **kwargs):+ seen["kv_heads"] = key.shape[1]+ seen["enable_gqa"] = enable_gqa+ return 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)+ monkeypatch.setattr(attention_module.F, "scaled_dot_product_attention", spy)++ torch.manual_seed(0)+ attn = Krea2Attention(hidden_size=HQ * HEAD_DIM, num_heads=HQ, num_kv_heads=HKV, eps=1e-5).eval()+ attn.set_processor(Krea2MemoryEfficientAttnProcessor())+ with torch.no_grad():+ attn(torch.randn(1, 32, HQ * HEAD_DIM), attention_mask=None, image_rotary_emb=None)++ assert seen["enable_gqa"] is True+ assert seen["kv_heads"] == HKV, "the K/V heads were expanded despite the dispatcher serving them"