From 8bbea17345574018867f2bfe3093520507dcbd95 Mon Sep 17 00:00:00 2001 From: ArchanaChetan07 Date: Fri, 4 Dec 2026 18:25:37 -0800 Subject: [PATCH 1/2] [Common] Reject odd width and start offset in NVFP4 2D partial cast nvfp4_2d_partial_cast_kernel writes each pair of adjacent elements as one whole byte. With an odd width a byte holds elements of two rows, and with an odd start offset it holds elements of two shards. The kernel then writes the wrong byte or nibble and can race on a byte shared between thread blocks (#4003). Callers in TE never pass these values. NVFP4 tensors need a width that is a multiple of 32, and the distributed-optimizer shards of a packed FP4 buffer start on byte boundaries. So check both on the host instead of making the kernel nibble-atomic. The check adds no device work. Add a single-GPU test that casts a tensor shard by shard, including widths that are not a multiple of the tile size and shards that split rows and tiles, and checks the bytes against a cast of the whole tensor. It also checks that odd widths and offsets are rejected. Co-Authored-By: Claude Opus 5.5 Signed-off-by: ArchanaChetan07 --- .../nvfp4/test_nvfp4_2d_partial_cast.py | 112 ++++++++++++++++++ .../include/transformer_engine/recipe.h | 8 +- transformer_engine/common/recipe/nvfp4.cu | 7 ++ 3 files changed, 123 insertions(+), 4 deletions(-) create mode 100644 tests/pytorch/nvfp4/test_nvfp4_2d_partial_cast.py 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..6050b5a8367 --- /dev/null +++ b/tests/pytorch/nvfp4/test_nvfp4_2d_partial_cast.py @@ -0,0 +1,112 @@ +# 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) + +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.skipif(not nvfp4_available, reason=reason_for_no_nvfp4) +@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.skipif(not torch.cuda.is_available(), reason="CUDA is required") +@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(); From 57270c898e2c67a7229cdc75e342b2258d32dede Mon Sep 17 00:00:00 2001 From: ArchanaChetan07 Date: Fri, 4 Dec 2026 18:46:12 -0800 Subject: [PATCH 2/2] [PyTorch] Skip NVFP4 partial-cast rejection test without NVFP4 support nvte_nvfp4_2d_partial_cast_v2 raises "FP4 support requires CUDA 12.8+" before the new width and offset checks when TE is built with CUDA older than 12.8, so the rejection test fails there. Gate the whole file on NVFP4 support, like the rest of tests/pytorch/nvfp4. Co-Authored-By: Claude Opus 5.5 Signed-off-by: ArchanaChetan07 --- tests/pytorch/nvfp4/test_nvfp4_2d_partial_cast.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/pytorch/nvfp4/test_nvfp4_2d_partial_cast.py b/tests/pytorch/nvfp4/test_nvfp4_2d_partial_cast.py index 6050b5a8367..6c90b991261 100644 --- a/tests/pytorch/nvfp4/test_nvfp4_2d_partial_cast.py +++ b/tests/pytorch/nvfp4/test_nvfp4_2d_partial_cast.py @@ -20,6 +20,9 @@ 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 @@ -59,7 +62,6 @@ def _partial_cast( ) -@pytest.mark.skipif(not nvfp4_available, reason=reason_for_no_nvfp4) @pytest.mark.parametrize( "shape, boundaries", [ @@ -89,7 +91,6 @@ def test_sharded_partial_cast_matches_full(shape: Tuple[int, int], boundaries: L torch.testing.assert_close(sharded, reference, atol=0, rtol=0) -@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA is required") @pytest.mark.parametrize( "shape, start, end, match", [