diff --git a/tests/pytorch/test_grouped_linear.py b/tests/pytorch/test_grouped_linear.py index f53fe23c27c..4979be02ae7 100644 --- a/tests/pytorch/test_grouped_linear.py +++ b/tests/pytorch/test_grouped_linear.py @@ -3897,3 +3897,53 @@ 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.""" + 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 = [] + 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) + # 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 + 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/common.h b/transformer_engine/pytorch/csrc/common.h index e85ebb491b4..213eeee87f7 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 13dd26f6259..4bd662ab8ba 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 @@ -2246,6 +2248,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. 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, + 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; + }); +} + +// 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, @@ -2298,6 +2414,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 eccebf62acb..4a3b673711a 100644 --- a/transformer_engine/pytorch/csrc/quantizer.cpp +++ b/transformer_engine/pytorch/csrc/quantizer.cpp @@ -668,37 +668,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 9da9de7b644..b66cb31474d 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():