diff --git a/src/diffusers/models/attention_dispatch.py b/src/diffusers/models/attention_dispatch.py index 89bf25e4de8e..7ecbe50a4cf8 100644 --- a/src/diffusers/models/attention_dispatch.py +++ b/src/diffusers/models/attention_dispatch.py @@ -599,13 +599,13 @@ def _prepare_for_flash_attn_or_sage_varlen_without_mask( ): seqlens_q = torch.full((batch_size,), seq_len_q, dtype=torch.int32, device=device) seqlens_k = torch.full((batch_size,), seq_len_kv, dtype=torch.int32, device=device) - cu_seqlens_q = torch.zeros(batch_size + 1, dtype=torch.int32, device=device) - cu_seqlens_k = torch.zeros(batch_size + 1, dtype=torch.int32, device=device) - cu_seqlens_q[1:] = torch.cumsum(seqlens_q, dim=0) - cu_seqlens_k[1:] = torch.cumsum(seqlens_k, dim=0) - max_seqlen_q = seqlens_q.max().item() - max_seqlen_k = seqlens_k.max().item() - return (seqlens_q, seqlens_k), (cu_seqlens_q, cu_seqlens_k), (max_seqlen_q, max_seqlen_k) + # Built with arange instead of cumsum(full(...)): inductor rewrites that pattern into + # `arange * fill_value`, which raises under dynamic shapes because the fill value is a + # symbolic sequence length. The lengths are uniform here, so arange is also cheaper. + offsets = torch.arange(0, batch_size + 1, dtype=torch.int32, device=device) + cu_seqlens_q = offsets * seq_len_q + cu_seqlens_k = offsets * seq_len_kv + return (seqlens_q, seqlens_k), (cu_seqlens_q, cu_seqlens_k), (seq_len_q, seq_len_kv) def _prepare_for_flash_attn_or_sage_varlen_with_mask( @@ -616,13 +616,13 @@ def _prepare_for_flash_attn_or_sage_varlen_with_mask( ): seqlens_q = torch.full((batch_size,), seq_len_q, dtype=torch.int32, device=device) seqlens_k = attn_mask.sum(dim=1, dtype=torch.int32) - cu_seqlens_q = torch.zeros(batch_size + 1, dtype=torch.int32, device=device) + # Queries are uniform, so arange (see the no-mask helper: cumsum(full(...)) breaks inductor + # under dynamic shapes). Keys are data-dependent and keep the cumsum. + cu_seqlens_q = torch.arange(0, batch_size + 1, dtype=torch.int32, device=device) * seq_len_q cu_seqlens_k = torch.zeros(batch_size + 1, dtype=torch.int32, device=device) - cu_seqlens_q[1:] = torch.cumsum(seqlens_q, dim=0) cu_seqlens_k[1:] = torch.cumsum(seqlens_k, dim=0) - max_seqlen_q = seqlens_q.max().item() max_seqlen_k = seqlens_k.max().item() - return (seqlens_q, seqlens_k), (cu_seqlens_q, cu_seqlens_k), (max_seqlen_q, max_seqlen_k) + return (seqlens_q, seqlens_k), (cu_seqlens_q, cu_seqlens_k), (seq_len_q, max_seqlen_k) def _prepare_for_flash_attn_or_sage_varlen( diff --git a/tests/models/test_attention_dispatch.py b/tests/models/test_attention_dispatch.py index 1276ac4894dc..2143707aac40 100644 --- a/tests/models/test_attention_dispatch.py +++ b/tests/models/test_attention_dispatch.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +import contextlib import os import pytest @@ -29,6 +30,8 @@ is_attention, is_context_parallel, is_kernels_available, + is_torch_compile, + require_torch_accelerator, require_torch_multi_accelerator, torch_device, ) @@ -170,3 +173,50 @@ def test_attn_backend_backward_parity(self, cp_type, attention_backend): f"{attention_backend} {cp_type} gradient `{name}` rel_err={rel:.3e} " f"exceeds tol={GRAD_RTOL:.1e}: {rel_errs}" ) + + +@is_attention +class TestVarlenAttentionCompile: + """Op-level tests for the varlen backends under `torch.compile` with dynamic shapes, model independent.""" + + @pytest.mark.parametrize( + "attention_backend", + [ + pytest.param( + "flash_varlen_hub", + marks=pytest.mark.skipif(not is_kernels_available(), reason="`kernels` is not available."), + ), + pytest.param( + "_flash_3_varlen_hub", + marks=pytest.mark.skipif(not is_kernels_available(), reason="`kernels` is not available."), + ), + ], + ) + @is_torch_compile + @require_torch_accelerator + def test_dynamic_shapes(self, attention_backend): + def make_qkv(seq_len): + torch.manual_seed(0) + return tuple(torch.randn(2, seq_len, 4, 64, device=torch_device, dtype=torch.bfloat16) for _ in range(3)) + + with contextlib.ExitStack() as stack, torch.no_grad(): + try: + stack.enter_context(attention_backend_ctx(attention_backend)) + dispatch_attention_fn(*make_qkv(128)) + except Exception as e: + pytest.skip(f"Skipping test for backend '{attention_backend}': {e}") + + torch.compiler.reset() + compiled_attention = torch.compile(dispatch_attention_fn, dynamic=True, fullgraph=True) + try: + with ( + torch._inductor.utils.fresh_inductor_cache(), + torch._dynamo.config.patch(error_on_recompile=True), + ): + for seq_len in (128, 256, 256): + q, k, v = make_qkv(seq_len) + torch.testing.assert_close( + compiled_attention(q, k, v), dispatch_attention_fn(q, k, v), atol=1e-3, rtol=1e-3 + ) + finally: + torch.compiler.reset()