From d70c2742a8aa5e5acc2d3a2b24b85ff04fb432b9 Mon Sep 17 00:00:00 2001 From: Sudhakar Singh Date: Thu, 1 Oct 2026 15:39:10 -0700 Subject: [PATCH 01/10] Update FA4 D=256 capability gates FA4 b31 added seqused_q/k forward support for the SM100 D=256 kernel, while b33 added backward support. Select FA4 by the installed release and actual backward eligibility, retain the deterministic backward guard, and exercise the released b33 dependency stack in L3. Signed-off-by: Sudhakar Singh --- qa/L3_pytorch_FA_versions_test/test.sh | 10 ++--- .../attention/dot_product_attention/utils.py | 41 ++++++++++++++++--- 2 files changed, 41 insertions(+), 10 deletions(-) diff --git a/qa/L3_pytorch_FA_versions_test/test.sh b/qa/L3_pytorch_FA_versions_test/test.sh index e7fd3189f35..8f16ac6e768 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. Its b33 test pin needs + # CUTLASS DSL 4.7.1, 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.7.1 \ --no-build-isolation || error_exit "Failed to install Flash Attention $fa_version" else export NVTE_FLASH_ATTN_V3=1 diff --git a/transformer_engine/pytorch/attention/dot_product_attention/utils.py b/transformer_engine/pytorch/attention/dot_product_attention/utils.py index 3e11039c1f4..6a87bdad59c 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.7.1""" 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,31 @@ 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 for padding. + 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 +1792,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: From 1afbbc295d26e262b8327eef6e5ae0d6ebe1b397 Mon Sep 17 00:00:00 2001 From: Sudhakar Singh Date: Thu, 1 Oct 2026 15:39:10 -0700 Subject: [PATCH 02/10] Cover FA4 D=256 seqused paths Protect the release boundary with focused selector cases and extend the existing no-load-balance CP test to run D=256. This verifies the existing all-gather metadata path without adding strategy-specific production plumbing. Signed-off-by: Sudhakar Singh --- .../attention/run_attention_with_cp.py | 3 + .../test_attention_backend_selection.py | 61 +++++++++++++++---- .../attention/test_attention_with_cp.py | 19 +++++- 3 files changed, 69 insertions(+), 14 deletions(-) diff --git a/tests/pytorch/attention/run_attention_with_cp.py b/tests/pytorch/attention/run_attention_with_cp.py index 0d2a142dbc1..a594c28b251 100644 --- a/tests/pytorch/attention/run_attention_with_cp.py +++ b/tests/pytorch/attention/run_attention_with_cp.py @@ -237,6 +237,7 @@ def run_dpa_with_cp( fa_pad_between_seqs="False", deterministic="False", load_balancing_strategy="DUAL_CHUNK_SWAP", + head_dim=None, softcap="0.0", log_level=logging.WARNING, ): @@ -276,6 +277,8 @@ def run_dpa_with_cp( config = copy.deepcopy(model_configs_fused_attn[model]) else: assert False, f"{model=} is not a known FusedAttention CP config!" + if head_dim is not None: + config.head_dim_qk = config.head_dim_v = int(head_dim) assert config.attn_mask_type in [ "causal", "no_mask", diff --git a/tests/pytorch/attention/test_attention_backend_selection.py b/tests/pytorch/attention/test_attention_backend_selection.py index c2944eece3b..2188f5b25b5 100644 --- a/tests/pytorch/attention/test_attention_backend_selection.py +++ b/tests/pytorch/attention/test_attention_backend_selection.py @@ -42,19 +42,20 @@ def isolated_backends(monkeypatch): @pytest.mark.parametrize( - "capability,training,backward,deterministic,unfused,expect_flash", + "capability,training,backward,deterministic,head_dim,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, True, False, id="sm120-training"), + pytest.param((12, 0), False, True, True, 128, True, False, id="sm120-eval-backward"), + pytest.param((12, 1), False, True, True, 128, True, False, id="sm121-eval-backward"), + pytest.param((12, 0), False, False, True, 128, True, True, id="forward-only"), + pytest.param((12, 0), True, True, False, 128, True, True, id="nondeterministic"), + pytest.param((12, 0), True, True, True, 128, False, False, id="no-fallback"), + pytest.param((10, 0), True, True, True, 128, True, True, id="sm100-d128"), + pytest.param((10, 0), True, True, True, 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_dim, unfused, expect_flash ): monkeypatch.setenv("NVTE_UNFUSED_ATTN", str(int(unfused))) monkeypatch.setattr(dpa_utils, "get_device_compute_capability", lambda device: capability) @@ -66,8 +67,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_dim, + head_dim_v=head_dim, attn_mask_type="causal", window_size=(-1, 0), deterministic=deterministic, @@ -82,6 +83,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])) diff --git a/tests/pytorch/attention/test_attention_with_cp.py b/tests/pytorch/attention/test_attention_with_cp.py index e4b5ad86edb..6276417eab1 100644 --- a/tests/pytorch/attention/test_attention_with_cp.py +++ b/tests/pytorch/attention/test_attention_with_cp.py @@ -779,13 +779,23 @@ 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("head_dim", (128, 256)) +def test_cp_with_flash_attention_no_load_balance(cp_pool, head_dim): """Check the supported unpadded FlashAttention path.""" + if head_dim == 256 and ( + not (10, 0) <= get_device_compute_capability() < (12, 0) + or not fa4_enabled + or not FlashAttentionUtils.v4_is_installed + or FlashAttentionUtils.fa4_version < FlashAttentionUtils.v4_0_0_beta33 + or _deterministic + ): + pytest.skip("D=256 THD all-gather requires SM100/SM110 FA4 b33+ non-deterministic.") config = copy.deepcopy(model_configs_flash_attn["cp_2_0"]) + config.head_dim_qk = config.head_dim_v = head_dim 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 +803,15 @@ def test_cp_with_flash_attention_no_load_balance(cp_pool): is_training=True, deterministic=_deterministic, ) - if not available_backends[0]: + if head_dim == 256: + assert available_backends[0] and flash_backend is not None and flash_backend.major == 4 + elif not available_backends[0]: pytest.skip("FlashAttention is unavailable.") _submit( cp_pool(2), dtype="bf16", model="cp_2_0", + head_dim=head_dim, qkv_format="thd", kernel_backend="FlashAttention", cp_comm_type="all_gather", From 848c87f3176cba1353247992262d946ef41051ec Mon Sep 17 00:00:00 2001 From: Sudhakar Singh Date: Tue, 6 Oct 2026 16:27:31 -0700 Subject: [PATCH 03/10] Integrate FA4 window sentinel handling into D=256 coverage FA4 b33 treats TE's -1 unbounded window sentinel as a literal offset, so the D=256 coverage in this PR needs the adapter from #3532 at all four FA4 entry points. Bring that final adapter change into this branch instead of leaving the new FA4 path dependent on another open PR. Keep the regression tests in test_attention_backend_selection.py alongside the focused FA4 tests. Cover both window argument forms and preserved negative offsets, compare every batch and head with a float64 reference, and run these cases under the FA4 b33 L3 lane. Signed-off-by: Sudhakar Singh --- qa/L3_pytorch_FA_versions_test/test.sh | 8 ++ .../test_attention_backend_selection.py | 82 +++++++++++++++++++ .../dot_product_attention/backends.py | 43 +++++++++- 3 files changed, 129 insertions(+), 4 deletions(-) diff --git a/qa/L3_pytorch_FA_versions_test/test.sh b/qa/L3_pytorch_FA_versions_test/test.sh index 8f16ac6e768..7fdb97782e3 100644 --- a/qa/L3_pytorch_FA_versions_test/test.sh +++ b/qa/L3_pytorch_FA_versions_test/test.sh @@ -135,6 +135,14 @@ 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_fa4_window_sentinel_normalization" \ + "$TE_PATH/tests/pytorch/attention/test_attention_backend_selection.py::test_fa4_causal_attention_is_not_all_zeros" \ + || test_fail "FA4 window sentinel 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 2188f5b25b5..060478e4b0d 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, ) @@ -200,3 +201,84 @@ 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": (-1, -1)}, {"window_size": (None, None)}), + ({"window_size": (511, 0)}, {"window_size": (511, 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": -1, "window_size_right": -1}, + {"window_size_left": None, "window_size_right": None}, + ), + ( + {"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}, + ), + ( + {"window_size_left": 256, "window_size_right": 0}, + {"window_size_left": 256, "window_size_right": 0}, + ), + ({"window_size": (None, None)}, {"window_size": (None, None)}), + ({"window_size": None}, {"window_size": None}), + ({}, {}), + ], +) +def test_fa4_window_sentinel_normalization(sent, expected): + """Convert only TE's -1 sentinel for both FA4 window argument forms.""" + assert _fa4_normalized_kwargs(sent) == expected + + +def test_fa4_causal_attention_is_not_all_zeros(monkeypatch): + """Compare selected FA4 causal attention with an independent float64 reference.""" + if not torch.cuda.is_available(): + pytest.skip("Requires CUDA") + if dpa_backends.flash_attn_func_v4 is None: + pytest.skip("Requires FlashAttention 4") + if torch.cuda.get_device_capability() != (10, 0): + pytest.skip("The FA4 CuTe kernels under test are SM100") + + monkeypatch.setenv("NVTE_UNFUSED_ATTN", "0") + dpa_module._attention_backends["backend_selection_requires_update"] = True + b, h, s, d = 2, 8, 1024, 128 + dtype = torch.bfloat16 + torch.manual_seed(0) + q, k, v = (torch.randn(b, s, h, d, device="cuda", dtype=dtype) for _ in range(3)) + dpa = DotProductAttention( + h, d, qkv_format="bshd", attn_mask_type="causal", attention_dropout=0.0 + ).to(dtype=dtype, device="cuda") + out = dpa(q, k, v).view(b, s, h, d) + + selected = dpa_module._attention_backends["flash_attention_backend"] + assert selected is not None and str(selected).startswith( + "4" + ), f"expected FlashAttention 4 to serve this config, got {selected}" + assert out.abs().max() > 0, "FA4 returned an all-zero output for causal attention" + + qs, ks, vs = (t.double().transpose(1, 2) for t in (q, k, v)) + scores = (qs @ ks.transpose(-1, -2)) * (d**-0.5) + scores = scores.masked_fill( + torch.ones(s, s, dtype=torch.bool, device=qs.device).triu(1), float("-inf") + ) + reference = (torch.softmax(scores, dim=-1) @ vs).transpose(1, 2) + error = (out.double() - reference).abs().max() / reference.abs().max() + assert error < 2e-2, f"FA4 causal attention differs from the float64 reference: {error:.3e}" diff --git a/transformer_engine/pytorch/attention/dot_product_attention/backends.py b/transformer_engine/pytorch/attention/dot_product_attention/backends.py index f90fc46c032..8fb1fcddc16 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,38 @@ except (ValueError, TypeError): fa_utils.fa3_supports_softcap = False + +def _fa4_with_none_window_sentinel(func: Callable) -> Callable: + """Rewrite TE's ``-1`` unbounded-window sentinel to the ``None`` FlashAttention 4 expects. + + TE spells an unbounded side ``-1``; FA4 spells it ``None``. FA4 widens a window to full + attention only when *both* bounds are negative, so TE's causal ``(-1, 0)`` reaches the kernel + as the band ``[row + 1, row]`` -- empty. The output is then all zeros and the LSE all ``-inf``, + with nothing raised: a wrong answer rather than a failure. + + Only ``-1`` is rewritten. A lone negative bound is a valid FA4 request for an empty window, so + widening every negative here would silently turn one of those into full attention. + + Wrapped at the entry points rather than at the ~20 call sites that build these kwargs, since + those are shared with FA2 >= 2.7 and FA3, where ``-1`` is the correct spelling. All four are + wrapped together because ``run_attention_with_cp.py`` grades a CP run against a non-CP run of + the same backend: with both sides empty the comparison agrees, so fixing one pair alone would + present as a regression. Keyword arguments only; a positional caller bypasses this. + """ + + @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 +292,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() From dcb2daa6f46d1b640903053066c2003311e57811 Mon Sep 17 00:00:00 2001 From: Sudhakar Singh Date: Tue, 6 Oct 2026 16:31:50 -0700 Subject: [PATCH 04/10] Shorten FA4 sentinel regression explanations Keep the adapter comment focused on the sentinel contract and the FA4-only boundary. Name the numerical test for its independent reference and remove the redundant all-zero assertion, which singled out one symptom already caught by the full-output comparison. Signed-off-by: Sudhakar Singh --- qa/L3_pytorch_FA_versions_test/test.sh | 2 +- .../test_attention_backend_selection.py | 4 +--- .../attention/dot_product_attention/backends.py | 17 +++-------------- 3 files changed, 5 insertions(+), 18 deletions(-) diff --git a/qa/L3_pytorch_FA_versions_test/test.sh b/qa/L3_pytorch_FA_versions_test/test.sh index 7fdb97782e3..23c660eeeaf 100644 --- a/qa/L3_pytorch_FA_versions_test/test.sh +++ b/qa/L3_pytorch_FA_versions_test/test.sh @@ -140,7 +140,7 @@ do 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_fa4_window_sentinel_normalization" \ - "$TE_PATH/tests/pytorch/attention/test_attention_backend_selection.py::test_fa4_causal_attention_is_not_all_zeros" \ + "$TE_PATH/tests/pytorch/attention/test_attention_backend_selection.py::test_fa4_causal_attention_matches_reference" \ || test_fail "FA4 window sentinel tests (FA $fa_version)" fi done diff --git a/tests/pytorch/attention/test_attention_backend_selection.py b/tests/pytorch/attention/test_attention_backend_selection.py index 060478e4b0d..80938a8abe8 100644 --- a/tests/pytorch/attention/test_attention_backend_selection.py +++ b/tests/pytorch/attention/test_attention_backend_selection.py @@ -248,7 +248,7 @@ def test_fa4_window_sentinel_normalization(sent, expected): assert _fa4_normalized_kwargs(sent) == expected -def test_fa4_causal_attention_is_not_all_zeros(monkeypatch): +def test_fa4_causal_attention_matches_reference(monkeypatch): """Compare selected FA4 causal attention with an independent float64 reference.""" if not torch.cuda.is_available(): pytest.skip("Requires CUDA") @@ -272,8 +272,6 @@ def test_fa4_causal_attention_is_not_all_zeros(monkeypatch): assert selected is not None and str(selected).startswith( "4" ), f"expected FlashAttention 4 to serve this config, got {selected}" - assert out.abs().max() > 0, "FA4 returned an all-zero output for causal attention" - qs, ks, vs = (t.double().transpose(1, 2) for t in (q, k, v)) scores = (qs @ ks.transpose(-1, -2)) * (d**-0.5) scores = scores.masked_fill( diff --git a/transformer_engine/pytorch/attention/dot_product_attention/backends.py b/transformer_engine/pytorch/attention/dot_product_attention/backends.py index 8fb1fcddc16..174ee49f412 100644 --- a/transformer_engine/pytorch/attention/dot_product_attention/backends.py +++ b/transformer_engine/pytorch/attention/dot_product_attention/backends.py @@ -221,21 +221,10 @@ def _fa4_with_none_window_sentinel(func: Callable) -> Callable: - """Rewrite TE's ``-1`` unbounded-window sentinel to the ``None`` FlashAttention 4 expects. + """Translate TE's ``-1`` unbounded-window sentinel to FA4's ``None``. - TE spells an unbounded side ``-1``; FA4 spells it ``None``. FA4 widens a window to full - attention only when *both* bounds are negative, so TE's causal ``(-1, 0)`` reaches the kernel - as the band ``[row + 1, row]`` -- empty. The output is then all zeros and the LSE all ``-inf``, - with nothing raised: a wrong answer rather than a failure. - - Only ``-1`` is rewritten. A lone negative bound is a valid FA4 request for an empty window, so - widening every negative here would silently turn one of those into full attention. - - Wrapped at the entry points rather than at the ~20 call sites that build these kwargs, since - those are shared with FA2 >= 2.7 and FA3, where ``-1`` is the correct spelling. All four are - wrapped together because ``run_attention_with_cp.py`` grades a CP run against a non-CP run of - the same backend: with both sides empty the comparison agrees, so fixing one pair alone would - present as a regression. Keyword arguments only; a positional caller bypasses this. + 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) From 49ed1b285567fef023e3ebef9287d97ce44d8ac1 Mon Sep 17 00:00:00 2001 From: Sudhakar Singh Date: Wed, 7 Oct 2026 12:52:12 -0700 Subject: [PATCH 05/10] Remove redundant FA4 float64 reference test The standalone D=128 BSHD comparison does not exercise the D=256 THD path added by this PR. Keep the direct window-sentinel regression in L3; existing attention tests provide numerical comparisons. Signed-off-by: Sudhakar Singh --- qa/L3_pytorch_FA_versions_test/test.sh | 1 - .../test_attention_backend_selection.py | 34 ------------------- 2 files changed, 35 deletions(-) diff --git a/qa/L3_pytorch_FA_versions_test/test.sh b/qa/L3_pytorch_FA_versions_test/test.sh index 23c660eeeaf..931c8377735 100644 --- a/qa/L3_pytorch_FA_versions_test/test.sh +++ b/qa/L3_pytorch_FA_versions_test/test.sh @@ -140,7 +140,6 @@ do 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_fa4_window_sentinel_normalization" \ - "$TE_PATH/tests/pytorch/attention/test_attention_backend_selection.py::test_fa4_causal_attention_matches_reference" \ || test_fail "FA4 window sentinel tests (FA $fa_version)" fi done diff --git a/tests/pytorch/attention/test_attention_backend_selection.py b/tests/pytorch/attention/test_attention_backend_selection.py index 80938a8abe8..323b8f66364 100644 --- a/tests/pytorch/attention/test_attention_backend_selection.py +++ b/tests/pytorch/attention/test_attention_backend_selection.py @@ -246,37 +246,3 @@ def _fa4_normalized_kwargs(kwargs): def test_fa4_window_sentinel_normalization(sent, expected): """Convert only TE's -1 sentinel for both FA4 window argument forms.""" assert _fa4_normalized_kwargs(sent) == expected - - -def test_fa4_causal_attention_matches_reference(monkeypatch): - """Compare selected FA4 causal attention with an independent float64 reference.""" - if not torch.cuda.is_available(): - pytest.skip("Requires CUDA") - if dpa_backends.flash_attn_func_v4 is None: - pytest.skip("Requires FlashAttention 4") - if torch.cuda.get_device_capability() != (10, 0): - pytest.skip("The FA4 CuTe kernels under test are SM100") - - monkeypatch.setenv("NVTE_UNFUSED_ATTN", "0") - dpa_module._attention_backends["backend_selection_requires_update"] = True - b, h, s, d = 2, 8, 1024, 128 - dtype = torch.bfloat16 - torch.manual_seed(0) - q, k, v = (torch.randn(b, s, h, d, device="cuda", dtype=dtype) for _ in range(3)) - dpa = DotProductAttention( - h, d, qkv_format="bshd", attn_mask_type="causal", attention_dropout=0.0 - ).to(dtype=dtype, device="cuda") - out = dpa(q, k, v).view(b, s, h, d) - - selected = dpa_module._attention_backends["flash_attention_backend"] - assert selected is not None and str(selected).startswith( - "4" - ), f"expected FlashAttention 4 to serve this config, got {selected}" - qs, ks, vs = (t.double().transpose(1, 2) for t in (q, k, v)) - scores = (qs @ ks.transpose(-1, -2)) * (d**-0.5) - scores = scores.masked_fill( - torch.ones(s, s, dtype=torch.bool, device=qs.device).triu(1), float("-inf") - ) - reference = (torch.softmax(scores, dim=-1) @ vs).transpose(1, 2) - error = (out.double() - reference).abs().max() / reference.abs().max() - assert error < 2e-2, f"FA4 causal attention differs from the float64 reference: {error:.3e}" From ff2345d788a1fe914da83d70ee6cd1a4b6d88e38 Mon Sep 17 00:00:00 2001 From: Sudhakar Singh Date: Wed, 7 Oct 2026 12:58:01 -0700 Subject: [PATCH 06/10] Restore FA4 numerical sentinel regression The argument-only sentinel test cannot prove the adapted FA4 call produces correct attention; generic cross-backend comparisons may skip. Restore the independent reference check and keep only representative left, right, and non-sentinel cases for both window argument forms. Signed-off-by: Sudhakar Singh --- qa/L3_pytorch_FA_versions_test/test.sh | 1 + .../test_attention_backend_selection.py | 47 ++++++++++++++----- 2 files changed, 35 insertions(+), 13 deletions(-) diff --git a/qa/L3_pytorch_FA_versions_test/test.sh b/qa/L3_pytorch_FA_versions_test/test.sh index 931c8377735..23c660eeeaf 100644 --- a/qa/L3_pytorch_FA_versions_test/test.sh +++ b/qa/L3_pytorch_FA_versions_test/test.sh @@ -140,6 +140,7 @@ do 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_fa4_window_sentinel_normalization" \ + "$TE_PATH/tests/pytorch/attention/test_attention_backend_selection.py::test_fa4_causal_attention_matches_reference" \ || test_fail "FA4 window sentinel tests (FA $fa_version)" fi done diff --git a/tests/pytorch/attention/test_attention_backend_selection.py b/tests/pytorch/attention/test_attention_backend_selection.py index 323b8f66364..ecb029ce2cc 100644 --- a/tests/pytorch/attention/test_attention_backend_selection.py +++ b/tests/pytorch/attention/test_attention_backend_selection.py @@ -213,8 +213,6 @@ def _fa4_normalized_kwargs(kwargs): "sent,expected", [ ({"window_size": (-1, 0)}, {"window_size": (None, 0)}), - ({"window_size": (-1, -1)}, {"window_size": (None, None)}), - ({"window_size": (511, 0)}, {"window_size": (511, 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)}), @@ -222,10 +220,6 @@ def _fa4_normalized_kwargs(kwargs): {"window_size_left": -1, "window_size_right": 0}, {"window_size_left": None, "window_size_right": 0}, ), - ( - {"window_size_left": -1, "window_size_right": -1}, - {"window_size_left": None, "window_size_right": None}, - ), ( {"window_size_left": 0, "window_size_right": -1}, {"window_size_left": 0, "window_size_right": None}, @@ -234,15 +228,42 @@ def _fa4_normalized_kwargs(kwargs): {"window_size_left": 7, "window_size_right": -8}, {"window_size_left": 7, "window_size_right": -8}, ), - ( - {"window_size_left": 256, "window_size_right": 0}, - {"window_size_left": 256, "window_size_right": 0}, - ), - ({"window_size": (None, None)}, {"window_size": (None, None)}), - ({"window_size": None}, {"window_size": None}), - ({}, {}), ], ) def test_fa4_window_sentinel_normalization(sent, expected): """Convert only TE's -1 sentinel for both FA4 window argument forms.""" assert _fa4_normalized_kwargs(sent) == expected + + +def test_fa4_causal_attention_matches_reference(monkeypatch): + """Compare selected FA4 causal attention with an independent float64 reference.""" + if not torch.cuda.is_available(): + pytest.skip("Requires CUDA") + if dpa_backends.flash_attn_func_v4 is None: + pytest.skip("Requires FlashAttention 4") + if torch.cuda.get_device_capability() != (10, 0): + pytest.skip("The FA4 CuTe kernels under test are SM100") + + monkeypatch.setenv("NVTE_UNFUSED_ATTN", "0") + dpa_module._attention_backends["backend_selection_requires_update"] = True + b, h, s, d = 2, 8, 1024, 128 + dtype = torch.bfloat16 + torch.manual_seed(0) + q, k, v = (torch.randn(b, s, h, d, device="cuda", dtype=dtype) for _ in range(3)) + dpa = DotProductAttention( + h, d, qkv_format="bshd", attn_mask_type="causal", attention_dropout=0.0 + ).to(dtype=dtype, device="cuda") + out = dpa(q, k, v).view(b, s, h, d) + + selected = dpa_module._attention_backends["flash_attention_backend"] + assert selected is not None and str(selected).startswith( + "4" + ), f"expected FlashAttention 4 to serve this config, got {selected}" + qs, ks, vs = (t.double().transpose(1, 2) for t in (q, k, v)) + scores = (qs @ ks.transpose(-1, -2)) * (d**-0.5) + scores = scores.masked_fill( + torch.ones(s, s, dtype=torch.bool, device=qs.device).triu(1), float("-inf") + ) + reference = (torch.softmax(scores, dim=-1) @ vs).transpose(1, 2) + error = (out.double() - reference).abs().max() / reference.abs().max() + assert error < 2e-2, f"FA4 causal attention differs from the float64 reference: {error:.3e}" From 5dc3806cd90b8de242a884ff6f0e5948cc8b3224 Mon Sep 17 00:00:00 2001 From: Sudhakar Singh Date: Fri, 9 Oct 2026 11:07:19 -0700 Subject: [PATCH 07/10] Update FA4 L3 dependency and backend coverage CUTLASS DSL 4.8.0 recognizes SM107 while the previous pin does not, so keep the FA4 L3 dependency and installation guidance aligned. Running the small backend-selection module directly covers its eligibility and window-sentinel cases without a bespoke node list. Clarify that non-all-gather THD metadata depends on pad_between_seqs. Signed-off-by: Sudhakar Singh --- qa/L3_pytorch_FA_versions_test/test.sh | 11 +++++------ .../pytorch/attention/dot_product_attention/utils.py | 5 +++-- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/qa/L3_pytorch_FA_versions_test/test.sh b/qa/L3_pytorch_FA_versions_test/test.sh index 23c660eeeaf..266abff774d 100644 --- a/qa/L3_pytorch_FA_versions_test/test.sh +++ b/qa/L3_pytorch_FA_versions_test/test.sh @@ -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 b33 test pin needs - # CUTLASS DSL 4.7.1, 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.7.1 \ + 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 @@ -139,9 +139,8 @@ do 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_fa4_window_sentinel_normalization" \ - "$TE_PATH/tests/pytorch/attention/test_attention_backend_selection.py::test_fa4_causal_attention_matches_reference" \ - || test_fail "FA4 window sentinel tests (FA $fa_version)" + "$TE_PATH/tests/pytorch/attention/test_attention_backend_selection.py" \ + || test_fail "FA4 backend-selection tests (FA $fa_version)" fi done diff --git a/transformer_engine/pytorch/attention/dot_product_attention/utils.py b/transformer_engine/pytorch/attention/dot_product_attention/utils.py index 6a87bdad59c..a773091cd4e 100644 --- a/transformer_engine/pytorch/attention/dot_product_attention/utils.py +++ b/transformer_engine/pytorch/attention/dot_product_attention/utils.py @@ -154,7 +154,7 @@ class FlashAttentionUtils: # 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.0b33 nvidia-cutlass-dsl[cu13]==4.7.1""" +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. @@ -1289,7 +1289,8 @@ def _is_fa3_supported(num_heads, num_gqa_groups, head_dim_qk, head_dim_v, qkv_dt ) 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 for padding. + # 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") ) From 3900799029b059bae385e313540c75c41cc7e8f0 Mon Sep 17 00:00:00 2001 From: Sudhakar Singh Date: Fri, 9 Oct 2026 11:07:26 -0700 Subject: [PATCH 08/10] Keep FA4 regression tests focused on model configs A dedicated D=256 model preserves separate QK and V dimensions without a one-off runner override. Exclude it from the broad CP matrix because the no-load-balance test already exercises the intended path. The L3 causal cross-backend cases cover numerical behavior, so retain the sentinel unit test and remove the redundant standalone reference test. Signed-off-by: Sudhakar Singh --- .../attention/run_attention_with_cp.py | 3 - .../test_attention_backend_selection.py | 58 ++++--------------- .../attention/test_attention_with_cp.py | 20 +++---- 3 files changed, 22 insertions(+), 59 deletions(-) diff --git a/tests/pytorch/attention/run_attention_with_cp.py b/tests/pytorch/attention/run_attention_with_cp.py index a594c28b251..0d2a142dbc1 100644 --- a/tests/pytorch/attention/run_attention_with_cp.py +++ b/tests/pytorch/attention/run_attention_with_cp.py @@ -237,7 +237,6 @@ def run_dpa_with_cp( fa_pad_between_seqs="False", deterministic="False", load_balancing_strategy="DUAL_CHUNK_SWAP", - head_dim=None, softcap="0.0", log_level=logging.WARNING, ): @@ -277,8 +276,6 @@ def run_dpa_with_cp( config = copy.deepcopy(model_configs_fused_attn[model]) else: assert False, f"{model=} is not a known FusedAttention CP config!" - if head_dim is not None: - config.head_dim_qk = config.head_dim_v = int(head_dim) assert config.attn_mask_type in [ "causal", "no_mask", diff --git a/tests/pytorch/attention/test_attention_backend_selection.py b/tests/pytorch/attention/test_attention_backend_selection.py index ecb029ce2cc..bd587416a79 100644 --- a/tests/pytorch/attention/test_attention_backend_selection.py +++ b/tests/pytorch/attention/test_attention_backend_selection.py @@ -43,20 +43,20 @@ def isolated_backends(monkeypatch): @pytest.mark.parametrize( - "capability,training,backward,deterministic,head_dim,unfused,expect_flash", + "capability,training,backward,deterministic,head_dims,unfused,expect_flash", [ - pytest.param((12, 0), True, True, True, 128, True, False, id="sm120-training"), - pytest.param((12, 0), False, True, True, 128, True, False, id="sm120-eval-backward"), - pytest.param((12, 1), False, True, True, 128, True, False, id="sm121-eval-backward"), - pytest.param((12, 0), False, False, True, 128, True, True, id="forward-only"), - pytest.param((12, 0), True, True, False, 128, True, True, id="nondeterministic"), - pytest.param((12, 0), True, True, True, 128, False, False, id="no-fallback"), - pytest.param((10, 0), True, True, True, 128, True, True, id="sm100-d128"), - pytest.param((10, 0), True, True, True, 256, True, False, id="sm100-d256"), + 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, head_dim, 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) @@ -68,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=head_dim, - head_dim_v=head_dim, + head_dim_qk=head_dims[0], + head_dim_v=head_dims[1], attn_mask_type="causal", window_size=(-1, 0), deterministic=deterministic, @@ -233,37 +233,3 @@ def _fa4_normalized_kwargs(kwargs): def test_fa4_window_sentinel_normalization(sent, expected): """Convert only TE's -1 sentinel for both FA4 window argument forms.""" assert _fa4_normalized_kwargs(sent) == expected - - -def test_fa4_causal_attention_matches_reference(monkeypatch): - """Compare selected FA4 causal attention with an independent float64 reference.""" - if not torch.cuda.is_available(): - pytest.skip("Requires CUDA") - if dpa_backends.flash_attn_func_v4 is None: - pytest.skip("Requires FlashAttention 4") - if torch.cuda.get_device_capability() != (10, 0): - pytest.skip("The FA4 CuTe kernels under test are SM100") - - monkeypatch.setenv("NVTE_UNFUSED_ATTN", "0") - dpa_module._attention_backends["backend_selection_requires_update"] = True - b, h, s, d = 2, 8, 1024, 128 - dtype = torch.bfloat16 - torch.manual_seed(0) - q, k, v = (torch.randn(b, s, h, d, device="cuda", dtype=dtype) for _ in range(3)) - dpa = DotProductAttention( - h, d, qkv_format="bshd", attn_mask_type="causal", attention_dropout=0.0 - ).to(dtype=dtype, device="cuda") - out = dpa(q, k, v).view(b, s, h, d) - - selected = dpa_module._attention_backends["flash_attention_backend"] - assert selected is not None and str(selected).startswith( - "4" - ), f"expected FlashAttention 4 to serve this config, got {selected}" - qs, ks, vs = (t.double().transpose(1, 2) for t in (q, k, v)) - scores = (qs @ ks.transpose(-1, -2)) * (d**-0.5) - scores = scores.masked_fill( - torch.ones(s, s, dtype=torch.bool, device=qs.device).triu(1), float("-inf") - ) - reference = (torch.softmax(scores, dim=-1) @ vs).transpose(1, 2) - error = (out.double() - reference).abs().max() / reference.abs().max() - assert error < 2e-2, f"FA4 causal attention differs from the float64 reference: {error:.3e}" diff --git a/tests/pytorch/attention/test_attention_with_cp.py b/tests/pytorch/attention/test_attention_with_cp.py index 6276417eab1..c1e953da23d 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( @@ -320,7 +321,7 @@ def _submit(pool: PoolWorker, **kwargs) -> None: qkv_formats = ["bshd", "sbhd", "thd"] cp_comm_types = ["p2p", "all_gather", "a2a", "a2a+p2p"] if test_essential: - configs = ["cp_2_0", "cp_2_2", "cp_3_0", "cp_3_3"] + configs = ["cp_2_0", "cp_2_2", "cp_2_4", "cp_3_0", "cp_3_3"] model_configs_flash_attn = {k: model_configs_flash_attn[k] for k in configs} dtypes = ["bf16"] qkv_formats = ["sbhd", "thd"] @@ -336,7 +337,8 @@ 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()) +# The D=256 model is covered by the focused no-load-balance test, not this broad matrix. +@pytest.mark.parametrize("model", [m for m in model_configs_flash_attn if m != "cp_2_4"]) @pytest.mark.parametrize("qkv_format", qkv_formats) @pytest.mark.parametrize("cp_comm_type", cp_comm_types) @pytest.mark.parametrize("pad_between_seqs", [False, True]) @@ -779,10 +781,11 @@ def test_cp_with_fused_attention_no_load_balance(cp_pool): ) -@pytest.mark.parametrize("head_dim", (128, 256)) -def test_cp_with_flash_attention_no_load_balance(cp_pool, head_dim): +@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.""" - if head_dim == 256 and ( + config = copy.deepcopy(model_configs_flash_attn[model]) + if config.head_dim_qk == 256 and ( not (10, 0) <= get_device_compute_capability() < (12, 0) or not fa4_enabled or not FlashAttentionUtils.v4_is_installed @@ -790,8 +793,6 @@ def test_cp_with_flash_attention_no_load_balance(cp_pool, head_dim): or _deterministic ): pytest.skip("D=256 THD all-gather requires SM100/SM110 FA4 b33+ non-deterministic.") - config = copy.deepcopy(model_configs_flash_attn["cp_2_0"]) - config.head_dim_qk = config.head_dim_v = head_dim config.context_parallel = True config.cp_comm_type = "all_gather" config.attn_mask_type = "padding_causal" @@ -803,15 +804,14 @@ def test_cp_with_flash_attention_no_load_balance(cp_pool, head_dim): is_training=True, deterministic=_deterministic, ) - if head_dim == 256: + if config.head_dim_qk == 256: assert available_backends[0] and flash_backend is not None and flash_backend.major == 4 elif not available_backends[0]: pytest.skip("FlashAttention is unavailable.") _submit( cp_pool(2), dtype="bf16", - model="cp_2_0", - head_dim=head_dim, + model=model, qkv_format="thd", kernel_backend="FlashAttention", cp_comm_type="all_gather", From f52353f3f1f0e97739ed3856716c5ef48314e051 Mon Sep 17 00:00:00 2001 From: Sudhakar Singh Date: Fri, 9 Oct 2026 13:48:12 -0700 Subject: [PATCH 09/10] Keep FA4 expectation explicit in CP test Query backend availability before deciding whether to skip the D=256 case. Supported FA4 b33 configurations should fail when FA4 is unexpectedly unavailable, while unsupported configurations still skip. Keep the general no-Flash skip separate from the D=256 assertion. Signed-off-by: Sudhakar Singh --- .../attention/test_attention_with_cp.py | 22 ++++++++++--------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/tests/pytorch/attention/test_attention_with_cp.py b/tests/pytorch/attention/test_attention_with_cp.py index c1e953da23d..7b0c4644148 100644 --- a/tests/pytorch/attention/test_attention_with_cp.py +++ b/tests/pytorch/attention/test_attention_with_cp.py @@ -785,14 +785,14 @@ def test_cp_with_fused_attention_no_load_balance(cp_pool): 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[model]) - if config.head_dim_qk == 256 and ( - not (10, 0) <= get_device_compute_capability() < (12, 0) - or not fa4_enabled - or not FlashAttentionUtils.v4_is_installed - or FlashAttentionUtils.fa4_version < FlashAttentionUtils.v4_0_0_beta33 - or _deterministic - ): - pytest.skip("D=256 THD all-gather requires SM100/SM110 FA4 b33+ non-deterministic.") + 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" @@ -804,9 +804,11 @@ def test_cp_with_flash_attention_no_load_balance(cp_pool, model): is_training=True, deterministic=_deterministic, ) - if config.head_dim_qk == 256: + if fa4_expected: assert available_backends[0] and flash_backend is not None and flash_backend.major == 4 - elif not available_backends[0]: + 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), From 88b294b280cc24c009cf2d89de75bf551c69626c Mon Sep 17 00:00:00 2001 From: Sudhakar Singh Date: Fri, 9 Oct 2026 14:12:10 -0700 Subject: [PATCH 10/10] Keep full CP model catalogs for focused tests The earlier D=256 broad-matrix exclusion kept cp_2_4 in the essential FlashAttention catalog solely for the focused no-load-balance case. That mixes model availability with test selection. Keep the full FlashAttention and FusedAttention catalogs available to the runner and focused tests, and narrow only the essential broad CP parametrizations. Non-essential broad runs continue to use the full catalog. Signed-off-by: Sudhakar Singh --- tests/pytorch/attention/test_attention_with_cp.py | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/tests/pytorch/attention/test_attention_with_cp.py b/tests/pytorch/attention/test_attention_with_cp.py index 7b0c4644148..64158556cc7 100644 --- a/tests/pytorch/attention/test_attention_with_cp.py +++ b/tests/pytorch/attention/test_attention_with_cp.py @@ -320,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_2_4", "cp_3_0", "cp_3_3"] - model_configs_flash_attn = {k: model_configs_flash_attn[k] for k in configs} + configs = ["cp_2_0", "cp_2_2", "cp_3_0", "cp_3_3"] + essential_model_configs_flash_attn = {k: model_configs_flash_attn[k] for k in configs} dtypes = ["bf16"] qkv_formats = ["sbhd", "thd"] @@ -337,8 +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) -# The D=256 model is covered by the focused no-load-balance test, not this broad matrix. -@pytest.mark.parametrize("model", [m for m in model_configs_flash_attn if m != "cp_2_4"]) +@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]) @@ -554,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", @@ -569,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])