Skip to content
22 changes: 11 additions & 11 deletions src/diffusers/models/attention_dispatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why are we changing the return signature? The caller can reuse the seq_len_q and seq_len_kv right?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The shape is unchanged, still three pairs. The third pair was seqlens.max().item(), which for uniform lengths is the input by construction, so this just skips a device sync per call. It also matters for compile: full((b,), n, dtype=int32).max() with a symbolic n fails inductor codegen under dynamic=True on torch 2.12 (int32/int64 loop-carried type mismatch in the reduction kernel).



def _prepare_for_flash_attn_or_sage_varlen_with_mask(
Expand All @@ -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)
Comment thread
ShivamShrirao marked this conversation as resolved.
Resolved


def _prepare_for_flash_attn_or_sage_varlen(
Expand Down
50 changes: 50 additions & 0 deletions tests/models/test_attention_dispatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.

import contextlib
import os

import pytest
Expand All @@ -29,6 +30,8 @@
is_attention,
is_context_parallel,
is_kernels_available,
is_torch_compile,
require_torch_accelerator,
require_torch_multi_accelerator,
torch_device,
)
Expand Down Expand Up @@ -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
)
Comment on lines +212 to +220

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perfect!

finally:
torch.compiler.reset()
Loading