Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions tests/pytorch/attention/test_attention_backend_selection.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]))
Expand Down
46 changes: 46 additions & 0 deletions tests/pytorch/test_sanity.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -1325,6 +1326,51 @@ 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")

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, generator=generator)
b = torch.randn(b_shape, device="cuda", dtype=torch.bfloat16, generator=generator)

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)
# 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).float(), 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"""
Expand Down
11 changes: 11 additions & 0 deletions transformer_engine/common/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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})
Expand Down
10 changes: 6 additions & 4 deletions transformer_engine/common/transformer_engine.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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];
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1194,6 +1194,23 @@ 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.
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 requires_grouped_query_backward
):
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
Expand Down
4 changes: 4 additions & 0 deletions transformer_engine/pytorch/csrc/extensions/pybind.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<py::gil_scoped_release>());
m.def("get_cublasLt_version", &transformer_engine::pytorch::get_cublasLt_version,
"Get cublasLt version", py::call_guard<py::gil_scoped_release>());
m.def("get_cublasLt_build_version", &nvte_get_cublaslt_build_version,
Expand Down
36 changes: 27 additions & 9 deletions transformer_engine/pytorch/quantization.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."

Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -311,11 +323,14 @@ 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.
# pylint: disable-next=fixme
# 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()


Expand Down Expand Up @@ -398,7 +413,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
----------
Expand Down
11 changes: 5 additions & 6 deletions transformer_engine/pytorch/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading