From 0d28d50f0c501da31120ad0a3745bfc129d90ffc Mon Sep 17 00:00:00 2001 From: Desh Raj Date: Wed, 29 Jul 2026 08:05:35 -0700 Subject: [PATCH 01/16] Add per-sequence causal policy to THD attention Signed-off-by: Desh Raj --- .../attention/test_mixed_thd_attention.py | 197 +++++++++++++++ .../dot_product_attention.py | 233 ++++++++++++++++++ 2 files changed, 430 insertions(+) create mode 100644 tests/pytorch/attention/test_mixed_thd_attention.py diff --git a/tests/pytorch/attention/test_mixed_thd_attention.py b/tests/pytorch/attention/test_mixed_thd_attention.py new file mode 100644 index 00000000000..dc6fb9b8475 --- /dev/null +++ b/tests/pytorch/attention/test_mixed_thd_attention.py @@ -0,0 +1,197 @@ +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. + +"""Tests for mixed causal/non-causal packed THD attention.""" + +import pytest +import torch + +from transformer_engine.pytorch import DotProductAttention + + +pytestmark = pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA is required") + +NUM_HEADS = 16 +HEAD_DIM = 64 + + +def _make_dpa(dtype: torch.dtype) -> DotProductAttention: + return DotProductAttention( + num_attention_heads=NUM_HEADS, + kv_channels=HEAD_DIM, + attention_dropout=0.0, + qkv_format="thd", + attn_mask_type="padding", + tp_size=1, + tp_group=None, + layer_number=1, + ).to(device="cuda", dtype=dtype) + + +def _per_sequence_scalar_reference( + attention: DotProductAttention, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + cu_seqlens: torch.Tensor, + sequence_is_causal: torch.Tensor, +) -> torch.Tensor: + """Reference every packed sequence through its scalar-policy DPA call.""" + outputs = [] + start = 0 + for length, is_causal in zip( + (cu_seqlens[1:] - cu_seqlens[:-1]).tolist(), sequence_is_causal.tolist() + ): + end = start + length + sequence_cu_seqlens = torch.tensor((0, length), dtype=torch.int32, device=query.device) + outputs.append( + attention( + # THD scalar attention requires tensors with a zero storage + # offset. clone() is differentiable, so the reference still + # accumulates gradients into the original packed inputs. + query[start:end].clone(), + key[start:end].clone(), + value[start:end].clone(), + qkv_format="thd", + cu_seqlens_q=sequence_cu_seqlens, + cu_seqlens_kv=sequence_cu_seqlens, + max_seqlen_q=length, + max_seqlen_kv=length, + attn_mask_type="padding_causal" if is_causal else "padding", + window_size=(-1, 0) if is_causal else (-1, -1), + bottom_right_diagonal=False, + ) + ) + start = end + + return torch.cat(outputs, dim=0) + + +@pytest.mark.parametrize( + "sequence_is_causal", + ( + (False, True, False, True), + (False, False, False, False), + (True, True, True, True), + ), +) +@pytest.mark.parametrize("dtype", (torch.float16, torch.bfloat16)) +def test_mixed_thd_matches_scalar_forward_and_backward(sequence_is_causal, dtype): + """Mixed THD dispatch must match attention applied to each packed sequence.""" + if dtype == torch.bfloat16 and not torch.cuda.is_bf16_supported(): + pytest.skip("BF16 is not supported by this GPU") + + torch.manual_seed(1234) + lengths = torch.tensor((7, 3, 5, 4), dtype=torch.int32, device="cuda") + cu_seqlens = torch.cat((lengths.new_zeros(1), torch.cumsum(lengths, dim=0, dtype=torch.int32))) + token_count = int(lengths.sum().item()) + sequence_is_causal = torch.tensor(sequence_is_causal, dtype=torch.bool, device="cuda") + + def make_input(): + return ( + 0.1 * torch.randn(token_count, NUM_HEADS, HEAD_DIM, dtype=dtype, device="cuda") + ).requires_grad_() + + query, key, value = make_input(), make_input(), make_input() + reference_query = query.detach().clone().requires_grad_() + reference_key = key.detach().clone().requires_grad_() + reference_value = value.detach().clone().requires_grad_() + + attention = _make_dpa(dtype) + mixed_output = attention( + query, + key, + value, + qkv_format="thd", + cu_seqlens_q=cu_seqlens, + cu_seqlens_kv=cu_seqlens, + max_seqlen_q=int(lengths.max().item()), + max_seqlen_kv=int(lengths.max().item()), + thd_sequence_is_causal=sequence_is_causal, + ) + reference_output = _per_sequence_scalar_reference( + attention, + reference_query, + reference_key, + reference_value, + cu_seqlens, + sequence_is_causal, + ) + + tolerances = {"atol": 1.0e-3, "rtol": 1.0e-3} + if dtype == torch.bfloat16: + tolerances = {"atol": 1.5e-2, "rtol": 1.5e-2} + torch.testing.assert_close(mixed_output, reference_output, **tolerances) + + output_grad = torch.randn_like(mixed_output) + mixed_output.backward(output_grad) + reference_output.backward(output_grad) + for mixed_grad, reference_grad in ( + (query.grad, reference_query.grad), + (key.grad, reference_key.grad), + (value.grad, reference_value.grad), + ): + torch.testing.assert_close(mixed_grad, reference_grad, **tolerances) + + +@pytest.mark.parametrize( + ("invalid_case", "error"), + ( + ("policy_dtype", "one-dimensional torch.bool"), + ("sliding_window", "sliding-window attention"), + ), +) +def test_mixed_thd_rejects_unsupported_inputs(invalid_case, error): + """Reject metadata that the grouping path cannot preserve.""" + query = torch.randn(4, NUM_HEADS, HEAD_DIM, device="cuda", dtype=torch.float16) + key = torch.randn_like(query) + value = torch.randn_like(query) + cu_seqlens = torch.tensor((0, 2, 4), dtype=torch.int32, device="cuda") + attention = _make_dpa(torch.float16) + + kwargs = { + "thd_sequence_is_causal": torch.tensor((False, True), dtype=torch.bool, device="cuda"), + } + if invalid_case == "policy_dtype": + kwargs["thd_sequence_is_causal"] = torch.tensor((0, 1), dtype=torch.int32, device="cuda") + else: + kwargs["window_size"] = (4, 0) + + with pytest.raises(ValueError, match=error): + attention( + query, + key, + value, + qkv_format="thd", + cu_seqlens_q=cu_seqlens, + cu_seqlens_kv=cu_seqlens, + max_seqlen_q=2, + max_seqlen_kv=2, + **kwargs, + ) + + +def test_mixed_thd_empty_batch_preserves_input_gradients(): + """An all-empty packed batch needs zero gradients, not a disconnected output.""" + attention = _make_dpa(torch.float16) + query = torch.empty( + 0, NUM_HEADS, HEAD_DIM, device="cuda", dtype=torch.float16, requires_grad=True + ) + key = torch.empty_like(query, requires_grad=True) + value = torch.empty_like(query, requires_grad=True) + cu_seqlens = torch.zeros(1, dtype=torch.int32, device="cuda") + + output = attention( + query, + key, + value, + qkv_format="thd", + cu_seqlens_q=cu_seqlens, + cu_seqlens_kv=cu_seqlens, + max_seqlen_q=0, + max_seqlen_kv=0, + thd_sequence_is_causal=torch.empty(0, dtype=torch.bool, device="cuda"), + ) + assert output.shape == (0, NUM_HEADS * HEAD_DIM) + output.sum().backward() + for input_tensor in (query, key, value): + torch.testing.assert_close(input_tensor.grad, torch.zeros_like(input_tensor)) 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 e6f50eb0dac..a6137081c02 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 @@ -1323,6 +1323,99 @@ def get_quantizer_roles( ] return base[:num_quantizers] + def _forward_mixed_thd( + self, + query_layer: torch.Tensor, + key_layer: torch.Tensor, + value_layer: torch.Tensor, + cu_seqlens: torch.Tensor, + thd_sequence_is_causal: torch.Tensor, + max_seqlen_q: Optional[int], + max_seqlen_kv: Optional[int], + *, + fast_zero_fill: bool, + ) -> torch.Tensor: + """Dispatch mixed causal/non-causal THD self-attention. + + Group whole sequences by policy, call the existing scalar-policy path + for each non-empty group, and restore the original packed token order. + """ + sequence_lengths = cu_seqlens[1:] - cu_seqlens[:-1] + token_count = query_layer.shape[0] + output_features = query_layer.shape[-2] * value_layer.shape[-1] + + if token_count == 0: + empty_output = query_layer.new_empty((0, output_features)) + return empty_output + 0 * (query_layer.sum() + key_layer.sum() + value_layer.sum()) + + def run_scalar_policy( + group_query: torch.Tensor, + group_key: torch.Tensor, + group_value: torch.Tensor, + group_cu_seqlens: torch.Tensor, + group_max_seqlen_q: Optional[int], + group_max_seqlen_kv: Optional[int], + is_causal: bool, + ) -> torch.Tensor: + return self.forward( + group_query, + group_key, + group_value, + qkv_format="thd", + cu_seqlens_q=group_cu_seqlens, + cu_seqlens_kv=group_cu_seqlens, + max_seqlen_q=group_max_seqlen_q, + max_seqlen_kv=group_max_seqlen_kv, + attn_mask_type="padding_causal" if is_causal else "padding", + window_size=(-1, 0) if is_causal else (-1, -1), + bottom_right_diagonal=False, + fast_zero_fill=fast_zero_fill, + ) + + first_policy = bool(thd_sequence_is_causal[0].item()) + if bool(torch.all(thd_sequence_is_causal == first_policy).item()): + return run_scalar_policy( + query_layer, + key_layer, + value_layer, + cu_seqlens, + max_seqlen_q, + max_seqlen_kv, + is_causal=first_policy, + ) + + token_is_causal = torch.repeat_interleave( + thd_sequence_is_causal, + sequence_lengths.to(dtype=torch.long), + output_size=token_count, + ) + output = query_layer.new_empty((token_count, output_features)) + for is_causal in (False, True): + sequence_mask = thd_sequence_is_causal == is_causal + group_token_indices = torch.nonzero(token_is_causal == is_causal).flatten() + if group_token_indices.numel() == 0: + continue + group_lengths = sequence_lengths[sequence_mask] + group_cu_seqlens = torch.cat( + ( + group_lengths.new_zeros(1), + torch.cumsum(group_lengths, dim=0, dtype=torch.int32), + ) + ) + group_max_seqlen = int(group_lengths.max().item()) + group_output = run_scalar_policy( + query_layer.index_select(0, group_token_indices), + key_layer.index_select(0, group_token_indices), + value_layer.index_select(0, group_token_indices), + group_cu_seqlens, + group_max_seqlen, + group_max_seqlen, + is_causal=is_causal, + ) + output = output.index_copy(0, group_token_indices, group_output) + + return output + @no_torch_dynamo(recursive=False) def forward( self, @@ -1357,6 +1450,7 @@ def forward( qkv_layer: Optional[torch.Tensor] = None, kv_layer: Optional[torch.Tensor] = None, qkv_interleave_dim: int = -3, + thd_sequence_is_causal: Optional[torch.Tensor] = None, ) -> torch.Tensor: r""" Dot Product Attention Layer. @@ -1596,8 +1690,147 @@ def forward( interleave sits; must be -3 (e.g. ``bs3hd``) or -2 (e.g. ``bsh3d``, Megatron-style). This is an explicit knob rather than shape inference, since e.g. ``h == 3`` would make the shapes ambiguous. + thd_sequence_is_causal: Optional[torch.Tensor], default = None + Per-sequence causal policy for packed THD self-attention. When supplied, + it must be a CUDA ``torch.bool`` tensor of shape ``[batch_size]``, where + ``batch_size = cu_seqlens_q.numel() - 1``. ``True`` selects causal + attention for that sequence and ``False`` selects full-context + attention. Transformer Engine groups the two policies and launches the + existing scalar-mask attention path once per non-empty group, then + restores the original packed token order. It therefore shares the + surrounding encoder computation but is not a single fused-attention + kernel. Initial support is limited to FP16/BF16 THD self-attention + without attention dropout, context parallelism, cacheing, FP8, + arbitrary padding between packed sequences, bias/ALiBi, score-mod, or + attention checkpointing. """ + if thd_sequence_is_causal is not None: + resolved_qkv_format = qkv_format if qkv_format is not None else self.qkv_format + if resolved_qkv_format != "thd": + raise ValueError("thd_sequence_is_causal is supported only with qkv_format='thd'.") + if ( + qkv_layer is not None + or kv_layer is not None + or query_layer is None + or key_layer is None + or value_layer is None + ): + raise ValueError( + "thd_sequence_is_causal requires separate query_layer, key_layer, and " + "value_layer." + ) + qkv = (query_layer, key_layer, value_layer) + if not all(tensor.is_cuda and tensor.device == query_layer.device for tensor in qkv): + raise ValueError( + "thd_sequence_is_causal requires CUDA Q, K, and V on the same device." + ) + if query_layer.dtype not in (torch.float16, torch.bfloat16) or not all( + tensor.dtype == query_layer.dtype for tensor in qkv + ): + raise ValueError( + "thd_sequence_is_causal requires FP16 or BF16 Q, K, and V of the same dtype." + ) + if self.attention_type != "self": + raise ValueError("thd_sequence_is_causal is supported only for self-attention.") + if cu_seqlens_q is None or cu_seqlens_kv is None: + raise ValueError("thd_sequence_is_causal requires cu_seqlens_q and cu_seqlens_kv.") + if not all( + cu_seqlens.ndim == 1 + and cu_seqlens.numel() >= 1 + and cu_seqlens.dtype == torch.int32 + and cu_seqlens.device == query_layer.device + for cu_seqlens in (cu_seqlens_q, cu_seqlens_kv) + ): + raise ValueError( + "thd_sequence_is_causal requires one-dimensional int32 cu_seqlens " + "on the Q/K/V device." + ) + if not torch.equal(cu_seqlens_q, cu_seqlens_kv): + raise ValueError( + "thd_sequence_is_causal requires identical Q and KV sequence boundaries." + ) + if thd_sequence_is_causal.dtype != torch.bool or thd_sequence_is_causal.ndim != 1: + raise ValueError( + "thd_sequence_is_causal must be a one-dimensional torch.bool tensor." + ) + if thd_sequence_is_causal.device != query_layer.device: + raise ValueError( + "thd_sequence_is_causal must be on the same device as query_layer." + ) + if thd_sequence_is_causal.numel() != cu_seqlens_q.numel() - 1: + raise ValueError( + "thd_sequence_is_causal must have one value per packed sequence: " + f"got {thd_sequence_is_causal.numel()} values for " + f"{cu_seqlens_q.numel() - 1} sequences." + ) + if not all( + tensor.ndim == 3 and tensor.shape[0] == query_layer.shape[0] for tensor in qkv + ): + raise ValueError( + "thd_sequence_is_causal requires THD Q, K, and V with the same token count." + ) + if int(cu_seqlens_q[-1].item()) != query_layer.shape[0]: + raise ValueError("The final cu_seqlens value must equal the THD Q/K/V token count.") + unsupported_options = ( + attention_mask is not None, + cu_seqlens_q_padded is not None, + cu_seqlens_kv_padded is not None, + inference_params is not None, + checkpoint_core_attention, + core_attention_bias_type != "no_bias", + core_attention_bias is not None, + alibi_slopes is not None, + score_mod is not None, + score_mod_bprop is not None, + score_mod_tensors is not None, + score_mod_bprop_tensors is not None, + fp8_output, + self.fp8, + self.attention_dropout != 0.0, + self.softmax_type != "vanilla", + self.return_max_logit, + self.cp_group is not None, + pad_between_seqs not in (None, False), + num_splits not in (None, 1), + ) + if any(unsupported_options): + raise ValueError( + "thd_sequence_is_causal currently supports only plain THD self-attention " + "without padding gaps, dropout, bias, score-mod, caching, FP8 output, " + "context parallelism, softmax variants, or attention checkpointing." + ) + if FP8GlobalStateManager.is_fp8_enabled() or FP8GlobalStateManager.is_fp8_calibration(): + raise ValueError("thd_sequence_is_causal does not yet support FP8 attention.") + if is_graph_capturing() or is_in_onnx_export_mode(): + raise ValueError( + "thd_sequence_is_causal does not yet support CUDA graph capture or ONNX export." + ) + effective_window_size = self.window_size if window_size is None else window_size + if effective_window_size not in {(-1, -1), (-1, 0)}: + raise ValueError( + "thd_sequence_is_causal does not yet support sliding-window attention." + ) + effective_bottom_right_diagonal = ( + self.bottom_right_diagonal + if bottom_right_diagonal is None + else bottom_right_diagonal + ) + if effective_bottom_right_diagonal is True: + raise ValueError( + "thd_sequence_is_causal requires the standard top-left causal diagonal." + ) + return self._forward_mixed_thd( + query_layer, + key_layer, + value_layer, + cu_seqlens_q, + thd_sequence_is_causal, + max_seqlen_q, + max_seqlen_kv, + fast_zero_fill=fast_zero_fill, + ) + query_layer, key_layer, value_layer, declared_qkv_layout = _unpack_packed_qkv( qkv_layer, kv_layer, From 50d2c81201a33a31521faab954a98e412367b614 Mon Sep 17 00:00:00 2001 From: Desh Raj Date: Thu, 30 Jul 2026 09:29:20 -0700 Subject: [PATCH 02/16] Fix mixed THD test CI coverage Signed-off-by: Desh Raj --- qa/L0_pytorch_unittest/test.sh | 1 + tests/pytorch/attention/test_mixed_thd_attention.py | 4 +++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/qa/L0_pytorch_unittest/test.sh b/qa/L0_pytorch_unittest/test.sh index 759432857ad..f0de413133c 100644 --- a/qa/L0_pytorch_unittest/test.sh +++ b/qa/L0_pytorch_unittest/test.sh @@ -63,6 +63,7 @@ python3 -m pytest --tb=auto --junitxml=$XML_LOG_DIR/pytest_test_linear_mxfp8_att python3 -m pytest --tb=auto --junitxml=$XML_LOG_DIR/pytest_test_fused_mla_q_uproj.xml $TE_PATH/tests/pytorch/attention/test_fused_mla_q_uproj.py || test_fail "test_fused_mla_q_uproj.py" python3 -m pytest --tb=auto --junitxml=$XML_LOG_DIR/pytest_test_kv_cache.xml $TE_PATH/tests/pytorch/attention/test_kv_cache.py || test_fail "test_kv_cache.py" python3 -m pytest --tb=auto --junitxml=$XML_LOG_DIR/pytest_test_cu_seqlens_cache.xml $TE_PATH/tests/pytorch/attention/test_cu_seqlens_cache.py || test_fail "test_cu_seqlens_cache.py" +python3 -m pytest --tb=auto --junitxml=$XML_LOG_DIR/pytest_test_mixed_thd_attention.xml $TE_PATH/tests/pytorch/attention/test_mixed_thd_attention.py || test_fail "test_mixed_thd_attention.py" python3 -m pytest --tb=auto --junitxml=$XML_LOG_DIR/pytest_test_hf_integration.xml $TE_PATH/tests/pytorch/test_hf_integration.py || test_fail "test_hf_integration.py" export NVTE_TEST_CHECKPOINT_ARTIFACT_PATH=$TE_PATH/artifacts/tests/pytorch/test_checkpoint if [ ! -d "$NVTE_TEST_CHECKPOINT_ARTIFACT_PATH" ]; then diff --git a/tests/pytorch/attention/test_mixed_thd_attention.py b/tests/pytorch/attention/test_mixed_thd_attention.py index dc6fb9b8475..04624eece4b 100644 --- a/tests/pytorch/attention/test_mixed_thd_attention.py +++ b/tests/pytorch/attention/test_mixed_thd_attention.py @@ -1,4 +1,6 @@ -# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# See LICENSE for license information. """Tests for mixed causal/non-causal packed THD attention.""" From a88c9b64b291bccea2373f15a9bcf90626508afb Mon Sep 17 00:00:00 2001 From: Desh Raj Date: Fri, 7 Aug 2026 10:53:39 -0700 Subject: [PATCH 03/16] Use inter-sequence padding for mixed THD masks Replace the per-policy Q/K/V gather and output scatter dispatcher with the review-suggested inter-sequence-padding design. Keep the original packed Q/K/V storage, derive logical and physical cu-seqlens for each mask policy, run the ordinary scalar-mask DPA path with pad_between_seqs, and sum its disjoint zero-padded outputs. Expose a generic attn_mask_type_per_seq mapping plus window_size_per_mask_type so callers can combine full-context offline attention with bounded causal attention. Preserve the scalar fast path for uniform batches, avoid policy-dependent host synchronization, and cover forward/backward parity, existing physical padding, cross-attention, per-policy windows, bottom-right masks, invalid inputs, empty batches, and CUDA graph replay. NRT H100 validation passed all 16 TransformerEngine cases and 3 focused Megatron integration tests. In an 8-node/64-H100 matched-auto comparison over iterations 7-100, grouped averaged 1802.289 ms and pad-between averaged 1779.596 ms (-1.259%); the paired 95% interval crossed zero, indicating practical parity when the backend is held constant. In the deployable-backend comparison, grouped/Flash averaged 1596.129 ms while pad-between/auto-cuDNN averaged 1766.769 ms: pad-between was 10.691% slower by mean and 11.482% slower by 5%-trimmed mean. The paired penalty was +170.640 ms with a 95% interval of +89.728 to +251.552 ms, with all 16 fully logged workload counters matching across 100 steps. The implementation removes the original data-movement contention, but the current image cannot run full-context inter-sequence padding through FlashAttention 2 and has no FA3, so the path falls back to cuDNN fused attention. Retain grouped/Flash for production until a competitive padding-capable backend is available; this commit keeps the cleaner generic API for review and future backend support. Signed-off-by: Desh Raj --- .../attention/test_mixed_thd_attention.py | 318 ++++++++++--- .../dot_product_attention.py | 446 ++++++++++-------- 2 files changed, 495 insertions(+), 269 deletions(-) diff --git a/tests/pytorch/attention/test_mixed_thd_attention.py b/tests/pytorch/attention/test_mixed_thd_attention.py index 04624eece4b..4cb3f395781 100644 --- a/tests/pytorch/attention/test_mixed_thd_attention.py +++ b/tests/pytorch/attention/test_mixed_thd_attention.py @@ -2,7 +2,7 @@ # # See LICENSE for license information. -"""Tests for mixed causal/non-causal packed THD attention.""" +"""Tests for per-sequence mask types in packed THD attention.""" import pytest import torch @@ -16,77 +16,110 @@ HEAD_DIM = 64 -def _make_dpa(dtype: torch.dtype) -> DotProductAttention: +def _make_dpa(dtype: torch.dtype, attention_type: str = "self") -> DotProductAttention: return DotProductAttention( num_attention_heads=NUM_HEADS, kv_channels=HEAD_DIM, attention_dropout=0.0, qkv_format="thd", attn_mask_type="padding", + attention_type=attention_type, tp_size=1, tp_group=None, layer_number=1, ).to(device="cuda", dtype=dtype) +def _make_cu_seqlens(lengths): + lengths = torch.tensor(lengths, dtype=torch.int32, device="cuda") + return torch.cat((lengths.new_zeros(1), torch.cumsum(lengths, dim=0, dtype=torch.int32))) + + +def _make_policy(sequence_ids): + return { + mask_type: torch.tensor(ids, dtype=torch.int64, device="cuda") + for mask_type, ids in sequence_ids.items() + } + + def _per_sequence_scalar_reference( attention: DotProductAttention, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, - cu_seqlens: torch.Tensor, - sequence_is_causal: torch.Tensor, + cu_seqlens_q: torch.Tensor, + cu_seqlens_kv: torch.Tensor, + mask_type_per_seq, + *, + cu_seqlens_q_padded=None, + cu_seqlens_kv_padded=None, + window_size_per_mask_type=None, ) -> torch.Tensor: - """Reference every packed sequence through its scalar-policy DPA call.""" - outputs = [] - start = 0 - for length, is_causal in zip( - (cu_seqlens[1:] - cu_seqlens[:-1]).tolist(), sequence_is_causal.tolist() - ): - end = start + length - sequence_cu_seqlens = torch.tensor((0, length), dtype=torch.int32, device=query.device) - outputs.append( - attention( - # THD scalar attention requires tensors with a zero storage - # offset. clone() is differentiable, so the reference still - # accumulates gradients into the original packed inputs. - query[start:end].clone(), - key[start:end].clone(), - value[start:end].clone(), + """Reference each physical sequence through an ordinary scalar-mask call.""" + q_physical = cu_seqlens_q if cu_seqlens_q_padded is None else cu_seqlens_q_padded + kv_physical = cu_seqlens_kv if cu_seqlens_kv_padded is None else cu_seqlens_kv_padded + outputs = [None] * (cu_seqlens_q.numel() - 1) + for mask_type, sequence_ids in mask_type_per_seq.items(): + for sequence_id in sequence_ids.tolist(): + q_length = int((cu_seqlens_q[sequence_id + 1] - cu_seqlens_q[sequence_id]).item()) + kv_length = int( + (cu_seqlens_kv[sequence_id + 1] - cu_seqlens_kv[sequence_id]).item() + ) + q_start = int(q_physical[sequence_id].item()) + kv_start = int(kv_physical[sequence_id].item()) + q_end = q_start + q_length + kv_end = kv_start + kv_length + sequence_cu_seqlens_q = torch.tensor( + (0, q_length), dtype=torch.int32, device=query.device + ) + sequence_cu_seqlens_kv = torch.tensor( + (0, kv_length), dtype=torch.int32, device=query.device + ) + policy_window_size = None + if window_size_per_mask_type is not None: + policy_window_size = window_size_per_mask_type.get(mask_type) + outputs[sequence_id] = attention( + # THD scalar attention requires zero-offset storage. clone() is + # differentiable, so gradients still reach the packed inputs. + query[q_start:q_end].clone(), + key[kv_start:kv_end].clone(), + value[kv_start:kv_end].clone(), qkv_format="thd", - cu_seqlens_q=sequence_cu_seqlens, - cu_seqlens_kv=sequence_cu_seqlens, - max_seqlen_q=length, - max_seqlen_kv=length, - attn_mask_type="padding_causal" if is_causal else "padding", - window_size=(-1, 0) if is_causal else (-1, -1), - bottom_right_diagonal=False, + cu_seqlens_q=sequence_cu_seqlens_q, + cu_seqlens_kv=sequence_cu_seqlens_kv, + max_seqlen_q=q_length, + max_seqlen_kv=kv_length, + attn_mask_type=mask_type, + window_size=policy_window_size, ) - ) - start = end - return torch.cat(outputs, dim=0) + output = query.new_zeros((query.shape[0], NUM_HEADS * HEAD_DIM)) + for sequence_id, sequence_output in enumerate(outputs): + q_length = int((cu_seqlens_q[sequence_id + 1] - cu_seqlens_q[sequence_id]).item()) + q_start = int(q_physical[sequence_id].item()) + output[q_start : q_start + q_length] = sequence_output + return output @pytest.mark.parametrize( - "sequence_is_causal", + "mask_type_per_seq", ( - (False, True, False, True), - (False, False, False, False), - (True, True, True, True), + {"padding": (0, 2), "padding_causal": (1, 3)}, + {"padding": (0, 1, 2, 3)}, + {"padding_causal": (0, 1, 2, 3)}, + {"padding": (0, 2), "padding_causal_bottom_right": (1, 3)}, ), ) @pytest.mark.parametrize("dtype", (torch.float16, torch.bfloat16)) -def test_mixed_thd_matches_scalar_forward_and_backward(sequence_is_causal, dtype): - """Mixed THD dispatch must match attention applied to each packed sequence.""" +def test_thd_mask_types_match_scalar_forward_and_backward(mask_type_per_seq, dtype): + """Per-sequence masks must match independent scalar-policy attention.""" if dtype == torch.bfloat16 and not torch.cuda.is_bf16_supported(): pytest.skip("BF16 is not supported by this GPU") torch.manual_seed(1234) - lengths = torch.tensor((7, 3, 5, 4), dtype=torch.int32, device="cuda") - cu_seqlens = torch.cat((lengths.new_zeros(1), torch.cumsum(lengths, dim=0, dtype=torch.int32))) - token_count = int(lengths.sum().item()) - sequence_is_causal = torch.tensor(sequence_is_causal, dtype=torch.bool, device="cuda") + cu_seqlens = _make_cu_seqlens((7, 3, 5, 4)) + token_count = 19 + mask_type_per_seq = _make_policy(mask_type_per_seq) def make_input(): return ( @@ -99,16 +132,16 @@ def make_input(): reference_value = value.detach().clone().requires_grad_() attention = _make_dpa(dtype) - mixed_output = attention( + output = attention( query, key, value, qkv_format="thd", cu_seqlens_q=cu_seqlens, cu_seqlens_kv=cu_seqlens, - max_seqlen_q=int(lengths.max().item()), - max_seqlen_kv=int(lengths.max().item()), - thd_sequence_is_causal=sequence_is_causal, + max_seqlen_q=7, + max_seqlen_kv=7, + attn_mask_type_per_seq=mask_type_per_seq, ) reference_output = _per_sequence_scalar_reference( attention, @@ -116,47 +149,205 @@ def make_input(): reference_key, reference_value, cu_seqlens, - sequence_is_causal, + cu_seqlens, + mask_type_per_seq, ) tolerances = {"atol": 1.0e-3, "rtol": 1.0e-3} if dtype == torch.bfloat16: tolerances = {"atol": 1.5e-2, "rtol": 1.5e-2} - torch.testing.assert_close(mixed_output, reference_output, **tolerances) + torch.testing.assert_close(output, reference_output, **tolerances) - output_grad = torch.randn_like(mixed_output) - mixed_output.backward(output_grad) + output_grad = torch.randn_like(output) + output.backward(output_grad) reference_output.backward(output_grad) - for mixed_grad, reference_grad in ( + for actual_grad, reference_grad in ( (query.grad, reference_query.grad), (key.grad, reference_key.grad), (value.grad, reference_value.grad), ): - torch.testing.assert_close(mixed_grad, reference_grad, **tolerances) + torch.testing.assert_close(actual_grad, reference_grad, **tolerances) + + +def test_thd_mask_types_compose_with_existing_inter_sequence_padding(): + """Policy gaps and pre-existing THD padding must share the physical layout.""" + torch.manual_seed(1234) + dtype = torch.float16 + cu_seqlens = _make_cu_seqlens((7, 3, 5, 4)) + cu_seqlens_padded = torch.tensor((0, 9, 12, 19, 23), dtype=torch.int32, device="cuda") + mask_type_per_seq = _make_policy({"padding": (0, 2), "padding_causal": (1, 3)}) + + def make_input(): + return ( + 0.1 * torch.randn(23, NUM_HEADS, HEAD_DIM, dtype=dtype, device="cuda") + ).requires_grad_() + + query, key, value = make_input(), make_input(), make_input() + reference_query = query.detach().clone().requires_grad_() + reference_key = key.detach().clone().requires_grad_() + reference_value = value.detach().clone().requires_grad_() + attention = _make_dpa(dtype) + + output = attention( + query, + key, + value, + qkv_format="thd", + cu_seqlens_q=cu_seqlens, + cu_seqlens_kv=cu_seqlens, + cu_seqlens_q_padded=cu_seqlens_padded, + cu_seqlens_kv_padded=cu_seqlens_padded, + max_seqlen_q=7, + max_seqlen_kv=7, + attn_mask_type_per_seq=mask_type_per_seq, + ) + reference_output = _per_sequence_scalar_reference( + attention, + reference_query, + reference_key, + reference_value, + cu_seqlens, + cu_seqlens, + mask_type_per_seq, + cu_seqlens_q_padded=cu_seqlens_padded, + cu_seqlens_kv_padded=cu_seqlens_padded, + ) + torch.testing.assert_close(output, reference_output, atol=1.0e-3, rtol=1.0e-3) + + output_grad = torch.randn_like(output) + output.backward(output_grad) + reference_output.backward(output_grad) + for actual_grad, reference_grad in ( + (query.grad, reference_query.grad), + (key.grad, reference_key.grad), + (value.grad, reference_value.grad), + ): + torch.testing.assert_close(actual_grad, reference_grad, atol=1.0e-3, rtol=1.0e-3) + + +def test_thd_mask_types_support_cross_attention_and_per_policy_windows(): + """Mask groups may use different Q/KV lengths and sliding windows.""" + torch.manual_seed(1234) + dtype = torch.float16 + cu_seqlens_q = _make_cu_seqlens((5, 3, 4)) + cu_seqlens_kv = _make_cu_seqlens((7, 2, 5)) + mask_type_per_seq = _make_policy( + {"padding": (0, 2), "padding_causal_bottom_right": (1,)} + ) + windows = {"padding": (-1, -1), "padding_causal_bottom_right": (2, 0)} + + query = ( + 0.1 * torch.randn(12, NUM_HEADS, HEAD_DIM, dtype=dtype, device="cuda") + ).requires_grad_() + key = (0.1 * torch.randn(14, NUM_HEADS, HEAD_DIM, dtype=dtype, device="cuda")).requires_grad_() + value = (0.1 * torch.randn_like(key)).requires_grad_() + reference_query = query.detach().clone().requires_grad_() + reference_key = key.detach().clone().requires_grad_() + reference_value = value.detach().clone().requires_grad_() + attention = _make_dpa(dtype, attention_type="cross") + + output = attention( + query, + key, + value, + qkv_format="thd", + cu_seqlens_q=cu_seqlens_q, + cu_seqlens_kv=cu_seqlens_kv, + max_seqlen_q=5, + max_seqlen_kv=7, + attn_mask_type_per_seq=mask_type_per_seq, + window_size_per_mask_type=windows, + ) + reference_output = _per_sequence_scalar_reference( + attention, + reference_query, + reference_key, + reference_value, + cu_seqlens_q, + cu_seqlens_kv, + mask_type_per_seq, + window_size_per_mask_type=windows, + ) + torch.testing.assert_close(output, reference_output, atol=1.0e-3, rtol=1.0e-3) + + output_grad = torch.randn_like(output) + output.backward(output_grad) + reference_output.backward(output_grad) + for actual_grad, reference_grad in ( + (query.grad, reference_query.grad), + (key.grad, reference_key.grad), + (value.grad, reference_value.grad), + ): + torch.testing.assert_close(actual_grad, reference_grad, atol=1.0e-3, rtol=1.0e-3) + + +def test_thd_mask_types_support_cuda_graph_capture(): + """The sync-free policy metadata path must be replayable in a CUDA graph.""" + torch.manual_seed(1234) + dtype = torch.float16 + cu_seqlens = _make_cu_seqlens((7, 3, 5, 4)) + mask_type_per_seq = _make_policy({"padding": (0, 2), "padding_causal": (1, 3)}) + query = 0.1 * torch.randn(19, NUM_HEADS, HEAD_DIM, dtype=dtype, device="cuda") + key = 0.1 * torch.randn_like(query) + value = 0.1 * torch.randn_like(query) + attention = _make_dpa(dtype).eval() + + def run_attention(): + return attention( + query, + key, + value, + qkv_format="thd", + cu_seqlens_q=cu_seqlens, + cu_seqlens_kv=cu_seqlens, + max_seqlen_q=7, + max_seqlen_kv=7, + attn_mask_type_per_seq=mask_type_per_seq, + ) + + warmup_stream = torch.cuda.Stream() + warmup_stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(warmup_stream): + for _ in range(3): + run_attention() + torch.cuda.current_stream().wait_stream(warmup_stream) + + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + captured_output = run_attention() + graph.replay() + actual_output = captured_output.clone() + expected_output = run_attention() + torch.testing.assert_close(actual_output, expected_output, atol=1.0e-3, rtol=1.0e-3) @pytest.mark.parametrize( ("invalid_case", "error"), ( - ("policy_dtype", "one-dimensional torch.bool"), - ("sliding_window", "sliding-window attention"), + ("policy_dtype", "one-dimensional int32 or int64"), + ("missing_sequence", "assign every sequence exactly once by count"), + ("mask_type", "only padding mask types"), + ("window_key", "mask not present"), ), ) -def test_mixed_thd_rejects_unsupported_inputs(invalid_case, error): - """Reject metadata that the grouping path cannot preserve.""" +def test_thd_mask_types_reject_invalid_inputs(invalid_case, error): + """Reject malformed policy metadata before launching attention.""" query = torch.randn(4, NUM_HEADS, HEAD_DIM, device="cuda", dtype=torch.float16) key = torch.randn_like(query) value = torch.randn_like(query) cu_seqlens = torch.tensor((0, 2, 4), dtype=torch.int32, device="cuda") attention = _make_dpa(torch.float16) + policies = _make_policy({"padding": (0,), "padding_causal": (1,)}) + windows = None - kwargs = { - "thd_sequence_is_causal": torch.tensor((False, True), dtype=torch.bool, device="cuda"), - } if invalid_case == "policy_dtype": - kwargs["thd_sequence_is_causal"] = torch.tensor((0, 1), dtype=torch.int32, device="cuda") + policies["padding"] = torch.tensor((0,), dtype=torch.float32, device="cuda") + elif invalid_case == "missing_sequence": + policies = _make_policy({"padding": (0,)}) + elif invalid_case == "mask_type": + policies = _make_policy({"no_mask": (0,), "padding": (1,)}) else: - kwargs["window_size"] = (4, 0) + windows = {"padding_causal_bottom_right": (-1, 0)} with pytest.raises(ValueError, match=error): attention( @@ -168,12 +359,13 @@ def test_mixed_thd_rejects_unsupported_inputs(invalid_case, error): cu_seqlens_kv=cu_seqlens, max_seqlen_q=2, max_seqlen_kv=2, - **kwargs, + attn_mask_type_per_seq=policies, + window_size_per_mask_type=windows, ) -def test_mixed_thd_empty_batch_preserves_input_gradients(): - """An all-empty packed batch needs zero gradients, not a disconnected output.""" +def test_thd_mask_types_empty_batch_preserves_input_gradients(): + """An empty packed batch needs zero gradients, not a disconnected output.""" attention = _make_dpa(torch.float16) query = torch.empty( 0, NUM_HEADS, HEAD_DIM, device="cuda", dtype=torch.float16, requires_grad=True @@ -191,7 +383,7 @@ def test_mixed_thd_empty_batch_preserves_input_gradients(): cu_seqlens_kv=cu_seqlens, max_seqlen_q=0, max_seqlen_kv=0, - thd_sequence_is_causal=torch.empty(0, dtype=torch.bool, device="cuda"), + attn_mask_type_per_seq={"padding": torch.empty(0, dtype=torch.int64, device="cuda")}, ) assert output.shape == (0, NUM_HEADS * HEAD_DIM) output.sum().backward() 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 a6137081c02..4d286852cbf 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 @@ -1323,97 +1323,135 @@ def get_quantizer_roles( ] return base[:num_quantizers] - def _forward_mixed_thd( + @staticmethod + def _select_thd_sequences( + cu_seqlens: torch.Tensor, + cu_seqlens_padded: Optional[torch.Tensor], + sequence_ids: torch.Tensor, + ) -> Tuple[torch.Tensor, torch.Tensor]: + """Describe selected THD sequences without moving their token storage.""" + sequence_ids = sequence_ids.to(dtype=torch.long) + physical_cu_seqlens = cu_seqlens if cu_seqlens_padded is None else cu_seqlens_padded + physical_starts = physical_cu_seqlens.index_select(0, sequence_ids) + sequence_lengths = cu_seqlens.index_select(0, sequence_ids + 1) - cu_seqlens.index_select( + 0, sequence_ids + ) + selected_cu_seqlens = torch.cat( + ( + sequence_lengths.new_zeros(1), + torch.cumsum(sequence_lengths, dim=0, dtype=torch.int32), + ) + ) + selected_cu_seqlens_padded = torch.cat( + (physical_starts, physical_cu_seqlens[-1:]) + ) + return selected_cu_seqlens, selected_cu_seqlens_padded + + def _forward_thd_mask_types( self, query_layer: torch.Tensor, key_layer: torch.Tensor, value_layer: torch.Tensor, - cu_seqlens: torch.Tensor, - thd_sequence_is_causal: torch.Tensor, + cu_seqlens_q: torch.Tensor, + cu_seqlens_kv: torch.Tensor, + cu_seqlens_q_padded: Optional[torch.Tensor], + cu_seqlens_kv_padded: Optional[torch.Tensor], + attn_mask_type_per_seq: Dict[str, torch.Tensor], + window_size_per_mask_type: Optional[Dict[str, Tuple[int, int]]], max_seqlen_q: Optional[int], max_seqlen_kv: Optional[int], *, + window_size: Optional[Tuple[int, int]], + checkpoint_core_attention: bool, fast_zero_fill: bool, + pad_between_seqs: Optional[bool], + bf16_backward: Optional[bool], + num_splits: Optional[int], ) -> torch.Tensor: - """Dispatch mixed causal/non-causal THD self-attention. + """Dispatch per-sequence THD masks without regrouping Q/K/V tokens. - Group whole sequences by policy, call the existing scalar-policy path - for each non-empty group, and restore the original packed token order. + Each scalar-mask call sees the original Q/K/V storage. Sequences assigned + to other mask types are represented as inter-sequence padding, so the + backend leaves zeros at those positions. The disjoint outputs can then be + added without a token gather or scatter. """ - sequence_lengths = cu_seqlens[1:] - cu_seqlens[:-1] - token_count = query_layer.shape[0] output_features = query_layer.shape[-2] * value_layer.shape[-1] - - if token_count == 0: + if query_layer.shape[0] == 0: empty_output = query_layer.new_empty((0, output_features)) return empty_output + 0 * (query_layer.sum() + key_layer.sum() + value_layer.sum()) - def run_scalar_policy( - group_query: torch.Tensor, - group_key: torch.Tensor, - group_value: torch.Tensor, - group_cu_seqlens: torch.Tensor, - group_max_seqlen_q: Optional[int], - group_max_seqlen_kv: Optional[int], - is_causal: bool, - ) -> torch.Tensor: + nonempty_mask_types = [ + mask_type + for mask_type, sequence_ids in attn_mask_type_per_seq.items() + if sequence_ids.numel() > 0 + ] + batch_size = cu_seqlens_q.shape[0] - 1 + if ( + len(nonempty_mask_types) == 1 + and attn_mask_type_per_seq[nonempty_mask_types[0]].numel() == batch_size + ): + mask_type = nonempty_mask_types[0] + policy_window_size = window_size + if window_size_per_mask_type is not None: + policy_window_size = window_size_per_mask_type.get(mask_type, window_size) return self.forward( - group_query, - group_key, - group_value, + query_layer, + key_layer, + value_layer, qkv_format="thd", - cu_seqlens_q=group_cu_seqlens, - cu_seqlens_kv=group_cu_seqlens, - max_seqlen_q=group_max_seqlen_q, - max_seqlen_kv=group_max_seqlen_kv, - attn_mask_type="padding_causal" if is_causal else "padding", - window_size=(-1, 0) if is_causal else (-1, -1), - bottom_right_diagonal=False, + cu_seqlens_q=cu_seqlens_q, + cu_seqlens_kv=cu_seqlens_kv, + cu_seqlens_q_padded=cu_seqlens_q_padded, + cu_seqlens_kv_padded=cu_seqlens_kv_padded, + max_seqlen_q=max_seqlen_q, + max_seqlen_kv=max_seqlen_kv, + attn_mask_type=mask_type, + window_size=policy_window_size, + checkpoint_core_attention=checkpoint_core_attention, fast_zero_fill=fast_zero_fill, + pad_between_seqs=pad_between_seqs, + bf16_backward=bf16_backward, + num_splits=num_splits, ) - first_policy = bool(thd_sequence_is_causal[0].item()) - if bool(torch.all(thd_sequence_is_causal == first_policy).item()): - return run_scalar_policy( + output = None + for mask_type in nonempty_mask_types: + sequence_ids = attn_mask_type_per_seq[mask_type] + selected_cu_seqlens_q, selected_cu_seqlens_q_padded = self._select_thd_sequences( + cu_seqlens_q, + cu_seqlens_q_padded, + sequence_ids, + ) + selected_cu_seqlens_kv, selected_cu_seqlens_kv_padded = self._select_thd_sequences( + cu_seqlens_kv, + cu_seqlens_kv_padded, + sequence_ids, + ) + policy_window_size = window_size + if window_size_per_mask_type is not None: + policy_window_size = window_size_per_mask_type.get(mask_type, window_size) + policy_output = self.forward( query_layer, key_layer, value_layer, - cu_seqlens, - max_seqlen_q, - max_seqlen_kv, - is_causal=first_policy, - ) - - token_is_causal = torch.repeat_interleave( - thd_sequence_is_causal, - sequence_lengths.to(dtype=torch.long), - output_size=token_count, - ) - output = query_layer.new_empty((token_count, output_features)) - for is_causal in (False, True): - sequence_mask = thd_sequence_is_causal == is_causal - group_token_indices = torch.nonzero(token_is_causal == is_causal).flatten() - if group_token_indices.numel() == 0: - continue - group_lengths = sequence_lengths[sequence_mask] - group_cu_seqlens = torch.cat( - ( - group_lengths.new_zeros(1), - torch.cumsum(group_lengths, dim=0, dtype=torch.int32), - ) - ) - group_max_seqlen = int(group_lengths.max().item()) - group_output = run_scalar_policy( - query_layer.index_select(0, group_token_indices), - key_layer.index_select(0, group_token_indices), - value_layer.index_select(0, group_token_indices), - group_cu_seqlens, - group_max_seqlen, - group_max_seqlen, - is_causal=is_causal, + qkv_format="thd", + cu_seqlens_q=selected_cu_seqlens_q, + cu_seqlens_kv=selected_cu_seqlens_kv, + cu_seqlens_q_padded=selected_cu_seqlens_q_padded, + cu_seqlens_kv_padded=selected_cu_seqlens_kv_padded, + max_seqlen_q=max_seqlen_q, + max_seqlen_kv=max_seqlen_kv, + attn_mask_type=mask_type, + window_size=policy_window_size, + checkpoint_core_attention=checkpoint_core_attention, + fast_zero_fill=fast_zero_fill, + pad_between_seqs=True, + bf16_backward=bf16_backward, + num_splits=num_splits, ) - output = output.index_copy(0, group_token_indices, group_output) - + output = policy_output if output is None else output + policy_output + if output is None: + raise ValueError("attn_mask_type_per_seq must assign at least one sequence.") return output @no_torch_dynamo(recursive=False) @@ -1450,7 +1488,8 @@ def forward( qkv_layer: Optional[torch.Tensor] = None, kv_layer: Optional[torch.Tensor] = None, qkv_interleave_dim: int = -3, - thd_sequence_is_causal: Optional[torch.Tensor] = None, + attn_mask_type_per_seq: Optional[Dict[str, torch.Tensor]] = None, + window_size_per_mask_type: Optional[Dict[str, Tuple[int, int]]] = None, ) -> torch.Tensor: r""" Dot Product Attention Layer. @@ -1690,146 +1729,59 @@ def forward( interleave sits; must be -3 (e.g. ``bs3hd``) or -2 (e.g. ``bsh3d``, Megatron-style). This is an explicit knob rather than shape inference, since e.g. ``h == 3`` would make the shapes ambiguous. - thd_sequence_is_causal: Optional[torch.Tensor], default = None - Per-sequence causal policy for packed THD self-attention. When supplied, - it must be a CUDA ``torch.bool`` tensor of shape ``[batch_size]``, where - ``batch_size = cu_seqlens_q.numel() - 1``. ``True`` selects causal - attention for that sequence and ``False`` selects full-context - attention. Transformer Engine groups the two policies and launches the - existing scalar-mask attention path once per non-empty group, then - restores the original packed token order. It therefore shares the - surrounding encoder computation but is not a single fused-attention - kernel. Initial support is limited to FP16/BF16 THD self-attention - without attention dropout, context parallelism, cacheing, FP8, - arbitrary padding between packed sequences, bias/ALiBi, score-mod, or - attention checkpointing. + attn_mask_type_per_seq: Optional[Dict[str, torch.Tensor]], default = None + Per-sequence mask policies for packed THD attention. Each key is an + attention mask type and each value is a one-dimensional, ascending CUDA + integer tensor containing the sequence IDs assigned to that mask. The + sequence-ID tensors must be disjoint and together contain every sequence + exactly once. Transformer Engine keeps Q/K/V in their original packed + layout and describes the sequences assigned to other policies as + inter-sequence padding. It launches the existing scalar-mask attention + path once per non-empty policy and adds the disjoint outputs. + window_size_per_mask_type: Optional[Dict[str, Tuple[int, int]]], default = None + Optional sliding-window override for each key in + :attr:`attn_mask_type_per_seq`. This is useful when, for example, offline + sequences need full context while causal sequences use bounded left + context. Missing keys fall back to :attr:`window_size`. """ - if thd_sequence_is_causal is not None: - resolved_qkv_format = qkv_format if qkv_format is not None else self.qkv_format - if resolved_qkv_format != "thd": - raise ValueError("thd_sequence_is_causal is supported only with qkv_format='thd'.") - if ( - qkv_layer is not None - or kv_layer is not None - or query_layer is None - or key_layer is None - or value_layer is None - ): - raise ValueError( - "thd_sequence_is_causal requires separate query_layer, key_layer, and " - "value_layer." - ) - qkv = (query_layer, key_layer, value_layer) - if not all(tensor.is_cuda and tensor.device == query_layer.device for tensor in qkv): - raise ValueError( - "thd_sequence_is_causal requires CUDA Q, K, and V on the same device." - ) - if query_layer.dtype not in (torch.float16, torch.bfloat16) or not all( - tensor.dtype == query_layer.dtype for tensor in qkv - ): - raise ValueError( - "thd_sequence_is_causal requires FP16 or BF16 Q, K, and V of the same dtype." - ) - if self.attention_type != "self": - raise ValueError("thd_sequence_is_causal is supported only for self-attention.") - if cu_seqlens_q is None or cu_seqlens_kv is None: - raise ValueError("thd_sequence_is_causal requires cu_seqlens_q and cu_seqlens_kv.") - if not all( - cu_seqlens.ndim == 1 - and cu_seqlens.numel() >= 1 - and cu_seqlens.dtype == torch.int32 - and cu_seqlens.device == query_layer.device - for cu_seqlens in (cu_seqlens_q, cu_seqlens_kv) - ): - raise ValueError( - "thd_sequence_is_causal requires one-dimensional int32 cu_seqlens " - "on the Q/K/V device." - ) - if not torch.equal(cu_seqlens_q, cu_seqlens_kv): - raise ValueError( - "thd_sequence_is_causal requires identical Q and KV sequence boundaries." - ) - if thd_sequence_is_causal.dtype != torch.bool or thd_sequence_is_causal.ndim != 1: - raise ValueError( - "thd_sequence_is_causal must be a one-dimensional torch.bool tensor." - ) - if thd_sequence_is_causal.device != query_layer.device: - raise ValueError( - "thd_sequence_is_causal must be on the same device as query_layer." - ) - if thd_sequence_is_causal.numel() != cu_seqlens_q.numel() - 1: - raise ValueError( - "thd_sequence_is_causal must have one value per packed sequence: " - f"got {thd_sequence_is_causal.numel()} values for " - f"{cu_seqlens_q.numel() - 1} sequences." - ) - if not all( - tensor.ndim == 3 and tensor.shape[0] == query_layer.shape[0] for tensor in qkv - ): - raise ValueError( - "thd_sequence_is_causal requires THD Q, K, and V with the same token count." - ) - if int(cu_seqlens_q[-1].item()) != query_layer.shape[0]: - raise ValueError("The final cu_seqlens value must equal the THD Q/K/V token count.") - unsupported_options = ( - attention_mask is not None, - cu_seqlens_q_padded is not None, - cu_seqlens_kv_padded is not None, - inference_params is not None, - checkpoint_core_attention, - core_attention_bias_type != "no_bias", - core_attention_bias is not None, - alibi_slopes is not None, - score_mod is not None, - score_mod_bprop is not None, - score_mod_tensors is not None, - score_mod_bprop_tensors is not None, - fp8_output, - self.fp8, - self.attention_dropout != 0.0, - self.softmax_type != "vanilla", - self.return_max_logit, - self.cp_group is not None, - pad_between_seqs not in (None, False), - num_splits not in (None, 1), - ) - if any(unsupported_options): - raise ValueError( - "thd_sequence_is_causal currently supports only plain THD self-attention " - "without padding gaps, dropout, bias, score-mod, caching, FP8 output, " - "context parallelism, softmax variants, or attention checkpointing." - ) - if FP8GlobalStateManager.is_fp8_enabled() or FP8GlobalStateManager.is_fp8_calibration(): - raise ValueError("thd_sequence_is_causal does not yet support FP8 attention.") - if is_graph_capturing() or is_in_onnx_export_mode(): - raise ValueError( - "thd_sequence_is_causal does not yet support CUDA graph capture or ONNX export." - ) - effective_window_size = self.window_size if window_size is None else window_size - if effective_window_size not in {(-1, -1), (-1, 0)}: - raise ValueError( - "thd_sequence_is_causal does not yet support sliding-window attention." - ) - effective_bottom_right_diagonal = ( - self.bottom_right_diagonal - if bottom_right_diagonal is None - else bottom_right_diagonal - ) - if effective_bottom_right_diagonal is True: - raise ValueError( - "thd_sequence_is_causal requires the standard top-left causal diagonal." - ) - return self._forward_mixed_thd( - query_layer, - key_layer, - value_layer, - cu_seqlens_q, - thd_sequence_is_causal, - max_seqlen_q, - max_seqlen_kv, - fast_zero_fill=fast_zero_fill, + if window_size_per_mask_type is not None and attn_mask_type_per_seq is None: + raise ValueError( + "window_size_per_mask_type requires attn_mask_type_per_seq." ) + if attn_mask_type_per_seq is not None: + if not isinstance(attn_mask_type_per_seq, dict) or not attn_mask_type_per_seq: + raise ValueError("attn_mask_type_per_seq must be a non-empty dictionary.") + normalized_mask_types = {} + for mask_type, sequence_ids in attn_mask_type_per_seq.items(): + if not isinstance(mask_type, str): + raise ValueError("attn_mask_type_per_seq keys must be attention mask strings.") + mask_type = mask_type.replace(",", "_") + if mask_type == "causal_padding": + mask_type = "padding_causal" + if mask_type not in AttnMaskTypes or "padding" not in mask_type: + raise ValueError( + "attn_mask_type_per_seq supports only padding mask types, got " + f"{mask_type!r}." + ) + if mask_type in normalized_mask_types: + raise ValueError(f"Duplicate normalized attention mask type {mask_type!r}.") + normalized_mask_types[mask_type] = sequence_ids + attn_mask_type_per_seq = normalized_mask_types + + if window_size_per_mask_type is not None: + normalized_window_sizes = {} + for mask_type, policy_window_size in window_size_per_mask_type.items(): + mask_type = mask_type.replace(",", "_") + if mask_type == "causal_padding": + mask_type = "padding_causal" + if mask_type not in attn_mask_type_per_seq: + raise ValueError( + "window_size_per_mask_type contains a mask not present in " + f"attn_mask_type_per_seq: {mask_type!r}." + ) + normalized_window_sizes[mask_type] = policy_window_size + window_size_per_mask_type = normalized_window_sizes query_layer, key_layer, value_layer, declared_qkv_layout = _unpack_packed_qkv( qkv_layer, @@ -1909,7 +1861,11 @@ def forward( ) # checks for attention mask - if attn_mask_type is None: + if attn_mask_type_per_seq is not None: + # This scalar is used only for shared shape/window validation. + # Each policy call below uses its dictionary key. + attn_mask_type = next(iter(attn_mask_type_per_seq)) + elif attn_mask_type is None: attn_mask_type = self.attn_mask_type else: attn_mask_type = attn_mask_type.replace(",", "_") @@ -1986,6 +1942,84 @@ def forward( seqlens_kv = cu_seqlens_kv[1:] - cu_seqlens_kv[:-1] max_seqlen_kv = int((seqlens_kv.max().item() + 63) // 64 * 64) + if attn_mask_type_per_seq is not None: + if qkv_format != "thd": + raise ValueError( + "attn_mask_type_per_seq is supported only with qkv_format='thd'." + ) + if attention_mask is not None: + raise ValueError( + "attn_mask_type_per_seq does not support an explicit attention_mask." + ) + if ( + core_attention_bias_type != "no_bias" + or core_attention_bias is not None + or alibi_slopes is not None + ): + raise ValueError( + "attn_mask_type_per_seq does not yet support attention bias or ALiBi." + ) + if inference_params is not None: + raise ValueError( + "attn_mask_type_per_seq does not support KV caching." + ) + if ( + score_mod is not None + or score_mod_bprop is not None + or score_mod_tensors is not None + or score_mod_bprop_tensors is not None + ): + raise ValueError( + "attn_mask_type_per_seq does not support score modification." + ) + if fp8_output or self.fp8 or self.return_max_logit: + raise ValueError( + "attn_mask_type_per_seq does not yet support FP8 or max-logit output." + ) + assigned_sequence_count = 0 + for sequence_ids in attn_mask_type_per_seq.values(): + if not isinstance(sequence_ids, torch.Tensor): + raise ValueError( + "attn_mask_type_per_seq values must be sequence-ID tensors." + ) + if sequence_ids.ndim != 1 or sequence_ids.dtype not in ( + torch.int32, + torch.int64, + ): + raise ValueError( + "attn_mask_type_per_seq values must be one-dimensional int32 or " + "int64 sequence-ID tensors." + ) + if not sequence_ids.is_cuda or sequence_ids.device != query_layer.device: + raise ValueError( + "attn_mask_type_per_seq sequence IDs must be on the Q/K/V device." + ) + assigned_sequence_count += sequence_ids.numel() + if assigned_sequence_count != batch_size: + raise ValueError( + "attn_mask_type_per_seq must assign every sequence exactly once by count: " + f"got {assigned_sequence_count} assignments for {batch_size} sequences." + ) + return self._forward_thd_mask_types( + query_layer, + key_layer, + value_layer, + cu_seqlens_q, + cu_seqlens_kv, + cu_seqlens_q_padded, + cu_seqlens_kv_padded, + attn_mask_type_per_seq, + window_size_per_mask_type, + max_seqlen_q, + max_seqlen_kv, + window_size=window_size, + checkpoint_core_attention=checkpoint_core_attention, + fast_zero_fill=fast_zero_fill, + pad_between_seqs=pad_between_seqs, + bf16_backward=bf16_backward, + num_splits=num_splits, + ) + # update KV cache and retrieve saved tokens from cache for inference if inference_params is not None: assert self.layer_number is not None, "Layer number must be set!" From 98dcf173445c421171c01fa000c34cd0198ac5d1 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Fri, 7 Aug 2026 18:00:10 +0000 Subject: [PATCH 04/16] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- .../attention/test_mixed_thd_attention.py | 8 ++------ .../dot_product_attention.py | 16 ++++------------ 2 files changed, 6 insertions(+), 18 deletions(-) diff --git a/tests/pytorch/attention/test_mixed_thd_attention.py b/tests/pytorch/attention/test_mixed_thd_attention.py index 4cb3f395781..5d6fd6f16fa 100644 --- a/tests/pytorch/attention/test_mixed_thd_attention.py +++ b/tests/pytorch/attention/test_mixed_thd_attention.py @@ -62,9 +62,7 @@ def _per_sequence_scalar_reference( for mask_type, sequence_ids in mask_type_per_seq.items(): for sequence_id in sequence_ids.tolist(): q_length = int((cu_seqlens_q[sequence_id + 1] - cu_seqlens_q[sequence_id]).item()) - kv_length = int( - (cu_seqlens_kv[sequence_id + 1] - cu_seqlens_kv[sequence_id]).item() - ) + kv_length = int((cu_seqlens_kv[sequence_id + 1] - cu_seqlens_kv[sequence_id]).item()) q_start = int(q_physical[sequence_id].item()) kv_start = int(kv_physical[sequence_id].item()) q_end = q_start + q_length @@ -231,9 +229,7 @@ def test_thd_mask_types_support_cross_attention_and_per_policy_windows(): dtype = torch.float16 cu_seqlens_q = _make_cu_seqlens((5, 3, 4)) cu_seqlens_kv = _make_cu_seqlens((7, 2, 5)) - mask_type_per_seq = _make_policy( - {"padding": (0, 2), "padding_causal_bottom_right": (1,)} - ) + mask_type_per_seq = _make_policy({"padding": (0, 2), "padding_causal_bottom_right": (1,)}) windows = {"padding": (-1, -1), "padding_causal_bottom_right": (2, 0)} query = ( 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 4d286852cbf..e3a177b0476 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 @@ -1342,9 +1342,7 @@ def _select_thd_sequences( torch.cumsum(sequence_lengths, dim=0, dtype=torch.int32), ) ) - selected_cu_seqlens_padded = torch.cat( - (physical_starts, physical_cu_seqlens[-1:]) - ) + selected_cu_seqlens_padded = torch.cat((physical_starts, physical_cu_seqlens[-1:])) return selected_cu_seqlens, selected_cu_seqlens_padded def _forward_thd_mask_types( @@ -1746,9 +1744,7 @@ def forward( """ if window_size_per_mask_type is not None and attn_mask_type_per_seq is None: - raise ValueError( - "window_size_per_mask_type requires attn_mask_type_per_seq." - ) + raise ValueError("window_size_per_mask_type requires attn_mask_type_per_seq.") if attn_mask_type_per_seq is not None: if not isinstance(attn_mask_type_per_seq, dict) or not attn_mask_type_per_seq: raise ValueError("attn_mask_type_per_seq must be a non-empty dictionary.") @@ -1960,18 +1956,14 @@ def forward( "attn_mask_type_per_seq does not yet support attention bias or ALiBi." ) if inference_params is not None: - raise ValueError( - "attn_mask_type_per_seq does not support KV caching." - ) + raise ValueError("attn_mask_type_per_seq does not support KV caching.") if ( score_mod is not None or score_mod_bprop is not None or score_mod_tensors is not None or score_mod_bprop_tensors is not None ): - raise ValueError( - "attn_mask_type_per_seq does not support score modification." - ) + raise ValueError("attn_mask_type_per_seq does not support score modification.") if fp8_output or self.fp8 or self.return_max_logit: raise ValueError( "attn_mask_type_per_seq does not yet support FP8 or max-logit output." From d52a461478ce4ffab5ba9b41a6cb3fea9e9898f1 Mon Sep 17 00:00:00 2001 From: Desh Raj Date: Fri, 7 Aug 2026 14:20:49 -0700 Subject: [PATCH 05/16] Mask inactive mixed-THD lanes for FA3 Mixed-mask dispatch represents sequences owned by other policies as inter-sequence padding. FA3 preserves that layout contract, but its padding lanes are unspecified: focused Hopper testing observed NaNs in inactive forward outputs and tile-spill garbage in inactive dQ/dK/dV lanes. Build a sync-free mask from the physical cu_seqlens, sanitize each policy output with torch.where, and wrap Q/K/V in an identity-forward autograd guard that zeros only inactive gradient lanes. This keeps the pad_between_seqs design, avoids regrouping or copying tokens, and lets disjoint policy results be summed safely across FA2 and FA3. Validation: NRT H100 source-overlay run passed all 16 focused mixed-THD tests for FP16/BF16 forward and backward, pre-existing padding, cross attention, per-policy windows, CUDA graphs, and validation errors. Signed-off-by: Desh Raj --- .../dot_product_attention.py | 71 +++++++++++++++++-- 1 file changed, 66 insertions(+), 5 deletions(-) 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 e3a177b0476..c3a0a509e58 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 @@ -87,6 +87,20 @@ } +class _IdentityWithMaskedGradient(torch.autograd.Function): + """Preserve tensor storage in forward and zero unselected backward lanes.""" + + @staticmethod + def forward(ctx, tensor: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: + ctx.save_for_backward(mask) + return tensor + + @staticmethod + def backward(ctx, grad_output: torch.Tensor) -> Tuple[torch.Tensor, None]: + (mask,) = ctx.saved_tensors + return torch.where(mask, grad_output, 0.0), None + + def _infer_custom_dpa_local_recipes( fp8_recipe: Recipe, fp8_meta: Dict[str, Any], @@ -1345,6 +1359,30 @@ def _select_thd_sequences( selected_cu_seqlens_padded = torch.cat((physical_starts, physical_cu_seqlens[-1:])) return selected_cu_seqlens, selected_cu_seqlens_padded + @staticmethod + def _selected_thd_token_mask( + token_count: int, + cu_seqlens: torch.Tensor, + cu_seqlens_padded: Optional[torch.Tensor], + sequence_ids: torch.Tensor, + ) -> torch.Tensor: + """Return a sync-free mask for selected tokens in physical THD storage.""" + sequence_ids = sequence_ids.to(dtype=torch.long) + physical_cu_seqlens = cu_seqlens if cu_seqlens_padded is None else cu_seqlens_padded + starts = physical_cu_seqlens.index_select(0, sequence_ids) + lengths = cu_seqlens.index_select(0, sequence_ids + 1) - cu_seqlens.index_select( + 0, sequence_ids + ) + ends = starts + lengths + boundaries = torch.cat((starts, ends)).to(dtype=torch.long) + deltas = torch.cat((torch.ones_like(starts), -torch.ones_like(ends))) + token_deltas = torch.zeros( + token_count + 1, + dtype=deltas.dtype, + device=cu_seqlens.device, + ).index_add(0, boundaries, deltas) + return torch.cumsum(token_deltas[:-1], dim=0, dtype=torch.int32).ne(0) + def _forward_thd_mask_types( self, query_layer: torch.Tensor, @@ -1370,8 +1408,9 @@ def _forward_thd_mask_types( Each scalar-mask call sees the original Q/K/V storage. Sequences assigned to other mask types are represented as inter-sequence padding, so the - backend leaves zeros at those positions. The disjoint outputs can then be - added without a token gather or scatter. + backend is allowed to leave unspecified values at those positions. Each + policy output is masked to its selected physical tokens before the + disjoint outputs are added, without a token gather or scatter. """ output_features = query_layer.shape[-2] * value_layer.shape[-1] if query_layer.shape[0] == 0: @@ -1415,6 +1454,27 @@ def _forward_thd_mask_types( output = None for mask_type in nonempty_mask_types: sequence_ids = attn_mask_type_per_seq[mask_type] + policy_q_token_mask = self._selected_thd_token_mask( + query_layer.shape[0], + cu_seqlens_q, + cu_seqlens_q_padded, + sequence_ids, + ) + policy_kv_token_mask = self._selected_thd_token_mask( + key_layer.shape[0], + cu_seqlens_kv, + cu_seqlens_kv_padded, + sequence_ids, + ) + policy_query = _IdentityWithMaskedGradient.apply( + query_layer, policy_q_token_mask[:, None, None] + ) + policy_key = _IdentityWithMaskedGradient.apply( + key_layer, policy_kv_token_mask[:, None, None] + ) + policy_value = _IdentityWithMaskedGradient.apply( + value_layer, policy_kv_token_mask[:, None, None] + ) selected_cu_seqlens_q, selected_cu_seqlens_q_padded = self._select_thd_sequences( cu_seqlens_q, cu_seqlens_q_padded, @@ -1429,9 +1489,9 @@ def _forward_thd_mask_types( if window_size_per_mask_type is not None: policy_window_size = window_size_per_mask_type.get(mask_type, window_size) policy_output = self.forward( - query_layer, - key_layer, - value_layer, + policy_query, + policy_key, + policy_value, qkv_format="thd", cu_seqlens_q=selected_cu_seqlens_q, cu_seqlens_kv=selected_cu_seqlens_kv, @@ -1447,6 +1507,7 @@ def _forward_thd_mask_types( bf16_backward=bf16_backward, num_splits=num_splits, ) + policy_output = torch.where(policy_q_token_mask.unsqueeze(-1), policy_output, 0.0) output = policy_output if output is None else output + policy_output if output is None: raise ValueError("attn_mask_type_per_seq must assign at least one sequence.") From 1b278a2b8cf5433d9a87ac44795f8c3e7c6de850 Mon Sep 17 00:00:00 2001 From: Desh Raj Date: Sat, 8 Aug 2026 04:51:19 -0700 Subject: [PATCH 06/16] Select mixed THD implementation by GPU backend Keep attn_mask_type_per_seq and window_size_per_mask_type invariant at the caller boundary while selecting the physical implementation inside DotProductAttention. Use inter-sequence padding only on SM90 when FlashAttention 3 is installed and enabled. Fall back to per-policy token compaction, scalar THD attention, and output restoration for FlashAttention 2 and other configurations. Preserve the uniform-policy scalar fast path and restrict CUDA graph coverage to the sync-free FA3 padding path. Add a runtime dispatch matrix covering architecture, FA3 availability, and backend environment controls. Validation: - NRT H100/FA3: 21 mixed-THD tests and 4 Megatron policy/API tests passed - IAD A100/FA2: 20 mixed-THD tests passed, 1 Hopper-only graph test skipped, and 4 Megatron policy/API tests passed - Installed-image five-step training smokes were bit-identical within FA3 across NRT/HEL and within FA2 across IAD/ORD; maximum cross-backend loss delta was 1.56e-5 --- .../attention/test_mixed_thd_attention.py | 35 +++ .../dot_product_attention.py | 239 ++++++++++++++---- 2 files changed, 226 insertions(+), 48 deletions(-) diff --git a/tests/pytorch/attention/test_mixed_thd_attention.py b/tests/pytorch/attention/test_mixed_thd_attention.py index 5d6fd6f16fa..2bed4d9605e 100644 --- a/tests/pytorch/attention/test_mixed_thd_attention.py +++ b/tests/pytorch/attention/test_mixed_thd_attention.py @@ -8,6 +8,9 @@ import torch from transformer_engine.pytorch import DotProductAttention +from transformer_engine.pytorch.attention.dot_product_attention import ( + dot_product_attention as dpa_module, +) pytestmark = pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA is required") @@ -277,8 +280,40 @@ def test_thd_mask_types_support_cross_attention_and_per_policy_windows(): torch.testing.assert_close(actual_grad, reference_grad, atol=1.0e-3, rtol=1.0e-3) +@pytest.mark.parametrize( + ("compute_capability", "fa3_installed", "flash_enabled", "fa3_enabled", "expected"), + ( + ((9, 0), True, "1", "1", True), + ((8, 0), True, "1", "1", False), + ((9, 0), False, "1", "1", False), + ((9, 0), True, "0", "1", False), + ((9, 0), True, "1", "0", False), + ), +) +def test_thd_mask_type_runtime_dispatch( + monkeypatch, + compute_capability, + fa3_installed, + flash_enabled, + fa3_enabled, + expected, +): + """Only Hopper with enabled FA3 uses the inter-sequence-padding implementation.""" + monkeypatch.setattr( + dpa_module.dpa_utils, "get_device_compute_capability", lambda: compute_capability + ) + monkeypatch.setattr(dpa_module.FlashAttentionUtils, "v3_is_installed", fa3_installed) + monkeypatch.setenv("NVTE_FLASH_ATTN", flash_enabled) + monkeypatch.setenv("NVTE_FLASH_ATTN_V3", fa3_enabled) + + assert DotProductAttention._use_thd_mask_type_padding_dispatch() is expected + + def test_thd_mask_types_support_cuda_graph_capture(): """The sync-free policy metadata path must be replayable in a CUDA graph.""" + if not DotProductAttention._use_thd_mask_type_padding_dispatch(): + pytest.skip("CUDA graph capture requires the Hopper/FA3 padding implementation") + torch.manual_seed(1234) dtype = torch.float16 cu_seqlens = _make_cu_seqlens((7, 3, 5, 4)) 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 c3a0a509e58..88ca7b0af9b 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 @@ -1383,7 +1383,16 @@ def _selected_thd_token_mask( ).index_add(0, boundaries, deltas) return torch.cumsum(token_deltas[:-1], dim=0, dtype=torch.int32).ne(0) - def _forward_thd_mask_types( + @staticmethod + def _use_thd_mask_type_padding_dispatch() -> bool: + return ( + dpa_utils.get_device_compute_capability() == (9, 0) + and FlashAttentionUtils.v3_is_installed + and bool(int(os.environ.get("NVTE_FLASH_ATTN", "1"))) + and bool(int(os.environ.get("NVTE_FLASH_ATTN_V3", "1"))) + ) + + def _forward_thd_mask_types_with_padding( self, query_layer: torch.Tensor, key_layer: torch.Tensor, @@ -1400,57 +1409,15 @@ def _forward_thd_mask_types( window_size: Optional[Tuple[int, int]], checkpoint_core_attention: bool, fast_zero_fill: bool, - pad_between_seqs: Optional[bool], bf16_backward: Optional[bool], num_splits: Optional[int], ) -> torch.Tensor: - """Dispatch per-sequence THD masks without regrouping Q/K/V tokens. - - Each scalar-mask call sees the original Q/K/V storage. Sequences assigned - to other mask types are represented as inter-sequence padding, so the - backend is allowed to leave unspecified values at those positions. Each - policy output is masked to its selected physical tokens before the - disjoint outputs are added, without a token gather or scatter. - """ - output_features = query_layer.shape[-2] * value_layer.shape[-1] - if query_layer.shape[0] == 0: - empty_output = query_layer.new_empty((0, output_features)) - return empty_output + 0 * (query_layer.sum() + key_layer.sum() + value_layer.sum()) - + """Dispatch mixed THD masks with FA3 inter-sequence padding.""" nonempty_mask_types = [ mask_type for mask_type, sequence_ids in attn_mask_type_per_seq.items() if sequence_ids.numel() > 0 ] - batch_size = cu_seqlens_q.shape[0] - 1 - if ( - len(nonempty_mask_types) == 1 - and attn_mask_type_per_seq[nonempty_mask_types[0]].numel() == batch_size - ): - mask_type = nonempty_mask_types[0] - policy_window_size = window_size - if window_size_per_mask_type is not None: - policy_window_size = window_size_per_mask_type.get(mask_type, window_size) - return self.forward( - query_layer, - key_layer, - value_layer, - qkv_format="thd", - cu_seqlens_q=cu_seqlens_q, - cu_seqlens_kv=cu_seqlens_kv, - cu_seqlens_q_padded=cu_seqlens_q_padded, - cu_seqlens_kv_padded=cu_seqlens_kv_padded, - max_seqlen_q=max_seqlen_q, - max_seqlen_kv=max_seqlen_kv, - attn_mask_type=mask_type, - window_size=policy_window_size, - checkpoint_core_attention=checkpoint_core_attention, - fast_zero_fill=fast_zero_fill, - pad_between_seqs=pad_between_seqs, - bf16_backward=bf16_backward, - num_splits=num_splits, - ) - output = None for mask_type in nonempty_mask_types: sequence_ids = attn_mask_type_per_seq[mask_type] @@ -1513,6 +1480,180 @@ def _forward_thd_mask_types( raise ValueError("attn_mask_type_per_seq must assign at least one sequence.") return output + def _forward_thd_mask_types_grouped( + self, + query_layer: torch.Tensor, + key_layer: torch.Tensor, + value_layer: torch.Tensor, + cu_seqlens_q: torch.Tensor, + cu_seqlens_kv: torch.Tensor, + cu_seqlens_q_padded: Optional[torch.Tensor], + cu_seqlens_kv_padded: Optional[torch.Tensor], + attn_mask_type_per_seq: Dict[str, torch.Tensor], + window_size_per_mask_type: Optional[Dict[str, Tuple[int, int]]], + max_seqlen_q: Optional[int], + max_seqlen_kv: Optional[int], + *, + window_size: Optional[Tuple[int, int]], + checkpoint_core_attention: bool, + fast_zero_fill: bool, + bf16_backward: Optional[bool], + num_splits: Optional[int], + ) -> torch.Tensor: + """Dispatch mixed THD masks by compacting each policy for FA2.""" + output_features = query_layer.shape[-2] * value_layer.shape[-1] + output = query_layer.new_zeros((query_layer.shape[0], output_features)) + for mask_type, sequence_ids in attn_mask_type_per_seq.items(): + if sequence_ids.numel() == 0: + continue + q_token_mask = self._selected_thd_token_mask( + query_layer.shape[0], + cu_seqlens_q, + cu_seqlens_q_padded, + sequence_ids, + ) + kv_token_mask = self._selected_thd_token_mask( + key_layer.shape[0], + cu_seqlens_kv, + cu_seqlens_kv_padded, + sequence_ids, + ) + q_token_indices = torch.nonzero(q_token_mask, as_tuple=False).flatten() + kv_token_indices = torch.nonzero(kv_token_mask, as_tuple=False).flatten() + selected_cu_seqlens_q, _ = self._select_thd_sequences( + cu_seqlens_q, + cu_seqlens_q_padded, + sequence_ids, + ) + selected_cu_seqlens_kv, _ = self._select_thd_sequences( + cu_seqlens_kv, + cu_seqlens_kv_padded, + sequence_ids, + ) + policy_window_size = window_size + if window_size_per_mask_type is not None: + policy_window_size = window_size_per_mask_type.get(mask_type, window_size) + policy_output = self.forward( + query_layer.index_select(0, q_token_indices), + key_layer.index_select(0, kv_token_indices), + value_layer.index_select(0, kv_token_indices), + qkv_format="thd", + cu_seqlens_q=selected_cu_seqlens_q, + cu_seqlens_kv=selected_cu_seqlens_kv, + max_seqlen_q=max_seqlen_q, + max_seqlen_kv=max_seqlen_kv, + attn_mask_type=mask_type, + window_size=policy_window_size, + checkpoint_core_attention=checkpoint_core_attention, + fast_zero_fill=fast_zero_fill, + pad_between_seqs=False, + bf16_backward=bf16_backward, + num_splits=num_splits, + ) + output = output.index_copy(0, q_token_indices, policy_output) + return output + + def _forward_thd_mask_types( + self, + query_layer: torch.Tensor, + key_layer: torch.Tensor, + value_layer: torch.Tensor, + cu_seqlens_q: torch.Tensor, + cu_seqlens_kv: torch.Tensor, + cu_seqlens_q_padded: Optional[torch.Tensor], + cu_seqlens_kv_padded: Optional[torch.Tensor], + attn_mask_type_per_seq: Dict[str, torch.Tensor], + window_size_per_mask_type: Optional[Dict[str, Tuple[int, int]]], + max_seqlen_q: Optional[int], + max_seqlen_kv: Optional[int], + *, + window_size: Optional[Tuple[int, int]], + checkpoint_core_attention: bool, + fast_zero_fill: bool, + pad_between_seqs: Optional[bool], + bf16_backward: Optional[bool], + num_splits: Optional[int], + ) -> torch.Tensor: + """Dispatch mixed THD masks through the best runtime implementation.""" + output_features = query_layer.shape[-2] * value_layer.shape[-1] + if query_layer.shape[0] == 0: + empty_output = query_layer.new_empty((0, output_features)) + return empty_output + 0 * (query_layer.sum() + key_layer.sum() + value_layer.sum()) + + nonempty_mask_types = [ + mask_type + for mask_type, sequence_ids in attn_mask_type_per_seq.items() + if sequence_ids.numel() > 0 + ] + batch_size = cu_seqlens_q.shape[0] - 1 + if ( + len(nonempty_mask_types) == 1 + and attn_mask_type_per_seq[nonempty_mask_types[0]].numel() == batch_size + ): + mask_type = nonempty_mask_types[0] + policy_window_size = window_size + if window_size_per_mask_type is not None: + policy_window_size = window_size_per_mask_type.get(mask_type, window_size) + return self.forward( + query_layer, + key_layer, + value_layer, + qkv_format="thd", + cu_seqlens_q=cu_seqlens_q, + cu_seqlens_kv=cu_seqlens_kv, + cu_seqlens_q_padded=cu_seqlens_q_padded, + cu_seqlens_kv_padded=cu_seqlens_kv_padded, + max_seqlen_q=max_seqlen_q, + max_seqlen_kv=max_seqlen_kv, + attn_mask_type=mask_type, + window_size=policy_window_size, + checkpoint_core_attention=checkpoint_core_attention, + fast_zero_fill=fast_zero_fill, + pad_between_seqs=pad_between_seqs, + bf16_backward=bf16_backward, + num_splits=num_splits, + ) + if not nonempty_mask_types: + raise ValueError("attn_mask_type_per_seq must assign at least one sequence.") + + if self._use_thd_mask_type_padding_dispatch(): + return self._forward_thd_mask_types_with_padding( + query_layer, + key_layer, + value_layer, + cu_seqlens_q, + cu_seqlens_kv, + cu_seqlens_q_padded, + cu_seqlens_kv_padded, + attn_mask_type_per_seq, + window_size_per_mask_type, + max_seqlen_q, + max_seqlen_kv, + window_size=window_size, + checkpoint_core_attention=checkpoint_core_attention, + fast_zero_fill=fast_zero_fill, + bf16_backward=bf16_backward, + num_splits=num_splits, + ) + return self._forward_thd_mask_types_grouped( + query_layer, + key_layer, + value_layer, + cu_seqlens_q, + cu_seqlens_kv, + cu_seqlens_q_padded, + cu_seqlens_kv_padded, + attn_mask_type_per_seq, + window_size_per_mask_type, + max_seqlen_q, + max_seqlen_kv, + window_size=window_size, + checkpoint_core_attention=checkpoint_core_attention, + fast_zero_fill=fast_zero_fill, + bf16_backward=bf16_backward, + num_splits=num_splits, + ) + @no_torch_dynamo(recursive=False) def forward( self, @@ -1793,10 +1934,12 @@ def forward( attention mask type and each value is a one-dimensional, ascending CUDA integer tensor containing the sequence IDs assigned to that mask. The sequence-ID tensors must be disjoint and together contain every sequence - exactly once. Transformer Engine keeps Q/K/V in their original packed - layout and describes the sequences assigned to other policies as - inter-sequence padding. It launches the existing scalar-mask attention - path once per non-empty policy and adds the disjoint outputs. + exactly once. On Hopper with FlashAttention 3 enabled, Transformer Engine + keeps Q/K/V in their original packed layout and represents sequences owned + by other policies as inter-sequence padding. Otherwise it compacts each + policy's logical tokens for an ordinary scalar-mask call and restores the + original physical THD layout. The caller-facing API is identical for both + implementations. window_size_per_mask_type: Optional[Dict[str, Tuple[int, int]]], default = None Optional sliding-window override for each key in :attr:`attn_mask_type_per_seq`. This is useful when, for example, offline From 654d52442b3e7cc10bca588fffc1820e3aabf4e1 Mon Sep 17 00:00:00 2001 From: Desh Raj Date: Sat, 8 Aug 2026 06:08:29 -0700 Subject: [PATCH 07/16] Centralize mixed THD architecture dispatch --- .../attention/test_mixed_thd_attention.py | 5 +++-- .../dot_product_attention.py | 11 +---------- .../attention/dot_product_attention/utils.py | 16 ++++++++++++++++ 3 files changed, 20 insertions(+), 12 deletions(-) diff --git a/tests/pytorch/attention/test_mixed_thd_attention.py b/tests/pytorch/attention/test_mixed_thd_attention.py index 2bed4d9605e..ea1d726dc8d 100644 --- a/tests/pytorch/attention/test_mixed_thd_attention.py +++ b/tests/pytorch/attention/test_mixed_thd_attention.py @@ -285,6 +285,7 @@ def test_thd_mask_types_support_cross_attention_and_per_policy_windows(): ( ((9, 0), True, "1", "1", True), ((8, 0), True, "1", "1", False), + ((10, 0), True, "1", "1", False), ((9, 0), False, "1", "1", False), ((9, 0), True, "0", "1", False), ((9, 0), True, "1", "0", False), @@ -306,12 +307,12 @@ def test_thd_mask_type_runtime_dispatch( monkeypatch.setenv("NVTE_FLASH_ATTN", flash_enabled) monkeypatch.setenv("NVTE_FLASH_ATTN_V3", fa3_enabled) - assert DotProductAttention._use_thd_mask_type_padding_dispatch() is expected + assert dpa_module.dpa_utils.is_thd_mask_type_padding_supported() is expected def test_thd_mask_types_support_cuda_graph_capture(): """The sync-free policy metadata path must be replayable in a CUDA graph.""" - if not DotProductAttention._use_thd_mask_type_padding_dispatch(): + if not dpa_module.dpa_utils.is_thd_mask_type_padding_supported(): pytest.skip("CUDA graph capture requires the Hopper/FA3 padding implementation") torch.manual_seed(1234) 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 88ca7b0af9b..ad5725c8aff 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 @@ -1383,15 +1383,6 @@ def _selected_thd_token_mask( ).index_add(0, boundaries, deltas) return torch.cumsum(token_deltas[:-1], dim=0, dtype=torch.int32).ne(0) - @staticmethod - def _use_thd_mask_type_padding_dispatch() -> bool: - return ( - dpa_utils.get_device_compute_capability() == (9, 0) - and FlashAttentionUtils.v3_is_installed - and bool(int(os.environ.get("NVTE_FLASH_ATTN", "1"))) - and bool(int(os.environ.get("NVTE_FLASH_ATTN_V3", "1"))) - ) - def _forward_thd_mask_types_with_padding( self, query_layer: torch.Tensor, @@ -1616,7 +1607,7 @@ def _forward_thd_mask_types( if not nonempty_mask_types: raise ValueError("attn_mask_type_per_seq must assign at least one sequence.") - if self._use_thd_mask_type_padding_dispatch(): + if dpa_utils.is_thd_mask_type_padding_supported(): return self._forward_thd_mask_types_with_padding( query_layer, key_layer, diff --git a/transformer_engine/pytorch/attention/dot_product_attention/utils.py b/transformer_engine/pytorch/attention/dot_product_attention/utils.py index 6eb3ce54f18..39d7a7e376d 100644 --- a/transformer_engine/pytorch/attention/dot_product_attention/utils.py +++ b/transformer_engine/pytorch/attention/dot_product_attention/utils.py @@ -379,6 +379,22 @@ def _get_fused_attn_backend( ) +def is_thd_mask_type_padding_supported() -> bool: + """Whether mixed THD masks can use the inter-sequence-padding implementation. + + FlashAttention 3 is the FlashAttention backend that supports padding between + sequences, and TE only enables it on Hopper (SM90). Keep this capability + selection next to the rest of the attention backend architecture filters so + callers can fall back without exposing a hardware-specific API. + """ + return ( + get_device_compute_capability() == (9, 0) + and FlashAttentionUtils.v3_is_installed + and bool(int(os.environ.get("NVTE_FLASH_ATTN", "1"))) + and bool(int(os.environ.get("NVTE_FLASH_ATTN_V3", "1"))) + ) + + def get_attention_backend( attention_params: AttentionParams = None, ): From fff75e60c2a558c166b483bb8842391eb9efdbb0 Mon Sep 17 00:00:00 2001 From: Desh Raj Date: Wed, 19 Aug 2026 07:13:57 -0700 Subject: [PATCH 08/16] Fix mixed THD window normalization order --- .../attention/test_mixed_thd_attention.py | 66 ++++++++++++++++++- .../dot_product_attention.py | 27 ++++++-- 2 files changed, 86 insertions(+), 7 deletions(-) diff --git a/tests/pytorch/attention/test_mixed_thd_attention.py b/tests/pytorch/attention/test_mixed_thd_attention.py index ea1d726dc8d..26de85e499d 100644 --- a/tests/pytorch/attention/test_mixed_thd_attention.py +++ b/tests/pytorch/attention/test_mixed_thd_attention.py @@ -56,6 +56,7 @@ def _per_sequence_scalar_reference( *, cu_seqlens_q_padded=None, cu_seqlens_kv_padded=None, + window_size=None, window_size_per_mask_type=None, ) -> torch.Tensor: """Reference each physical sequence through an ordinary scalar-mask call.""" @@ -76,9 +77,9 @@ def _per_sequence_scalar_reference( sequence_cu_seqlens_kv = torch.tensor( (0, kv_length), dtype=torch.int32, device=query.device ) - policy_window_size = None + policy_window_size = window_size if window_size_per_mask_type is not None: - policy_window_size = window_size_per_mask_type.get(mask_type) + policy_window_size = window_size_per_mask_type.get(mask_type, window_size) outputs[sequence_id] = attention( # THD scalar attention requires zero-offset storage. clone() is # differentiable, so gradients still reach the packed inputs. @@ -280,6 +281,67 @@ def test_thd_mask_types_support_cross_attention_and_per_policy_windows(): torch.testing.assert_close(actual_grad, reference_grad, atol=1.0e-3, rtol=1.0e-3) +@pytest.mark.parametrize( + "mask_type_per_seq", + ( + {"padding_causal": (0, 2), "padding": (1, 3)}, + {"padding": (1, 3), "padding_causal": (0, 2)}, + ), +) +def test_thd_mask_types_default_window_is_independent_of_policy_order(mask_type_per_seq): + """Normalize a shared fallback window independently for every mask policy.""" + torch.manual_seed(1234) + dtype = torch.float16 + cu_seqlens = _make_cu_seqlens((7, 3, 5, 4)) + mask_type_per_seq = _make_policy(mask_type_per_seq) + window_size = (2, 2) + + def make_input(): + return ( + 0.1 * torch.randn(19, NUM_HEADS, HEAD_DIM, dtype=dtype, device="cuda") + ).requires_grad_() + + query, key, value = make_input(), make_input(), make_input() + reference_query = query.detach().clone().requires_grad_() + reference_key = key.detach().clone().requires_grad_() + reference_value = value.detach().clone().requires_grad_() + attention = _make_dpa(dtype) + + output = attention( + query, + key, + value, + qkv_format="thd", + cu_seqlens_q=cu_seqlens, + cu_seqlens_kv=cu_seqlens, + max_seqlen_q=7, + max_seqlen_kv=7, + attn_mask_type_per_seq=mask_type_per_seq, + window_size=window_size, + ) + reference_output = _per_sequence_scalar_reference( + attention, + reference_query, + reference_key, + reference_value, + cu_seqlens, + cu_seqlens, + mask_type_per_seq, + window_size=window_size, + ) + torch.testing.assert_close(output, reference_output, atol=1.0e-3, rtol=1.0e-3) + + output_grad = torch.randn_like(output) + output.backward(output_grad) + reference_output.backward(output_grad) + for actual_grad, reference_grad in ( + (query.grad, reference_query.grad), + (key.grad, reference_key.grad), + (value.grad, reference_value.grad), + ): + torch.testing.assert_close(actual_grad, reference_grad, atol=1.0e-3, rtol=1.0e-3) + + @pytest.mark.parametrize( ("compute_capability", "fa3_installed", "flash_enabled", "fa3_enabled", "expected"), ( 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 ad5725c8aff..3954cc848d7 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 @@ -2053,8 +2053,8 @@ def forward( # checks for attention mask if attn_mask_type_per_seq is not None: - # This scalar is used only for shared shape/window validation. - # Each policy call below uses its dictionary key. + # This scalar is used only for shared THD shape validation. + # Each policy call below uses its dictionary key and resolved window. attn_mask_type = next(iter(attn_mask_type_per_seq)) elif attn_mask_type is None: attn_mask_type = self.attn_mask_type @@ -2067,9 +2067,24 @@ def forward( ), f"Attention mask type {attn_mask_type} is not supported!" # checks for sliding window - if window_size is None: - window_size = self.window_size - window_size = dpa_utils.check_set_window_size(attn_mask_type, window_size) + if attn_mask_type_per_seq is not None: + default_window_size = self.window_size if window_size is None else window_size + resolved_window_sizes = {} + for mask_type in attn_mask_type_per_seq: + policy_window_size = default_window_size + if window_size_per_mask_type is not None: + policy_window_size = window_size_per_mask_type.get( + mask_type, default_window_size + ) + resolved_window_sizes[mask_type] = dpa_utils.check_set_window_size( + mask_type, policy_window_size + ) + window_size_per_mask_type = resolved_window_sizes + window_size = default_window_size + else: + if window_size is None: + window_size = self.window_size + window_size = dpa_utils.check_set_window_size(attn_mask_type, window_size) if bottom_right_diagonal is None: bottom_right_diagonal = self.bottom_right_diagonal if attn_mask_type in {"causal", "padding_causal"}: @@ -2134,6 +2149,8 @@ def forward( max_seqlen_kv = int((seqlens_kv.max().item() + 63) // 64 * 64) if attn_mask_type_per_seq is not None: + # Validate the shared call contract before dispatching each policy + # through an ordinary scalar-mask attention invocation. if qkv_format != "thd": raise ValueError( "attn_mask_type_per_seq is supported only with qkv_format='thd'." From d5e370c5c56a4057fa688811843fa14e35e97aa3 Mon Sep 17 00:00:00 2001 From: Desh Raj Date: Fri, 21 Aug 2026 05:18:17 -0700 Subject: [PATCH 09/16] Refine mixed THD policy API and backend dispatch --- .../attention/test_mixed_thd_attention.py | 257 +++++++---- .../dot_product_attention.py | 415 +++++++++--------- .../attention/dot_product_attention/utils.py | 16 - 3 files changed, 390 insertions(+), 298 deletions(-) diff --git a/tests/pytorch/attention/test_mixed_thd_attention.py b/tests/pytorch/attention/test_mixed_thd_attention.py index 26de85e499d..3f975881642 100644 --- a/tests/pytorch/attention/test_mixed_thd_attention.py +++ b/tests/pytorch/attention/test_mixed_thd_attention.py @@ -38,11 +38,15 @@ def _make_cu_seqlens(lengths): return torch.cat((lengths.new_zeros(1), torch.cumsum(lengths, dim=0, dtype=torch.int32))) -def _make_policy(sequence_ids): - return { - mask_type: torch.tensor(ids, dtype=torch.int64, device="cuda") - for mask_type, ids in sequence_ids.items() - } +def _make_policies(policy_specs): + return [ + { + "sequence_ids": torch.tensor(sequence_ids, dtype=torch.int64, device="cuda"), + "mask_type": mask_type, + "window_size": window_size, + } + for mask_type, sequence_ids, window_size in policy_specs + ] def _per_sequence_scalar_reference( @@ -52,18 +56,19 @@ def _per_sequence_scalar_reference( value: torch.Tensor, cu_seqlens_q: torch.Tensor, cu_seqlens_kv: torch.Tensor, - mask_type_per_seq, + policies, *, cu_seqlens_q_padded=None, cu_seqlens_kv_padded=None, - window_size=None, - window_size_per_mask_type=None, ) -> torch.Tensor: """Reference each physical sequence through an ordinary scalar-mask call.""" q_physical = cu_seqlens_q if cu_seqlens_q_padded is None else cu_seqlens_q_padded kv_physical = cu_seqlens_kv if cu_seqlens_kv_padded is None else cu_seqlens_kv_padded outputs = [None] * (cu_seqlens_q.numel() - 1) - for mask_type, sequence_ids in mask_type_per_seq.items(): + for policy in policies: + mask_type = policy["mask_type"] + sequence_ids = policy["sequence_ids"] + policy_window_size = policy["window_size"] for sequence_id in sequence_ids.tolist(): q_length = int((cu_seqlens_q[sequence_id + 1] - cu_seqlens_q[sequence_id]).item()) kv_length = int((cu_seqlens_kv[sequence_id + 1] - cu_seqlens_kv[sequence_id]).item()) @@ -77,9 +82,6 @@ def _per_sequence_scalar_reference( sequence_cu_seqlens_kv = torch.tensor( (0, kv_length), dtype=torch.int32, device=query.device ) - policy_window_size = window_size - if window_size_per_mask_type is not None: - policy_window_size = window_size_per_mask_type.get(mask_type, window_size) outputs[sequence_id] = attention( # THD scalar attention requires zero-offset storage. clone() is # differentiable, so gradients still reach the packed inputs. @@ -104,16 +106,19 @@ def _per_sequence_scalar_reference( @pytest.mark.parametrize( - "mask_type_per_seq", + "policy_specs", ( - {"padding": (0, 2), "padding_causal": (1, 3)}, - {"padding": (0, 1, 2, 3)}, - {"padding_causal": (0, 1, 2, 3)}, - {"padding": (0, 2), "padding_causal_bottom_right": (1, 3)}, + (("padding", (0, 2), (-1, -1)), ("padding_causal", (1, 3), (-1, 0))), + (("padding", (0, 1, 2, 3), (-1, -1)),), + (("padding_causal", (0, 1, 2, 3), (-1, 0)),), + ( + ("padding", (0, 2), (-1, -1)), + ("padding_causal_bottom_right", (1, 3), (-1, 0)), + ), ), ) @pytest.mark.parametrize("dtype", (torch.float16, torch.bfloat16)) -def test_thd_mask_types_match_scalar_forward_and_backward(mask_type_per_seq, dtype): +def test_thd_mask_types_match_scalar_forward_and_backward(policy_specs, dtype): """Per-sequence masks must match independent scalar-policy attention.""" if dtype == torch.bfloat16 and not torch.cuda.is_bf16_supported(): pytest.skip("BF16 is not supported by this GPU") @@ -121,7 +126,7 @@ def test_thd_mask_types_match_scalar_forward_and_backward(mask_type_per_seq, dty torch.manual_seed(1234) cu_seqlens = _make_cu_seqlens((7, 3, 5, 4)) token_count = 19 - mask_type_per_seq = _make_policy(mask_type_per_seq) + policies = _make_policies(policy_specs) def make_input(): return ( @@ -143,7 +148,7 @@ def make_input(): cu_seqlens_kv=cu_seqlens, max_seqlen_q=7, max_seqlen_kv=7, - attn_mask_type_per_seq=mask_type_per_seq, + attn_mask_type_and_window_size_per_seq_policies=policies, ) reference_output = _per_sequence_scalar_reference( attention, @@ -152,7 +157,7 @@ def make_input(): reference_value, cu_seqlens, cu_seqlens, - mask_type_per_seq, + policies, ) tolerances = {"atol": 1.0e-3, "rtol": 1.0e-3} @@ -177,7 +182,7 @@ def test_thd_mask_types_compose_with_existing_inter_sequence_padding(): dtype = torch.float16 cu_seqlens = _make_cu_seqlens((7, 3, 5, 4)) cu_seqlens_padded = torch.tensor((0, 9, 12, 19, 23), dtype=torch.int32, device="cuda") - mask_type_per_seq = _make_policy({"padding": (0, 2), "padding_causal": (1, 3)}) + policies = _make_policies((("padding", (0, 2), (-1, -1)), ("padding_causal", (1, 3), (-1, 0)))) def make_input(): return ( @@ -201,7 +206,7 @@ def make_input(): cu_seqlens_kv_padded=cu_seqlens_padded, max_seqlen_q=7, max_seqlen_kv=7, - attn_mask_type_per_seq=mask_type_per_seq, + attn_mask_type_and_window_size_per_seq_policies=policies, ) reference_output = _per_sequence_scalar_reference( attention, @@ -210,7 +215,7 @@ def make_input(): reference_value, cu_seqlens, cu_seqlens, - mask_type_per_seq, + policies, cu_seqlens_q_padded=cu_seqlens_padded, cu_seqlens_kv_padded=cu_seqlens_padded, ) @@ -233,8 +238,9 @@ def test_thd_mask_types_support_cross_attention_and_per_policy_windows(): dtype = torch.float16 cu_seqlens_q = _make_cu_seqlens((5, 3, 4)) cu_seqlens_kv = _make_cu_seqlens((7, 2, 5)) - mask_type_per_seq = _make_policy({"padding": (0, 2), "padding_causal_bottom_right": (1,)}) - windows = {"padding": (-1, -1), "padding_causal_bottom_right": (2, 0)} + policies = _make_policies( + (("padding", (0, 2), (-1, -1)), ("padding_causal_bottom_right", (1,), (2, 0))) + ) query = ( 0.1 * torch.randn(12, NUM_HEADS, HEAD_DIM, dtype=dtype, device="cuda") @@ -255,8 +261,7 @@ def test_thd_mask_types_support_cross_attention_and_per_policy_windows(): cu_seqlens_kv=cu_seqlens_kv, max_seqlen_q=5, max_seqlen_kv=7, - attn_mask_type_per_seq=mask_type_per_seq, - window_size_per_mask_type=windows, + attn_mask_type_and_window_size_per_seq_policies=policies, ) reference_output = _per_sequence_scalar_reference( attention, @@ -265,8 +270,7 @@ def test_thd_mask_types_support_cross_attention_and_per_policy_windows(): reference_value, cu_seqlens_q, cu_seqlens_kv, - mask_type_per_seq, - window_size_per_mask_type=windows, + policies, ) torch.testing.assert_close(output, reference_output, atol=1.0e-3, rtol=1.0e-3) @@ -282,19 +286,26 @@ def test_thd_mask_types_support_cross_attention_and_per_policy_windows(): @pytest.mark.parametrize( - "mask_type_per_seq", + "policy_specs", ( - {"padding_causal": (0, 2), "padding": (1, 3)}, - {"padding": (1, 3), "padding_causal": (0, 2)}, + ( + ("padding_causal", (0,), (1, 0)), + ("padding_causal", (2,), (3, 0)), + ("padding", (1, 3), (2, 2)), + ), + ( + ("padding", (1, 3), (2, 2)), + ("padding_causal", (2,), (3, 0)), + ("padding_causal", (0,), (1, 0)), + ), ), ) -def test_thd_mask_types_default_window_is_independent_of_policy_order(mask_type_per_seq): - """Normalize a shared fallback window independently for every mask policy.""" +def test_thd_mask_types_support_repeated_masks_and_policy_order(policy_specs): + """Repeated mask types may use distinct windows in any policy-list order.""" torch.manual_seed(1234) dtype = torch.float16 cu_seqlens = _make_cu_seqlens((7, 3, 5, 4)) - mask_type_per_seq = _make_policy(mask_type_per_seq) - window_size = (2, 2) + policies = _make_policies(policy_specs) def make_input(): return ( @@ -316,8 +327,7 @@ def make_input(): cu_seqlens_kv=cu_seqlens, max_seqlen_q=7, max_seqlen_kv=7, - attn_mask_type_per_seq=mask_type_per_seq, - window_size=window_size, + attn_mask_type_and_window_size_per_seq_policies=policies, ) reference_output = _per_sequence_scalar_reference( attention, @@ -326,8 +336,7 @@ def make_input(): reference_value, cu_seqlens, cu_seqlens, - mask_type_per_seq, - window_size=window_size, + policies, ) torch.testing.assert_close(output, reference_output, atol=1.0e-3, rtol=1.0e-3) @@ -342,45 +351,124 @@ def make_input(): torch.testing.assert_close(actual_grad, reference_grad, atol=1.0e-3, rtol=1.0e-3) -@pytest.mark.parametrize( - ("compute_capability", "fa3_installed", "flash_enabled", "fa3_enabled", "expected"), - ( - ((9, 0), True, "1", "1", True), - ((8, 0), True, "1", "1", False), - ((10, 0), True, "1", "1", False), - ((9, 0), False, "1", "1", False), - ((9, 0), True, "0", "1", False), - ((9, 0), True, "1", "0", False), - ), -) -def test_thd_mask_type_runtime_dispatch( - monkeypatch, - compute_capability, - fa3_installed, - flash_enabled, - fa3_enabled, - expected, -): - """Only Hopper with enabled FA3 uses the inter-sequence-padding implementation.""" +def test_thd_mask_type_runtime_dispatch_uses_backend_selection(monkeypatch): + """Route each policy according to backend support for inter-sequence padding.""" + policies = [ + { + "sequence_ids": torch.tensor((0, 2), dtype=torch.int64, device="cuda"), + "mask_type": "padding", + "window_size": (-1, -1), + "bottom_right_diagonal": True, + }, + { + "sequence_ids": torch.tensor((1,), dtype=torch.int64, device="cuda"), + "mask_type": "padding_causal", + "window_size": (2, 0), + "bottom_right_diagonal": False, + }, + ] + observed_params = [] + + def fake_get_attention_backend(attention_params): + observed_params.append(attention_params) + available_backends = [False, attention_params.attn_mask_type == "padding", False] + return False, None, available_backends[1], None, False, available_backends + + monkeypatch.setattr(dpa_module.dpa_utils, "get_attention_backend", fake_get_attention_backend) + padded_policies, grouped_policies = DotProductAttention._partition_thd_mask_policies( + policies, + {}, + ) + + assert padded_policies[0] is policies[0] + assert grouped_policies[0] is policies[1] + assert [params.batch_size for params in observed_params] == [2, 1] + assert [params.attn_mask_type for params in observed_params] == [ + "padding", + "padding_causal", + ] + assert [params.window_size for params in observed_params] == [(-1, -1), (2, 0)] + assert [params.bottom_right_diagonal for params in observed_params] == [True, False] + assert all(params.pad_between_seqs for params in observed_params) + + +def test_thd_mask_type_runtime_dispatch_combines_backend_outputs(monkeypatch): + """Policies routed to different backend representations share one output.""" + attention = _make_dpa(torch.float16) + cu_seqlens = _make_cu_seqlens((1, 1)) + policies = [ + { + "sequence_ids": torch.tensor((0,), dtype=torch.int64, device="cuda"), + "mask_type": "padding", + "window_size": (-1, -1), + "bottom_right_diagonal": True, + }, + { + "sequence_ids": torch.tensor((1,), dtype=torch.int64, device="cuda"), + "mask_type": "padding_causal", + "window_size": (-1, 0), + "bottom_right_diagonal": False, + }, + ] + query = torch.zeros(2, NUM_HEADS, HEAD_DIM, dtype=torch.float16, device="cuda") + padded_output = query.new_zeros((2, NUM_HEADS * HEAD_DIM)) + grouped_output = torch.zeros_like(padded_output) + padded_output[0] = 1 + grouped_output[1] = 2 + monkeypatch.setattr( - dpa_module.dpa_utils, "get_device_compute_capability", lambda: compute_capability + attention, + "_partition_thd_mask_policies", + lambda *_args, **_kwargs: ([policies[0]], [policies[1]]), + ) + monkeypatch.setattr( + attention, + "_forward_thd_mask_types_with_padding", + lambda *_args, **_kwargs: padded_output, + ) + monkeypatch.setattr( + attention, + "_forward_thd_mask_types_grouped", + lambda *_args, **_kwargs: grouped_output, ) - monkeypatch.setattr(dpa_module.FlashAttentionUtils, "v3_is_installed", fa3_installed) - monkeypatch.setenv("NVTE_FLASH_ATTN", flash_enabled) - monkeypatch.setenv("NVTE_FLASH_ATTN_V3", fa3_enabled) - assert dpa_module.dpa_utils.is_thd_mask_type_padding_supported() is expected + output = attention._forward_thd_mask_types( + query, + query, + query, + cu_seqlens, + cu_seqlens, + None, + None, + policies, + 1, + 1, + attention_params_kwargs={}, + checkpoint_core_attention=False, + fast_zero_fill=True, + pad_between_seqs=False, + bf16_backward=None, + num_splits=None, + ) + torch.testing.assert_close(output, padded_output + grouped_output) -def test_thd_mask_types_support_cuda_graph_capture(): +def test_thd_mask_types_support_cuda_graph_capture(monkeypatch): """The sync-free policy metadata path must be replayable in a CUDA graph.""" - if not dpa_module.dpa_utils.is_thd_mask_type_padding_supported(): + if dpa_module.dpa_utils.get_device_compute_capability() != (9, 0): + pytest.skip("CUDA graph capture requires a Hopper GPU for the FA3 test path") + if not dpa_module.FlashAttentionUtils.v3_is_installed: pytest.skip("CUDA graph capture requires the Hopper/FA3 padding implementation") + monkeypatch.setenv("NVTE_FLASH_ATTN", "1") + monkeypatch.setenv("NVTE_FLASH_ATTN_V3", "1") + monkeypatch.setenv("NVTE_FUSED_ATTN", "0") + monkeypatch.setenv("NVTE_UNFUSED_ATTN", "0") + torch.manual_seed(1234) dtype = torch.float16 cu_seqlens = _make_cu_seqlens((7, 3, 5, 4)) - mask_type_per_seq = _make_policy({"padding": (0, 2), "padding_causal": (1, 3)}) + policies = _make_policies((("padding", (0, 2), (-1, -1)), ("padding_causal", (1, 3), (-1, 0)))) query = 0.1 * torch.randn(19, NUM_HEADS, HEAD_DIM, dtype=dtype, device="cuda") key = 0.1 * torch.randn_like(query) value = 0.1 * torch.randn_like(query) @@ -396,7 +484,7 @@ def run_attention(): cu_seqlens_kv=cu_seqlens, max_seqlen_q=7, max_seqlen_kv=7, - attn_mask_type_per_seq=mask_type_per_seq, + attn_mask_type_and_window_size_per_seq_policies=policies, ) warmup_stream = torch.cuda.Stream() @@ -421,7 +509,8 @@ def run_attention(): ("policy_dtype", "one-dimensional int32 or int64"), ("missing_sequence", "assign every sequence exactly once by count"), ("mask_type", "only padding mask types"), - ("window_key", "mask not present"), + ("policy_keys", "must contain exactly"), + ("scalar_mask", "do not also pass"), ), ) def test_thd_mask_types_reject_invalid_inputs(invalid_case, error): @@ -431,17 +520,19 @@ def test_thd_mask_types_reject_invalid_inputs(invalid_case, error): value = torch.randn_like(query) cu_seqlens = torch.tensor((0, 2, 4), dtype=torch.int32, device="cuda") attention = _make_dpa(torch.float16) - policies = _make_policy({"padding": (0,), "padding_causal": (1,)}) - windows = None + policies = _make_policies((("padding", (0,), (-1, -1)), ("padding_causal", (1,), (-1, 0)))) + scalar_mask_type = None if invalid_case == "policy_dtype": - policies["padding"] = torch.tensor((0,), dtype=torch.float32, device="cuda") + policies[0]["sequence_ids"] = torch.tensor((0,), dtype=torch.float32, device="cuda") elif invalid_case == "missing_sequence": - policies = _make_policy({"padding": (0,)}) + policies = _make_policies((("padding", (0,), (-1, -1)),)) elif invalid_case == "mask_type": - policies = _make_policy({"no_mask": (0,), "padding": (1,)}) + policies[0]["mask_type"] = "no_mask" + elif invalid_case == "policy_keys": + del policies[0]["window_size"] else: - windows = {"padding_causal_bottom_right": (-1, 0)} + scalar_mask_type = "padding" with pytest.raises(ValueError, match=error): attention( @@ -453,8 +544,8 @@ def test_thd_mask_types_reject_invalid_inputs(invalid_case, error): cu_seqlens_kv=cu_seqlens, max_seqlen_q=2, max_seqlen_kv=2, - attn_mask_type_per_seq=policies, - window_size_per_mask_type=windows, + attn_mask_type=scalar_mask_type, + attn_mask_type_and_window_size_per_seq_policies=policies, ) @@ -477,7 +568,13 @@ def test_thd_mask_types_empty_batch_preserves_input_gradients(): cu_seqlens_kv=cu_seqlens, max_seqlen_q=0, max_seqlen_kv=0, - attn_mask_type_per_seq={"padding": torch.empty(0, dtype=torch.int64, device="cuda")}, + attn_mask_type_and_window_size_per_seq_policies=[ + { + "sequence_ids": torch.empty(0, dtype=torch.int64, device="cuda"), + "mask_type": "padding", + "window_size": (-1, -1), + } + ], ) assert output.shape == (0, NUM_HEADS * HEAD_DIM) output.sum().backward() 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 3954cc848d7..0f9f98cea11 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 @@ -1337,6 +1337,32 @@ def get_quantizer_roles( ] return base[:num_quantizers] + @staticmethod + def _partition_thd_mask_policies( + policies: List[Dict[str, Any]], + attention_params_kwargs: Dict[str, Any], + ) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]: + """Partition policies by inter-sequence-padding backend availability.""" + padded_policies = [] + grouped_policies = [] + for policy in policies: + if policy["sequence_ids"].numel() == 0: + continue + padded_attention_params = dpa_utils.AttentionParams( + **attention_params_kwargs, + batch_size=policy["sequence_ids"].numel(), + attn_mask_type=policy["mask_type"], + window_size=policy["window_size"], + bottom_right_diagonal=policy["bottom_right_diagonal"], + pad_between_seqs=True, + ) + *_, available_backends = dpa_utils.get_attention_backend(padded_attention_params) + if any(available_backends): + padded_policies.append(policy) + else: + grouped_policies.append(policy) + return padded_policies, grouped_policies + @staticmethod def _select_thd_sequences( cu_seqlens: torch.Tensor, @@ -1392,26 +1418,19 @@ def _forward_thd_mask_types_with_padding( cu_seqlens_kv: torch.Tensor, cu_seqlens_q_padded: Optional[torch.Tensor], cu_seqlens_kv_padded: Optional[torch.Tensor], - attn_mask_type_per_seq: Dict[str, torch.Tensor], - window_size_per_mask_type: Optional[Dict[str, Tuple[int, int]]], + policies: List[Dict[str, Any]], max_seqlen_q: Optional[int], max_seqlen_kv: Optional[int], *, - window_size: Optional[Tuple[int, int]], checkpoint_core_attention: bool, fast_zero_fill: bool, bf16_backward: Optional[bool], num_splits: Optional[int], ) -> torch.Tensor: - """Dispatch mixed THD masks with FA3 inter-sequence padding.""" - nonempty_mask_types = [ - mask_type - for mask_type, sequence_ids in attn_mask_type_per_seq.items() - if sequence_ids.numel() > 0 - ] + """Dispatch mixed THD policies with inter-sequence padding.""" output = None - for mask_type in nonempty_mask_types: - sequence_ids = attn_mask_type_per_seq[mask_type] + for policy in policies: + sequence_ids = policy["sequence_ids"] policy_q_token_mask = self._selected_thd_token_mask( query_layer.shape[0], cu_seqlens_q, @@ -1443,9 +1462,6 @@ def _forward_thd_mask_types_with_padding( cu_seqlens_kv_padded, sequence_ids, ) - policy_window_size = window_size - if window_size_per_mask_type is not None: - policy_window_size = window_size_per_mask_type.get(mask_type, window_size) policy_output = self.forward( policy_query, policy_key, @@ -1457,8 +1473,9 @@ def _forward_thd_mask_types_with_padding( cu_seqlens_kv_padded=selected_cu_seqlens_kv_padded, max_seqlen_q=max_seqlen_q, max_seqlen_kv=max_seqlen_kv, - attn_mask_type=mask_type, - window_size=policy_window_size, + attn_mask_type=policy["mask_type"], + window_size=policy["window_size"], + bottom_right_diagonal=policy["bottom_right_diagonal"], checkpoint_core_attention=checkpoint_core_attention, fast_zero_fill=fast_zero_fill, pad_between_seqs=True, @@ -1468,7 +1485,7 @@ def _forward_thd_mask_types_with_padding( policy_output = torch.where(policy_q_token_mask.unsqueeze(-1), policy_output, 0.0) output = policy_output if output is None else output + policy_output if output is None: - raise ValueError("attn_mask_type_per_seq must assign at least one sequence.") + raise ValueError("Mixed THD policies must assign at least one sequence.") return output def _forward_thd_mask_types_grouped( @@ -1480,21 +1497,20 @@ def _forward_thd_mask_types_grouped( cu_seqlens_kv: torch.Tensor, cu_seqlens_q_padded: Optional[torch.Tensor], cu_seqlens_kv_padded: Optional[torch.Tensor], - attn_mask_type_per_seq: Dict[str, torch.Tensor], - window_size_per_mask_type: Optional[Dict[str, Tuple[int, int]]], + policies: List[Dict[str, Any]], max_seqlen_q: Optional[int], max_seqlen_kv: Optional[int], *, - window_size: Optional[Tuple[int, int]], checkpoint_core_attention: bool, fast_zero_fill: bool, bf16_backward: Optional[bool], num_splits: Optional[int], ) -> torch.Tensor: - """Dispatch mixed THD masks by compacting each policy for FA2.""" + """Dispatch mixed THD policies by compacting each policy's tokens.""" output_features = query_layer.shape[-2] * value_layer.shape[-1] output = query_layer.new_zeros((query_layer.shape[0], output_features)) - for mask_type, sequence_ids in attn_mask_type_per_seq.items(): + for policy in policies: + sequence_ids = policy["sequence_ids"] if sequence_ids.numel() == 0: continue q_token_mask = self._selected_thd_token_mask( @@ -1521,9 +1537,6 @@ def _forward_thd_mask_types_grouped( cu_seqlens_kv_padded, sequence_ids, ) - policy_window_size = window_size - if window_size_per_mask_type is not None: - policy_window_size = window_size_per_mask_type.get(mask_type, window_size) policy_output = self.forward( query_layer.index_select(0, q_token_indices), key_layer.index_select(0, kv_token_indices), @@ -1533,8 +1546,9 @@ def _forward_thd_mask_types_grouped( cu_seqlens_kv=selected_cu_seqlens_kv, max_seqlen_q=max_seqlen_q, max_seqlen_kv=max_seqlen_kv, - attn_mask_type=mask_type, - window_size=policy_window_size, + attn_mask_type=policy["mask_type"], + window_size=policy["window_size"], + bottom_right_diagonal=policy["bottom_right_diagonal"], checkpoint_core_attention=checkpoint_core_attention, fast_zero_fill=fast_zero_fill, pad_between_seqs=False, @@ -1553,38 +1567,30 @@ def _forward_thd_mask_types( cu_seqlens_kv: torch.Tensor, cu_seqlens_q_padded: Optional[torch.Tensor], cu_seqlens_kv_padded: Optional[torch.Tensor], - attn_mask_type_per_seq: Dict[str, torch.Tensor], - window_size_per_mask_type: Optional[Dict[str, Tuple[int, int]]], + policies: List[Dict[str, Any]], max_seqlen_q: Optional[int], max_seqlen_kv: Optional[int], *, - window_size: Optional[Tuple[int, int]], + attention_params_kwargs: Dict[str, Any], checkpoint_core_attention: bool, fast_zero_fill: bool, pad_between_seqs: Optional[bool], bf16_backward: Optional[bool], num_splits: Optional[int], ) -> torch.Tensor: - """Dispatch mixed THD masks through the best runtime implementation.""" + """Dispatch mixed THD policies through backend-compatible representations.""" output_features = query_layer.shape[-2] * value_layer.shape[-1] if query_layer.shape[0] == 0: empty_output = query_layer.new_empty((0, output_features)) return empty_output + 0 * (query_layer.sum() + key_layer.sum() + value_layer.sum()) - nonempty_mask_types = [ - mask_type - for mask_type, sequence_ids in attn_mask_type_per_seq.items() - if sequence_ids.numel() > 0 - ] + nonempty_policies = [policy for policy in policies if policy["sequence_ids"].numel() > 0] batch_size = cu_seqlens_q.shape[0] - 1 if ( - len(nonempty_mask_types) == 1 - and attn_mask_type_per_seq[nonempty_mask_types[0]].numel() == batch_size + len(nonempty_policies) == 1 + and nonempty_policies[0]["sequence_ids"].numel() == batch_size ): - mask_type = nonempty_mask_types[0] - policy_window_size = window_size - if window_size_per_mask_type is not None: - policy_window_size = window_size_per_mask_type.get(mask_type, window_size) + policy = nonempty_policies[0] return self.forward( query_layer, key_layer, @@ -1596,19 +1602,25 @@ def _forward_thd_mask_types( cu_seqlens_kv_padded=cu_seqlens_kv_padded, max_seqlen_q=max_seqlen_q, max_seqlen_kv=max_seqlen_kv, - attn_mask_type=mask_type, - window_size=policy_window_size, + attn_mask_type=policy["mask_type"], + window_size=policy["window_size"], + bottom_right_diagonal=policy["bottom_right_diagonal"], checkpoint_core_attention=checkpoint_core_attention, fast_zero_fill=fast_zero_fill, pad_between_seqs=pad_between_seqs, bf16_backward=bf16_backward, num_splits=num_splits, ) - if not nonempty_mask_types: - raise ValueError("attn_mask_type_per_seq must assign at least one sequence.") + if not nonempty_policies: + raise ValueError("Mixed THD policies must assign at least one sequence.") - if dpa_utils.is_thd_mask_type_padding_supported(): - return self._forward_thd_mask_types_with_padding( + padded_policies, grouped_policies = self._partition_thd_mask_policies( + nonempty_policies, + attention_params_kwargs, + ) + padded_output = None + if padded_policies: + padded_output = self._forward_thd_mask_types_with_padding( query_layer, key_layer, value_layer, @@ -1616,34 +1628,37 @@ def _forward_thd_mask_types( cu_seqlens_kv, cu_seqlens_q_padded, cu_seqlens_kv_padded, - attn_mask_type_per_seq, - window_size_per_mask_type, + padded_policies, max_seqlen_q, max_seqlen_kv, - window_size=window_size, checkpoint_core_attention=checkpoint_core_attention, fast_zero_fill=fast_zero_fill, bf16_backward=bf16_backward, num_splits=num_splits, ) - return self._forward_thd_mask_types_grouped( - query_layer, - key_layer, - value_layer, - cu_seqlens_q, - cu_seqlens_kv, - cu_seqlens_q_padded, - cu_seqlens_kv_padded, - attn_mask_type_per_seq, - window_size_per_mask_type, - max_seqlen_q, - max_seqlen_kv, - window_size=window_size, - checkpoint_core_attention=checkpoint_core_attention, - fast_zero_fill=fast_zero_fill, - bf16_backward=bf16_backward, - num_splits=num_splits, - ) + grouped_output = None + if grouped_policies: + grouped_output = self._forward_thd_mask_types_grouped( + query_layer, + key_layer, + value_layer, + cu_seqlens_q, + cu_seqlens_kv, + cu_seqlens_q_padded, + cu_seqlens_kv_padded, + grouped_policies, + max_seqlen_q, + max_seqlen_kv, + checkpoint_core_attention=checkpoint_core_attention, + fast_zero_fill=fast_zero_fill, + bf16_backward=bf16_backward, + num_splits=num_splits, + ) + if padded_output is None: + return grouped_output + if grouped_output is None: + return padded_output + return padded_output + grouped_output @no_torch_dynamo(recursive=False) def forward( @@ -1679,8 +1694,7 @@ def forward( qkv_layer: Optional[torch.Tensor] = None, kv_layer: Optional[torch.Tensor] = None, qkv_interleave_dim: int = -3, - attn_mask_type_per_seq: Optional[Dict[str, torch.Tensor]] = None, - window_size_per_mask_type: Optional[Dict[str, Tuple[int, int]]] = None, + attn_mask_type_and_window_size_per_seq_policies: Optional[List[Dict[str, Any]]] = None, ) -> torch.Tensor: r""" Dot Product Attention Layer. @@ -1920,59 +1934,76 @@ def forward( interleave sits; must be -3 (e.g. ``bs3hd``) or -2 (e.g. ``bsh3d``, Megatron-style). This is an explicit knob rather than shape inference, since e.g. ``h == 3`` would make the shapes ambiguous. - attn_mask_type_per_seq: Optional[Dict[str, torch.Tensor]], default = None - Per-sequence mask policies for packed THD attention. Each key is an - attention mask type and each value is a one-dimensional, ascending CUDA - integer tensor containing the sequence IDs assigned to that mask. The - sequence-ID tensors must be disjoint and together contain every sequence - exactly once. On Hopper with FlashAttention 3 enabled, Transformer Engine - keeps Q/K/V in their original packed layout and represents sequences owned - by other policies as inter-sequence padding. Otherwise it compacts each - policy's logical tokens for an ordinary scalar-mask call and restores the - original physical THD layout. The caller-facing API is identical for both - implementations. - window_size_per_mask_type: Optional[Dict[str, Tuple[int, int]]], default = None - Optional sliding-window override for each key in - :attr:`attn_mask_type_per_seq`. This is useful when, for example, offline - sequences need full context while causal sequences use bounded left - context. Missing keys fall back to :attr:`window_size`. + attn_mask_type_and_window_size_per_seq_policies: Optional[List[Dict[str, Any]]], + default = None + Per-sequence policies for packed THD attention. Each list item must contain + ``"sequence_ids"``, ``"mask_type"``, and ``"window_size"``. Sequence IDs + are supplied as a one-dimensional, strictly ascending CUDA integer tensor; + all policy tensors must be disjoint and together contain every sequence + exactly once. A list may contain multiple policies with the same mask type + and different windows. Transformer Engine queries its ordinary backend + selector for every policy, preserves the original packed layout when an + inter-sequence-padding backend is available, and otherwise compacts that + policy's logical tokens before its scalar-mask attention call. """ - if window_size_per_mask_type is not None and attn_mask_type_per_seq is None: - raise ValueError("window_size_per_mask_type requires attn_mask_type_per_seq.") - if attn_mask_type_per_seq is not None: - if not isinstance(attn_mask_type_per_seq, dict) or not attn_mask_type_per_seq: - raise ValueError("attn_mask_type_per_seq must be a non-empty dictionary.") - normalized_mask_types = {} - for mask_type, sequence_ids in attn_mask_type_per_seq.items(): + thd_mask_policies = None + if attn_mask_type_and_window_size_per_seq_policies is not None: + if ( + not isinstance(attn_mask_type_and_window_size_per_seq_policies, list) + or not attn_mask_type_and_window_size_per_seq_policies + ): + raise ValueError( + "attn_mask_type_and_window_size_per_seq_policies must be a non-empty list." + ) + if attn_mask_type is not None or window_size is not None: + raise ValueError( + "Mixed THD policies specify mask_type and window_size per policy; do not " + "also pass attn_mask_type or window_size." + ) + + required_policy_keys = {"sequence_ids", "mask_type", "window_size"} + thd_mask_policies = [] + for policy_index, policy in enumerate(attn_mask_type_and_window_size_per_seq_policies): + if not isinstance(policy, dict): + raise ValueError(f"Mixed THD policy {policy_index} must be a dictionary.") + if set(policy) != required_policy_keys: + raise ValueError( + f"Mixed THD policy {policy_index} must contain exactly " + "'sequence_ids', 'mask_type', and 'window_size'." + ) + mask_type = policy["mask_type"] if not isinstance(mask_type, str): - raise ValueError("attn_mask_type_per_seq keys must be attention mask strings.") + raise ValueError(f"Mixed THD policy {policy_index} mask_type must be a string.") mask_type = mask_type.replace(",", "_") if mask_type == "causal_padding": mask_type = "padding_causal" if mask_type not in AttnMaskTypes or "padding" not in mask_type: raise ValueError( - "attn_mask_type_per_seq supports only padding mask types, got " - f"{mask_type!r}." + f"Mixed THD policies support only padding mask types, got {mask_type!r}." ) - if mask_type in normalized_mask_types: - raise ValueError(f"Duplicate normalized attention mask type {mask_type!r}.") - normalized_mask_types[mask_type] = sequence_ids - attn_mask_type_per_seq = normalized_mask_types - - if window_size_per_mask_type is not None: - normalized_window_sizes = {} - for mask_type, policy_window_size in window_size_per_mask_type.items(): - mask_type = mask_type.replace(",", "_") - if mask_type == "causal_padding": - mask_type = "padding_causal" - if mask_type not in attn_mask_type_per_seq: - raise ValueError( - "window_size_per_mask_type contains a mask not present in " - f"attn_mask_type_per_seq: {mask_type!r}." - ) - normalized_window_sizes[mask_type] = policy_window_size - window_size_per_mask_type = normalized_window_sizes + policy_window_size = dpa_utils.check_set_window_size( + mask_type, + policy["window_size"], + ) + policy_bottom_right_diagonal = bottom_right_diagonal + if policy_bottom_right_diagonal is None: + policy_bottom_right_diagonal = self.bottom_right_diagonal + if mask_type in {"causal", "padding_causal"}: + policy_bottom_right_diagonal = False + if policy_bottom_right_diagonal is None or mask_type in { + "causal_bottom_right", + "padding_causal_bottom_right", + }: + policy_bottom_right_diagonal = True + thd_mask_policies.append( + { + "sequence_ids": policy["sequence_ids"], + "mask_type": mask_type, + "window_size": policy_window_size, + "bottom_right_diagonal": policy_bottom_right_diagonal, + } + ) query_layer, key_layer, value_layer, declared_qkv_layout = _unpack_packed_qkv( qkv_layer, @@ -2051,49 +2082,29 @@ def forward( f" {self.num_gqa_groups_per_partition} heads! Found {num_gqa_groups}." ) - # checks for attention mask - if attn_mask_type_per_seq is not None: - # This scalar is used only for shared THD shape validation. - # Each policy call below uses its dictionary key and resolved window. - attn_mask_type = next(iter(attn_mask_type_per_seq)) - elif attn_mask_type is None: - attn_mask_type = self.attn_mask_type - else: - attn_mask_type = attn_mask_type.replace(",", "_") - if attn_mask_type == "causal_padding": - attn_mask_type = "padding_causal" - assert ( - attn_mask_type in AttnMaskTypes - ), f"Attention mask type {attn_mask_type} is not supported!" - - # checks for sliding window - if attn_mask_type_per_seq is not None: - default_window_size = self.window_size if window_size is None else window_size - resolved_window_sizes = {} - for mask_type in attn_mask_type_per_seq: - policy_window_size = default_window_size - if window_size_per_mask_type is not None: - policy_window_size = window_size_per_mask_type.get( - mask_type, default_window_size - ) - resolved_window_sizes[mask_type] = dpa_utils.check_set_window_size( - mask_type, policy_window_size - ) - window_size_per_mask_type = resolved_window_sizes - window_size = default_window_size - else: + # checks for scalar attention mask and sliding window + if thd_mask_policies is None: + if attn_mask_type is None: + attn_mask_type = self.attn_mask_type + else: + attn_mask_type = attn_mask_type.replace(",", "_") + if attn_mask_type == "causal_padding": + attn_mask_type = "padding_causal" + assert ( + attn_mask_type in AttnMaskTypes + ), f"Attention mask type {attn_mask_type} is not supported!" if window_size is None: window_size = self.window_size window_size = dpa_utils.check_set_window_size(attn_mask_type, window_size) - if bottom_right_diagonal is None: - bottom_right_diagonal = self.bottom_right_diagonal - if attn_mask_type in {"causal", "padding_causal"}: - bottom_right_diagonal = False - if bottom_right_diagonal is None or attn_mask_type in { - "causal_bottom_right", - "padding_causal_bottom_right", - }: - bottom_right_diagonal = True + if bottom_right_diagonal is None: + bottom_right_diagonal = self.bottom_right_diagonal + if attn_mask_type in {"causal", "padding_causal"}: + bottom_right_diagonal = False + if bottom_right_diagonal is None or attn_mask_type in { + "causal_bottom_right", + "padding_causal_bottom_right", + }: + bottom_right_diagonal = True # checks for qkv_format if qkv_format is None: @@ -2120,9 +2131,10 @@ def forward( assert all( len(x.shape) == 3 for x in (query_layer, key_layer, value_layer) ), "Queries, keys and values must be 3D tensors when qkv_format = thd!" - assert ( - "padding" in attn_mask_type - ), "Attention mask type must be padding or padding_causal for qkv_format=thd!" + if thd_mask_policies is None: + assert ( + "padding" in attn_mask_type + ), "Attention mask type must be padding or padding_causal for qkv_format=thd!" assert ( cu_seqlens_q is not None and cu_seqlens_kv is not None ), "cu_seqlens_q and cu_seqlens_kv can not be None when qkv_format = thd!" @@ -2148,81 +2160,57 @@ def forward( seqlens_kv = cu_seqlens_kv[1:] - cu_seqlens_kv[:-1] max_seqlen_kv = int((seqlens_kv.max().item() + 63) // 64 * 64) - if attn_mask_type_per_seq is not None: + if thd_mask_policies is not None: # Validate the shared call contract before dispatching each policy # through an ordinary scalar-mask attention invocation. if qkv_format != "thd": - raise ValueError( - "attn_mask_type_per_seq is supported only with qkv_format='thd'." - ) + raise ValueError("Mixed THD policies are supported only with qkv_format='thd'.") if attention_mask is not None: - raise ValueError( - "attn_mask_type_per_seq does not support an explicit attention_mask." - ) + raise ValueError("Mixed THD policies do not support an attention_mask.") if ( core_attention_bias_type != "no_bias" or core_attention_bias is not None or alibi_slopes is not None ): raise ValueError( - "attn_mask_type_per_seq does not yet support attention bias or ALiBi." + "Mixed THD policies do not yet support attention bias or ALiBi." ) if inference_params is not None: - raise ValueError("attn_mask_type_per_seq does not support KV caching.") + raise ValueError("Mixed THD policies do not support KV caching.") if ( score_mod is not None or score_mod_bprop is not None or score_mod_tensors is not None or score_mod_bprop_tensors is not None ): - raise ValueError("attn_mask_type_per_seq does not support score modification.") + raise ValueError("Mixed THD policies do not support score modification.") if fp8_output or self.fp8 or self.return_max_logit: raise ValueError( - "attn_mask_type_per_seq does not yet support FP8 or max-logit output." + "Mixed THD policies do not yet support FP8 or max-logit output." ) assigned_sequence_count = 0 - for sequence_ids in attn_mask_type_per_seq.values(): + for policy in thd_mask_policies: + sequence_ids = policy["sequence_ids"] if not isinstance(sequence_ids, torch.Tensor): - raise ValueError( - "attn_mask_type_per_seq values must be sequence-ID tensors." - ) + raise ValueError("Mixed THD policy sequence_ids must be a torch.Tensor.") if sequence_ids.ndim != 1 or sequence_ids.dtype not in ( torch.int32, torch.int64, ): raise ValueError( - "attn_mask_type_per_seq values must be one-dimensional int32 or " - "int64 sequence-ID tensors." + "Mixed THD policy sequence_ids must be one-dimensional int32 or " + "int64 tensors." ) if not sequence_ids.is_cuda or sequence_ids.device != query_layer.device: raise ValueError( - "attn_mask_type_per_seq sequence IDs must be on the Q/K/V device." + "Mixed THD policy sequence_ids must be on the Q/K/V device." ) assigned_sequence_count += sequence_ids.numel() if assigned_sequence_count != batch_size: raise ValueError( - "attn_mask_type_per_seq must assign every sequence exactly once by count: " + "Mixed THD policies must assign every sequence exactly once by count: " f"got {assigned_sequence_count} assignments for {batch_size} sequences." ) - return self._forward_thd_mask_types( - query_layer, - key_layer, - value_layer, - cu_seqlens_q, - cu_seqlens_kv, - cu_seqlens_q_padded, - cu_seqlens_kv_padded, - attn_mask_type_per_seq, - window_size_per_mask_type, - max_seqlen_q, - max_seqlen_kv, - window_size=window_size, - checkpoint_core_attention=checkpoint_core_attention, - fast_zero_fill=fast_zero_fill, - pad_between_seqs=pad_between_seqs, - bf16_backward=bf16_backward, - num_splits=num_splits, - ) # update KV cache and retrieve saved tokens from cache for inference if inference_params is not None: @@ -2474,27 +2462,22 @@ def forward( ), "score_mod_bprop_tensors must map string names to torch.Tensor instances!" # gather attention params for get_attention_backend - attention_params = dpa_utils.AttentionParams( + attention_params_kwargs = dict( qkv_type=type(query_layer), qkv_dtype=query_layer.dtype, qkv_layout=qkv_layout, - batch_size=batch_size, num_heads=num_attention_heads, num_gqa_groups=num_gqa_groups, max_seqlen_q=max_seqlen_q, max_seqlen_kv=max_seqlen_kv, head_dim_qk=head_dim_qk, head_dim_v=head_dim_v, - attn_mask_type=attn_mask_type, - window_size=window_size, - bottom_right_diagonal=bottom_right_diagonal, alibi_slopes_shape=alibi_slopes.shape if alibi_slopes is not None else None, core_attention_bias_type=core_attention_bias_type, core_attention_bias_shape=core_attention_bias_shape, core_attention_bias_requires_grad=( core_attention_bias.requires_grad if core_attention_bias is not None else False ), - pad_between_seqs=pad_between_seqs, attention_dropout=self.attention_dropout, context_parallel=context_parallel, cp_comm_type=self.cp_comm_type, @@ -2513,6 +2496,34 @@ def forward( has_score_mod=score_mod is not None, has_score_mod_bprop=score_mod_bprop is not None, ) + if thd_mask_policies is not None: + return self._forward_thd_mask_types( + query_layer, + key_layer, + value_layer, + cu_seqlens_q, + cu_seqlens_kv, + cu_seqlens_q_padded, + cu_seqlens_kv_padded, + thd_mask_policies, + max_seqlen_q, + max_seqlen_kv, + attention_params_kwargs=attention_params_kwargs, + checkpoint_core_attention=checkpoint_core_attention, + fast_zero_fill=fast_zero_fill, + pad_between_seqs=pad_between_seqs, + bf16_backward=bf16_backward, + num_splits=num_splits, + ) + + attention_params = dpa_utils.AttentionParams( + **attention_params_kwargs, + batch_size=batch_size, + attn_mask_type=attn_mask_type, + window_size=window_size, + bottom_right_diagonal=bottom_right_diagonal, + pad_between_seqs=pad_between_seqs, + ) global _attention_backends if is_in_onnx_export_mode(): # We do not want to call get_attention_backend() in ONNX mode diff --git a/transformer_engine/pytorch/attention/dot_product_attention/utils.py b/transformer_engine/pytorch/attention/dot_product_attention/utils.py index 39d7a7e376d..6eb3ce54f18 100644 --- a/transformer_engine/pytorch/attention/dot_product_attention/utils.py +++ b/transformer_engine/pytorch/attention/dot_product_attention/utils.py @@ -379,22 +379,6 @@ def _get_fused_attn_backend( ) -def is_thd_mask_type_padding_supported() -> bool: - """Whether mixed THD masks can use the inter-sequence-padding implementation. - - FlashAttention 3 is the FlashAttention backend that supports padding between - sequences, and TE only enables it on Hopper (SM90). Keep this capability - selection next to the rest of the attention backend architecture filters so - callers can fall back without exposing a hardware-specific API. - """ - return ( - get_device_compute_capability() == (9, 0) - and FlashAttentionUtils.v3_is_installed - and bool(int(os.environ.get("NVTE_FLASH_ATTN", "1"))) - and bool(int(os.environ.get("NVTE_FLASH_ATTN_V3", "1"))) - ) - - def get_attention_backend( attention_params: AttentionParams = None, ): From 9f01ef863650617e2c633a2d7c58efedb81c43cf Mon Sep 17 00:00:00 2001 From: Desh Raj Date: Tue, 1 Sep 2026 06:18:12 -0700 Subject: [PATCH 10/16] Add grouped override for mixed THD attention Signed-off-by: Desh Raj --- tests/pytorch/attention/test_attention.py | 89 +++++--- .../attention/test_mixed_thd_attention.py | 212 +++++++++++++++--- .../dot_product_attention.py | 39 +++- 3 files changed, 263 insertions(+), 77 deletions(-) diff --git a/tests/pytorch/attention/test_attention.py b/tests/pytorch/attention/test_attention.py index 82791084d89..9a7a16673b9 100644 --- a/tests/pytorch/attention/test_attention.py +++ b/tests/pytorch/attention/test_attention.py @@ -205,7 +205,7 @@ def test_dot_product_attention( # UnfusedDotProductAttention backend if unfused_attn_supported: - unfused_attn_fwd, unfused_max_logit, unfused_attn_bwd = _run_dot_product_attention( + unfused_attn_fwd, unfused_max_logit, unfused_attn_bwd = run_dot_product_attention( dtype, config, "UnfusedDotProductAttention", @@ -217,7 +217,7 @@ def test_dot_product_attention( # FusedAttention backend if fused_attn_supported: - fused_attn_fwd, fused_max_logit, fused_attn_bwd = _run_dot_product_attention( + fused_attn_fwd, fused_max_logit, fused_attn_bwd = run_dot_product_attention( dtype, config, "FusedAttention", @@ -230,7 +230,7 @@ def test_dot_product_attention( # FlashAttention backend if flash_attn_supported: - flash_attn_fwd, _, flash_attn_bwd = _run_dot_product_attention( + flash_attn_fwd, _, flash_attn_bwd = run_dot_product_attention( dtype, config, "FlashAttention", @@ -1115,7 +1115,47 @@ def test_dpa_qkv_layout_thd_declarative(dtype, model_configs, model, qkv_layout) test_dpa_qkv_layout_thd(dtype, model_configs, model, qkv_layout, declarative_packed=True) -def _run_dot_product_attention( +def make_cu_seqlens(seqlens: torch.Tensor) -> torch.Tensor: + """Construct CUDA cumulative sequence lengths from per-sequence lengths.""" + cu_seqlens = torch.zeros(seqlens.numel() + 1, dtype=torch.int32, device=seqlens.device) + cu_seqlens[1:] = torch.cumsum(seqlens, dim=0) + return cu_seqlens + + +def make_dot_product_attention( + dtype: torch.dtype, + config: ModelConfig, + qkv_format: str, + *, + get_rng_state_tracker=None, + is_training: bool = True, + attention_type: str = None, +) -> DotProductAttention: + """Construct a configured DotProductAttention test module.""" + block = DotProductAttention( + config.num_heads, + (config.head_dim_qk, config.head_dim_v), + num_gqa_groups=config.num_gqa_groups, + attention_dropout=config.dropout_p, + qkv_format=qkv_format, + attn_mask_type=config.attn_mask_type, + sequence_parallel=False, + tp_size=1, + get_rng_state_tracker=get_rng_state_tracker, + tp_group=None, + layer_number=1, + attention_type=config.attn_type if attention_type is None else attention_type, + softmax_type=config.softmax_type, + return_max_logit=config.return_max_logit, + ).to(dtype=dtype, device="cuda") + if not is_training: + block = block.eval() + if is_training and config.softmax_type != "vanilla": + block.softmax_offset.requires_grad = True + return block + + +def run_dot_product_attention( dtype: torch.dtype, config: ModelConfig, backend: str, @@ -1124,6 +1164,7 @@ def _run_dot_product_attention( pad_between_seqs: bool, is_training: bool, declarative_packed: bool = False, + forward_kwargs: Dict[str, Any] = None, ) -> Tuple[torch.Tensor, Tuple[torch.Tensor, torch.Tensor, torch.Tensor]]: """Run DotProductAttention module with one forward pass and one backward pass. @@ -1169,10 +1210,8 @@ def _run_dot_product_attention( seqlens_kv = torch.full( [config.batch_size], config.max_seqlen_kv, dtype=torch.int32, device="cuda" ) - cu_seqlens_q = torch.zeros(config.batch_size + 1, dtype=torch.int32, device="cuda") - cu_seqlens_kv = torch.zeros(config.batch_size + 1, dtype=torch.int32, device="cuda") - cu_seqlens_q[1:] = torch.cumsum(seqlens_q, dim=0) - cu_seqlens_kv[1:] = torch.cumsum(seqlens_kv, dim=0) + cu_seqlens_q = make_cu_seqlens(seqlens_q) + cu_seqlens_kv = make_cu_seqlens(seqlens_kv) seqlens_q_after_pad = seqlens_q.clone() seqlens_kv_after_pad = seqlens_kv.clone() @@ -1398,26 +1437,13 @@ def get_dummy_cuda_rng_tracker() -> CudaRNGStatesTracker: return _DUMMY_CUDA_RNG_STATE_TRACKER # Set up model - block = DotProductAttention( - config.num_heads, - (config.head_dim_qk, config.head_dim_v), - num_gqa_groups=config.num_gqa_groups, - attention_dropout=config.dropout_p, - qkv_format=qkv_format, - attn_mask_type=config.attn_mask_type, - sequence_parallel=False, - tp_size=1, + block = make_dot_product_attention( + dtype, + config, + qkv_format, get_rng_state_tracker=get_dummy_cuda_rng_tracker, - tp_group=None, - layer_number=1, - attention_type=config.attn_type, - softmax_type=config.softmax_type, - return_max_logit=config.return_max_logit, - ).to(dtype=dtype, device="cuda") - if not is_training: - block = block.eval() - if is_training and config.softmax_type != "vanilla": - block.softmax_offset.requires_grad = True + is_training=is_training, + ) # Run a forward and backward pass if backend in ["UnfusedDotProductAttention"]: @@ -1440,11 +1466,7 @@ def get_dummy_cuda_rng_tracker() -> CudaRNGStatesTracker: else: packed_kwargs["kv_layer"] = packed_tensor k, v = None, None - out = block( - q, - k, - v, - **packed_kwargs, + dpa_forward_kwargs = dict( window_size=config.window_size, attention_mask=attention_mask, qkv_format=qkv_format, @@ -1468,6 +1490,9 @@ def get_dummy_cuda_rng_tracker() -> CudaRNGStatesTracker: # Only pass num_splits when exercising the FlashAttention path num_splits=config.num_splits if backend == "FlashAttention" else 1, ) + if forward_kwargs is not None: + dpa_forward_kwargs.update(forward_kwargs) + out = block(q, k, v, **packed_kwargs, **dpa_forward_kwargs) max_logit = None if config.return_max_logit: out, max_logit = out diff --git a/tests/pytorch/attention/test_mixed_thd_attention.py b/tests/pytorch/attention/test_mixed_thd_attention.py index 3f975881642..c34fadaa70b 100644 --- a/tests/pytorch/attention/test_mixed_thd_attention.py +++ b/tests/pytorch/attention/test_mixed_thd_attention.py @@ -11,31 +11,33 @@ from transformer_engine.pytorch.attention.dot_product_attention import ( dot_product_attention as dpa_module, ) +from test_attention import ( + ModelConfig, + compare_and_assert, + dtype_tols, + make_cu_seqlens, + make_dot_product_attention, + reset_rng_states, + run_dot_product_attention, +) pytestmark = pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA is required") -NUM_HEADS = 16 -HEAD_DIM = 64 - - -def _make_dpa(dtype: torch.dtype, attention_type: str = "self") -> DotProductAttention: - return DotProductAttention( - num_attention_heads=NUM_HEADS, - kv_channels=HEAD_DIM, - attention_dropout=0.0, - qkv_format="thd", - attn_mask_type="padding", - attention_type=attention_type, - tp_size=1, - tp_group=None, - layer_number=1, - ).to(device="cuda", dtype=dtype) +MODEL_CONFIG = ModelConfig( + batch_size=4, + max_seqlen_q=7, + num_heads=16, + head_dim_qk=64, + attn_mask_type="padding", +) +NUM_HEADS = MODEL_CONFIG.num_heads +HEAD_DIM = MODEL_CONFIG.head_dim_qk def _make_cu_seqlens(lengths): lengths = torch.tensor(lengths, dtype=torch.int32, device="cuda") - return torch.cat((lengths.new_zeros(1), torch.cumsum(lengths, dim=0, dtype=torch.int32))) + return make_cu_seqlens(lengths) def _make_policies(policy_specs): @@ -123,7 +125,7 @@ def test_thd_mask_types_match_scalar_forward_and_backward(policy_specs, dtype): if dtype == torch.bfloat16 and not torch.cuda.is_bf16_supported(): pytest.skip("BF16 is not supported by this GPU") - torch.manual_seed(1234) + reset_rng_states() cu_seqlens = _make_cu_seqlens((7, 3, 5, 4)) token_count = 19 policies = _make_policies(policy_specs) @@ -138,7 +140,7 @@ def make_input(): reference_key = key.detach().clone().requires_grad_() reference_value = value.detach().clone().requires_grad_() - attention = _make_dpa(dtype) + attention = make_dot_product_attention(dtype, MODEL_CONFIG, "thd") output = attention( query, key, @@ -160,10 +162,18 @@ def make_input(): policies, ) - tolerances = {"atol": 1.0e-3, "rtol": 1.0e-3} - if dtype == torch.bfloat16: - tolerances = {"atol": 1.5e-2, "rtol": 1.5e-2} - torch.testing.assert_close(output, reference_output, **tolerances) + tolerances = dtype_tols(dtype) + tolerances["atol"] = tolerances["rtol"] + compare_and_assert( + output, + reference_output, + "mixed policy output", + "scalar policy output", + tolerances["atol"], + tolerances["rtol"], + 0.0, + False, + ) output_grad = torch.randn_like(output) output.backward(output_grad) @@ -173,12 +183,21 @@ def make_input(): (key.grad, reference_key.grad), (value.grad, reference_value.grad), ): - torch.testing.assert_close(actual_grad, reference_grad, **tolerances) + compare_and_assert( + actual_grad, + reference_grad, + "mixed policy gradient", + "scalar policy gradient", + tolerances["atol"], + tolerances["rtol"], + 0.0, + False, + ) def test_thd_mask_types_compose_with_existing_inter_sequence_padding(): """Policy gaps and pre-existing THD padding must share the physical layout.""" - torch.manual_seed(1234) + reset_rng_states() dtype = torch.float16 cu_seqlens = _make_cu_seqlens((7, 3, 5, 4)) cu_seqlens_padded = torch.tensor((0, 9, 12, 19, 23), dtype=torch.int32, device="cuda") @@ -193,7 +212,7 @@ def make_input(): reference_query = query.detach().clone().requires_grad_() reference_key = key.detach().clone().requires_grad_() reference_value = value.detach().clone().requires_grad_() - attention = _make_dpa(dtype) + attention = make_dot_product_attention(dtype, MODEL_CONFIG, "thd") output = attention( query, @@ -234,7 +253,7 @@ def make_input(): def test_thd_mask_types_support_cross_attention_and_per_policy_windows(): """Mask groups may use different Q/KV lengths and sliding windows.""" - torch.manual_seed(1234) + reset_rng_states() dtype = torch.float16 cu_seqlens_q = _make_cu_seqlens((5, 3, 4)) cu_seqlens_kv = _make_cu_seqlens((7, 2, 5)) @@ -250,7 +269,12 @@ def test_thd_mask_types_support_cross_attention_and_per_policy_windows(): reference_query = query.detach().clone().requires_grad_() reference_key = key.detach().clone().requires_grad_() reference_value = value.detach().clone().requires_grad_() - attention = _make_dpa(dtype, attention_type="cross") + attention = make_dot_product_attention( + dtype, + MODEL_CONFIG, + "thd", + attention_type="cross", + ) output = attention( query, @@ -302,7 +326,7 @@ def test_thd_mask_types_support_cross_attention_and_per_policy_windows(): ) def test_thd_mask_types_support_repeated_masks_and_policy_order(policy_specs): """Repeated mask types may use distinct windows in any policy-list order.""" - torch.manual_seed(1234) + reset_rng_states() dtype = torch.float16 cu_seqlens = _make_cu_seqlens((7, 3, 5, 4)) policies = _make_policies(policy_specs) @@ -316,7 +340,7 @@ def make_input(): reference_query = query.detach().clone().requires_grad_() reference_key = key.detach().clone().requires_grad_() reference_value = value.detach().clone().requires_grad_() - attention = _make_dpa(dtype) + attention = make_dot_product_attention(dtype, MODEL_CONFIG, "thd") output = attention( query, @@ -394,7 +418,7 @@ def fake_get_attention_backend(attention_params): def test_thd_mask_type_runtime_dispatch_combines_backend_outputs(monkeypatch): """Policies routed to different backend representations share one output.""" - attention = _make_dpa(torch.float16) + attention = make_dot_product_attention(torch.float16, MODEL_CONFIG, "thd") cu_seqlens = _make_cu_seqlens((1, 1)) policies = [ { @@ -449,10 +473,116 @@ def test_thd_mask_type_runtime_dispatch_combines_backend_outputs(monkeypatch): pad_between_seqs=False, bf16_backward=None, num_splits=None, + thd_attention_policy_dispatch="auto", ) torch.testing.assert_close(output, padded_output + grouped_output) +def test_thd_mask_type_runtime_dispatch_can_force_grouped(monkeypatch): + """The per-call override must bypass padded backend probing.""" + attention = make_dot_product_attention(torch.float16, MODEL_CONFIG, "thd") + cu_seqlens = _make_cu_seqlens((1, 1)) + policies = _make_policies((("padding", (0,), (-1, -1)), ("padding_causal", (1,), (-1, 0)))) + query = torch.zeros(2, NUM_HEADS, HEAD_DIM, dtype=torch.float16, device="cuda") + grouped_output = query.new_ones((2, NUM_HEADS * HEAD_DIM)) + + monkeypatch.setattr( + attention, + "_partition_thd_mask_policies", + lambda *_args, **_kwargs: pytest.fail("grouped override probed padded backends"), + ) + monkeypatch.setattr( + attention, + "_forward_thd_mask_types_with_padding", + lambda *_args, **_kwargs: pytest.fail("grouped override used padded dispatch"), + ) + monkeypatch.setattr( + attention, + "_forward_thd_mask_types_grouped", + lambda *_args, **_kwargs: grouped_output, + ) + + output = attention._forward_thd_mask_types( + query, + query, + query, + cu_seqlens, + cu_seqlens, + None, + None, + policies, + 1, + 1, + attention_params_kwargs={}, + checkpoint_core_attention=False, + fast_zero_fill=True, + pad_between_seqs=False, + bf16_backward=None, + num_splits=None, + thd_attention_policy_dispatch="grouped", + ) + torch.testing.assert_close(output, grouped_output) + + +def test_thd_mask_type_grouped_override_matches_auto_dispatch(): + """The shared DPA runner must produce matching automatic and grouped results.""" + policies = _make_policies((("padding", (0, 2), (-1, -1)), ("padding_causal", (1, 3), (-1, 0)))) + common_forward_kwargs = { + "attention_mask": None, + "attn_mask_type": None, + "window_size": None, + "attn_mask_type_and_window_size_per_seq_policies": policies, + } + runner_kwargs = { + "dtype": torch.float16, + "config": MODEL_CONFIG, + "backend": "FlashAttention", + "ckpt_attn": False, + "qkv_layout": "thd_thd_thd", + "pad_between_seqs": False, + "is_training": True, + } + + auto_output, _, auto_grads = run_dot_product_attention( + **runner_kwargs, + forward_kwargs={ + **common_forward_kwargs, + "thd_attention_policy_dispatch": "auto", + }, + ) + grouped_output, _, grouped_grads = run_dot_product_attention( + **runner_kwargs, + forward_kwargs={ + **common_forward_kwargs, + "thd_attention_policy_dispatch": "grouped", + }, + ) + + tolerances = dtype_tols(torch.float16) + tolerances["atol"] = tolerances["rtol"] + compare_and_assert( + auto_output, + grouped_output, + "automatic mixed policy output", + "grouped mixed policy output", + tolerances["atol"], + tolerances["rtol"], + 0.0, + False, + ) + for auto_grad, grouped_grad in zip(auto_grads[:3], grouped_grads[:3]): + compare_and_assert( + auto_grad, + grouped_grad, + "automatic mixed policy gradient", + "grouped mixed policy gradient", + tolerances["atol"], + tolerances["rtol"], + 0.0, + False, + ) + + def test_thd_mask_types_support_cuda_graph_capture(monkeypatch): """The sync-free policy metadata path must be replayable in a CUDA graph.""" if dpa_module.dpa_utils.get_device_compute_capability() != (9, 0): @@ -465,14 +595,19 @@ def test_thd_mask_types_support_cuda_graph_capture(monkeypatch): monkeypatch.setenv("NVTE_FUSED_ATTN", "0") monkeypatch.setenv("NVTE_UNFUSED_ATTN", "0") - torch.manual_seed(1234) + reset_rng_states() dtype = torch.float16 cu_seqlens = _make_cu_seqlens((7, 3, 5, 4)) policies = _make_policies((("padding", (0, 2), (-1, -1)), ("padding_causal", (1, 3), (-1, 0)))) query = 0.1 * torch.randn(19, NUM_HEADS, HEAD_DIM, dtype=dtype, device="cuda") key = 0.1 * torch.randn_like(query) value = 0.1 * torch.randn_like(query) - attention = _make_dpa(dtype).eval() + attention = make_dot_product_attention( + dtype, + MODEL_CONFIG, + "thd", + is_training=False, + ) def run_attention(): return attention( @@ -511,6 +646,7 @@ def run_attention(): ("mask_type", "only padding mask types"), ("policy_keys", "must contain exactly"), ("scalar_mask", "do not also pass"), + ("policy_dispatch", "must be either 'auto' or 'grouped'"), ), ) def test_thd_mask_types_reject_invalid_inputs(invalid_case, error): @@ -519,9 +655,10 @@ def test_thd_mask_types_reject_invalid_inputs(invalid_case, error): key = torch.randn_like(query) value = torch.randn_like(query) cu_seqlens = torch.tensor((0, 2, 4), dtype=torch.int32, device="cuda") - attention = _make_dpa(torch.float16) + attention = make_dot_product_attention(torch.float16, MODEL_CONFIG, "thd") policies = _make_policies((("padding", (0,), (-1, -1)), ("padding_causal", (1,), (-1, 0)))) scalar_mask_type = None + policy_dispatch = "auto" if invalid_case == "policy_dtype": policies[0]["sequence_ids"] = torch.tensor((0,), dtype=torch.float32, device="cuda") @@ -531,8 +668,10 @@ def test_thd_mask_types_reject_invalid_inputs(invalid_case, error): policies[0]["mask_type"] = "no_mask" elif invalid_case == "policy_keys": del policies[0]["window_size"] - else: + elif invalid_case == "scalar_mask": scalar_mask_type = "padding" + else: + policy_dispatch = "padded" with pytest.raises(ValueError, match=error): attention( @@ -546,12 +685,13 @@ def test_thd_mask_types_reject_invalid_inputs(invalid_case, error): max_seqlen_kv=2, attn_mask_type=scalar_mask_type, attn_mask_type_and_window_size_per_seq_policies=policies, + thd_attention_policy_dispatch=policy_dispatch, ) def test_thd_mask_types_empty_batch_preserves_input_gradients(): """An empty packed batch needs zero gradients, not a disconnected output.""" - attention = _make_dpa(torch.float16) + attention = make_dot_product_attention(torch.float16, MODEL_CONFIG, "thd") query = torch.empty( 0, NUM_HEADS, HEAD_DIM, device="cuda", dtype=torch.float16, requires_grad=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 0f9f98cea11..62db3a699d7 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 @@ -1342,7 +1342,12 @@ def _partition_thd_mask_policies( policies: List[Dict[str, Any]], attention_params_kwargs: Dict[str, Any], ) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]: - """Partition policies by inter-sequence-padding backend availability.""" + """Partition policies using padded-first backend routing. + + Backend selection here checks support, not relative performance. If any backend + supports a policy with inter-sequence padding, preserve the original packed layout; + otherwise compact that policy's tokens before attention. + """ padded_policies = [] grouped_policies = [] for policy in policies: @@ -1577,6 +1582,7 @@ def _forward_thd_mask_types( pad_between_seqs: Optional[bool], bf16_backward: Optional[bool], num_splits: Optional[int], + thd_attention_policy_dispatch: str, ) -> torch.Tensor: """Dispatch mixed THD policies through backend-compatible representations.""" output_features = query_layer.shape[-2] * value_layer.shape[-1] @@ -1614,10 +1620,13 @@ def _forward_thd_mask_types( if not nonempty_policies: raise ValueError("Mixed THD policies must assign at least one sequence.") - padded_policies, grouped_policies = self._partition_thd_mask_policies( - nonempty_policies, - attention_params_kwargs, - ) + if thd_attention_policy_dispatch == "grouped": + padded_policies, grouped_policies = [], nonempty_policies + else: + padded_policies, grouped_policies = self._partition_thd_mask_policies( + nonempty_policies, + attention_params_kwargs, + ) padded_output = None if padded_policies: padded_output = self._forward_thd_mask_types_with_padding( @@ -1695,6 +1704,7 @@ def forward( kv_layer: Optional[torch.Tensor] = None, qkv_interleave_dim: int = -3, attn_mask_type_and_window_size_per_seq_policies: Optional[List[Dict[str, Any]]] = None, + thd_attention_policy_dispatch: str = "auto", ) -> torch.Tensor: r""" Dot Product Attention Layer. @@ -1941,12 +1951,22 @@ def forward( are supplied as a one-dimensional, strictly ascending CUDA integer tensor; all policy tensors must be disjoint and together contain every sequence exactly once. A list may contain multiple policies with the same mask type - and different windows. Transformer Engine queries its ordinary backend - selector for every policy, preserves the original packed layout when an - inter-sequence-padding backend is available, and otherwise compacts that - policy's logical tokens before its scalar-mask attention call. + and different windows. Mixed THD dispatch is intentionally padded-first: + Transformer Engine queries its ordinary backend selector for every policy and + preserves the original packed layout whenever an inter-sequence-padding backend + is available. This is a capability check, not a performance comparison. If no + such backend is available, the policy's logical tokens are compacted before its + scalar-mask attention call. + thd_attention_policy_dispatch: {``"auto"``, ``"grouped"``}, default = ``"auto"`` + Dispatch strategy for mixed THD policies. ``"auto"`` uses the padded-first + backend capability check described above. ``"grouped"`` compacts each policy's + logical tokens before attention, without changing backend eligibility for this or + other attention calls. """ + if thd_attention_policy_dispatch not in {"auto", "grouped"}: + raise ValueError("thd_attention_policy_dispatch must be either 'auto' or 'grouped'.") + thd_mask_policies = None if attn_mask_type_and_window_size_per_seq_policies is not None: if ( @@ -2514,6 +2534,7 @@ def forward( pad_between_seqs=pad_between_seqs, bf16_backward=bf16_backward, num_splits=num_splits, + thd_attention_policy_dispatch=thd_attention_policy_dispatch, ) attention_params = dpa_utils.AttentionParams( From 2dca0089afe1f509ed59e113421f6bbead14679c Mon Sep 17 00:00:00 2001 From: Desh Raj Date: Tue, 1 Sep 2026 07:09:54 -0700 Subject: [PATCH 11/16] Validate mixed THD sequence policies --- .../attention/test_mixed_thd_attention.py | 41 ++++++++++ .../dot_product_attention.py | 77 ++++++++++++++++++- 2 files changed, 117 insertions(+), 1 deletion(-) diff --git a/tests/pytorch/attention/test_mixed_thd_attention.py b/tests/pytorch/attention/test_mixed_thd_attention.py index c34fadaa70b..142bb58f8c5 100644 --- a/tests/pytorch/attention/test_mixed_thd_attention.py +++ b/tests/pytorch/attention/test_mixed_thd_attention.py @@ -643,6 +643,10 @@ def run_attention(): ( ("policy_dtype", "one-dimensional int32 or int64"), ("missing_sequence", "assign every sequence exactly once by count"), + ("sequence_order", "strictly ascending"), + ("sequence_duplicate", "strictly ascending"), + ("sequence_overlap", "assign every sequence exactly once"), + ("sequence_range", "assign every sequence exactly once"), ("mask_type", "only padding mask types"), ("policy_keys", "must contain exactly"), ("scalar_mask", "do not also pass"), @@ -664,6 +668,14 @@ def test_thd_mask_types_reject_invalid_inputs(invalid_case, error): policies[0]["sequence_ids"] = torch.tensor((0,), dtype=torch.float32, device="cuda") elif invalid_case == "missing_sequence": policies = _make_policies((("padding", (0,), (-1, -1)),)) + elif invalid_case == "sequence_order": + policies = _make_policies((("padding", (1, 0), (-1, -1)),)) + elif invalid_case == "sequence_duplicate": + policies = _make_policies((("padding", (0, 0), (-1, -1)),)) + elif invalid_case == "sequence_overlap": + policies = _make_policies((("padding", (0,), (-1, -1)), ("padding_causal", (0,), (-1, 0)))) + elif invalid_case == "sequence_range": + policies = _make_policies((("padding", (0, 2), (-1, -1)),)) elif invalid_case == "mask_type": policies[0]["mask_type"] = "no_mask" elif invalid_case == "policy_keys": @@ -689,6 +701,35 @@ def test_thd_mask_types_reject_invalid_inputs(invalid_case, error): ) +def test_thd_mask_types_reject_context_parallelism(monkeypatch): + """Mixed THD policies must fail before entering an unsupported CP path.""" + query = torch.randn(4, NUM_HEADS, HEAD_DIM, device="cuda", dtype=torch.float16) + cu_seqlens = torch.tensor((0, 2, 4), dtype=torch.int32, device="cuda") + attention = make_dot_product_attention(torch.float16, MODEL_CONFIG, "thd") + attention.cp_group = [object()] + monkeypatch.setattr(dpa_module, "get_distributed_world_size", lambda _group: 2) + monkeypatch.setattr( + attention, + "_forward_thd_mask_types", + lambda *_args, **_kwargs: query.new_zeros((query.shape[0], NUM_HEADS * HEAD_DIM)), + ) + + with pytest.raises(ValueError, match="do not support context parallelism"): + attention( + query, + query, + query, + qkv_format="thd", + cu_seqlens_q=cu_seqlens, + cu_seqlens_kv=cu_seqlens, + max_seqlen_q=2, + max_seqlen_kv=2, + attn_mask_type_and_window_size_per_seq_policies=_make_policies( + (("padding", (0,), (-1, -1)), ("padding_causal", (1,), (-1, 0))) + ), + ) + + def test_thd_mask_types_empty_batch_preserves_input_gradients(): """An empty packed batch needs zero gradients, not a disconnected output.""" attention = make_dot_product_attention(torch.float16, MODEL_CONFIG, "thd") 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 62db3a699d7..4de0267f402 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 @@ -86,6 +86,76 @@ "_alibi_bias_require_update": False, } +# Sequence-ID validation synchronizes once to report malformed policy metadata. Share +# successful validations across DPA layers, and retain only a small number of recent +# policy sets so dynamically constructed batches do not grow the cache without bound. +_THD_POLICY_VALIDATION_CACHE_LIMIT = 64 +_thd_policy_validation_cache = [] + + +def _get_thd_policy_tensor_version(tensor: torch.Tensor) -> Optional[int]: + """Return the mutation version when the tensor tracks one.""" + try: + return tensor._version + except RuntimeError: + return None + + +def _validate_thd_policy_sequence_ids(policies: List[Dict[str, Any]], batch_size: int) -> None: + """Validate static mixed-THD sequence IDs outside CUDA graph capture.""" + sequence_id_tensors = tuple(policy["sequence_ids"] for policy in policies) + sequence_id_versions = tuple( + _get_thd_policy_tensor_version(sequence_ids) for sequence_ids in sequence_id_tensors + ) + + for cache_index, (cached_batch_size, cached_tensors, cached_versions) in enumerate( + _thd_policy_validation_cache + ): + if ( + cached_batch_size == batch_size + and sequence_id_versions == cached_versions + and len(sequence_id_tensors) == len(cached_tensors) + and all( + sequence_ids is cached_sequence_ids + for sequence_ids, cached_sequence_ids in zip(sequence_id_tensors, cached_tensors) + ) + ): + _thd_policy_validation_cache.append(_thd_policy_validation_cache.pop(cache_index)) + return + + if is_graph_capturing(): + raise RuntimeError( + "Mixed THD policy sequence_ids must be validated by an eager warm-up call " + "before CUDA graph capture." + ) + + order_checks = [ + sequence_ids[1:] > sequence_ids[:-1] + for sequence_ids in sequence_id_tensors + if sequence_ids.numel() > 1 + ] + if order_checks: + strictly_ascending = torch.cat(order_checks).all() + else: + strictly_ascending = torch.ones((), dtype=torch.bool, device=sequence_id_tensors[0].device) + all_sequence_ids = torch.cat( + [sequence_ids.to(dtype=torch.int64) for sequence_ids in sequence_id_tensors] + ) + expected_sequence_ids = torch.arange( + batch_size, dtype=torch.int64, device=all_sequence_ids.device + ) + exact_coverage = torch.all(torch.sort(all_sequence_ids).values == expected_sequence_ids) + valid_order, valid_coverage = torch.stack((strictly_ascending, exact_coverage)).tolist() + + if not valid_order: + raise ValueError("Mixed THD policy sequence_ids must be strictly ascending.") + if not valid_coverage: + raise ValueError("Mixed THD policies must assign every sequence exactly once.") + + _thd_policy_validation_cache.append((batch_size, sequence_id_tensors, sequence_id_versions)) + if len(_thd_policy_validation_cache) > _THD_POLICY_VALIDATION_CACHE_LIMIT: + _thd_policy_validation_cache.pop(0) + class _IdentityWithMaskedGradient(torch.autograd.Function): """Preserve tensor storage in forward and zero unselected backward lanes.""" @@ -1951,7 +2021,9 @@ def forward( are supplied as a one-dimensional, strictly ascending CUDA integer tensor; all policy tensors must be disjoint and together contain every sequence exactly once. A list may contain multiple policies with the same mask type - and different windows. Mixed THD dispatch is intentionally padded-first: + and different windows. Policy IDs are validated before their first use and + must remain immutable during CUDA graph capture. Context parallelism is not + supported. Mixed THD dispatch is intentionally padded-first: Transformer Engine queries its ordinary backend selector for every policy and preserves the original packed layout whenever an inter-sequence-padding backend is available. This is a capability check, not a performance comparison. If no @@ -2231,6 +2303,7 @@ def forward( "Mixed THD policies must assign every sequence exactly once by count: " f"got {assigned_sequence_count} assignments for {batch_size} sequences." ) + _validate_thd_policy_sequence_ids(thd_mask_policies, batch_size) # update KV cache and retrieve saved tokens from cache for inference if inference_params is not None: @@ -2341,6 +2414,8 @@ def forward( for group in self.cp_group: cp_size *= get_distributed_world_size(group) context_parallel = cp_size > 1 + if thd_mask_policies is not None and context_parallel: + raise ValueError("Mixed THD policies do not support context parallelism.") if q_format in ["sbhd", "bshd"]: max_seqlen_q *= cp_size if cu_seqlens_q is None: From 0ced9fc91e5aef6c39df097a563e5d23591198c3 Mon Sep 17 00:00:00 2001 From: Desh Raj Date: Tue, 1 Sep 2026 08:44:19 -0700 Subject: [PATCH 12/16] Cache mixed THD backend selection --- .../attention/test_mixed_thd_attention.py | 63 +++++++++ .../dot_product_attention.py | 120 ++++++++++++++++-- 2 files changed, 171 insertions(+), 12 deletions(-) diff --git a/tests/pytorch/attention/test_mixed_thd_attention.py b/tests/pytorch/attention/test_mixed_thd_attention.py index 142bb58f8c5..3375771f99d 100644 --- a/tests/pytorch/attention/test_mixed_thd_attention.py +++ b/tests/pytorch/attention/test_mixed_thd_attention.py @@ -415,6 +415,69 @@ def fake_get_attention_backend(attention_params): assert [params.bottom_right_diagonal for params in observed_params] == [True, False] assert all(params.pad_between_seqs for params in observed_params) + DotProductAttention._partition_thd_mask_policies(policies, {}) + assert len(observed_params) == 2 + + monkeypatch.setenv("NVTE_FLASH_ATTN", "0") + DotProductAttention._partition_thd_mask_policies(policies, {}) + assert len(observed_params) == 4 + + +def test_thd_mask_type_runtime_dispatch_caches_backend_selection(monkeypatch): + """Repeated mixed-policy forwards should reuse backend-selection results.""" + monkeypatch.setenv("NVTE_FLASH_ATTN", "1") + monkeypatch.setenv("NVTE_FUSED_ATTN", "0") + monkeypatch.setenv("NVTE_UNFUSED_ATTN", "0") + + original_get_attention_backend = dpa_module.dpa_utils.get_attention_backend + selector_calls = 0 + + def counted_get_attention_backend(attention_params): + nonlocal selector_calls + selector_calls += 1 + return original_get_attention_backend(attention_params) + + monkeypatch.setattr( + dpa_module.dpa_utils, + "get_attention_backend", + counted_get_attention_backend, + ) + + attention = make_dot_product_attention( + torch.float16, + MODEL_CONFIG, + "thd", + is_training=False, + ) + cu_seqlens = _make_cu_seqlens((7, 3, 5, 4)) + query = torch.randn(19, NUM_HEADS, HEAD_DIM, dtype=torch.float16, device="cuda") + key = torch.randn_like(query) + value = torch.randn_like(query) + policies = _make_policies((("padding", (0, 2), (-1, -1)), ("padding_causal", (1, 3), (-1, 0)))) + + def run_attention(): + return attention( + query, + key, + value, + qkv_format="thd", + cu_seqlens_q=cu_seqlens, + cu_seqlens_kv=cu_seqlens, + max_seqlen_q=7, + max_seqlen_kv=7, + attn_mask_type_and_window_size_per_seq_policies=policies, + ) + + with torch.inference_mode(): + run_attention() + torch.cuda.synchronize() + warmup_selector_calls = selector_calls + assert warmup_selector_calls > 0 + run_attention() + torch.cuda.synchronize() + + assert selector_calls == warmup_selector_calls + def test_thd_mask_type_runtime_dispatch_combines_backend_outputs(monkeypatch): """Policies routed to different backend representations share one output.""" 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 4de0267f402..e0d949ffc36 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 @@ -75,6 +75,20 @@ "backend_selection_requires_update": False, } +# Mixed THD attention alternates between a small set of policy-specific attention +# configurations. Cache their full backend-selection results to avoid re-running the +# selector for every policy in every layer and forward pass. +_THD_POLICY_BACKEND_CACHE_LIMIT = 64 +_THD_POLICY_BACKEND_ENV_VARS = ( + "NVTE_FLASH_ATTN", + "NVTE_FLASH_ATTN_V2", + "NVTE_FLASH_ATTN_V3", + "NVTE_FLASH_ATTN_V4", + "NVTE_FUSED_ATTN", + "NVTE_UNFUSED_ATTN", +) +_thd_policy_backend_cache = [] + _alibi_cache = { "_num_heads": None, "_alibi_slopes": None, @@ -93,6 +107,64 @@ _thd_policy_validation_cache = [] +def _get_thd_policy_attention_backend( + policy: Dict[str, Any], + attention_params_kwargs: Dict[str, Any], + pad_between_seqs: bool, +) -> Tuple[Any, ...]: + """Select and cache a mixed-policy backend for reuse by the scalar forward.""" + attention_params = dpa_utils.AttentionParams( + **attention_params_kwargs, + batch_size=policy["sequence_ids"].numel(), + attn_mask_type=policy["mask_type"], + window_size=policy["window_size"], + bottom_right_diagonal=policy["bottom_right_diagonal"], + pad_between_seqs=pad_between_seqs, + ) + selector = dpa_utils.get_attention_backend + environment = tuple(os.environ.get(name) for name in _THD_POLICY_BACKEND_ENV_VARS) + for cache_index, ( + cached_selector, + cached_environment, + cached_attention_params, + cached_selection, + ) in enumerate(_thd_policy_backend_cache): + if ( + selector is cached_selector + and environment == cached_environment + and attention_params == cached_attention_params + ): + _thd_policy_backend_cache.append(_thd_policy_backend_cache.pop(cache_index)) + selection = cached_selection + break + else: + selection = selector(attention_params) + _thd_policy_backend_cache.append((selector, environment, attention_params, selection)) + if len(_thd_policy_backend_cache) > _THD_POLICY_BACKEND_CACHE_LIMIT: + _thd_policy_backend_cache.pop(0) + + ( + use_flash_attention, + flash_attention_backend, + use_fused_attention, + fused_attention_backend, + use_unfused_attention, + _, + ) = selection + _attention_backends.update( + { + "attention_params": attention_params, + "use_flash_attention": use_flash_attention, + "flash_attention_backend": flash_attention_backend, + "use_fused_attention": use_fused_attention, + "fused_attention_backend": fused_attention_backend, + "use_unfused_attention": use_unfused_attention, + "backend_selection_requires_update": False, + } + ) + return selection + + def _get_thd_policy_tensor_version(tensor: torch.Tensor) -> Optional[int]: """Return the mutation version when the tensor tracks one.""" try: @@ -1423,15 +1495,11 @@ def _partition_thd_mask_policies( for policy in policies: if policy["sequence_ids"].numel() == 0: continue - padded_attention_params = dpa_utils.AttentionParams( - **attention_params_kwargs, - batch_size=policy["sequence_ids"].numel(), - attn_mask_type=policy["mask_type"], - window_size=policy["window_size"], - bottom_right_diagonal=policy["bottom_right_diagonal"], - pad_between_seqs=True, + *_, available_backends = _get_thd_policy_attention_backend( + policy, + attention_params_kwargs, + True, ) - *_, available_backends = dpa_utils.get_attention_backend(padded_attention_params) if any(available_backends): padded_policies.append(policy) else: @@ -1497,6 +1565,7 @@ def _forward_thd_mask_types_with_padding( max_seqlen_q: Optional[int], max_seqlen_kv: Optional[int], *, + attention_params_kwargs: Dict[str, Any], checkpoint_core_attention: bool, fast_zero_fill: bool, bf16_backward: Optional[bool], @@ -1527,6 +1596,11 @@ def _forward_thd_mask_types_with_padding( policy_value = _IdentityWithMaskedGradient.apply( value_layer, policy_kv_token_mask[:, None, None] ) + _get_thd_policy_attention_backend( + policy, + attention_params_kwargs, + True, + ) selected_cu_seqlens_q, selected_cu_seqlens_q_padded = self._select_thd_sequences( cu_seqlens_q, cu_seqlens_q_padded, @@ -1576,6 +1650,7 @@ def _forward_thd_mask_types_grouped( max_seqlen_q: Optional[int], max_seqlen_kv: Optional[int], *, + attention_params_kwargs: Dict[str, Any], checkpoint_core_attention: bool, fast_zero_fill: bool, bf16_backward: Optional[bool], @@ -1584,6 +1659,10 @@ def _forward_thd_mask_types_grouped( """Dispatch mixed THD policies by compacting each policy's tokens.""" output_features = query_layer.shape[-2] * value_layer.shape[-1] output = query_layer.new_zeros((query_layer.shape[0], output_features)) + grouped_attention_params_kwargs = { + **attention_params_kwargs, + "qkv_layout": "thd_thd_thd", + } for policy in policies: sequence_ids = policy["sequence_ids"] if sequence_ids.numel() == 0: @@ -1612,10 +1691,18 @@ def _forward_thd_mask_types_grouped( cu_seqlens_kv_padded, sequence_ids, ) + policy_query = query_layer.index_select(0, q_token_indices) + policy_key = key_layer.index_select(0, kv_token_indices) + policy_value = value_layer.index_select(0, kv_token_indices) + _get_thd_policy_attention_backend( + policy, + grouped_attention_params_kwargs, + False, + ) policy_output = self.forward( - query_layer.index_select(0, q_token_indices), - key_layer.index_select(0, kv_token_indices), - value_layer.index_select(0, kv_token_indices), + policy_query, + policy_key, + policy_value, qkv_format="thd", cu_seqlens_q=selected_cu_seqlens_q, cu_seqlens_kv=selected_cu_seqlens_kv, @@ -1667,6 +1754,11 @@ def _forward_thd_mask_types( and nonempty_policies[0]["sequence_ids"].numel() == batch_size ): policy = nonempty_policies[0] + _get_thd_policy_attention_backend( + policy, + attention_params_kwargs, + pad_between_seqs, + ) return self.forward( query_layer, key_layer, @@ -1710,6 +1802,7 @@ def _forward_thd_mask_types( padded_policies, max_seqlen_q, max_seqlen_kv, + attention_params_kwargs=attention_params_kwargs, checkpoint_core_attention=checkpoint_core_attention, fast_zero_fill=fast_zero_fill, bf16_backward=bf16_backward, @@ -1728,6 +1821,7 @@ def _forward_thd_mask_types( grouped_policies, max_seqlen_q, max_seqlen_kv, + attention_params_kwargs=attention_params_kwargs, checkpoint_core_attention=checkpoint_core_attention, fast_zero_fill=fast_zero_fill, bf16_backward=bf16_backward, @@ -2035,6 +2129,7 @@ def forward( logical tokens before attention, without changing backend eligibility for this or other attention calls. """ + global _attention_backends if thd_attention_policy_dispatch not in {"auto", "grouped"}: raise ValueError("thd_attention_policy_dispatch must be either 'auto' or 'grouped'.") @@ -2592,6 +2687,8 @@ def forward( has_score_mod_bprop=score_mod_bprop is not None, ) if thd_mask_policies is not None: + if _attention_backends["backend_selection_requires_update"]: + _thd_policy_backend_cache.clear() return self._forward_thd_mask_types( query_layer, key_layer, @@ -2620,7 +2717,6 @@ def forward( bottom_right_diagonal=bottom_right_diagonal, pad_between_seqs=pad_between_seqs, ) - global _attention_backends if is_in_onnx_export_mode(): # We do not want to call get_attention_backend() in ONNX mode # and we want to avoid using any global variables like _attention_backends. From 156069f1d5114a6aa2b32a5bc74f9e47ab133af6 Mon Sep 17 00:00:00 2001 From: Desh Raj Date: Tue, 1 Sep 2026 09:27:50 -0700 Subject: [PATCH 13/16] Expose THD attention policies through transformer layers --- .../attention/test_mixed_thd_attention.py | 70 ++++++++++++++++--- .../dot_product_attention.py | 17 ++--- .../pytorch/attention/multi_head_attention.py | 47 ++++++++----- transformer_engine/pytorch/transformer.py | 44 +++++++----- 4 files changed, 120 insertions(+), 58 deletions(-) diff --git a/tests/pytorch/attention/test_mixed_thd_attention.py b/tests/pytorch/attention/test_mixed_thd_attention.py index 3375771f99d..abd129d0c7f 100644 --- a/tests/pytorch/attention/test_mixed_thd_attention.py +++ b/tests/pytorch/attention/test_mixed_thd_attention.py @@ -7,7 +7,7 @@ import pytest import torch -from transformer_engine.pytorch import DotProductAttention +from transformer_engine.pytorch import DotProductAttention, MultiheadAttention, TransformerLayer from transformer_engine.pytorch.attention.dot_product_attention import ( dot_product_attention as dpa_module, ) @@ -51,6 +51,54 @@ def _make_policies(policy_specs): ] +@pytest.mark.parametrize("module_type", ("multihead_attention", "transformer_layer")) +def test_thd_attention_policies_plumbed_through_attention_layers(module_type): + """MHA and TransformerLayer should pass mixed THD policies to DPA.""" + dtype = torch.float16 + cu_seqlens = _make_cu_seqlens((7, 3, 5, 4)) + policies = _make_policies((("padding", (0, 2), (-1, -1)), ("padding_causal", (1, 3), (-1, 0)))) + hidden_states = torch.randn( + 19, + MODEL_CONFIG.hidden_size, + dtype=dtype, + device="cuda", + ) + if module_type == "multihead_attention": + module = MultiheadAttention( + MODEL_CONFIG.hidden_size, + MODEL_CONFIG.num_heads, + kv_channels=MODEL_CONFIG.head_dim_qk, + attention_dropout=0.0, + attn_mask_type="padding", + qkv_format="thd", + params_dtype=dtype, + ).to(device="cuda") + else: + module = TransformerLayer( + MODEL_CONFIG.hidden_size, + 4 * MODEL_CONFIG.hidden_size, + MODEL_CONFIG.num_heads, + kv_channels=MODEL_CONFIG.head_dim_qk, + hidden_dropout=0.0, + attention_dropout=0.0, + self_attn_mask_type="padding", + attn_input_format="thd", + params_dtype=dtype, + ).to(device="cuda") + module.eval() + + with torch.inference_mode(): + output = module( + hidden_states, + cu_seqlens_q=cu_seqlens, + cu_seqlens_kv=cu_seqlens, + max_seqlen_q=7, + max_seqlen_kv=7, + thd_attention_policies=policies, + ) + assert output.shape == hidden_states.shape + + def _per_sequence_scalar_reference( attention: DotProductAttention, query: torch.Tensor, @@ -150,7 +198,7 @@ def make_input(): cu_seqlens_kv=cu_seqlens, max_seqlen_q=7, max_seqlen_kv=7, - attn_mask_type_and_window_size_per_seq_policies=policies, + thd_attention_policies=policies, ) reference_output = _per_sequence_scalar_reference( attention, @@ -225,7 +273,7 @@ def make_input(): cu_seqlens_kv_padded=cu_seqlens_padded, max_seqlen_q=7, max_seqlen_kv=7, - attn_mask_type_and_window_size_per_seq_policies=policies, + thd_attention_policies=policies, ) reference_output = _per_sequence_scalar_reference( attention, @@ -285,7 +333,7 @@ def test_thd_mask_types_support_cross_attention_and_per_policy_windows(): cu_seqlens_kv=cu_seqlens_kv, max_seqlen_q=5, max_seqlen_kv=7, - attn_mask_type_and_window_size_per_seq_policies=policies, + thd_attention_policies=policies, ) reference_output = _per_sequence_scalar_reference( attention, @@ -351,7 +399,7 @@ def make_input(): cu_seqlens_kv=cu_seqlens, max_seqlen_q=7, max_seqlen_kv=7, - attn_mask_type_and_window_size_per_seq_policies=policies, + thd_attention_policies=policies, ) reference_output = _per_sequence_scalar_reference( attention, @@ -465,7 +513,7 @@ def run_attention(): cu_seqlens_kv=cu_seqlens, max_seqlen_q=7, max_seqlen_kv=7, - attn_mask_type_and_window_size_per_seq_policies=policies, + thd_attention_policies=policies, ) with torch.inference_mode(): @@ -594,7 +642,7 @@ def test_thd_mask_type_grouped_override_matches_auto_dispatch(): "attention_mask": None, "attn_mask_type": None, "window_size": None, - "attn_mask_type_and_window_size_per_seq_policies": policies, + "thd_attention_policies": policies, } runner_kwargs = { "dtype": torch.float16, @@ -682,7 +730,7 @@ def run_attention(): cu_seqlens_kv=cu_seqlens, max_seqlen_q=7, max_seqlen_kv=7, - attn_mask_type_and_window_size_per_seq_policies=policies, + thd_attention_policies=policies, ) warmup_stream = torch.cuda.Stream() @@ -759,7 +807,7 @@ def test_thd_mask_types_reject_invalid_inputs(invalid_case, error): max_seqlen_q=2, max_seqlen_kv=2, attn_mask_type=scalar_mask_type, - attn_mask_type_and_window_size_per_seq_policies=policies, + thd_attention_policies=policies, thd_attention_policy_dispatch=policy_dispatch, ) @@ -787,7 +835,7 @@ def test_thd_mask_types_reject_context_parallelism(monkeypatch): cu_seqlens_kv=cu_seqlens, max_seqlen_q=2, max_seqlen_kv=2, - attn_mask_type_and_window_size_per_seq_policies=_make_policies( + thd_attention_policies=_make_policies( (("padding", (0,), (-1, -1)), ("padding_causal", (1,), (-1, 0))) ), ) @@ -812,7 +860,7 @@ def test_thd_mask_types_empty_batch_preserves_input_gradients(): cu_seqlens_kv=cu_seqlens, max_seqlen_q=0, max_seqlen_kv=0, - attn_mask_type_and_window_size_per_seq_policies=[ + thd_attention_policies=[ { "sequence_ids": torch.empty(0, dtype=torch.int64, device="cuda"), "mask_type": "padding", 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 e0d949ffc36..de2999a5dd9 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 @@ -1867,7 +1867,7 @@ def forward( qkv_layer: Optional[torch.Tensor] = None, kv_layer: Optional[torch.Tensor] = None, qkv_interleave_dim: int = -3, - attn_mask_type_and_window_size_per_seq_policies: Optional[List[Dict[str, Any]]] = None, + thd_attention_policies: Optional[List[Dict[str, Any]]] = None, thd_attention_policy_dispatch: str = "auto", ) -> torch.Tensor: r""" @@ -2108,7 +2108,7 @@ def forward( interleave sits; must be -3 (e.g. ``bs3hd``) or -2 (e.g. ``bsh3d``, Megatron-style). This is an explicit knob rather than shape inference, since e.g. ``h == 3`` would make the shapes ambiguous. - attn_mask_type_and_window_size_per_seq_policies: Optional[List[Dict[str, Any]]], + thd_attention_policies: Optional[List[Dict[str, Any]]], default = None Per-sequence policies for packed THD attention. Each list item must contain ``"sequence_ids"``, ``"mask_type"``, and ``"window_size"``. Sequence IDs @@ -2135,14 +2135,9 @@ def forward( raise ValueError("thd_attention_policy_dispatch must be either 'auto' or 'grouped'.") thd_mask_policies = None - if attn_mask_type_and_window_size_per_seq_policies is not None: - if ( - not isinstance(attn_mask_type_and_window_size_per_seq_policies, list) - or not attn_mask_type_and_window_size_per_seq_policies - ): - raise ValueError( - "attn_mask_type_and_window_size_per_seq_policies must be a non-empty list." - ) + if thd_attention_policies is not None: + if not isinstance(thd_attention_policies, list) or not thd_attention_policies: + raise ValueError("thd_attention_policies must be a non-empty list.") if attn_mask_type is not None or window_size is not None: raise ValueError( "Mixed THD policies specify mask_type and window_size per policy; do not " @@ -2151,7 +2146,7 @@ def forward( required_policy_keys = {"sequence_ids", "mask_type", "window_size"} thd_mask_policies = [] - for policy_index, policy in enumerate(attn_mask_type_and_window_size_per_seq_policies): + for policy_index, policy in enumerate(thd_attention_policies): if not isinstance(policy, dict): raise ValueError(f"Mixed THD policy {policy_index} must be a dictionary.") if set(policy) != required_policy_keys: diff --git a/transformer_engine/pytorch/attention/multi_head_attention.py b/transformer_engine/pytorch/attention/multi_head_attention.py index f87365bf7cf..ea40c7891a2 100644 --- a/transformer_engine/pytorch/attention/multi_head_attention.py +++ b/transformer_engine/pytorch/attention/multi_head_attention.py @@ -5,7 +5,7 @@ """Multi-head Attention.""" import os import collections -from typing import Any, Callable, List, Optional, Tuple, Union +from typing import Any, Callable, Dict, List, Optional, Tuple, Union import torch from transformer_engine.pytorch.quantization import FP8GlobalStateManager, QuantizerRole @@ -736,6 +736,7 @@ def forward( max_seqlen_kv: Optional[int] = None, fast_zero_fill: bool = True, pad_between_seqs: Optional[bool] = None, + thd_attention_policies: Optional[List[Dict[str, Any]]] = None, ) -> Tuple[Union[torch.Tensor, None], ...]: r""" Forward propagation for MultiheadAttention layer. @@ -772,6 +773,10 @@ def forward( or bottom right (`True`) corner of the softmax matrix in the encoder. If `None`, it will be set to `False` for `attn_mask_type` = {`causal`, `padding_causal`} and `True` for other mask types. + thd_attention_policies: Optional[List[Dict[str, Any]]], default = None + Per-sequence policies for packed THD attention. Passed through to + :class:`DotProductAttention`; do not also pass :attr:`attn_mask_type` + or :attr:`window_size`. encoder_output : Optional[torch.Tensor], default = None Output of the encoder block to be fed into the decoder block if using ``layer_type="decoder"``. @@ -831,23 +836,28 @@ def forward( """ # hidden_states: [sq, b, h] - if attn_mask_type is None: - attn_mask_type = self.attn_mask_type - if window_size is None: - window_size = self.window_size - - window_size = dpa_utils.check_set_window_size(attn_mask_type, window_size) - if bottom_right_diagonal is None: - bottom_right_diagonal = self.bottom_right_diagonal - if attn_mask_type in {"causal", "padding_causal"}: - bottom_right_diagonal = False - if bottom_right_diagonal is None or attn_mask_type in { - "causal_bottom_right", - "padding_causal_bottom_right", - }: - bottom_right_diagonal = True - - if "padding" in attn_mask_type and attention_mask is not None: + if thd_attention_policies is None: + if attn_mask_type is None: + attn_mask_type = self.attn_mask_type + if window_size is None: + window_size = self.window_size + + window_size = dpa_utils.check_set_window_size(attn_mask_type, window_size) + if bottom_right_diagonal is None: + bottom_right_diagonal = self.bottom_right_diagonal + if attn_mask_type in {"causal", "padding_causal"}: + bottom_right_diagonal = False + if bottom_right_diagonal is None or attn_mask_type in { + "causal_bottom_right", + "padding_causal_bottom_right", + }: + bottom_right_diagonal = True + + if ( + thd_attention_policies is None + and "padding" in attn_mask_type + and attention_mask is not None + ): for mask in attention_mask: assert mask.dtype == torch.bool, "Attention mask must be in boolean type!" @@ -1211,6 +1221,7 @@ def forward( attn_mask_type=attn_mask_type, window_size=window_size, bottom_right_diagonal=bottom_right_diagonal, + thd_attention_policies=thd_attention_policies, checkpoint_core_attention=checkpoint_core_attention, core_attention_bias_type=core_attention_bias_type, core_attention_bias=core_attention_bias, diff --git a/transformer_engine/pytorch/transformer.py b/transformer_engine/pytorch/transformer.py index d377e5f3b36..e47a9816a63 100644 --- a/transformer_engine/pytorch/transformer.py +++ b/transformer_engine/pytorch/transformer.py @@ -6,7 +6,7 @@ import os import warnings from contextlib import nullcontext -from typing import Any, Callable, List, Optional, Tuple, Union +from typing import Any, Callable, Dict, List, Optional, Tuple, Union import torch @@ -658,6 +658,7 @@ def forward( max_seqlen_kv: Optional[int] = None, fast_zero_fill: bool = True, pad_between_seqs: Optional[bool] = None, + thd_attention_policies: Optional[List[Dict[str, Any]]] = None, ) -> torch.Tensor: r""" Transformer Layer: attention block and a feedforward network (MLP) @@ -692,6 +693,10 @@ def forward( or bottom right (`True`) corner of the softmax matrix in the encoder. If `None`, it will be set to `False` for `self_attn_mask_type` = {`causal`, `padding_causal`} and `True` for other mask types. + thd_attention_policies: Optional[List[Dict[str, Any]]], default = None + Per-sequence policies for packed THD self-attention. Passed through to + :class:`MultiheadAttention`; do not also pass :attr:`self_attn_mask_type` + or :attr:`window_size`. encoder_output : Optional[torch.Tensor], default = None Output of the encoder block to be fed into the decoder block if using :attr:`layer_type` = ``"decoder"``. @@ -775,11 +780,22 @@ def forward( i.e. :attr:`qkv_format` = ``'thd'``. """ - if self_attn_mask_type is None: - self_attn_mask_type = self.self_attn_mask_type - if window_size is None: - window_size = self.window_size - window_size = dpa_utils.check_set_window_size(self_attn_mask_type, window_size) + if thd_attention_policies is None: + if self_attn_mask_type is None: + self_attn_mask_type = self.self_attn_mask_type + if window_size is None: + window_size = self.window_size + window_size = dpa_utils.check_set_window_size(self_attn_mask_type, window_size) + + if bottom_right_diagonal is None: + bottom_right_diagonal = self.bottom_right_diagonal + if self_attn_mask_type in {"causal", "padding_causal"}: + bottom_right_diagonal = False + if bottom_right_diagonal is None or self_attn_mask_type in { + "causal_bottom_right", + "padding_causal_bottom_right", + }: + bottom_right_diagonal = True if enc_dec_attn_mask_type is None: enc_dec_attn_mask_type = self.enc_dec_attn_mask_type @@ -789,16 +805,6 @@ def forward( enc_dec_attn_mask_type, enc_dec_window_size ) - if bottom_right_diagonal is None: - bottom_right_diagonal = self.bottom_right_diagonal - if self_attn_mask_type in {"causal", "padding_causal"}: - bottom_right_diagonal = False - if bottom_right_diagonal is None or self_attn_mask_type in { - "causal_bottom_right", - "padding_causal_bottom_right", - }: - bottom_right_diagonal = True - if enc_dec_bottom_right_diagonal is None: enc_dec_bottom_right_diagonal = self.enc_dec_bottom_right_diagonal if enc_dec_attn_mask_type in {"causal", "padding_causal"}: @@ -809,7 +815,7 @@ def forward( }: enc_dec_bottom_right_diagonal = True - if self_attn_mask_type not in AttnMaskTypes: + if thd_attention_policies is None and self_attn_mask_type not in AttnMaskTypes: raise ValueError( f"self_attn_mask_type {self_attn_mask_type!r} is not supported. " f"Supported types are: {', '.join(repr(t) for t in AttnMaskTypes)}" @@ -833,7 +839,8 @@ def forward( ) if ( - "padding" in self_attn_mask_type or self_attn_mask_type == "arbitrary" + thd_attention_policies is None + and ("padding" in self_attn_mask_type or self_attn_mask_type == "arbitrary") ) and attention_mask is not None: if not all(attention_mask[i].dtype == torch.bool for i in range(len(attention_mask))): non_bool_dtypes = [ @@ -872,6 +879,7 @@ def forward( attn_mask_type=self_attn_mask_type, window_size=window_size, bottom_right_diagonal=bottom_right_diagonal, + thd_attention_policies=thd_attention_policies, inference_params=inference_params, is_first_microbatch=is_first_microbatch, checkpoint_core_attention=checkpoint_core_attention, From d46d82125b90c906459b03f38f366a29b8635b65 Mon Sep 17 00:00:00 2001 From: Desh Raj Date: Tue, 1 Sep 2026 10:45:03 -0700 Subject: [PATCH 14/16] Support per-policy THD diagonal alignment --- .../attention/test_mixed_thd_attention.py | 23 +++++++++++----- .../dot_product_attention.py | 27 ++++++++++++++----- 2 files changed, 38 insertions(+), 12 deletions(-) diff --git a/tests/pytorch/attention/test_mixed_thd_attention.py b/tests/pytorch/attention/test_mixed_thd_attention.py index abd129d0c7f..abfabebc5b2 100644 --- a/tests/pytorch/attention/test_mixed_thd_attention.py +++ b/tests/pytorch/attention/test_mixed_thd_attention.py @@ -119,6 +119,7 @@ def _per_sequence_scalar_reference( mask_type = policy["mask_type"] sequence_ids = policy["sequence_ids"] policy_window_size = policy["window_size"] + policy_bottom_right_diagonal = policy.get("bottom_right_diagonal") for sequence_id in sequence_ids.tolist(): q_length = int((cu_seqlens_q[sequence_id + 1] - cu_seqlens_q[sequence_id]).item()) kv_length = int((cu_seqlens_kv[sequence_id + 1] - cu_seqlens_kv[sequence_id]).item()) @@ -145,6 +146,7 @@ def _per_sequence_scalar_reference( max_seqlen_kv=kv_length, attn_mask_type=mask_type, window_size=policy_window_size, + bottom_right_diagonal=policy_bottom_right_diagonal, ) output = query.new_zeros((query.shape[0], NUM_HEADS * HEAD_DIM)) @@ -299,20 +301,26 @@ def make_input(): torch.testing.assert_close(actual_grad, reference_grad, atol=1.0e-3, rtol=1.0e-3) -def test_thd_mask_types_support_cross_attention_and_per_policy_windows(): - """Mask groups may use different Q/KV lengths and sliding windows.""" +def test_thd_mask_types_support_cross_attention_and_per_policy_options(): + """Mask groups may use different Q/KV lengths, windows, and diagonal alignment.""" reset_rng_states() dtype = torch.float16 cu_seqlens_q = _make_cu_seqlens((5, 3, 4)) - cu_seqlens_kv = _make_cu_seqlens((7, 2, 5)) + cu_seqlens_kv = _make_cu_seqlens((7, 4, 5)) policies = _make_policies( - (("padding", (0, 2), (-1, -1)), ("padding_causal_bottom_right", (1,), (2, 0))) + ( + ("padding", (0,), (2, 1)), + ("padding", (1,), (2, 1)), + ("padding_causal_bottom_right", (2,), (2, 0)), + ) ) + policies[0]["bottom_right_diagonal"] = True + policies[1]["bottom_right_diagonal"] = False query = ( 0.1 * torch.randn(12, NUM_HEADS, HEAD_DIM, dtype=dtype, device="cuda") ).requires_grad_() - key = (0.1 * torch.randn(14, NUM_HEADS, HEAD_DIM, dtype=dtype, device="cuda")).requires_grad_() + key = (0.1 * torch.randn(16, NUM_HEADS, HEAD_DIM, dtype=dtype, device="cuda")).requires_grad_() value = (0.1 * torch.randn_like(key)).requires_grad_() reference_query = query.detach().clone().requires_grad_() reference_key = key.detach().clone().requires_grad_() @@ -759,7 +767,8 @@ def run_attention(): ("sequence_overlap", "assign every sequence exactly once"), ("sequence_range", "assign every sequence exactly once"), ("mask_type", "only padding mask types"), - ("policy_keys", "must contain exactly"), + ("policy_keys", "must contain"), + ("bottom_right_diagonal", "must be a bool"), ("scalar_mask", "do not also pass"), ("policy_dispatch", "must be either 'auto' or 'grouped'"), ), @@ -791,6 +800,8 @@ def test_thd_mask_types_reject_invalid_inputs(invalid_case, error): policies[0]["mask_type"] = "no_mask" elif invalid_case == "policy_keys": del policies[0]["window_size"] + elif invalid_case == "bottom_right_diagonal": + policies[0]["bottom_right_diagonal"] = "bottom_right" elif invalid_case == "scalar_mask": scalar_mask_type = "padding" else: 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 de2999a5dd9..d34c3c76781 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 @@ -2111,8 +2111,10 @@ def forward( thd_attention_policies: Optional[List[Dict[str, Any]]], default = None Per-sequence policies for packed THD attention. Each list item must contain - ``"sequence_ids"``, ``"mask_type"``, and ``"window_size"``. Sequence IDs - are supplied as a one-dimensional, strictly ascending CUDA integer tensor; + ``"sequence_ids"``, ``"mask_type"``, and ``"window_size"``, and may contain + ``"bottom_right_diagonal"`` to override the diagonal alignment for that policy. + If omitted, the forward or module-level alignment is used. Sequence IDs are + supplied as a one-dimensional, strictly ascending CUDA integer tensor; all policy tensors must be disjoint and together contain every sequence exactly once. A list may contain multiple policies with the same mask type and different windows. Policy IDs are validated before their first use and @@ -2145,14 +2147,19 @@ def forward( ) required_policy_keys = {"sequence_ids", "mask_type", "window_size"} + optional_policy_keys = {"bottom_right_diagonal"} thd_mask_policies = [] for policy_index, policy in enumerate(thd_attention_policies): if not isinstance(policy, dict): raise ValueError(f"Mixed THD policy {policy_index} must be a dictionary.") - if set(policy) != required_policy_keys: + policy_keys = set(policy) + if not required_policy_keys.issubset(policy_keys) or not policy_keys.issubset( + required_policy_keys | optional_policy_keys + ): raise ValueError( - f"Mixed THD policy {policy_index} must contain exactly " - "'sequence_ids', 'mask_type', and 'window_size'." + f"Mixed THD policy {policy_index} must contain 'sequence_ids', " + "'mask_type', and 'window_size', and may optionally contain " + "'bottom_right_diagonal'." ) mask_type = policy["mask_type"] if not isinstance(mask_type, str): @@ -2168,7 +2175,15 @@ def forward( mask_type, policy["window_size"], ) - policy_bottom_right_diagonal = bottom_right_diagonal + policy_bottom_right_diagonal = policy.get("bottom_right_diagonal") + if policy_bottom_right_diagonal is not None and not isinstance( + policy_bottom_right_diagonal, bool + ): + raise ValueError( + f"Mixed THD policy {policy_index} bottom_right_diagonal must be a bool." + ) + if policy_bottom_right_diagonal is None: + policy_bottom_right_diagonal = bottom_right_diagonal if policy_bottom_right_diagonal is None: policy_bottom_right_diagonal = self.bottom_right_diagonal if mask_type in {"causal", "padding_causal"}: From 20ba61823a4e7864f4e7e22af6bf7bb4a0974e5d Mon Sep 17 00:00:00 2001 From: Desh Raj Date: Tue, 1 Sep 2026 12:42:32 -0700 Subject: [PATCH 15/16] Honor grouped THD dispatch through transformer layers --- tests/pytorch/attention/test_mixed_thd_attention.py | 9 +++++++-- .../dot_product_attention/dot_product_attention.py | 3 ++- .../pytorch/attention/multi_head_attention.py | 5 +++++ transformer_engine/pytorch/transformer.py | 5 +++++ 4 files changed, 19 insertions(+), 3 deletions(-) diff --git a/tests/pytorch/attention/test_mixed_thd_attention.py b/tests/pytorch/attention/test_mixed_thd_attention.py index abfabebc5b2..d665df4ceff 100644 --- a/tests/pytorch/attention/test_mixed_thd_attention.py +++ b/tests/pytorch/attention/test_mixed_thd_attention.py @@ -95,6 +95,7 @@ def test_thd_attention_policies_plumbed_through_attention_layers(module_type): max_seqlen_q=7, max_seqlen_kv=7, thd_attention_policies=policies, + thd_attention_policy_dispatch="grouped", ) assert output.shape == hidden_states.shape @@ -597,11 +598,15 @@ def test_thd_mask_type_runtime_dispatch_combines_backend_outputs(monkeypatch): torch.testing.assert_close(output, padded_output + grouped_output) -def test_thd_mask_type_runtime_dispatch_can_force_grouped(monkeypatch): +@pytest.mark.parametrize("uniform_policy", (False, True)) +def test_thd_mask_type_runtime_dispatch_can_force_grouped(monkeypatch, uniform_policy): """The per-call override must bypass padded backend probing.""" attention = make_dot_product_attention(torch.float16, MODEL_CONFIG, "thd") cu_seqlens = _make_cu_seqlens((1, 1)) - policies = _make_policies((("padding", (0,), (-1, -1)), ("padding_causal", (1,), (-1, 0)))) + if uniform_policy: + policies = _make_policies((("padding", (0, 1), (-1, -1)),)) + else: + policies = _make_policies((("padding", (0,), (-1, -1)), ("padding_causal", (1,), (-1, 0)))) query = torch.zeros(2, NUM_HEADS, HEAD_DIM, dtype=torch.float16, device="cuda") grouped_output = query.new_ones((2, NUM_HEADS * HEAD_DIM)) 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 d34c3c76781..f5881f16de9 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 @@ -1750,7 +1750,8 @@ def _forward_thd_mask_types( nonempty_policies = [policy for policy in policies if policy["sequence_ids"].numel() > 0] batch_size = cu_seqlens_q.shape[0] - 1 if ( - len(nonempty_policies) == 1 + thd_attention_policy_dispatch != "grouped" + and len(nonempty_policies) == 1 and nonempty_policies[0]["sequence_ids"].numel() == batch_size ): policy = nonempty_policies[0] diff --git a/transformer_engine/pytorch/attention/multi_head_attention.py b/transformer_engine/pytorch/attention/multi_head_attention.py index ea40c7891a2..87fec8df73a 100644 --- a/transformer_engine/pytorch/attention/multi_head_attention.py +++ b/transformer_engine/pytorch/attention/multi_head_attention.py @@ -737,6 +737,7 @@ def forward( fast_zero_fill: bool = True, pad_between_seqs: Optional[bool] = None, thd_attention_policies: Optional[List[Dict[str, Any]]] = None, + thd_attention_policy_dispatch: str = "auto", ) -> Tuple[Union[torch.Tensor, None], ...]: r""" Forward propagation for MultiheadAttention layer. @@ -777,6 +778,9 @@ def forward( Per-sequence policies for packed THD attention. Passed through to :class:`DotProductAttention`; do not also pass :attr:`attn_mask_type` or :attr:`window_size`. + thd_attention_policy_dispatch: {``"auto"``, ``"grouped"``}, default = ``"auto"`` + Dispatch strategy for :attr:`thd_attention_policies`. Passed through + to :class:`DotProductAttention`. encoder_output : Optional[torch.Tensor], default = None Output of the encoder block to be fed into the decoder block if using ``layer_type="decoder"``. @@ -1222,6 +1226,7 @@ def forward( window_size=window_size, bottom_right_diagonal=bottom_right_diagonal, thd_attention_policies=thd_attention_policies, + thd_attention_policy_dispatch=thd_attention_policy_dispatch, checkpoint_core_attention=checkpoint_core_attention, core_attention_bias_type=core_attention_bias_type, core_attention_bias=core_attention_bias, diff --git a/transformer_engine/pytorch/transformer.py b/transformer_engine/pytorch/transformer.py index e47a9816a63..08440a87e6f 100644 --- a/transformer_engine/pytorch/transformer.py +++ b/transformer_engine/pytorch/transformer.py @@ -659,6 +659,7 @@ def forward( fast_zero_fill: bool = True, pad_between_seqs: Optional[bool] = None, thd_attention_policies: Optional[List[Dict[str, Any]]] = None, + thd_attention_policy_dispatch: str = "auto", ) -> torch.Tensor: r""" Transformer Layer: attention block and a feedforward network (MLP) @@ -697,6 +698,9 @@ def forward( Per-sequence policies for packed THD self-attention. Passed through to :class:`MultiheadAttention`; do not also pass :attr:`self_attn_mask_type` or :attr:`window_size`. + thd_attention_policy_dispatch: {``"auto"``, ``"grouped"``}, default = ``"auto"`` + Dispatch strategy for :attr:`thd_attention_policies`. Passed through to + :class:`MultiheadAttention`. encoder_output : Optional[torch.Tensor], default = None Output of the encoder block to be fed into the decoder block if using :attr:`layer_type` = ``"decoder"``. @@ -880,6 +884,7 @@ def forward( window_size=window_size, bottom_right_diagonal=bottom_right_diagonal, thd_attention_policies=thd_attention_policies, + thd_attention_policy_dispatch=thd_attention_policy_dispatch, inference_params=inference_params, is_first_microbatch=is_first_microbatch, checkpoint_core_attention=checkpoint_core_attention, From 98f375f0cc2b9c97092919a7db6ed6e6209fc801 Mon Sep 17 00:00:00 2001 From: Desh Raj Date: Wed, 2 Sep 2026 03:55:33 -0700 Subject: [PATCH 16/16] Fix FlashAttention cross-attention backend selection Signed-off-by: Desh Raj --- .../attention/dot_product_attention/utils.py | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/transformer_engine/pytorch/attention/dot_product_attention/utils.py b/transformer_engine/pytorch/attention/dot_product_attention/utils.py index a87dd12a6bd..33d612b4f43 100644 --- a/transformer_engine/pytorch/attention/dot_product_attention/utils.py +++ b/transformer_engine/pytorch/attention/dot_product_attention/utils.py @@ -1370,12 +1370,17 @@ def _is_fa3_supported(num_heads, num_gqa_groups, head_dim_qk, head_dim_v, qkv_dt "Disabling FlashAttention as sliding window attention requires flash-attn 2.3+" ) use_flash_attention_2 = False - elif not bottom_right_diagonal and max_seqlen_q != max_seqlen_kv: - logger.debug( - "Disabling FlashAttention as it only supports sliding window with bottom right" - " diagonal alignment for cross-attention" - ) - use_flash_attention = False + if ( + use_flash_attention + and (window_size[0] != -1 or window_size[1] not in [-1, 0]) + and not bottom_right_diagonal + and max_seqlen_q != max_seqlen_kv + ): + logger.debug( + "Disabling FlashAttention as it only supports sliding window with bottom right" + " diagonal alignment for cross-attention" + ) + use_flash_attention = False # Filter: Attention bias # backend | bias types | ALiBi diagonal alignment