From ab61056787c102c8334b88e3dfb7cabd3aa43f17 Mon Sep 17 00:00:00 2001 From: Zhihao Wang Date: Sat, 5 Dec 2026 02:48:51 +0000 Subject: [PATCH] [Common] Compute decode scale first in FP8 blockwise scaling FP8 blockwise scaling (`1x128` and `128x128`) stores only the decoding scale (`scale_inv`) and feeds it to block-scaled GEMMs, whereas per-tensor FP8 recipes derive `scale_inv` from a stored encoding `scale`. Computing `scale = max_fp8 / amax` first and taking `scale_inv = 1 / scale` second caused: - Double-reciprocal FP32 rounding drift (`1 / (max_fp8 / amax)` vs `amax / max_fp8`) on ~33.2% of normal BF16 block amaxes when `force_pow_2_scales=false`, as well as quantized element mismatches when `x * (1 / scale_inv)` differs from `x * scale`. - Overflow of `max_fp8 / amax` to `+inf` for tiny positive `amax` values (`amax <= 2^-120`), corrupting `scale_inv` via per-tensor `value_for_inf` fallback or producing subnormal `2^-127` scales incompatible with UE8M0 (`E8M0` minimum normal exponent is `2^-126 = FLT_MIN`) when `force_pow_2_scales=true`, plus boundary direction mismatches where `round_down_pow2(max_fp8 / amax)` differs from `ceil_pow2(amax / max_fp8)`. Introduce `compute_decoding_scaling_factor_blockwise` and `compute_blockwise_scale_and_scale_inv` in `recipe_common.cuh` to compute `scale_inv = max(amax / max_fp8, FLT_MIN)` first (rounding up to a power of two via FTZ-safe IEEE-754 bit operations when `force_pow_2_scales` is enabled, and returning `1.0f` for zero/non-positive/non-finite blocks) and derive the encoding multiplier as `scale = 1 / scale_inv`. Wire all single and grouped `1x128`/`128x128` blockwise quantization kernels and distributed master-weight casting (`multi_tensor_compute_scale_and_scale_inv_blockwise`) to this path while keeping existing per-tensor APIs unchanged. Signed-off-by: Zhihao Wang Co-authored-by: Perplexity --- .../fp8_blockwise_scaling.rst | 26 ++++-- .../cpp/operator/test_cast_float8blockwise.cu | 51 +++++------ .../blockwise_quantizer_reference.py | 8 +- .../pytorch/references/quantize_scale_calc.py | 36 ++++++++ .../test_float8_blockwise_scaling_exact.py | 68 +++++++++++++++ tests/pytorch/test_multi_tensor.py | 73 +++++++++++++++- .../group_quantize_fp8_blockwise.cuh | 21 +++-- .../include/transformer_engine/multi_tensor.h | 19 ++++ .../common/multi_tensor/compute_scale.cu | 52 +++++++++-- .../common/recipe/recipe_common.cuh | 87 +++++++++++++++---- .../quantize_transpose_square_blockwise.cu | 18 ++-- .../quantize_transpose_vector_blockwise.cu | 21 +++-- transformer_engine/pytorch/csrc/extensions.h | 4 + .../extensions/multi_tensor/compute_scale.cpp | 15 ++++ .../pytorch/csrc/extensions/pybind.cpp | 4 + transformer_engine/pytorch/tensor/utils.py | 3 +- 16 files changed, 417 insertions(+), 89 deletions(-) diff --git a/docs/features/low_precision_training/fp8_blockwise_scaling/fp8_blockwise_scaling.rst b/docs/features/low_precision_training/fp8_blockwise_scaling/fp8_blockwise_scaling.rst index 33a5e7cc7dc..355536a454b 100644 --- a/docs/features/low_precision_training/fp8_blockwise_scaling/fp8_blockwise_scaling.rst +++ b/docs/features/low_precision_training/fp8_blockwise_scaling/fp8_blockwise_scaling.rst @@ -89,17 +89,25 @@ By default, they are constrained to powers of 2 (utilizing the 8 exponent bits o On Hopper, this constraint can be relaxed by setting the environment variable ``NVTE_FP8_BLOCK_SCALING_FP32_SCALES=1``. On Blackwell, only powers of 2 are supported. -Each block's scaling factor is computed through the following steps: +Each block's scaling factor ``s_block`` (stored as ``scale_inv`` in Transformer Engine) is computed +through the following steps: 1. Find the maximum absolute value (``amax_block``) across all elements in the block - (128 consecutive values for 1D blocks, or 128×128 values for 2D blocks). -2. Calculate ``s_block = max_fp8 / amax_block``, where ``max_fp8`` is - the maximum representable value in the FP8 format (448 for E4M3, 57344 for E5M2). -3. If the power-of-2 constraint is enabled, round down to the nearest power of 2 - by zeroing out the mantissa bits, retaining only the sign and exponent. -4. Multiply each element in the block by ``s_block`` before converting to FP8. - -This approach ensures that the largest value in each block fits within the FP8 representable range without overflow. + (128 consecutive values for 1D blocks, or 128×128 values for 2D blocks), clamping to + ``amax_epsilon`` when configured. +2. If ``amax_block`` is zero or non-finite, set ``s_block = 1``. Otherwise, calculate the + dequantization scale ``s_block = max(amax_block / max_fp8, 2^-126)``, where ``max_fp8`` is the + maximum finite representable value in the FP8 format (448 for E4M3, 57344 for E5M2) and + ``2^-126`` is the minimum positive normal FP32 value. +3. If the power-of-2 constraint is enabled, round ``s_block`` up to the smallest power of 2 + greater than or equal to ``s_block``. +4. Compute the quantization multiplier ``1 / s_block``, multiply each element in the block by + ``1 / s_block``, and cast (with saturation) to FP8. + +Computing ``s_block`` first and deriving ``1 / s_block`` from it matches standard blockwise FP8 +quantization conventions and keeps ``s_block >= amax_block / max_fp8`` under power-of-2 rounding +(up to single-ULP FP32 rounding when the power-of-2 constraint is disabled, which is handled by +the saturating FP8 cast). Handling transposes diff --git a/tests/cpp/operator/test_cast_float8blockwise.cu b/tests/cpp/operator/test_cast_float8blockwise.cu index d50589ca437..0665f25e5f4 100644 --- a/tests/cpp/operator/test_cast_float8blockwise.cu +++ b/tests/cpp/operator/test_cast_float8blockwise.cu @@ -11,6 +11,10 @@ #include #include +#include +#include +#include + #include "../test_common.h" #include "transformer_engine/transformer_engine.h" @@ -47,27 +51,30 @@ enum ActivationType { template void scales_from_amax(float amax, const QuantizationOptions& opts, float* qscale_out, float* qscale_inv_out) { - float input_type_max_val = Quantized_Limits::max(); float quant_type_max_val = Quantized_Limits::max(); float eps = opts.amax_epsilon; - amax = std::max(amax, eps); - float qscale = quant_type_max_val / amax; - if (std::isinf(qscale)) { - qscale = input_type_max_val; + if (amax < eps) { + amax = eps; } - if (std::isnan(qscale) || amax == 0) { - qscale = 1.0; + if (std::isinf(amax) || amax == 0.0f || std::isnan(amax)) { + *qscale_out = 1.0f; + *qscale_inv_out = 1.0f; + return; } - if (opts.force_pow_2_scales && qscale != 0.0) { - uint32_t scale_bits = *reinterpret_cast(&qscale); - // Scale must be positive, shift it - uint8_t exp = scale_bits >> 23; - ASSERT_FALSE(exp == 0) << "Subnormals in this path is a logic error."; - qscale = ldexpf(1.0f, static_cast(exp) - 127); + constexpr float kMinNormalFp32 = 1.17549435082228750797e-38f; + float qscale_inv = std::max(amax / quant_type_max_val, kMinNormalFp32); + + if (opts.force_pow_2_scales) { + uint32_t scale_inv_bits = 0; + std::memcpy(&scale_inv_bits, &qscale_inv, sizeof(scale_inv_bits)); + constexpr uint32_t kMaxPow2Bits = 0x7F000000u; // 2^127 + scale_inv_bits = (std::min(scale_inv_bits, kMaxPow2Bits) + 0x7FFFFFu) & 0xFF800000u; + ASSERT_NE(scale_inv_bits & 0x7F800000u, 0u) << "Subnormals in this path is a logic error."; + std::memcpy(&qscale_inv, &scale_inv_bits, sizeof(qscale_inv)); } - float qscale_inv = 1.0 / qscale; + float qscale = 1.0f / qscale_inv; *qscale_out = qscale; *qscale_inv_out = qscale_inv; } @@ -411,9 +418,8 @@ void runTestCaseOneDimensionalBlocks(const ProcessingMethod processing_method, } std::vector> matrix_sizes = { - {1, 16}, {65, 96}, {256, 256}, {993, 512}, - {256, 65536}, {4096, 1632}, {1024, 1}, - {16, 512}, {1024}, {8, 32, 1024}, {16, 8, 4, 512}, + {1, 16}, {65, 96}, {256, 256}, {993, 512}, {256, 65536}, {4096, 1632}, + {1024, 1}, {16, 512}, {1024}, {8, 32, 1024}, {16, 8, 4, 512}, }; std::vector input_scenarios = { @@ -438,10 +444,9 @@ std::vector Activation_types = { // ActivationType::SReLU, }; - std::vector amax_epsilons = { 0.0f, - 1.0f, // Make large to be observable. + 1.0f, // Make large to be observable. }; @@ -461,9 +466,7 @@ class FusedCastFloat8VectorwiseTestSuite switch (OP_FUNC_TYPE) { \ case ActivationType::Identity: { \ constexpr auto OP = &identity; \ - { \ - __VA_ARGS__ \ - } \ + { __VA_ARGS__ } \ } break; \ } @@ -471,9 +474,7 @@ class FusedCastFloat8VectorwiseTestSuite switch (OP_FUNC_TYPE) { \ case ActivationType::Identity: { \ constexpr auto OP = &identity; \ - { \ - __VA_ARGS__ \ - } \ + { __VA_ARGS__ } \ } break; \ } diff --git a/tests/pytorch/references/blockwise_quantizer_reference.py b/tests/pytorch/references/blockwise_quantizer_reference.py index f0bc2ba0fbc..4cbc90c2be6 100644 --- a/tests/pytorch/references/blockwise_quantizer_reference.py +++ b/tests/pytorch/references/blockwise_quantizer_reference.py @@ -6,7 +6,7 @@ import math import torch from typing import Optional, Protocol, Tuple -from references.quantize_scale_calc import scale_from_amax_tensor +from references.quantize_scale_calc import blockwise_scale_from_amax_tensor @dataclasses.dataclass() @@ -118,8 +118,7 @@ def _quantize_square_block_tiling( ).float() dtype_max = torch.finfo(quant_dtype).max - scale, scale_inv, _ = scale_from_amax_tensor( - x_dtype=x.dtype, + scale, scale_inv, _ = blockwise_scale_from_amax_tensor( amax=amax_grid, quant_dtype=quant_dtype, pow_2_scales=pow_2_scales, @@ -155,8 +154,7 @@ def _quantize_vectorwise_reference( dtype_max = torch.finfo(quant_dtype).max x_tiled = x.reshape(M, K // tile_len, tile_len) amax_grid = torch.abs(x_tiled).amax(dim=-1).float() - scale, scale_inv, _ = scale_from_amax_tensor( - x_dtype=x.dtype, + scale, scale_inv, _ = blockwise_scale_from_amax_tensor( amax=amax_grid, quant_dtype=quant_dtype, pow_2_scales=pow_2_scales, diff --git a/tests/pytorch/references/quantize_scale_calc.py b/tests/pytorch/references/quantize_scale_calc.py index a6ff425133f..986f4949a36 100644 --- a/tests/pytorch/references/quantize_scale_calc.py +++ b/tests/pytorch/references/quantize_scale_calc.py @@ -58,3 +58,39 @@ def scale_from_amax_tensor( scale_inv = torch.reciprocal(scale) return scale, scale_inv, amax + + +def blockwise_scale_from_amax_tensor( + amax: torch.Tensor, + quant_dtype: torch.dtype, + *, + eps: float, + pow_2_scales: bool, +) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Derives blockwise quantization and dequantization scales from amax. + + Computes the dequantization scale (scale_inv) first from amax / fp8_max + (rounded up to a power of two when pow_2_scales is True), then derives + the quantization scale as 1 / scale_inv. + """ + assert amax.dtype == torch.float, "amax must be a float tensor." + fp8_max = torch.tensor(torch.finfo(quant_dtype).max, dtype=torch.float32, device=amax.device) + eps_tensor = torch.tensor(eps, dtype=torch.float32, device=amax.device) + amax = torch.where(amax < eps_tensor, eps_tensor, amax) + + invalid_amax = (amax <= 0.0) | torch.isinf(amax) | torch.isnan(amax) + min_normal_fp32 = torch.tensor( + torch.finfo(torch.float32).tiny, dtype=torch.float32, device=amax.device + ) + scale_inv = torch.maximum(torch.div(amax, fp8_max), min_normal_fp32) + + if pow_2_scales: + scale_inv_bits = scale_inv.view(torch.int32) + max_pow2_bits = 0x7F000000 # 2^127 + scale_inv_bits = (torch.clamp(scale_inv_bits, max=max_pow2_bits) + 0x7FFFFF) & 0x7F800000 + scale_inv = scale_inv_bits.view(torch.float32) + + ones = torch.ones_like(scale_inv) + scale_inv = torch.where(invalid_amax, ones, scale_inv) + scale = torch.div(ones, scale_inv) + return scale, scale_inv, amax diff --git a/tests/pytorch/test_float8_blockwise_scaling_exact.py b/tests/pytorch/test_float8_blockwise_scaling_exact.py index 09f3986ad06..7dd9dbaabdf 100644 --- a/tests/pytorch/test_float8_blockwise_scaling_exact.py +++ b/tests/pytorch/test_float8_blockwise_scaling_exact.py @@ -502,3 +502,71 @@ def test_fp8_current_scaling_with_layernorm_linear_module( recipe1_golden_tensors=None, recipe2_golden_tensors=fp8_zero_tolerance_tensor_dumps_recipe2, ) + + +@pytest.mark.skipif(not recipe_available, reason=reason_for_no_recipe) +@pytest.mark.parametrize("block_scaling_dim", [1, 2]) +@pytest.mark.parametrize("shape", [(128, 128), (160, 160)]) +@pytest.mark.parametrize("pow_2_scales", [False, True]) +def test_float8_blockwise_decode_scale_first( + block_scaling_dim: int, + shape: Tuple[int, int], + pow_2_scales: bool, +) -> None: + if recipe_emulated and not pow_2_scales: + pytest.skip( + "On Blackwell and newer, the FP8 block scaling recipe is emulated " + "with MXFP8, which requires using power of two scaling factors." + ) + + device = "cuda" + quantizer = Float8BlockQuantizer( + fp8_dtype=te.DType.kFloat8E4M3, + rowwise=True, + columnwise=True, + amax_epsilon=0.0, + force_pow_2_scales=pow_2_scales, + block_scaling_dim=block_scaling_dim, + ) + + if not pow_2_scales: + # 0.51171875 and 3.03125 are exact in BF16/FP32 and distinguish decode-first + # (amax / 448 = 0x3a95b6db / 0x3bddb6db) from encode-first + # (1 / (448 / amax) = 0x3a95b6dc / 0x3bddb6dc) in IEEE-754 FP32. + for amax_val in (0.51171875, 3.03125): + x = torch.zeros(shape, dtype=torch.bfloat16, device=device) + x[0, 0] = amax_val + q = quantizer(x) + + expected_scale_inv = torch.div( + torch.tensor(amax_val, dtype=torch.float32, device=device), + torch.tensor(448.0, dtype=torch.float32, device=device), + ) + encode_first_scale_inv = torch.reciprocal( + torch.div( + torch.tensor(448.0, dtype=torch.float32, device=device), + torch.tensor(amax_val, dtype=torch.float32, device=device), + ) + ) + assert expected_scale_inv.item() != encode_first_scale_inv.item() + assert q._rowwise_scale_inv.flatten()[0].item() == expected_scale_inv.item() + assert q._columnwise_scale_inv.flatten()[0].item() == expected_scale_inv.item() + else: + # Tiny positive amax (1e-37 in BF16/FP32, and 0x04600001 in FP32) previously + # produced subnormal scale_inv = 2^-127 under encode-first; decode-first floors + # positive scale_inv at FLT_MIN = 2^-126 so both scale_inv and scale stay normal. + min_normal = torch.finfo(torch.float32).tiny + for x_dtype, tiny_bits in [ + (torch.bfloat16, None), + (torch.float32, 0x04600001), + ]: + x = torch.zeros(shape, dtype=x_dtype, device=device) + if tiny_bits is None: + x[0, 0] = torch.tensor(1e-37, dtype=torch.float32, device=device).to(x_dtype) + else: + x[0, 0] = torch.tensor([tiny_bits], dtype=torch.int32, device=device).view( + torch.float32 + )[0] + q = quantizer(x) + assert q._rowwise_scale_inv.flatten()[0].item() == min_normal + assert q._columnwise_scale_inv.flatten()[0].item() == min_normal diff --git a/tests/pytorch/test_multi_tensor.py b/tests/pytorch/test_multi_tensor.py index 6f1b6948ab2..d9f48de0329 100644 --- a/tests/pytorch/test_multi_tensor.py +++ b/tests/pytorch/test_multi_tensor.py @@ -10,7 +10,10 @@ from transformer_engine.pytorch import is_mxfp8_available from transformer_engine.pytorch.optimizers import MultiTensorApply -from references.quantize_scale_calc import scale_from_amax_tensor +from references.quantize_scale_calc import ( + blockwise_scale_from_amax_tensor, + scale_from_amax_tensor, +) input_size_pairs = [ @@ -374,6 +377,74 @@ def test_multi_tensor_compute_scale_and_scale_inv( torch.testing.assert_close(scale_inv, scale_inv_ref, rtol=0, atol=0) +@pytest.mark.parametrize("input_size_pair", [(777, 555), (555, 2048 * 32 + 1), (8, 8)]) +@pytest.mark.parametrize("applier", appliers) +@pytest.mark.parametrize("fp8_dtype", [torch.float8_e4m3fn, torch.float8_e5m2]) +@pytest.mark.parametrize("pow_2_scales", [False, True]) +@pytest.mark.parametrize("epsilon", [0.0, float.fromhex("0x1p-149"), 1e-12]) +def test_multi_tensor_compute_scale_and_scale_inv_blockwise( + input_size_pair, applier, fp8_dtype, pow_2_scales, epsilon +): + sizea, sizeb = input_size_pair + device = torch.device("cuda") + overflow_buf = torch.zeros(1, dtype=torch.int32, device=device) + a = torch.randn([sizea], dtype=torch.float32, device=device).abs() + b = torch.randn([sizeb], dtype=torch.float32, device=device).abs() + special = torch.tensor( + [ + 0.0, + -0.0, + 1e-45, + 1e-38, + 1e-36, + 2.6331075e-36, + 0.51171875, + 3.03125, + 448.0, + float("inf"), + float("nan"), + ], + dtype=torch.float32, + device=device, + ) + a[: min(sizea, special.numel())] = special[: min(sizea, special.numel())] + max_fp8 = torch.finfo(fp8_dtype).max + + amax_list = [a, b] + scale_list = [torch.full_like(x, -1.0) for x in amax_list] + scale_inv_list = [torch.full_like(x, -1.0) for x in amax_list] + + # Verify non-zero noop_flag leaves outputs untouched. + noop_buf = torch.ones(1, dtype=torch.int32, device=device) + applier( + tex.multi_tensor_compute_scale_and_scale_inv_blockwise, + noop_buf, + [amax_list, scale_list, scale_inv_list], + max_fp8, + pow_2_scales, + epsilon, + ) + for scale, scale_inv in zip(scale_list, scale_inv_list): + assert torch.all(scale == -1.0) + assert torch.all(scale_inv == -1.0) + + applier( + tex.multi_tensor_compute_scale_and_scale_inv_blockwise, + overflow_buf, + [amax_list, scale_list, scale_inv_list], + max_fp8, + pow_2_scales, + epsilon, + ) + + for amax, scale, scale_inv in zip(amax_list, scale_list, scale_inv_list): + scale_ref, scale_inv_ref, _ = blockwise_scale_from_amax_tensor( + amax, fp8_dtype, eps=epsilon, pow_2_scales=pow_2_scales + ) + torch.testing.assert_close(scale, scale_ref, rtol=0, atol=0) + torch.testing.assert_close(scale_inv, scale_inv_ref, rtol=0, atol=0) + + @pytest.mark.skipif(not mxfp8_available, reason=reason_for_no_mxfp8) @pytest.mark.parametrize("input_size_pair", input_size_pairs + [(1, 1)]) @pytest.mark.parametrize("applier", appliers) diff --git a/transformer_engine/common/cast/fp8_blockwise/group_quantize_fp8_blockwise.cuh b/transformer_engine/common/cast/fp8_blockwise/group_quantize_fp8_blockwise.cuh index 20689fce6d6..17ecdc64d76 100644 --- a/transformer_engine/common/cast/fp8_blockwise/group_quantize_fp8_blockwise.cuh +++ b/transformer_engine/common/cast/fp8_blockwise/group_quantize_fp8_blockwise.cuh @@ -382,7 +382,10 @@ __global__ void __launch_bounds__(kThreadsPerBlock, 4) group_block_scaled_2d_tma for (int w = 1; w < kNumWarps; ++w) { block_amax = fmaxf(block_amax, warp_amaxes[w]); } - const CType scale = compute_scale_from_types(block_amax, epsilon, pow_2_scales); + CType scale; + CType scale_inv; + compute_blockwise_scale_and_scale_inv(block_amax, epsilon, pow_2_scales, &scale, + &scale_inv); // The 2D colwise per-expert scale offset requires a CTA-cooperative prefix // sum in the VARYING_FIRST_DIM case, so compute it across all threads before @@ -396,7 +399,6 @@ __global__ void __launch_bounds__(kThreadsPerBlock, 4) group_block_scaled_2d_tma } if (leading_thread) { - const CType scale_inv = 1.f / scale; if constexpr (kReturnRowwise) { // 2D rowwise: kernel-global stride matches per-expert layout naturally. // Expert t's rows occupy [tensor_block_y_base, +blocks_y_t) of the buffer, @@ -533,8 +535,9 @@ __global__ void __launch_bounds__(kThreadsPerBlock) CType amax = compute_row_amax(in_vec[it]); amax = subwarp_reduce_max_broadcast(amax); - const CType scale = compute_scale_from_types(amax, epsilon, pow_2_scales); - const CType scale_inv = 1.f / scale; + CType scale; + CType scale_inv; + compute_blockwise_scale_and_scale_inv(amax, epsilon, pow_2_scales, &scale, &scale_inv); if (thr_col == 0 && r_global < R_total) { // Per-expert layout: (blocks_X, roundup(M_t, 4)). Compute expert base // offset + local stride matching cuBLAS grouped GEMM's per-expert view. @@ -661,8 +664,9 @@ __global__ void __launch_bounds__(kThreadsPerBlock) group_block_scaled_1d_tma_ke CType amax = compute_row_amax(in_vec); amax = subwarp_reduce_max_broadcast(amax); - const CType scale = compute_scale_from_types(amax, epsilon, pow_2_scales); - const CType scale_inv = 1.f / scale; + CType scale; + CType scale_inv; + compute_blockwise_scale_and_scale_inv(amax, epsilon, pow_2_scales, &scale, &scale_inv); const size_t r_global = global_row_base + row_local; const bool row_in_bounds = (r_global < R_total); @@ -737,8 +741,9 @@ __global__ void __launch_bounds__(kThreadsPerBlock) group_block_scaled_1d_tma_ke } amax = subwarp_reduce_max_broadcast(amax); - const CType scale = compute_scale_from_types(amax, epsilon, pow_2_scales); - const CType scale_inv = 1.f / scale; + CType scale; + CType scale_inv; + compute_blockwise_scale_and_scale_inv(amax, epsilon, pow_2_scales, &scale, &scale_inv); const size_t c_global = global_col_base + col_local; const bool col_in_bounds = (c_global < K); diff --git a/transformer_engine/common/include/transformer_engine/multi_tensor.h b/transformer_engine/common/include/transformer_engine/multi_tensor.h index 30f7669392e..95cfc6da22e 100644 --- a/transformer_engine/common/include/transformer_engine/multi_tensor.h +++ b/transformer_engine/common/include/transformer_engine/multi_tensor.h @@ -282,6 +282,25 @@ void nvte_multi_tensor_compute_scale_and_scale_inv_cuda(int chunk_size, NVTETens float max_fp8, int force_pow_2_scales, float epsilon, cudaStream_t stream); +/*! \brief Compute blockwise FP8 scale_inv first from amax and derive scale = 1 / scale_inv. + * + * \warning This API is **experimental** and subject to change. + * + * \param[in] chunk_size Number of tensor elements processed by a CUDA block. + * \param[in] noop_flag Single-element int32 GPU tensor; if non-zero, kernel exits immediately. + * \param[in,out] tensor_lists 2D array of input tensors. + * \param[in] num_tensor_lists Size (dim0) of tensor_lists. + * \param[in] num_tensors_per_list Size (dim1) of tensor_lists. + * \param[in] max_fp8 Maximum representible value in underlying FP8 format. + * \param[in] force_pow_2_scales Ensure scaling factors are a power of 2. + * \param[in] epsilon Floor applied to amax for numerical stability. + * \param[in] stream CUDA stream used for this operation. + */ +void nvte_multi_tensor_compute_scale_and_scale_inv_blockwise_cuda( + int chunk_size, NVTETensor noop_flag, NVTETensor **tensor_lists, const size_t num_tensor_lists, + const size_t num_tensors_per_list, float max_fp8, int force_pow_2_scales, float epsilon, + cudaStream_t stream); + /*! \brief Compute E8M0 scale_inv for a list of tensors. * * \warning This API is **experimental** and subject to change. diff --git a/transformer_engine/common/multi_tensor/compute_scale.cu b/transformer_engine/common/multi_tensor/compute_scale.cu index d4039352afe..cdcd56dba01 100644 --- a/transformer_engine/common/multi_tensor/compute_scale.cu +++ b/transformer_engine/common/multi_tensor/compute_scale.cu @@ -23,6 +23,7 @@ namespace multi_tensor_compute_scale { #define BLOCK_SIZE 256 +template struct ComputeScaleAndScaleInvFunctor { __device__ __forceinline__ void operator()(int64_t chunk_size, volatile int *noop_gmem, TensorListMetadata<3> &tl, // NOLINT(*) @@ -31,6 +32,11 @@ struct ComputeScaleAndScaleInvFunctor { // I'd like this kernel to propagate infs/nans. // if(*noop_gmem == 1) // return; + if constexpr (kDecodeScaleFirst) { + if (noop_gmem != nullptr && *noop_gmem) { + return; + } + } int tensor_loc = tl.block_to_tensor[blockIdx.x]; int chunk_idx = tl.block_to_chunk[blockIdx.x]; @@ -48,10 +54,17 @@ struct ComputeScaleAndScaleInvFunctor { n -= chunk_idx * chunk_size; for (int i_start = threadIdx.x; i_start < n && i_start < chunk_size; i_start += blockDim.x) { - float scale_val = transformer_engine::compute_scale_from_amax( - amax[i_start], max_fp8, force_pow_2_scales, epsilon, std::numeric_limits::max()); - scale[i_start] = scale_val; - transformer_engine::reciprocal(scale_inv + i_start, scale_val); + if constexpr (kDecodeScaleFirst) { + float scale_inv_val = transformer_engine::compute_decoding_scaling_factor_blockwise( + amax[i_start], max_fp8, force_pow_2_scales, epsilon); + scale_inv[i_start] = scale_inv_val; + transformer_engine::reciprocal(scale + i_start, scale_inv_val); + } else { + float scale_val = transformer_engine::compute_scale_from_amax( + amax[i_start], max_fp8, force_pow_2_scales, epsilon, std::numeric_limits::max()); + scale[i_start] = scale_val; + transformer_engine::reciprocal(scale_inv + i_start, scale_val); + } } } }; @@ -83,7 +96,23 @@ void multi_tensor_compute_scale_and_scale_inv_cuda(int chunk_size, Tensor noop_f float max_fp8, bool force_pow_2_scales, float epsilon, cudaStream_t stream) { multi_tensor_apply<3>(BLOCK_SIZE, chunk_size, noop_flag, tensor_lists, - ComputeScaleAndScaleInvFunctor(), stream, max_fp8, force_pow_2_scales, + ComputeScaleAndScaleInvFunctor(), stream, max_fp8, + force_pow_2_scales, epsilon); + NVTE_CHECK_CUDA(cudaGetLastError()); +} + +void multi_tensor_compute_scale_and_scale_inv_blockwise_cuda( + int chunk_size, Tensor noop_flag, std::vector> tensor_lists, + float max_fp8, bool force_pow_2_scales, float epsilon, cudaStream_t stream) { + if (noop_flag.data.dptr != nullptr) { + NVTE_CHECK(noop_flag.data.dtype == DType::kInt32, + "Expected noop_flag to have int32 dtype, but got ", to_string(noop_flag.data.dtype), + "."); + NVTE_CHECK(noop_flag.numel() == 1, "Expected noop_flag to have 1 element, but got ", + noop_flag.numel(), "."); + } + multi_tensor_apply<3>(BLOCK_SIZE, chunk_size, noop_flag, tensor_lists, + ComputeScaleAndScaleInvFunctor(), stream, max_fp8, force_pow_2_scales, epsilon); NVTE_CHECK_CUDA(cudaGetLastError()); } @@ -119,6 +148,19 @@ void nvte_multi_tensor_compute_scale_and_scale_inv_cuda(int chunk_size, NVTETens force_pow_2_scales, epsilon, stream); } +void nvte_multi_tensor_compute_scale_and_scale_inv_blockwise_cuda( + int chunk_size, NVTETensor noop_flag, NVTETensor **tensor_lists, const size_t num_tensor_lists, + const size_t num_tensors_per_list, float max_fp8, int force_pow_2_scales, float epsilon, + cudaStream_t stream) { + NVTE_API_CALL(nvte_multi_tensor_compute_scale_and_scale_inv_blockwise_cuda); + using namespace transformer_engine; + + multi_tensor_compute_scale::multi_tensor_compute_scale_and_scale_inv_blockwise_cuda( + chunk_size, *convertNVTETensorCheck(noop_flag), + convert_tensor_array(tensor_lists, num_tensor_lists, num_tensors_per_list), max_fp8, + force_pow_2_scales, epsilon, stream); +} + void nvte_multi_tensor_compute_scale_inv_e8m0_cuda(int chunk_size, NVTETensor **tensor_lists, const size_t num_tensor_lists, const size_t num_tensors_per_list, diff --git a/transformer_engine/common/recipe/recipe_common.cuh b/transformer_engine/common/recipe/recipe_common.cuh index 07839407a3f..6739760e1aa 100644 --- a/transformer_engine/common/recipe/recipe_common.cuh +++ b/transformer_engine/common/recipe/recipe_common.cuh @@ -48,24 +48,79 @@ __device__ __forceinline__ float compute_scale_from_amax(float amax, float max_f return scale; } -// Calculate the quantization scale for an individual data element -// given the amax(abs(tile)) value for a given quantization tile. +// Calculate the dequantization scale (scale_inv) first from amax / max_fp8 +// for blockwise FP8 quantization, then derive quantization scale = 1 / scale_inv. // -// -// Arguments: -// IType: data type of the tensor being quantized (float or bf16) -// OType: quantized data type (e4m3 or e5m2) -// amax: The evaluation of amax(abs(tile)) for the quantization tile. -// eps: An epsilon used as a floor for amax. -// pow_2_scaling: Whether to force the scale to be a power of 2. -template -__device__ __forceinline__ float compute_scale_from_types(const float amax, const float eps, - const float pow_2_scaling) { +// Computing scale_inv first matches the blockwise FP8 convention used by +// inference and kernel libraries: when force_pow_2_scales is true, scale_inv is +// rounded up to a power of two (>= amax / max_fp8); when force_pow_2_scales is +// false, scale_inv = __fdiv_rn(amax, max_fp8) directly without double-reciprocal +// rounding drift. Positive scale_inv is floored at FLT_MIN (2^-126) so both +// scale_inv and its reciprocal stay normal in FP32. +__device__ __forceinline__ float compute_decoding_scaling_factor_blockwise(float amax, + float max_fp8, + bool force_pow_2_scales, + float epsilon) { + // Use IEEE-754 bit operations for NaN/zero/epsilon handling so subnormal + // amax/epsilon values are preserved even in translation units compiled with + // --use_fast_math (-ftz=true). + uint32_t amax_bits = __float_as_uint(amax); + if ((amax_bits & 0x7FFFFFFFu) > 0x7F800000u) { + return 1.f; + } + + const uint32_t eps_bits = __float_as_uint(epsilon); + if ((eps_bits & 0x7FFFFFFFu) <= 0x7F800000u) { + const bool amax_neg = (amax_bits & 0x80000000u) != 0u; + const bool eps_neg = (eps_bits & 0x80000000u) != 0u; + const uint32_t amax_mag = amax_bits & 0x7FFFFFFFu; + const uint32_t eps_mag = eps_bits & 0x7FFFFFFFu; + bool less_than_eps = false; + if (amax_mag == 0u && eps_mag == 0u) { + less_than_eps = false; + } else if (amax_neg != eps_neg) { + less_than_eps = amax_neg; + } else if (amax_neg) { + less_than_eps = amax_mag > eps_mag; + } else { + less_than_eps = amax_mag < eps_mag; + } + if (less_than_eps) { + amax_bits = eps_bits; + } + } + + // Zero (+0.0 / -0.0), negative amax, or +-inf -> unit scale. + if ((amax_bits & 0x7FFFFFFFu) == 0u || (amax_bits & 0x80000000u) != 0u || + amax_bits >= 0x7F800000u) { + return 1.f; + } + + constexpr uint32_t kMinNormalFp32Bits = 0x00800000u; // 2^-126 (FLT_MIN) + const float raw_scale_inv = __fdiv_rn(__uint_as_float(amax_bits), max_fp8); + uint32_t scale_inv_bits = max(__float_as_uint(raw_scale_inv), kMinNormalFp32Bits); + + if (force_pow_2_scales) { + constexpr uint32_t kMaxPow2Bits = 0x7F000000u; // 2^127 + scale_inv_bits = ((min(scale_inv_bits, kMaxPow2Bits) + 0x7FFFFFu) & 0xFF800000u); + } + + __builtin_assume(scale_inv_bits != 0u); + __builtin_assume(scale_inv_bits != 0x80000000u); + return __uint_as_float(scale_inv_bits); +} + +template +__device__ __forceinline__ void compute_blockwise_scale_and_scale_inv(const float amax, + const float eps, + const bool pow_2_scaling, + float *scale_out, + float *scale_inv_out) { constexpr float fp8_max = TypeInfo::max_finite_value; - // NOTE: We're relying on compute_scale_from_amax to have behavior where it - // clips the mantissa of the max_finite_value if power of 2 scaling applies. - constexpr float value_for_inf = TypeInfo::max_finite_value; - return compute_scale_from_amax(amax, fp8_max, pow_2_scaling, eps, value_for_inf); + const float scale_inv = + compute_decoding_scaling_factor_blockwise(amax, fp8_max, pow_2_scaling, eps); + *scale_inv_out = scale_inv; + *scale_out = __frcp_rn(scale_inv); } } // namespace transformer_engine diff --git a/transformer_engine/common/transpose/quantize_transpose_square_blockwise.cu b/transformer_engine/common/transpose/quantize_transpose_square_blockwise.cu index 2d1a62e0fae..ff87ca66847 100644 --- a/transformer_engine/common/transpose/quantize_transpose_square_blockwise.cu +++ b/transformer_engine/common/transpose/quantize_transpose_square_blockwise.cu @@ -154,13 +154,12 @@ __global__ void __launch_bounds__(THREADS_PER_BLOCK) __syncthreads(); block_tile_amax = block_tile_amax_shared[0]; - block_tile_scale = - compute_scale_from_types(block_tile_amax, epsilon, pow_2_scaling); + static_assert(std::is_same::value); + CType scale_inv; + compute_blockwise_scale_and_scale_inv(block_tile_amax, epsilon, pow_2_scaling, + &block_tile_scale, &scale_inv); if (threadIdx.x == 0) { - static_assert(std::is_same::value); - const CType scale_inv = 1.0f / block_tile_scale; - if (tile_scales_inv_c != nullptr) { size_t row_idx = tile_id_y; size_t col_idx = tile_id_x; @@ -385,13 +384,12 @@ __global__ void __launch_bounds__(THREADS_PER_BLOCK) block_scaled_cast_transpose __syncthreads(); block_tile_amax = block_tile_amax_shared[0]; - block_tile_scale = - compute_scale_from_types(block_tile_amax, epsilon, pow_2_scaling); + static_assert(std::is_same::value); + CType scale_inv; + compute_blockwise_scale_and_scale_inv(block_tile_amax, epsilon, pow_2_scaling, + &block_tile_scale, &scale_inv); if (threadIdx.x == 0) { - static_assert(std::is_same::value); - const CType scale_inv = 1.0f / block_tile_scale; - if (tile_scales_inv_c != nullptr) { size_t row_idx = tile_id_y; size_t col_idx = tile_id_x; diff --git a/transformer_engine/common/transpose/quantize_transpose_vector_blockwise.cu b/transformer_engine/common/transpose/quantize_transpose_vector_blockwise.cu index df869b43317..ec4b491fa12 100644 --- a/transformer_engine/common/transpose/quantize_transpose_vector_blockwise.cu +++ b/transformer_engine/common/transpose/quantize_transpose_vector_blockwise.cu @@ -291,15 +291,16 @@ __global__ void __launch_bounds__(kThreadsPerBlock) block_scaled_1d_cast_transpo } amax = __shfl_sync(mask, amax, src_lane); CType scale; - // Step 2.4: Compute scale - scale = compute_scale_from_types(amax, epsilon, pow_2_scaling); + CType scale_inv; + // Step 2.4: Compute scale_inv and scale + compute_blockwise_scale_and_scale_inv(amax, epsilon, pow_2_scaling, &scale, + &scale_inv); // Step 2.5: Write scale_inv bool write_scale_inv = is_src_lane; if constexpr (!kAligned) { write_scale_inv &= (r_g < num_rows); } if (write_scale_inv) { - CType scale_inv = 1.0 / scale; size_t row_idx = static_cast(blockIdx.y) * kTileDim + r_s; size_t col_idx = static_cast(blockIdx.x); tile_scales_inv_c[row_idx * scale_stride_y + col_idx * scale_stride_x] = scale_inv; @@ -379,16 +380,17 @@ __global__ void __launch_bounds__(kThreadsPerBlock) block_scaled_1d_cast_transpo amax = fmaxf(amax, other_amax); } amax = __shfl_sync(mask, amax, src_lane); - // Step 3.4: Compute scale + // Step 3.4: Compute scale_inv and scale CType scale; - scale = compute_scale_from_types(amax, epsilon, pow_2_scaling); + CType scale_inv; + compute_blockwise_scale_and_scale_inv(amax, epsilon, pow_2_scaling, &scale, + &scale_inv); // Step 3.5: Write scale_inv_t bool write_scale_inv = is_src_lane; if constexpr (!kAligned) { write_scale_inv &= (r_g + smem_idx < row_length); } if (write_scale_inv) { - CType scale_inv = 1.0 / scale; size_t row_idx = static_cast(blockIdx.x) * kTileDim + c_s * kNVecSMem + smem_idx; size_t col_idx = static_cast(blockIdx.y); tile_scales_inv_t[row_idx * scale_t_stride_y + col_idx * scale_t_stride_x] = scale_inv; @@ -475,9 +477,11 @@ __global__ void __launch_bounds__(kThreadsPerBlock) block_scaled_1d_cast_transpo amax = warp_reduce_max(amax); constexpr int lane_zero = 0; amax = __shfl_sync(0xFFFFFFFF, amax, lane_zero); - // Step 3.4: Compute scale + // Step 3.4: Compute scale_inv and scale CType scale; - scale = compute_scale_from_types(amax, epsilon, pow_2_scaling); + CType scale_inv; + compute_blockwise_scale_and_scale_inv(amax, epsilon, pow_2_scaling, &scale, + &scale_inv); thr_scale.data.elt[reg_idx] = scale; // Step 3.5: Write scale_inv_t bool write_scale_inv = is_src_lane; @@ -485,7 +489,6 @@ __global__ void __launch_bounds__(kThreadsPerBlock) block_scaled_1d_cast_transpo write_scale_inv &= (c_g + reg_idx < row_length); } if (write_scale_inv) { - CType scale_inv = 1.0 / scale; size_t row_idx = static_cast(blockIdx.y); size_t col_idx = static_cast(blockIdx.x) * kTileDim + c_s * kNVecSMem + reg_idx; tile_scales_inv_t[row_idx * scale_t_stride_y + col_idx * scale_t_stride_x] = scale_inv; diff --git a/transformer_engine/pytorch/csrc/extensions.h b/transformer_engine/pytorch/csrc/extensions.h index 4a582ac24c2..2a03e5628fd 100644 --- a/transformer_engine/pytorch/csrc/extensions.h +++ b/transformer_engine/pytorch/csrc/extensions.h @@ -723,6 +723,10 @@ void multi_tensor_compute_scale_and_scale_inv_cuda( int chunk_size, at::Tensor noop_flag, std::vector> tensor_lists, float max_fp8, bool force_pow_2_scales, float epsilon); +void multi_tensor_compute_scale_and_scale_inv_blockwise_cuda( + int chunk_size, at::Tensor noop_flag, std::vector> tensor_lists, + float max_fp8, bool force_pow_2_scales, float epsilon); + void multi_tensor_compute_scale_inv_e8m0_cuda(int chunk_size, const py::object &dummy, std::vector> tensor_lists); diff --git a/transformer_engine/pytorch/csrc/extensions/multi_tensor/compute_scale.cpp b/transformer_engine/pytorch/csrc/extensions/multi_tensor/compute_scale.cpp index 328970ffa8b..ca9be4b358a 100644 --- a/transformer_engine/pytorch/csrc/extensions/multi_tensor/compute_scale.cpp +++ b/transformer_engine/pytorch/csrc/extensions/multi_tensor/compute_scale.cpp @@ -20,6 +20,21 @@ void multi_tensor_compute_scale_and_scale_inv_cuda( force_pow_2_scales, epsilon, at::cuda::getCurrentCUDAStream()); } +void multi_tensor_compute_scale_and_scale_inv_blockwise_cuda( + int chunk_size, at::Tensor noop_flag, std::vector> tensor_lists, + float max_fp8, bool force_pow_2_scales, float epsilon) { + NVTE_CHECK(noop_flag.is_cuda(), "noop_flag must be a CUDA tensor."); + NVTE_CHECK(noop_flag.scalar_type() == at::kInt, "noop_flag must be an int32 tensor."); + NVTE_CHECK(noop_flag.numel() == 1, "noop_flag must have 1 element."); + auto noop_flag_cu = makeTransformerEngineTensor(noop_flag); + auto [_, __, tensor_lists_ptr, num_lists, num_tensors] = + makeTransformerEngineTensorList(tensor_lists); + + nvte_multi_tensor_compute_scale_and_scale_inv_blockwise_cuda( + chunk_size, noop_flag_cu.data(), tensor_lists_ptr.data(), num_lists, num_tensors, max_fp8, + force_pow_2_scales, epsilon, at::cuda::getCurrentCUDAStream()); +} + void multi_tensor_compute_scale_inv_e8m0_cuda(int chunk_size, const py::object &dummy, std::vector> tensor_lists) { NVTE_CHECK(dummy.is_none(), "No-op flag is not supported."); diff --git a/transformer_engine/pytorch/csrc/extensions/pybind.cpp b/transformer_engine/pytorch/csrc/extensions/pybind.cpp index 82fa3ec2428..e8ff81d4ba2 100644 --- a/transformer_engine/pytorch/csrc/extensions/pybind.cpp +++ b/transformer_engine/pytorch/csrc/extensions/pybind.cpp @@ -773,6 +773,10 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("multi_tensor_compute_scale_and_scale_inv", &transformer_engine::pytorch::multi_tensor_compute_scale_and_scale_inv_cuda, "Fused compute scale and scale_inv from amax", py::call_guard()); + m.def("multi_tensor_compute_scale_and_scale_inv_blockwise", + &transformer_engine::pytorch::multi_tensor_compute_scale_and_scale_inv_blockwise_cuda, + "Fused compute blockwise scale_inv first from amax and derive scale", + py::call_guard()); m.def("multi_tensor_compute_scale_inv_e8m0", &transformer_engine::pytorch::multi_tensor_compute_scale_inv_e8m0_cuda, "Fused compute E8M0 scale_inv from amax", py::call_guard()); diff --git a/transformer_engine/pytorch/tensor/utils.py b/transformer_engine/pytorch/tensor/utils.py index caaf9cf5aad..787e2cfac2e 100644 --- a/transformer_engine/pytorch/tensor/utils.py +++ b/transformer_engine/pytorch/tensor/utils.py @@ -11,6 +11,7 @@ from transformer_engine_torch import ( multi_tensor_scale, multi_tensor_compute_scale_and_scale_inv, + multi_tensor_compute_scale_and_scale_inv_blockwise, multi_tensor_compute_scale_inv_e8m0, ) @@ -708,7 +709,7 @@ def _cast_master_weights_to_fp8_blockwise_scaling( else: raise ValueError(f"Unsupported FP8 dtype: {fp8_dtype}") multi_tensor_applier( - multi_tensor_compute_scale_and_scale_inv, + multi_tensor_compute_scale_and_scale_inv_blockwise, dummy_overflow_buf, [amaxes, scales, scale_invs], max_fp8,