diff --git a/qa/L3_pytorch_FA_versions_test/test.sh b/qa/L3_pytorch_FA_versions_test/test.sh index e7fd3189f35..266abff774d 100644 --- a/qa/L3_pytorch_FA_versions_test/test.sh +++ b/qa/L3_pytorch_FA_versions_test/test.sh @@ -36,8 +36,8 @@ export FLASH_ATTN_CUDA_ARCHS=$sm_arch CP_FA_VERSION="" if [ $sm_arch -gt 90 ] then - FA_versions=(4.0.0b11) - CP_FA_VERSION="4.0.0b11" + FA_versions=(4.0.0b33) + CP_FA_VERSION="4.0.0b33" elif [ $sm_arch -eq 90 ] then FA_versions=(3.0.0b1) @@ -66,13 +66,13 @@ do elif [[ "${fa_version}" == 4.* ]] then export NVTE_FLASH_ATTN_V4=1 - # FA4 is intentionally last in every version array. Its b11 test pin needs - # CUTLASS DSL 4.4.2, so replace the image-matched stack only for this final + # FA4 is intentionally last in every version array. CUTLASS DSL 4.8.0 supports + # SM107, so replace the image-matched stack only for this final # iteration; later iterations would otherwise need that stack restored. pip3 uninstall -y nvidia-cutlass-dsl nvidia-cutlass-dsl-libs-base \ nvidia-cutlass-dsl-libs-cu12 nvidia-cutlass-dsl-libs-cu13 \ || error_exit "Failed to isolate CUTLASS DSL for Flash Attention $fa_version" - pip3 install flash-attn-4==${fa_version} nvidia-cutlass-dsl[cu13]==4.4.2 \ + pip3 install flash-attn-4==${fa_version} nvidia-cutlass-dsl[cu13]==4.8.0 \ --no-build-isolation || error_exit "Failed to install Flash Attention $fa_version" else export NVTE_FLASH_ATTN_V3=1 @@ -135,6 +135,13 @@ do fi NVTE_TORCH_COMPILE=0 NVTE_ALLOW_UNSAFE_PICKLE_EXTRA_STATE=1 python3 -m pytest -v -s --junitxml=$XML_ATTN $TE_PATH/tests/pytorch/attention/test_attention.py || test_fail "test_attention.py (FA $fa_version)" fi + + if [[ "${fa_version}" == 4.* ]]; then + XML_BACKEND="$XML_LOG_DIR/pytest_test_attention_backend_selection_fa${fa_tag}.xml" + NVTE_TORCH_COMPILE=0 python3 -m pytest -v -s --junitxml="$XML_BACKEND" \ + "$TE_PATH/tests/pytorch/attention/test_attention_backend_selection.py" \ + || test_fail "FA4 backend-selection tests (FA $fa_version)" + fi done if [ "$RET" -ne 0 ]; then diff --git a/tests/pytorch/attention/test_attention_backend_selection.py b/tests/pytorch/attention/test_attention_backend_selection.py index c2944eece3b..bd587416a79 100644 --- a/tests/pytorch/attention/test_attention_backend_selection.py +++ b/tests/pytorch/attention/test_attention_backend_selection.py @@ -12,6 +12,7 @@ from transformer_engine.pytorch import DotProductAttention from transformer_engine.pytorch.attention.dot_product_attention import ( + backends as dpa_backends, dot_product_attention as dpa_module, utils as dpa_utils, ) @@ -42,19 +43,20 @@ def isolated_backends(monkeypatch): @pytest.mark.parametrize( - "capability,training,backward,deterministic,unfused,expect_flash", + "capability,training,backward,deterministic,head_dims,unfused,expect_flash", [ - pytest.param((12, 0), True, True, True, True, False, id="sm120-training"), - pytest.param((12, 0), False, True, True, True, False, id="sm120-eval-backward"), - pytest.param((12, 1), False, True, True, True, False, id="sm121-eval-backward"), - pytest.param((12, 0), False, False, True, True, True, id="forward-only"), - pytest.param((12, 0), True, True, False, True, True, id="nondeterministic"), - pytest.param((12, 0), True, True, True, False, False, id="no-fallback"), - pytest.param((10, 0), True, True, True, True, True, id="sm100-unaffected"), + pytest.param((12, 0), True, True, True, (128, 128), True, False, id="sm120-training"), + pytest.param((12, 0), False, True, True, (128, 128), True, False, id="sm120-eval-backward"), + pytest.param((12, 1), False, True, True, (128, 128), True, False, id="sm121-eval-backward"), + pytest.param((12, 0), False, False, True, (128, 128), True, True, id="forward-only"), + pytest.param((12, 0), True, True, False, (128, 128), True, True, id="nondeterministic"), + pytest.param((12, 0), True, True, True, (128, 128), False, False, id="no-fallback"), + pytest.param((10, 0), True, True, True, (128, 128), True, True, id="sm100-d128"), + pytest.param((10, 0), True, True, True, (256, 256), True, False, id="sm100-d256"), ], ) def test_fa4_deterministic_backend_selection( - monkeypatch, capability, training, backward, deterministic, unfused, expect_flash + monkeypatch, capability, training, backward, deterministic, head_dims, unfused, expect_flash ): monkeypatch.setenv("NVTE_UNFUSED_ATTN", str(int(unfused))) monkeypatch.setattr(dpa_utils, "get_device_compute_capability", lambda device: capability) @@ -66,8 +68,8 @@ def test_fa4_deterministic_backend_selection( device=torch.device("cuda:0"), qkv_dtype=torch.bfloat16, qkv_layout="bshd_bshd_bshd", - head_dim_qk=128, - head_dim_v=128, + head_dim_qk=head_dims[0], + head_dim_v=head_dims[1], attn_mask_type="causal", window_size=(-1, 0), deterministic=deterministic, @@ -82,6 +84,44 @@ def test_fa4_deterministic_backend_selection( assert available == [expect_flash, False, unfused] +@pytest.mark.parametrize( + "version,backward,expect_flash", + [ + pytest.param("4.0.0b30", False, False, id="b30-forward"), + pytest.param("4.0.0b31", False, True, id="b31-forward"), + pytest.param("4.0.0b32", True, False, id="b32-backward"), + pytest.param("4.0.0b33", True, True, id="b33-backward"), + ], +) +@pytest.mark.parametrize("path", ["compact", "padding", "all-gather"]) +def test_fa4_d256_seqused_backend_selection(monkeypatch, version, backward, expect_flash, path): + """FA4 D=256 eligibility follows seqused_q/k forward/backward support.""" + monkeypatch.setenv("NVTE_ALLOW_NONDETERMINISTIC_ALGO", "1") + monkeypatch.setattr(dpa_utils, "get_device_compute_capability", lambda device: (10, 0)) + monkeypatch.setattr(dpa_utils, "get_cudnn_version", lambda: (9, 26, 0)) + monkeypatch.setattr(dpa_utils.FlashAttentionUtils, "v4_is_installed", True) + monkeypatch.setattr(dpa_utils.FlashAttentionUtils, "fa4_version", PkgVersion(version)) + monkeypatch.setattr(dpa_utils.FlashAttentionUtils, "v4_validate_head_dims", None) + params = dpa_utils.AttentionParams( + device=torch.device("cuda:0"), + qkv_dtype=torch.bfloat16, + qkv_layout="thd_thd_thd", + head_dim_qk=256, + head_dim_v=256, + attn_mask_type="padding_causal", + pad_between_seqs=path == "padding", + context_parallel=path == "all-gather", + cp_comm_type="all_gather" if path == "all-gather" else "p2p", + deterministic=False, + requires_backward=backward, + ) + flash, selected_version, _, _, _, available = dpa_utils.get_attention_backend(params) + expected = path == "compact" or expect_flash + assert bool(flash) is expected + assert selected_version == (dpa_utils.FlashAttentionUtils.fa4_version if expected else None) + assert bool(available[0]) is expected + + @pytest.mark.parametrize("changed_field", ["device", "requires_backward"]) def test_thd_backend_cache_tracks_execution_context(monkeypatch, changed_field): selector = Mock(return_value=(False, None, False, None, True, [False, False, True])) @@ -161,3 +201,35 @@ def test_fa4_cached_selection_from_other_device(monkeypatch): assert selector.call_args.args[0].device == qkv[0].device assert dpa_module._attention_backends["use_unfused_attention"] assert all(t.grad is not None and torch.isfinite(t.grad).all() for t in qkv) + + +def _fa4_normalized_kwargs(kwargs): + received = {} + dpa_backends._fa4_with_none_window_sentinel(received.update)(**kwargs) + return received + + +@pytest.mark.parametrize( + "sent,expected", + [ + ({"window_size": (-1, 0)}, {"window_size": (None, 0)}), + ({"window_size": (511, -1)}, {"window_size": (511, None)}), + # Other negative offsets are not the -1 sentinel. + ({"window_size": (7, -8)}, {"window_size": (7, -8)}), + ( + {"window_size_left": -1, "window_size_right": 0}, + {"window_size_left": None, "window_size_right": 0}, + ), + ( + {"window_size_left": 0, "window_size_right": -1}, + {"window_size_left": 0, "window_size_right": None}, + ), + ( + {"window_size_left": 7, "window_size_right": -8}, + {"window_size_left": 7, "window_size_right": -8}, + ), + ], +) +def test_fa4_window_sentinel_normalization(sent, expected): + """Convert only TE's -1 sentinel for both FA4 window argument forms.""" + assert _fa4_normalized_kwargs(sent) == expected diff --git a/tests/pytorch/attention/test_attention_with_cp.py b/tests/pytorch/attention/test_attention_with_cp.py index e4b5ad86edb..64158556cc7 100644 --- a/tests/pytorch/attention/test_attention_with_cp.py +++ b/tests/pytorch/attention/test_attention_with_cp.py @@ -60,6 +60,7 @@ "cp_2_1": ModelConfig(2, 4096, 12, 128, num_gqa_groups=2), # GQA "cp_2_2": ModelConfig(2, 4096, 32, 128, attn_mask_type="causal", window_size=(128, 0)), # GQA "cp_2_3": ModelConfig(2, 4096, 12, 128, num_gqa_groups=2, window_size=(512, 512)), # GQA + "cp_2_4": ModelConfig(2, 4096, 32, 256, num_gqa_groups=4, attn_mask_type="causal"), # GQA "cp_3_0": ModelConfig(2, 4096, 128, 192, attn_mask_type="causal", head_dim_v=128), # MLA "cp_3_1": ModelConfig(2, 4096, 12, 192, head_dim_v=128), # MLA "cp_3_2": ModelConfig( @@ -319,9 +320,10 @@ def _submit(pool: PoolWorker, **kwargs) -> None: dtypes = ["bf16", "fp16"] qkv_formats = ["bshd", "sbhd", "thd"] cp_comm_types = ["p2p", "all_gather", "a2a", "a2a+p2p"] +essential_model_configs_flash_attn = model_configs_flash_attn if test_essential: configs = ["cp_2_0", "cp_2_2", "cp_3_0", "cp_3_3"] - model_configs_flash_attn = {k: model_configs_flash_attn[k] for k in configs} + essential_model_configs_flash_attn = {k: model_configs_flash_attn[k] for k in configs} dtypes = ["bf16"] qkv_formats = ["sbhd", "thd"] @@ -336,7 +338,7 @@ def _submit(pool: PoolWorker, **kwargs) -> None: ) @pytest.mark.skipif(get_device_compute_capability() < (8, 0), reason="CP tests require sm80+.") @pytest.mark.parametrize("dtype", dtypes) -@pytest.mark.parametrize("model", model_configs_flash_attn.keys()) +@pytest.mark.parametrize("model", essential_model_configs_flash_attn.keys()) @pytest.mark.parametrize("qkv_format", qkv_formats) @pytest.mark.parametrize("cp_comm_type", cp_comm_types) @pytest.mark.parametrize("pad_between_seqs", [False, True]) @@ -552,6 +554,7 @@ def test_cp_with_flash_attention_softcap(cp_pool, cp_comm_type): dtypes = ["bf16", "fp16", "fp8"] qkv_formats = ["bshd", "sbhd", "thd"] cp_comm_types = ["p2p", "all_gather", "a2a", "a2a+p2p"] +essential_model_configs_fused_attn = model_configs_fused_attn if test_essential: configs = [ "cp_1_0", @@ -567,14 +570,14 @@ def test_cp_with_flash_attention_softcap(cp_pool, cp_comm_type): "cp_5_0", "cp_5_1", ] - model_configs_fused_attn = {k: model_configs_fused_attn[k] for k in configs} + essential_model_configs_fused_attn = {k: model_configs_fused_attn[k] for k in configs} dtypes = ["bf16", "fp8"] qkv_formats = ["sbhd", "thd"] @pytest.mark.skipif(get_device_compute_capability() < (8, 0), reason="CP tests require sm80+.") @pytest.mark.parametrize("dtype", dtypes) -@pytest.mark.parametrize("model", model_configs_fused_attn.keys()) +@pytest.mark.parametrize("model", essential_model_configs_fused_attn.keys()) @pytest.mark.parametrize("qkv_format", qkv_formats) @pytest.mark.parametrize("cp_comm_type", cp_comm_types) @pytest.mark.parametrize("fp8_bwd", [True, False]) @@ -779,13 +782,22 @@ def test_cp_with_fused_attention_no_load_balance(cp_pool): ) -def test_cp_with_flash_attention_no_load_balance(cp_pool): +@pytest.mark.parametrize("model", ("cp_2_0", "cp_2_4")) +def test_cp_with_flash_attention_no_load_balance(cp_pool, model): """Check the supported unpadded FlashAttention path.""" - config = copy.deepcopy(model_configs_flash_attn["cp_2_0"]) + config = copy.deepcopy(model_configs_flash_attn[model]) + fa4_expected = ( + config.head_dim_qk == 256 + and (10, 0) <= get_device_compute_capability() < (12, 0) + and fa4_enabled + and FlashAttentionUtils.v4_is_installed + and FlashAttentionUtils.fa4_version >= FlashAttentionUtils.v4_0_0_beta33 + and not _deterministic + ) config.context_parallel = True config.cp_comm_type = "all_gather" config.attn_mask_type = "padding_causal" - available_backends, _, _ = get_available_attention_backends( + available_backends, flash_backend, _ = get_available_attention_backends( config, qkv_dtype=torch.bfloat16, qkv_layout="thd_thd_thd", @@ -793,12 +805,16 @@ def test_cp_with_flash_attention_no_load_balance(cp_pool): is_training=True, deterministic=_deterministic, ) + if fa4_expected: + assert available_backends[0] and flash_backend is not None and flash_backend.major == 4 + elif config.head_dim_qk == 256: + pytest.skip("D=256 THD all-gather requires SM100/SM110 FA4 b33+ non-deterministic.") if not available_backends[0]: pytest.skip("FlashAttention is unavailable.") _submit( cp_pool(2), dtype="bf16", - model="cp_2_0", + model=model, qkv_format="thd", kernel_backend="FlashAttention", cp_comm_type="all_gather", diff --git a/transformer_engine/pytorch/attention/dot_product_attention/backends.py b/transformer_engine/pytorch/attention/dot_product_attention/backends.py index f90fc46c032..174ee49f412 100644 --- a/transformer_engine/pytorch/attention/dot_product_attention/backends.py +++ b/transformer_engine/pytorch/attention/dot_product_attention/backends.py @@ -8,6 +8,7 @@ from dataclasses import dataclass from importlib.metadata import version as get_pkg_version from importlib.metadata import PackageNotFoundError +import functools import inspect import os from typing import Any, Callable, Dict, List, Optional, Tuple, Union @@ -218,6 +219,27 @@ except (ValueError, TypeError): fa_utils.fa3_supports_softcap = False + +def _fa4_with_none_window_sentinel(func: Callable) -> Callable: + """Translate TE's ``-1`` unbounded-window sentinel to FA4's ``None``. + + Preserve other negative offsets, which can represent empty windows. Adapt the FA4 entry + points because shared FA2/FA3 callers still use ``-1``. + """ + + @functools.wraps(func) + def wrapper(*args, **kwargs): + window = kwargs.get("window_size") + if window is not None: + kwargs["window_size"] = tuple(None if bound == -1 else bound for bound in window) + for bound_name in ("window_size_left", "window_size_right"): + if kwargs.get(bound_name) == -1: + kwargs[bound_name] = None + return func(*args, **kwargs) + + return wrapper + + # Try to import Flash Attention v4 try: fa_utils.fa4_version = PkgVersion(get_pkg_version("flash-attn-4")) @@ -259,10 +281,12 @@ else: # Unlike versions 2 and 3, FlashAttention 4 registers no custom ops: it builds # its kernels through the CUTLASS DSL as it runs. Keep it an eager island. - flash_attn_func_v4 = no_torch_dynamo()(_flash_attn_func_v4) - flash_attn_varlen_func_v4 = no_torch_dynamo()(_flash_attn_varlen_func_v4) - _flash_attn_fwd_v4 = no_torch_dynamo()(_flash_attn_fwd_v4) - _flash_attn_bwd_v4 = no_torch_dynamo()(_flash_attn_bwd_v4) + flash_attn_func_v4 = no_torch_dynamo()(_fa4_with_none_window_sentinel(_flash_attn_func_v4)) + flash_attn_varlen_func_v4 = no_torch_dynamo()( + _fa4_with_none_window_sentinel(_flash_attn_varlen_func_v4) + ) + _flash_attn_fwd_v4 = no_torch_dynamo()(_fa4_with_none_window_sentinel(_flash_attn_fwd_v4)) + _flash_attn_bwd_v4 = no_torch_dynamo()(_fa4_with_none_window_sentinel(_flash_attn_bwd_v4)) fa_utils.v4_validate_head_dims = _fa4_validate_head_dims fa_utils.set_flash_attention_4_params() diff --git a/transformer_engine/pytorch/attention/dot_product_attention/utils.py b/transformer_engine/pytorch/attention/dot_product_attention/utils.py index 3e11039c1f4..a773091cd4e 100644 --- a/transformer_engine/pytorch/attention/dot_product_attention/utils.py +++ b/transformer_engine/pytorch/attention/dot_product_attention/utils.py @@ -148,11 +148,13 @@ class FlashAttentionUtils: v4_is_installed = False fa4_version = PkgVersion("0") + v4_0_0_beta31 = PkgVersion("4.0.0b31") + v4_0_0_beta33 = PkgVersion("4.0.0b33") use_v4 = False # Set by a signature probe in backends.py; fail-closed default. fa3_supports_softcap = False v4_installation_steps = """\ -pip install flash-attn-4==4.0.0b11 nvidia-cutlass-dsl[cu13]""" +pip install flash-attn-4==4.0.0b33 nvidia-cutlass-dsl[cu13]==4.8.0""" v4_warning_printed = False # Set by backends.py if FA4 is installed; calls flash_attn.cute.interface._validate_head_dims # which raises AssertionError for unsupported (head_dim, head_dim_v) combinations. @@ -1286,6 +1288,32 @@ def _is_fa3_supported(num_heads, num_gqa_groups, head_dim_qk, head_dim_v, qkv_dt cp_comm_type, ) use_flash_attention_4 = False + # SM100/SM110 D=256 gained seqused_q/k support in b31 for forward and b33 for backward. + # THD all-gather always passes this metadata; other THD paths pass it only + # when pad_between_seqs=True. + fa4_uses_seqused = qkv_format == "thd" and ( + pad_between_seqs or (context_parallel and cp_comm_type == "all_gather") + ) + if ( # pylint: disable=too-many-boolean-expressions + use_flash_attention_4 + and FlashAttentionUtils.v4_is_installed + and (10, 0) <= device_compute_capability < (12, 0) + and head_dim_qk == head_dim_v == 256 + and fa4_uses_seqused + and ( + FlashAttentionUtils.fa4_version < FlashAttentionUtils.v4_0_0_beta31 + or ( + attention_params.requires_backward + and FlashAttentionUtils.fa4_version < FlashAttentionUtils.v4_0_0_beta33 + ) + ) + ): + logger.debug( + "Disabling FlashAttention 4 for SM100/SM110 head_dim=256 with seqused_q/k: " + "version %s does not support the requested execution direction.", + FlashAttentionUtils.fa4_version, + ) + use_flash_attention_4 = False if context_parallel and ( use_flash_attention_2 or use_flash_attention_3 or use_flash_attention_4 ): @@ -1765,11 +1793,15 @@ def _is_fa3_supported(num_heads, num_gqa_groups, head_dim_qk, head_dim_v, qkv_dt ) use_flash_attention_3 = False if use_flash_attention_4 and deterministic and FlashAttentionUtils.v4_is_installed: - # eval() does not disable autograd; only forward-only calls can use this kernel. - if attention_params.requires_backward and device_compute_capability[0] == 12: + # eval() does not disable autograd. SM12x backward and SM100/SM110 D=256 backward + # reject deterministic execution, so only forward-only calls can use those kernels. + if attention_params.requires_backward and ( + device_compute_capability[0] == 12 + or ((10, 0) <= device_compute_capability < (12, 0) and head_dim_qk == head_dim_v == 256) + ): logger.debug( - "Disabling FlashAttention 4 for deterministic backward on SM12x: the CuTe" - " SM12x backward kernel does not support deterministic execution." + "Disabling FlashAttention 4 because the selected backward kernel does not " + "support deterministic execution." ) use_flash_attention_4 = False if use_fused_attention and deterministic: