diff --git a/qa/L1_pytorch_distributed_unittest/test.sh b/qa/L1_pytorch_distributed_unittest/test.sh index 35a3a03d128..daf3752fe1d 100644 --- a/qa/L1_pytorch_distributed_unittest/test.sh +++ b/qa/L1_pytorch_distributed_unittest/test.sh @@ -65,6 +65,7 @@ python3 -m pytest -v -s --junitxml=$XML_LOG_DIR/pytest_test_fusible_ops_with_use python3 -m pytest -v -s --junitxml=$XML_LOG_DIR/pytest_test_cp_utils.xml $TE_PATH/tests/pytorch/attention/test_cp_utils.py || test_fail "test_cp_utils.py" python3 -m pytest -v -s --junitxml=$XML_LOG_DIR/pytest_test_cu_seqlens_cache.xml $TE_PATH/tests/pytorch/attention/test_cu_seqlens_cache.py || test_fail "test_cu_seqlens_cache.py" python3 -m pytest -v -s --junitxml=$XML_LOG_DIR/pytest_test_cast_master_weights_to_fp8.xml $TE_PATH/tests/pytorch/distributed/test_cast_master_weights_to_fp8.py || test_fail "test_cast_master_weights_to_fp8.py" +python3 -m pytest -v -s --junitxml=$XML_LOG_DIR/pytest_test_nvfp4_master_weight_cast.xml $TE_PATH/tests/pytorch/distributed/test_nvfp4_master_weight_cast.py || test_fail "test_nvfp4_master_weight_cast.py" python3 -m pytest -v -s --junitxml=$XML_LOG_DIR/pytest_test_newton_schulz.xml $TE_PATH/tests/pytorch/distributed/test_newton_schulz.py || test_fail "test_newton_schulz.py" python3 -m pytest -v -s --junitxml=$XML_LOG_DIR/pytest_test_ep.xml $TE_PATH/tests/pytorch/distributed/test_ep.py || test_fail "test_ep.py" diff --git a/tests/pytorch/distributed/test_nvfp4_master_weight_cast.py b/tests/pytorch/distributed/test_nvfp4_master_weight_cast.py new file mode 100644 index 00000000000..24b4fd07ab1 --- /dev/null +++ b/tests/pytorch/distributed/test_nvfp4_master_weight_cast.py @@ -0,0 +1,275 @@ +# Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# See LICENSE for license information. + +"""quantize_master_weights for NVFP4 2D weights against a full-tensor NVFP4 quantization. + +Each rank owns an uneven, contiguous slice of the concatenated weights, as a distributed +optimizer does. The slice boundaries cut tensors in the middle of rows and of 16x16 tiles. +The FP32 masters are not representable in the model dtype and include all-zero tiles and +outliers. For several update steps, every rank's amaxes and scale-inverses, and the FP4 bytes of +its own shards, must equal those of NVFP4Quantizer applied to the full master weights cast to +the model dtype; the bytes outside its shards must be left unchanged. +""" + +import argparse +import pathlib +import sys + +sys.path.append(str(pathlib.Path(__file__).resolve().parent.parent)) +from utils import run_distributed + +import pytest +import torch +import torch.distributed as dist + +import transformer_engine.pytorch as te +from transformer_engine.common.recipe import NVFP4BlockScaling +from transformer_engine.pytorch import NVFP4Quantizer, is_nvfp4_available +import transformer_engine.pytorch.tensor.utils as te_utils + +SHAPES = [ + (4096, 7168), + (7168, 2048), + (512, 512), + (256, 1536), + (48, 64), # scale rows padded beyond the tile rows + (1024, 2048), + (128, 7168), + (7168, 128), + (64, 4096), + (40, 96), # partial tile rows; the scale-inverse has 8 columns for 6 tile columns + (2112, 7168), +] * 3 # more tensors than one launch takes + + +def _make_weights(shapes, model_dtypes): + torch.manual_seed(1234) + with te.quantized_model_init(enabled=True, recipe=NVFP4BlockScaling()): + layers = [ + te.Linear(w, h, bias=False, params_dtype=dtype, device="cuda") + for (h, w), dtype in zip(shapes, model_dtypes) + ] + return [layer.weight for layer in layers] + + +def _masters(shapes): + torch.manual_seed(999) # same full masters on every rank + masters = [] + for i, (h, w) in enumerate(shapes): + m = torch.randn(h, w, device="cuda", dtype=torch.float32) * (0.02 * (1 + i % 3)) + if i % 4 == 1: + m[: h // 3] *= 1e-3 + if i % 5 == 2: + m[:16, :16] = 0 # all-zero tile + if i == 0: + m[5, 7] = 3.7 # outlier + masters.append(m) + return masters + + +def _rank_slice(numels, rank, world, seed, cuts_2_mod_4=False): + """Uneven contiguous slice of the flat space, cut at even offsets (all of them 2 mod 4 with + cuts_2_mod_4, which no tensor boundary is, since every numel is a multiple of 16).""" + total = sum(numels) + g = torch.Generator().manual_seed(seed) + cuts = (torch.rand(world - 1, generator=g) * total).tolist() + if cuts_2_mod_4: + cuts = sorted({int(x) // 4 * 4 + 2 for x in cuts}) + else: + cuts = sorted({int(x) // 2 * 2 for x in cuts}) + bounds = [0] + cuts + [total] * (world - len(cuts)) + return bounds[rank], bounds[rank + 1] + + +def _shards(masters, lo, hi, dtype, layout): + """This rank's master shards, their start offsets and their [start, end) element spans. + + layout "clone": each shard in its own allocation, so a shard that starts at an offset of + 2 mod 4 is misaligned for vector loads. "view": each shard is a view into a buffer of the + whole tensor, as in a distributed optimizer's flat buffer, so its tile rows stay aligned + at any even offset. "strided": non-contiguous shards. + """ + shards, offsets, spans = [], [], [] + base = 0 + for m in masters: + n = m.numel() + s, e = max(lo, base), min(hi, base + n) + if s < e: + values = m.view(-1)[s - base : e - base].to(dtype) + if layout == "clone": + shard = values.clone() + elif layout == "view": + shard = torch.empty(n, dtype=dtype, device="cuda")[s - base : e - base] + shard.copy_(values) + else: + assert layout == "strided", layout + shard = torch.empty(2 * values.numel(), dtype=dtype, device="cuda")[::2] + shard.copy_(values) + shards.append(shard) + offsets.append(s - base) + spans.append((s - base, e - base)) + else: + shards.append(None) + offsets.append(None) + spans.append(None) + base += n + return shards, offsets, spans + + +def _update(masters, shards, spans, generator): + """An optimizer step: the same update of the full masters on every rank, copied in place + into this rank's shards.""" + for m, shard, span in zip(masters, shards, spans): + m.add_(torch.randn(m.shape, device="cuda", generator=generator) * 1e-3) + if shard is not None: + shard.copy_(m.view(-1)[span[0] : span[1]]) + + +def _quantize(weights, shards, offsets, group): + te_utils.quantize_master_weights( + weights, shards, offsets, group, manual_post_all_gather_processing=True + ) + + +def _check(weights, data_before, masters, master_dtype, spans, tag): + rank = dist.get_rank() + reference_quantizer = NVFP4Quantizer(rowwise=True, columnwise=False, with_2d_quantization=True) + bad = [] + for i, (weight, before, master, span) in enumerate(zip(weights, data_before, masters, spans)): + ref = reference_quantizer(master.to(master_dtype).to(weight.dtype)) + h, w = weight.shape + tile_cols = (w + 15) // 16 + name = f"[rank {rank}] {tag} tensor {i} {(h, w)} {weight.dtype}" + if not torch.equal(weight._amax_rowwise, ref._amax_rowwise): + bad.append(f"{name} amax") + scale_inv = weight._rowwise_scale_inv.view(torch.uint8)[:h, :tile_cols] + if not torch.equal(scale_inv, ref._rowwise_scale_inv.view(torch.uint8)[:h, :tile_cols]): + bad.append(f"{name} scale_inv") + expected = before.clone() + if span is not None: + s, e = span + ref_data = ref._rowwise_data.view(torch.uint8).view(-1) + expected[s // 2 : e // 2] = ref_data[s // 2 : e // 2] + if e % 2: # the high nibble of the last byte belongs to the next rank + expected[e // 2] = (expected[e // 2] & 0xF0) | (ref_data[e // 2] & 0x0F) + if not torch.equal(weight._rowwise_data.view(torch.uint8).view(-1), expected): + bad.append(f"{name} rowwise data") + flag = torch.tensor([len(bad)], device="cuda") + dist.all_reduce(flag) + assert flag.item() == 0, "\n".join(bad) or "mismatch on another rank" + + +def _snapshot(weights): + return [w._rowwise_data.view(torch.uint8).view(-1).clone() for w in weights] + + +def _check_cast(model_dtypes, master_dtype, seed, layout="clone", cuts_2_mod_4=False): + rank, world = dist.get_rank(), dist.get_world_size() + group = dist.new_group(ranks=list(range(world))) + weights = _make_weights(SHAPES, model_dtypes) + masters = _masters(SHAPES) + lo, hi = _rank_slice([h * w for h, w in SHAPES], rank, world, seed, cuts_2_mod_4) + shards, offsets, spans = _shards(masters, lo, hi, master_dtype, layout) + generator = torch.Generator(device="cuda").manual_seed(seed) + for step in range(3): + if step > 0: + _update(masters, shards, spans, generator) + before = _snapshot(weights) + _quantize(weights, shards, offsets, group) + torch.cuda.synchronize() + _check(weights, before, masters, master_dtype, spans, f"{master_dtype} step {step}") + + +def _check_cuda_graph(seed): + """Capture the cast once and replay it after in-place master updates.""" + rank, world = dist.get_rank(), dist.get_world_size() + group = dist.new_group(ranks=list(range(world))) + shapes = SHAPES[:11] + weights = _make_weights(shapes, [torch.bfloat16] * len(shapes)) + masters = _masters(shapes) + lo, hi = _rank_slice([h * w for h, w in shapes], rank, world, seed) + shards, offsets, spans = _shards(masters, lo, hi, torch.float32, layout="clone") + + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + for _ in range(2): # warm up NCCL and the allocator outside the capture + _quantize(weights, shards, offsets, group) + torch.cuda.current_stream().wait_stream(stream) + torch.cuda.synchronize() + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph, stream=stream): + _quantize(weights, shards, offsets, group) + + generator = torch.Generator(device="cuda").manual_seed(seed) + for step in range(3): + _update(masters, shards, spans, generator) + before = _snapshot(weights) + graph.replay() + torch.cuda.synchronize() + _check(weights, before, masters, torch.float32, spans, f"cuda graph replay {step}") + + +def _check_odd_offset_rejected(): + """Two FP4 values share a byte, so a shard that starts at an odd offset is an error.""" + group = dist.new_group(ranks=list(range(dist.get_world_size()))) + weight = _make_weights([(64, 64)], [torch.bfloat16])[0] + shard = torch.zeros(64 * 64 - 1, device="cuda") + # Every rank passes an odd offset, so every rank raises before the all-reduce. + with pytest.raises(ValueError, match="even element offset"): + _quantize([weight], [shard], [1], group) + + +def _worker(): + dist.init_process_group("nccl") + torch.cuda.set_device(dist.get_rank() % torch.cuda.device_count()) + try: + n = len(SHAPES) + bf16, fp32, fp16 = torch.bfloat16, torch.float32, torch.float16 + # BF16 model weights with FP32 masters: values are rounded to BF16 in registers. + _check_cast([bf16] * n, fp32, seed=77) + _check_cast([bf16] * n, fp32, seed=78) + # FP32 model weights: no rounding. + _check_cast([fp32] * n, fp32, seed=79) + # BF16 masters. + _check_cast([bf16] * n, bf16, seed=80) + # Mixed model dtypes in one call, including FP16. + _check_cast([(bf16, fp32, fp16)[i % 3] for i in range(n)], fp32, seed=82) + # Non-contiguous master shards. + _check_cast([bf16] * n, fp32, seed=83, layout="strided") + # Shards that start at offsets of 2 mod 4: vector loads and stores as views into + # whole-tensor buffers, per-element accesses as separate allocations. + _check_cast([bf16] * n, fp32, seed=84, layout="view", cuts_2_mod_4=True) + _check_cast([bf16] * n, fp32, seed=85, layout="clone", cuts_2_mod_4=True) + _check_odd_offset_rejected() + _check_cuda_graph(seed=81) + dist.barrier() + finally: + dist.destroy_process_group() + + +@pytest.mark.parametrize("world_size", [1, 2, 4]) +def test_nvfp4_master_weight_cast(world_size: int) -> None: + """Launch the distributed NVFP4 master-weight cast test.""" + available, reason = is_nvfp4_available(return_reason=True) + if not available: + pytest.skip(reason) + if torch.cuda.device_count() < world_size: + pytest.skip(f"needs {world_size} GPUs") + command = [ + sys.executable, + "-m", + "torch.distributed.run", + f"--nproc_per_node={world_size}", + str(pathlib.Path(__file__).resolve()), + "--worker", + ] + run_distributed(command) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--worker", action="store_true") + if parser.parse_args().worker: + _worker() diff --git a/transformer_engine/common/CMakeLists.txt b/transformer_engine/common/CMakeLists.txt index 26bd44c0156..bc74ce52468 100644 --- a/transformer_engine/common/CMakeLists.txt +++ b/transformer_engine/common/CMakeLists.txt @@ -382,6 +382,7 @@ list(APPEND transformer_engine_cuda_arch_specific_sources normalization/rmsnorm/rmsnorm_fwd_mxfp8.cu recipe/mxfp8_scaling.cu recipe/nvfp4.cu + recipe/nvfp4_multi_tensor.cu transpose/quantize_transpose_square_blockwise.cu transpose/quantize_transpose_vector_blockwise_fp4.cu) diff --git a/transformer_engine/common/include/transformer_engine/recipe.h b/transformer_engine/common/include/transformer_engine/recipe.h index 1c9af7d4fcf..68b0d218b14 100644 --- a/transformer_engine/common/include/transformer_engine/recipe.h +++ b/transformer_engine/common/include/transformer_engine/recipe.h @@ -378,7 +378,7 @@ void nvte_nvfp4_2d_compute_partial_amax(const NVTETensor inp, NVTETensor amax, s * \param[in] w Number of columns in the full 2D tensor. * \param[in] scale_stride_h Stride for scale in tile-row dimension. * \param[in] scale_stride_w Stride for scale in tile-col dimension. - * \param[in] start_offset Starting element offset in the flattened tensor. + * \param[in] start_offset Starting element offset in the flattened tensor (even). * \param[in] block_len Tile dimension (must be 16 for NVFP4 2D). * \param[in] stream CUDA stream used for the operation. */ @@ -399,7 +399,7 @@ void nvte_nvfp4_2d_partial_cast(const NVTETensor inp, NVTETensor out, const NVTE * \param[in] w Number of columns in the full 2D tensor. * \param[in] scale_stride_h Stride for scale in tile-row dimension. * \param[in] scale_stride_w Stride for scale in tile-col dimension. - * \param[in] start_offset Starting element offset in the flattened tensor. + * \param[in] start_offset Starting element offset in the flattened tensor (even). * \param[in] block_len Tile dimension (must be 16 for NVFP4 2D). * \param[in] scale_dtype NVFP4 scale storage type (E4M3 or UE5M3). * \param[in] stream CUDA stream used for the operation. @@ -483,7 +483,8 @@ void nvte_nvfp4_compute_per_block_scale_v2(const NVTETensor block_amax, NVTETens * \param[in] block_amax Input block amax tensor [tile_rows, tile_cols], float32. * \param[in] global_amax Global amax tensor [1], float32. * \param[out] per_block_scale Output per-block scale [tile_rows, tile_cols], float32 (for partial_cast). - * \param[out] target_scale Output scale tensor [rows_padded, tile_cols], uint8. + * \param[out] target_scale Output scale tensor [rows_padded, columns >= tile_cols], uint8; + * rows are `columns` apart for a 2D tensor. * \param[out] target_amax Output amax tensor [1], float32 (copy of global_amax). * \param[in] tile_rows Number of tile rows. * \param[in] tile_cols Number of tile columns. @@ -503,7 +504,8 @@ void nvte_nvfp4_fused_scale(const NVTETensor block_amax, const NVTETensor global * \param[in] block_amax Input block amax tensor [tile_rows, tile_cols], float32. * \param[in] global_amax Global amax tensor [1], float32. * \param[out] per_block_scale Output per-block scale [tile_rows, tile_cols], float32 (for partial_cast). - * \param[out] target_scale Output scale tensor [rows_padded, tile_cols], uint8. + * \param[out] target_scale Output scale tensor [rows_padded, columns >= tile_cols], uint8; + * rows are `columns` apart for a 2D tensor. * \param[out] target_amax Output amax tensor [1], float32 (copy of global_amax). * \param[in] tile_rows Number of tile rows. * \param[in] tile_cols Number of tile columns. @@ -542,6 +544,92 @@ void nvte_nvfp4_compute_global_scale(const NVTETensor global_amax, NVTETensor gl void nvte_nvfp4_compute_global_scale_v2(const NVTETensor global_amax, NVTETensor global_scale, NVTEDType scale_dtype, cudaStream_t stream); +/*! \brief Compute the 16x16 tile amaxes of the partial shards of several 2D tensors. + * + * Multi-tensor version of nvte_nvfp4_2d_compute_partial_amax for contiguous amax buffers. + * The shards of one call share one dtype (FP32, BF16 or FP16). Each value is converted to + * `cast_dtype` before the amax is taken, so an FP32 master shard with `cast_dtype` = BF16 + * gives the amaxes of the shard cast to BF16. Tiles that do not overlap a shard are not + * written, so the amax buffers should be zero-initialized. + * + * \param[in] inp Input shards, one per tensor (may be empty). + * \param[out] amax Amax buffers [ceil(h / 16), ceil(w / 16)], float32. + * \param[in] h Number of rows of each full 2D tensor. + * \param[in] w Number of columns of each full 2D tensor. + * \param[in] start_offset Element offset of each shard in its flattened tensor (even). + * \param[in] num_tensors Number of tensors. + * \param[in] block_len Tile dimension (must be 16). + * \param[in] cast_dtype kNVTEFloat32, kNVTEBFloat16 or kNVTEFloat16. + * \param[in] stream CUDA stream used for the operation. + */ +void nvte_nvfp4_2d_multi_tensor_partial_amax(const NVTETensor* inp, NVTETensor* amax, + const size_t* h, const size_t* w, + const size_t* start_offset, size_t num_tensors, + size_t block_len, NVTEDType cast_dtype, + cudaStream_t stream); + +/*! \brief Compute per-tensor global amaxes as the maximum of each tensor's tile amaxes. + * + * After the tile amaxes have been max-reduced across the ranks that hold shards of a + * tensor, this equals the reduced amax of the whole tensor. + * + * \param[in] block_amax Tile amax buffers, float32, contiguous. + * \param[out] global_amax Global amaxes [1], float32. + * \param[in] num_tensors Number of tensors. + * \param[in] stream CUDA stream used for the operation. + */ +void nvte_nvfp4_2d_multi_tensor_global_amax(const NVTETensor* block_amax, NVTETensor* global_amax, + size_t num_tensors, cudaStream_t stream); + +/*! \brief Multi-tensor version of nvte_nvfp4_fused_scale_v2. + * + * Computes the same per-block decode scales, row-expanded target scales and target amaxes as + * nvte_nvfp4_fused_scale_v2 for every tensor. The tile counts are the shape of `block_amax`, + * and the padded rows and row stride are the shape of `target_scale`. All buffers are + * contiguous. + * + * \param[in] block_amax Tile amaxes [tile_rows, tile_cols], float32. + * \param[in] global_amax Global amaxes [1], float32. + * \param[out] per_block_scale Per-block decode scales [tile_rows, tile_cols], float32. + * \param[out] target_scale Expanded scales [rows_padded, columns >= tile_cols], uint8. + * \param[out] target_amax Copies of the global amaxes [1], float32. + * \param[in] num_tensors Number of tensors. + * \param[in] block_len Tile dimension (must be 16). + * \param[in] scale_dtype NVFP4 scale storage type (E4M3 or UE5M3). + * \param[in] stream CUDA stream used for the operation. + */ +void nvte_nvfp4_2d_multi_tensor_fused_scale(const NVTETensor* block_amax, + const NVTETensor* global_amax, + NVTETensor* per_block_scale, NVTETensor* target_scale, + NVTETensor* target_amax, size_t num_tensors, + size_t block_len, NVTEDType scale_dtype, + cudaStream_t stream); + +/*! \brief Cast the partial shards of several 2D tensors to NVFP4 with 16x16 tile scales. + * + * Multi-tensor version of nvte_nvfp4_2d_partial_cast_v2 for contiguous scale buffers. Gives + * the same bytes as nvte_nvfp4_2d_partial_cast_v2 applied to the shards converted to + * `cast_dtype`. The shards of one call share one dtype (FP32, BF16 or FP16). + * + * \param[in] inp Input shards, one per tensor (may be empty). + * \param[out] out Packed FP4 bytes of each shard (element i of the flattened + * tensor at byte (i - start_offset) / 2). + * \param[in] scale Per-tile decode scales [ceil(h / 16), ceil(w / 16)], float32. + * \param[in] global_scale Global encode scales [1], float32. + * \param[in] h Number of rows of each full 2D tensor. + * \param[in] w Number of columns of each full 2D tensor. + * \param[in] start_offset Element offset of each shard in its flattened tensor (even). + * \param[in] num_tensors Number of tensors. + * \param[in] block_len Tile dimension (must be 16). + * \param[in] cast_dtype kNVTEFloat32, kNVTEBFloat16 or kNVTEFloat16. + * \param[in] scale_dtype NVFP4 scale storage type (E4M3 or UE5M3). + * \param[in] stream CUDA stream used for the operation. + */ +void nvte_nvfp4_2d_multi_tensor_partial_cast( + const NVTETensor* inp, NVTETensor* out, const NVTETensor* scale, const NVTETensor* global_scale, + const size_t* h, const size_t* w, const size_t* start_offset, size_t num_tensors, + size_t block_len, NVTEDType cast_dtype, NVTEDType scale_dtype, cudaStream_t stream); + #ifdef __cplusplus } // extern "C" #endif diff --git a/transformer_engine/common/recipe/nvfp4.cu b/transformer_engine/common/recipe/nvfp4.cu index 14a0264074e..2032b61310f 100644 --- a/transformer_engine/common/recipe/nvfp4.cu +++ b/transformer_engine/common/recipe/nvfp4.cu @@ -295,6 +295,10 @@ void nvfp4_2d_partial_cast(const Tensor inp, Tensor out, const Tensor scale, DType scale_dtype, cudaStream_t stream) { NVTE_CHECK(block_len == 16, "NVFP4 2D supports 16x16 tiles only (block_len = 16)."); NVTE_CHECK(out.dtype() == DType::kByte, "NVFP4 rowwise data must be uint8."); + // `out` starts at the byte that holds element start_offset, so an odd offset would put every + // later element pair in the previous byte. + NVTE_CHECK(start_offset % 2 == 0, "NVFP4 2D shards must start at an even element offset, got ", + start_offset, "."); size_t len = inp.numel(); @@ -752,10 +756,10 @@ __global__ void nvfp4_fused_scale_kernel( const float *__restrict__ block_amax, // [tile_rows, tile_cols] const float *__restrict__ global_amax, // [1] float *__restrict__ per_block_scale, // [tile_rows, tile_cols] - for partial_cast - ScaleType *__restrict__ target_scale, // [rows_padded, tile_cols] + ScaleType *__restrict__ target_scale, // [rows_padded, target_scale_stride] float *__restrict__ target_amax, // [1] const size_t tile_rows, const size_t tile_cols, const size_t rows_padded, - const size_t block_len) { + const size_t target_scale_stride, const size_t block_len) { const size_t out_row = blockIdx.y * blockDim.y + threadIdx.y; const size_t out_col = blockIdx.x * blockDim.x + threadIdx.x; @@ -796,7 +800,7 @@ __global__ void nvfp4_fused_scale_kernel( } } - target_scale[out_row * tile_cols + out_col] = static_cast(scale_val); + target_scale[out_row * target_scale_stride + out_col] = static_cast(scale_val); } void nvfp4_fused_scale(const Tensor block_amax, const Tensor global_amax, Tensor per_block_scale, @@ -814,6 +818,14 @@ void nvfp4_fused_scale(const Tensor block_amax, const Tensor global_amax, Tensor if (tile_rows == 0 || tile_cols == 0 || rows_padded == 0) return; + // The scale-inverse of an NVFP4 tensor has round_up(tile_cols, 4) columns. + const size_t target_scale_stride = + target_scale.data.shape.size() == 2 ? target_scale.data.shape[1] : tile_cols; + NVTE_CHECK(target_scale_stride >= tile_cols, "Target scale has ", target_scale_stride, + " columns, fewer than the ", tile_cols, " tile columns."); + NVTE_CHECK(target_scale.data.numel() >= rows_padded * target_scale_stride, + "Target scale has fewer than rows_padded rows."); + constexpr int kBlockDim = 16; dim3 block(kBlockDim, kBlockDim); dim3 grid((tile_cols + kBlockDim - 1) / kBlockDim, (rows_padded + kBlockDim - 1) / kBlockDim); @@ -826,7 +838,7 @@ void nvfp4_fused_scale(const Tensor block_amax, const Tensor global_amax, Tensor reinterpret_cast(per_block_scale.data.dptr), reinterpret_cast(target_scale.data.dptr), reinterpret_cast(target_amax.data.dptr), tile_rows, - tile_cols, rows_padded, block_len);) + tile_cols, rows_padded, target_scale_stride, block_len);) NVTE_CHECK_CUDA(cudaGetLastError()); } diff --git a/transformer_engine/common/recipe/nvfp4_multi_tensor.cu b/transformer_engine/common/recipe/nvfp4_multi_tensor.cu new file mode 100644 index 00000000000..f7b4e9f241b --- /dev/null +++ b/transformer_engine/common/recipe/nvfp4_multi_tensor.cu @@ -0,0 +1,648 @@ +/************************************************************************* + * Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * + * See LICENSE for license information. + ************************************************************************/ + +/* + * --------------------------------------------------------------------------- + * MULTI-TENSOR NVFP4 2D PARTIAL-SHARD KERNELS + * + * Multi-tensor versions of the NVFP4 2D partial amax / fused scale / partial cast helpers in + * nvfp4.cu, for casting the master-weight shards of a distributed optimizer to NVFP4 model + * weights. They give the same bytes as those helpers, with these differences: + * + * - One launch covers up to kMaxTensorsPerLaunch tensors. Per-tensor metadata is passed as a + * kernel parameter, so the calls are CUDA-graph capturable and need no device buffers. + * - One thread handles one 16x16 tile, with vector loads of tile rows and 8-byte stores of the + * FP4 bytes of tiles that the shard covers fully, and only the tile rows the shard touches + * are launched. The per-tensor kernels use one 256-thread block per tile of the whole tensor. + * - Each value is converted to `cast_dtype` in registers, which gives the values of + * input.to(cast_dtype) without materializing that copy (for instance an FP32 master shard + * cast to a BF16 model weight). For the tile amax, round(max |x|) == max |round(x)| because + * round-to-nearest-even is monotonic and symmetric. + * - The per-tensor global amax is the maximum of the all-reduced tile amaxes (the maximum of + * the per-tile maxima is the maximum of the tensor), so it needs no pass over the shard and + * no all-reduce of its own. + * --------------------------------------------------------------------------- + */ + +#include + +#include +#include +#include + +#include "../cast/nvfp4/core_nvfp4.cuh" +#include "../common.h" +#include "../util/ptx_arch_spec.cuh" +#include "../utils.cuh" + +namespace transformer_engine { +namespace nvfp4_recipe { +namespace multi_tensor { + +#if FP4_TYPE_SUPPORTED + +constexpr int kTileDim = 16; +constexpr int kThreadsPerBlock = 256; +// Kernel parameters stay below 4 KB. +constexpr int kMaxTensorsPerLaunch = 24; + +// One tensor's shard as seen by the amax and cast kernels. +struct ShardMeta { + const void *input; // shard of the flattened [h, w] tensor, `len` elements + uint8_t *output; // packed FP4 bytes; element idx is in output[(idx - start) / 2] + float *block_amax; // [tile_rows, tile_cols], contiguous + const float *decode_scale; // [tile_rows, tile_cols], contiguous + const float *global_scale; // [1] + int64_t len; + int64_t start; + int64_t h; + int64_t w; + int64_t tile_cols; + int64_t first_tile_row; // first tile row the shard touches + int32_t vec_load; // whole-tile rows can be read with vector loads + int32_t vec_store; // whole-tile rows can be written with 8-byte stores +}; + +struct ShardArgs { + ShardMeta meta[kMaxTensorsPerLaunch]; + int64_t tile_offset[kMaxTensorsPerLaunch + 1]; // prefix sum of the tiles each shard touches + int num_tensors; +}; + +struct GlobalAmaxArgs { + const float *block_amax[kMaxTensorsPerLaunch]; + float *global_amax[kMaxTensorsPerLaunch]; + int64_t num_blocks[kMaxTensorsPerLaunch]; +}; + +struct ScaleMeta { + const float *block_amax; // [tile_rows, tile_cols] + const float *global_amax; // [1] + float *per_block_scale; // [tile_rows, tile_cols] + uint8_t *target_scale; // [rows_padded, scale_stride] + float *target_amax; // [1] + int64_t tile_rows; + int64_t tile_cols; + int64_t rows_padded; + int64_t scale_stride; +}; + +struct ScaleArgs { + ScaleMeta meta[kMaxTensorsPerLaunch]; + // Prefix sum of (row groups of 16 rows of target_scale) x tile_cols. + int64_t work_offset[kMaxTensorsPerLaunch + 1]; + int num_tensors; +}; + +__device__ __forceinline__ int find_tensor(const int64_t *offsets, int n, int64_t t) { + int lo = 0, hi = n - 1; + while (lo < hi) { + const int mid = (lo + hi + 1) >> 1; + if (offsets[mid] <= t) { + lo = mid; + } else { + hi = mid - 1; + } + } + return lo; +} + +// An input value as input.to(CType) gives it, in FP32. +template +__device__ __forceinline__ float cast_value(const float x) { + if constexpr (std::is_same_v || std::is_same_v) { + return x; + } else if constexpr (std::is_same_v) { + return __bfloat162float(__float2bfloat16_rn(x)); + } else { + static_assert(std::is_same_v, "Unsupported cast type"); + return __half2float(__float2half_rn(x)); + } +} + +// Four consecutive values, 16-byte aligned for FP32 and 8-byte aligned for 16-bit types. +template +__device__ __forceinline__ void load4(const IType *p, float (&v)[4]) { + if constexpr (sizeof(IType) == 4) { + const float4 t = __ldg(reinterpret_cast(p)); + v[0] = t.x; + v[1] = t.y; + v[2] = t.z; + v[3] = t.w; + } else { + static_assert(sizeof(IType) == 2, "Unsupported input type"); + const uint2 t = __ldg(reinterpret_cast(p)); + const IType *e = reinterpret_cast(&t); +#pragma unroll + for (int j = 0; j < 4; ++j) v[j] = static_cast(e[j]); + } +} + +// Tile (tile_row, tile_col) of shard `m` for thread t of the launch. +__device__ __forceinline__ void tile_of(const ShardMeta &m, const int64_t local, int64_t *r0, + int64_t *c0) { + *r0 = (m.first_tile_row + local / m.tile_cols) * kTileDim; + *c0 = (local % m.tile_cols) * kTileDim; +} + +__device__ __forceinline__ bool tile_in_shard(const ShardMeta &m, const int64_t r0, + const int64_t c0) { + return (r0 + kTileDim <= m.h) && (c0 + kTileDim <= m.w) && (r0 * m.w + c0 >= m.start) && + ((r0 + kTileDim - 1) * m.w + c0 + kTileDim - 1 < m.start + m.len); +} + +template +__global__ void __launch_bounds__(kThreadsPerBlock) + partial_amax_kernel(const ShardArgs args, const int64_t total_tiles) { + const int64_t t = static_cast(blockIdx.x) * blockDim.x + threadIdx.x; + if (t >= total_tiles) return; + const int ti = find_tensor(args.tile_offset, args.num_tensors, t); + const ShardMeta &m = args.meta[ti]; + int64_t r0, c0; + tile_of(m, t - args.tile_offset[ti], &r0, &c0); + const int64_t end = m.start + m.len; + const IType *in = reinterpret_cast(m.input) - m.start; + + float amax = 0.f; + if (m.vec_load && tile_in_shard(m, r0, c0)) { +#pragma unroll 4 + for (int r = 0; r < kTileDim; ++r) { + const IType *row = in + (r0 + r) * m.w + c0; +#pragma unroll + for (int k = 0; k < kTileDim / 4; ++k) { + float v[4]; + load4(row + 4 * k, v); + amax = fmaxf(amax, fmaxf(fmaxf(fabsf(v[0]), fabsf(v[1])), fmaxf(fabsf(v[2]), fabsf(v[3])))); + } + } + } else { + bool any = false; + for (int r = 0; r < kTileDim && r0 + r < m.h; ++r) { + for (int c = 0; c < kTileDim && c0 + c < m.w; ++c) { + const int64_t idx = (r0 + r) * m.w + c0 + c; + if (idx >= m.start && idx < end) { + amax = fmaxf(amax, fabsf(static_cast(in[idx]))); + any = true; + } + } + } + // Tiles of other ranks are not written; the caller zero-initializes the amax buffer. + if (!any) return; + } + m.block_amax[(r0 / kTileDim) * m.tile_cols + c0 / kTileDim] = cast_value(amax); +} + +// One block per tensor: global amax = maximum of the (all-reduced) block amaxes. +__global__ void __launch_bounds__(kThreadsPerBlock) global_amax_kernel(const GlobalAmaxArgs args) { + const int ti = blockIdx.x; + const float *block_amax = args.block_amax[ti]; + const int64_t n = args.num_blocks[ti]; + float a = 0.f; + for (int64_t i = threadIdx.x; i < n; i += blockDim.x) a = fmaxf(a, block_amax[i]); + for (int d = 16; d > 0; d >>= 1) a = fmaxf(a, __shfl_xor_sync(0xffffffffu, a, d)); + __shared__ float smem[kThreadsPerBlock / 32]; + if ((threadIdx.x & 31) == 0) smem[threadIdx.x >> 5] = a; + __syncthreads(); + if (threadIdx.x == 0) { + for (int i = 0; i < kThreadsPerBlock / 32; ++i) a = fmaxf(a, smem[i]); + *args.global_amax[ti] = a; + } +} + +// Same arithmetic as nvfp4_fused_scale_kernel; one thread per 16-row group and tile column. +template +__global__ void __launch_bounds__(kThreadsPerBlock) + fused_scale_kernel(const ScaleArgs args, const int64_t total) { + const int64_t t = static_cast(blockIdx.x) * blockDim.x + threadIdx.x; + if (t >= total) return; + const int ti = find_tensor(args.work_offset, args.num_tensors, t); + const ScaleMeta &m = args.meta[ti]; + const int64_t local = t - args.work_offset[ti]; + const int64_t tile_row = local / m.tile_cols; + const int64_t col = local % m.tile_cols; + + const float g_amax = *m.global_amax; + if (local == 0) *m.target_amax = g_amax; + + constexpr float fp4_max = transformer_engine::TypeInfo::max_finite_value; + constexpr float scale_max = transformer_engine::TypeInfo::max_finite_value; + constexpr float flt_max = 3.402823466e+38f; + constexpr float tiny = 1.17549435e-38f; + + float scale_val = 0.0f; + if (tile_row < m.tile_rows) { + const float safe_global_amax = fmaxf(g_amax, tiny); + const float global_scale = + (g_amax > 0.0f) ? fminf((scale_max * fp4_max) / safe_global_amax, flt_max) : 1.0f; + constexpr float fp4_max_inv = 1.0f / fp4_max; + const float global_scale_multiplier = global_scale * fp4_max_inv; + const float amax_val = m.block_amax[tile_row * m.tile_cols + col]; + scale_val = fminf(amax_val * global_scale_multiplier, flt_max); + m.per_block_scale[tile_row * m.tile_cols + col] = scale_val; + } + const ScaleType q = static_cast(scale_val); + const uint8_t q_bits = reinterpret_cast(q); + const int64_t row_end = min((tile_row + 1) * kTileDim, m.rows_padded); + for (int64_t r = tile_row * kTileDim; r < row_end; ++r) { + m.target_scale[r * m.scale_stride + col] = q_bits; + } +} + +__device__ __forceinline__ uint16_t cvt_4x(const float (&v)[4], const float s) { + const auto packed = ptx::mul_cvt_fp32_to_fp4_4x( + make_float2(v[0], v[1]), make_float2(v[2], v[3]), make_float2(s, s), 0); + return reinterpret_cast(packed); +} + +__device__ __forceinline__ void store_nibble(uint8_t *byte, const int64_t elem_idx, + const uint8_t nibble) { + *byte = ((elem_idx & 1) == 0) ? static_cast((*byte & 0xF0u) | nibble) + : static_cast((*byte & 0x0Fu) | (nibble << 4)); +} + +// Same arithmetic as nvfp4_2d_partial_cast_kernel; one thread per 16x16 tile. +template +__global__ void __launch_bounds__(kThreadsPerBlock) + partial_cast_kernel(const ShardArgs args, const int64_t total_tiles) { + const int64_t t = static_cast(blockIdx.x) * blockDim.x + threadIdx.x; + if (t >= total_tiles) return; + const int ti = find_tensor(args.tile_offset, args.num_tensors, t); + const ShardMeta &m = args.meta[ti]; + int64_t r0, c0; + tile_of(m, t - args.tile_offset[ti], &r0, &c0); + const int64_t end = m.start + m.len; + const IType *in = reinterpret_cast(m.input) - m.start; + + float global_encode_scale = *m.global_scale; + if (global_encode_scale <= 0.f) { + global_encode_scale = 1.f; + } + const float global_decode_scale = 1.0f / global_encode_scale; + float tile_decode_scale = m.decode_scale[(r0 / kTileDim) * m.tile_cols + c0 / kTileDim]; + tile_decode_scale = static_cast(static_cast(tile_decode_scale)); + constexpr float kFp32Max = 3.402823466e+38F; + float s = (tile_decode_scale > 0.f) ? 1.0f / (tile_decode_scale * global_decode_scale) : kFp32Max; + s = fminf(s, kFp32Max); + + if (m.vec_load && tile_in_shard(m, r0, c0)) { +#pragma unroll 2 + for (int r = 0; r < kTileDim; ++r) { + const int64_t idx0 = (r0 + r) * m.w + c0; + uint64_t bits = 0; +#pragma unroll + for (int k = 0; k < kTileDim / 4; ++k) { + float v[4]; + load4(in + idx0 + 4 * k, v); +#pragma unroll + for (int j = 0; j < 4; ++j) v[j] = cast_value(v[j]); + bits |= static_cast(cvt_4x(v, s)) << (16 * k); + } + uint8_t *out = m.output + ((idx0 - m.start) >> 1); + if (m.vec_store) { + *reinterpret_cast(out) = + make_uint2(static_cast(bits), static_cast(bits >> 32)); + } else { +#pragma unroll + for (int b = 0; b < 8; ++b) out[b] = static_cast(bits >> (8 * b)); + } + } + return; + } + + // Tile cut by the shard or by the tensor edge: the nibble read-modify-write of + // nvfp4_2d_partial_cast_kernel, four elements at a time. + for (int r = 0; r < kTileDim && r0 + r < m.h; ++r) { + for (int g = 0; g < kTileDim / 4; ++g) { + float v[4]; + bool mask[4]; + int64_t elem_idx[4]; + bool any = false; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int64_t col = c0 + 4 * g + j; + const int64_t idx = (r0 + r) * m.w + col; + elem_idx[j] = idx; + mask[j] = col < m.w && idx >= m.start && idx < end; + v[j] = mask[j] ? cast_value(static_cast(in[idx])) : 0.0f; + any |= mask[j]; + } + if (!any) continue; + const uint16_t packed_bits = cvt_4x(v, s); + for (int pair = 0; pair < 2; ++pair) { + const int first = 2 * pair, second = first + 1; + if (!mask[first] && !mask[second]) continue; + const int64_t ref_idx = mask[first] ? elem_idx[first] : elem_idx[second]; + uint8_t byte = m.output[(ref_idx - m.start) >> 1]; + if (mask[first]) { + store_nibble(&byte, elem_idx[first], + static_cast((packed_bits >> (4 * first)) & 0xF)); + } + if (mask[second]) { + store_nibble(&byte, elem_idx[second], + static_cast((packed_bits >> (4 * second)) & 0xF)); + } + m.output[(ref_idx - m.start) >> 1] = byte; + } + } + } +} + +// Checks that `t` is a float32 [ceil(h / 16), ceil(w / 16)] buffer of per-tile values. +void check_tile_buffer(const Tensor &t, size_t h, size_t w, const char *name) { + NVTE_CHECK(t.dtype() == DType::kFloat32, name, " must be float32."); + const size_t tile_rows = (h + kTileDim - 1) / kTileDim; + const size_t tile_cols = (w + kTileDim - 1) / kTileDim; + NVTE_CHECK( + t.data.shape.size() == 2 && t.data.shape[0] == tile_rows && t.data.shape[1] == tile_cols, + name, " must have shape [", tile_rows, ", ", tile_cols, "] for a ", h, "x", w, " tensor."); +} + +void check_input_dtypes(const Tensor *const *inp, size_t num_tensors, DType cast_dtype) { + const DType input_dtype = inp[0]->dtype(); + NVTE_CHECK(input_dtype == DType::kFloat32 || input_dtype == DType::kBFloat16 || + input_dtype == DType::kFloat16, + "NVFP4 2D shards must be FP32, BF16 or FP16."); + NVTE_CHECK(cast_dtype == DType::kFloat32 || cast_dtype == DType::kBFloat16 || + cast_dtype == DType::kFloat16, + "cast_dtype must be FP32, BF16 or FP16."); + for (size_t i = 0; i < num_tensors; ++i) { + NVTE_CHECK(inp[i]->dtype() == input_dtype, + "All NVFP4 2D shards of one call must have one dtype."); + } +} + +// Fills one launch's ShardArgs from tensors [begin, end); returns the number of tiles. +int64_t make_shard_args(ShardArgs *args, const Tensor *const *inp, Tensor *const *out, + Tensor *const *amax, const Tensor *const *scale, + const Tensor *const *global_scale, const size_t *h, const size_t *w, + const size_t *start_offset, size_t begin, size_t end, size_t elem_size) { + int64_t tiles = 0; + args->num_tensors = static_cast(end - begin); + for (size_t i = begin; i < end; ++i) { + ShardMeta &m = args->meta[i - begin]; + const Tensor &input = *inp[i]; + m.input = input.data.dptr; + m.output = out != nullptr ? reinterpret_cast(out[i]->data.dptr) : nullptr; + m.block_amax = amax != nullptr ? reinterpret_cast(amax[i]->data.dptr) : nullptr; + m.decode_scale = + scale != nullptr ? reinterpret_cast(scale[i]->data.dptr) : nullptr; + m.global_scale = global_scale != nullptr + ? reinterpret_cast(global_scale[i]->data.dptr) + : nullptr; + m.len = static_cast(input.numel()); + m.start = static_cast(start_offset[i]); + m.h = static_cast(h[i]); + m.w = static_cast(w[i]); + NVTE_CHECK(m.h > 0 && m.w > 0, "NVFP4 2D tensors must not be empty."); + NVTE_CHECK(m.start % 2 == 0, "NVFP4 2D shards must start at an even element offset, got ", + m.start, "."); + NVTE_CHECK(m.start + m.len <= m.h * m.w, "NVFP4 2D shard exceeds its tensor."); + m.tile_cols = (m.w + kTileDim - 1) / kTileDim; + args->tile_offset[i - begin] = tiles; + if (m.len > 0) { + const int64_t first = (m.start / m.w) / kTileDim; + const int64_t last = ((m.start + m.len - 1) / m.w) / kTileDim; + m.first_tile_row = first; + tiles += (last - first + 1) * m.tile_cols; + } else { + m.first_tile_row = 0; + } + // Tile rows are addressed from where element 0 of the tensor would be (input - start and + // output - start / 2), at element offsets that are multiples of 4 (loads) and 16 (stores) + // for these widths, so the alignment of element 0 decides, not that of the shard start. + const uintptr_t in_base = reinterpret_cast(m.input) - m.start * elem_size; + m.vec_load = (m.w % 4 == 0) && (in_base % (4 * elem_size) == 0); + const uintptr_t out_base = reinterpret_cast(m.output) - m.start / 2; + m.vec_store = (m.w % kTileDim == 0) && (out_base % 8 == 0); + } + args->tile_offset[end - begin] = tiles; + return tiles; +} + +void partial_amax(const Tensor *const *inp, Tensor *const *amax, const size_t *h, const size_t *w, + const size_t *start_offset, size_t num_tensors, size_t block_len, + DType cast_dtype, cudaStream_t stream) { + NVTE_CHECK(block_len == kTileDim, "NVFP4 2D supports 16x16 tiles only (block_len = 16)."); + if (num_tensors == 0) return; + check_input_dtypes(inp, num_tensors, cast_dtype); + const DType input_dtype = inp[0]->dtype(); + for (size_t i = 0; i < num_tensors; ++i) { + check_tile_buffer(*amax[i], h[i], w[i], "Block amax"); + } + for (size_t begin = 0; begin < num_tensors; begin += kMaxTensorsPerLaunch) { + const size_t end = std::min(num_tensors, begin + kMaxTensorsPerLaunch); + ShardArgs args; + const int64_t tiles = make_shard_args(&args, inp, nullptr, amax, nullptr, nullptr, h, w, + start_offset, begin, end, typeToSize(input_dtype)); + if (tiles == 0) continue; + const dim3 grid(static_cast((tiles + kThreadsPerBlock - 1) / kThreadsPerBlock)); + TRANSFORMER_ENGINE_TYPE_SWITCH_NON_FP8ONLY( + input_dtype, IType, + TRANSFORMER_ENGINE_TYPE_SWITCH_NON_FP8ONLY( + cast_dtype, CType, + partial_amax_kernel + <<>>(args, tiles););); + NVTE_CHECK_CUDA(cudaGetLastError()); + } +} + +void global_amax_from_block_amax(const Tensor *const *block_amax, Tensor *const *global_amax, + size_t num_tensors, cudaStream_t stream) { + for (size_t begin = 0; begin < num_tensors; begin += kMaxTensorsPerLaunch) { + const size_t end = std::min(num_tensors, begin + kMaxTensorsPerLaunch); + GlobalAmaxArgs args; + for (size_t i = begin; i < end; ++i) { + NVTE_CHECK(block_amax[i]->dtype() == DType::kFloat32, "Block amax must be float32."); + NVTE_CHECK(global_amax[i]->dtype() == DType::kFloat32, "Global amax must be float32."); + NVTE_CHECK(global_amax[i]->numel() == 1, "Global amax must be a single element tensor."); + args.block_amax[i - begin] = reinterpret_cast(block_amax[i]->data.dptr); + args.global_amax[i - begin] = reinterpret_cast(global_amax[i]->data.dptr); + args.num_blocks[i - begin] = static_cast(block_amax[i]->numel()); + } + global_amax_kernel<<(end - begin), kThreadsPerBlock, 0, stream>>>(args); + NVTE_CHECK_CUDA(cudaGetLastError()); + } +} + +void fused_scale(const Tensor *const *block_amax, const Tensor *const *global_amax, + Tensor *const *per_block_scale, Tensor *const *target_scale, + Tensor *const *target_amax, size_t num_tensors, size_t block_len, + DType scale_dtype, cudaStream_t stream) { + NVTE_CHECK(block_len == kTileDim, "NVFP4 2D supports 16x16 tiles only (block_len = 16)."); + for (size_t begin = 0; begin < num_tensors; begin += kMaxTensorsPerLaunch) { + const size_t end = std::min(num_tensors, begin + kMaxTensorsPerLaunch); + ScaleArgs args; + args.num_tensors = static_cast(end - begin); + int64_t work = 0; + for (size_t i = begin; i < end; ++i) { + const Tensor &amax = *block_amax[i]; + const Tensor &scale = *target_scale[i]; + NVTE_CHECK(amax.dtype() == DType::kFloat32, "Block amax must be float32."); + NVTE_CHECK(amax.data.shape.size() == 2, "Block amax must be [tile_rows, tile_cols]."); + NVTE_CHECK(global_amax[i]->dtype() == DType::kFloat32, "Global amax must be float32."); + NVTE_CHECK(per_block_scale[i]->dtype() == DType::kFloat32, + "Per-block scale must be float32."); + NVTE_CHECK(per_block_scale[i]->numel() == amax.numel(), + "Per-block scale must have the shape of the block amax."); + NVTE_CHECK(scale.dtype() == DType::kByte || scale.dtype() == scale_dtype, + "Target scale must be byte storage or have the selected NVFP4 scale dtype."); + NVTE_CHECK(scale.data.shape.size() == 2, "Target scale must be [rows_padded, columns]."); + NVTE_CHECK(target_amax[i]->dtype() == DType::kFloat32, "Target amax must be float32."); + NVTE_CHECK(global_amax[i]->numel() == 1 && target_amax[i]->numel() == 1, + "Global and target amax must be single element tensors."); + ScaleMeta &m = args.meta[i - begin]; + m.block_amax = reinterpret_cast(amax.data.dptr); + m.global_amax = reinterpret_cast(global_amax[i]->data.dptr); + m.per_block_scale = reinterpret_cast(per_block_scale[i]->data.dptr); + m.target_scale = reinterpret_cast(scale.data.dptr); + m.target_amax = reinterpret_cast(target_amax[i]->data.dptr); + m.tile_rows = static_cast(amax.data.shape[0]); + m.tile_cols = static_cast(amax.data.shape[1]); + // The scale-inverse of an NVFP4 tensor is padded to round_up(rows, 128) rows and + // round_up(tile_cols, 4) columns. + m.rows_padded = static_cast(scale.data.shape[0]); + m.scale_stride = static_cast(scale.data.shape[1]); + NVTE_CHECK(m.scale_stride >= m.tile_cols, "Target scale has ", m.scale_stride, + " columns, fewer than the ", m.tile_cols, " tile columns."); + NVTE_CHECK((m.rows_padded + kTileDim - 1) / kTileDim >= m.tile_rows, "Target scale has ", + m.rows_padded, " rows, too few for ", m.tile_rows, " tile rows."); + args.work_offset[i - begin] = work; + work += ((m.rows_padded + kTileDim - 1) / kTileDim) * m.tile_cols; + } + args.work_offset[end - begin] = work; + if (work == 0) continue; + const dim3 grid(static_cast((work + kThreadsPerBlock - 1) / kThreadsPerBlock)); + TRANSFORMER_ENGINE_NVFP4_SCALE_TYPE_SWITCH( + scale_dtype, ScaleType, + fused_scale_kernel<<>>(args, work);); + NVTE_CHECK_CUDA(cudaGetLastError()); + } +} + +void partial_cast(const Tensor *const *inp, Tensor *const *out, const Tensor *const *scale, + const Tensor *const *global_scale, const size_t *h, const size_t *w, + const size_t *start_offset, size_t num_tensors, size_t block_len, + DType cast_dtype, DType scale_dtype, cudaStream_t stream) { + NVTE_CHECK(block_len == kTileDim, "NVFP4 2D supports 16x16 tiles only (block_len = 16)."); + if (num_tensors == 0) return; + check_input_dtypes(inp, num_tensors, cast_dtype); + const DType input_dtype = inp[0]->dtype(); + for (size_t i = 0; i < num_tensors; ++i) { + NVTE_CHECK(out[i]->dtype() == DType::kByte, "NVFP4 rowwise data must be uint8."); + NVTE_CHECK(out[i]->numel() >= (inp[i]->numel() + 1) / 2, + "NVFP4 output is smaller than the packed shard."); + check_tile_buffer(*scale[i], h[i], w[i], "Scale"); + NVTE_CHECK(global_scale[i]->dtype() == DType::kFloat32 && global_scale[i]->numel() == 1, + "Global scale must be a single float32 element."); + } + for (size_t begin = 0; begin < num_tensors; begin += kMaxTensorsPerLaunch) { + const size_t end = std::min(num_tensors, begin + kMaxTensorsPerLaunch); + ShardArgs args; + const int64_t tiles = make_shard_args(&args, inp, out, nullptr, scale, global_scale, h, w, + start_offset, begin, end, typeToSize(input_dtype)); + if (tiles == 0) continue; + const dim3 grid(static_cast((tiles + kThreadsPerBlock - 1) / kThreadsPerBlock)); + TRANSFORMER_ENGINE_NVFP4_SCALE_TYPE_SWITCH( + scale_dtype, ScaleType, + TRANSFORMER_ENGINE_TYPE_SWITCH_NON_FP8ONLY( + input_dtype, IType, + TRANSFORMER_ENGINE_TYPE_SWITCH_NON_FP8ONLY( + cast_dtype, CType, + partial_cast_kernel + <<>>(args, tiles);));); + NVTE_CHECK_CUDA(cudaGetLastError()); + } +} + +#endif // FP4_TYPE_SUPPORTED + +} // namespace multi_tensor +} // namespace nvfp4_recipe +} // namespace transformer_engine + +namespace { + +std::vector convert_list(const NVTETensor *tensors, size_t n) { + std::vector out(n); + for (size_t i = 0; i < n; ++i) out[i] = transformer_engine::convertNVTETensorCheck(tensors[i]); + return out; +} + +} // namespace + +void nvte_nvfp4_2d_multi_tensor_partial_amax(const NVTETensor *inp, NVTETensor *amax, + const size_t *h, const size_t *w, + const size_t *start_offset, size_t num_tensors, + size_t block_len, NVTEDType cast_dtype, + cudaStream_t stream) { +#if FP4_TYPE_SUPPORTED + NVTE_API_CALL(nvte_nvfp4_2d_multi_tensor_partial_amax); + using namespace transformer_engine; + const auto inp_t = convert_list(inp, num_tensors); + const auto amax_t = convert_list(amax, num_tensors); + nvfp4_recipe::multi_tensor::partial_amax(inp_t.data(), amax_t.data(), h, w, start_offset, + num_tensors, block_len, static_cast(cast_dtype), + stream); +#else + NVTE_ERROR("FP4 support requires CUDA 12.8+, but compile-time CUDA version is ", CUDA_VERSION); +#endif // FP4_TYPE_SUPPORTED +} + +void nvte_nvfp4_2d_multi_tensor_global_amax(const NVTETensor *block_amax, NVTETensor *global_amax, + size_t num_tensors, cudaStream_t stream) { +#if FP4_TYPE_SUPPORTED + NVTE_API_CALL(nvte_nvfp4_2d_multi_tensor_global_amax); + using namespace transformer_engine; + const auto block_amax_t = convert_list(block_amax, num_tensors); + const auto global_amax_t = convert_list(global_amax, num_tensors); + nvfp4_recipe::multi_tensor::global_amax_from_block_amax(block_amax_t.data(), global_amax_t.data(), + num_tensors, stream); +#else + NVTE_ERROR("FP4 support requires CUDA 12.8+, but compile-time CUDA version is ", CUDA_VERSION); +#endif // FP4_TYPE_SUPPORTED +} + +void nvte_nvfp4_2d_multi_tensor_fused_scale(const NVTETensor *block_amax, + const NVTETensor *global_amax, + NVTETensor *per_block_scale, NVTETensor *target_scale, + NVTETensor *target_amax, size_t num_tensors, + size_t block_len, NVTEDType scale_dtype, + cudaStream_t stream) { +#if FP4_TYPE_SUPPORTED + NVTE_API_CALL(nvte_nvfp4_2d_multi_tensor_fused_scale); + using namespace transformer_engine; + const auto block_amax_t = convert_list(block_amax, num_tensors); + const auto global_amax_t = convert_list(global_amax, num_tensors); + const auto per_block_scale_t = convert_list(per_block_scale, num_tensors); + const auto target_scale_t = convert_list(target_scale, num_tensors); + const auto target_amax_t = convert_list(target_amax, num_tensors); + nvfp4_recipe::multi_tensor::fused_scale( + block_amax_t.data(), global_amax_t.data(), per_block_scale_t.data(), target_scale_t.data(), + target_amax_t.data(), num_tensors, block_len, static_cast(scale_dtype), stream); +#else + NVTE_ERROR("FP4 support requires CUDA 12.8+, but compile-time CUDA version is ", CUDA_VERSION); +#endif // FP4_TYPE_SUPPORTED +} + +void nvte_nvfp4_2d_multi_tensor_partial_cast( + const NVTETensor *inp, NVTETensor *out, const NVTETensor *scale, const NVTETensor *global_scale, + const size_t *h, const size_t *w, const size_t *start_offset, size_t num_tensors, + size_t block_len, NVTEDType cast_dtype, NVTEDType scale_dtype, cudaStream_t stream) { +#if FP4_TYPE_SUPPORTED + NVTE_API_CALL(nvte_nvfp4_2d_multi_tensor_partial_cast); + using namespace transformer_engine; + const auto inp_t = convert_list(inp, num_tensors); + const auto out_t = convert_list(out, num_tensors); + const auto scale_t = convert_list(scale, num_tensors); + const auto global_scale_t = convert_list(global_scale, num_tensors); + nvfp4_recipe::multi_tensor::partial_cast(inp_t.data(), out_t.data(), scale_t.data(), + global_scale_t.data(), h, w, start_offset, num_tensors, + block_len, static_cast(cast_dtype), + static_cast(scale_dtype), stream); +#else + NVTE_ERROR("FP4 support requires CUDA 12.8+, but compile-time CUDA version is ", CUDA_VERSION); +#endif // FP4_TYPE_SUPPORTED +} diff --git a/transformer_engine/pytorch/csrc/extensions.h b/transformer_engine/pytorch/csrc/extensions.h index 4a582ac24c2..8a3c9b9ed0c 100644 --- a/transformer_engine/pytorch/csrc/extensions.h +++ b/transformer_engine/pytorch/csrc/extensions.h @@ -216,11 +216,6 @@ void nvfp4_2d_multi_tensor_transpose(std::vector rowwise_data_list, std::vector columnwise_scale_inv_list, std::vector M_list, std::vector K_list); -void nvfp4_multi_tensor_compute_partial_amax( - std::vector master_weight_list, std::vector partial_amax_list, - std::vector global_amax_list, std::vector h_list, - std::vector w_list, std::vector start_offset_list, int64_t block_len); - void nvfp4_expand_scale_to_fp8(at::Tensor input, at::Tensor output, int64_t tile_rows, int64_t tile_cols, int64_t rows_padded, int64_t block_len, DType scale_dtype = DType::kFloat8E4M3); @@ -233,13 +228,6 @@ void nvfp4_fused_scale(at::Tensor block_amax, at::Tensor global_amax, at::Tensor int64_t tile_cols, int64_t rows_padded, int64_t block_len, const DType scale_dtype = DType::kFloat8E4M3); -void nvfp4_multi_tensor_fused_scale( - std::vector block_amax_list, std::vector global_amax_list, - std::vector per_block_scale_list, std::vector target_scale_list, - std::vector target_amax_list, std::vector tile_rows_list, - std::vector tile_cols_list, std::vector rows_padded_list, int64_t block_len, - const DType scale_dtype = DType::kFloat8E4M3); - void nvfp4_compute_global_scale(at::Tensor global_amax, at::Tensor global_scale, const DType scale_dtype = DType::kFloat8E4M3); @@ -543,13 +531,30 @@ void nvfp4_2d_partial_cast(const at::Tensor &inp, py::handle out, const at::Tens const at::Tensor &global_scale, size_t h, size_t w, size_t start_offset, size_t block_len, const DType scale_dtype = DType::kFloat8E4M3); -void nvfp4_multi_tensor_2d_partial_cast(std::vector inp_list, - std::vector out_list, - std::vector scale_list, - std::vector global_scale_list, - std::vector h_list, std::vector w_list, - std::vector start_offset_list, int64_t block_len, - const DType scale_dtype = DType::kFloat8E4M3); +void nvfp4_2d_multi_tensor_partial_amax(const std::vector &inp_list, + const std::vector &amax_list, + const std::vector &h_list, + const std::vector &w_list, + const std::vector &start_offset_list, + int64_t block_len, const DType cast_dtype); + +void nvfp4_2d_multi_tensor_global_amax(const std::vector &block_amax_list, + const std::vector &global_amax_list); + +void nvfp4_2d_multi_tensor_fused_scale(const std::vector &block_amax_list, + const std::vector &global_amax_list, + const std::vector &per_block_scale_list, + const std::vector &target_scale_list, + const std::vector &target_amax_list, + int64_t block_len, const DType scale_dtype); + +void nvfp4_2d_multi_tensor_partial_cast( + const std::vector &inp_list, const std::vector &out_list, + const std::vector &scale_list, const std::vector &global_scale_list, + const std::vector &h_list, const std::vector &w_list, + const std::vector &start_offset_list, int64_t block_len, const DType cast_dtype, + const DType scale_dtype); + void mxfp8_scaling_compute_partial_amax(const at::Tensor &input, at::Tensor amax_rowwise, at::Tensor amax_colwise, int rows, int cols, size_t start_offset); diff --git a/transformer_engine/pytorch/csrc/extensions/nvfp4_2d_partial_cast.cpp b/transformer_engine/pytorch/csrc/extensions/nvfp4_2d_partial_cast.cpp index 4ecd50deb87..2c7d68b209c 100644 --- a/transformer_engine/pytorch/csrc/extensions/nvfp4_2d_partial_cast.cpp +++ b/transformer_engine/pytorch/csrc/extensions/nvfp4_2d_partial_cast.cpp @@ -49,111 +49,119 @@ void nvfp4_2d_partial_cast(const at::Tensor& inp, py::handle out, const at::Tens at::cuda::getCurrentCUDAStream()); } -void nvfp4_multi_tensor_2d_partial_cast(std::vector inp_list, - std::vector out_list, - std::vector scale_list, - std::vector global_scale_list, - std::vector h_list, std::vector w_list, - std::vector start_offset_list, int64_t block_len, - const DType scale_dtype) { - TORCH_CHECK(block_len == 16, "Currently only block_len = 16 is supported for NVFP4 2D"); - - const size_t num_tensors = inp_list.size(); - TORCH_CHECK(out_list.size() == num_tensors, "out_list size mismatch"); - TORCH_CHECK(scale_list.size() == num_tensors, "scale_list size mismatch"); - TORCH_CHECK(global_scale_list.size() == num_tensors, "global_scale_list size mismatch"); - TORCH_CHECK(h_list.size() == num_tensors, "h_list size mismatch"); - TORCH_CHECK(w_list.size() == num_tensors, "w_list size mismatch"); - TORCH_CHECK(start_offset_list.size() == num_tensors, "start_offset_list size mismatch"); - - if (num_tensors == 0) { - return; +namespace { + +// TE tensors for a list of contiguous torch tensors; `wrappers` keeps them alive. +std::vector make_te_tensors(const std::vector& tensors, + std::vector* wrappers, const char* name) { + std::vector out; + out.reserve(tensors.size()); + for (const auto& t : tensors) { + TORCH_CHECK(t.is_contiguous(), name, " tensors must be contiguous"); + wrappers->emplace_back(makeTransformerEngineTensor(t)); + out.push_back(wrappers->back().data()); } + return out; +} - auto stream = at::cuda::getCurrentCUDAStream(); - - for (size_t i = 0; i < num_tensors; ++i) { - const auto& inp = inp_list[i]; - const auto& out = out_list[i]; - const auto& scale = scale_list[i]; - const auto& global_scale = global_scale_list[i]; - const size_t h = static_cast(h_list[i]); - const size_t w = static_cast(w_list[i]); - const size_t start_offset = static_cast(start_offset_list[i]); - - TORCH_CHECK(scale.dim() == 2, "scale must be a 2D tensor"); - TORCH_CHECK(scale.scalar_type() == at::ScalarType::Float, "scale must be a float tensor"); - TORCH_CHECK(global_scale.numel() == 1, "global_scale must be a scalar tensor"); - TORCH_CHECK(global_scale.scalar_type() == at::ScalarType::Float, - "global_scale must be a float tensor"); - TORCH_CHECK( - inp.scalar_type() == at::ScalarType::Float || inp.scalar_type() == at::ScalarType::BFloat16, - "input must be a float or bfloat16 tensor"); - - const TensorWrapper inp_cu = makeTransformerEngineTensor(inp.contiguous()); - const TensorWrapper out_cu = makeTransformerEngineTensor(out); - const TensorWrapper scale_cu = makeTransformerEngineTensor(scale); - const TensorWrapper global_scale_cu = makeTransformerEngineTensor(global_scale); - - nvte_nvfp4_2d_partial_cast_v2(inp_cu.data(), out_cu.data(), scale_cu.data(), - global_scale_cu.data(), h, w, scale.stride(0), scale.stride(1), - start_offset, static_cast(block_len), - static_cast(scale_dtype), stream); +std::vector to_size_vector(const std::vector& v, size_t n, const char* name) { + TORCH_CHECK(v.size() == n, name, " size mismatch"); + std::vector out(n); + for (size_t i = 0; i < n; ++i) { + TORCH_CHECK(v[i] >= 0, name, " must not be negative"); + out[i] = static_cast(v[i]); } + return out; } -void nvfp4_multi_tensor_compute_partial_amax( - std::vector master_weight_list, std::vector partial_amax_list, - std::vector global_amax_list, std::vector h_list, - std::vector w_list, std::vector start_offset_list, int64_t block_len) { - TORCH_CHECK(block_len == 16, "Currently only block_len = 16 is supported for NVFP4 2D"); +} // namespace + +void nvfp4_2d_multi_tensor_partial_amax(const std::vector& inp_list, + const std::vector& amax_list, + const std::vector& h_list, + const std::vector& w_list, + const std::vector& start_offset_list, + int64_t block_len, const DType cast_dtype) { + const size_t n = inp_list.size(); + TORCH_CHECK(amax_list.size() == n, "amax_list size mismatch"); + if (n == 0) return; + const auto h = to_size_vector(h_list, n, "h_list"); + const auto w = to_size_vector(w_list, n, "w_list"); + const auto start = to_size_vector(start_offset_list, n, "start_offset_list"); + std::vector wrappers; + wrappers.reserve(2 * n); + auto inp = make_te_tensors(inp_list, &wrappers, "inp_list"); + auto amax = make_te_tensors(amax_list, &wrappers, "amax_list"); + nvte_nvfp4_2d_multi_tensor_partial_amax( + inp.data(), amax.data(), h.data(), w.data(), start.data(), n, static_cast(block_len), + static_cast(cast_dtype), at::cuda::getCurrentCUDAStream()); +} - const size_t num_tensors = master_weight_list.size(); - TORCH_CHECK(partial_amax_list.size() == num_tensors, "partial_amax_list size mismatch"); - TORCH_CHECK(global_amax_list.size() == num_tensors, "global_amax_list size mismatch"); - TORCH_CHECK(h_list.size() == num_tensors, "h_list size mismatch"); - TORCH_CHECK(w_list.size() == num_tensors, "w_list size mismatch"); - TORCH_CHECK(start_offset_list.size() == num_tensors, "start_offset_list size mismatch"); +void nvfp4_2d_multi_tensor_global_amax(const std::vector& block_amax_list, + const std::vector& global_amax_list) { + const size_t n = block_amax_list.size(); + TORCH_CHECK(global_amax_list.size() == n, "global_amax_list size mismatch"); + if (n == 0) return; + std::vector wrappers; + wrappers.reserve(2 * n); + auto block_amax = make_te_tensors(block_amax_list, &wrappers, "block_amax_list"); + auto global_amax = make_te_tensors(global_amax_list, &wrappers, "global_amax_list"); + nvte_nvfp4_2d_multi_tensor_global_amax(block_amax.data(), global_amax.data(), n, + at::cuda::getCurrentCUDAStream()); +} - if (num_tensors == 0) { - return; +void nvfp4_2d_multi_tensor_fused_scale(const std::vector& block_amax_list, + const std::vector& global_amax_list, + const std::vector& per_block_scale_list, + const std::vector& target_scale_list, + const std::vector& target_amax_list, + int64_t block_len, const DType scale_dtype) { + const size_t n = block_amax_list.size(); + TORCH_CHECK(global_amax_list.size() == n, "global_amax_list size mismatch"); + TORCH_CHECK(per_block_scale_list.size() == n, "per_block_scale_list size mismatch"); + TORCH_CHECK(target_scale_list.size() == n, "target_scale_list size mismatch"); + TORCH_CHECK(target_amax_list.size() == n, "target_amax_list size mismatch"); + if (n == 0) return; + for (const auto& t : target_scale_list) { + TORCH_CHECK(t.scalar_type() == at::kByte, "Target scale must be uint8 scale storage."); } + std::vector wrappers; + wrappers.reserve(5 * n); + auto block_amax = make_te_tensors(block_amax_list, &wrappers, "block_amax_list"); + auto global_amax = make_te_tensors(global_amax_list, &wrappers, "global_amax_list"); + auto per_block_scale = make_te_tensors(per_block_scale_list, &wrappers, "per_block_scale_list"); + auto target_scale = make_te_tensors(target_scale_list, &wrappers, "target_scale_list"); + auto target_amax = make_te_tensors(target_amax_list, &wrappers, "target_amax_list"); + nvte_nvfp4_2d_multi_tensor_fused_scale( + block_amax.data(), global_amax.data(), per_block_scale.data(), target_scale.data(), + target_amax.data(), n, static_cast(block_len), static_cast(scale_dtype), + at::cuda::getCurrentCUDAStream()); +} - auto stream = at::cuda::getCurrentCUDAStream(); - - for (size_t i = 0; i < num_tensors; ++i) { - const auto& master_weight = master_weight_list[i]; - auto& partial_amax = partial_amax_list[i]; - auto& global_amax = global_amax_list[i]; - const size_t h = static_cast(h_list[i]); - const size_t w = static_cast(w_list[i]); - const size_t start_offset = static_cast(start_offset_list[i]); - - TORCH_CHECK(partial_amax.dim() == 2, "partial_amax must be a 2D tensor"); - TORCH_CHECK(partial_amax.scalar_type() == at::ScalarType::Float, - "partial_amax must be a float tensor"); - TORCH_CHECK(master_weight.scalar_type() == at::ScalarType::Float || - master_weight.scalar_type() == at::ScalarType::BFloat16, - "master_weight must be a float or bfloat16 tensor"); - TORCH_CHECK(global_amax.scalar_type() == at::ScalarType::Float, - "global_amax must be a float tensor"); - TORCH_CHECK(global_amax.numel() == 1, "global_amax must have exactly one element"); - - // Compute partial amax (per-block amax) - const TensorWrapper tensor_cu = makeTransformerEngineTensor(master_weight.contiguous()); - TensorWrapper amax_cu = makeTransformerEngineTensor(partial_amax); - - nvte_nvfp4_2d_compute_partial_amax(tensor_cu.data(), amax_cu.data(), h, w, - partial_amax.stride(0), partial_amax.stride(1), start_offset, - static_cast(block_len), stream); - - // Compute global amax - auto* global_amax_ptr = global_amax.data_ptr(); - TensorWrapper fake_te_output( - /*dptr=*/nullptr, tensor_cu.shape(), DType::kFloat32, global_amax_ptr); - - nvte_compute_amax(tensor_cu.data(), fake_te_output.data(), stream); - } +void nvfp4_2d_multi_tensor_partial_cast( + const std::vector& inp_list, const std::vector& out_list, + const std::vector& scale_list, const std::vector& global_scale_list, + const std::vector& h_list, const std::vector& w_list, + const std::vector& start_offset_list, int64_t block_len, const DType cast_dtype, + const DType scale_dtype) { + const size_t n = inp_list.size(); + TORCH_CHECK(out_list.size() == n, "out_list size mismatch"); + TORCH_CHECK(scale_list.size() == n, "scale_list size mismatch"); + TORCH_CHECK(global_scale_list.size() == n, "global_scale_list size mismatch"); + if (n == 0) return; + const auto h = to_size_vector(h_list, n, "h_list"); + const auto w = to_size_vector(w_list, n, "w_list"); + const auto start = to_size_vector(start_offset_list, n, "start_offset_list"); + std::vector wrappers; + wrappers.reserve(4 * n); + auto inp = make_te_tensors(inp_list, &wrappers, "inp_list"); + auto out = make_te_tensors(out_list, &wrappers, "out_list"); + auto scale = make_te_tensors(scale_list, &wrappers, "scale_list"); + auto global_scale = make_te_tensors(global_scale_list, &wrappers, "global_scale_list"); + nvte_nvfp4_2d_multi_tensor_partial_cast( + inp.data(), out.data(), scale.data(), global_scale.data(), h.data(), w.data(), start.data(), + n, static_cast(block_len), static_cast(cast_dtype), + static_cast(scale_dtype), at::cuda::getCurrentCUDAStream()); } } // namespace transformer_engine::pytorch diff --git a/transformer_engine/pytorch/csrc/extensions/pybind.cpp b/transformer_engine/pytorch/csrc/extensions/pybind.cpp index 82fa3ec2428..09049e6c324 100644 --- a/transformer_engine/pytorch/csrc/extensions/pybind.cpp +++ b/transformer_engine/pytorch/csrc/extensions/pybind.cpp @@ -507,15 +507,6 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { py::arg("rows_padded"), py::arg("block_len"), py::arg("scale_dtype") = transformer_engine::DType::kFloat8E4M3, py::call_guard()); - m.def("nvfp4_multi_tensor_fused_scale", - &transformer_engine::pytorch::nvfp4_multi_tensor_fused_scale, - "Batched fused scale: compute per-block decode scale, copy global amax, expand to FP8 for " - "multiple tensors", - py::arg("block_amax_list"), py::arg("global_amax_list"), py::arg("per_block_scale_list"), - py::arg("target_scale_list"), py::arg("target_amax_list"), py::arg("tile_rows_list"), - py::arg("tile_cols_list"), py::arg("rows_padded_list"), py::arg("block_len"), - py::arg("scale_dtype") = transformer_engine::DType::kFloat8E4M3, - py::call_guard()); m.def("nvfp4_2d_multi_tensor_transpose", &transformer_engine::pytorch::nvfp4_2d_multi_tensor_transpose, "Batched NVFP4 columnwise creation: transpose data and scales for multiple tensors", @@ -549,23 +540,38 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { "Compute partial amax from master weights for NVFP4 2D", py::arg("tensor"), py::arg("amax"), py::arg("h"), py::arg("w"), py::arg("start_offset"), py::arg("block_len") = 16, py::call_guard()); - m.def("nvfp4_multi_tensor_compute_partial_amax", - &transformer_engine::pytorch::nvfp4_multi_tensor_compute_partial_amax, - "Batched compute partial and global amax from master weights for NVFP4 2D", - py::arg("master_weight_list"), py::arg("partial_amax_list"), py::arg("global_amax_list"), - py::arg("h_list"), py::arg("w_list"), py::arg("start_offset_list"), - py::arg("block_len") = 16, py::call_guard()); m.def("nvfp4_2d_partial_cast", &transformer_engine::pytorch::nvfp4_2d_partial_cast, "Partial cast from master weights for NVFP4 2D", py::arg("inp"), py::arg("out"), py::arg("scale"), py::arg("global_scale"), py::arg("h"), py::arg("w"), py::arg("start_offset"), py::arg("block_len") = 16, py::arg("scale_dtype") = transformer_engine::DType::kFloat8E4M3, py::call_guard()); - m.def("nvfp4_multi_tensor_2d_partial_cast", - &transformer_engine::pytorch::nvfp4_multi_tensor_2d_partial_cast, - "Batched partial cast from master weights for NVFP4 2D", py::arg("inp_list"), - py::arg("out_list"), py::arg("scale_list"), py::arg("global_scale_list"), py::arg("h_list"), - py::arg("w_list"), py::arg("start_offset_list"), py::arg("block_len") = 16, + m.def("nvfp4_2d_multi_tensor_partial_amax", + &transformer_engine::pytorch::nvfp4_2d_multi_tensor_partial_amax, + "NVFP4 2D tile amaxes of several partial shards, of the shards converted to cast_dtype", + py::arg("inp_list"), py::arg("amax_list"), py::arg("h_list"), py::arg("w_list"), + py::arg("start_offset_list"), py::arg("block_len") = 16, + py::arg("cast_dtype") = transformer_engine::DType::kFloat32, + py::call_guard()); + m.def("nvfp4_2d_multi_tensor_global_amax", + &transformer_engine::pytorch::nvfp4_2d_multi_tensor_global_amax, + "Per-tensor global amax as the maximum of the (reduced) NVFP4 2D tile amaxes", + py::arg("block_amax_list"), py::arg("global_amax_list"), + py::call_guard()); + m.def("nvfp4_2d_multi_tensor_fused_scale", + &transformer_engine::pytorch::nvfp4_2d_multi_tensor_fused_scale, + "Multi-tensor nvfp4_fused_scale, with the shapes taken from the tensors", + py::arg("block_amax_list"), py::arg("global_amax_list"), py::arg("per_block_scale_list"), + py::arg("target_scale_list"), py::arg("target_amax_list"), py::arg("block_len") = 16, + py::arg("scale_dtype") = transformer_engine::DType::kFloat8E4M3, + py::call_guard()); + m.def("nvfp4_2d_multi_tensor_partial_cast", + &transformer_engine::pytorch::nvfp4_2d_multi_tensor_partial_cast, + "NVFP4 2D partial cast of several shards, of the shards converted to cast_dtype", + py::arg("inp_list"), py::arg("out_list"), py::arg("scale_list"), + py::arg("global_scale_list"), py::arg("h_list"), py::arg("w_list"), + py::arg("start_offset_list"), py::arg("block_len") = 16, + py::arg("cast_dtype") = transformer_engine::DType::kFloat32, py::arg("scale_dtype") = transformer_engine::DType::kFloat8E4M3, py::call_guard()); m.def("mxfp8_scaling_compute_partial_amax", diff --git a/transformer_engine/pytorch/csrc/extensions/transpose.cpp b/transformer_engine/pytorch/csrc/extensions/transpose.cpp index 938b0f83b70..57d3c4efcb8 100644 --- a/transformer_engine/pytorch/csrc/extensions/transpose.cpp +++ b/transformer_engine/pytorch/csrc/extensions/transpose.cpp @@ -200,61 +200,6 @@ void nvfp4_fused_scale(at::Tensor block_amax, at::Tensor global_amax, at::Tensor static_cast(scale_dtype), at::cuda::getCurrentCUDAStream()); } -void nvfp4_multi_tensor_fused_scale( - std::vector block_amax_list, std::vector global_amax_list, - std::vector per_block_scale_list, std::vector target_scale_list, - std::vector target_amax_list, std::vector tile_rows_list, - std::vector tile_cols_list, std::vector rows_padded_list, int64_t block_len, - const DType scale_dtype) { - init_extension(); - - const size_t num_tensors = block_amax_list.size(); - NVTE_CHECK(global_amax_list.size() == num_tensors, "global_amax_list size mismatch"); - NVTE_CHECK(per_block_scale_list.size() == num_tensors, "per_block_scale_list size mismatch"); - NVTE_CHECK(target_scale_list.size() == num_tensors, "target_scale_list size mismatch"); - NVTE_CHECK(target_amax_list.size() == num_tensors, "target_amax_list size mismatch"); - NVTE_CHECK(tile_rows_list.size() == num_tensors, "tile_rows_list size mismatch"); - NVTE_CHECK(tile_cols_list.size() == num_tensors, "tile_cols_list size mismatch"); - NVTE_CHECK(rows_padded_list.size() == num_tensors, "rows_padded_list size mismatch"); - - if (num_tensors == 0) { - return; - } - - auto stream = at::cuda::getCurrentCUDAStream(); - - for (size_t i = 0; i < num_tensors; ++i) { - const auto& block_amax = block_amax_list[i]; - const auto& global_amax = global_amax_list[i]; - auto& per_block_scale = per_block_scale_list[i]; - auto& target_scale = target_scale_list[i]; - auto& target_amax = target_amax_list[i]; - const size_t tile_rows = static_cast(tile_rows_list[i]); - const size_t tile_cols = static_cast(tile_cols_list[i]); - const size_t rows_padded = static_cast(rows_padded_list[i]); - - NVTE_CHECK(block_amax.scalar_type() == at::kFloat, "Block amax must be float32."); - NVTE_CHECK(global_amax.scalar_type() == at::kFloat, "Global amax must be float32."); - NVTE_CHECK(per_block_scale.scalar_type() == at::kFloat, "Per-block scale must be float32."); - NVTE_CHECK(target_scale.scalar_type() == at::kByte, - "Target scale must be uint8 scale storage."); - NVTE_CHECK(target_amax.scalar_type() == at::kFloat, "Target amax must be float32."); - NVTE_CHECK(global_amax.numel() == 1, "Global amax must be a single element tensor."); - NVTE_CHECK(target_amax.numel() == 1, "Target amax must be a single element tensor."); - - auto block_amax_cu = makeTransformerEngineTensor(block_amax); - auto global_amax_cu = makeTransformerEngineTensor(global_amax); - auto per_block_scale_cu = makeTransformerEngineTensor(per_block_scale); - auto target_scale_cu = makeTransformerEngineTensor(target_scale); - auto target_amax_cu = makeTransformerEngineTensor(target_amax); - - nvte_nvfp4_fused_scale_v2( - block_amax_cu.data(), global_amax_cu.data(), per_block_scale_cu.data(), - target_scale_cu.data(), target_amax_cu.data(), tile_rows, tile_cols, rows_padded, - static_cast(block_len), static_cast(scale_dtype), stream); - } -} - void nvfp4_compute_global_scale(at::Tensor global_amax, at::Tensor global_scale, DType scale_dtype) { init_extension(); diff --git a/transformer_engine/pytorch/tensor/utils.py b/transformer_engine/pytorch/tensor/utils.py index caaf9cf5aad..f6fa1f49c78 100644 --- a/transformer_engine/pytorch/tensor/utils.py +++ b/transformer_engine/pytorch/tensor/utils.py @@ -24,7 +24,7 @@ from .storage.identity_tensor_storage import IdentityTensorStorage from ..optimizers.multi_tensor_apply import multi_tensor_applier from ..utils import is_non_tn_fp8_gemm_supported -from ..constants import NVFP4_BLOCK_SCALING_SIZE, DType +from ..constants import NVFP4_BLOCK_SCALING_SIZE, DType, TE_DType def replace_raw_data(tensor: QuantizedTensor, new_raw_data: torch.Tensor): @@ -283,15 +283,16 @@ def quantize_master_weights( if hasattr(model_weight, "clear_high_precision_init_val"): model_weight.clear_high_precision_init_val() - if master_weight is not None: + quantizer = model_weight._get_quantizer() + + if master_weight is not None and not isinstance(quantizer, NVFP4Quantizer): # When not using fp8/fp4_primary_weights, the master_weight (fp32) is first cast to # bf16/fp16, and then cast to fp8 during forward. Although it's not necessary when # fp8/fp4_primary_weights is enabled, we still keep this logic to keep numerical # consistency. So here we cast the master_weight to model_weight.dtype. + # The NVFP4 kernels do this conversion in registers instead. master_weight = master_weight.to(model_weight.dtype) - quantizer = model_weight._get_quantizer() - if isinstance(quantizer, NVFP4Quantizer): nvfp4_params.append( (model_weight, master_weight, start_offset, fsdp_shard_model_weight) @@ -754,10 +755,22 @@ def _cast_master_weights_to_nvfp4_2d( ): r"""Helper function to cast master weights to NVFP4 2D quantized weights. + The master weights keep their own dtype (typically FP32). The kernels convert each value to + the model weight's dtype in registers, which gives the FP4 data and scales of the master + weights cast with ``master_weight.to(model_weight.dtype)`` without materializing that copy. + Each step is a few multi-tensor launches for all tensors: + + 1. tile amaxes of this rank's master shards; + 2. max all-reduce of the tile amaxes; + 3. per-tensor global amaxes as the maximum of the reduced tile amaxes, which is the amax of + the whole tensor; + 4. global encode scales, per-tile scales and the partial cast of this rank's shards. + Parameters ---------- - params : List of tuple, each tuple contains a model weight, a master weight, and an offset - indicating the starting index of the master weight in the model weight. + params : List of tuple, each tuple contains a model weight, a master weight, an offset + indicating the starting index of the master weight in the model weight, and the + FSDP shard of the model weight (None if the model weights are not sharded). group : The distributed group to do amax reduction. Typically it's the data parallel group. use_fsdp_shard_model_weights : bool, if True, it means that the model weights are sharded. @@ -766,12 +779,8 @@ def _cast_master_weights_to_nvfp4_2d( device = params[0][0].device block_len = NVFP4_BLOCK_SCALING_SIZE - cu_amax_sizes = [0] - tile_shapes: List[tuple[int, int]] = [] - tile_widths: List[int] = [] - scale_targets: List[torch.Tensor] = [] - amax_targets: List[Optional[torch.Tensor]] = [] - for model_weight, _, _, _ in params: + scale_dtypes = set() + for model_weight, master_weight, start_offset, _ in params: quantizer = model_weight._get_quantizer() if not isinstance(quantizer, NVFP4Quantizer): raise TypeError(f"Expected NVFP4Quantizer, got {type(quantizer).__name__}") @@ -779,200 +788,129 @@ def _cast_master_weights_to_nvfp4_2d( raise ValueError("NVFP4 2D quantization must be enabled.") if len(model_weight.shape) != 2: raise ValueError(f"Expected 2D model weight, got {len(model_weight.shape)}D") - h, w = model_weight.shape - tile_h = (h + block_len - 1) // block_len - tile_w = (w + block_len - 1) // block_len - tile_shapes.append((tile_h, tile_w)) - tile_widths.append(tile_w) - scale_targets.append(model_weight._rowwise_scale_inv) - amax_targets.append(model_weight._amax_rowwise) - num_amaxes = tile_h * tile_w - cu_amax_sizes.append(cu_amax_sizes[-1] + num_amaxes) - - packed_amaxes = torch.zeros(cu_amax_sizes[-1], dtype=torch.float32, device=device) - packed_scales = torch.zeros(cu_amax_sizes[-1], dtype=torch.float32, device=device) - - amaxes: List[torch.Tensor] = [] - scales: List[torch.Tensor] = [] - global_amaxes = torch.zeros(len(params), dtype=torch.float32, device=device) - global_amax_views: List[torch.Tensor] = [global_amaxes[i : i + 1] for i in range(len(params))] - - # Collect tensors for batched multi-tensor amax computation - master_weight_list: List[torch.Tensor] = [] - partial_amax_list: List[torch.Tensor] = [] - global_amax_list: List[torch.Tensor] = [] - h_list: List[int] = [] - w_list: List[int] = [] - start_offset_list: List[int] = [] - - for i, (model_weight, master_weight, start_offset, _) in enumerate(params): - scale_shape = tile_shapes[i] - amax = packed_amaxes[cu_amax_sizes[i] : cu_amax_sizes[i + 1]].reshape(scale_shape) - scale = packed_scales[cu_amax_sizes[i] : cu_amax_sizes[i + 1]].reshape(scale_shape) - global_amax_view = global_amax_views[i] - if model_weight._rowwise_scale_inv is None: raise RuntimeError("model_weight._rowwise_scale_inv must not be None") + scale_dtypes.add(quantizer.scale_dtype) + if master_weight is not None and master_weight.numel() > 0 and start_offset % 2 != 0: + raise ValueError( + "NVFP4 master weight shards must start at an even element offset, since two FP4 " + f"values share a byte. Got start offset {start_offset} for a model weight of " + f"shape {tuple(model_weight.shape)}." + ) + # There should only be one scale dtype for all quantizers in the params list if using the + # same NVFP4 recipe. + if len(scale_dtypes) != 1: + raise ValueError( + "quantize_master_weights requires a single NVFP4 scale dtype per call, " + f"but got {scale_dtypes}." + ) + # NVFP4Quantizer.scale_dtype is the pure-python constants.DType; the pybind + # entry points want tex.DType. The enum values are shared, so map by value. + scale_dtype = tex.DType(int(scale_dtypes.pop())) - amaxes.append(amax) - scales.append(scale) + tile_shapes: List[tuple[int, int]] = [] + cu_tiles = [0] + for model_weight, _, _, _ in params: + h, w = model_weight.shape + tile_shapes.append(((h + block_len - 1) // block_len, (w + block_len - 1) // block_len)) + cu_tiles.append(cu_tiles[-1] + tile_shapes[-1][0] * tile_shapes[-1][1]) + # Tiles outside this rank's shards keep a zero amax for the max all-reduce. + packed_amaxes = torch.zeros(cu_tiles[-1], dtype=torch.float32, device=device) + packed_scales = torch.empty(cu_tiles[-1], dtype=torch.float32, device=device) + amaxes = [ + packed_amaxes[cu_tiles[i] : cu_tiles[i + 1]].view(tile_shapes[i]) + for i in range(len(params)) + ] + scales = [ + packed_scales[cu_tiles[i] : cu_tiles[i + 1]].view(tile_shapes[i]) + for i in range(len(params)) + ] + global_amaxes = torch.empty(len(params), dtype=torch.float32, device=device) + global_scales = torch.empty(len(params), dtype=torch.float32, device=device) + global_amax_views = [global_amaxes[i : i + 1] for i in range(len(params))] + global_scale_views = [global_scales[i : i + 1] for i in range(len(params))] + + # This rank's shards, grouped by (master dtype, model dtype): each launch takes one of each. + shard_groups = {} + for i, (model_weight, master_weight, start_offset, fsdp_fragment) in enumerate(params): + if master_weight is None or master_weight.numel() == 0: + continue + if master_weight.dtype not in (torch.float32, torch.bfloat16, torch.float16): + master_weight = master_weight.to(model_weight.dtype) + master_weight = master_weight.contiguous() + if use_fsdp_shard_model_weights: + output = fsdp_fragment + else: + end_offset = start_offset + master_weight.numel() + output = model_weight._rowwise_data.view(-1)[start_offset // 2 : (end_offset + 1) // 2] + key = (master_weight.dtype, model_weight.dtype) + shard_groups.setdefault(key, []).append((i, master_weight, output)) + + def shard_args(shards): + model_weights = [params[i][0] for i, _, _ in shards] + return ( + [master_weight for _, master_weight, _ in shards], + [model_weight.shape[0] for model_weight in model_weights], + [model_weight.shape[1] for model_weight in model_weights], + [params[i][2] for i, _, _ in shards], + ) - if master_weight is not None and master_weight.numel() > 0: - if len(model_weight.shape) != 2: - raise ValueError(f"Expected 2D model weight, got {len(model_weight.shape)}D") - h, w = model_weight.shape - # Collect for batched processing - master_weight_list.append(master_weight) - partial_amax_list.append(amax) - global_amax_list.append(global_amax_view) - h_list.append(h) - w_list.append(w) - start_offset_list.append(start_offset) - - # Batched multi-tensor call for partial and global amax computation - if master_weight_list: - tex.nvfp4_multi_tensor_compute_partial_amax( - master_weight_list, - partial_amax_list, - global_amax_list, + for (_, model_dtype), shards in shard_groups.items(): + inputs, h_list, w_list, start_offsets = shard_args(shards) + tex.nvfp4_2d_multi_tensor_partial_amax( + inputs, + [amaxes[i] for i, _, _ in shards], h_list, w_list, - start_offset_list, + start_offsets, block_len, + cast_dtype=tex.DType(int(TE_DType[model_dtype])), ) if packed_amaxes.numel() > 0: torch.distributed.all_reduce(packed_amaxes, op=torch.distributed.ReduceOp.MAX, group=group) + tex.nvfp4_2d_multi_tensor_global_amax(amaxes, global_amax_views) + tex.nvfp4_compute_global_scale(global_amaxes, global_scales, scale_dtype=scale_dtype) + + if not manual_post_all_gather_processing: + # Reset transpose cache for all model weights. + # We cannot create transpose cache here because users (like megatron) may want to + # overlap the all-gather of model weights and forward process, so the model weight is + # not updated currently. + for model_weight, _, _, _ in params: + model_weight.update_usage(rowwise_usage=True, columnwise_usage=False) - if global_amaxes.numel() > 0: - torch.distributed.all_reduce(global_amaxes, op=torch.distributed.ReduceOp.MAX, group=group) - - # Use GPU kernel to compute global encode scales from global amaxes - # This replaces multiple Python tensor operations with a single kernel - global_scale_tensor = torch.empty_like(global_amaxes) - - # There should only be one scale dtype for all quantizers in the params list if using the same NVFP4 recipe. - scale_dtypes = {p[0]._get_quantizer().scale_dtype for p in params} - if len(scale_dtypes) != 1: - raise ValueError( - "quantize_master_weights requires a single NVFP4 scale dtype per call, " - f"but got {scale_dtypes}." + # A model weight without a rowwise amax buffer still gets its scales. + target_amaxes = [ + ( + model_weight._amax_rowwise + if model_weight._amax_rowwise is not None + else torch.empty(1, dtype=torch.float32, device=device) ) - # NVFP4Quantizer.scale_dtype is the pure-python constants.DType; the pybind - # entry points want tex.DType. The enum values are shared, so map by value. - scale_dtype = tex.DType(int(scale_dtypes.pop())) - tex.nvfp4_compute_global_scale(global_amaxes, global_scale_tensor, scale_dtype=scale_dtype) - global_scale_views = [global_scale_tensor[i : i + 1] for i in range(len(params))] - - # Collect tensors for batched fused scale kernel - fused_scale_block_amax_list: List[torch.Tensor] = [] - fused_scale_global_amax_list: List[torch.Tensor] = [] - fused_scale_per_block_scale_list: List[torch.Tensor] = [] - fused_scale_target_scale_list: List[torch.Tensor] = [] - fused_scale_target_amax_list: List[torch.Tensor] = [] - fused_scale_tile_rows_list: List[int] = [] - fused_scale_tile_cols_list: List[int] = [] - fused_scale_rows_padded_list: List[int] = [] - - # Collect tensors for batched partial cast kernel - partial_cast_inp_list: List[torch.Tensor] = [] - partial_cast_out_list: List[torch.Tensor] = [] - partial_cast_scale_list: List[torch.Tensor] = [] - partial_cast_global_scale_list: List[torch.Tensor] = [] - partial_cast_h_list: List[int] = [] - partial_cast_w_list: List[int] = [] - partial_cast_start_offset_list: List[int] = [] - - # First pass: collect all tensors and update usage - zipped_meta = zip( - tile_shapes, - tile_widths, - scale_targets, - amax_targets, - params, + for model_weight, _, _, _ in params + ] + tex.nvfp4_2d_multi_tensor_fused_scale( amaxes, + global_amax_views, scales, - global_scale_views, + [model_weight._rowwise_scale_inv for model_weight, _, _, _ in params], + target_amaxes, + block_len, + scale_dtype=scale_dtype, ) - for idx, ( - tile_shape, - tile_col_cnt, - target_scale, - target_amax, - (model_weight, master_weight, start_offset, model_weight_fragment), - block_amax, - per_block_decode_scale, - global_scale, - ) in enumerate(zipped_meta): - - if not manual_post_all_gather_processing: - # Reset transpose cache for all model weights. - # We cannot create transpose cache here because users (like megatron) may want to - # overlap the all-gather of model weights and forward process, so the model weight is - # not updated currently. - model_weight.update_usage(rowwise_usage=True, columnwise_usage=False) - - tile_rows = tile_shape[0] - rows_padded = target_scale.shape[0] - global_amax_view = global_amaxes[idx : idx + 1] - - # Collect for fused scale kernel (only if target_amax is not None) - if target_amax is not None: - fused_scale_block_amax_list.append(block_amax) - fused_scale_global_amax_list.append(global_amax_view) - fused_scale_per_block_scale_list.append(per_block_decode_scale) - fused_scale_target_scale_list.append(target_scale) - fused_scale_target_amax_list.append(target_amax) - fused_scale_tile_rows_list.append(tile_rows) - fused_scale_tile_cols_list.append(tile_col_cnt) - fused_scale_rows_padded_list.append(rows_padded) - - # Collect for partial cast kernel (only for layers owned by this rank) - if master_weight is not None and master_weight.numel() > 0: - end_offset = start_offset + master_weight.numel() - if not use_fsdp_shard_model_weights: - rowwise_bytes = model_weight._rowwise_data.view(-1) - byte_start = start_offset // 2 - byte_end = (end_offset + 1) // 2 - model_weight_fragment = rowwise_bytes[byte_start:byte_end] - if len(model_weight.shape) != 2: - raise ValueError(f"Expected 2D model weight, got {len(model_weight.shape)}D") - h, w = model_weight.shape - partial_cast_inp_list.append(master_weight) - partial_cast_out_list.append(model_weight_fragment) - partial_cast_scale_list.append(per_block_decode_scale) - partial_cast_global_scale_list.append(global_scale) - partial_cast_h_list.append(h) - partial_cast_w_list.append(w) - partial_cast_start_offset_list.append(start_offset) - - # Batched multi-tensor call for fused scale - if fused_scale_block_amax_list: - tex.nvfp4_multi_tensor_fused_scale( - fused_scale_block_amax_list, - fused_scale_global_amax_list, - fused_scale_per_block_scale_list, - fused_scale_target_scale_list, - fused_scale_target_amax_list, - fused_scale_tile_rows_list, - fused_scale_tile_cols_list, - fused_scale_rows_padded_list, - block_len, - scale_dtype=scale_dtype, - ) - - # Batched multi-tensor call for partial cast - if partial_cast_inp_list: - tex.nvfp4_multi_tensor_2d_partial_cast( - partial_cast_inp_list, - partial_cast_out_list, - partial_cast_scale_list, - partial_cast_global_scale_list, - partial_cast_h_list, - partial_cast_w_list, - partial_cast_start_offset_list, + for (_, model_dtype), shards in shard_groups.items(): + inputs, h_list, w_list, start_offsets = shard_args(shards) + tex.nvfp4_2d_multi_tensor_partial_cast( + inputs, + [output for _, _, output in shards], + [scales[i] for i, _, _ in shards], + [global_scale_views[i] for i, _, _ in shards], + h_list, + w_list, + start_offsets, block_len, + cast_dtype=tex.DType(int(TE_DType[model_dtype])), scale_dtype=scale_dtype, )