Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
51 changes: 26 additions & 25 deletions tests/cpp/operator/test_cast_float8blockwise.cu
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@
#include <transformer_engine/activation.h>
#include <transformer_engine/cast.h>

#include <algorithm>
#include <cmath>
#include <cstring>

#include "../test_common.h"
#include "transformer_engine/transformer_engine.h"

Expand Down Expand Up @@ -47,27 +51,30 @@ enum ActivationType {
template <typename InputType, typename OutputType>
void scales_from_amax(float amax, const QuantizationOptions& opts, float* qscale_out,
float* qscale_inv_out) {
float input_type_max_val = Quantized_Limits<InputType>::max();
float quant_type_max_val = Quantized_Limits<OutputType>::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<uint32_t*>(&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<int32_t>(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;
}
Expand Down Expand Up @@ -411,9 +418,8 @@ void runTestCaseOneDimensionalBlocks(const ProcessingMethod processing_method,
}

std::vector<std::vector<size_t>> 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<InputsFillCase> input_scenarios = {
Expand All @@ -438,10 +444,9 @@ std::vector<ActivationType> Activation_types = {
// ActivationType::SReLU,
};


std::vector<float> amax_epsilons = {
0.0f,
1.0f, // Make large to be observable.
1.0f, // Make large to be observable.

};

Expand All @@ -461,19 +466,15 @@ class FusedCastFloat8VectorwiseTestSuite
switch (OP_FUNC_TYPE) { \
case ActivationType::Identity: { \
constexpr auto OP = &identity; \
{ \
__VA_ARGS__ \
} \
{ __VA_ARGS__ } \
} break; \
}

#define ACT_FUNC_SWITCH(OP_FUNC_TYPE, OP, ...) \
switch (OP_FUNC_TYPE) { \
case ActivationType::Identity: { \
constexpr auto OP = &identity; \
{ \
__VA_ARGS__ \
} \
{ __VA_ARGS__ } \
} break; \
}

Expand Down
8 changes: 3 additions & 5 deletions tests/pytorch/references/blockwise_quantizer_reference.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
36 changes: 36 additions & 0 deletions tests/pytorch/references/quantize_scale_calc.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
68 changes: 68 additions & 0 deletions tests/pytorch/test_float8_blockwise_scaling_exact.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Comment on lines +551 to +553

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 FP8 values go unchecked

The new regression test checks only scale_inv, not the FP8 values produced with it. It would still pass if a kernel stored the new decoding scale but kept the old quantization multiplier—the second discrepancy this PR aims to fix. Add an interior value near an FP8 rounding boundary and compare both _rowwise_data and _columnwise_data against the decode-first reference.

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
73 changes: 72 additions & 1 deletion tests/pytorch/test_multi_tensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
Expand Down Expand Up @@ -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)
Expand Down
Loading