From 9725f1f649f0cd604d0ca661fff5dd5053d70221 Mon Sep 17 00:00:00 2001 From: ZenAlexa Date: Thu, 5 Nov 2026 07:21:56 -0500 Subject: [PATCH 1/2] [PyTorch] Quantize FP8 current-scaling splits with the grouped kernels Signed-off-by: ZenAlexa --- tests/pytorch/test_grouped_linear.py | 47 +++++++ transformer_engine/pytorch/csrc/common.h | 10 ++ .../pytorch/csrc/extensions/cast.cpp | 123 ++++++++++++++++++ transformer_engine/pytorch/csrc/quantizer.cpp | 47 ++++--- .../pytorch/ops/basic/grouped_linear.py | 8 +- 5 files changed, 215 insertions(+), 20 deletions(-) diff --git a/tests/pytorch/test_grouped_linear.py b/tests/pytorch/test_grouped_linear.py index 19b27798c5d..1ebdd49ce18 100644 --- a/tests/pytorch/test_grouped_linear.py +++ b/tests/pytorch/test_grouped_linear.py @@ -3827,3 +3827,50 @@ def test_swizzle_scales_and_pack_ptrs_for_discrete_weights( swizzled_scales_buffer, expected_swizzled_scales_buffer, ) + + +@pytest.mark.skipif(not fp8_available, reason=reason_for_no_fp8) +@pytest.mark.parametrize( + "split_sizes", [[64, 64, 64, 64], [0, 48, 1, 207, 0, 16], [0, 0], [33]], ids=str +) +@pytest.mark.parametrize("columnwise", [True, False]) +@pytest.mark.parametrize("internal", [False, True]) +@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float32], ids=str) +def test_split_quantize_fp8_current_scaling_matches_per_split( + split_sizes, columnwise, internal, dtype +): + """Grouped split quantization must match quantizing every split on its own.""" + from transformer_engine.pytorch.utils import is_non_tn_fp8_gemm_supported + + torch.manual_seed(0) + hidden = 128 + x = torch.randn(sum(split_sizes), hidden, dtype=dtype, device="cuda") + x[: max(split_sizes[0], 1)] *= 1e3 # give splits different scales + + def quantizers(): + out = [] + for _ in split_sizes: + quantizer = Float8CurrentScalingQuantizer( + fp8_dtype=tex.DType.kFloat8E4M3, device="cuda" + ) + quantizer.set_usage(rowwise=True, columnwise=columnwise) + quantizer.internal = internal + out.append(quantizer) + return out + + grouped = tex.split_quantize(x, split_sizes, quantizers()) + reference = tex.split_quantize(x, split_sizes, quantizers(), disable_bulk_allocation=True) + # The grouped kernel writes +0 where the per-split cast keeps a negative zero + # on GPUs with non-TN FP8 GEMMs, so compare bytes only where FP8 GEMMs are TN-only. + compare_bytes = not is_non_tn_fp8_gemm_supported() + for size, out, ref in zip(split_sizes, grouped, reference): + for name in ("_data", "_transpose"): + got, expected = getattr(out, name), getattr(ref, name) + assert (got is None) == (expected is None), name + if got is not None: + assert got.shape == expected.shape, name + if compare_bytes: + assert torch.equal(got, expected), name + if size > 0: + assert torch.equal(out._scale_inv, ref._scale_inv) + torch.testing.assert_close(out.dequantize(), ref.dequantize(), rtol=0, atol=0) diff --git a/transformer_engine/pytorch/csrc/common.h b/transformer_engine/pytorch/csrc/common.h index 9a3c6314054..3bebe5b93a0 100644 --- a/transformer_engine/pytorch/csrc/common.h +++ b/transformer_engine/pytorch/csrc/common.h @@ -237,6 +237,16 @@ class Float8CurrentScalingQuantizer : public Quantizer { const std::optional& precomputed_tensor_offsets, size_t logical_first_dim, size_t logical_last_dim) const override; + /*! @brief Construct a tensor with pre-initialized buffers + * + * Buffers the quantizer's usages need but the caller omits are allocated. + * The buffers may be views into a larger allocation. + */ + std::pair create_tensor( + const std::vector& shape, DType dtype, std::optional data, + std::optional transpose, std::optional scale_inv, + std::optional device = std::nullopt, bool pin_memory = false) const; + /*! @brief Construct an unquantized tensor with a freshly allocated amax buffer. * * The amax is zeroed out. Most TE kernels that output amax expect diff --git a/transformer_engine/pytorch/csrc/extensions/cast.cpp b/transformer_engine/pytorch/csrc/extensions/cast.cpp index 3d61dc525f8..bf984610db0 100644 --- a/transformer_engine/pytorch/csrc/extensions/cast.cpp +++ b/transformer_engine/pytorch/csrc/extensions/cast.cpp @@ -10,8 +10,10 @@ #include #include #include +#include #include #include +#include #include #include #include @@ -2099,6 +2101,120 @@ void split_quantize_nvfp4_impl(const TensorWrapper &input, }); } +// Whether every split can share one grouped FP8 current-scaling quantization: +// the splits cover a matrix whose rows start 32-byte aligned and whose last +// dimension keeps each split's slice of the grouped buffers 16-byte aligned for +// FP8 GEMMs, and every quantizer has the same configuration. Unequal splits pass +// their sizes to the device with a host copy, which a CUDA graph would replay +// from a stale host buffer, so a capture only takes equal splits. +bool can_split_quantize_fp8_current_scaling( + const at::Tensor &input, const std::vector &split_sections, + const std::vector &quantizer_list, + const std::vector> &quantizer_cpp_list) { + if (input.dim() < 2 || input.size(-1) == 0 || input.size(-1) % 16 != 0 || + reinterpret_cast(input.data_ptr()) % 32 != 0 || + std::accumulate(split_sections.begin(), split_sections.end(), size_t{0}) != + static_cast(input.size(0))) { + return false; + } + const bool equal_splits = std::adjacent_find(split_sections.begin(), split_sections.end(), + std::not_equal_to()) == split_sections.end(); + if (!equal_splits && + at::cuda::currentStreamCaptureStatusMayInitCtx() != at::cuda::CaptureStatus::None) { + return false; + } + if (!std::all_of(quantizer_list.begin(), quantizer_list.end(), [](const py::handle &quantizer) { + return detail::IsFloat8CurrentScalingQuantizers(quantizer.ptr()); + })) { + return false; + } + const auto &first = static_cast(*quantizer_cpp_list[0]); + // Like the per-split cast, the grouped kernel needs row-wise data for a + // column-wise output wherever FP8 GEMMs only take the TN layout. + if (!first.rowwise_usage && (!first.columnwise_usage || !nvte_is_non_tn_fp8_gemm_supported())) { + return false; + } + return std::all_of( + quantizer_cpp_list.begin(), quantizer_cpp_list.end(), + [&first](const std::unique_ptr &quantizer_cpp) { + const auto &q = static_cast(*quantizer_cpp); + return q.dtype == first.dtype && q.rowwise_usage == first.rowwise_usage && + q.columnwise_usage == first.columnwise_usage && q.internal == first.internal && + q.force_pow_2_scales == first.force_pow_2_scales && + q.amax_epsilon == first.amax_epsilon && + q.with_amax_reduction == first.with_amax_reduction && + q.amax_reduction_group == first.amax_reduction_group; + }); +} + +// Quantizes all splits with one grouped amax, scale and cast(-transpose) launch +// each. Every returned tensor views its rows of the grouped data, transpose and +// scale-inverse buffers. +std::vector split_quantize_fp8_current_scaling( + const at::Tensor &input, const std::vector> &split_shapes, + const std::vector &quantizer_list, + const std::vector> &quantizer_cpp_list) { + const size_t num_splits = split_shapes.size(); + const int64_t cols = input.size(-1); + std::vector metadata(2 * num_splits + 1, 0); // rows per split, then element offsets + for (size_t i = 0; i < num_splits; ++i) { + const int64_t numel = static_cast(product(split_shapes[i])); + metadata[i] = numel / cols; + metadata[num_splits + i + 1] = metadata[num_splits + i] + numel; + } + const int64_t *rows = metadata.data(); + const int64_t *offsets = metadata.data() + num_splits; + const int64_t total_rows = offsets[num_splits] / cols; + + std::optional first_dims, tensor_offsets; + if (!std::all_of(rows, rows + num_splits, [rows](int64_t r) { return r == rows[0]; })) { + // Pinned staging keeps the copy asynchronous; the caching host allocator holds + // the block until the copy completes. + auto host_metadata = at::empty({static_cast(metadata.size())}, + at::TensorOptions().dtype(at::kLong).pinned_memory(true)); + std::copy(metadata.begin(), metadata.end(), host_metadata.data_ptr()); + auto device_metadata = host_metadata.to(at::TensorOptions().device(input.device()), + /*non_blocking=*/true); + first_dims = device_metadata.narrow(0, 0, num_splits); + tensor_offsets = device_metadata.narrow(0, num_splits, num_splits + 1); + } + py::object grouped = + group_quantize(input.view({total_rows, cols}), quantizer_list[0], num_splits, first_dims, + std::nullopt, tensor_offsets, std::nullopt, py::none()); + + auto buffer = [&grouped](const char *name) { + py::object tensor = grouped.attr(name); + return tensor.is_none() ? at::Tensor() : tensor.cast(); + }; + const at::Tensor data = buffer("rowwise_data"); + const at::Tensor transpose = buffer("columnwise_data"); + const at::Tensor scale_inv = buffer("scale_inv"); + const auto input_dtype = GetTransformerEngineDType(input.scalar_type()); + std::vector outputs; + outputs.reserve(num_splits); + for (size_t i = 0; i < num_splits; ++i) { + const int64_t numel = offsets[i + 1] - offsets[i]; + const std::vector shape(split_shapes[i].begin(), split_shapes[i].end()); + std::vector transpose_shape{shape.back()}; + transpose_shape.insert(transpose_shape.end(), shape.begin(), shape.end() - 1); + const auto &quantizer = + static_cast(*quantizer_cpp_list[i]); + auto rows_of = [&](const at::Tensor &buffer, + const std::vector &view_shape) -> std::optional { + if (!buffer.defined()) { + return std::nullopt; + } + return buffer.narrow(0, offsets[i], numel).view(view_shape); + }; + outputs.push_back(quantizer + .create_tensor(split_shapes[i], input_dtype, rows_of(data, shape), + rows_of(transpose, transpose_shape), + scale_inv.narrow(0, i, 1), input.device()) + .second); + } + return outputs; +} + } // namespace std::vector split_quantize(const at::Tensor &tensor, @@ -2151,6 +2267,13 @@ std::vector split_quantize(const at::Tensor &tensor, quantizer_cpp_list.push_back(convert_quantizer(quantizer_list[i])); } + if (!disable_bulk_allocation && + can_split_quantize_fp8_current_scaling(input_py, split_sections, quantizer_list, + quantizer_cpp_list)) { + return split_quantize_fp8_current_scaling(input_py, split_shapes, quantizer_list, + quantizer_cpp_list); + } + // Choose implementation for allocating and populating tensors enum class AllocationMethod { UNFUSED, BULK_FP8_BLOCKWISE, BULK_MXFP8, BULK_NVFP4 }; enum class QuantizationMethod { UNFUSED, FUSED_NVFP4 }; diff --git a/transformer_engine/pytorch/csrc/quantizer.cpp b/transformer_engine/pytorch/csrc/quantizer.cpp index 960e0fe46f4..28dd0f75a1a 100644 --- a/transformer_engine/pytorch/csrc/quantizer.cpp +++ b/transformer_engine/pytorch/csrc/quantizer.cpp @@ -670,37 +670,46 @@ void Float8CurrentScalingQuantizer::set_quantization_params(TensorWrapper* tenso std::pair Float8CurrentScalingQuantizer::create_tensor( const std::vector& shape, DType dtype, std::optional device_opt, bool pin_memory) const { - const auto device = resolve_device(device_opt); + return create_tensor(shape, dtype, std::nullopt, std::nullopt, std::nullopt, device_opt, + pin_memory); +} + +std::pair Float8CurrentScalingQuantizer::create_tensor( + const std::vector& shape, DType dtype, std::optional data, + std::optional transpose, std::optional scale_inv, + std::optional device_opt, bool pin_memory) const { + const auto device = resolve_device(device_opt, data); using namespace pybind11::literals; + const auto uint8_opts = + at::TensorOptions().dtype(torch::kUInt8).device(device).pinned_memory(pin_memory); + int is_non_tn_fp8_gemm_supported = nvte_is_non_tn_fp8_gemm_supported(); // Initialize data tensor - at::Tensor data_tensor; - int is_non_tn_fp8_gemm_supported = nvte_is_non_tn_fp8_gemm_supported(); const bool with_data = rowwise_usage || is_non_tn_fp8_gemm_supported; - if (with_data) { + if (with_data && !data) { const std::vector shape_int64(shape.begin(), shape.end()); - const auto opts = - at::TensorOptions().dtype(torch::kUInt8).device(device).pinned_memory(pin_memory); - data_tensor = at::empty(shape_int64, opts); + data = at::empty(shape_int64, uint8_opts); + } else if (!with_data && data) { + data.reset(); } // Initialize transpose tensor - at::Tensor transpose_tensor; const bool with_transpose = columnwise_usage && !is_non_tn_fp8_gemm_supported; - if (with_transpose) { - const auto transpose_shape = make_transpose_shape(shape); - const auto opts = - at::TensorOptions().dtype(torch::kUInt8).device(device).pinned_memory(pin_memory); - transpose_tensor = at::empty(transpose_shape, opts); + if (with_transpose && !transpose) { + transpose = at::empty(make_transpose_shape(shape), uint8_opts); + } else if (!with_transpose && transpose) { + transpose.reset(); } + // Initialize scale-inverse tensor - at::Tensor scale_inv_tensor; - { - const std::vector scale_inv_shape = {1}; - const auto opts = - at::TensorOptions().dtype(torch::kFloat32).device(device).pinned_memory(pin_memory); - scale_inv_tensor = at::empty(scale_inv_shape, opts); + if (!scale_inv) { + scale_inv = at::empty( + {1}, at::TensorOptions().dtype(torch::kFloat32).device(device).pinned_memory(pin_memory)); } + const at::Tensor data_tensor = with_data ? *data : at::Tensor(); + const at::Tensor transpose_tensor = with_transpose ? *transpose : at::Tensor(); + const at::Tensor scale_inv_tensor = *scale_inv; + // Construct Python FP8 tensor py::object out_py; py::object scale_inv_py = py::cast(scale_inv_tensor); diff --git a/transformer_engine/pytorch/ops/basic/grouped_linear.py b/transformer_engine/pytorch/ops/basic/grouped_linear.py index a54258d5c78..1c0c265d916 100644 --- a/transformer_engine/pytorch/ops/basic/grouped_linear.py +++ b/transformer_engine/pytorch/ops/basic/grouped_linear.py @@ -1349,7 +1349,13 @@ def _fuser_forward_split_quantize( if with_quantized_compute: for quantizer in input_quantizers: quantizer.set_usage(rowwise=True, columnwise=weight_requires_grad) - xs = tex.split_quantize(x, split_sizes_int, input_quantizers) + # Bulk-allocated splits share storage, so offloading needs separate buffers + xs = tex.split_quantize( + x, + split_sizes_int, + input_quantizers, + disable_bulk_allocation=is_cpu_offload_enabled(), + ) else: xs = torch.split(x, split_sizes_int) if is_cpu_offload_enabled(): From 09b42c49ebe6cde17da8f20bb39f1eb1d1914375 Mon Sep 17 00:00:00 2001 From: ZenAlexa Date: Thu, 5 Nov 2026 12:02:48 -0500 Subject: [PATCH 2/2] [PyTorch] Keep amax-reduced splits per split and check the grouped path in the test Signed-off-by: ZenAlexa --- tests/pytorch/test_grouped_linear.py | 17 ++++++++++------- .../pytorch/csrc/extensions/cast.cpp | 8 ++++---- 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/tests/pytorch/test_grouped_linear.py b/tests/pytorch/test_grouped_linear.py index 1ebdd49ce18..2d79e1706ca 100644 --- a/tests/pytorch/test_grouped_linear.py +++ b/tests/pytorch/test_grouped_linear.py @@ -3840,12 +3840,11 @@ def test_split_quantize_fp8_current_scaling_matches_per_split( split_sizes, columnwise, internal, dtype ): """Grouped split quantization must match quantizing every split on its own.""" - from transformer_engine.pytorch.utils import is_non_tn_fp8_gemm_supported - torch.manual_seed(0) hidden = 128 x = torch.randn(sum(split_sizes), hidden, dtype=dtype, device="cuda") x[: max(split_sizes[0], 1)] *= 1e3 # give splits different scales + x.view(-1)[:1] = -0.0 def quantizers(): out = [] @@ -3860,17 +3859,21 @@ def quantizers(): grouped = tex.split_quantize(x, split_sizes, quantizers()) reference = tex.split_quantize(x, split_sizes, quantizers(), disable_bulk_allocation=True) - # The grouped kernel writes +0 where the per-split cast keeps a negative zero - # on GPUs with non-TN FP8 GEMMs, so compare bytes only where FP8 GEMMs are TN-only. - compare_bytes = not is_non_tn_fp8_gemm_supported() + # Grouped outputs view one shared scale-inverse buffer. + assert len({out._scale_inv.untyped_storage().data_ptr() for out in grouped}) == 1 + + def fp8_bytes(tensor): + # The SM100+ grouped cast rounds an input of -0.0 to +0 (0x00), the + # per-split cast to -0 (0x80). + return torch.where(tensor == 0x80, 0, tensor) + for size, out, ref in zip(split_sizes, grouped, reference): for name in ("_data", "_transpose"): got, expected = getattr(out, name), getattr(ref, name) assert (got is None) == (expected is None), name if got is not None: assert got.shape == expected.shape, name - if compare_bytes: - assert torch.equal(got, expected), name + assert torch.equal(fp8_bytes(got), fp8_bytes(expected)), name if size > 0: assert torch.equal(out._scale_inv, ref._scale_inv) torch.testing.assert_close(out.dequantize(), ref.dequantize(), rtol=0, atol=0) diff --git a/transformer_engine/pytorch/csrc/extensions/cast.cpp b/transformer_engine/pytorch/csrc/extensions/cast.cpp index bf984610db0..ffbe14ad377 100644 --- a/transformer_engine/pytorch/csrc/extensions/cast.cpp +++ b/transformer_engine/pytorch/csrc/extensions/cast.cpp @@ -2106,7 +2106,9 @@ void split_quantize_nvfp4_impl(const TensorWrapper &input, // dimension keeps each split's slice of the grouped buffers 16-byte aligned for // FP8 GEMMs, and every quantizer has the same configuration. Unequal splits pass // their sizes to the device with a host copy, which a CUDA graph would replay -// from a stale host buffer, so a capture only takes equal splits. +// from a stale host buffer, so a capture only takes equal splits. Amax reduction +// stays per split: the choice depends on rank-local split sizes and alignment, +// and ranks taking different paths would issue mismatched collectives. bool can_split_quantize_fp8_current_scaling( const at::Tensor &input, const std::vector &split_sections, const std::vector &quantizer_list, @@ -2141,9 +2143,7 @@ bool can_split_quantize_fp8_current_scaling( return q.dtype == first.dtype && q.rowwise_usage == first.rowwise_usage && q.columnwise_usage == first.columnwise_usage && q.internal == first.internal && q.force_pow_2_scales == first.force_pow_2_scales && - q.amax_epsilon == first.amax_epsilon && - q.with_amax_reduction == first.with_amax_reduction && - q.amax_reduction_group == first.amax_reduction_group; + q.amax_epsilon == first.amax_epsilon && !q.with_amax_reduction; }); }