From b1193adad2d90d14a3deb2d346b1e7cf48ecf31c Mon Sep 17 00:00:00 2001 From: Kshitij Lakhani Date: Tue, 20 Oct 2026 19:17:31 -0700 Subject: [PATCH 1/5] Enable explicit SM121 builds with CUDA 12.9 or newer Signed-off-by: Kshitij Lakhani --- transformer_engine/common/CMakeLists.txt | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/transformer_engine/common/CMakeLists.txt b/transformer_engine/common/CMakeLists.txt index 26bd44c015..2ae66c6b19 100644 --- a/transformer_engine/common/CMakeLists.txt +++ b/transformer_engine/common/CMakeLists.txt @@ -147,6 +147,17 @@ if(NOT arch_120_index EQUAL -1) endif() endif() +# Check for architecture 121 +list(FIND CMAKE_CUDA_ARCHITECTURES "121" arch_121_index) +if(NOT arch_121_index EQUAL -1) + if(CUDAToolkit_VERSION VERSION_LESS 12.9) + message(FATAL_ERROR "CUDA 12.9+ is required for SM121, but found CUDA ${CUDAToolkit_VERSION}") + endif() + list(REMOVE_ITEM CMAKE_CUDA_ARCHITECTURES "121") + list(APPEND NVTE_GENERIC_ARCHS "121") + list(APPEND NVTE_SPECIFIC_ARCHS "121f") +endif() + # Move remaining standard (pre-Blackwell) architectures into NVTE_STANDARD_ARCHS. # These are applied to all CUDA sources (both generic and arch-specific). set(NVTE_STANDARD_ARCHS ${CMAKE_CUDA_ARCHITECTURES}) From b4e630ed0429c4ea177567cd0b4f41a33bbe9ba6 Mon Sep 17 00:00:00 2001 From: Kshitij Lakhani Date: Tue, 20 Oct 2026 19:46:45 -0700 Subject: [PATCH 2/5] Guard SM12x FA4 variable-length grouped-query backward Avoid incorrect K/V gradients until the upstream fix is qualified. Signed-off-by: Kshitij Lakhani --- .../test_attention_backend_selection.py | 49 +++++++++++++++++++ .../attention/dot_product_attention/utils.py | 14 ++++++ 2 files changed, 63 insertions(+) diff --git a/tests/pytorch/attention/test_attention_backend_selection.py b/tests/pytorch/attention/test_attention_backend_selection.py index 66e1ff7c1c..6106d9f1b9 100644 --- a/tests/pytorch/attention/test_attention_backend_selection.py +++ b/tests/pytorch/attention/test_attention_backend_selection.py @@ -261,6 +261,55 @@ def test_fa4_d256_seqused_backend_selection(monkeypatch, version, backward, expe assert bool(available[0]) is expected +@pytest.mark.parametrize( + "capability,layout,mask,padded,backward,kv_heads,cp,expected", + [ + pytest.param((12, 0), "thd", "padding", False, True, 4, False, False, id="compact-gqa"), + pytest.param((12, 0), "thd", "padding", True, True, 4, False, False, id="padded-gqa"), + pytest.param((12, 1), "thd", "padding", False, True, 1, False, False, id="sm121-mqa"), + pytest.param((12, 0), "bshd", "padding", False, True, 4, False, False, id="bshd-varlen"), + pytest.param((12, 0), "thd", "padding", True, False, 4, False, True, id="forward-only"), + pytest.param((12, 0), "thd", "padding", True, True, 8, False, True, id="mha"), + pytest.param((12, 0), "bshd", "causal", False, True, 4, False, True, id="fixed-length"), + pytest.param((12, 0), "bshd", "causal", False, True, 4, True, True, id="fixed-length-cp"), + pytest.param((10, 0), "thd", "padding", True, True, 4, False, True, id="sm100"), + ], +) +def test_fa4_sm12x_varlen_gqa_backend_selection( + monkeypatch, capability, layout, mask, padded, backward, kv_heads, cp, expected +): + """Reject only FA4 varlen grouped-query backward on SM12x.""" + monkeypatch.setattr(dpa_utils, "get_device_compute_capability", lambda device: capability) + monkeypatch.setattr(dpa_utils, "get_cudnn_version", lambda: (9, 29, 0)) + monkeypatch.setattr(dpa_utils.FlashAttentionUtils, "v4_is_installed", True) + monkeypatch.setattr(dpa_utils.FlashAttentionUtils, "fa4_version", PkgVersion("4.0.0b33")) + 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="_".join([layout] * 3), + batch_size=2, + num_heads=8, + num_gqa_groups=kv_heads, + head_dim_qk=64, + head_dim_v=64, + max_seqlen_q=32, + max_seqlen_kv=32, + num_tokens_q=48, + num_tokens_kv=48, + attn_mask_type=mask, + pad_between_seqs=padded, + context_parallel=cp, + cp_size=2 if cp else 1, + deterministic=False, + is_training=False, + requires_backward=backward, + ) + flash, _, _, _, _, available = dpa_utils.get_attention_backend(params) + assert bool(flash) is expected + 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/transformer_engine/pytorch/attention/dot_product_attention/utils.py b/transformer_engine/pytorch/attention/dot_product_attention/utils.py index c80795f7f1..4d88f2f1dc 100644 --- a/transformer_engine/pytorch/attention/dot_product_attention/utils.py +++ b/transformer_engine/pytorch/attention/dot_product_attention/utils.py @@ -1194,6 +1194,20 @@ def _is_fa3_supported(num_heads, num_gqa_groups, head_dim_qk, head_dim_v, qkv_dt use_flash_attention_4 = False # Filter: QKV layout + # FA4's SM12x varlen backward can write grouped K/V gradients at the wrong offsets. + # TODO(KshitijLakhani): Requalify FA4 with the fix in flash-attention PR #2814. + if ( + is_sm12x + and use_flash_attention_4 + and FlashAttentionUtils.v4_is_installed + and attention_params.requires_backward + and num_heads != num_gqa_groups + and ( + "thd" in (q_format, kv_format) or ("padding" in attn_mask_type and not context_parallel) + ) + ): + logger.debug("Disabling FlashAttention 4 varlen GQA/MQA backward on SM12x") + use_flash_attention_4 = False if "thd" in (q_format, kv_format): if pad_between_seqs: if ( # pylint: disable=too-many-boolean-expressions From f36b36b363b56ac90a8b674d119d42fdf4a21999 Mon Sep 17 00:00:00 2001 From: Kshitij Lakhani Date: Thu, 3 Dec 2026 17:48:31 -0800 Subject: [PATCH 3/5] Enable non-TN per-tensor FP8 GEMM on SM120 with cuBLASLt 13.6 Keep the transposed representation on older runtimes and share the capability check with PyTorch. Signed-off-by: Kshitij Lakhani --- tests/pytorch/test_sanity.py | 44 +++++++++++++++++++ .../common/transformer_engine.cpp | 10 +++-- .../pytorch/csrc/extensions/pybind.cpp | 4 ++ transformer_engine/pytorch/utils.py | 11 +++-- 4 files changed, 59 insertions(+), 10 deletions(-) diff --git a/tests/pytorch/test_sanity.py b/tests/pytorch/test_sanity.py index 048a966aa1..8c838a001a 100644 --- a/tests/pytorch/test_sanity.py +++ b/tests/pytorch/test_sanity.py @@ -14,6 +14,7 @@ from transformer_engine.pytorch.quantization import FP8GlobalStateManager from transformer_engine.pytorch.utils import ( init_method_normal, + is_non_tn_fp8_gemm_supported, scaled_init_method_normal, ) from transformer_engine.pytorch import ( @@ -1325,6 +1326,49 @@ def test_sanity_fp8_gemm_with_unalignment(N, datatype): torch.cuda.synchronize() +@pytest.mark.skipif(not fp8_available, reason=reason_for_no_fp8) +@pytest.mark.parametrize( + "layout,a_usage,b_usage", + [ + ("TN", "rowwise", "rowwise"), + ("NN", "rowwise", "rowwise"), + ("NT", "rowwise", "rowwise"), + ("NN", "columnwise", "rowwise"), + ("NT", "rowwise", "columnwise"), + ], +) +def test_fp8_non_tn_gemm_storage_layouts(layout, a_usage, b_usage): + if not is_non_tn_fp8_gemm_supported(): + pytest.skip("Non-TN per-tensor FP8 GEMM is unsupported") + + m, n, k = 32, 48, 64 + a_shape = (n, k) if layout[0] == "T" else (k, n) + b_shape = (k, m) if layout[1] == "T" else (m, k) + a = torch.randn(a_shape, device="cuda", dtype=torch.bfloat16) + b = torch.randn(b_shape, device="cuda", dtype=torch.bfloat16) + + def quantize(x, usage): + quantizer = Float8CurrentScalingQuantizer( + te.DType.kFloat8E4M3, + device="cuda", + rowwise=usage == "rowwise", + columnwise=usage == "columnwise", + ) + return quantizer(x) + + a_fp8 = quantize(a, a_usage) + b_fp8 = quantize(b, b_usage) + actual, *_ = general_gemm(a_fp8, b_fp8, torch.float32, layout=layout) + a_ref = a_fp8.dequantize().float() + b_ref = b_fp8.dequantize().float() + if layout[0] == "T": + a_ref = a_ref.T + if layout[1] == "T": + b_ref = b_ref.T + # Match the existing per-tensor FP8 GEMM numerical tolerance. + torch.testing.assert_close(actual, b_ref @ a_ref, rtol=0.125, atol=0.0675) + + @pytest.mark.skipif(not fp8_available, reason=reason_for_no_fp8) def test_replace_raw_data_for_float8tensor(): """Test the functionality of replace_raw_data""" diff --git a/transformer_engine/common/transformer_engine.cpp b/transformer_engine/common/transformer_engine.cpp index b46851b27c..357a36d184 100644 --- a/transformer_engine/common/transformer_engine.cpp +++ b/transformer_engine/common/transformer_engine.cpp @@ -1263,10 +1263,12 @@ int nvte_is_non_tn_fp8_gemm_supported() { int device_id = transformer_engine::cuda::current_device(); std::call_once(flags[device_id], [&]() { int deviceComputeCapability = transformer_engine::cuda::sm_arch(device_id); - // Note: this is temporary restriction and should be lifted in the future. - // (remove the note once it's done.) - cache[device_id] = (deviceComputeCapability >= 100 && deviceComputeCapability < 120) || - deviceComputeCapability >= 130; + // SM120 needs cuBLASLt 13.6+ for all ordinary per-tensor FP8 training layouts. + // TODO(klakhani): Validate direct per-tensor FP8 NN/NT on SM121 before skipping its transpose. + cache[device_id] = + (deviceComputeCapability >= 100 && deviceComputeCapability < 120) || + deviceComputeCapability >= 130 || + (deviceComputeCapability == 120 && transformer_engine::cuda::cublas_version() >= 130600); }); return cache[device_id]; } diff --git a/transformer_engine/pytorch/csrc/extensions/pybind.cpp b/transformer_engine/pytorch/csrc/extensions/pybind.cpp index 82fa3ec242..9ecdb9397a 100644 --- a/transformer_engine/pytorch/csrc/extensions/pybind.cpp +++ b/transformer_engine/pytorch/csrc/extensions/pybind.cpp @@ -655,6 +655,10 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { py::arg("grad_input") = std::nullopt); // Misc + m.def( + "is_non_tn_fp8_gemm_supported", []() { return nvte_is_non_tn_fp8_gemm_supported() != 0; }, + "Check ordinary per-tensor FP8 layout support for the current device and cuBLASLt", + py::call_guard()); m.def("get_cublasLt_version", &transformer_engine::pytorch::get_cublasLt_version, "Get cublasLt version", py::call_guard()); m.def("get_cublasLt_build_version", &nvte_get_cublaslt_build_version, diff --git a/transformer_engine/pytorch/utils.py b/transformer_engine/pytorch/utils.py index 1a19476dac..8ac4ef7349 100644 --- a/transformer_engine/pytorch/utils.py +++ b/transformer_engine/pytorch/utils.py @@ -729,13 +729,12 @@ def is_bf16_available(return_reason: bool = False) -> Union[bool, Tuple[bool, st return available, reason -@functools.lru_cache(maxsize=None) +@torch.compiler.assume_constant_result def is_non_tn_fp8_gemm_supported() -> bool: - """Checks whether the device supports - non-TN layouts for FP8 GEMMs. - """ - device_capability = torch.cuda.get_device_capability() - return (10, 0) <= device_capability < (12, 0) or device_capability >= (13, 0) + """Check ordinary per-tensor FP8 layouts using common's device/library policy.""" + import transformer_engine_torch as tex + + return tex.is_non_tn_fp8_gemm_supported() @functools.lru_cache(maxsize=None) From 37cd4a1f803146b01a4f684752f4fa9a3896eab4 Mon Sep 17 00:00:00 2001 From: Kshitij Lakhani Date: Thu, 3 Dec 2026 17:48:31 -0800 Subject: [PATCH 4/5] Enable MXFP8 training GEMMs on SM120 and SM121 with cuBLASLt 13.6 Keep FP8 current scaling as the default and reject explicit MXFP8 on older runtimes. Signed-off-by: Kshitij Lakhani --- transformer_engine/pytorch/quantization.py | 35 ++++++++++++++++------ 1 file changed, 26 insertions(+), 9 deletions(-) diff --git a/transformer_engine/pytorch/quantization.py b/transformer_engine/pytorch/quantization.py index 1ee441bbe6..53e9a126ce 100644 --- a/transformer_engine/pytorch/quantization.py +++ b/transformer_engine/pytorch/quantization.py @@ -166,10 +166,22 @@ def _compute_fp8_support() -> Tuple[bool, str]: def _compute_mxfp8_support() -> Tuple[bool, str]: - """Return if fp8 support is available""" - if get_device_compute_capability() >= (12, 0): - return False, "MXFP8 (for all gemm layouts) is not supported on 12.0+ architectures yet." - if get_device_compute_capability() >= (10, 0): # blackwell and above + """Check the device and runtime requirements for the MXFP8BlockScaling recipe.""" + capability = get_device_compute_capability() + if capability in ((12, 0), (12, 1)): + version = tex.get_cublasLt_version() + if version >= 130600: + return True, "" + return ( + False, + ( + "MXFP8 TN/NN/NT GEMMs on SM120/SM121 require cuBLASLt 13.6 or newer " + f"(loaded version: {version}). Upgrade cuBLASLt or use Float8CurrentScaling." + ), + ) + if capability >= (12, 0): + return False, "MXFP8 is not supported on this compute capability yet." + if capability >= (10, 0): # blackwell and above return True, "" return False, "Device compute capability 10.0 or higher required for MXFP8 execution." @@ -211,7 +223,7 @@ def check_fp8_support() -> Tuple[bool, str]: @torch.compiler.assume_constant_result def check_mxfp8_support() -> Tuple[bool, str]: - """Return if MXFP8 support is available.""" + """Return MXFP8BlockScaling recipe availability and a reason if unavailable.""" global _MXFP8_SUPPORT if _MXFP8_SUPPORT is None: _MXFP8_SUPPORT = _compute_mxfp8_support() @@ -311,11 +323,13 @@ def get_default_fp8_recipe() -> Recipe: "their construction is not traceable. " "Pass an explicit recipe to te.autocast() instead." ) - if check_mxfp8_support()[0]: - return MXFP8BlockScaling() if get_device_compute_capability() >= (12, 0): - # This is a temporary restriction until MXFP8 is supported for all gemm layouts. + # Keep the established SM12x default separate from MXFP8 availability. + # TODO: Evaluate making MXFP8BlockScaling the default on supported SM12x + # systems, as on other MXFP8-capable architectures. return Float8CurrentScaling() + if check_mxfp8_support()[0]: + return MXFP8BlockScaling() return DelayedScaling() @@ -398,7 +412,10 @@ def is_fp8_available(return_reason: bool = False) -> Union[bool, Tuple[bool, str def is_mxfp8_available(return_reason: bool = False) -> Union[bool, Tuple[bool, str]]: """ - Determine if support is available for the MXFP8 recipe. + Determine whether the ``MXFP8BlockScaling`` recipe is available. + + This check is based on support for the TN, NN, and NT GEMMs used in training. + Native GPU-offset grouped GEMM has separate requirements. Parameters ---------- From 050ea59ed26c9464394bee914a011984a895da41 Mon Sep 17 00:00:00 2001 From: Kshitij Lakhani Date: Fri, 4 Dec 2026 10:47:38 -0800 Subject: [PATCH 5/5] Fix SM12x FP8 regression reference and lint Use deterministic operands and an FP32-dequantized reference for the ordinary FP8 layout test. Keep the MXFP8 default TODO with a line-scoped pylint suppression and simplify the FA4 variable-length guard. Signed-off-by: Kshitij Lakhani --- tests/pytorch/test_sanity.py | 12 +++++++----- .../attention/dot_product_attention/utils.py | 17 ++++++++++------- transformer_engine/pytorch/quantization.py | 1 + 3 files changed, 18 insertions(+), 12 deletions(-) diff --git a/tests/pytorch/test_sanity.py b/tests/pytorch/test_sanity.py index 8c838a001a..288adae74d 100644 --- a/tests/pytorch/test_sanity.py +++ b/tests/pytorch/test_sanity.py @@ -1341,11 +1341,12 @@ def test_fp8_non_tn_gemm_storage_layouts(layout, a_usage, b_usage): if not is_non_tn_fp8_gemm_supported(): pytest.skip("Non-TN per-tensor FP8 GEMM is unsupported") + generator = torch.Generator(device="cuda").manual_seed(87) m, n, k = 32, 48, 64 a_shape = (n, k) if layout[0] == "T" else (k, n) b_shape = (k, m) if layout[1] == "T" else (m, k) - a = torch.randn(a_shape, device="cuda", dtype=torch.bfloat16) - b = torch.randn(b_shape, device="cuda", dtype=torch.bfloat16) + a = torch.randn(a_shape, device="cuda", dtype=torch.bfloat16, generator=generator) + b = torch.randn(b_shape, device="cuda", dtype=torch.bfloat16, generator=generator) def quantize(x, usage): quantizer = Float8CurrentScalingQuantizer( @@ -1359,14 +1360,15 @@ def quantize(x, usage): a_fp8 = quantize(a, a_usage) b_fp8 = quantize(b, b_usage) actual, *_ = general_gemm(a_fp8, b_fp8, torch.float32, layout=layout) - a_ref = a_fp8.dequantize().float() - b_ref = b_fp8.dequantize().float() + # Decode in FP32 and use FP64 matmul to avoid BF16 rounding and TF32. + a_ref = a_fp8.dequantize(dtype=torch.float32).double() + b_ref = b_fp8.dequantize(dtype=torch.float32).double() if layout[0] == "T": a_ref = a_ref.T if layout[1] == "T": b_ref = b_ref.T # Match the existing per-tensor FP8 GEMM numerical tolerance. - torch.testing.assert_close(actual, b_ref @ a_ref, rtol=0.125, atol=0.0675) + torch.testing.assert_close(actual, (b_ref @ a_ref).float(), rtol=0.125, atol=0.0675) @pytest.mark.skipif(not fp8_available, reason=reason_for_no_fp8) diff --git a/transformer_engine/pytorch/attention/dot_product_attention/utils.py b/transformer_engine/pytorch/attention/dot_product_attention/utils.py index 4d88f2f1dc..f6ae6d42e3 100644 --- a/transformer_engine/pytorch/attention/dot_product_attention/utils.py +++ b/transformer_engine/pytorch/attention/dot_product_attention/utils.py @@ -1196,18 +1196,21 @@ def _is_fa3_supported(num_heads, num_gqa_groups, head_dim_qk, head_dim_v, qkv_dt # Filter: QKV layout # FA4's SM12x varlen backward can write grouped K/V gradients at the wrong offsets. # TODO(KshitijLakhani): Requalify FA4 with the fix in flash-attention PR #2814. + requires_grouped_query_backward = ( + attention_params.requires_backward and num_heads != num_gqa_groups + ) if ( is_sm12x and use_flash_attention_4 and FlashAttentionUtils.v4_is_installed - and attention_params.requires_backward - and num_heads != num_gqa_groups - and ( - "thd" in (q_format, kv_format) or ("padding" in attn_mask_type and not context_parallel) - ) + and requires_grouped_query_backward ): - logger.debug("Disabling FlashAttention 4 varlen GQA/MQA backward on SM12x") - use_flash_attention_4 = False + uses_varlen = "thd" in (q_format, kv_format) or ( + "padding" in attn_mask_type and not context_parallel + ) + if uses_varlen: + logger.debug("Disabling FlashAttention 4 varlen GQA/MQA backward on SM12x") + use_flash_attention_4 = False if "thd" in (q_format, kv_format): if pad_between_seqs: if ( # pylint: disable=too-many-boolean-expressions diff --git a/transformer_engine/pytorch/quantization.py b/transformer_engine/pytorch/quantization.py index 53e9a126ce..4898eb94ae 100644 --- a/transformer_engine/pytorch/quantization.py +++ b/transformer_engine/pytorch/quantization.py @@ -325,6 +325,7 @@ def get_default_fp8_recipe() -> Recipe: ) if get_device_compute_capability() >= (12, 0): # Keep the established SM12x default separate from MXFP8 availability. + # pylint: disable-next=fixme # TODO: Evaluate making MXFP8BlockScaling the default on supported SM12x # systems, as on other MXFP8-capable architectures. return Float8CurrentScaling()