Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions tests/pytorch/attention/test_attention_backend_selection.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

"""Focused FA4 eligibility and backend-cache regressions."""

import collections
from unittest.mock import Mock
from types import SimpleNamespace

Expand Down Expand Up @@ -42,6 +43,7 @@ def isolated_backends(monkeypatch):
},
)
monkeypatch.setattr(dpa_module, "_thd_policy_backend_cache", [])
monkeypatch.setattr(dpa_module, "_thd_pad_between_seqs_cache", collections.OrderedDict())


@pytest.mark.parametrize(
Expand Down Expand Up @@ -371,3 +373,60 @@ def _fa4_normalized_kwargs(kwargs):
def test_fa4_window_sentinel_normalization(sent, expected):
"""Convert only TE's -1 sentinel for both FA4 window argument forms."""
assert _fa4_normalized_kwargs(sent) == expected


def _cu_seqlens(*values):
return torch.tensor(values, dtype=torch.int32)


@pytest.mark.parametrize(
"padded_q,padded_kv,expected",
[
pytest.param(None, None, False, id="no-padded"),
pytest.param("alias", "alias", False, id="aliased"),
pytest.param([0, 3, 8], [0, 3, 8], False, id="equal-values"),
pytest.param([0, 4, 12], [0, 4, 12], True, id="padded"),
pytest.param([0, 3, 12], [0, 3, 12], True, id="tail-padded"),
pytest.param("alias", [0, 4, 12], True, id="kv-only-padded"),
pytest.param([0, 3, 8], None, False, id="q-only-equal-values"),
],
)
def test_thd_pad_between_seqs_detection(padded_q, padded_kv, expected):
"""Infer THD inter-sequence padding from cu_seqlens values, not tensor identity."""
cu_seqlens_q, cu_seqlens_kv = _cu_seqlens(0, 3, 8), _cu_seqlens(0, 3, 8)

def padded(spec, cu_seqlens):
return cu_seqlens if spec == "alias" else None if spec is None else _cu_seqlens(*spec)

assert (
dpa_module._infer_thd_pad_between_seqs(
cu_seqlens_q,
cu_seqlens_kv,
padded(padded_q, cu_seqlens_q),
padded(padded_kv, cu_seqlens_kv),
)
is expected
)


def test_thd_pad_between_seqs_detection_cuda_graph(monkeypatch):
"""Graph capture reuses eager results for unmodified tensors and is otherwise conservative."""
cu_seqlens, cu_seqlens_padded = _cu_seqlens(0, 3, 8), _cu_seqlens(0, 3, 8)
infer = dpa_module._infer_thd_pad_between_seqs
args = (cu_seqlens, cu_seqlens, cu_seqlens_padded, cu_seqlens_padded)

monkeypatch.setattr(dpa_module, "is_graph_capturing", lambda: True)
assert infer(*args) is True
monkeypatch.setattr(dpa_module, "is_graph_capturing", lambda: False)
assert infer(*args) is False

equal = Mock(wraps=torch.equal)
monkeypatch.setattr(torch, "equal", equal)
monkeypatch.setattr(dpa_module, "is_graph_capturing", lambda: True)
assert infer(*args) is False
equal.assert_not_called()

cu_seqlens_padded[1:] = _cu_seqlens(4, 12)
assert infer(*args) is True
monkeypatch.setattr(dpa_module, "is_graph_capturing", lambda: False)
assert infer(*args) is True
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
# See LICENSE for license information.

"""Attention."""
import collections
from contextlib import nullcontext
import math
import os
Expand Down Expand Up @@ -109,6 +110,13 @@
_THD_POLICY_VALIDATION_CACHE_LIMIT = 64
_thd_policy_validation_cache = []

# Inferring THD inter-sequence padding compares cu_seqlens values, which synchronizes
# once. Share results across DPA layers, and reuse eager warm-up results during CUDA
# graph capture, where values cannot be read. Entries hold their tensors, so the ids in
# a key cannot be reused by other tensors while the entry is cached.
_THD_PAD_BETWEEN_SEQS_CACHE_LIMIT = 64
_thd_pad_between_seqs_cache = collections.OrderedDict()


def _get_thd_policy_attention_backend(
policy: Dict[str, Any],
Expand Down Expand Up @@ -232,6 +240,52 @@ def _validate_thd_policy_sequence_ids(policies: List[Dict[str, Any]], batch_size
_thd_policy_validation_cache.pop(0)


def _infer_thd_pad_between_seqs(
cu_seqlens_q: Optional[torch.Tensor],
cu_seqlens_kv: Optional[torch.Tensor],
cu_seqlens_q_padded: Optional[torch.Tensor],
cu_seqlens_kv_padded: Optional[torch.Tensor],
) -> bool:
"""Infer whether THD sequences are separated by padding.

Padded cu_seqlens that are absent or alias the unpadded ones imply no padding.
Otherwise, eager calls compare values. CUDA graph capture reuses the result of an
eager call with the same unmodified tensors, or conservatively assumes padding.
"""
pairs = tuple(
(cu_seqlens, cu_seqlens_padded)
for cu_seqlens, cu_seqlens_padded in (
(cu_seqlens_q, cu_seqlens_q_padded),
(cu_seqlens_kv, cu_seqlens_kv_padded),
)
if cu_seqlens_padded is not None and cu_seqlens_padded is not cu_seqlens
)
if not pairs:
return False
if any(cu_seqlens is None for cu_seqlens, _ in pairs):
return True

tensors = tuple(tensor for pair in pairs for tensor in pair)
versions = tuple(_get_thd_policy_tensor_version(tensor) for tensor in tensors)
key = (tuple(id(tensor) for tensor in tensors), versions)
if key in _thd_pad_between_seqs_cache:
_thd_pad_between_seqs_cache.move_to_end(key)
return _thd_pad_between_seqs_cache[key][1]

if is_graph_capturing():
return True

pad_between_seqs = not all(
cu_seqlens.dtype == cu_seqlens_padded.dtype and torch.equal(cu_seqlens, cu_seqlens_padded)
for cu_seqlens, cu_seqlens_padded in pairs
)
if None not in versions:
_thd_pad_between_seqs_cache[key] = (tensors, pad_between_seqs)
if len(_thd_pad_between_seqs_cache) > _THD_PAD_BETWEEN_SEQS_CACHE_LIMIT:
_thd_pad_between_seqs_cache.popitem(last=False)
return pad_between_seqs


class _IdentityWithMaskedGradient(torch.autograd.Function):
"""Preserve tensor storage in forward and zero unselected backward lanes."""

Expand Down Expand Up @@ -2715,24 +2769,14 @@ def forward(
else None
)

# Default pad_between_seqs auto-detect. For THD, infer presence of
# inter-sequence padding from whether padded cu_seqlens were supplied --
# sync-free, and stable across eager and CUDA graph capture (the auto-detect
# must return the same value in both modes for backend selection to match).
# If padded cu_seqlens are the *same object* as the unpadded ones, no real
# inter-sequence padding exists (only THD tail padding) -- treat as False so
# FlashAttention v2/v4 remain eligible.
# Default pad_between_seqs auto-detect. Value-equal padded cu_seqlens imply no
# inter-sequence padding, which keeps FlashAttention v2/v4 eligible and lets
# context parallelism skip per-rank padded cu_seqlens.
if pad_between_seqs is None:
if qkv_format == "thd":
if (
cu_seqlens_q_padded is cu_seqlens_q
and cu_seqlens_kv_padded is cu_seqlens_kv
):
pad_between_seqs = False
else:
pad_between_seqs = (
cu_seqlens_q_padded is not None or cu_seqlens_kv_padded is not None
)
pad_between_seqs = _infer_thd_pad_between_seqs(
cu_seqlens_q, cu_seqlens_kv, cu_seqlens_q_padded, cu_seqlens_kv_padded
)
else:
pad_between_seqs = False

Expand Down