diff --git a/tests/pytorch/nvfp4/test_nvfp4_2d_partial_cast.py b/tests/pytorch/nvfp4/test_nvfp4_2d_partial_cast.py new file mode 100644 index 00000000000..6c90b991261 --- /dev/null +++ b/tests/pytorch/nvfp4/test_nvfp4_2d_partial_cast.py @@ -0,0 +1,113 @@ +# Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# See LICENSE for license information. + +"""Single-GPU tests for the NVFP4 2D partial cast used to cast master-weight shards. + +Casting a tensor shard by shard into slices of one packed FP4 buffer must give the same +bytes as casting the whole tensor at once. The kernel writes each pair of adjacent elements +as one whole byte, so it rejects an odd width or an odd shard start, where a byte would hold +elements of two rows or of two shards. +""" + +from typing import List, Tuple + +import pytest +import torch + +import transformer_engine.pytorch as te +import transformer_engine_torch as tex + +nvfp4_available, reason_for_no_nvfp4 = te.is_nvfp4_available(return_reason=True) + +# The NVFP4 partial-cast API is only compiled with CUDA 12.8+ and only runs on Blackwell. +pytestmark = pytest.mark.skipif(not nvfp4_available, reason=reason_for_no_nvfp4) + +BLOCK_LEN = 16 + + +def _scales(master: torch.Tensor, h: int, w: int) -> Tuple[torch.Tensor, torch.Tensor]: + """Per-tile decode scales and the global encode scale for the whole tensor.""" + tile_shape = ((h + BLOCK_LEN - 1) // BLOCK_LEN, (w + BLOCK_LEN - 1) // BLOCK_LEN) + block_amax = torch.zeros(tile_shape, dtype=torch.float32, device=master.device) + tex.nvfp4_2d_compute_partial_amax(master.view(-1), block_amax, h, w, 0, BLOCK_LEN) + global_amax = block_amax.amax().view(1) + per_block_scale = torch.empty_like(block_amax) + tex.nvfp4_compute_per_block_scale(block_amax, per_block_scale, global_amax) + global_scale = torch.empty_like(global_amax) + tex.nvfp4_compute_global_scale(global_amax, global_scale) + return per_block_scale, global_scale + + +def _partial_cast( + master: torch.Tensor, + out: torch.Tensor, + scale: torch.Tensor, + global_scale: torch.Tensor, + h: int, + w: int, + start: int, + end: int, +) -> None: + """Cast master elements [start, end) into the bytes of ``out`` that hold them.""" + tex.nvfp4_2d_partial_cast( + master.view(-1)[start:end], + out[start // 2 : (end + 1) // 2], + scale, + global_scale, + h, + w, + start, + BLOCK_LEN, + ) + + +@pytest.mark.parametrize( + "shape, boundaries", + [ + # Width a multiple of the tile size, shards split mid-row and mid-tile. + ((64, 96), [0, 1000, 2050, 4096, 6144]), + # Width not a multiple of the tile size (unaligned kernel path). + ((48, 40), [0, 18, 640, 1202, 1920]), + ((33, 34), [0, 34, 36, 568, 1122]), + # Single short shard in the middle of the tensor. + ((32, 64), [0, 130, 132, 2048]), + ], +) +def test_sharded_partial_cast_matches_full(shape: Tuple[int, int], boundaries: List[int]): + h, w = shape + assert boundaries[0] == 0 and boundaries[-1] == h * w + torch.manual_seed(0) + master = torch.randn(shape, dtype=torch.float32, device="cuda") + scale, global_scale = _scales(master, h, w) + + reference = torch.zeros(h * w // 2, dtype=torch.uint8, device="cuda") + _partial_cast(master, reference, scale, global_scale, h, w, 0, h * w) + + sharded = torch.zeros_like(reference) + for start, end in zip(boundaries[:-1], boundaries[1:]): + _partial_cast(master, sharded, scale, global_scale, h, w, start, end) + + torch.testing.assert_close(sharded, reference, atol=0, rtol=0) + + +@pytest.mark.parametrize( + "shape, start, end, match", + [ + ((2, 3), 0, 6, "even number of columns"), + ((64, 17), 0, 64 * 17, "even number of columns"), + ((1, 16), 1, 7, "even start offset"), + ((32, 64), 1001, 2048, "even start offset"), + ], +) +def test_partial_cast_rejects_odd_width_or_offset( + shape: Tuple[int, int], start: int, end: int, match: str +): + h, w = shape + master = torch.randn(shape, dtype=torch.float32, device="cuda") + tile_shape = ((h + BLOCK_LEN - 1) // BLOCK_LEN, (w + BLOCK_LEN - 1) // BLOCK_LEN) + scale = torch.ones(tile_shape, dtype=torch.float32, device="cuda") + global_scale = torch.ones(1, dtype=torch.float32, device="cuda") + out = torch.zeros((h * w + 1) // 2, dtype=torch.uint8, device="cuda") + with pytest.raises(RuntimeError, match=match): + _partial_cast(master, out, scale, global_scale, h, w, start, end) diff --git a/transformer_engine/common/include/transformer_engine/recipe.h b/transformer_engine/common/include/transformer_engine/recipe.h index 1c9af7d4fcf..eb54bb28289 100644 --- a/transformer_engine/common/include/transformer_engine/recipe.h +++ b/transformer_engine/common/include/transformer_engine/recipe.h @@ -375,10 +375,10 @@ void nvte_nvfp4_2d_compute_partial_amax(const NVTETensor inp, NVTETensor amax, s * \param[in] scale Per-tile scale factors [tile_rows, tile_cols], float32. * \param[in] global_scale Global scale factor [1], float32. * \param[in] h Number of rows in the full 2D tensor. - * \param[in] w Number of columns in the full 2D tensor. + * \param[in] w Number of columns in the full 2D tensor. Must be even. * \param[in] scale_stride_h Stride for scale in tile-row dimension. * \param[in] scale_stride_w Stride for scale in tile-col dimension. - * \param[in] start_offset Starting element offset in the flattened tensor. + * \param[in] start_offset Starting element offset in the flattened tensor. Must be even. * \param[in] block_len Tile dimension (must be 16 for NVFP4 2D). * \param[in] stream CUDA stream used for the operation. */ @@ -396,10 +396,10 @@ void nvte_nvfp4_2d_partial_cast(const NVTETensor inp, NVTETensor out, const NVTE * \param[in] scale Per-tile scale factors [tile_rows, tile_cols], float32. * \param[in] global_scale Global scale factor [1], float32. * \param[in] h Number of rows in the full 2D tensor. - * \param[in] w Number of columns in the full 2D tensor. + * \param[in] w Number of columns in the full 2D tensor. Must be even. * \param[in] scale_stride_h Stride for scale in tile-row dimension. * \param[in] scale_stride_w Stride for scale in tile-col dimension. - * \param[in] start_offset Starting element offset in the flattened tensor. + * \param[in] start_offset Starting element offset in the flattened tensor. Must be even. * \param[in] block_len Tile dimension (must be 16 for NVFP4 2D). * \param[in] scale_dtype NVFP4 scale storage type (E4M3 or UE5M3). * \param[in] stream CUDA stream used for the operation. diff --git a/transformer_engine/common/recipe/nvfp4.cu b/transformer_engine/common/recipe/nvfp4.cu index 14a0264074e..6258fb8a17a 100644 --- a/transformer_engine/common/recipe/nvfp4.cu +++ b/transformer_engine/common/recipe/nvfp4.cu @@ -295,6 +295,13 @@ void nvfp4_2d_partial_cast(const Tensor inp, Tensor out, const Tensor scale, DType scale_dtype, cudaStream_t stream) { NVTE_CHECK(block_len == 16, "NVFP4 2D supports 16x16 tiles only (block_len = 16)."); NVTE_CHECK(out.dtype() == DType::kByte, "NVFP4 rowwise data must be uint8."); + // The kernel writes each pair of adjacent elements as one whole byte, so every byte must hold + // two elements of the same row and of the same shard. + NVTE_CHECK(w % 2 == 0, "NVFP4 2D partial cast requires an even number of columns, got w = ", w, + "."); + NVTE_CHECK(start_offset % 2 == 0, + "NVFP4 2D partial cast requires an even start offset, got start_offset = ", + start_offset, "."); size_t len = inp.numel();