From 7bd7eb84217c5e458cbb68eea6e72f657a29c07d Mon Sep 17 00:00:00 2001 From: ArchanaChetan07 Date: Fri, 4 Dec 2026 18:25:55 -0800 Subject: [PATCH] [PyTorch] Detect THD inter-sequence padding by cu_seqlens values With qkv_format="thd" and pad_between_seqs=None, DotProductAttention inferred inter-sequence padding from tensor identity: padded cu_seqlens that were separate objects from the unpadded ones always selected the padded path, even when the values were equal. Under P2P context parallelism that path recomputes per-rank padded cu_seqlens at every step (#3487). Compare the values in eager mode instead, and cache the result by tensor identity and version so the sync happens once per cu_seqlens set rather than once per layer. During CUDA graph capture, reuse the result of an eager warm-up call with the same unmodified tensors, and otherwise keep the previous conservative answer (padding present). Absent or aliased padded cu_seqlens still imply no padding without reading values. Fixes #3487 Co-Authored-By: Claude Opus 5.5 Signed-off-by: ArchanaChetan07 --- .../test_attention_backend_selection.py | 59 ++++++++++++++ .../dot_product_attention.py | 76 +++++++++++++++---- 2 files changed, 119 insertions(+), 16 deletions(-) diff --git a/tests/pytorch/attention/test_attention_backend_selection.py b/tests/pytorch/attention/test_attention_backend_selection.py index 11cf3df3075..3983c979a4a 100644 --- a/tests/pytorch/attention/test_attention_backend_selection.py +++ b/tests/pytorch/attention/test_attention_backend_selection.py @@ -4,6 +4,7 @@ """Focused FA4 eligibility and backend-cache regressions.""" +import collections from unittest.mock import Mock from types import SimpleNamespace @@ -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( @@ -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 diff --git a/transformer_engine/pytorch/attention/dot_product_attention/dot_product_attention.py b/transformer_engine/pytorch/attention/dot_product_attention/dot_product_attention.py index c9045fde112..8d7cb01e5e7 100644 --- a/transformer_engine/pytorch/attention/dot_product_attention/dot_product_attention.py +++ b/transformer_engine/pytorch/attention/dot_product_attention/dot_product_attention.py @@ -3,6 +3,7 @@ # See LICENSE for license information. """Attention.""" +import collections from contextlib import nullcontext import math import os @@ -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], @@ -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.""" @@ -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