diff --git a/qa/L0_pytorch_unittest/test.sh b/qa/L0_pytorch_unittest/test.sh index a06ffa70458..a78a99d7f95 100644 --- a/qa/L0_pytorch_unittest/test.sh +++ b/qa/L0_pytorch_unittest/test.sh @@ -69,6 +69,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_attention.py b/tests/pytorch/attention/test_attention.py index 9dd377c41cd..0f5cdfa6476 100644 --- a/tests/pytorch/attention/test_attention.py +++ b/tests/pytorch/attention/test_attention.py @@ -240,7 +240,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", @@ -252,7 +252,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", @@ -265,7 +265,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", @@ -1149,7 +1149,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, @@ -1158,6 +1198,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. @@ -1203,10 +1244,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() @@ -1432,26 +1471,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"]: @@ -1474,11 +1500,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, @@ -1502,6 +1524,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 new file mode 100644 index 00000000000..d665df4ceff --- /dev/null +++ b/tests/pytorch/attention/test_mixed_thd_attention.py @@ -0,0 +1,890 @@ +# Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# See LICENSE for license information. + +"""Tests for per-sequence mask types in packed THD attention.""" + +import pytest +import torch + +from transformer_engine.pytorch import DotProductAttention, MultiheadAttention, TransformerLayer +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") + +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 make_cu_seqlens(lengths) + + +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 + ] + + +@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, + thd_attention_policy_dispatch="grouped", + ) + assert output.shape == hidden_states.shape + + +def _per_sequence_scalar_reference( + attention: DotProductAttention, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + cu_seqlens_q: torch.Tensor, + cu_seqlens_kv: torch.Tensor, + policies, + *, + cu_seqlens_q_padded=None, + cu_seqlens_kv_padded=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 policy in policies: + 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()) + 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 + ) + 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_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, + bottom_right_diagonal=policy_bottom_right_diagonal, + ) + + 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( + "policy_specs", + ( + (("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(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") + + reset_rng_states() + cu_seqlens = _make_cu_seqlens((7, 3, 5, 4)) + token_count = 19 + policies = _make_policies(policy_specs) + + 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_dot_product_attention(dtype, MODEL_CONFIG, "thd") + 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, + thd_attention_policies=policies, + ) + reference_output = _per_sequence_scalar_reference( + attention, + reference_query, + reference_key, + reference_value, + cu_seqlens, + cu_seqlens, + policies, + ) + + 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) + 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), + ): + 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.""" + 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") + policies = _make_policies((("padding", (0, 2), (-1, -1)), ("padding_causal", (1, 3), (-1, 0)))) + + 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_dot_product_attention(dtype, MODEL_CONFIG, "thd") + + 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, + thd_attention_policies=policies, + ) + reference_output = _per_sequence_scalar_reference( + attention, + reference_query, + reference_key, + reference_value, + cu_seqlens, + cu_seqlens, + policies, + 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_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, 4, 5)) + policies = _make_policies( + ( + ("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(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_() + reference_value = value.detach().clone().requires_grad_() + attention = make_dot_product_attention( + dtype, + MODEL_CONFIG, + "thd", + 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, + thd_attention_policies=policies, + ) + reference_output = _per_sequence_scalar_reference( + attention, + reference_query, + reference_key, + reference_value, + cu_seqlens_q, + cu_seqlens_kv, + policies, + ) + 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( + "policy_specs", + ( + ( + ("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_support_repeated_masks_and_policy_order(policy_specs): + """Repeated mask types may use distinct windows in any policy-list order.""" + reset_rng_states() + dtype = torch.float16 + cu_seqlens = _make_cu_seqlens((7, 3, 5, 4)) + policies = _make_policies(policy_specs) + + 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_dot_product_attention(dtype, MODEL_CONFIG, "thd") + + 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, + thd_attention_policies=policies, + ) + reference_output = _per_sequence_scalar_reference( + attention, + reference_query, + reference_key, + reference_value, + cu_seqlens, + cu_seqlens, + policies, + ) + 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_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) + + 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, + thd_attention_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.""" + attention = make_dot_product_attention(torch.float16, MODEL_CONFIG, "thd") + 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( + 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, + ) + + 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="auto", + ) + torch.testing.assert_close(output, padded_output + grouped_output) + + +@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)) + 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)) + + 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, + "thd_attention_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): + 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") + + 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_dot_product_attention( + dtype, + MODEL_CONFIG, + "thd", + is_training=False, + ) + + 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, + thd_attention_policies=policies, + ) + + 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 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"), + ("bottom_right_diagonal", "must be a bool"), + ("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): + """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_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") + 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": + 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: + policy_dispatch = "padded" + + 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, + attn_mask_type=scalar_mask_type, + thd_attention_policies=policies, + thd_attention_policy_dispatch=policy_dispatch, + ) + + +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, + thd_attention_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") + 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_attention_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() + 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 1e5f5552d42..dabfd10de44 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 @@ -82,6 +82,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,148 @@ "_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_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: + 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.""" + + @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, @@ -293,6 +449,9 @@ def _needs_eager_dpa(call: Dict[str, Any]) -> Optional[str]: if call.get("checkpoint_core_attention", False): return "activation checkpointing of the attention" + if call.get("thd_attention_policies") is not None: + return "mixed THD attention policies" + qkv_format = call.get("qkv_format") or call["self"].qkv_format if qkv_format == "thd" and ( call.get("max_seqlen_q") is None or call.get("max_seqlen_kv") is None @@ -1391,6 +1550,361 @@ 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 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: + if policy["sequence_ids"].numel() == 0: + continue + *_, available_backends = _get_thd_policy_attention_backend( + policy, + attention_params_kwargs, + True, + ) + 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, + 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 + + @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_with_padding( + 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], + policies: List[Dict[str, Any]], + 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], + num_splits: Optional[int], + ) -> torch.Tensor: + """Dispatch mixed THD policies with inter-sequence padding.""" + output = None + 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, + 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] + ) + _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, + 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_output = self.forward( + policy_query, + policy_key, + policy_value, + 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=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, + 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("Mixed THD policies 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], + policies: List[Dict[str, Any]], + 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], + num_splits: Optional[int], + ) -> torch.Tensor: + """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: + 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_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( + policy_query, + policy_key, + policy_value, + 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=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, + 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], + policies: List[Dict[str, Any]], + max_seqlen_q: Optional[int], + max_seqlen_kv: Optional[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], + 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] + 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_policies = [policy for policy in policies if policy["sequence_ids"].numel() > 0] + batch_size = cu_seqlens_q.shape[0] - 1 + if ( + thd_attention_policy_dispatch != "grouped" + and len(nonempty_policies) == 1 + 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, + 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=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_policies: + raise ValueError("Mixed THD policies must assign at least one sequence.") + + 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( + query_layer, + key_layer, + value_layer, + cu_seqlens_q, + cu_seqlens_kv, + cu_seqlens_q_padded, + cu_seqlens_kv_padded, + 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, + 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, + attention_params_kwargs=attention_params_kwargs, + 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(when=_needs_eager_dpa) def forward( self, @@ -1425,6 +1939,8 @@ def forward( qkv_layer: Optional[torch.Tensor] = None, kv_layer: Optional[torch.Tensor] = None, qkv_interleave_dim: int = -3, + thd_attention_policies: Optional[List[Dict[str, Any]]] = None, + thd_attention_policy_dispatch: str = "auto", ) -> torch.Tensor: r""" Dot Product Attention Layer. @@ -1664,7 +2180,99 @@ 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_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"``, 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 + 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 + 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. """ + global _attention_backends + + 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 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 " + "also pass attn_mask_type or window_size." + ) + + 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.") + 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 '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): + 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( + f"Mixed THD policies support only padding mask types, got {mask_type!r}." + ) + policy_window_size = dpa_utils.check_set_window_size( + mask_type, + policy["window_size"], + ) + 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"}: + 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, @@ -1743,30 +2351,29 @@ def forward( f" {self.num_gqa_groups_per_partition} heads! Found {num_gqa_groups}." ) - # checks for attention mask - 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!" - - # 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 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 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 # checks for qkv_format if qkv_format is None: @@ -1797,9 +2404,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!" @@ -1825,6 +2433,59 @@ def forward( seqlens_kv = cu_seqlens_kv[1:] - cu_seqlens_kv[:-1] max_seqlen_kv = int((seqlens_kv.max().item() + 63) // 64 * 64) + 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("Mixed THD policies are supported only with qkv_format='thd'.") + if attention_mask is not None: + 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( + "Mixed THD policies do not yet support attention bias or ALiBi." + ) + if inference_params is not None: + 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("Mixed THD policies do not support score modification.") + if fp8_output or self.fp8 or self.return_max_logit: + raise ValueError( + "Mixed THD policies do not yet support FP8 or max-logit output." + ) + assigned_sequence_count = 0 + for policy in thd_mask_policies: + sequence_ids = policy["sequence_ids"] + if not isinstance(sequence_ids, torch.Tensor): + 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( + "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( + "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( + "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: assert self.layer_number is not None, "Layer number must be set!" @@ -1934,6 +2595,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: @@ -2075,27 +2738,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, @@ -2114,7 +2772,37 @@ def forward( has_score_mod=score_mod is not None, has_score_mod_bprop=score_mod_bprop is not None, ) - global _attention_backends + 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, + 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, + thd_attention_policy_dispatch=thd_attention_policy_dispatch, + ) + + 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, + ) 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. 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 diff --git a/transformer_engine/pytorch/attention/multi_head_attention.py b/transformer_engine/pytorch/attention/multi_head_attention.py index ed68dc82f04..82221f0c836 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 @@ -752,6 +752,8 @@ 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, + thd_attention_policy_dispatch: str = "auto", ) -> Tuple[Union[torch.Tensor, None], ...]: r""" Forward propagation for MultiheadAttention layer. @@ -788,6 +790,13 @@ 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`. + 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"``. @@ -847,23 +856,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!" @@ -1227,6 +1241,8 @@ def forward( attn_mask_type=attn_mask_type, 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 56028396e3d..664683b5551 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 @@ -675,6 +675,8 @@ 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, + thd_attention_policy_dispatch: str = "auto", ) -> torch.Tensor: r""" Transformer Layer: attention block and a feedforward network (MLP) @@ -709,6 +711,13 @@ 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`. + 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"``. @@ -792,11 +801,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 @@ -806,16 +826,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"}: @@ -826,7 +836,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)}" @@ -850,7 +860,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 = [ @@ -889,6 +900,8 @@ 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, + thd_attention_policy_dispatch=thd_attention_policy_dispatch, inference_params=inference_params, is_first_microbatch=is_first_microbatch, checkpoint_core_attention=checkpoint_core_attention,