From c55753c3e40ca92f4c2ff00048159a937519ff79 Mon Sep 17 00:00:00 2001 From: Zhongbo Zhu Date: Wed, 25 Nov 2026 02:24:21 -0800 Subject: [PATCH 01/16] Clarify NVFP4 host-split APIs and retire frontend split fusions Signed-off-by: Zhongbo Zhu --- docs/api/c/index.rst | 5 + docs/api/c/nvfp4_host_split.rst | 38 ++++ .../test_row_scaled_nvfp4_grouped_amax.cu | 3 +- .../nvfp4/test_nvfp4_host_split_fallback.py | 73 ++++++ .../common/cast/cast_grouped.cu | 2 +- .../group_hadamard_transform.cu | 21 +- ...cast_col_hadamard_transform_cast_fusion.cu | 15 +- .../common/include/transformer_engine/cast.h | 6 +- .../transformer_engine/hadamard_transform.h | 15 ++ .../include/transformer_engine/multi_tensor.h | 10 +- .../pytorch/csrc/extensions/cast.cpp | 212 +++--------------- 11 files changed, 211 insertions(+), 189 deletions(-) create mode 100644 docs/api/c/nvfp4_host_split.rst create mode 100644 tests/pytorch/nvfp4/test_nvfp4_host_split_fallback.py diff --git a/docs/api/c/index.rst b/docs/api/c/index.rst index 82024e25b02..a0e9eb7d16d 100644 --- a/docs/api/c/index.rst +++ b/docs/api/c/index.rst @@ -9,6 +9,11 @@ C/C++ API The C/C++ API allows you to access the custom kernels defined in `libtransformer_engine.so` library directly from C/C++, without Python. +.. toctree:: + :caption: Migration + + nvfp4_host_split + .. toctree:: :caption: Headers diff --git a/docs/api/c/nvfp4_host_split.rst b/docs/api/c/nvfp4_host_split.rst new file mode 100644 index 00000000000..054eddeb7a4 --- /dev/null +++ b/docs/api/c/nvfp4_host_split.rst @@ -0,0 +1,38 @@ +.. + Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. + + See LICENSE for license information. + +NVFP4 Host-Split API Migration +============================= + +Host-split APIs consume a host array of expert lengths. Their new names make +that ownership explicit: + +* ``nvte_group_amax_host_split`` +* ``nvte_group_hadamard_transform_amax_host_split`` +* ``nvte_group_hadamard_transform_cast_fusion_host_split`` + +The previous names remain deprecated forwarding symbols. Renaming does not +change amax semantics or alignment. Reading dynamic expert lengths back from +the device is not CUDA-graph safe; fixed host splits do not require that copy. + +The fused host-split RHT quantizer requires each expert's row count and the +shared hidden dimension to be divisible by 128. Empty experts are allowed. +The PyTorch split-quantize dispatcher checks this before selecting the fusion. +For example, splits ``[64, 64]`` cannot use it even though the total is 128; +they use per-expert quantization with the same RHT recipe instead. Scale layout +conversion follows the selected implementation. + +``nvte_group_nvfp4_quantize_with_amax`` and +``nvte_group_hadamard_transform_cast_fusion_columnwise`` are deprecated. +PyTorch no longer uses these single-direction grouped kernels. Their common +implementations remain available for compatibility, including their existing +alignment and supplied-amax contracts. A 2D quantizer is not a replacement for +the former's 1D recipe. + +``nvte_group_nvfp4_compute_amax`` remains a deprecated host-split alias. +``nvte_group_amax_graph_safe`` is also deprecated as a standalone public entry; +its internal implementations remain available. Ordinary GroupedTensor +quantization uses ``nvte_group_quantize`` for supported recipes. The existing +GroupedTensor RHT APIs are unchanged. diff --git a/tests/cpp/operator/test_row_scaled_nvfp4_grouped_amax.cu b/tests/cpp/operator/test_row_scaled_nvfp4_grouped_amax.cu index 226e5c4c2ed..9a5021fc1a6 100644 --- a/tests/cpp/operator/test_row_scaled_nvfp4_grouped_amax.cu +++ b/tests/cpp/operator/test_row_scaled_nvfp4_grouped_amax.cu @@ -80,11 +80,12 @@ void performGroupedFusedAmaxTest(const GroupedAmaxConfig& cfg) { auto outs = make_row_scaled_outputs("gout_", Ms, K); std::vector out_handles; for (auto& t : outs) out_handles.push_back(t->data()); - nvte_group_amax(packed.data(), out_handles.data(), splits.data(), num_tensors, 0); + nvte_group_amax_host_split(packed.data(), out_handles.data(), splits.data(), num_tensors, 0); auto outs2 = make_row_scaled_outputs("gout2_", Ms, K); std::vector out_handles2; for (auto& t : outs2) out_handles2.push_back(t->data()); + // The deprecated symbol must remain ABI-compatible and numerically identical. nvte_group_amax(packed.data(), out_handles2.data(), splits.data(), num_tensors, 0); cudaDeviceSynchronize(); diff --git a/tests/pytorch/nvfp4/test_nvfp4_host_split_fallback.py b/tests/pytorch/nvfp4/test_nvfp4_host_split_fallback.py new file mode 100644 index 00000000000..951a9958dc1 --- /dev/null +++ b/tests/pytorch/nvfp4/test_nvfp4_host_split_fallback.py @@ -0,0 +1,73 @@ +# Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# See LICENSE for license information. + +import pytest +import torch + +import transformer_engine.pytorch as te +import transformer_engine_torch as tex +from transformer_engine.pytorch import NVFP4Quantizer + + +def _valid_scales(output, direction, rows, cols): + scales = getattr(output, f"_{direction}_scale_inv").view(torch.uint8) + if output._with_gemm_swizzled_scales: + padded_rows, padded_cols = scales.shape + scales = ( + scales.reshape(padded_rows // 128, padded_cols // 4, 32, 4, 4) + .permute(0, 3, 2, 1, 4) + .reshape(padded_rows, padded_cols) + ) + return scales[:rows, : cols // 16] + + +@pytest.mark.skipif(not te.is_nvfp4_available(), reason="NVFP4 requires Blackwell") +@pytest.mark.parametrize("splits", [(128, 128), (64, 64), (0, 64, 192), (128, 0, 128), (0, 0)]) +@pytest.mark.parametrize("directions", [(True, True), (True, False), (False, True)]) +@pytest.mark.parametrize("optimize_for_gemm", [False, True]) +@pytest.mark.parametrize("disable_fusion", [False, True]) +def test_host_split_rht_fallback( + splits, directions, optimize_for_gemm, disable_fusion, monkeypatch +): + monkeypatch.setenv("NVTE_NVFP4_DISABLE_RHT_CAST_FUSION", str(int(disable_fusion))) + torch.manual_seed(123) + x = torch.randn(sum(splits), 128, dtype=torch.bfloat16, device="cuda") + quantizers = [ + NVFP4Quantizer( + fp4_dtype=te.DType.kFloat4E2M1, + rowwise=directions[0], + columnwise=directions[1], + with_rht=True, + with_post_rht_amax=True, + with_random_sign_mask=False, + ) + for _ in splits + ] + for quantizer in quantizers: + quantizer.optimize_for_gemm = optimize_for_gemm + expected = [q(part) for q, part in zip(quantizers, x.split(splits))] + with torch.profiler.profile(activities=[torch.profiler.ProfilerActivity.CUDA]) as prof: + actual = tex.split_quantize(x, splits, quantizers) + # Neither the full fusion nor its per-expert fallback may call retired kernels. + names = [event.name for event in prof.events()] + assert not any("group_quantize_transpose_nvfp4_kernel" in name for name in names) + assert not any("group_rht_gemm_device" in name for name in names) + for rows, result, reference in zip(splits, actual, expected): + for enabled, direction, amax, shape in ( + (directions[0], "rowwise", "_amax_rowwise", (rows, 128)), + (directions[1], "columnwise", "_amax_columnwise", (128, rows)), + ): + if not enabled: + continue + data = getattr(result, f"_{direction}_data") + ref_data = getattr(reference, f"_{direction}_data") + assert data.shape == ref_data.shape + if rows == 0: + continue # Empty-expert storage is not initialized by either path. + assert torch.equal(data.view(torch.uint8), ref_data.view(torch.uint8)) + assert torch.equal(getattr(result, amax), getattr(reference, amax)) + assert torch.equal( + _valid_scales(result, direction, *shape), + _valid_scales(reference, direction, *shape), + ) diff --git a/transformer_engine/common/cast/cast_grouped.cu b/transformer_engine/common/cast/cast_grouped.cu index 0a33f62d5fb..89229af0829 100644 --- a/transformer_engine/common/cast/cast_grouped.cu +++ b/transformer_engine/common/cast/cast_grouped.cu @@ -102,5 +102,5 @@ void nvte_group_nvfp4_quantize_with_amax(const NVTETensor input, NVTETensor *out void nvte_group_nvfp4_compute_amax(const NVTETensor input, NVTETensor *outputs, const size_t *split_sections, const size_t num_tensors, cudaStream_t stream) { - nvte_group_amax(input, outputs, split_sections, num_tensors, stream); + nvte_group_amax_host_split(input, outputs, split_sections, num_tensors, stream); } diff --git a/transformer_engine/common/hadamard_transform/group_hadamard_transform.cu b/transformer_engine/common/hadamard_transform/group_hadamard_transform.cu index f8c04bea0cb..80fe6b0be85 100644 --- a/transformer_engine/common/hadamard_transform/group_hadamard_transform.cu +++ b/transformer_engine/common/hadamard_transform/group_hadamard_transform.cu @@ -563,11 +563,11 @@ void group_hadamard_transform_amax(const Tensor& input_, std::vector& o // in dimension 0, we can treat the entire input as a single tensor. // Although mathmatically 16 multple is enough for this function to be correct, // for this kernel, we required 64 multiple of 16 in dimension 0 for better performance. -void nvte_group_hadamard_transform_amax(const NVTETensor input, NVTETensor* outputs, +void nvte_group_hadamard_transform_amax_host_split(const NVTETensor input, NVTETensor* outputs, const size_t* split_sections, size_t num_tensors, int random_sign_mask, int random_sign_mask_t, cudaStream_t stream) { - NVTE_API_CALL(nvte_group_hadamard_transform_amax); + NVTE_API_CALL(nvte_group_hadamard_transform_amax_host_split); using namespace transformer_engine; if (num_tensors == 0) { return; @@ -585,9 +585,9 @@ void nvte_group_hadamard_transform_amax(const NVTETensor input, NVTETensor* outp } // Grouped-tensor amax -void nvte_group_amax(const NVTETensor input, NVTETensor* outputs, const size_t* split_sections, +void nvte_group_amax_host_split(const NVTETensor input, NVTETensor* outputs, const size_t* split_sections, size_t num_tensors, cudaStream_t stream) { - NVTE_API_CALL(nvte_group_amax); + NVTE_API_CALL(nvte_group_amax_host_split); using namespace transformer_engine; if (num_tensors == 0) { return; @@ -626,3 +626,16 @@ void nvte_group_amax(const NVTETensor input, NVTETensor* outputs, const size_t* group_hadamard_transform_amax(*input_tensor, output_list, split_sections, num_tensors, 0, 0, true, stream); } + +void nvte_group_amax(const NVTETensor input, NVTETensor* outputs, const size_t* split_sections, + size_t num_tensors, cudaStream_t stream) { + nvte_group_amax_host_split(input, outputs, split_sections, num_tensors, stream); +} + +void nvte_group_hadamard_transform_amax(const NVTETensor input, NVTETensor* outputs, + const size_t* split_sections, size_t num_tensors, + int random_sign_mask, int random_sign_mask_t, + cudaStream_t stream) { + nvte_group_hadamard_transform_amax_host_split(input, outputs, split_sections, num_tensors, + random_sign_mask, random_sign_mask_t, stream); +} diff --git a/transformer_engine/common/hadamard_transform/group_row_cast_col_hadamard_transform_cast_fusion.cu b/transformer_engine/common/hadamard_transform/group_row_cast_col_hadamard_transform_cast_fusion.cu index 67452c6aa75..8bf3c2fd902 100644 --- a/transformer_engine/common/hadamard_transform/group_row_cast_col_hadamard_transform_cast_fusion.cu +++ b/transformer_engine/common/hadamard_transform/group_row_cast_col_hadamard_transform_cast_fusion.cu @@ -1489,17 +1489,19 @@ void group_hadamard_transform_cast_fusion(const Tensor &input_, std::vector 0, "Number of tensors should be greater than 0."); Tensor *input_tensor = convertNVTETensorCheck(input); + NVTE_CHECK(input_tensor->flat_last_dim() % 128 == 0, + "Grouped RHT quantization requires the hidden dimension to be a multiple of 128."); std::vector output_list(num_tensors); for (size_t i = 0; i < num_tensors; ++i) { output_list[i] = convertNVTETensorCheck(outputs[i]); @@ -1517,3 +1519,12 @@ void nvte_group_hadamard_transform_cast_fusion(const NVTETensor input, NVTETenso *convertNVTETensorCheck(hadamard_matrix), quant_config_cpp, *quant_workspace_tensor, stream); } + +void nvte_group_hadamard_transform_cast_fusion( + const NVTETensor input, NVTETensor *outputs, const NVTETensor hadamard_matrix, + const size_t *split_sections, const size_t num_tensors, + const NVTEQuantizationConfig quant_config, NVTETensor quant_workspace, cudaStream_t stream) { + nvte_group_hadamard_transform_cast_fusion_host_split( + input, outputs, hadamard_matrix, split_sections, num_tensors, quant_config, quant_workspace, + stream); +} diff --git a/transformer_engine/common/include/transformer_engine/cast.h b/transformer_engine/common/include/transformer_engine/cast.h index 1af93d42919..b29332276b9 100644 --- a/transformer_engine/common/include/transformer_engine/cast.h +++ b/transformer_engine/common/include/transformer_engine/cast.h @@ -467,6 +467,10 @@ void nvte_multi_tensor_quantize(const NVTETensor *inputs, NVTETensor *outputs, cudaStream_t stream); /*! \brief Casts grouped input tensor to quantized output tensors. + * + * \deprecated Legacy host-split rowwise-only NVFP4 quantization with supplied amax. + * Retained for compatibility. Use single-tensor nvte_quantize_v2 for ordinary + * 1D quantization; ordinary grouped 2D quantization is not a replacement. * * \param[in] input Input tensor to be cast. * \param[in,out] outputs Output quantized tensors. @@ -480,7 +484,7 @@ void nvte_group_nvfp4_quantize_with_amax(const NVTETensor input, NVTETensor *out const NVTEQuantizationConfig quant_config, cudaStream_t stream); -/*! \deprecated Use nvte_group_amax instead. */ +/*! \deprecated Use nvte_group_amax_host_split instead. */ void nvte_group_nvfp4_compute_amax(const NVTETensor input, NVTETensor *outputs, const size_t *split_sections, size_t num_tensors, cudaStream_t stream); diff --git a/transformer_engine/common/include/transformer_engine/hadamard_transform.h b/transformer_engine/common/include/transformer_engine/hadamard_transform.h index 8f1a213cec1..7cf87e115d9 100644 --- a/transformer_engine/common/include/transformer_engine/hadamard_transform.h +++ b/transformer_engine/common/include/transformer_engine/hadamard_transform.h @@ -96,6 +96,11 @@ void nvte_quantize_with_hadamard_transform(const NVTETensor input, NVTETensor ou * \param[in] random_sign_mask_t 16-bit sign mask for transposed RHT. * \param[in] stream CUDA stream used for the operation. */ +void nvte_group_hadamard_transform_amax_host_split( + const NVTETensor input, NVTETensor* outputs, const size_t* split_sections, size_t num_tensors, + int random_sign_mask, int random_sign_mask_t, cudaStream_t stream); + +/*! \deprecated Use nvte_group_hadamard_transform_amax_host_split. */ void nvte_group_hadamard_transform_amax(const NVTETensor input, NVTETensor* outputs, const size_t* split_sections, size_t num_tensors, int random_sign_mask, int random_sign_mask_t, @@ -122,6 +127,10 @@ void nvte_group_hadamard_transform_amax_graph_safe(const NVTEGroupedTensor input /*! * \brief Perform the grouped-tensor columnwise Hadamard transform cast fusion operation. * + * \deprecated Legacy host-split columnwise-only quantization. The implementation is retained + * for compatibility. Use the fused host-split entry for eligible shapes or a + * single-tensor RHT path otherwise; their alignment requirements differ. + * * This function is experimental and the API is not stable. Group_ prefix means contiguous input concatenated * * \param[in] input Input tensor to apply Hadamard transform. @@ -151,6 +160,12 @@ void nvte_group_hadamard_transform_cast_fusion_columnwise( * \param[in] quant_workspace Workspace buffer. Must be at least 4 bytes. * \param[in] stream CUDA stream used for the operation. */ +void nvte_group_hadamard_transform_cast_fusion_host_split( + const NVTETensor input, NVTETensor* outputs, const NVTETensor hadamard_matrix, + const size_t* split_sections, size_t num_tensors, const NVTEQuantizationConfig quant_config, + NVTETensor quant_workspace, cudaStream_t stream); + +/*! \deprecated Use nvte_group_hadamard_transform_cast_fusion_host_split. */ void nvte_group_hadamard_transform_cast_fusion(const NVTETensor input, NVTETensor* outputs, const NVTETensor hadamard_matrix, const size_t* split_sections, size_t num_tensors, diff --git a/transformer_engine/common/include/transformer_engine/multi_tensor.h b/transformer_engine/common/include/transformer_engine/multi_tensor.h index 30f7669392e..364b991f379 100644 --- a/transformer_engine/common/include/transformer_engine/multi_tensor.h +++ b/transformer_engine/common/include/transformer_engine/multi_tensor.h @@ -304,7 +304,7 @@ void nvte_multi_tensor_compute_scale_inv_e8m0_cuda(int chunk_size, NVTETensor ** * For each tensor split, compute the maximum absolute value (amax) * and populate the amax buffers of the corresponding output tensor. * All output tensors must have the same tensor format, and the - * tensor format determines which amaxes are computed. + * tensor format determines which amaxes are computed. Split lengths reside on the host. * * \param[in] input Input tensor. * \param[in,out] outputs Array of output tensors. Only amax buffers are updated. @@ -312,10 +312,18 @@ void nvte_multi_tensor_compute_scale_inv_e8m0_cuda(int chunk_size, NVTETensor ** * \param[in] num_tensors Number of tensor splits. * \param[in] stream CUDA stream used for the operation. */ +void nvte_group_amax_host_split(const NVTETensor input, NVTETensor *outputs, + const size_t *split_sections, size_t num_tensors, + cudaStream_t stream); + +/*! \deprecated Use nvte_group_amax_host_split. The signature and behavior are unchanged. */ void nvte_group_amax(const NVTETensor input, NVTETensor *outputs, const size_t *split_sections, size_t num_tensors, cudaStream_t stream); /*! \brief Graph-safe variant of nvte_group_amax for grouped tensors. + * + * \deprecated Standalone grouped amax entry. Existing behavior is retained for compatibility; + * quantization paths should use nvte_group_quantize when supported. * * This function is experimental and the API is not stable. * diff --git a/transformer_engine/pytorch/csrc/extensions/cast.cpp b/transformer_engine/pytorch/csrc/extensions/cast.cpp index 13dd26f6259..4107432286c 100644 --- a/transformer_engine/pytorch/csrc/extensions/cast.cpp +++ b/transformer_engine/pytorch/csrc/extensions/cast.cpp @@ -1854,190 +1854,45 @@ static StochasticRngStateResources setup_stochastic_rounding_rng_states_helper( // Implements split-quantize NVFP4 with Row/Column-wise Hadamard Transform (RHT) void split_quantize_nvfp4_impl_with_rht_helper(const TensorWrapper &input, - const std::vector &input_list, std::vector &output_list, const std::vector &split_sections, const std::vector &quantizers, cudaStream_t stream) { const size_t num_tensors = split_sections.size(); const auto &quantizer = *quantizers.front(); - const bool nvfp4_use_4over6 = quantizer.nvfp4_4over6_mode != kNVTENVFP44Over6Disabled; - NVTE_CHECK(!nvfp4_use_4over6, + NVTE_CHECK(quantizer.nvfp4_4over6_mode == kNVTENVFP44Over6Disabled, "NVFP4 4over6 quantization is not supported with RHT split quantization."); - - std::vector nvte_tensor_input_list; - std::vector nvte_tensor_output_list; - for (size_t i = 0; i < num_tensors; ++i) { - nvte_tensor_input_list.push_back(input_list[i].data()); - nvte_tensor_output_list.push_back(output_list[i].data()); - } - - // trigger the row-col fusion when the split-sections shapes are all 128 aligned for max performance - bool all_aligned_token_dim = - std::all_of(split_sections.begin(), split_sections.end(), - [](size_t split_section) { return split_section % 128 == 0; }); - - // in the case when rowwise and colwise cannot be fused, we have to generate the RNG states twice - // so that rowwise and colwise will have different random numbers - bool need_separate_rng_states = - (!all_aligned_token_dim) && quantizer.rowwise_usage && quantizer.columnwise_usage; - - // Objects for TE C API - std::vector quant_config_list; - std::vector quant_config_list_colwise; - for (size_t i = 0; i < num_tensors; ++i) { - quant_config_list.emplace_back(QuantizationConfigWrapper()); - quant_config_list_colwise.emplace_back(QuantizationConfigWrapper()); - } - - // this is true because we have already built grouped kernels for rowwise and colwise quantization with RHT - bool with_bulk_generate_rng_states = true; - - // Stochastic rounding - bool need_stochastic_rounding = quantizer.stochastic_rounding; - auto stochastic_rng_state_resources = setup_stochastic_rounding_rng_states_helper( - num_tensors, need_stochastic_rounding, with_bulk_generate_rng_states, - need_separate_rng_states, quant_config_list, quant_config_list_colwise); - - for (auto &config : quant_config_list) { - config.set_nvfp4_4over6_mode(quantizer.nvfp4_4over6_mode); - } - for (auto &config : quant_config_list_colwise) { - config.set_nvfp4_4over6_mode(quantizer.nvfp4_4over6_mode); - } - - // Enable NVFP4 kernels to use math operations that sacrifice - // accuracy for performance. These optimizations are experimental - // and inconsistently implemented. - // What math is accelerated? Only the high precision math, so numerical impact is minimal - // 1. replace 1 / x by reciprocal_approximate_ftz(x) - // 2. when RHT cast fusion is available, fusion allows cast to be performed on FP32 data, - // this will essentially remove a round trip between FP32 to BF16 then FP32 - // NVFP4 4over6 candidate error math is controlled separately by - // NVTE_NVFP4_4OVER6_ERR_USE_FAST_MATH. - const auto use_fast_math = transformer_engine::getenv("NVTE_USE_FAST_MATH"); - if (use_fast_math && !nvfp4_use_4over6) { - for (auto &config : quant_config_list) { - config.set_use_fast_math(true); - } - for (auto &config : quant_config_list_colwise) { - config.set_use_fast_math(true); - } + std::vector output_handles; + for (const auto &output : output_list) { + output_handles.push_back(output.data()); } - const auto use_4over6_err_use_fast_math = - transformer_engine::getenv("NVTE_NVFP4_4OVER6_ERR_USE_FAST_MATH"); - if (use_4over6_err_use_fast_math) { - for (auto &config : quant_config_list) { - config.set_nvfp4_4over6_err_use_fast_math(true); - } - for (auto &config : quant_config_list_colwise) { - config.set_nvfp4_4over6_err_use_fast_math(true); - } + std::vector configs(num_tensors); + std::vector unused_columnwise_configs; + auto rng_resources = setup_stochastic_rounding_rng_states_helper( + num_tensors, quantizer.stochastic_rounding, /*with_bulk_generate_rng_states=*/true, + /*need_separate_rng_states=*/false, configs, unused_columnwise_configs); + if (transformer_engine::getenv("NVTE_USE_FAST_MATH")) { + configs[0].set_use_fast_math(true); } - auto &quant_config_list_colwise_to_use = - need_separate_rng_states ? quant_config_list_colwise : quant_config_list; - - // Compute amaxes - if (quantizer.disable_second_level_scale) { - // A null amax tells common NVFP4 kernels to use a unit global scale. - } else if (quantizer.with_post_rht_amax) { - // We need: - // 1. Rowwise amax = amax for input - // 2. Columnwise amax = amax for RHT(input.t) - nvte_group_hadamard_transform_amax( - input.data(), reinterpret_cast(nvte_tensor_output_list.data()), - split_sections.data(), num_tensors, 0, quantizer.rht_matrix_random_sign_mask_t, stream); - } else { - // RHT is enabled, but amax is pre-RHT amax - NVTE_ERROR("NVFP4 split-quantize does not yet support pre-RHT amax"); + if (!quantizer.disable_second_level_scale) { + NVTE_CHECK(quantizer.with_post_rht_amax, + "NVFP4 split-quantize does not yet support pre-RHT amax"); + nvte_group_hadamard_transform_amax_host_split( + input.data(), output_handles.data(), split_sections.data(), num_tensors, 0, + quantizer.rht_matrix_random_sign_mask_t, stream); } - // Check that RHT matrix is available NVTE_CHECK(quantizer.rht_matrix.defined() && quantizer.rht_matrix.numel() > 0, "RHT matrix is not available."); - auto rht_matrix_nvte = makeTransformerEngineTensor(quantizer.rht_matrix); - - if (all_aligned_token_dim) { - // allocate a tile scheduler workspace - auto tile_scheduler_workspace_torch = - at::empty({1}, at::device(at::kCUDA).dtype(torch::kInt32)); - auto nvte_tile_scheduler_workspace = - makeTransformerEngineTensor(tile_scheduler_workspace_torch); - // call the fully-fused grouped kernel for rowwise quantization & colwise RHT quantization transpose - nvte_group_hadamard_transform_cast_fusion( - input.data(), reinterpret_cast(nvte_tensor_output_list.data()), - rht_matrix_nvte.data(), split_sections.data(), num_tensors, quant_config_list[0], - nvte_tile_scheduler_workspace.data(), stream); - } else { - // Separate quantization for rowwise usage and columnwise usage - // Rowwise quantization fusion with grouped version - if (quantizer.rowwise_usage) { - std::vector out_identity_list; - std::vector nvte_tensor_out_identity_list; - for (size_t i = 0; i < num_tensors; i++) { - bool is_empty_split = input_list[i].numel() == 0; - TensorWrapper out_identity(output_list[i].scaling_mode()); - auto out_identity_data = output_list[i].get_rowwise_data(); - auto out_identity_scale_inv = output_list[i].get_rowwise_scale_inv(); - auto out_identity_amax = output_list[i].get_amax(); - if (!is_empty_split) { - out_identity.set_rowwise_data(out_identity_data.data_ptr, - static_cast(out_identity_data.dtype), - out_identity_data.shape); - out_identity.set_rowwise_scale_inv(out_identity_scale_inv.data_ptr, - static_cast(out_identity_scale_inv.dtype), - out_identity_scale_inv.shape); - out_identity.set_amax(out_identity_amax.data_ptr, - static_cast(out_identity_amax.dtype), - out_identity_amax.shape); - } - out_identity_list.emplace_back(std::move(out_identity)); - nvte_tensor_out_identity_list.push_back(out_identity_list.back().data()); - } - nvte_group_nvfp4_quantize_with_amax(input.data(), nvte_tensor_out_identity_list.data(), - split_sections.data(), num_tensors, quant_config_list[0], - stream); - } - - // Columnwise RHT quantization fusion with grouped version - if (quantizer.columnwise_usage) { - std::vector out_transpose_list; - std::vector nvte_tensor_out_transpose_list; - for (size_t i = 0; i < num_tensors; i++) { - bool is_empty_split = input_list[i].numel() == 0; - auto out_columnwise_data = output_list[i].get_columnwise_data(); - auto out_columnwise_scale_inv = output_list[i].get_columnwise_scale_inv(); - auto out_columnwise_amax = output_list[i].get_columnwise_amax(); - - // Create a wrapper for the columnwise output, as the rowwise output. Input is in transposed layout. - TensorWrapper out_transpose(output_list[i].scaling_mode()); - if (!is_empty_split) { - auto [cw_first, cw_last] = get_2d_dims(out_columnwise_data.shape, true); - std::vector colwise_data_shape_2d = {cw_first, cw_last}; - - out_transpose.set_rowwise_data(out_columnwise_data.data_ptr, - static_cast(out_columnwise_data.dtype), - colwise_data_shape_2d); - out_transpose.set_rowwise_scale_inv(out_columnwise_scale_inv.data_ptr, - static_cast(out_columnwise_scale_inv.dtype), - out_columnwise_scale_inv.shape); - out_transpose.set_amax(out_columnwise_amax.data_ptr, - static_cast(out_columnwise_amax.dtype), - out_columnwise_amax.shape); - } - out_transpose_list.emplace_back(std::move(out_transpose)); - nvte_tensor_out_transpose_list.push_back(out_transpose_list.back().data()); - } - nvte_group_hadamard_transform_cast_fusion_columnwise( - input.data(), reinterpret_cast(nvte_tensor_out_transpose_list.data()), - rht_matrix_nvte.data(), split_sections.data(), num_tensors, - quant_config_list_colwise_to_use[0], stream); - } - } + auto rht_matrix = makeTransformerEngineTensor(quantizer.rht_matrix); + auto workspace = at::empty({1}, at::device(at::kCUDA).dtype(torch::kInt32)); + auto workspace_tensor = makeTransformerEngineTensor(workspace); + nvte_group_hadamard_transform_cast_fusion_host_split( + input.data(), output_handles.data(), rht_matrix.data(), split_sections.data(), num_tensors, + configs[0], workspace_tensor.data(), stream); } - void split_quantize_nvfp4_impl_helper(const TensorWrapper &input, const std::vector &input_list, std::vector &output_list, @@ -2118,7 +1973,7 @@ void split_quantize_nvfp4_impl_helper(const TensorWrapper &input, NVTE_CHECK(amax_ptr != nullptr, "Could not find amax pointer"); output_list[i].set_amax(amax_ptr, DType::kFloat32, std::vector{1}); } - nvte_group_amax(input.data(), reinterpret_cast(nvte_tensor_output_list.data()), + nvte_group_amax_host_split(input.data(), reinterpret_cast(nvte_tensor_output_list.data()), split_sections.data(), num_tensors, stream); for (size_t i = 0; i < num_tensors; i++) { output_list[i].set_amax(orig_amax_ptr_list[i], DType::kFloat32, std::vector{1}); @@ -2188,22 +2043,21 @@ void split_quantize_nvfp4_impl(const TensorWrapper &input, // CUDA stream auto stream = at::cuda::getCurrentCUDAStream(); - // The grouped Hadamard transform kernels are implemented for the SM100 family - // only. On other architectures, where - // NVFP4Quantizer::is_eligible_for_rht_cast_fusion is false as well, quantize - // each split on its own instead. That takes the generic unfused RHT path. - const int sm = transformer_engine::cuda::sm_arch(); - const bool grouped_rht_supported = sm >= 100 && sm <= 110; - - const bool emits_gemm_swizzled_scales = + // Check each expert, not just the packed input. The grouped fusion requires + // 128-row alignment; the per-tensor path also supports 64-row splits and + // handles disabled fusion or unsupported architectures without changing RHT. + const bool grouped_rht_supported = quantizer.with_rht && std::all_of(input_list.begin(), input_list.end(), [](const auto &input) { return NVFP4Quantizer::is_eligible_for_rht_cast_fusion(get_tensor_shape(input), /*for_grouped_kernel=*/true); }); + // Per-tensor RHT quantizers own their scale conversion, including shape fallbacks. + const bool per_tensor_rht = quantizer.with_rht && !grouped_rht_supported; + const bool emits_gemm_swizzled_scales = grouped_rht_supported; std::vector needs_swizzle(num_tensors); for (size_t i = 0; i < num_tensors; ++i) { - needs_swizzle[i] = outputs[i].get_with_gemm_swizzled_scales() && !emits_gemm_swizzled_scales && + needs_swizzle[i] = !per_tensor_rht && outputs[i].get_with_gemm_swizzled_scales() && !emits_gemm_swizzled_scales && input_list[i].numel() != 0; } std::vector scale_buffers; @@ -2218,7 +2072,7 @@ void split_quantize_nvfp4_impl(const TensorWrapper &input, NVTE_CHECK(input.dtype() == DType::kBFloat16, "RHT is only supported for bfloat16 input"); if (grouped_rht_supported) { // Fuse the rowwise and colwise into one when the kernel is ready - split_quantize_nvfp4_impl_with_rht_helper(input, input_list, output_list, split_sections, + split_quantize_nvfp4_impl_with_rht_helper(input, output_list, split_sections, quantizers, stream); } else { for (size_t i = 0; i < num_tensors; ++i) { From 7ab1535f55036fe69d28f6a0841b662b38962035 Mon Sep 17 00:00:00 2001 From: Zhongbo Zhu Date: Wed, 25 Nov 2026 02:31:25 -0800 Subject: [PATCH 02/16] Format NVFP4 host-split API migration Signed-off-by: Zhongbo Zhu --- .../group_hadamard_transform.cu | 13 +++++----- ...cast_col_hadamard_transform_cast_fusion.cu | 26 +++++++++---------- .../transformer_engine/hadamard_transform.h | 7 ++--- .../pytorch/csrc/extensions/cast.cpp | 19 +++++++------- 4 files changed, 34 insertions(+), 31 deletions(-) diff --git a/transformer_engine/common/hadamard_transform/group_hadamard_transform.cu b/transformer_engine/common/hadamard_transform/group_hadamard_transform.cu index 80fe6b0be85..e9e18048c96 100644 --- a/transformer_engine/common/hadamard_transform/group_hadamard_transform.cu +++ b/transformer_engine/common/hadamard_transform/group_hadamard_transform.cu @@ -564,9 +564,9 @@ void group_hadamard_transform_amax(const Tensor& input_, std::vector& o // Although mathmatically 16 multple is enough for this function to be correct, // for this kernel, we required 64 multiple of 16 in dimension 0 for better performance. void nvte_group_hadamard_transform_amax_host_split(const NVTETensor input, NVTETensor* outputs, - const size_t* split_sections, size_t num_tensors, - int random_sign_mask, int random_sign_mask_t, - cudaStream_t stream) { + const size_t* split_sections, size_t num_tensors, + int random_sign_mask, int random_sign_mask_t, + cudaStream_t stream) { NVTE_API_CALL(nvte_group_hadamard_transform_amax_host_split); using namespace transformer_engine; if (num_tensors == 0) { @@ -585,8 +585,9 @@ void nvte_group_hadamard_transform_amax_host_split(const NVTETensor input, NVTET } // Grouped-tensor amax -void nvte_group_amax_host_split(const NVTETensor input, NVTETensor* outputs, const size_t* split_sections, - size_t num_tensors, cudaStream_t stream) { +void nvte_group_amax_host_split(const NVTETensor input, NVTETensor* outputs, + const size_t* split_sections, size_t num_tensors, + cudaStream_t stream) { NVTE_API_CALL(nvte_group_amax_host_split); using namespace transformer_engine; if (num_tensors == 0) { @@ -637,5 +638,5 @@ void nvte_group_hadamard_transform_amax(const NVTETensor input, NVTETensor* outp int random_sign_mask, int random_sign_mask_t, cudaStream_t stream) { nvte_group_hadamard_transform_amax_host_split(input, outputs, split_sections, num_tensors, - random_sign_mask, random_sign_mask_t, stream); + random_sign_mask, random_sign_mask_t, stream); } diff --git a/transformer_engine/common/hadamard_transform/group_row_cast_col_hadamard_transform_cast_fusion.cu b/transformer_engine/common/hadamard_transform/group_row_cast_col_hadamard_transform_cast_fusion.cu index 8bf3c2fd902..e86c8ae6166 100644 --- a/transformer_engine/common/hadamard_transform/group_row_cast_col_hadamard_transform_cast_fusion.cu +++ b/transformer_engine/common/hadamard_transform/group_row_cast_col_hadamard_transform_cast_fusion.cu @@ -1489,12 +1489,10 @@ void group_hadamard_transform_cast_fusion(const Tensor &input_, std::vector 0, "Number of tensors should be greater than 0."); @@ -1520,11 +1518,13 @@ void nvte_group_hadamard_transform_cast_fusion_host_split(const NVTETensor input *quant_workspace_tensor, stream); } -void nvte_group_hadamard_transform_cast_fusion( - const NVTETensor input, NVTETensor *outputs, const NVTETensor hadamard_matrix, - const size_t *split_sections, const size_t num_tensors, - const NVTEQuantizationConfig quant_config, NVTETensor quant_workspace, cudaStream_t stream) { - nvte_group_hadamard_transform_cast_fusion_host_split( - input, outputs, hadamard_matrix, split_sections, num_tensors, quant_config, quant_workspace, - stream); +void nvte_group_hadamard_transform_cast_fusion(const NVTETensor input, NVTETensor *outputs, + const NVTETensor hadamard_matrix, + const size_t *split_sections, + const size_t num_tensors, + const NVTEQuantizationConfig quant_config, + NVTETensor quant_workspace, cudaStream_t stream) { + nvte_group_hadamard_transform_cast_fusion_host_split(input, outputs, hadamard_matrix, + split_sections, num_tensors, quant_config, + quant_workspace, stream); } diff --git a/transformer_engine/common/include/transformer_engine/hadamard_transform.h b/transformer_engine/common/include/transformer_engine/hadamard_transform.h index 7cf87e115d9..00e2d4c1da6 100644 --- a/transformer_engine/common/include/transformer_engine/hadamard_transform.h +++ b/transformer_engine/common/include/transformer_engine/hadamard_transform.h @@ -96,9 +96,10 @@ void nvte_quantize_with_hadamard_transform(const NVTETensor input, NVTETensor ou * \param[in] random_sign_mask_t 16-bit sign mask for transposed RHT. * \param[in] stream CUDA stream used for the operation. */ -void nvte_group_hadamard_transform_amax_host_split( - const NVTETensor input, NVTETensor* outputs, const size_t* split_sections, size_t num_tensors, - int random_sign_mask, int random_sign_mask_t, cudaStream_t stream); +void nvte_group_hadamard_transform_amax_host_split(const NVTETensor input, NVTETensor* outputs, + const size_t* split_sections, size_t num_tensors, + int random_sign_mask, int random_sign_mask_t, + cudaStream_t stream); /*! \deprecated Use nvte_group_hadamard_transform_amax_host_split. */ void nvte_group_hadamard_transform_amax(const NVTETensor input, NVTETensor* outputs, diff --git a/transformer_engine/pytorch/csrc/extensions/cast.cpp b/transformer_engine/pytorch/csrc/extensions/cast.cpp index 4107432286c..6b446f811a9 100644 --- a/transformer_engine/pytorch/csrc/extensions/cast.cpp +++ b/transformer_engine/pytorch/csrc/extensions/cast.cpp @@ -1879,9 +1879,9 @@ void split_quantize_nvfp4_impl_with_rht_helper(const TensorWrapper &input, if (!quantizer.disable_second_level_scale) { NVTE_CHECK(quantizer.with_post_rht_amax, "NVFP4 split-quantize does not yet support pre-RHT amax"); - nvte_group_hadamard_transform_amax_host_split( - input.data(), output_handles.data(), split_sections.data(), num_tensors, 0, - quantizer.rht_matrix_random_sign_mask_t, stream); + nvte_group_hadamard_transform_amax_host_split(input.data(), output_handles.data(), + split_sections.data(), num_tensors, 0, + quantizer.rht_matrix_random_sign_mask_t, stream); } NVTE_CHECK(quantizer.rht_matrix.defined() && quantizer.rht_matrix.numel() > 0, @@ -1973,8 +1973,9 @@ void split_quantize_nvfp4_impl_helper(const TensorWrapper &input, NVTE_CHECK(amax_ptr != nullptr, "Could not find amax pointer"); output_list[i].set_amax(amax_ptr, DType::kFloat32, std::vector{1}); } - nvte_group_amax_host_split(input.data(), reinterpret_cast(nvte_tensor_output_list.data()), - split_sections.data(), num_tensors, stream); + nvte_group_amax_host_split(input.data(), + reinterpret_cast(nvte_tensor_output_list.data()), + split_sections.data(), num_tensors, stream); for (size_t i = 0; i < num_tensors; i++) { output_list[i].set_amax(orig_amax_ptr_list[i], DType::kFloat32, std::vector{1}); } @@ -2057,8 +2058,8 @@ void split_quantize_nvfp4_impl(const TensorWrapper &input, const bool emits_gemm_swizzled_scales = grouped_rht_supported; std::vector needs_swizzle(num_tensors); for (size_t i = 0; i < num_tensors; ++i) { - needs_swizzle[i] = !per_tensor_rht && outputs[i].get_with_gemm_swizzled_scales() && !emits_gemm_swizzled_scales && - input_list[i].numel() != 0; + needs_swizzle[i] = !per_tensor_rht && outputs[i].get_with_gemm_swizzled_scales() && + !emits_gemm_swizzled_scales && input_list[i].numel() != 0; } std::vector scale_buffers; auto compact_outputs = @@ -2072,8 +2073,8 @@ void split_quantize_nvfp4_impl(const TensorWrapper &input, NVTE_CHECK(input.dtype() == DType::kBFloat16, "RHT is only supported for bfloat16 input"); if (grouped_rht_supported) { // Fuse the rowwise and colwise into one when the kernel is ready - split_quantize_nvfp4_impl_with_rht_helper(input, output_list, split_sections, - quantizers, stream); + split_quantize_nvfp4_impl_with_rht_helper(input, output_list, split_sections, quantizers, + stream); } else { for (size_t i = 0; i < num_tensors; ++i) { if (input_list[i].numel() == 0) { From 40e26cdd09b1b428d62924662e507ba01d1ab6f7 Mon Sep 17 00:00:00 2001 From: Zhongbo Zhu Date: Wed, 25 Nov 2026 02:32:04 -0800 Subject: [PATCH 03/16] Add graph-safe grouped NVFP4 2D quantization with per-expert amax Signed-off-by: Zhongbo Zhu --- .../nvfp4/test_nvfp4_group_quantize_2d.py | 152 +++++++++++++++ transformer_engine/common/CMakeLists.txt | 1 + .../common/cast/dispatch/quantize.cuh | 10 +- .../cast/nvfp4/group_quantize_2d_nvfp4.cu | 175 ++++++++++++++++++ .../cast/nvfp4/group_quantize_2d_nvfp4.h | 24 +++ .../graph_safe_group_hadamard_transform.cu | 40 ++-- .../pytorch/csrc/extensions/cast.cpp | 45 ++++- 7 files changed, 430 insertions(+), 17 deletions(-) create mode 100644 tests/pytorch/nvfp4/test_nvfp4_group_quantize_2d.py create mode 100644 transformer_engine/common/cast/nvfp4/group_quantize_2d_nvfp4.cu create mode 100644 transformer_engine/common/cast/nvfp4/group_quantize_2d_nvfp4.h diff --git a/tests/pytorch/nvfp4/test_nvfp4_group_quantize_2d.py b/tests/pytorch/nvfp4/test_nvfp4_group_quantize_2d.py new file mode 100644 index 00000000000..a69c792457d --- /dev/null +++ b/tests/pytorch/nvfp4/test_nvfp4_group_quantize_2d.py @@ -0,0 +1,152 @@ +# Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# See LICENSE for license information. + +import pytest +import torch + +import transformer_engine.pytorch as te +import transformer_engine_torch as tex +from transformer_engine.pytorch import NVFP4Quantizer +from nvfp4_utils import swizzle_nvfp4_scale + +pytestmark = pytest.mark.skipif(not te.is_nvfp4_available(), reason="NVFP4 requires Blackwell") + + +def _quantizer(directions, swizzled): + q = NVFP4Quantizer(rowwise=directions[0], columnwise=directions[1], with_2d_quantization=True) + q.optimize_for_gemm = swizzled + return q + + +def _check(x, splits, grouped, directions, swizzled): + # Debug views cache host metadata. Refresh only outside graph capture/replay. + grouped.tensor_shapes = None + grouped.offsets = None + results = grouped.split_into_quantized_tensors() + reference_quantizer = _quantizer(directions, False) + start = 0 + for rows, result in zip(splits, results): + part = x[start : start + rows] + start += rows + if rows == 0: + for enabled, name in zip(directions, ("_amax_rowwise", "_amax_columnwise")): + if enabled: + assert torch.equal(getattr(result, name), torch.zeros(1, device=x.device)) + continue + reference = reference_quantizer(part) + for enabled, direction, amax_name, shape in ( + (directions[0], "rowwise", "_amax_rowwise", (rows, x.shape[1])), + (directions[1], "columnwise", "_amax_columnwise", (x.shape[1], rows)), + ): + if not enabled: + continue + assert torch.equal( + getattr(result, f"_{direction}_data").view(torch.uint8), + getattr(reference, f"_{direction}_data").view(torch.uint8), + ) + assert torch.equal(getattr(result, amax_name), getattr(reference, amax_name)) + scales = getattr(result, f"_{direction}_scale_inv").view(torch.uint8) + expected = getattr(reference, f"_{direction}_scale_inv").view(torch.uint8) + expected = expected[: shape[0], : shape[1] // 16] + if swizzled: + expected = swizzle_nvfp4_scale(shape[0], shape[1], expected, False) + assert torch.equal(scales, expected) + + +@pytest.mark.parametrize("cols", [128, 256, 384, 1024]) +@pytest.mark.parametrize("directions", [(True, True), (True, False), (False, True)]) +@pytest.mark.parametrize("swizzled", [False, True]) +@pytest.mark.parametrize("paged", [False, True]) +@pytest.mark.parametrize( + "splits", + [(128, 128, 128), (0, 0, 0), (0, 128, 256), (256, 128, 0), (128, 0, 256), (256, 384, 128)], + ids=[ + "regular", + "zero_tokens_all", + "zero_tokens_front", + "zero_tokens_end", + "zero_tokens_middle", + "uneven", + ], +) +def test_grouped_2d_bitwise(cols, directions, swizzled, paged, splits): + torch.manual_seed(32) + capacity = sum(splits) + (256 if paged else 0) + x = torch.randn(capacity, cols, device="cuda", dtype=torch.bfloat16) + # A capacity tail must not affect any expert's scalar amax or quantized values. + x[sum(splits) :] = 10000 + metadata = torch.tensor(splits, device="cuda", dtype=torch.int64) + q = _quantizer(directions, swizzled) + result = tex.group_quantize(x, q, len(splits), metadata) + _check(x, splits, result, directions, swizzled) + + +@pytest.mark.parametrize("paged", [False, True]) +@pytest.mark.parametrize("directions", [(True, True), (True, False), (False, True)]) +@pytest.mark.parametrize("swizzled", [False, True]) +def test_grouped_2d_graph_replay(paged, directions, swizzled): + x = torch.randn(512, 256, device="cuda", dtype=torch.bfloat16) + metadata = torch.tensor([128, 128, 256], device="cuda", dtype=torch.int64) + q = _quantizer(directions, swizzled) + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + tex.group_quantize(x, q, 3, metadata) + torch.cuda.current_stream().wait_stream(stream) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + output = tex.group_quantize(x, q, 3, metadata) + cases = ( + [(128, 128, 256), (256, 0, 128), (0, 0, 0), (128, 256, 128)] + if paged + else [(128, 128, 256), (256, 0, 256), (0, 384, 128), (128, 256, 128)] + ) + for splits in cases: + metadata.copy_(torch.tensor(splits, device="cuda", dtype=torch.int64)) + x.normal_() + x[sum(splits) :] = 10000 + graph.replay() + _check(x, splits, output, directions, swizzled) + + +def test_grouped_2d_noop_and_uniform_weight_reuse(): + x = torch.randn(512, 256, device="cuda", dtype=torch.bfloat16) + q = _quantizer((True, True), True) + output = tex.group_quantize(x, q, 4, None) + flag = torch.ones(1, device="cuda", dtype=torch.float32) + names = ( + "rowwise_data", + "columnwise_data", + "scale_inv", + "columnwise_scale_inv", + "amax", + "columnwise_amax", + ) + before = {name: getattr(output, name).clone() for name in names} + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + tex.group_quantize(x, q, 4, None, noop_flag=flag, output=output) + x.normal_() + graph.replay() + for name in names: + assert torch.equal(getattr(output, name), before[name]) + flag.zero_() + graph.replay() + _check(x, [128] * 4, output, (True, True), True) + + +@pytest.mark.parametrize( + "option", + [ + "with_2d_quantization", + "stochastic_rounding", + "with_amax_reduction", + "disable_second_level_scale", + ], +) +def test_grouped_2d_rejects_unsupported_recipe(option): + q = _quantizer((True, True), False) + setattr(q, option, option != "with_2d_quantization") + x = torch.zeros(256, 128, device="cuda", dtype=torch.bfloat16) + with pytest.raises(RuntimeError, match="not implemented|local per-tensor amax"): + tex.group_quantize(x, q, 2, None) diff --git a/transformer_engine/common/CMakeLists.txt b/transformer_engine/common/CMakeLists.txt index 61a8359b251..8e8a68f70c2 100644 --- a/transformer_engine/common/CMakeLists.txt +++ b/transformer_engine/common/CMakeLists.txt @@ -364,6 +364,7 @@ list(APPEND transformer_engine_cuda_arch_specific_sources cast/cast.cu cast/cast_dbias.cu cast/cast_grouped.cu + cast/nvfp4/group_quantize_2d_nvfp4.cu cast/cast_grouped_dbias.cu cast/mxfp8/requantize_mxfp8.cu fused_rope/fused_mla_kv_rope_mxfp8.cu diff --git a/transformer_engine/common/cast/dispatch/quantize.cuh b/transformer_engine/common/cast/dispatch/quantize.cuh index 999ce51f770..f677e6ac7b3 100644 --- a/transformer_engine/common/cast/dispatch/quantize.cuh +++ b/transformer_engine/common/cast/dispatch/quantize.cuh @@ -27,6 +27,7 @@ #include "../mxfp8/group_quantize_mxfp8.cuh" #include "../mxfp8/group_scaled_swiglu_mxfp8.cuh" #include "../mxfp8/quantize_mxfp8.cuh" +#include "../nvfp4/group_quantize_2d_nvfp4.h" #include "../nvfp4/group_quantize_transpose_nvfp4.cuh" #include "../nvfp4/quantize_4over6_nvfp4.cuh" #include "../nvfp4/quantize_transpose_nvfp4.cuh" @@ -582,8 +583,13 @@ void group_quantize_fwd_helper(const NVTEGroupedTensor input, NVTEGroupedTensor } case NVTE_NVFP4_1D_SCALING: { NVTE_CHECK(!IS_ACT, "IS_ACT is not implemented for grouped NVTE_NVFP4_1D_SCALING."); - NVTE_CHECK(output_tensor->row_scaled_nvfp4, - "Grouped NVFP4 quantization is only implemented for row-scaled NVFP4."); + if (!output_tensor->row_scaled_nvfp4) { + NVTE_CHECK(quant_config_cpp.nvfp4_2d_quantization, + "Per-tensor amax with 1D grouped NVFP4 quantization is not implemented."); + nvfp4::group_quantize_2d(input_tensor, noop_tensor, output_tensor, &quant_config_cpp, + stream); + break; + } NVTE_CHECK(!quant_config_cpp.stochastic_rounding, "Grouped row-scaled NVFP4 quantization does not support stochastic rounding."); NVTE_CHECK(!quant_config_cpp.nvfp4_2d_quantization, diff --git a/transformer_engine/common/cast/nvfp4/group_quantize_2d_nvfp4.cu b/transformer_engine/common/cast/nvfp4/group_quantize_2d_nvfp4.cu new file mode 100644 index 00000000000..46b88ed21d3 --- /dev/null +++ b/transformer_engine/common/cast/nvfp4/group_quantize_2d_nvfp4.cu @@ -0,0 +1,175 @@ +/************************************************************************* + * Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * See LICENSE for license information. + ************************************************************************/ +#include "../core/grouped_layout.cuh" +#include "core_nvfp4.cuh" +#include "group_quantize_2d_nvfp4.h" +#include "swizzle.cuh" + +namespace transformer_engine::dispatch::nvfp4 { +namespace { + +__global__ void validate_grouped_2d_splits(const int64_t* offsets, const int64_t* rows, + size_t count, size_t capacity, size_t cols, + const float* noop) { + if (noop && *noop == 1.0f) return; + const size_t i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= count) return; + if (rows[i] < 0 || rows[i] % 128 != 0 || offsets[i] < 0 || offsets[i + 1] < offsets[i] || + offsets[i + 1] > capacity * cols || offsets[i + 1] - offsets[i] != rows[i] * cols || + (i == 0 && offsets[0] != 0)) { + NVTE_DEVICE_ERROR( + "Grouped NVFP4 2D requires contiguous, 128-aligned expert rows within capacity."); + } +} + +#if FP4_TYPE_SUPPORTED +template +__global__ void grouped_nvfp4_2d_quantize_transpose(const bf16* input, uint8_t* row_data, + uint8_t* col_data, ScaleType* row_scales, + ScaleType* col_scales, const float* amax, + const int64_t* offsets, const int64_t* rows, + size_t count, size_t cols, bool swizzled, + const float* noop) { +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 1000 + if (noop && *noop == 1.0f) return; + const size_t global_row = blockIdx.y * 16; + if (global_row * cols >= offsets[count]) return; + const size_t expert = common::find_tensor_from_offsets(offsets, count, global_row * cols); + const size_t start = offsets[expert] / cols; + const size_t local_row = global_row - start; + const size_t col = blockIdx.x * 16; + const size_t m = rows[expert]; + const int lane_row = threadIdx.x / 4; + const int lane_col = (threadIdx.x % 4) * 4; + __shared__ bf16 tile[16][16]; + __shared__ float warp_max[2]; + alignas(8) bf16 values[4]; + float a = 0.0f; +#pragma unroll + for (int j = 0; j < 4; ++j) { + values[j] = input[(global_row + lane_row) * cols + col + lane_col + j]; + tile[lane_row][lane_col + j] = values[j]; + a = fmaxf(a, fabsf(static_cast(values[j]))); + } + for (int delta = 16; delta > 0; delta /= 2) { + a = fmaxf(a, __shfl_xor_sync(0xffffffff, a, delta)); + } + if (threadIdx.x % 32 == 0) warp_max[threadIdx.x / 32] = a; + __syncthreads(); + a = fmaxf(warp_max[0], warp_max[1]); + + // Use the same arithmetic and packed BF16 conversion as single-tensor 2D quantization. + const float encode = core::compute_global_encode_scaling_factor_FP4(amax[expert]); + const float decode = 1.0 / encode; + const ScaleType scale = core::compute_decoding_scaling_factor(a, encode); + const float inverse = + fminf(1.0f / (static_cast(scale) * decode), detail::TypeExtrema::max); + const float2 inverse2{inverse, inverse}; + const size_t scale_base = offsets[expert] / 16; + if (row_data) { + const auto packed = + ptx::mul_cvt_bf16_to_fp4_4x(*reinterpret_cast(values), inverse2, 0); + *reinterpret_cast(row_data + (global_row + lane_row) * (cols / 2) + + (col + lane_col) / 2) = packed; + if (lane_col == 0) { + const size_t r = local_row + lane_row; + const size_t c = col / 16; + const size_t index = + swizzled ? swizzle::gemm_swizzled_scale_idx(r, c, cols / 16) : r * (cols / 16) + c; + row_scales[scale_base + index] = scale; + } + } + if (col_data) { +#pragma unroll + for (int j = 0; j < 4; ++j) values[j] = tile[lane_col + j][lane_row]; + const auto packed = + ptx::mul_cvt_bf16_to_fp4_4x(*reinterpret_cast(values), inverse2, 0); + *reinterpret_cast(col_data + offsets[expert] / 2 + (col + lane_row) * (m / 2) + + (local_row + lane_col) / 2) = packed; + if (lane_col == 0) { + const size_t r = col + lane_row; + const size_t c = local_row / 16; + const size_t index = + swizzled ? swizzle::gemm_swizzled_scale_idx(r, c, m / 16) : r * (m / 16) + c; + col_scales[scale_base + index] = scale; + } + } +#else + NVTE_DEVICE_ERROR("Grouped NVFP4 2D quantization requires Blackwell."); +#endif +} +#endif +} // namespace + +void group_quantize_2d(const GroupedTensor* input, const Tensor* noop, GroupedTensor* output, + const QuantizationConfig* config, cudaStream_t stream) { +#if FP4_TYPE_SUPPORTED + NVTE_CHECK(input->dtype() == DType::kBFloat16, "Grouped NVFP4 2D requires BF16 input."); + NVTE_CHECK(input->num_tensors == output->num_tensors, "Grouped tensor counts must match."); + NVTE_CHECK(output->all_same_last_dim() || output->all_same_shape(), + "Grouped NVFP4 2D requires a common hidden dimension."); + NVTE_CHECK(!config->stochastic_rounding && config->nvfp4_4over6_mode == kNVTENVFP44Over6Disabled, + "Grouped NVFP4 2D does not support stochastic rounding or 4over6."); + CheckNoopTensor(*noop, "grouped_2d_noop"); + const size_t capacity = input->logical_shape.data[0]; + const size_t cols = input->logical_shape.data[1]; + const size_t count = input->num_tensors; + NVTE_CHECK(cols > 0 && cols % 128 == 0 && capacity % 128 == 0, + "Grouped NVFP4 2D requires 128-aligned capacity and hidden dimension."); + NVTE_CHECK(output->logical_shape.data[0] == capacity && output->logical_shape.data[1] == cols, + "Grouped NVFP4 2D input/output capacities must match."); + if (count == 0) return; + // Empty packed storage has a null pointer, but still has one amax per expert. + const bool rowwise = output->amax.has_data(); + const bool columnwise = output->columnwise_amax.has_data(); + NVTE_CHECK(rowwise || columnwise, "Missing quantized output."); + const auto validate_direction = [&](bool enabled, const SimpleTensor& data, + const SimpleTensor& scales, const SimpleTensor& amax) { + if (!enabled) return; + NVTE_CHECK(data.dtype == DType::kFloat4E2M1 && data.numel() >= capacity * cols / 2, + "Invalid grouped NVFP4 data buffer."); + NVTE_CHECK((capacity == 0 || scales.dptr) && scales.numel() >= capacity * cols / 16, + "Invalid grouped NVFP4 scale buffer."); + NVTE_CHECK(amax.dptr && amax.dtype == DType::kFloat32 && amax.numel() >= count, + "Grouped NVFP4 2D requires one FP32 amax per expert."); + }; + validate_direction(rowwise, output->data, output->scale_inv, output->amax); + validate_direction(columnwise, output->columnwise_data, output->columnwise_scale_inv, + output->columnwise_amax); + const DType scale_type = rowwise ? output->scale_inv.dtype : output->columnwise_scale_inv.dtype; + NVTE_CHECK( + !rowwise || !columnwise || output->scale_inv.dtype == output->columnwise_scale_inv.dtype, + "Grouped NVFP4 directions must use the same scale dtype."); + NVTE_CHECK(output->tensor_offsets.dtype == DType::kInt64 && + output->first_dims.dtype == DType::kInt64 && output->tensor_offsets.dptr && + output->tensor_offsets.numel() >= count + 1 && output->first_dims.dptr && + output->first_dims.numel() >= count, + "Grouped NVFP4 2D requires int64 device splits and offsets."); + if (count == 0) return; + const auto* offsets = static_cast(output->tensor_offsets.dptr); + const auto* rows = static_cast(output->first_dims.dptr); + const float* noop_ptr = static_cast(noop->data.dptr); + // Validate on device, including all-zero splits, without introducing a D2H synchronization. + validate_grouped_2d_splits<<>>(offsets, rows, count, capacity, + cols, noop_ptr); + group_hadamard_transform_amax_graph_safe(input, output, 0, 0, true, stream, noop_ptr); + if (capacity == 0) return; + const float* amax = + static_cast(rowwise ? output->amax.dptr : output->columnwise_amax.dptr); + TRANSFORMER_ENGINE_NVFP4_SCALE_TYPE_SWITCH( + scale_type, ScaleType, + grouped_nvfp4_2d_quantize_transpose + <<>>( + static_cast(input->data.dptr), static_cast(output->data.dptr), + static_cast(output->columnwise_data.dptr), + static_cast(output->scale_inv.dptr), + static_cast(output->columnwise_scale_inv.dptr), amax, offsets, rows, count, + cols, output->with_gemm_swizzled_scales, noop_ptr);); + NVTE_CHECK_CUDA(cudaGetLastError()); +#else + NVTE_ERROR("Grouped NVFP4 2D requires FP4 support in the CUDA toolkit."); +#endif +} +} // namespace transformer_engine::dispatch::nvfp4 diff --git a/transformer_engine/common/cast/nvfp4/group_quantize_2d_nvfp4.h b/transformer_engine/common/cast/nvfp4/group_quantize_2d_nvfp4.h new file mode 100644 index 00000000000..2248c376260 --- /dev/null +++ b/transformer_engine/common/cast/nvfp4/group_quantize_2d_nvfp4.h @@ -0,0 +1,24 @@ +/************************************************************************* + * Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * See LICENSE for license information. + ************************************************************************/ +#ifndef TRANSFORMER_ENGINE_GROUP_QUANTIZE_2D_NVFP4_H_ +#define TRANSFORMER_ENGINE_GROUP_QUANTIZE_2D_NVFP4_H_ + +#include "../../common.h" + +namespace transformer_engine { + +// Internal amax implementation, shared with the existing grouped RHT entry. +void group_hadamard_transform_amax_graph_safe(const GroupedTensor* input, GroupedTensor* output, + uint16_t random_sign_mask, + uint16_t random_sign_mask_t, + bool broadcast_pre_rht_amax, cudaStream_t stream, + const float* noop = nullptr); + +namespace dispatch::nvfp4 { +void group_quantize_2d(const GroupedTensor* input, const Tensor* noop, GroupedTensor* output, + const QuantizationConfig* config, cudaStream_t stream); +} +} // namespace transformer_engine +#endif diff --git a/transformer_engine/common/hadamard_transform/graph_safe_group_hadamard_transform.cu b/transformer_engine/common/hadamard_transform/graph_safe_group_hadamard_transform.cu index 0528ac0927a..f7a54942fe8 100644 --- a/transformer_engine/common/hadamard_transform/graph_safe_group_hadamard_transform.cu +++ b/transformer_engine/common/hadamard_transform/graph_safe_group_hadamard_transform.cu @@ -14,6 +14,7 @@ #include +#include "common/cast/nvfp4/group_quantize_2d_nvfp4.h" #include "common/cast/nvfp4/group_quantize_transpose_nvfp4.cuh" #include "common/common.h" #include "common/util/ptx.cuh" @@ -188,7 +189,8 @@ __device__ __forceinline__ void ReduceMax(const float pre_rht_amax, const float } __global__ void GraphSafeMultiZeroAmaxKernel(const size_t num_tensors, float* amax_rowwise_ptr, - float* amax_colwise_ptr) { + float* amax_colwise_ptr, const float* noop) { + if (noop && *noop == 1.0f) return; int tid = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; @@ -207,7 +209,9 @@ __global__ void GraphSafeMultiZeroAmaxKernel(const size_t num_tensors, float* am __global__ void GraphSafeMultiAmaxMemcpyD2DKernelPreRHT(const size_t num_tensors, float* amax_rowwise_ptr, - float* amax_colwise_ptr) { + float* amax_colwise_ptr, + const float* noop) { + if (noop && *noop == 1.0f) return; int tid = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; @@ -228,8 +232,10 @@ __global__ void GraphSafeGroupHadamardAmaxTmaKernel( uint16_t random_sign_mask_t, const ShapeRepresentation shape_rep, const size_t num_tensors, const size_t first_logical_dim, const size_t last_logical_dim, const int64_t* const __restrict__ offsets_ptr, const int64_t* const __restrict__ first_dims_ptr, - float* const __restrict__ amax_rowwise_ptr, float* const __restrict__ amax_colwise_ptr) { + float* const __restrict__ amax_rowwise_ptr, float* const __restrict__ amax_colwise_ptr, + const float* noop) { #if (defined __CUDA_ARCH__) && (__CUDA_ARCH__ >= 1000) + if (noop && *noop == 1.0f) return; float* output_pre_rht_amax_ptr; float* output_identity_amax_ptr = nullptr; @@ -244,8 +250,8 @@ __global__ void GraphSafeGroupHadamardAmaxTmaKernel( } int tensor_id = get_current_tensor_id(shape_rep, num_tensors, global_offset, first_logical_dim, last_logical_dim, offsets_ptr); - output_pre_rht_amax_ptr = static_cast(amax_rowwise_ptr) + tensor_id; - output_transpose_amax_ptr = static_cast(amax_colwise_ptr) + tensor_id; + output_pre_rht_amax_ptr = amax_rowwise_ptr ? amax_rowwise_ptr + tensor_id : nullptr; + output_transpose_amax_ptr = amax_colwise_ptr ? amax_colwise_ptr + tensor_id : nullptr; static_assert(CHUNK_DIM_Y >= BUFF_DIM_Y && CHUNK_DIM_Y % BUFF_DIM_Y == 0); static_assert(CHUNK_DIM_X >= BUFF_DIM_X && CHUNK_DIM_X % BUFF_DIM_X == 0); @@ -398,20 +404,23 @@ __global__ void GraphSafeGroupHadamardAmaxTmaKernel( void group_hadamard_transform_amax_graph_safe(const GroupedTensor* input, GroupedTensor* output, uint16_t random_sign_mask, uint16_t random_sign_mask_t, - bool broadcast_pre_rht_amax, cudaStream_t stream) { + bool broadcast_pre_rht_amax, cudaStream_t stream, + const float* noop) { NVTE_API_CALL(group_hadamard_transform_amax_graph_safe); #if CUDA_VERSION >= 12080 NVTE_CHECK(input->num_tensors == output->num_tensors, "Number of input and output tensors must be same."); - NVTE_CHECK(input->has_data(), "Cannot quantize tensor without rowwise data."); + NVTE_CHECK(input->has_data() || input->logical_shape.data[0] == 0, + "Cannot quantize tensor without rowwise data."); checkCuDriverContext(stream); - bool all_return_pre_rht_amax = output->has_data(); + bool all_return_pre_rht_amax = output->has_data() || broadcast_pre_rht_amax; // there is no rowwise RHT transform in current recipe bool all_return_identity_amax = false; - bool all_return_transposed_amax = output->has_columnwise_data(); + bool all_return_transposed_amax = + broadcast_pre_rht_amax ? output->columnwise_amax.has_data() : output->has_columnwise_data(); NVTE_CHECK(all_return_pre_rht_amax || all_return_identity_amax || all_return_transposed_amax, "At least one of return_pre_rht_amax, return_identity_amax, or return_transposed_amax " @@ -433,7 +442,9 @@ void group_hadamard_transform_amax_graph_safe(const GroupedTensor* input, Groupe NVTE_CHECK(last_logical_dim % 128 == 0, "Last dimension of a grouped tensor should be divisible by 128."); - float* const amax_rowwise_ptr = reinterpret_cast(output->amax.dptr); + float* const amax_rowwise_ptr = reinterpret_cast( + broadcast_pre_rht_amax && output->amax.dptr == nullptr ? output->columnwise_amax.dptr + : output->amax.dptr); float* const amax_colwise_ptr = reinterpret_cast(output->columnwise_amax.dptr); const int64_t* const offsets_ptr = reinterpret_cast(output->tensor_offsets.dptr); @@ -451,8 +462,9 @@ void group_hadamard_transform_amax_graph_safe(const GroupedTensor* input, Groupe dim3 block_setup_amax(kMaxTensorsPerKernel); dim3 grid_setup_amax(1); GraphSafeMultiZeroAmaxKernel<<>>( - num_tensors, amax_rowwise_ptr, amax_colwise_ptr); + num_tensors, amax_rowwise_ptr, amax_colwise_ptr, noop); NVTE_CHECK_CUDA(cudaGetLastError()); + if (first_logical_dim == 0 || num_tensors == 0) return; using IType = bf16; constexpr int kHadamardDimension = 16; @@ -529,11 +541,11 @@ void group_hadamard_transform_amax_graph_safe(const GroupedTensor* input, Groupe kernel<<>>( tensor_map_input, random_sign_mask, random_sign_mask_t, shape_rep, num_tensors, first_logical_dim, last_logical_dim, offsets_ptr, first_dims_ptr, - amax_rowwise_ptr, amax_colwise_ptr); - if (broadcast_pre_rht_amax) { + amax_rowwise_ptr, broadcast_pre_rht_amax ? nullptr : amax_colwise_ptr, noop); + if (broadcast_pre_rht_amax && amax_rowwise_ptr != amax_colwise_ptr) { GraphSafeMultiAmaxMemcpyD2DKernelPreRHT<<>>(num_tensors, amax_rowwise_ptr, - amax_colwise_ptr); + amax_colwise_ptr, noop); }))); NVTE_CHECK_CUDA(cudaGetLastError()); diff --git a/transformer_engine/pytorch/csrc/extensions/cast.cpp b/transformer_engine/pytorch/csrc/extensions/cast.cpp index 6b446f811a9..ea01c95ccf2 100644 --- a/transformer_engine/pytorch/csrc/extensions/cast.cpp +++ b/transformer_engine/pytorch/csrc/extensions/cast.cpp @@ -295,6 +295,22 @@ void group_quantize_nvfp4_row_scaled_impl(const GroupedTensorWrapper &grouped_in }); } +void group_quantize_nvfp4_2d_impl(const GroupedTensorWrapper &input, GroupedTensorWrapper &output, + const NVFP4Quantizer *quantizer, + const std::optional &noop, cudaStream_t stream) { + NVTE_CHECK(quantizer->with_2d_quantization, + "Per-tensor amax with 1D grouped NVFP4 quantization is not implemented."); + NVTE_CHECK(!quantizer->stochastic_rounding && !quantizer->with_amax_reduction && + !quantizer->disable_second_level_scale && + quantizer->nvfp4_4over6_mode == kNVTENVFP44Over6Disabled, + "Grouped NVFP4 2D requires local per-tensor amax and deterministic rounding."); + QuantizationConfigWrapper config; + config.set_nvfp4_2d_quantization(true); + if (noop.has_value()) config.set_noop_tensor(noop->data()); + config.set_use_fast_math(transformer_engine::getenv("NVTE_USE_FAST_MATH")); + NVTE_SCOPED_GIL_RELEASE({ nvte_group_quantize(input.data(), output.data(), config, stream); }); +} + float fp8_max_for_dtype(const DType dtype) { if (!is_fp8_dtype(dtype)) { NVTE_ERROR("Expected FP8 dtype for grouped current-scaling quantization, got ", @@ -390,6 +406,29 @@ py::object group_quantize(const at::Tensor &input, py::handle quantizer, const s const bool row_scaled_nvfp4 = detail::IsNVFP4Quantizers(quantizer.ptr()) && static_cast(quantizer_cpp.get())->row_scaled_nvfp4; + const bool per_tensor_nvfp4 = detail::IsNVFP4Quantizers(quantizer.ptr()) && !row_scaled_nvfp4 && + !static_cast(quantizer_cpp.get())->with_rht; + if (per_tensor_nvfp4) { + const auto *q = static_cast(quantizer_cpp.get()); + NVTE_CHECK(q->with_2d_quantization, + "Per-tensor amax with 1D grouped NVFP4 quantization is not implemented."); + NVTE_CHECK(!q->stochastic_rounding && !q->with_amax_reduction && + !q->disable_second_level_scale && + q->nvfp4_4over6_mode == kNVTENVFP44Over6Disabled, + "Grouped NVFP4 2D requires local per-tensor amax and deterministic rounding."); + NVTE_CHECK(!last_dims.has_value(), "Grouped NVFP4 2D requires a common hidden dimension."); + if (first_dims.has_value()) { + NVTE_CHECK(first_dims->is_cuda() && first_dims->is_contiguous() && + first_dims->scalar_type() == at::kLong && first_dims->numel() == num_tensors, + "Grouped NVFP4 2D requires contiguous int64 CUDA first_dims."); + } else if (output.is_none()) { + NVTE_CHECK(num_tensors > 0 && logical_first_dim % (num_tensors * 128) == 0, + "Uniform grouped NVFP4 2D requires 128-aligned expert rows."); + first_dims = at::full({static_cast(num_tensors)}, + static_cast(logical_first_dim / num_tensors), + tensor.options().dtype(at::kLong)); + } + } if (row_scaled_nvfp4) { NVTE_CHECK(output.is_none(), "group_quantize: output reuse is not supported with row-scaled NVFP4."); @@ -466,7 +505,7 @@ py::object group_quantize(const at::Tensor &input, py::handle quantizer, const s grouped_quantization_mode = GroupedQuantizationMode::FP8_BLOCKWISE_GROUPED_QUANTIZE; } - if (empty_input_buffer) { + if (empty_input_buffer && !per_tensor_nvfp4) { // early return for empty input buffer // just return the output tensor as is // no need to quantize @@ -483,6 +522,10 @@ py::object group_quantize(const at::Tensor &input, py::handle quantizer, const s group_quantize_nvfp4_row_scaled_impl(grouped_input_tensor, grouped_output_tensor_cpp, nvfp4_quantizer_cpp, noop_flag_cpp, at::cuda::getCurrentCUDAStream()); + } else if (per_tensor_nvfp4) { + group_quantize_nvfp4_2d_impl(grouped_input_tensor, grouped_output_tensor_cpp, + nvfp4_quantizer_cpp, noop_flag_cpp, + at::cuda::getCurrentCUDAStream()); } else { group_quantize_nvfp4_impl(grouped_input_tensor, grouped_output_tensor_cpp, nvfp4_quantizer_cpp, at::cuda::getCurrentCUDAStream(), From 1d98ca76779fe213458bbd1261ba412db89590fa Mon Sep 17 00:00:00 2001 From: Zhongbo Zhu Date: Wed, 25 Nov 2026 02:35:38 -0800 Subject: [PATCH 04/16] Document grouped 2D contract and add common API oracle test Signed-off-by: Zhongbo Zhu --- tests/cpp/operator/CMakeLists.txt | 1 + .../operator/test_cast_nvfp4_grouped_2d.cu | 105 ++++++++++++++++++ .../nvfp4/test_nvfp4_group_quantize_2d.py | 4 + .../cast/nvfp4/group_quantize_2d_nvfp4.cu | 4 +- .../common/include/transformer_engine/cast.h | 9 +- 5 files changed, 120 insertions(+), 3 deletions(-) create mode 100644 tests/cpp/operator/test_cast_nvfp4_grouped_2d.cu diff --git a/tests/cpp/operator/CMakeLists.txt b/tests/cpp/operator/CMakeLists.txt index 84c2ed20552..4671d3dfa77 100644 --- a/tests/cpp/operator/CMakeLists.txt +++ b/tests/cpp/operator/CMakeLists.txt @@ -16,6 +16,7 @@ add_executable(test_operator test_cast_mxfp8_grouped.cu test_cast_mxfp8_grouped_scaled_swiglu.cu test_cast_nvfp4_transpose.cu + test_cast_nvfp4_grouped_2d.cu test_row_scaled_nvfp4_grouped_amax.cu test_row_scaled_nvfp4_grouped_cast.cu test_cast_float8blockwise.cu diff --git a/tests/cpp/operator/test_cast_nvfp4_grouped_2d.cu b/tests/cpp/operator/test_cast_nvfp4_grouped_2d.cu new file mode 100644 index 00000000000..e2f832f27c7 --- /dev/null +++ b/tests/cpp/operator/test_cast_nvfp4_grouped_2d.cu @@ -0,0 +1,105 @@ +/************************************************************************* + * Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * See LICENSE for license information. + ************************************************************************/ +#include +#include +#include + +#include +#include +#include + +#include "../test_common.h" + +using namespace transformer_engine; +using namespace test; + +class NVFP4Grouped2D : public ::testing::TestWithParam {}; + +TEST_P(NVFP4Grouped2D, MatchesSingleTensorWithEmptyExpertAndCapacityTail) { + if (getDeviceComputeCapability() < blackwellComputeCapability) GTEST_SKIP(); + constexpr size_t capacity = 512, k = 128, count = 3; + const bool rowwise = GetParam() != 2; + const bool columnwise = GetParam() != 1; + const std::vector rows{128, 0, 256}; + const std::vector offsets{0, 128 * k, 128 * k, 384 * k}; + Tensor source("source", {capacity, k}, DType::kBFloat16); + auto* host = source.rowwise_cpu_dptr(); + for (size_t i = 0; i < capacity * k; ++i) { + host[i] = bf16(i < 384 * k ? (static_cast(i % 97) - 48) * 0.125f : 10000.0f); + } + source.from_cpu(); + auto device_rows = cuda_alloc(rows.size() * sizeof(int64_t)); + auto device_offsets = cuda_alloc(offsets.size() * sizeof(int64_t)); + NVTE_CHECK_CUDA(cudaMemcpy(device_rows.get(), rows.data(), rows.size() * sizeof(int64_t), + cudaMemcpyHostToDevice)); + NVTE_CHECK_CUDA(cudaMemcpy(device_offsets.get(), offsets.data(), offsets.size() * sizeof(int64_t), + cudaMemcpyHostToDevice)); + auto data_r = cuda_alloc(capacity * k / 2); + auto data_c = cuda_alloc(capacity * k / 2); + auto scale_r = cuda_alloc(capacity * k / 16); + auto scale_c = cuda_alloc(capacity * k / 16); + auto amax_r = cuda_alloc(count * sizeof(float)); + auto amax_c = cuda_alloc(count * sizeof(float)); + GroupedTensorWrapper input(count, {capacity, k}); + input.set_rowwise_data(source.rowwise_dptr(), DType::kBFloat16, {capacity, k}); + GroupedTensorWrapper output(count, {capacity, k}, NVTE_NVFP4_1D_SCALING); + output.set_first_dims(device_rows.get(), DType::kInt64, {count}); + output.set_tensor_offsets(device_offsets.get(), DType::kInt64, {count + 1}); + if (rowwise) { + output.set_rowwise_data(data_r.get(), DType::kFloat4E2M1, {capacity, k}); + output.set_rowwise_scale_inv(scale_r.get(), DType::kFloat8E4M3, {capacity, k / 16}); + output.set_amax(amax_r.get(), DType::kFloat32, {count}); + } + if (columnwise) { + output.set_columnwise_data(data_c.get(), DType::kFloat4E2M1, {k, capacity}); + output.set_columnwise_scale_inv(scale_c.get(), DType::kFloat8E4M3, {k, capacity / 16}); + output.set_columnwise_amax(amax_c.get(), DType::kFloat32, {count}); + } + QuantizationConfigWrapper config; + config.set_nvfp4_2d_quantization(true); + nvte_group_quantize(input.data(), output.data(), config, 0); + NVTE_CHECK_CUDA(cudaDeviceSynchronize()); + for (size_t i = 0; i < count; ++i) { + if (rows[i] == 0) { + float amax; + if (rowwise) { + NVTE_CHECK_CUDA(cudaMemcpy(&amax, amax_r.get() + i, sizeof(float), cudaMemcpyDeviceToHost)); + EXPECT_EQ(amax, 0.0f); + } + if (columnwise) { + NVTE_CHECK_CUDA(cudaMemcpy(&amax, amax_c.get() + i, sizeof(float), cudaMemcpyDeviceToHost)); + EXPECT_EQ(amax, 0.0f); + } + continue; + } + const size_t m = rows[i]; + Tensor expert("expert", {m, k}, DType::kBFloat16); + std::copy_n(host + offsets[i], m * k, expert.rowwise_cpu_dptr()); + expert.from_cpu(); + Tensor reference("reference", {m, k}, DType::kFloat4E2M1, true, true, NVTE_NVFP4_1D_SCALING); + nvte_compute_amax(expert.data(), reference.data(), 0); + nvte_quantize_v2(expert.data(), reference.data(), config, 0); + NVTE_CHECK_CUDA(cudaDeviceSynchronize()); + reference.to_cpu(); + for (bool col : {false, true}) { + if (col ? !columnwise : !rowwise) continue; + std::vector actual(m * k / 2), scales(m * k / 16); + NVTE_CHECK_CUDA(cudaMemcpy(actual.data(), + (col ? data_c.get() : data_r.get()) + offsets[i] / 2, + actual.size(), cudaMemcpyDeviceToHost)); + NVTE_CHECK_CUDA(cudaMemcpy(scales.data(), + (col ? scale_c.get() : scale_r.get()) + offsets[i] / 16, + scales.size(), cudaMemcpyDeviceToHost)); + const auto* expected = + col ? reference.columnwise_cpu_dptr() : reference.rowwise_cpu_dptr(); + const auto* expected_scales = col ? reference.columnwise_cpu_scale_inv_ptr() + : reference.rowwise_cpu_scale_inv_ptr(); + EXPECT_EQ(std::memcmp(actual.data(), expected, actual.size()), 0); + EXPECT_EQ(std::memcmp(scales.data(), expected_scales, scales.size()), 0); + } + } +} + +INSTANTIATE_TEST_SUITE_P(Directions, NVFP4Grouped2D, ::testing::Values(0, 1, 2)); diff --git a/tests/pytorch/nvfp4/test_nvfp4_group_quantize_2d.py b/tests/pytorch/nvfp4/test_nvfp4_group_quantize_2d.py index a69c792457d..bbd4173e752 100644 --- a/tests/pytorch/nvfp4/test_nvfp4_group_quantize_2d.py +++ b/tests/pytorch/nvfp4/test_nvfp4_group_quantize_2d.py @@ -73,6 +73,10 @@ def test_grouped_2d_bitwise(cols, directions, swizzled, paged, splits): torch.manual_seed(32) capacity = sum(splits) + (256 if paged else 0) x = torch.randn(capacity, cols, device="cuda", dtype=torch.bfloat16) + start = 0 + for expert, rows in enumerate(splits): + x[start : start + rows].mul_(16.0 ** (expert - 1)) + start += rows # A capacity tail must not affect any expert's scalar amax or quantized values. x[sum(splits) :] = 10000 metadata = torch.tensor(splits, device="cuda", dtype=torch.int64) diff --git a/transformer_engine/common/cast/nvfp4/group_quantize_2d_nvfp4.cu b/transformer_engine/common/cast/nvfp4/group_quantize_2d_nvfp4.cu index 46b88ed21d3..6f57ecad861 100644 --- a/transformer_engine/common/cast/nvfp4/group_quantize_2d_nvfp4.cu +++ b/transformer_engine/common/cast/nvfp4/group_quantize_2d_nvfp4.cu @@ -128,7 +128,8 @@ void group_quantize_2d(const GroupedTensor* input, const Tensor* noop, GroupedTe const auto validate_direction = [&](bool enabled, const SimpleTensor& data, const SimpleTensor& scales, const SimpleTensor& amax) { if (!enabled) return; - NVTE_CHECK(data.dtype == DType::kFloat4E2M1 && data.numel() >= capacity * cols / 2, + NVTE_CHECK(data.dtype == DType::kFloat4E2M1 && (capacity == 0 || data.dptr) && + data.numel() >= capacity * cols / 2, "Invalid grouped NVFP4 data buffer."); NVTE_CHECK((capacity == 0 || scales.dptr) && scales.numel() >= capacity * cols / 16, "Invalid grouped NVFP4 scale buffer."); @@ -147,7 +148,6 @@ void group_quantize_2d(const GroupedTensor* input, const Tensor* noop, GroupedTe output->tensor_offsets.numel() >= count + 1 && output->first_dims.dptr && output->first_dims.numel() >= count, "Grouped NVFP4 2D requires int64 device splits and offsets."); - if (count == 0) return; const auto* offsets = static_cast(output->tensor_offsets.dptr); const auto* rows = static_cast(output->first_dims.dptr); const float* noop_ptr = static_cast(noop->data.dptr); diff --git a/transformer_engine/common/include/transformer_engine/cast.h b/transformer_engine/common/include/transformer_engine/cast.h index b29332276b9..6fb3750a67c 100644 --- a/transformer_engine/common/include/transformer_engine/cast.h +++ b/transformer_engine/common/include/transformer_engine/cast.h @@ -93,7 +93,14 @@ void nvte_quantize(const NVTETensor input, NVTETensor output, cudaStream_t strea * The type of quantized tensor in the output depends on the scaling mode of the output * tensor. See file level comments. * For grouped tensors with a varying last dimension, the last dimension must be a multiple of 128. - * NVFP4 output requires row scaling, BF16 input, and dimensions that are multiples of 128. + * NVFP4 output supports row-scaled 1D quantization, or per-expert scalar amax with + * nvfp4_2d_quantization enabled (16x16 blocks). Both require BF16 input, a common + * hidden dimension divisible by 128, and each expert's row count divisible by 128. + * Zero-row experts and unused capacity tails are allowed. The per-tensor 2D path + * computes amax internally, supports either output direction and GEMM-swizzled scales, + * and honors noop across both amax and quantization. It requires device int64 + * first_dims and tensor_offsets; stochastic rounding and 4over6 are not supported. + * Per-tensor amax with ordinary 1D grouped NVFP4 is not implemented. * * \param[in] input Input grouped tensor to be cast. * \param[in,out] output Output grouped tensor. From 0ca25e6442e96d5175f7f19b2d35dbf6e8568603 Mon Sep 17 00:00:00 2001 From: Zhongbo Zhu Date: Wed, 25 Nov 2026 02:37:16 -0800 Subject: [PATCH 05/16] Fix grouped 2D CUDA launch dimension type Signed-off-by: Zhongbo Zhu --- .../common/cast/nvfp4/group_quantize_2d_nvfp4.cu | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/transformer_engine/common/cast/nvfp4/group_quantize_2d_nvfp4.cu b/transformer_engine/common/cast/nvfp4/group_quantize_2d_nvfp4.cu index 6f57ecad861..bb2618491a1 100644 --- a/transformer_engine/common/cast/nvfp4/group_quantize_2d_nvfp4.cu +++ b/transformer_engine/common/cast/nvfp4/group_quantize_2d_nvfp4.cu @@ -152,8 +152,8 @@ void group_quantize_2d(const GroupedTensor* input, const Tensor* noop, GroupedTe const auto* rows = static_cast(output->first_dims.dptr); const float* noop_ptr = static_cast(noop->data.dptr); // Validate on device, including all-zero splits, without introducing a D2H synchronization. - validate_grouped_2d_splits<<>>(offsets, rows, count, capacity, - cols, noop_ptr); + validate_grouped_2d_splits<<>>( + offsets, rows, count, capacity, cols, noop_ptr); group_hadamard_transform_amax_graph_safe(input, output, 0, 0, true, stream, noop_ptr); if (capacity == 0) return; const float* amax = From df333ee8167342a2c554afd14e9bca9622d7be47 Mon Sep 17 00:00:00 2001 From: Zhongbo Zhu Date: Wed, 25 Nov 2026 02:39:02 -0800 Subject: [PATCH 06/16] Flatten grouped CUDA grids for large single-weight capacities Signed-off-by: Zhongbo Zhu --- tests/pytorch/nvfp4/test_nvfp4_group_quantize_2d.py | 10 ++++++++++ .../common/cast/nvfp4/group_quantize_2d_nvfp4.cu | 6 +++--- .../graph_safe_group_hadamard_transform.cu | 11 +++++++---- 3 files changed, 20 insertions(+), 7 deletions(-) diff --git a/tests/pytorch/nvfp4/test_nvfp4_group_quantize_2d.py b/tests/pytorch/nvfp4/test_nvfp4_group_quantize_2d.py index bbd4173e752..1aeeb651247 100644 --- a/tests/pytorch/nvfp4/test_nvfp4_group_quantize_2d.py +++ b/tests/pytorch/nvfp4/test_nvfp4_group_quantize_2d.py @@ -139,6 +139,16 @@ def test_grouped_2d_noop_and_uniform_weight_reuse(): _check(x, [128] * 4, output, (True, True), True) +def test_grouped_2d_large_capacity_grid(): + # A flattened weight/capacity buffer can exceed CUDA's 65535-block grid.y limit. + x = torch.full((4194304, 128), 10000, device="cuda", dtype=torch.bfloat16) + x[:128].normal_() + splits = torch.tensor([128, 0], device="cuda", dtype=torch.int64) + q = _quantizer((True, True), False) + result = tex.group_quantize(x, q, 2, splits) + _check(x, [128, 0], result, (True, True), False) + + @pytest.mark.parametrize( "option", [ diff --git a/transformer_engine/common/cast/nvfp4/group_quantize_2d_nvfp4.cu b/transformer_engine/common/cast/nvfp4/group_quantize_2d_nvfp4.cu index bb2618491a1..a8f1e02b382 100644 --- a/transformer_engine/common/cast/nvfp4/group_quantize_2d_nvfp4.cu +++ b/transformer_engine/common/cast/nvfp4/group_quantize_2d_nvfp4.cu @@ -34,12 +34,12 @@ __global__ void grouped_nvfp4_2d_quantize_transpose(const bf16* input, uint8_t* const float* noop) { #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 1000 if (noop && *noop == 1.0f) return; - const size_t global_row = blockIdx.y * 16; + const size_t global_row = (static_cast(blockIdx.x) / (cols / 16)) * 16; if (global_row * cols >= offsets[count]) return; const size_t expert = common::find_tensor_from_offsets(offsets, count, global_row * cols); const size_t start = offsets[expert] / cols; const size_t local_row = global_row - start; - const size_t col = blockIdx.x * 16; + const size_t col = (blockIdx.x % (cols / 16)) * 16; const size_t m = rows[expert]; const int lane_row = threadIdx.x / 4; const int lane_col = (threadIdx.x % 4) * 4; @@ -161,7 +161,7 @@ void group_quantize_2d(const GroupedTensor* input, const Tensor* noop, GroupedTe TRANSFORMER_ENGINE_NVFP4_SCALE_TYPE_SWITCH( scale_type, ScaleType, grouped_nvfp4_2d_quantize_transpose - <<>>( + <<>>( static_cast(input->data.dptr), static_cast(output->data.dptr), static_cast(output->columnwise_data.dptr), static_cast(output->scale_inv.dptr), diff --git a/transformer_engine/common/hadamard_transform/graph_safe_group_hadamard_transform.cu b/transformer_engine/common/hadamard_transform/graph_safe_group_hadamard_transform.cu index f7a54942fe8..0da89c8381f 100644 --- a/transformer_engine/common/hadamard_transform/graph_safe_group_hadamard_transform.cu +++ b/transformer_engine/common/hadamard_transform/graph_safe_group_hadamard_transform.cu @@ -242,7 +242,10 @@ __global__ void GraphSafeGroupHadamardAmaxTmaKernel( float* output_transpose_amax_ptr; // calculate the global offset to get tensor id - size_t global_offset = blockIdx.y * CHUNK_DIM_Y * last_logical_dim; + const size_t tiles_x = DIVUP(last_logical_dim, size_t{CHUNK_DIM_X}); + const size_t tile_x = blockIdx.x % tiles_x; + const size_t tile_y = blockIdx.x / tiles_x; + size_t global_offset = tile_y * CHUNK_DIM_Y * last_logical_dim; // paged stashing: will have input buffer [M, N], where M is larger than sum(first_dims) // also need to early return if this CTA is processing a region larger than the last offsets[num_tensors] if (global_offset >= offsets_ptr[num_tensors]) { @@ -261,8 +264,8 @@ __global__ void GraphSafeGroupHadamardAmaxTmaKernel( constexpr int kNumWarps = (THREADS_PER_CHUNK * THREADS_PER_Y) / kThreadsPerWarp; - const int input_block_offset_Y = blockIdx.y * CHUNK_DIM_Y; - const int input_block_offset_X = blockIdx.x * CHUNK_DIM_X; + const int input_block_offset_Y = tile_y * CHUNK_DIM_Y; + const int input_block_offset_X = tile_x * CHUNK_DIM_X; extern __shared__ __align__(128) char dynamic_shmem[]; uintptr_t base_shmem_ptr = reinterpret_cast(dynamic_shmem); @@ -494,7 +497,7 @@ void group_hadamard_transform_amax_graph_safe(const GroupedTensor* input, Groupe constexpr uint64_t kNumWarps = kThreadBlockX * kThreadBlockY; dim3 block(kThreadBlockX * kThreadsPerWarp, kThreadBlockY); - dim3 grid(DIVUP(last_logical_dim, kChunkBlockXSmall), + dim3 grid(DIVUP(last_logical_dim, kChunkBlockXSmall) * DIVUP(first_logical_dim, kChunkBlockYSmall)); ShapeRepresentation shape_rep = ShapeRepresentation::VARYING_FIRST_DIM; From 5f82d7a92b05912e7c70603c90684320f2ea4649 Mon Sep 17 00:00:00 2001 From: Zhongbo Zhu Date: Wed, 25 Nov 2026 02:41:35 -0800 Subject: [PATCH 07/16] Tile grouped 2D quantization and fix common test shape constructors Signed-off-by: Zhongbo Zhu --- .../operator/test_cast_nvfp4_grouped_2d.cu | 31 ++++---- .../cast/nvfp4/group_quantize_2d_nvfp4.cu | 78 ++++++++++--------- 2 files changed, 58 insertions(+), 51 deletions(-) diff --git a/tests/cpp/operator/test_cast_nvfp4_grouped_2d.cu b/tests/cpp/operator/test_cast_nvfp4_grouped_2d.cu index e2f832f27c7..53bd9844c96 100644 --- a/tests/cpp/operator/test_cast_nvfp4_grouped_2d.cu +++ b/tests/cpp/operator/test_cast_nvfp4_grouped_2d.cu @@ -24,7 +24,7 @@ TEST_P(NVFP4Grouped2D, MatchesSingleTensorWithEmptyExpertAndCapacityTail) { const bool columnwise = GetParam() != 1; const std::vector rows{128, 0, 256}; const std::vector offsets{0, 128 * k, 128 * k, 384 * k}; - Tensor source("source", {capacity, k}, DType::kBFloat16); + Tensor source("source", std::vector{capacity, k}, DType::kBFloat16); auto* host = source.rowwise_cpu_dptr(); for (size_t i = 0; i < capacity * k; ++i) { host[i] = bf16(i < 384 * k ? (static_cast(i % 97) - 48) * 0.125f : 10000.0f); @@ -42,20 +42,22 @@ TEST_P(NVFP4Grouped2D, MatchesSingleTensorWithEmptyExpertAndCapacityTail) { auto scale_c = cuda_alloc(capacity * k / 16); auto amax_r = cuda_alloc(count * sizeof(float)); auto amax_c = cuda_alloc(count * sizeof(float)); - GroupedTensorWrapper input(count, {capacity, k}); - input.set_rowwise_data(source.rowwise_dptr(), DType::kBFloat16, {capacity, k}); - GroupedTensorWrapper output(count, {capacity, k}, NVTE_NVFP4_1D_SCALING); - output.set_first_dims(device_rows.get(), DType::kInt64, {count}); - output.set_tensor_offsets(device_offsets.get(), DType::kInt64, {count + 1}); + GroupedTensorWrapper input(count, std::vector{capacity, k}); + input.set_rowwise_data(source.rowwise_dptr(), DType::kBFloat16, std::vector{capacity, k}); + GroupedTensorWrapper output(count, std::vector{capacity, k}, NVTE_NVFP4_1D_SCALING); + output.set_first_dims(device_rows.get(), DType::kInt64, std::vector{count}); + output.set_tensor_offsets(device_offsets.get(), DType::kInt64, std::vector{count + 1}); if (rowwise) { - output.set_rowwise_data(data_r.get(), DType::kFloat4E2M1, {capacity, k}); - output.set_rowwise_scale_inv(scale_r.get(), DType::kFloat8E4M3, {capacity, k / 16}); - output.set_amax(amax_r.get(), DType::kFloat32, {count}); + output.set_rowwise_data(data_r.get(), DType::kFloat4E2M1, std::vector{capacity, k}); + output.set_rowwise_scale_inv(scale_r.get(), DType::kFloat8E4M3, + std::vector{capacity, k / 16}); + output.set_amax(amax_r.get(), DType::kFloat32, std::vector{count}); } if (columnwise) { - output.set_columnwise_data(data_c.get(), DType::kFloat4E2M1, {k, capacity}); - output.set_columnwise_scale_inv(scale_c.get(), DType::kFloat8E4M3, {k, capacity / 16}); - output.set_columnwise_amax(amax_c.get(), DType::kFloat32, {count}); + output.set_columnwise_data(data_c.get(), DType::kFloat4E2M1, std::vector{k, capacity}); + output.set_columnwise_scale_inv(scale_c.get(), DType::kFloat8E4M3, + std::vector{k, capacity / 16}); + output.set_columnwise_amax(amax_c.get(), DType::kFloat32, std::vector{count}); } QuantizationConfigWrapper config; config.set_nvfp4_2d_quantization(true); @@ -75,10 +77,11 @@ TEST_P(NVFP4Grouped2D, MatchesSingleTensorWithEmptyExpertAndCapacityTail) { continue; } const size_t m = rows[i]; - Tensor expert("expert", {m, k}, DType::kBFloat16); + Tensor expert("expert", std::vector{m, k}, DType::kBFloat16); std::copy_n(host + offsets[i], m * k, expert.rowwise_cpu_dptr()); expert.from_cpu(); - Tensor reference("reference", {m, k}, DType::kFloat4E2M1, true, true, NVTE_NVFP4_1D_SCALING); + Tensor reference("reference", std::vector{m, k}, DType::kFloat4E2M1, true, true, + NVTE_NVFP4_1D_SCALING); nvte_compute_amax(expert.data(), reference.data(), 0); nvte_quantize_v2(expert.data(), reference.data(), config, 0); NVTE_CHECK_CUDA(cudaDeviceSynchronize()); diff --git a/transformer_engine/common/cast/nvfp4/group_quantize_2d_nvfp4.cu b/transformer_engine/common/cast/nvfp4/group_quantize_2d_nvfp4.cu index a8f1e02b382..bd745df84c6 100644 --- a/transformer_engine/common/cast/nvfp4/group_quantize_2d_nvfp4.cu +++ b/transformer_engine/common/cast/nvfp4/group_quantize_2d_nvfp4.cu @@ -34,31 +34,33 @@ __global__ void grouped_nvfp4_2d_quantize_transpose(const bf16* input, uint8_t* const float* noop) { #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 1000 if (noop && *noop == 1.0f) return; - const size_t global_row = (static_cast(blockIdx.x) / (cols / 16)) * 16; + const size_t global_row = (static_cast(blockIdx.x) / (cols / 128)) * 32; if (global_row * cols >= offsets[count]) return; const size_t expert = common::find_tensor_from_offsets(offsets, count, global_row * cols); const size_t start = offsets[expert] / cols; const size_t local_row = global_row - start; - const size_t col = (blockIdx.x % (cols / 16)) * 16; + // Each half-warp owns one 16x16 scale block; a CTA covers a 32x128 tile. + const int scale_block = threadIdx.x / 16; + const int block_row = (scale_block / 8) * 16; + const int block_col = (scale_block % 8) * 16; + const int lane = threadIdx.x % 16; + const size_t col = (blockIdx.x % (cols / 128)) * 128 + block_col; const size_t m = rows[expert]; - const int lane_row = threadIdx.x / 4; - const int lane_col = (threadIdx.x % 4) * 4; - __shared__ bf16 tile[16][16]; - __shared__ float warp_max[2]; - alignas(8) bf16 values[4]; + __shared__ bf16 tile[32][129]; + alignas(16) bf16 values[16]; + const bf16* source = input + (global_row + block_row + lane) * cols + col; + reinterpret_cast(values)[0] = reinterpret_cast(source)[0]; + reinterpret_cast(values)[1] = reinterpret_cast(source)[1]; float a = 0.0f; #pragma unroll - for (int j = 0; j < 4; ++j) { - values[j] = input[(global_row + lane_row) * cols + col + lane_col + j]; - tile[lane_row][lane_col + j] = values[j]; + for (int j = 0; j < 16; ++j) { + tile[block_row + lane][block_col + j] = values[j]; a = fmaxf(a, fabsf(static_cast(values[j]))); } - for (int delta = 16; delta > 0; delta /= 2) { - a = fmaxf(a, __shfl_xor_sync(0xffffffff, a, delta)); + for (int delta = 8; delta > 0; delta /= 2) { + a = fmaxf(a, __shfl_xor_sync(0xffffffff, a, delta, 16)); } - if (threadIdx.x % 32 == 0) warp_max[threadIdx.x / 32] = a; - __syncthreads(); - a = fmaxf(warp_max[0], warp_max[1]); + __syncwarp(); // Use the same arithmetic and packed BF16 conversion as single-tensor 2D quantization. const float encode = core::compute_global_encode_scaling_factor_FP4(amax[expert]); @@ -69,32 +71,34 @@ __global__ void grouped_nvfp4_2d_quantize_transpose(const bf16* input, uint8_t* const float2 inverse2{inverse, inverse}; const size_t scale_base = offsets[expert] / 16; if (row_data) { - const auto packed = - ptx::mul_cvt_bf16_to_fp4_4x(*reinterpret_cast(values), inverse2, 0); - *reinterpret_cast(row_data + (global_row + lane_row) * (cols / 2) + - (col + lane_col) / 2) = packed; - if (lane_col == 0) { - const size_t r = local_row + lane_row; - const size_t c = col / 16; - const size_t index = - swizzled ? swizzle::gemm_swizzled_scale_idx(r, c, cols / 16) : r * (cols / 16) + c; - row_scales[scale_base + index] = scale; +#pragma unroll + for (int p = 0; p < 4; ++p) { + const auto packed = ptx::mul_cvt_bf16_to_fp4_4x( + *reinterpret_cast(values + 4 * p), inverse2, 0); + *reinterpret_cast(row_data + (global_row + block_row + lane) * (cols / 2) + + col / 2 + 2 * p) = packed; } + const size_t r = local_row + block_row + lane; + const size_t c = col / 16; + const size_t index = + swizzled ? swizzle::gemm_swizzled_scale_idx(r, c, cols / 16) : r * (cols / 16) + c; + row_scales[scale_base + index] = scale; } if (col_data) { #pragma unroll - for (int j = 0; j < 4; ++j) values[j] = tile[lane_col + j][lane_row]; - const auto packed = - ptx::mul_cvt_bf16_to_fp4_4x(*reinterpret_cast(values), inverse2, 0); - *reinterpret_cast(col_data + offsets[expert] / 2 + (col + lane_row) * (m / 2) + - (local_row + lane_col) / 2) = packed; - if (lane_col == 0) { - const size_t r = col + lane_row; - const size_t c = local_row / 16; - const size_t index = - swizzled ? swizzle::gemm_swizzled_scale_idx(r, c, m / 16) : r * (m / 16) + c; - col_scales[scale_base + index] = scale; + for (int p = 0; p < 4; ++p) { +#pragma unroll + for (int j = 0; j < 4; ++j) values[j] = tile[block_row + 4 * p + j][block_col + lane]; + const auto packed = ptx::mul_cvt_bf16_to_fp4_4x( + *reinterpret_cast(values), inverse2, 0); + *reinterpret_cast(col_data + offsets[expert] / 2 + (col + lane) * (m / 2) + + (local_row + block_row) / 2 + 2 * p) = packed; } + const size_t r = col + lane; + const size_t c = (local_row + block_row) / 16; + const size_t index = + swizzled ? swizzle::gemm_swizzled_scale_idx(r, c, m / 16) : r * (m / 16) + c; + col_scales[scale_base + index] = scale; } #else NVTE_DEVICE_ERROR("Grouped NVFP4 2D quantization requires Blackwell."); @@ -161,7 +165,7 @@ void group_quantize_2d(const GroupedTensor* input, const Tensor* noop, GroupedTe TRANSFORMER_ENGINE_NVFP4_SCALE_TYPE_SWITCH( scale_type, ScaleType, grouped_nvfp4_2d_quantize_transpose - <<>>( + <<>>( static_cast(input->data.dptr), static_cast(output->data.dptr), static_cast(output->columnwise_data.dptr), static_cast(output->scale_inv.dptr), From 7dc47f76571cfdbf1ca5916aaa1c1cf16450e1bd Mon Sep 17 00:00:00 2001 From: Zhongbo Zhu Date: Wed, 25 Nov 2026 02:42:03 -0800 Subject: [PATCH 08/16] Include NVFP4 conversion primitives without legacy static kernels Signed-off-by: Zhongbo Zhu --- transformer_engine/common/cast/nvfp4/group_quantize_2d_nvfp4.cu | 1 + 1 file changed, 1 insertion(+) diff --git a/transformer_engine/common/cast/nvfp4/group_quantize_2d_nvfp4.cu b/transformer_engine/common/cast/nvfp4/group_quantize_2d_nvfp4.cu index bd745df84c6..6441ae3f812 100644 --- a/transformer_engine/common/cast/nvfp4/group_quantize_2d_nvfp4.cu +++ b/transformer_engine/common/cast/nvfp4/group_quantize_2d_nvfp4.cu @@ -2,6 +2,7 @@ * Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. * See LICENSE for license information. ************************************************************************/ +#include "../../util/ptx_arch_spec.cuh" #include "../core/grouped_layout.cuh" #include "core_nvfp4.cuh" #include "group_quantize_2d_nvfp4.h" From 588ccee8ae887991a75e75d43af8b758d91a4577 Mon Sep 17 00:00:00 2001 From: Zhongbo Zhu Date: Wed, 25 Nov 2026 02:45:25 -0800 Subject: [PATCH 09/16] Validate grouped 2D inputs and cover constant blocks Signed-off-by: Zhongbo Zhu --- .../nvfp4/test_nvfp4_group_quantize_2d.py | 23 +++++++++++++++++++ .../cast/nvfp4/group_quantize_2d_nvfp4.cu | 4 ++++ 2 files changed, 27 insertions(+) diff --git a/tests/pytorch/nvfp4/test_nvfp4_group_quantize_2d.py b/tests/pytorch/nvfp4/test_nvfp4_group_quantize_2d.py index 1aeeb651247..41b89537ac1 100644 --- a/tests/pytorch/nvfp4/test_nvfp4_group_quantize_2d.py +++ b/tests/pytorch/nvfp4/test_nvfp4_group_quantize_2d.py @@ -149,6 +149,29 @@ def test_grouped_2d_large_capacity_grid(): _check(x, [128, 0], result, (True, True), False) +@pytest.mark.parametrize("value", [0.0, 1.0, -1.0, 2.0**-12, 2.0**12]) +def test_grouped_2d_constant_blocks(value): + x = torch.full((384, 128), value, device="cuda", dtype=torch.bfloat16) + metadata = torch.tensor([128, 256], device="cuda", dtype=torch.int64) + result = tex.group_quantize(x, _quantizer((True, True), False), 2, metadata) + _check(x, [128, 256], result, (True, True), False) + + +@pytest.mark.parametrize("shape", [(128, 64), (128, 192), (64, 128)]) +def test_grouped_2d_rejects_unaligned_shape(shape): + x = torch.zeros(shape, device="cuda", dtype=torch.bfloat16) + with pytest.raises(RuntimeError, match="128-aligned"): + tex.group_quantize(x, _quantizer((True, True), False), 1, None) + + +@pytest.mark.parametrize("device,dtype", [("cpu", torch.int64), ("cuda", torch.int32)]) +def test_grouped_2d_rejects_invalid_metadata(device, dtype): + x = torch.zeros(256, 128, device="cuda", dtype=torch.bfloat16) + metadata = torch.tensor([128, 128], device=device, dtype=dtype) + with pytest.raises(RuntimeError, match="int64 CUDA first_dims"): + tex.group_quantize(x, _quantizer((True, True), False), 2, metadata) + + @pytest.mark.parametrize( "option", [ diff --git a/transformer_engine/common/cast/nvfp4/group_quantize_2d_nvfp4.cu b/transformer_engine/common/cast/nvfp4/group_quantize_2d_nvfp4.cu index 6441ae3f812..0501bef0178 100644 --- a/transformer_engine/common/cast/nvfp4/group_quantize_2d_nvfp4.cu +++ b/transformer_engine/common/cast/nvfp4/group_quantize_2d_nvfp4.cu @@ -111,6 +111,8 @@ __global__ void grouped_nvfp4_2d_quantize_transpose(const bf16* input, uint8_t* void group_quantize_2d(const GroupedTensor* input, const Tensor* noop, GroupedTensor* output, const QuantizationConfig* config, cudaStream_t stream) { #if FP4_TYPE_SUPPORTED + NVTE_CHECK(input->logical_shape.ndim == 2 && output->logical_shape.ndim == 2, + "Grouped NVFP4 2D requires matrix inputs and outputs."); NVTE_CHECK(input->dtype() == DType::kBFloat16, "Grouped NVFP4 2D requires BF16 input."); NVTE_CHECK(input->num_tensors == output->num_tensors, "Grouped tensor counts must match."); NVTE_CHECK(output->all_same_last_dim() || output->all_same_shape(), @@ -123,6 +125,8 @@ void group_quantize_2d(const GroupedTensor* input, const Tensor* noop, GroupedTe const size_t count = input->num_tensors; NVTE_CHECK(cols > 0 && cols % 128 == 0 && capacity % 128 == 0, "Grouped NVFP4 2D requires 128-aligned capacity and hidden dimension."); + NVTE_CHECK((capacity == 0 || input->data.dptr) && input->data.numel() >= capacity * cols, + "Invalid grouped NVFP4 input buffer."); NVTE_CHECK(output->logical_shape.data[0] == capacity && output->logical_shape.data[1] == cols, "Grouped NVFP4 2D input/output capacities must match."); if (count == 0) return; From 018cf2cf6be76a8b4135305a713d60a07528b653 Mon Sep 17 00:00:00 2001 From: Zhongbo Zhu Date: Wed, 25 Nov 2026 02:47:50 -0800 Subject: [PATCH 10/16] Exercise larger randomized expert shapes in grouped 2D quantization Signed-off-by: Zhongbo Zhu --- tests/pytorch/nvfp4/test_nvfp4_group_quantize_2d.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/tests/pytorch/nvfp4/test_nvfp4_group_quantize_2d.py b/tests/pytorch/nvfp4/test_nvfp4_group_quantize_2d.py index 41b89537ac1..d63d33d7be2 100644 --- a/tests/pytorch/nvfp4/test_nvfp4_group_quantize_2d.py +++ b/tests/pytorch/nvfp4/test_nvfp4_group_quantize_2d.py @@ -157,6 +157,17 @@ def test_grouped_2d_constant_blocks(value): _check(x, [128, 256], result, (True, True), False) +@pytest.mark.parametrize("swizzled", [False, True]) +@pytest.mark.parametrize("cols", [2048, 4096]) +def test_grouped_2d_random_uneven_experts(cols, swizzled): + torch.manual_seed(57) + splits = (torch.randint(0, 17, (16,)) * 128).tolist() + x = torch.randn(sum(splits), cols, device="cuda", dtype=torch.bfloat16) + metadata = torch.tensor(splits, device="cuda", dtype=torch.int64) + result = tex.group_quantize(x, _quantizer((True, True), swizzled), 16, metadata) + _check(x, splits, result, (True, True), swizzled) + + @pytest.mark.parametrize("shape", [(128, 64), (128, 192), (64, 128)]) def test_grouped_2d_rejects_unaligned_shape(shape): x = torch.zeros(shape, device="cuda", dtype=torch.bfloat16) From cab0fb462c717c2079b37c66d13fd4a439dc7792 Mon Sep 17 00:00:00 2001 From: Zhongbo Zhu Date: Wed, 25 Nov 2026 02:50:35 -0800 Subject: [PATCH 11/16] Refresh debug scale views across graph replay and test single NVFP4 weight Signed-off-by: Zhongbo Zhu --- tests/pytorch/nvfp4/test_nvfp4_group_quantize_2d.py | 2 ++ tests/pytorch/test_grouped_linear.py | 5 +++++ 2 files changed, 7 insertions(+) diff --git a/tests/pytorch/nvfp4/test_nvfp4_group_quantize_2d.py b/tests/pytorch/nvfp4/test_nvfp4_group_quantize_2d.py index d63d33d7be2..ad97dfaf8e2 100644 --- a/tests/pytorch/nvfp4/test_nvfp4_group_quantize_2d.py +++ b/tests/pytorch/nvfp4/test_nvfp4_group_quantize_2d.py @@ -22,6 +22,8 @@ def _check(x, splits, grouped, directions, swizzled): # Debug views cache host metadata. Refresh only outside graph capture/replay. grouped.tensor_shapes = None grouped.offsets = None + grouped.scale_inv_offsets = None + grouped.columnwise_scale_inv_offsets = None results = grouped.split_into_quantized_tensors() reference_quantizer = _quantizer(directions, False) start = 0 diff --git a/tests/pytorch/test_grouped_linear.py b/tests/pytorch/test_grouped_linear.py index f53fe23c27c..07cf9c1c215 100644 --- a/tests/pytorch/test_grouped_linear.py +++ b/tests/pytorch/test_grouped_linear.py @@ -2213,6 +2213,11 @@ def test_single_grouped_weight_rejects_host_m_splits(m_splits, exception): ), id="fp8-block-scaling", ), + pytest.param( + nvfp4_rht_and_2d_quantization(), + marks=pytest.mark.skipif(not _nvfp4_available, reason=_reason_for_no_nvfp4), + id="nvfp4-2d-weight", + ), ], ) def test_single_grouped_weight_matches_discrete_grouped_tensor_path(fp8_recipe): From 49b0220a8e74c30e48b47353895579c47803c3a9 Mon Sep 17 00:00:00 2001 From: Zhongbo Zhu Date: Wed, 25 Nov 2026 02:52:14 -0800 Subject: [PATCH 12/16] Supply a process group when testing grouped amax reduction rejection Signed-off-by: Zhongbo Zhu --- tests/pytorch/nvfp4/test_nvfp4_group_quantize_2d.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/pytorch/nvfp4/test_nvfp4_group_quantize_2d.py b/tests/pytorch/nvfp4/test_nvfp4_group_quantize_2d.py index ad97dfaf8e2..80cfdc03731 100644 --- a/tests/pytorch/nvfp4/test_nvfp4_group_quantize_2d.py +++ b/tests/pytorch/nvfp4/test_nvfp4_group_quantize_2d.py @@ -197,6 +197,9 @@ def test_grouped_2d_rejects_invalid_metadata(device, dtype): def test_grouped_2d_rejects_unsupported_recipe(option): q = _quantizer((True, True), False) setattr(q, option, option != "with_2d_quantization") + if option == "with_amax_reduction": + # Quantizer construction needs a group, but dispatch must reject it before any collective. + q.amax_reduction_group = torch.distributed.ProcessGroup(torch.distributed.HashStore(), 0, 1) x = torch.zeros(256, 128, device="cuda", dtype=torch.bfloat16) with pytest.raises(RuntimeError, match="not implemented|local per-tensor amax"): tex.group_quantize(x, q, 2, None) From 92b0835c86dddb73afd68c90a9260005e0f67167 Mon Sep 17 00:00:00 2001 From: Zhongbo Zhu Date: Wed, 25 Nov 2026 02:56:35 -0800 Subject: [PATCH 13/16] Vectorize packed FP4 stores in grouped 2D quantization Signed-off-by: Zhongbo Zhu --- .../common/cast/nvfp4/group_quantize_2d_nvfp4.cu | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/transformer_engine/common/cast/nvfp4/group_quantize_2d_nvfp4.cu b/transformer_engine/common/cast/nvfp4/group_quantize_2d_nvfp4.cu index 0501bef0178..66385499ba1 100644 --- a/transformer_engine/common/cast/nvfp4/group_quantize_2d_nvfp4.cu +++ b/transformer_engine/common/cast/nvfp4/group_quantize_2d_nvfp4.cu @@ -72,13 +72,15 @@ __global__ void grouped_nvfp4_2d_quantize_transpose(const bf16* input, uint8_t* const float2 inverse2{inverse, inverse}; const size_t scale_base = offsets[expert] / 16; if (row_data) { + uint64_t packed_values = 0; #pragma unroll for (int p = 0; p < 4; ++p) { const auto packed = ptx::mul_cvt_bf16_to_fp4_4x( *reinterpret_cast(values + 4 * p), inverse2, 0); - *reinterpret_cast(row_data + (global_row + block_row + lane) * (cols / 2) + - col / 2 + 2 * p) = packed; + packed_values |= static_cast(packed.__x) << (16 * p); } + *reinterpret_cast(row_data + (global_row + block_row + lane) * (cols / 2) + + col / 2) = packed_values; const size_t r = local_row + block_row + lane; const size_t c = col / 16; const size_t index = @@ -86,15 +88,17 @@ __global__ void grouped_nvfp4_2d_quantize_transpose(const bf16* input, uint8_t* row_scales[scale_base + index] = scale; } if (col_data) { + uint64_t packed_values = 0; #pragma unroll for (int p = 0; p < 4; ++p) { #pragma unroll for (int j = 0; j < 4; ++j) values[j] = tile[block_row + 4 * p + j][block_col + lane]; const auto packed = ptx::mul_cvt_bf16_to_fp4_4x( *reinterpret_cast(values), inverse2, 0); - *reinterpret_cast(col_data + offsets[expert] / 2 + (col + lane) * (m / 2) + - (local_row + block_row) / 2 + 2 * p) = packed; + packed_values |= static_cast(packed.__x) << (16 * p); } + *reinterpret_cast(col_data + offsets[expert] / 2 + (col + lane) * (m / 2) + + (local_row + block_row) / 2) = packed_values; const size_t r = col + lane; const size_t c = (local_row + block_row) / 16; const size_t index = From 5a4fb1e9284ea9a77ae3bbb481be58670264783f Mon Sep 17 00:00:00 2001 From: Zhongbo Zhu Date: Wed, 25 Nov 2026 03:00:46 -0800 Subject: [PATCH 14/16] Validate dynamic CUDA graph replay directly through the common API Signed-off-by: Zhongbo Zhu --- .../operator/test_cast_nvfp4_grouped_2d.cu | 103 +++++++++++------- 1 file changed, 65 insertions(+), 38 deletions(-) diff --git a/tests/cpp/operator/test_cast_nvfp4_grouped_2d.cu b/tests/cpp/operator/test_cast_nvfp4_grouped_2d.cu index 53bd9844c96..4c0395c99d0 100644 --- a/tests/cpp/operator/test_cast_nvfp4_grouped_2d.cu +++ b/tests/cpp/operator/test_cast_nvfp4_grouped_2d.cu @@ -22,8 +22,8 @@ TEST_P(NVFP4Grouped2D, MatchesSingleTensorWithEmptyExpertAndCapacityTail) { constexpr size_t capacity = 512, k = 128, count = 3; const bool rowwise = GetParam() != 2; const bool columnwise = GetParam() != 1; - const std::vector rows{128, 0, 256}; - const std::vector offsets{0, 128 * k, 128 * k, 384 * k}; + std::vector rows{128, 0, 256}; + std::vector offsets{0, 128 * k, 128 * k, 384 * k}; Tensor source("source", std::vector{capacity, k}, DType::kBFloat16); auto* host = source.rowwise_cpu_dptr(); for (size_t i = 0; i < capacity * k; ++i) { @@ -63,46 +63,73 @@ TEST_P(NVFP4Grouped2D, MatchesSingleTensorWithEmptyExpertAndCapacityTail) { config.set_nvfp4_2d_quantization(true); nvte_group_quantize(input.data(), output.data(), config, 0); NVTE_CHECK_CUDA(cudaDeviceSynchronize()); - for (size_t i = 0; i < count; ++i) { - if (rows[i] == 0) { - float amax; - if (rowwise) { - NVTE_CHECK_CUDA(cudaMemcpy(&amax, amax_r.get() + i, sizeof(float), cudaMemcpyDeviceToHost)); - EXPECT_EQ(amax, 0.0f); + cudaStream_t stream; + cudaGraph_t graph; + cudaGraphExec_t executable; + NVTE_CHECK_CUDA(cudaStreamCreate(&stream)); + NVTE_CHECK_CUDA(cudaStreamBeginCapture(stream, cudaStreamCaptureModeGlobal)); + nvte_group_quantize(input.data(), output.data(), config, stream); + NVTE_CHECK_CUDA(cudaStreamEndCapture(stream, &graph)); + NVTE_CHECK_CUDA(cudaGraphInstantiate(&executable, graph, 0)); + const std::vector> cases{ + {128, 0, 256}, {256, 128, 128}, {0, 0, 0}, {128, 256, 0}}; + for (const auto& current_rows : cases) { + rows = current_rows; + offsets[0] = 0; + for (size_t i = 0; i < count; ++i) offsets[i + 1] = offsets[i] + rows[i] * k; + NVTE_CHECK_CUDA(cudaMemcpyAsync(device_rows.get(), rows.data(), rows.size() * sizeof(int64_t), + cudaMemcpyHostToDevice, stream)); + NVTE_CHECK_CUDA(cudaMemcpyAsync(device_offsets.get(), offsets.data(), + offsets.size() * sizeof(int64_t), cudaMemcpyHostToDevice, + stream)); + NVTE_CHECK_CUDA(cudaGraphLaunch(executable, stream)); + NVTE_CHECK_CUDA(cudaStreamSynchronize(stream)); + for (size_t i = 0; i < count; ++i) { + if (rows[i] == 0) { + float amax; + if (rowwise) { + NVTE_CHECK_CUDA( + cudaMemcpy(&amax, amax_r.get() + i, sizeof(float), cudaMemcpyDeviceToHost)); + EXPECT_EQ(amax, 0.0f); + } + if (columnwise) { + NVTE_CHECK_CUDA( + cudaMemcpy(&amax, amax_c.get() + i, sizeof(float), cudaMemcpyDeviceToHost)); + EXPECT_EQ(amax, 0.0f); + } + continue; } - if (columnwise) { - NVTE_CHECK_CUDA(cudaMemcpy(&amax, amax_c.get() + i, sizeof(float), cudaMemcpyDeviceToHost)); - EXPECT_EQ(amax, 0.0f); + const size_t m = rows[i]; + Tensor expert("expert", std::vector{m, k}, DType::kBFloat16); + std::copy_n(host + offsets[i], m * k, expert.rowwise_cpu_dptr()); + expert.from_cpu(); + Tensor reference("reference", std::vector{m, k}, DType::kFloat4E2M1, true, true, + NVTE_NVFP4_1D_SCALING); + nvte_compute_amax(expert.data(), reference.data(), 0); + nvte_quantize_v2(expert.data(), reference.data(), config, 0); + NVTE_CHECK_CUDA(cudaDeviceSynchronize()); + reference.to_cpu(); + for (bool col : {false, true}) { + if (col ? !columnwise : !rowwise) continue; + std::vector actual(m * k / 2), scales(m * k / 16); + NVTE_CHECK_CUDA(cudaMemcpy(actual.data(), + (col ? data_c.get() : data_r.get()) + offsets[i] / 2, + actual.size(), cudaMemcpyDeviceToHost)); + NVTE_CHECK_CUDA(cudaMemcpy(scales.data(), + (col ? scale_c.get() : scale_r.get()) + offsets[i] / 16, + scales.size(), cudaMemcpyDeviceToHost)); + const auto* expected = + col ? reference.columnwise_cpu_dptr() : reference.rowwise_cpu_dptr(); + const auto* expected_scales = col ? reference.columnwise_cpu_scale_inv_ptr() + : reference.rowwise_cpu_scale_inv_ptr(); + EXPECT_EQ(std::memcmp(actual.data(), expected, actual.size()), 0); + EXPECT_EQ(std::memcmp(scales.data(), expected_scales, scales.size()), 0); } - continue; - } - const size_t m = rows[i]; - Tensor expert("expert", std::vector{m, k}, DType::kBFloat16); - std::copy_n(host + offsets[i], m * k, expert.rowwise_cpu_dptr()); - expert.from_cpu(); - Tensor reference("reference", std::vector{m, k}, DType::kFloat4E2M1, true, true, - NVTE_NVFP4_1D_SCALING); - nvte_compute_amax(expert.data(), reference.data(), 0); - nvte_quantize_v2(expert.data(), reference.data(), config, 0); - NVTE_CHECK_CUDA(cudaDeviceSynchronize()); - reference.to_cpu(); - for (bool col : {false, true}) { - if (col ? !columnwise : !rowwise) continue; - std::vector actual(m * k / 2), scales(m * k / 16); - NVTE_CHECK_CUDA(cudaMemcpy(actual.data(), - (col ? data_c.get() : data_r.get()) + offsets[i] / 2, - actual.size(), cudaMemcpyDeviceToHost)); - NVTE_CHECK_CUDA(cudaMemcpy(scales.data(), - (col ? scale_c.get() : scale_r.get()) + offsets[i] / 16, - scales.size(), cudaMemcpyDeviceToHost)); - const auto* expected = - col ? reference.columnwise_cpu_dptr() : reference.rowwise_cpu_dptr(); - const auto* expected_scales = col ? reference.columnwise_cpu_scale_inv_ptr() - : reference.rowwise_cpu_scale_inv_ptr(); - EXPECT_EQ(std::memcmp(actual.data(), expected, actual.size()), 0); - EXPECT_EQ(std::memcmp(scales.data(), expected_scales, scales.size()), 0); } } + NVTE_CHECK_CUDA(cudaGraphExecDestroy(executable)); + NVTE_CHECK_CUDA(cudaGraphDestroy(graph)); + NVTE_CHECK_CUDA(cudaStreamDestroy(stream)); } INSTANTIATE_TEST_SUITE_P(Directions, NVFP4Grouped2D, ::testing::Values(0, 1, 2)); From c842f34573a65ed0f17555574d75a024d9b3e7c8 Mon Sep 17 00:00:00 2001 From: Zhongbo Zhu Date: Wed, 25 Nov 2026 10:53:10 -0800 Subject: [PATCH 15/16] Pipeline grouped NVFP4 2D quantization with TMA and packed transpose Signed-off-by: Zhongbo Zhu --- .../cast/nvfp4/group_quantize_2d_nvfp4.cu | 208 ++++++++++++------ 1 file changed, 137 insertions(+), 71 deletions(-) diff --git a/transformer_engine/common/cast/nvfp4/group_quantize_2d_nvfp4.cu b/transformer_engine/common/cast/nvfp4/group_quantize_2d_nvfp4.cu index 66385499ba1..871c2afc10c 100644 --- a/transformer_engine/common/cast/nvfp4/group_quantize_2d_nvfp4.cu +++ b/transformer_engine/common/cast/nvfp4/group_quantize_2d_nvfp4.cu @@ -26,85 +26,142 @@ __global__ void validate_grouped_2d_splits(const int64_t* offsets, const int64_t } #if FP4_TYPE_SUPPORTED -template -__global__ void grouped_nvfp4_2d_quantize_transpose(const bf16* input, uint8_t* row_data, - uint8_t* col_data, ScaleType* row_scales, - ScaleType* col_scales, const float* amax, - const int64_t* offsets, const int64_t* rows, - size_t count, size_t cols, bool swizzled, - const float* noop) { +template +__global__ __launch_bounds__(128) void grouped_nvfp4_2d_quantize_transpose( + const __grid_constant__ CUtensorMap input_map, uint8_t* row_data, uint8_t* col_data, + ScaleType* row_scales, ScaleType* col_scales, const float* amax, const int64_t* offsets, + const int64_t* rows, size_t count, size_t cols, const float* noop) { #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 1000 if (noop && *noop == 1.0f) return; - const size_t global_row = (static_cast(blockIdx.x) / (cols / 128)) * 32; + const size_t global_row = (static_cast(blockIdx.x) / (cols / 128)) * 128; if (global_row * cols >= offsets[count]) return; const size_t expert = common::find_tensor_from_offsets(offsets, count, global_row * cols); const size_t start = offsets[expert] / cols; const size_t local_row = global_row - start; - // Each half-warp owns one 16x16 scale block; a CTA covers a 32x128 tile. - const int scale_block = threadIdx.x / 16; - const int block_row = (scale_block / 8) * 16; - const int block_col = (scale_block % 8) * 16; - const int lane = threadIdx.x % 16; - const size_t col = (blockIdx.x % (cols / 128)) * 128 + block_col; + const size_t col = (blockIdx.x % (cols / 128)) * 128; const size_t m = rows[expert]; - __shared__ bf16 tile[32][129]; - alignas(16) bf16 values[16]; - const bf16* source = input + (global_row + block_row + lane) * cols + col; - reinterpret_cast(values)[0] = reinterpret_cast(source)[0]; - reinterpret_cast(values)[1] = reinterpret_cast(source)[1]; - float a = 0.0f; -#pragma unroll - for (int j = 0; j < 16; ++j) { - tile[block_row + lane][block_col + j] = values[j]; - a = fmaxf(a, fabsf(static_cast(values[j]))); - } - for (int delta = 8; delta > 0; delta /= 2) { - a = fmaxf(a, __shfl_xor_sync(0xffffffff, a, delta, 16)); - } - __syncwarp(); - - // Use the same arithmetic and packed BF16 conversion as single-tensor 2D quantization. const float encode = core::compute_global_encode_scaling_factor_FP4(amax[expert]); const float decode = 1.0 / encode; - const ScaleType scale = core::compute_decoding_scaling_factor(a, encode); - const float inverse = - fminf(1.0f / (static_cast(scale) * decode), detail::TypeExtrema::max); - const float2 inverse2{inverse, inverse}; const size_t scale_base = offsets[expert] / 16; - if (row_data) { - uint64_t packed_values = 0; + const int tid = threadIdx.x; + const bool leader = tid == 0; + __shared__ alignas(128) bf16 input[2][32][128]; + __shared__ alignas(16) uint32_t packed[8][64]; + __shared__ alignas(16) ScaleType scales[8][8]; + __shared__ alignas(8) uint64_t barriers[4]; + initialize_barriers<4, 128>(barriers, leader); + copy_2d_to_shared(input[0], &input_map, col, global_row, 32 * 128 * sizeof(bf16), &barriers[0], + leader); + + // A 128x128 chunk is consumed in four 32x128 stages. Prefetch into the other + // input buffer while quantizing the current stage; no dynamic tensor maps or D2H. +#pragma unroll + for (int stage = 0; stage < 4; ++stage) { + const int buff = stage % 2; + if (stage + 1 < 4) { + copy_2d_to_shared(input[(stage + 1) % 2], &input_map, col, global_row + (stage + 1) * 32, + 32 * 128 * sizeof(bf16), &barriers[stage + 1], leader); + } + ptx::mbarrier_wait_parity(&barriers[stage], 0); + uint32_t col_words[4] = {}; +#pragma unroll + for (int half = 0; half < 2; ++half) { + alignas(8) bf16 values[16]; + float a = 0.0f; #pragma unroll - for (int p = 0; p < 4; ++p) { - const auto packed = ptx::mul_cvt_bf16_to_fp4_4x( - *reinterpret_cast(values + 4 * p), inverse2, 0); - packed_values |= static_cast(packed.__x) << (16 * p); + for (int r = 0; r < 16; ++r) { + values[r] = input[buff][half * 16 + r][tid]; + a = fmaxf(a, fabsf(static_cast(values[r]))); + } +#pragma unroll + for (int delta = 8; delta > 0; delta /= 2) { + a = fmaxf(a, __shfl_xor_sync(0xffffffff, a, delta, 16)); + } + const ScaleType scale = core::compute_decoding_scaling_factor(a, encode); + const float inverse = + fminf(1.0f / (static_cast(scale) * decode), detail::TypeExtrema::max); + const float2 inverse2{inverse, inverse}; + if (tid % 16 == 0) scales[stage * 2 + half][tid / 16] = scale; + // With deterministic 2D scaling, both directions share the same FP4 values. + // Quantize once using the single-tensor arithmetic, then transpose the nibbles. +#pragma unroll + for (int q = 0; q < 4; ++q) { + const uint32_t bits = ptx::mul_cvt_bf16_to_fp4_4x( + *reinterpret_cast(values + 4 * q), inverse2, 0) + .__x; + col_words[half * 2 + q / 2] |= bits << ((q % 2) * 16); + if constexpr (ROWWISE) { + // Pair adjacent columns into whole words before storing to shared memory. + const uint32_t adjacent = __shfl_xor_sync(0xffffffff, bits, 1); + if (tid % 2 == 0) packed[half * 4 + q][tid / 2] = bits | (adjacent << 16); + } + } + } + if constexpr (COLUMNWISE) { + *reinterpret_cast(col_data + offsets[expert] / 2 + (col + tid) * (m / 2) + + (local_row + stage * 32) / 2) = + make_uint4(col_words[0], col_words[1], col_words[2], col_words[3]); + } + __syncthreads(); + if constexpr (ROWWISE) { +#pragma unroll + for (int i = 0; i < 4; ++i) { + const int r = (tid + i * 128) / 16; + const int c = (tid % 16) * 8; + const uint4 v = *reinterpret_cast(&packed[r / 4][c / 2]); + const int shift = (r % 4) * 4; + const auto pair = [shift](uint32_t x) { + return ((x >> shift) & 15u) | ((x >> (shift + 12)) & 240u); + }; + const uint32_t out = pair(v.x) | (pair(v.y) << 8) | (pair(v.z) << 16) | (pair(v.w) << 24); + *reinterpret_cast(row_data + (global_row + stage * 32 + r) * (cols / 2) + + (col + c) / 2) = out; + } } - *reinterpret_cast(row_data + (global_row + block_row + lane) * (cols / 2) + - col / 2) = packed_values; - const size_t r = local_row + block_row + lane; - const size_t c = col / 16; - const size_t index = - swizzled ? swizzle::gemm_swizzled_scale_idx(r, c, cols / 16) : r * (cols / 16) + c; - row_scales[scale_base + index] = scale; + __syncthreads(); } - if (col_data) { - uint64_t packed_values = 0; + // Emit the replicated scale matrix in 8-byte vectors rather than scattered + // byte stores per stage. Two 512-byte base blocks cover each swizzled tile. + static_assert(sizeof(ScaleType) == 1); + const auto* scale_bytes = reinterpret_cast(scales); + if constexpr (SWIZZLED) { + const int r0 = (tid / 2) % 32 + (tid % 2) * 64; + const int r1 = r0 + 32; + const int c = (tid / 64) * 4; + if constexpr (ROWWISE) { + const uint32_t lo = *reinterpret_cast(&scales[r0 / 16][c]); + const uint32_t hi = *reinterpret_cast(&scales[r1 / 16][c]); + const size_t base = swizzle::gemm_swizzled_scale_idx(local_row, col / 16, cols / 16); + reinterpret_cast(row_scales + scale_base + base)[tid] = + static_cast(lo) | (static_cast(hi) << 32); + } + if constexpr (COLUMNWISE) { + uint64_t bits = 0; #pragma unroll - for (int p = 0; p < 4; ++p) { + for (int j = 0; j < 4; ++j) { + bits |= static_cast(scale_bytes[(c + j) * 8 + r0 / 16]) << (8 * j); + bits |= static_cast(scale_bytes[(c + j) * 8 + r1 / 16]) << (32 + 8 * j); + } + const size_t base = swizzle::gemm_swizzled_scale_idx(col, local_row / 16, m / 16); + reinterpret_cast(col_scales + scale_base + base)[tid] = bits; + } + } else { + if constexpr (ROWWISE) { + *reinterpret_cast(row_scales + scale_base + (local_row + tid) * (cols / 16) + + col / 16) = + *reinterpret_cast(&scales[tid / 16][0]); + } + if constexpr (COLUMNWISE) { + uint64_t bits = 0; #pragma unroll - for (int j = 0; j < 4; ++j) values[j] = tile[block_row + 4 * p + j][block_col + lane]; - const auto packed = ptx::mul_cvt_bf16_to_fp4_4x( - *reinterpret_cast(values), inverse2, 0); - packed_values |= static_cast(packed.__x) << (16 * p); + for (int j = 0; j < 8; ++j) { + bits |= static_cast(scale_bytes[j * 8 + tid / 16]) << (8 * j); + } + *reinterpret_cast(col_scales + scale_base + (col + tid) * (m / 16) + + local_row / 16) = bits; } - *reinterpret_cast(col_data + offsets[expert] / 2 + (col + lane) * (m / 2) + - (local_row + block_row) / 2) = packed_values; - const size_t r = col + lane; - const size_t c = (local_row + block_row) / 16; - const size_t index = - swizzled ? swizzle::gemm_swizzled_scale_idx(r, c, m / 16) : r * (m / 16) + c; - col_scales[scale_base + index] = scale; } + destroy_barriers<4>(barriers, leader); #else NVTE_DEVICE_ERROR("Grouped NVFP4 2D quantization requires Blackwell."); #endif @@ -171,15 +228,24 @@ void group_quantize_2d(const GroupedTensor* input, const Tensor* noop, GroupedTe if (capacity == 0) return; const float* amax = static_cast(rowwise ? output->amax.dptr : output->columnwise_amax.dptr); - TRANSFORMER_ENGINE_NVFP4_SCALE_TYPE_SWITCH( - scale_type, ScaleType, - grouped_nvfp4_2d_quantize_transpose - <<>>( - static_cast(input->data.dptr), static_cast(output->data.dptr), - static_cast(output->columnwise_data.dptr), - static_cast(output->scale_inv.dptr), - static_cast(output->columnwise_scale_inv.dptr), amax, offsets, rows, count, - cols, output->with_gemm_swizzled_scales, noop_ptr);); + checkCuDriverContext(stream); + alignas(64) CUtensorMap input_map{}; + create_2D_tensor_map(input_map, input->data, capacity, cols, 32, 128, cols, 0, 16); + TRANSFORMER_ENGINE_NVFP4_SCALE_TYPE_SWITCH(scale_type, ScaleType, { + TRANSFORMER_ENGINE_SWITCH_CONDITION(rowwise, ROWWISE, { + TRANSFORMER_ENGINE_SWITCH_CONDITION(columnwise, COLUMNWISE, { + TRANSFORMER_ENGINE_SWITCH_CONDITION(output->with_gemm_swizzled_scales, SWIZZLED, { + grouped_nvfp4_2d_quantize_transpose + <<>>( + input_map, static_cast(output->data.dptr), + static_cast(output->columnwise_data.dptr), + static_cast(output->scale_inv.dptr), + static_cast(output->columnwise_scale_inv.dptr), amax, offsets, rows, + count, cols, noop_ptr); + }); + }); + }); + }); NVTE_CHECK_CUDA(cudaGetLastError()); #else NVTE_ERROR("Grouped NVFP4 2D requires FP4 support in the CUDA toolkit."); From 32133fd8ef3939989ba6e24c9adef1543fb11308 Mon Sep 17 00:00:00 2001 From: Zhongbo Zhu Date: Wed, 25 Nov 2026 16:50:01 -0800 Subject: [PATCH 16/16] Clarify NVFP4 2D scales use the 1D GEMM storage layout Signed-off-by: Zhongbo Zhu --- transformer_engine/common/cast/dispatch/quantize.cuh | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/transformer_engine/common/cast/dispatch/quantize.cuh b/transformer_engine/common/cast/dispatch/quantize.cuh index f677e6ac7b3..f349a418687 100644 --- a/transformer_engine/common/cast/dispatch/quantize.cuh +++ b/transformer_engine/common/cast/dispatch/quantize.cuh @@ -583,6 +583,10 @@ void group_quantize_fwd_helper(const NVTEGroupedTensor input, NVTEGroupedTensor } case NVTE_NVFP4_1D_SCALING: { NVTE_CHECK(!IS_ACT, "IS_ACT is not implemented for grouped NVTE_NVFP4_1D_SCALING."); + // 2D quantization replicates each 16x16 block scale into the 1x16 + // scale layout consumed by GEMM. The 1D scaling enum describes that storage + // format; nvfp4_2d_quantization selects how the scales are computed. + // Both quantization algorithms therefore use this scaling-mode branch. if (!output_tensor->row_scaled_nvfp4) { NVTE_CHECK(quant_config_cpp.nvfp4_2d_quantization, "Per-tensor amax with 1D grouped NVFP4 quantization is not implemented.");