From 9a8bb10cfa39264d82de35319ec17784fa8f4012 Mon Sep 17 00:00:00 2001 From: Siddhartha Raman S Date: Mon, 9 Nov 2026 12:23:01 -0800 Subject: [PATCH 1/6] [PyTorch] Multi-tensor NVFP4 2D master-weight cast Add NVTE_NVFP4_FUSED_MASTER_WEIGHT_CAST (default 0). With it set, quantize_master_weights casts the master shards of a distributed optimizer to 2D NVFP4 model weights with four new multi-tensor kernels (common/recipe/nvfp4_multi_tensor.cu, C API in recipe.h, pybind nvfp4_2d_multi_tensor_*): - tile amaxes read from the FP32 master shards directly; values are rounded to the model dtype (BF16) in registers instead of materializing master.to(bf16); - per-tensor global amaxes taken as the maximum of the all-reduced tile amaxes, which replaces the per-tensor compute_amax kernels and the second all-reduce; - fused scale and partial cast for all tensors, one thread per 16x16 tile with vector loads and 8-byte stores of whole tiles, using the same mul_cvt_fp32_to_fp4_4x conversion as nvfp4_2d_partial_cast. Each kernel takes up to 24 tensors per launch with the metadata passed as kernel parameters, so the calls are CUDA-graph capturable. The FP4 data, scale-inverses and amaxes are bit-identical to the default path; FSDP sharded weights, mixed dtypes and other unsupported layouts fall back to it. On one VR200, 32 x (4096x7168 | 7168x2048) BF16 NVFP4 weights with FP32 masters: 13.76 ms -> 0.59 ms of kernel time per call. Signed-off-by: Siddhartha Raman S Co-Authored-By: Claude Opus 5.5 Signed-off-by: Siddhartha Raman S --- docs/envvars.rst | 6 + .../test_nvfp4_fused_master_weight_cast.py | 245 +++++++ transformer_engine/common/CMakeLists.txt | 1 + .../include/transformer_engine/recipe.h | 89 +++ .../common/recipe/nvfp4_multi_tensor.cu | 623 ++++++++++++++++++ transformer_engine/pytorch/csrc/extensions.h | 27 + .../csrc/extensions/nvfp4_2d_partial_cast.cpp | 122 ++++ .../pytorch/csrc/extensions/pybind.cpp | 30 + transformer_engine/pytorch/tensor/utils.py | 173 ++++- 9 files changed, 1313 insertions(+), 3 deletions(-) create mode 100644 tests/pytorch/distributed/test_nvfp4_fused_master_weight_cast.py create mode 100644 transformer_engine/common/recipe/nvfp4_multi_tensor.cu diff --git a/docs/envvars.rst b/docs/envvars.rst index a0a64b3f637..94b6715789a 100644 --- a/docs/envvars.rst +++ b/docs/envvars.rst @@ -338,6 +338,12 @@ FP8 Configuration :Default: ``0`` :Description: Allow FP8 emulation in UnfusedDotProductAttention. When set to ``1``, UnfusedDotProductAttention can emulate FP8 operations using FP16/BF16 computation. +.. envvar:: NVTE_NVFP4_FUSED_MASTER_WEIGHT_CAST + + :Type: ``int`` (0 or 1) + :Default: ``0`` + :Description: In ``quantize_master_weights`` (the master-weight cast of a distributed optimizer), cast the shards to 2D NVFP4 model weights with multi-tensor kernels: one launch per 24 tensors for the tile amaxes, the global amaxes, the scales and the cast, reading FP32 masters directly instead of a BF16 copy, and with the per-tensor global amaxes taken from the all-reduced tile amaxes instead of a second all-reduce. The FP4 data, scales and amaxes are identical to the default path. FSDP-sharded model weights and unsupported layouts use the default path. + Kernel Configuration ^^^^^^^^^^^^^^^^^^^^ diff --git a/tests/pytorch/distributed/test_nvfp4_fused_master_weight_cast.py b/tests/pytorch/distributed/test_nvfp4_fused_master_weight_cast.py new file mode 100644 index 00000000000..d1cfd3a9d6b --- /dev/null +++ b/tests/pytorch/distributed/test_nvfp4_fused_master_weight_cast.py @@ -0,0 +1,245 @@ +# Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# See LICENSE for license information. + +"""NVTE_NVFP4_FUSED_MASTER_WEIGHT_CAST=1 must give the bytes of the default NVFP4 2D path. + +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 BF16-representable and include all-zero tiles and outliers. For +several update steps, quantize_master_weights with the option must write the same rowwise FP4 +data, scale-inverses and amaxes as without it, on every rank. +""" + +import argparse +import os +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 is_nvfp4_available +import transformer_engine.pytorch.tensor.utils as te_utils + +ENV = "NVTE_NVFP4_FUSED_MASTER_WEIGHT_CAST" + +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), + (2112, 7168), +] * 3 # more tensors than one launch takes + + +def _make_weights(shapes, params_dtype): + """NVFP4 weights; params_dtype "mixed" alternates BF16 and FP32.""" + torch.manual_seed(1234) + dtypes = [params_dtype] * len(shapes) + if params_dtype == "mixed": + dtypes = [(torch.bfloat16, torch.float32)[i % 2] for i in range(len(shapes))] + 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, 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_slices(numels, rank, world, seed): + """Uneven contiguous slices of the flat space, cut at even offsets.""" + total = sum(numels) + g = torch.Generator().manual_seed(seed) + cuts = sorted({int(x) // 2 * 2 for x in (torch.rand(world - 1, generator=g) * total).tolist()}) + bounds = [0] + cuts + [total] * (world + 1 - len(cuts) - 1) + return bounds[rank], bounds[rank + 1] + + +def _shards(masters, lo, hi, dtype): + shards, offsets = [], [] + base = 0 + for m in masters: + n = m.numel() + s, e = max(lo, base), min(hi, base + n) + if s < e: + shards.append(m.view(-1)[s - base : e - base].to(dtype).clone()) + offsets.append(s - base) + else: + shards.append(None) + offsets.append(0) + base += n + return shards, offsets + + +def _quantize(weights, shards, offsets, group, fused): + os.environ[ENV] = "1" if fused else "0" + try: + te_utils.quantize_master_weights( + weights, shards, offsets, group, manual_post_all_gather_processing=True + ) + finally: + os.environ.pop(ENV, None) + + +def _compare(ref, new, tag): + rank = dist.get_rank() + bad = [] + for i, (a, b) in enumerate(zip(ref, new)): + for name in ("_rowwise_data", "_rowwise_scale_inv", "_amax_rowwise"): + ta = getattr(a, name).view(torch.uint8) + tb = getattr(b, name).view(torch.uint8) + if not torch.equal(ta, tb): + bad.append(f"[rank {rank}] {tag} tensor {i} {tuple(a.shape)} {name}") + flag = torch.tensor([len(bad)], device="cuda") + dist.all_reduce(flag) + assert flag.item() == 0, "\n".join(bad) or "mismatch on another rank" + + +def _check_bit_identity(params_dtype, master_dtype, expect_fused, seed): + rank, world = dist.get_rank(), dist.get_world_size() + group = dist.new_group(ranks=list(range(world))) + shapes = SHAPES + ref = _make_weights(shapes, params_dtype) + new = [w.detach().clone() for w in ref] + masters = _masters(shapes) + lo, hi = _rank_slices([h * w for h, w in shapes], rank, world, seed) + shards_ref, offsets = _shards(masters, lo, hi, master_dtype) + shards_new, _ = _shards(masters, lo, hi, master_dtype) + + taken = [] + fused_fn = te_utils._cast_master_weights_to_nvfp4_2d_fused + + def spy(*args, **kwargs): + taken.append(fused_fn(*args, **kwargs)) + return taken[-1] + + te_utils._cast_master_weights_to_nvfp4_2d_fused = spy + try: + for step in range(3): + if step > 0: # an optimizer update between steps + for a, b in zip(shards_ref, shards_new): + if a is not None: + d = (torch.randn_like(a, dtype=torch.float32) * 1e-3).to(a.dtype) + a.add_(d) + b.add_(d) + _quantize(ref, shards_ref, offsets, group, fused=False) + _quantize(new, shards_new, offsets, group, fused=True) + torch.cuda.synchronize() + _compare(ref, new, f"{params_dtype} {master_dtype} step {step}") + finally: + te_utils._cast_master_weights_to_nvfp4_2d_fused = fused_fn + assert taken and all(t == expect_fused for t in taken), taken + + +def _check_cuda_graph(seed): + """Capture the fused 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] + ref = _make_weights(shapes, torch.bfloat16) + new = [w.detach().clone() for w in ref] + masters = _masters(shapes) + lo, hi = _rank_slices([h * w for h, w in shapes], rank, world, seed) + shards_ref, offsets = _shards(masters, lo, hi, torch.float32) + shards_new, _ = _shards(masters, lo, hi, torch.float32) + + 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(new, shards_new, offsets, group, fused=True) + torch.cuda.current_stream().wait_stream(stream) + torch.cuda.synchronize() + graph = torch.cuda.CUDAGraph() + os.environ[ENV] = "1" + try: + with torch.cuda.graph(graph, stream=stream): + te_utils.quantize_master_weights( + new, shards_new, offsets, group, manual_post_all_gather_processing=True + ) + finally: + os.environ.pop(ENV, None) + + for step in range(3): + for a, b in zip(shards_ref, shards_new): + if a is not None: + d = torch.randn_like(a) * 1e-3 + a.add_(d) + b.add_(d) + _quantize(ref, shards_ref, offsets, group, fused=False) + graph.replay() + torch.cuda.synchronize() + _compare(ref, new, f"cuda graph replay {step}") + + +def _worker(): + dist.init_process_group("nccl") + torch.cuda.set_device(dist.get_rank() % torch.cuda.device_count()) + try: + # BF16 model weights with FP32 masters: the fused path rounds in registers. + _check_bit_identity(torch.bfloat16, torch.float32, expect_fused=True, seed=77) + _check_bit_identity(torch.bfloat16, torch.float32, expect_fused=True, seed=78) + # FP32 model weights: no rounding. + _check_bit_identity(torch.float32, torch.float32, expect_fused=True, seed=79) + # BF16 masters. + _check_bit_identity(torch.bfloat16, torch.bfloat16, expect_fused=True, seed=80) + # Mixed model dtypes in one call are left to the default path. + _check_bit_identity("mixed", torch.float32, expect_fused=False, seed=82) + _check_cuda_graph(seed=81) + dist.barrier() + finally: + dist.destroy_process_group() + + +@pytest.mark.parametrize("world_size", [1, 2, 4]) +def test_nvfp4_fused_master_weight_cast(world_size: int) -> None: + """Launch the distributed bit-identity 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 f90f74449c5..3522ab201c5 100644 --- a/transformer_engine/common/CMakeLists.txt +++ b/transformer_engine/common/CMakeLists.txt @@ -378,6 +378,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 98c5eed0985..aec943d4d58 100644 --- a/transformer_engine/common/include/transformer_engine/recipe.h +++ b/transformer_engine/common/include/transformer_engine/recipe.h @@ -539,6 +539,95 @@ 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, + * with one thread per tile. Each input shard may be FP32 or BF16 (one dtype per call). The + * values are 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 [tile_rows, tile_cols], float32, contiguous. + * \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 or kNVTEBFloat16. + * \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, in one launch per 24 tensors. 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, tile_cols], uint8. + * \param[out] target_amax Copies of the global amaxes [1], float32. + * \param[in] tile_rows Tile rows of each tensor. + * \param[in] tile_cols Tile columns of each tensor. + * \param[in] rows_padded Rows of each target scale. + * \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, const size_t *tile_rows, + const size_t *tile_cols, const size_t *rows_padded, + 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, with + * one thread per tile. Gives the same bytes as nvte_nvfp4_2d_partial_cast_v2 applied to the + * shards converted to `cast_dtype`. + * + * \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 [tile_rows, tile_cols], 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 or kNVTEBFloat16. + * \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_multi_tensor.cu b/transformer_engine/common/recipe/nvfp4_multi_tensor.cu new file mode 100644 index 00000000000..81acc7826d4 --- /dev/null +++ b/transformer_engine/common/recipe/nvfp4_multi_tensor.cu @@ -0,0 +1,623 @@ +/************************************************************************* + * 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 produce 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 16-byte loads of FP32 rows (8-byte loads of BF16 + * rows) and 8-byte stores of the FP4 bytes of tiles that the shard covers fully. The existing + * kernels use one 256-thread block per tile and one element per thread. + * - The input can be the FP32 master shard itself with `cast_dtype` = BF16. Each value is then + * rounded to BF16 in registers, which gives the values of master.to(torch.bfloat16) without + * materializing that copy. For the block amax, bf16(max |x|) == max |bf16(x)| because + * round-to-nearest-even is monotonic. + * - The per-tensor global amax can be derived from the all-reduced block amaxes (the maximum of + * the per-tile maxima is the maximum of the tensor), instead of a separate amax pass over the + * shard and a second all-reduce. + * --------------------------------------------------------------------------- + */ + +#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, tile_cols] + float *target_amax; // [1] + int64_t tile_rows; + int64_t tile_cols; + int64_t rows_padded; +}; + +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; +} + +// Value as the existing kernels see it: the input converted to `cast_dtype` (input.to(dtype)), +// then to FP32. +template +__device__ __forceinline__ float cast_value(const float x) { + if constexpr (kRoundToBF16) { + return __bfloat162float(__float2bfloat16_rn(x)); + } else { + return x; + } +} + +template +__device__ __forceinline__ void load4(const IType *p, float (&v)[4]); + +template <> +__device__ __forceinline__ void load4(const float *p, float (&v)[4]) { + const float4 t = __ldg(reinterpret_cast(p)); + v[0] = t.x; + v[1] = t.y; + v[2] = t.z; + v[3] = t.w; +} + +template <> +__device__ __forceinline__ void load4(const bf16 *p, float (&v)[4]) { + const uint2 t = __ldg(reinterpret_cast(p)); + v[0] = __uint_as_float(t.x << 16); + v[1] = __uint_as_float(t.x & 0xFFFF0000u); + v[2] = __uint_as_float(t.y << 16); + v[3] = __uint_as_float(t.y & 0xFFFF0000u); +} + +// 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.tile_cols + 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; + } + } + } +} + +// 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."); + 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; + } + const uintptr_t in_ptr = reinterpret_cast(m.input); + m.vec_load = (m.w % 4 == 0) && (m.start % 4 == 0) && (in_ptr % (4 * elem_size) == 0); + const uintptr_t out_ptr = reinterpret_cast(m.output); + m.vec_store = (m.w % kTileDim == 0) && (m.start % kTileDim == 0) && (out_ptr % 8 == 0); + } + args->tile_offset[end - begin] = tiles; + return tiles; +} + +void check_shard_input(const Tensor &inp, DType input_dtype) { + NVTE_CHECK(inp.dtype() == input_dtype, "All NVFP4 2D shards of one call must have one dtype."); +} + +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; + const DType input_dtype = inp[0]->dtype(); + NVTE_CHECK(input_dtype == DType::kFloat32 || input_dtype == DType::kBFloat16, + "NVFP4 2D shards must be FP32 or BF16."); + NVTE_CHECK(cast_dtype == DType::kFloat32 || cast_dtype == DType::kBFloat16, + "cast_dtype must be FP32 or BF16."); + for (size_t i = 0; i < num_tensors; ++i) { + check_shard_input(*inp[i], input_dtype); + NVTE_CHECK(amax[i]->dtype() == DType::kFloat32, "Block amax must be float32."); + } + const bool round_to_bf16 = cast_dtype == DType::kBFloat16 && input_dtype == DType::kFloat32; + 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_SWITCH_CONDITION( + input_dtype == DType::kFloat32, kFP32Input, + TRANSFORMER_ENGINE_SWITCH_CONDITION( + round_to_bf16, kRoundToBF16, using IType = std::conditional_t; + 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, const size_t *tile_rows, const size_t *tile_cols, + const size_t *rows_padded, 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) { + 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(per_block_scale[i]->dtype() == DType::kFloat32, + "Per-block scale must be float32."); + NVTE_CHECK( + target_scale[i]->dtype() == DType::kByte || target_scale[i]->dtype() == scale_dtype, + "Target scale must be byte storage or have the selected NVFP4 scale dtype."); + 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(block_amax[i]->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(target_scale[i]->data.dptr); + m.target_amax = reinterpret_cast(target_amax[i]->data.dptr); + m.tile_rows = static_cast(tile_rows[i]); + m.tile_cols = static_cast(tile_cols[i]); + m.rows_padded = static_cast(rows_padded[i]); + 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; + const DType input_dtype = inp[0]->dtype(); + NVTE_CHECK(input_dtype == DType::kFloat32 || input_dtype == DType::kBFloat16, + "NVFP4 2D shards must be FP32 or BF16."); + NVTE_CHECK(cast_dtype == DType::kFloat32 || cast_dtype == DType::kBFloat16, + "cast_dtype must be FP32 or BF16."); + for (size_t i = 0; i < num_tensors; ++i) { + check_shard_input(*inp[i], input_dtype); + NVTE_CHECK(out[i]->dtype() == DType::kByte, "NVFP4 rowwise data must be uint8."); + NVTE_CHECK(scale[i]->dtype() == DType::kFloat32, "Scale must be float32."); + NVTE_CHECK(global_scale[i]->dtype() == DType::kFloat32 && global_scale[i]->numel() == 1, + "Global scale must be a single float32 element."); + } + const bool round_to_bf16 = cast_dtype == DType::kBFloat16 && input_dtype == DType::kFloat32; + 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_SWITCH_CONDITION( + input_dtype == DType::kFloat32, kFP32Input, + TRANSFORMER_ENGINE_SWITCH_CONDITION( + round_to_bf16, kRoundToBF16, + using IType = std::conditional_t; + 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, const size_t *tile_rows, + const size_t *tile_cols, const size_t *rows_padded, + 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(), tile_rows, tile_cols, rows_padded, 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 7bcd8430ce1..334d9dd6083 100644 --- a/transformer_engine/pytorch/csrc/extensions.h +++ b/transformer_engine/pytorch/csrc/extensions.h @@ -542,6 +542,33 @@ void nvfp4_multi_tensor_2d_partial_cast(std::vector inp_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, + const std::vector &tile_rows_list, + const std::vector &tile_cols_list, + const std::vector &rows_padded_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..5ccbb4aa87b 100644 --- a/transformer_engine/pytorch/csrc/extensions/nvfp4_2d_partial_cast.cpp +++ b/transformer_engine/pytorch/csrc/extensions/nvfp4_2d_partial_cast.cpp @@ -156,4 +156,126 @@ void nvfp4_multi_tensor_compute_partial_amax( } } +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; +} + +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; +} + +} // 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()); +} + +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()); +} + +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, + const std::vector& tile_rows_list, + const std::vector& tile_cols_list, + const std::vector& rows_padded_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; + const auto tile_rows = to_size_vector(tile_rows_list, n, "tile_rows_list"); + const auto tile_cols = to_size_vector(tile_cols_list, n, "tile_cols_list"); + const auto rows_padded = to_size_vector(rows_padded_list, n, "rows_padded_list"); + 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(), tile_rows.data(), tile_cols.data(), rows_padded.data(), n, + static_cast(block_len), static_cast(scale_dtype), + at::cuda::getCurrentCUDAStream()); +} + +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 6fbed1436fb..04f9e70dcdc 100644 --- a/transformer_engine/pytorch/csrc/extensions/pybind.cpp +++ b/transformer_engine/pytorch/csrc/extensions/pybind.cpp @@ -540,6 +540,36 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { py::arg("w_list"), py::arg("start_offset_list"), py::arg("block_len") = 16, py::arg("scale_dtype") = transformer_engine::DType::kFloat8E4M3, py::call_guard()); + 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, optionally of the shards cast to BF16", + 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 in one launch per 24 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") = 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 in one launch per 24 tensors, optionally of the " + "shards cast to BF16", + 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", &transformer_engine::pytorch::mxfp8_scaling_compute_partial_amax, "Compute partial amax from master weights for fp8 mxfp8 scaling", py::arg("input"), diff --git a/transformer_engine/pytorch/tensor/utils.py b/transformer_engine/pytorch/tensor/utils.py index caaf9cf5aad..defea065a03 100644 --- a/transformer_engine/pytorch/tensor/utils.py +++ b/transformer_engine/pytorch/tensor/utils.py @@ -4,6 +4,7 @@ """Helper functions for using fp8/nvfp4 tensors as weights""" +import os from typing import Optional, Union, List import torch @@ -248,6 +249,7 @@ def quantize_master_weights( fsdp_shard_model_weights = [None] * len(model_weights) else: use_fsdp_shard_model_weights = True + fused_nvfp4_cast = _use_fused_nvfp4_master_weight_cast() and not use_fsdp_shard_model_weights # Validate the entire batch before clearing initialization state or # populating any per-format work buckets. for model_weight, master_weight, start_offset, fsdp_shard_model_weight in zip( @@ -283,15 +285,18 @@ 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 ( + fused_nvfp4_cast and 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 fused NVFP4 cast does 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) @@ -763,6 +768,21 @@ def _cast_master_weights_to_nvfp4_2d( use_fsdp_shard_model_weights : bool, if True, it means that the model weights are sharded. """ + if _use_fused_nvfp4_master_weight_cast() and not use_fsdp_shard_model_weights: + if _cast_master_weights_to_nvfp4_2d_fused(params, group, manual_post_all_gather_processing): + return + # Not eligible: cast the master weights to the model dtype here, as + # quantize_master_weights does without the fused cast. + params = [ + ( + model_weight, + master_weight.to(model_weight.dtype) if master_weight is not None else None, + start_offset, + fragment, + ) + for model_weight, master_weight, start_offset, fragment in params + ] + device = params[0][0].device block_len = NVFP4_BLOCK_SCALING_SIZE @@ -977,6 +997,153 @@ def _cast_master_weights_to_nvfp4_2d( ) +def _use_fused_nvfp4_master_weight_cast() -> bool: + """Whether NVTE_NVFP4_FUSED_MASTER_WEIGHT_CAST=1 selects the multi-tensor NVFP4 2D cast.""" + return os.getenv("NVTE_NVFP4_FUSED_MASTER_WEIGHT_CAST", "0") == "1" + + +def _cast_master_weights_to_nvfp4_2d_fused( + params, group, manual_post_all_gather_processing=False +) -> bool: + r"""Multi-tensor version of `_cast_master_weights_to_nvfp4_2d` (unsharded model weights). + + Produces the same FP4 data, scale-inverses and amaxes as `_cast_master_weights_to_nvfp4_2d` + applied to the master weights cast to the model weights' dtype, with one launch per 24 + tensors for each step: + + 1. tile amaxes, read from the master shards directly (FP32 masters are rounded to BF16 in + registers when the model weights are BF16); + 2. max all-reduce of the tile amaxes (unchanged); + 3. per-tensor global amaxes as the maximum of the reduced tile amaxes, which equals the + all-reduced amax of the tensor: this replaces the per-tensor amax kernels and the second + all-reduce; + 4. global encode scales (unchanged), fused scale and partial cast. + + Returns False without doing anything if the parameters are not eligible. + """ + block_len = NVFP4_BLOCK_SCALING_SIZE + model_dtypes = set() + input_dtypes = set() + for model_weight, master_weight, start_offset, _ in params: + quantizer = model_weight._get_quantizer() + if not isinstance(quantizer, NVFP4Quantizer) or not quantizer.with_2d_quantization: + return False + if len(model_weight.shape) != 2: + return False + data = model_weight._rowwise_data + scale_inv = model_weight._rowwise_scale_inv + if data is None or scale_inv is None or model_weight._amax_rowwise is None: + return False + if not data.is_contiguous() or not scale_inv.is_contiguous(): + return False + if scale_inv.dim() != 2 or scale_inv.dtype != torch.uint8: + return False + model_dtypes.add(model_weight.dtype) + if master_weight is not None and master_weight.numel() > 0: + if not master_weight.is_contiguous() or start_offset % 2 != 0: + return False + input_dtypes.add(master_weight.dtype) + if len(model_dtypes) != 1 or len(input_dtypes) > 1: + return False + model_dtype = model_dtypes.pop() + if model_dtype not in (torch.float32, torch.bfloat16): + return False + if input_dtypes and input_dtypes.pop() not in (torch.float32, torch.bfloat16): + return False + scale_dtypes = {p[0]._get_quantizer().scale_dtype for p in params} + if len(scale_dtypes) != 1: + return False + scale_dtype = tex.DType(int(scale_dtypes.pop())) + cast_dtype = tex.DType.kBFloat16 if model_dtype == torch.bfloat16 else tex.DType.kFloat32 + + device = params[0][0].device + tile_shapes = [] + cu_amax_sizes = [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_amax_sizes.append(cu_amax_sizes[-1] + tile_shapes[-1][0] * tile_shapes[-1][1]) + 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) + global_amaxes = torch.empty(len(params), dtype=torch.float32, device=device) + global_scales = torch.empty(len(params), dtype=torch.float32, device=device) + amaxes = [ + packed_amaxes[cu_amax_sizes[i] : cu_amax_sizes[i + 1]].view(tile_shapes[i]) + for i in range(len(params)) + ] + scales = [ + packed_scales[cu_amax_sizes[i] : cu_amax_sizes[i + 1]].view(tile_shapes[i]) + for i in range(len(params)) + ] + 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))] + + # Shards owned by this rank + owned = [ + i + for i, (_, master_weight, _, _) in enumerate(params) + if master_weight is not None and master_weight.numel() > 0 + ] + shard_inputs = [params[i][1] for i in owned] + shard_h = [params[i][0].shape[0] for i in owned] + shard_w = [params[i][0].shape[1] for i in owned] + shard_starts = [params[i][2] for i in owned] + + tex.nvfp4_2d_multi_tensor_partial_amax( + shard_inputs, + [amaxes[i] for i in owned], + shard_h, + shard_w, + shard_starts, + block_len, + cast_dtype=cast_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: + # See _cast_master_weights_to_nvfp4_2d: the transpose cache is rebuilt after the + # all-gather of the model weights. + for model_weight, _, _, _ in params: + model_weight.update_usage(rowwise_usage=True, columnwise_usage=False) + + tex.nvfp4_2d_multi_tensor_fused_scale( + amaxes, + global_amax_views, + scales, + [p[0]._rowwise_scale_inv for p in params], + [p[0]._amax_rowwise for p in params], + [shape[0] for shape in tile_shapes], + [shape[1] for shape in tile_shapes], + [p[0]._rowwise_scale_inv.shape[0] for p in params], + block_len, + scale_dtype=scale_dtype, + ) + + outputs = [] + for i in owned: + model_weight, master_weight, start_offset, _ = params[i] + rowwise_bytes = model_weight._rowwise_data.view(-1) + outputs.append( + rowwise_bytes[start_offset // 2 : (start_offset + master_weight.numel() + 1) // 2] + ) + tex.nvfp4_2d_multi_tensor_partial_cast( + shard_inputs, + outputs, + [scales[i] for i in owned], + [global_scale_views[i] for i in owned], + shard_h, + shard_w, + shard_starts, + block_len, + cast_dtype=cast_dtype, + scale_dtype=scale_dtype, + ) + return True + + def _identity_storage_data(tensor): if not isinstance(tensor, IdentityTensorStorage): raise TypeError(f"Expected IdentityTensorStorage, got {type(tensor).__name__}") From 22339a5b1174656baf4165d6fb215edaecbce086 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 19:06:50 +0000 Subject: [PATCH 2/6] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- transformer_engine/common/include/transformer_engine/recipe.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/transformer_engine/common/include/transformer_engine/recipe.h b/transformer_engine/common/include/transformer_engine/recipe.h index aec943d4d58..e968df6e75d 100644 --- a/transformer_engine/common/include/transformer_engine/recipe.h +++ b/transformer_engine/common/include/transformer_engine/recipe.h @@ -40,7 +40,7 @@ extern "C" { */ void nvte_delayed_scaling_recipe_amax_and_scale_update( const NVTETensor amax_history, const NVTETensor scale, NVTETensor updated_amax_history, - NVTETensor updated_scale, const char* amax_compute_algo, NVTEDType fp8_dtype, float margin, + NVTETensor updated_scale, const char *amax_compute_algo, NVTEDType fp8_dtype, float margin, cudaStream_t stream); /*! \brief Bulk-update FP8 scaling factors with delayed scaling recipe after amax reduction. @@ -70,7 +70,7 @@ void nvte_delayed_scaling_recipe_amax_and_scale_update( */ void nvte_delayed_scaling_recipe_amax_and_scale_update_after_reduction( const NVTETensor amax_reduction_buffer, std::vector amax_histories, - std::vector scales, const char* amax_compute_algo, NVTEDType fp8_dtype, + std::vector scales, const char *amax_compute_algo, NVTEDType fp8_dtype, float margin, cudaStream_t stream); /*! \brief Compute an FP8 tensor's amax. From 3d25741c88e1e1dcaeee4dec7b8f5d43697aca95 Mon Sep 17 00:00:00 2001 From: Siddhartha Raman S Date: Fri, 13 Nov 2026 11:03:22 -0800 Subject: [PATCH 3/6] [PyTorch] NVFP4 fused master cast: same collectives on every rank The fused path's eligibility used each rank's own master shards (contiguity, start offset, dtype), so one rank could fall back to the default path, which runs two all-reduces, while the others ran the fused path's one, and training would hang. Eligibility now depends only on the model weights, which every rank holds identically. A rank whose own shards the multi-tensor kernels cannot read casts them to the model dtype and computes its tile amaxes and partial cast with the per-tensor kernels, within the fused path's collective schedule. The test adds an odd slice boundary, so one rank takes the per-tensor kernels and the others the multi-tensor ones. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Siddhartha Raman S --- .../test_nvfp4_fused_master_weight_cast.py | 18 +++- transformer_engine/pytorch/tensor/utils.py | 91 +++++++++++++------ 2 files changed, 78 insertions(+), 31 deletions(-) diff --git a/tests/pytorch/distributed/test_nvfp4_fused_master_weight_cast.py b/tests/pytorch/distributed/test_nvfp4_fused_master_weight_cast.py index d1cfd3a9d6b..0355eeccce2 100644 --- a/tests/pytorch/distributed/test_nvfp4_fused_master_weight_cast.py +++ b/tests/pytorch/distributed/test_nvfp4_fused_master_weight_cast.py @@ -8,7 +8,9 @@ optimizer does. The slice boundaries cut tensors in the middle of rows and of 16x16 tiles. The FP32 masters are not BF16-representable and include all-zero tiles and outliers. For several update steps, quantize_master_weights with the option must write the same rowwise FP4 -data, scale-inverses and amaxes as without it, on every rank. +data, scale-inverses and amaxes as without it, on every rank. With an odd slice boundary, +the rank whose shard starts at the odd offset runs the per-tensor kernels for its own shards +while the others run the multi-tensor ones, under the same collectives (no hang). """ import argparse @@ -74,11 +76,14 @@ def _masters(shapes): return masters -def _rank_slices(numels, rank, world, seed): - """Uneven contiguous slices of the flat space, cut at even offsets.""" +def _rank_slices(numels, rank, world, seed, odd_cut=False): + """Uneven contiguous slices of the flat space, cut at even offsets (the first cut at an odd + offset with odd_cut).""" total = sum(numels) g = torch.Generator().manual_seed(seed) cuts = sorted({int(x) // 2 * 2 for x in (torch.rand(world - 1, generator=g) * total).tolist()}) + if odd_cut and cuts: + cuts[0] += 1 bounds = [0] + cuts + [total] * (world + 1 - len(cuts) - 1) return bounds[rank], bounds[rank + 1] @@ -123,14 +128,14 @@ def _compare(ref, new, tag): assert flag.item() == 0, "\n".join(bad) or "mismatch on another rank" -def _check_bit_identity(params_dtype, master_dtype, expect_fused, seed): +def _check_bit_identity(params_dtype, master_dtype, expect_fused, seed, odd_cut=False): rank, world = dist.get_rank(), dist.get_world_size() group = dist.new_group(ranks=list(range(world))) shapes = SHAPES ref = _make_weights(shapes, params_dtype) new = [w.detach().clone() for w in ref] masters = _masters(shapes) - lo, hi = _rank_slices([h * w for h, w in shapes], rank, world, seed) + lo, hi = _rank_slices([h * w for h, w in shapes], rank, world, seed, odd_cut) shards_ref, offsets = _shards(masters, lo, hi, master_dtype) shards_new, _ = _shards(masters, lo, hi, master_dtype) @@ -211,6 +216,9 @@ def _worker(): _check_bit_identity(torch.float32, torch.float32, expect_fused=True, seed=79) # BF16 masters. _check_bit_identity(torch.bfloat16, torch.bfloat16, expect_fused=True, seed=80) + # An odd slice boundary: one rank's shard starts at an odd offset, which only the + # per-tensor kernels take. Every rank must still take the fused path's collectives. + _check_bit_identity(torch.bfloat16, torch.float32, expect_fused=True, seed=83, odd_cut=True) # Mixed model dtypes in one call are left to the default path. _check_bit_identity("mixed", torch.float32, expect_fused=False, seed=82) _check_cuda_graph(seed=81) diff --git a/transformer_engine/pytorch/tensor/utils.py b/transformer_engine/pytorch/tensor/utils.py index defea065a03..45c312b3793 100644 --- a/transformer_engine/pytorch/tensor/utils.py +++ b/transformer_engine/pytorch/tensor/utils.py @@ -1019,11 +1019,18 @@ def _cast_master_weights_to_nvfp4_2d_fused( all-reduce; 4. global encode scales (unchanged), fused scale and partial cast. - Returns False without doing anything if the parameters are not eligible. + Returns False without doing anything if the parameters are not eligible. Eligibility only + depends on the model weights, which every rank of ``group`` holds identically, so all ranks + make the same choice and run the same collectives. The master shards differ per rank: a rank + whose shards the multi-tensor kernels cannot read (non-contiguous, odd start offset, or a + master dtype other than a single FP32 or BF16) casts them to the model dtype and runs the + per-tensor kernels of `_cast_master_weights_to_nvfp4_2d` for its own tile amaxes and partial + cast instead, still within this function's collective schedule. """ block_len = NVFP4_BLOCK_SCALING_SIZE model_dtypes = set() input_dtypes = set() + local_fused = True for model_weight, master_weight, start_offset, _ in params: quantizer = model_weight._get_quantizer() if not isinstance(quantizer, NVFP4Quantizer) or not quantizer.with_2d_quantization: @@ -1040,16 +1047,19 @@ def _cast_master_weights_to_nvfp4_2d_fused( return False model_dtypes.add(model_weight.dtype) if master_weight is not None and master_weight.numel() > 0: + # Rank-local properties: never a reason to return False (see the docstring). if not master_weight.is_contiguous() or start_offset % 2 != 0: - return False + local_fused = False input_dtypes.add(master_weight.dtype) - if len(model_dtypes) != 1 or len(input_dtypes) > 1: + if len(model_dtypes) != 1: return False model_dtype = model_dtypes.pop() if model_dtype not in (torch.float32, torch.bfloat16): return False - if input_dtypes and input_dtypes.pop() not in (torch.float32, torch.bfloat16): - return False + if len(input_dtypes) > 1 or ( + input_dtypes and next(iter(input_dtypes)) not in (torch.float32, torch.bfloat16) + ): + local_fused = False scale_dtypes = {p[0]._get_quantizer().scale_dtype for p in params} if len(scale_dtypes) != 1: return False @@ -1089,15 +1099,31 @@ def _cast_master_weights_to_nvfp4_2d_fused( shard_w = [params[i][0].shape[1] for i in owned] shard_starts = [params[i][2] for i in owned] - tex.nvfp4_2d_multi_tensor_partial_amax( - shard_inputs, - [amaxes[i] for i in owned], - shard_h, - shard_w, - shard_starts, - block_len, - cast_dtype=cast_dtype, - ) + if local_fused: + tex.nvfp4_2d_multi_tensor_partial_amax( + shard_inputs, + [amaxes[i] for i in owned], + shard_h, + shard_w, + shard_starts, + block_len, + cast_dtype=cast_dtype, + ) + elif owned: + # Per-tensor kernels on the master shards cast to the model dtype, as in + # _cast_master_weights_to_nvfp4_2d. Their per-rank global amaxes are not needed: the + # global amaxes come from the reduced tile amaxes below. + shard_inputs = [params[i][1].to(params[i][0].dtype) for i in owned] + unused_global_amaxes = torch.zeros(len(owned), dtype=torch.float32, device=device) + tex.nvfp4_multi_tensor_compute_partial_amax( + shard_inputs, + [amaxes[i] for i in owned], + [unused_global_amaxes[j : j + 1] for j in range(len(owned))], + shard_h, + shard_w, + shard_starts, + block_len, + ) 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) @@ -1129,18 +1155,31 @@ def _cast_master_weights_to_nvfp4_2d_fused( outputs.append( rowwise_bytes[start_offset // 2 : (start_offset + master_weight.numel() + 1) // 2] ) - tex.nvfp4_2d_multi_tensor_partial_cast( - shard_inputs, - outputs, - [scales[i] for i in owned], - [global_scale_views[i] for i in owned], - shard_h, - shard_w, - shard_starts, - block_len, - cast_dtype=cast_dtype, - scale_dtype=scale_dtype, - ) + if local_fused: + tex.nvfp4_2d_multi_tensor_partial_cast( + shard_inputs, + outputs, + [scales[i] for i in owned], + [global_scale_views[i] for i in owned], + shard_h, + shard_w, + shard_starts, + block_len, + cast_dtype=cast_dtype, + scale_dtype=scale_dtype, + ) + elif owned: + tex.nvfp4_multi_tensor_2d_partial_cast( + shard_inputs, + outputs, + [scales[i] for i in owned], + [global_scale_views[i] for i in owned], + shard_h, + shard_w, + shard_starts, + block_len, + scale_dtype=scale_dtype, + ) return True From 6685677b40a16cc38008c101b634de7583523b5a Mon Sep 17 00:00:00 2001 From: Kirthi Shankar Sivamani Date: Fri, 4 Dec 2026 12:11:23 -0800 Subject: [PATCH 4/6] Combine APIs Signed-off-by: Kirthi Shankar Sivamani --- docs/envvars.rst | 6 - .../test_nvfp4_fused_master_weight_cast.py | 253 ----------------- .../test_nvfp4_master_weight_cast.py | 256 ++++++++++++++++++ 3 files changed, 256 insertions(+), 259 deletions(-) delete mode 100644 tests/pytorch/distributed/test_nvfp4_fused_master_weight_cast.py create mode 100644 tests/pytorch/distributed/test_nvfp4_master_weight_cast.py diff --git a/docs/envvars.rst b/docs/envvars.rst index 94b6715789a..a0a64b3f637 100644 --- a/docs/envvars.rst +++ b/docs/envvars.rst @@ -338,12 +338,6 @@ FP8 Configuration :Default: ``0`` :Description: Allow FP8 emulation in UnfusedDotProductAttention. When set to ``1``, UnfusedDotProductAttention can emulate FP8 operations using FP16/BF16 computation. -.. envvar:: NVTE_NVFP4_FUSED_MASTER_WEIGHT_CAST - - :Type: ``int`` (0 or 1) - :Default: ``0`` - :Description: In ``quantize_master_weights`` (the master-weight cast of a distributed optimizer), cast the shards to 2D NVFP4 model weights with multi-tensor kernels: one launch per 24 tensors for the tile amaxes, the global amaxes, the scales and the cast, reading FP32 masters directly instead of a BF16 copy, and with the per-tensor global amaxes taken from the all-reduced tile amaxes instead of a second all-reduce. The FP4 data, scales and amaxes are identical to the default path. FSDP-sharded model weights and unsupported layouts use the default path. - Kernel Configuration ^^^^^^^^^^^^^^^^^^^^ diff --git a/tests/pytorch/distributed/test_nvfp4_fused_master_weight_cast.py b/tests/pytorch/distributed/test_nvfp4_fused_master_weight_cast.py deleted file mode 100644 index 0355eeccce2..00000000000 --- a/tests/pytorch/distributed/test_nvfp4_fused_master_weight_cast.py +++ /dev/null @@ -1,253 +0,0 @@ -# Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# -# See LICENSE for license information. - -"""NVTE_NVFP4_FUSED_MASTER_WEIGHT_CAST=1 must give the bytes of the default NVFP4 2D path. - -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 BF16-representable and include all-zero tiles and outliers. For -several update steps, quantize_master_weights with the option must write the same rowwise FP4 -data, scale-inverses and amaxes as without it, on every rank. With an odd slice boundary, -the rank whose shard starts at the odd offset runs the per-tensor kernels for its own shards -while the others run the multi-tensor ones, under the same collectives (no hang). -""" - -import argparse -import os -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 is_nvfp4_available -import transformer_engine.pytorch.tensor.utils as te_utils - -ENV = "NVTE_NVFP4_FUSED_MASTER_WEIGHT_CAST" - -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), - (2112, 7168), -] * 3 # more tensors than one launch takes - - -def _make_weights(shapes, params_dtype): - """NVFP4 weights; params_dtype "mixed" alternates BF16 and FP32.""" - torch.manual_seed(1234) - dtypes = [params_dtype] * len(shapes) - if params_dtype == "mixed": - dtypes = [(torch.bfloat16, torch.float32)[i % 2] for i in range(len(shapes))] - 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, 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_slices(numels, rank, world, seed, odd_cut=False): - """Uneven contiguous slices of the flat space, cut at even offsets (the first cut at an odd - offset with odd_cut).""" - total = sum(numels) - g = torch.Generator().manual_seed(seed) - cuts = sorted({int(x) // 2 * 2 for x in (torch.rand(world - 1, generator=g) * total).tolist()}) - if odd_cut and cuts: - cuts[0] += 1 - bounds = [0] + cuts + [total] * (world + 1 - len(cuts) - 1) - return bounds[rank], bounds[rank + 1] - - -def _shards(masters, lo, hi, dtype): - shards, offsets = [], [] - base = 0 - for m in masters: - n = m.numel() - s, e = max(lo, base), min(hi, base + n) - if s < e: - shards.append(m.view(-1)[s - base : e - base].to(dtype).clone()) - offsets.append(s - base) - else: - shards.append(None) - offsets.append(0) - base += n - return shards, offsets - - -def _quantize(weights, shards, offsets, group, fused): - os.environ[ENV] = "1" if fused else "0" - try: - te_utils.quantize_master_weights( - weights, shards, offsets, group, manual_post_all_gather_processing=True - ) - finally: - os.environ.pop(ENV, None) - - -def _compare(ref, new, tag): - rank = dist.get_rank() - bad = [] - for i, (a, b) in enumerate(zip(ref, new)): - for name in ("_rowwise_data", "_rowwise_scale_inv", "_amax_rowwise"): - ta = getattr(a, name).view(torch.uint8) - tb = getattr(b, name).view(torch.uint8) - if not torch.equal(ta, tb): - bad.append(f"[rank {rank}] {tag} tensor {i} {tuple(a.shape)} {name}") - flag = torch.tensor([len(bad)], device="cuda") - dist.all_reduce(flag) - assert flag.item() == 0, "\n".join(bad) or "mismatch on another rank" - - -def _check_bit_identity(params_dtype, master_dtype, expect_fused, seed, odd_cut=False): - rank, world = dist.get_rank(), dist.get_world_size() - group = dist.new_group(ranks=list(range(world))) - shapes = SHAPES - ref = _make_weights(shapes, params_dtype) - new = [w.detach().clone() for w in ref] - masters = _masters(shapes) - lo, hi = _rank_slices([h * w for h, w in shapes], rank, world, seed, odd_cut) - shards_ref, offsets = _shards(masters, lo, hi, master_dtype) - shards_new, _ = _shards(masters, lo, hi, master_dtype) - - taken = [] - fused_fn = te_utils._cast_master_weights_to_nvfp4_2d_fused - - def spy(*args, **kwargs): - taken.append(fused_fn(*args, **kwargs)) - return taken[-1] - - te_utils._cast_master_weights_to_nvfp4_2d_fused = spy - try: - for step in range(3): - if step > 0: # an optimizer update between steps - for a, b in zip(shards_ref, shards_new): - if a is not None: - d = (torch.randn_like(a, dtype=torch.float32) * 1e-3).to(a.dtype) - a.add_(d) - b.add_(d) - _quantize(ref, shards_ref, offsets, group, fused=False) - _quantize(new, shards_new, offsets, group, fused=True) - torch.cuda.synchronize() - _compare(ref, new, f"{params_dtype} {master_dtype} step {step}") - finally: - te_utils._cast_master_weights_to_nvfp4_2d_fused = fused_fn - assert taken and all(t == expect_fused for t in taken), taken - - -def _check_cuda_graph(seed): - """Capture the fused 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] - ref = _make_weights(shapes, torch.bfloat16) - new = [w.detach().clone() for w in ref] - masters = _masters(shapes) - lo, hi = _rank_slices([h * w for h, w in shapes], rank, world, seed) - shards_ref, offsets = _shards(masters, lo, hi, torch.float32) - shards_new, _ = _shards(masters, lo, hi, torch.float32) - - 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(new, shards_new, offsets, group, fused=True) - torch.cuda.current_stream().wait_stream(stream) - torch.cuda.synchronize() - graph = torch.cuda.CUDAGraph() - os.environ[ENV] = "1" - try: - with torch.cuda.graph(graph, stream=stream): - te_utils.quantize_master_weights( - new, shards_new, offsets, group, manual_post_all_gather_processing=True - ) - finally: - os.environ.pop(ENV, None) - - for step in range(3): - for a, b in zip(shards_ref, shards_new): - if a is not None: - d = torch.randn_like(a) * 1e-3 - a.add_(d) - b.add_(d) - _quantize(ref, shards_ref, offsets, group, fused=False) - graph.replay() - torch.cuda.synchronize() - _compare(ref, new, f"cuda graph replay {step}") - - -def _worker(): - dist.init_process_group("nccl") - torch.cuda.set_device(dist.get_rank() % torch.cuda.device_count()) - try: - # BF16 model weights with FP32 masters: the fused path rounds in registers. - _check_bit_identity(torch.bfloat16, torch.float32, expect_fused=True, seed=77) - _check_bit_identity(torch.bfloat16, torch.float32, expect_fused=True, seed=78) - # FP32 model weights: no rounding. - _check_bit_identity(torch.float32, torch.float32, expect_fused=True, seed=79) - # BF16 masters. - _check_bit_identity(torch.bfloat16, torch.bfloat16, expect_fused=True, seed=80) - # An odd slice boundary: one rank's shard starts at an odd offset, which only the - # per-tensor kernels take. Every rank must still take the fused path's collectives. - _check_bit_identity(torch.bfloat16, torch.float32, expect_fused=True, seed=83, odd_cut=True) - # Mixed model dtypes in one call are left to the default path. - _check_bit_identity("mixed", torch.float32, expect_fused=False, seed=82) - _check_cuda_graph(seed=81) - dist.barrier() - finally: - dist.destroy_process_group() - - -@pytest.mark.parametrize("world_size", [1, 2, 4]) -def test_nvfp4_fused_master_weight_cast(world_size: int) -> None: - """Launch the distributed bit-identity 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/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..e33fe2f77ea --- /dev/null +++ b/tests/pytorch/distributed/test_nvfp4_master_weight_cast.py @@ -0,0 +1,256 @@ +# 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): + """Uneven contiguous slice of the flat space, cut at even offsets.""" + total = sum(numels) + g = torch.Generator().manual_seed(seed) + cuts = sorted({int(x) // 2 * 2 for x in (torch.rand(world - 1, generator=g) * total).tolist()}) + bounds = [0] + cuts + [total] * (world - len(cuts)) + return bounds[rank], bounds[rank + 1] + + +def _shards(masters, lo, hi, dtype, contiguous): + """This rank's master shards, their start offsets and their [start, end) element spans.""" + 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 contiguous: + shard = values.clone() + else: + 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, contiguous=True): + 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) + shards, offsets, spans = _shards(masters, lo, hi, master_dtype, contiguous) + 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, contiguous=True) + + 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, contiguous=False) + _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() From 8a5c24de4c0469f2ff7eb3465ff515f68bf0ad2e Mon Sep 17 00:00:00 2001 From: Kirthi Shankar Sivamani Date: Fri, 4 Dec 2026 12:11:51 -0800 Subject: [PATCH 5/6] Combine APIs Signed-off-by: Kirthi Shankar Sivamani --- .../include/transformer_engine/recipe.h | 71 ++- transformer_engine/common/recipe/nvfp4.cu | 20 +- .../common/recipe/nvfp4_multi_tensor.cu | 200 ++++---- transformer_engine/pytorch/csrc/extensions.h | 22 - .../csrc/extensions/nvfp4_2d_partial_cast.cpp | 116 +---- .../pytorch/csrc/extensions/pybind.cpp | 34 +- .../pytorch/csrc/extensions/transpose.cpp | 55 --- transformer_engine/pytorch/tensor/utils.py | 460 ++++-------------- 8 files changed, 264 insertions(+), 714 deletions(-) diff --git a/transformer_engine/common/include/transformer_engine/recipe.h b/transformer_engine/common/include/transformer_engine/recipe.h index e968df6e75d..c4a5eb79d34 100644 --- a/transformer_engine/common/include/transformer_engine/recipe.h +++ b/transformer_engine/common/include/transformer_engine/recipe.h @@ -40,7 +40,7 @@ extern "C" { */ void nvte_delayed_scaling_recipe_amax_and_scale_update( const NVTETensor amax_history, const NVTETensor scale, NVTETensor updated_amax_history, - NVTETensor updated_scale, const char *amax_compute_algo, NVTEDType fp8_dtype, float margin, + NVTETensor updated_scale, const char* amax_compute_algo, NVTEDType fp8_dtype, float margin, cudaStream_t stream); /*! \brief Bulk-update FP8 scaling factors with delayed scaling recipe after amax reduction. @@ -70,7 +70,7 @@ void nvte_delayed_scaling_recipe_amax_and_scale_update( */ void nvte_delayed_scaling_recipe_amax_and_scale_update_after_reduction( const NVTETensor amax_reduction_buffer, std::vector amax_histories, - std::vector scales, const char *amax_compute_algo, NVTEDType fp8_dtype, + std::vector scales, const char* amax_compute_algo, NVTEDType fp8_dtype, float margin, cudaStream_t stream); /*! \brief Compute an FP8 tensor's amax. @@ -375,7 +375,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. */ @@ -396,7 +396,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. @@ -480,7 +480,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. @@ -500,7 +501,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. @@ -541,25 +543,25 @@ void nvte_nvfp4_compute_global_scale_v2(const NVTETensor global_amax, NVTETensor /*! \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, - * with one thread per tile. Each input shard may be FP32 or BF16 (one dtype per call). The - * values are 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. + * 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 [tile_rows, tile_cols], float32, contiguous. + * \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 or kNVTEBFloat16. + * \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, +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); @@ -573,59 +575,56 @@ void nvte_nvfp4_2d_multi_tensor_partial_amax(const NVTETensor *inp, NVTETensor * * \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, +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, in one launch per 24 tensors. All buffers are + * 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, tile_cols], uint8. + * \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] tile_rows Tile rows of each tensor. - * \param[in] tile_cols Tile columns of each tensor. - * \param[in] rows_padded Rows of each target scale. * \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, const size_t *tile_rows, - const size_t *tile_cols, const size_t *rows_padded, - size_t num_tensors, size_t block_len, - NVTEDType scale_dtype, cudaStream_t stream); +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, with - * one thread per tile. Gives the same bytes as nvte_nvfp4_2d_partial_cast_v2 applied to the - * shards converted to `cast_dtype`. + * 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 [tile_rows, tile_cols], float32. + * \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 or kNVTEBFloat16. + * \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, + 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 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 index 81acc7826d4..400d92ce18a 100644 --- a/transformer_engine/common/recipe/nvfp4_multi_tensor.cu +++ b/transformer_engine/common/recipe/nvfp4_multi_tensor.cu @@ -10,26 +10,27 @@ * * 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 produce the same bytes as those helpers, with these differences: + * 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 16-byte loads of FP32 rows (8-byte loads of BF16 - * rows) and 8-byte stores of the FP4 bytes of tiles that the shard covers fully. The existing - * kernels use one 256-thread block per tile and one element per thread. - * - The input can be the FP32 master shard itself with `cast_dtype` = BF16. Each value is then - * rounded to BF16 in registers, which gives the values of master.to(torch.bfloat16) without - * materializing that copy. For the block amax, bf16(max |x|) == max |bf16(x)| because - * round-to-nearest-even is monotonic. - * - The per-tensor global amax can be derived from the all-reduced block amaxes (the maximum of - * the per-tile maxima is the maximum of the tensor), instead of a separate amax pass over the - * shard and a second all-reduce. + * - 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" @@ -81,11 +82,12 @@ 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, 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 { @@ -108,36 +110,35 @@ __device__ __forceinline__ int find_tensor(const int64_t *offsets, int n, int64_ return lo; } -// Value as the existing kernels see it: the input converted to `cast_dtype` (input.to(dtype)), -// then to FP32. -template +// An input value as input.to(CType) gives it, in FP32. +template __device__ __forceinline__ float cast_value(const float x) { - if constexpr (kRoundToBF16) { + 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 { - return x; + 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]); - -template <> -__device__ __forceinline__ void load4(const float *p, float (&v)[4]) { - const float4 t = __ldg(reinterpret_cast(p)); - v[0] = t.x; - v[1] = t.y; - v[2] = t.z; - v[3] = t.w; -} - -template <> -__device__ __forceinline__ void load4(const bf16 *p, float (&v)[4]) { - const uint2 t = __ldg(reinterpret_cast(p)); - v[0] = __uint_as_float(t.x << 16); - v[1] = __uint_as_float(t.x & 0xFFFF0000u); - v[2] = __uint_as_float(t.y << 16); - v[3] = __uint_as_float(t.y & 0xFFFF0000u); +__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. @@ -153,7 +154,7 @@ __device__ __forceinline__ bool tile_in_shard(const ShardMeta &m, const int64_t ((r0 + kTileDim - 1) * m.w + c0 + kTileDim - 1 < m.start + m.len); } -template +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; @@ -191,7 +192,7 @@ __global__ void __launch_bounds__(kThreadsPerBlock) // 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); + 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. @@ -246,7 +247,7 @@ __global__ void __launch_bounds__(kThreadsPerBlock) 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.tile_cols + col] = q_bits; + m.target_scale[r * m.scale_stride + col] = q_bits; } } @@ -263,7 +264,7 @@ __device__ __forceinline__ void store_nibble(uint8_t *byte, const int64_t elem_i } // Same arithmetic as nvfp4_2d_partial_cast_kernel; one thread per 16x16 tile. -template +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; @@ -296,7 +297,7 @@ __global__ void __launch_bounds__(kThreadsPerBlock) float v[4]; load4(in + idx0 + 4 * k, v); #pragma unroll - for (int j = 0; j < 4; ++j) v[j] = cast_value(v[j]); + 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); @@ -325,7 +326,7 @@ __global__ void __launch_bounds__(kThreadsPerBlock) 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; + v[j] = mask[j] ? cast_value(static_cast(in[idx])) : 0.0f; any |= mask[j]; } if (!any) continue; @@ -349,6 +350,30 @@ __global__ void __launch_bounds__(kThreadsPerBlock) } } +// 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, @@ -372,7 +397,8 @@ int64_t make_shard_args(ShardArgs *args, const Tensor *const *inp, Tensor *const 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."); + 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; @@ -393,25 +419,16 @@ int64_t make_shard_args(ShardArgs *args, const Tensor *const *inp, Tensor *const return tiles; } -void check_shard_input(const Tensor &inp, DType input_dtype) { - NVTE_CHECK(inp.dtype() == input_dtype, "All NVFP4 2D shards of one call must have one dtype."); -} - 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(); - NVTE_CHECK(input_dtype == DType::kFloat32 || input_dtype == DType::kBFloat16, - "NVFP4 2D shards must be FP32 or BF16."); - NVTE_CHECK(cast_dtype == DType::kFloat32 || cast_dtype == DType::kBFloat16, - "cast_dtype must be FP32 or BF16."); for (size_t i = 0; i < num_tensors; ++i) { - check_shard_input(*inp[i], input_dtype); - NVTE_CHECK(amax[i]->dtype() == DType::kFloat32, "Block amax must be float32."); + check_tile_buffer(*amax[i], h[i], w[i], "Block amax"); } - const bool round_to_bf16 = cast_dtype == DType::kBFloat16 && input_dtype == DType::kFloat32; for (size_t begin = 0; begin < num_tensors; begin += kMaxTensorsPerLaunch) { const size_t end = std::min(num_tensors, begin + kMaxTensorsPerLaunch); ShardArgs args; @@ -419,11 +436,11 @@ void partial_amax(const Tensor *const *inp, Tensor *const *amax, const size_t *h start_offset, begin, end, typeToSize(input_dtype)); if (tiles == 0) continue; const dim3 grid(static_cast((tiles + kThreadsPerBlock - 1) / kThreadsPerBlock)); - TRANSFORMER_ENGINE_SWITCH_CONDITION( - input_dtype == DType::kFloat32, kFP32Input, - TRANSFORMER_ENGINE_SWITCH_CONDITION( - round_to_bf16, kRoundToBF16, using IType = std::conditional_t; - partial_amax_kernel + 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()); } @@ -449,9 +466,8 @@ void global_amax_from_block_amax(const Tensor *const *block_amax, Tensor *const 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, const size_t *tile_rows, const size_t *tile_cols, - const size_t *rows_padded, size_t num_tensors, size_t block_len, DType scale_dtype, - cudaStream_t stream) { + 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); @@ -459,25 +475,37 @@ void fused_scale(const Tensor *const *block_amax, const Tensor *const *global_am args.num_tensors = static_cast(end - begin); int64_t work = 0; for (size_t i = begin; i < end; ++i) { - NVTE_CHECK(block_amax[i]->dtype() == DType::kFloat32, "Block amax must be float32."); + 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( - target_scale[i]->dtype() == DType::kByte || target_scale[i]->dtype() == scale_dtype, - "Target scale must be byte storage or have the selected NVFP4 scale dtype."); + 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(block_amax[i]->data.dptr); + 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(target_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(tile_rows[i]); - m.tile_cols = static_cast(tile_cols[i]); - m.rows_padded = static_cast(rows_padded[i]); + 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; } @@ -497,19 +525,16 @@ void partial_cast(const Tensor *const *inp, Tensor *const *out, const Tensor *co 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(); - NVTE_CHECK(input_dtype == DType::kFloat32 || input_dtype == DType::kBFloat16, - "NVFP4 2D shards must be FP32 or BF16."); - NVTE_CHECK(cast_dtype == DType::kFloat32 || cast_dtype == DType::kBFloat16, - "cast_dtype must be FP32 or BF16."); for (size_t i = 0; i < num_tensors; ++i) { - check_shard_input(*inp[i], input_dtype); NVTE_CHECK(out[i]->dtype() == DType::kByte, "NVFP4 rowwise data must be uint8."); - NVTE_CHECK(scale[i]->dtype() == DType::kFloat32, "Scale must be float32."); + 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."); } - const bool round_to_bf16 = cast_dtype == DType::kBFloat16 && input_dtype == DType::kFloat32; for (size_t begin = 0; begin < num_tensors; begin += kMaxTensorsPerLaunch) { const size_t end = std::min(num_tensors, begin + kMaxTensorsPerLaunch); ShardArgs args; @@ -519,12 +544,11 @@ void partial_cast(const Tensor *const *inp, Tensor *const *out, const Tensor *co const dim3 grid(static_cast((tiles + kThreadsPerBlock - 1) / kThreadsPerBlock)); TRANSFORMER_ENGINE_NVFP4_SCALE_TYPE_SWITCH( scale_dtype, ScaleType, - TRANSFORMER_ENGINE_SWITCH_CONDITION( - input_dtype == DType::kFloat32, kFP32Input, - TRANSFORMER_ENGINE_SWITCH_CONDITION( - round_to_bf16, kRoundToBF16, - using IType = std::conditional_t; - partial_cast_kernel + 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()); } @@ -581,10 +605,9 @@ void nvte_nvfp4_2d_multi_tensor_global_amax(const NVTETensor *block_amax, NVTETe 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, const size_t *tile_rows, - const size_t *tile_cols, const size_t *rows_padded, - size_t num_tensors, size_t block_len, - NVTEDType scale_dtype, cudaStream_t stream) { + 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; @@ -595,8 +618,7 @@ void nvte_nvfp4_2d_multi_tensor_fused_scale(const NVTETensor *block_amax, 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(), tile_rows, tile_cols, rows_padded, num_tensors, block_len, - static_cast(scale_dtype), stream); + 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 diff --git a/transformer_engine/pytorch/csrc/extensions.h b/transformer_engine/pytorch/csrc/extensions.h index 67c413410c1..748d1f61221 100644 --- a/transformer_engine/pytorch/csrc/extensions.h +++ b/transformer_engine/pytorch/csrc/extensions.h @@ -220,11 +220,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); @@ -237,13 +232,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); @@ -547,13 +535,6 @@ 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, @@ -569,9 +550,6 @@ void nvfp4_2d_multi_tensor_fused_scale(const std::vector &block_amax const std::vector &per_block_scale_list, const std::vector &target_scale_list, const std::vector &target_amax_list, - const std::vector &tile_rows_list, - const std::vector &tile_cols_list, - const std::vector &rows_padded_list, int64_t block_len, const DType scale_dtype); void nvfp4_2d_multi_tensor_partial_cast( 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 5ccbb4aa87b..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,113 +49,6 @@ 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; - } - - 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); - } -} - -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"); - - 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"); - - if (num_tensors == 0) { - return; - } - - 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); - } -} - namespace { // TE tensors for a list of contiguous torch tensors; `wrappers` keeps them alive. @@ -222,9 +115,6 @@ void nvfp4_2d_multi_tensor_fused_scale(const std::vector& block_amax const std::vector& per_block_scale_list, const std::vector& target_scale_list, const std::vector& target_amax_list, - const std::vector& tile_rows_list, - const std::vector& tile_cols_list, - const std::vector& rows_padded_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"); @@ -232,9 +122,6 @@ void nvfp4_2d_multi_tensor_fused_scale(const std::vector& block_amax 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; - const auto tile_rows = to_size_vector(tile_rows_list, n, "tile_rows_list"); - const auto tile_cols = to_size_vector(tile_cols_list, n, "tile_cols_list"); - const auto rows_padded = to_size_vector(rows_padded_list, n, "rows_padded_list"); for (const auto& t : target_scale_list) { TORCH_CHECK(t.scalar_type() == at::kByte, "Target scale must be uint8 scale storage."); } @@ -247,8 +134,7 @@ void nvfp4_2d_multi_tensor_fused_scale(const std::vector& block_amax 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(), tile_rows.data(), tile_cols.data(), rows_padded.data(), n, - static_cast(block_len), static_cast(scale_dtype), + target_amax.data(), n, static_cast(block_len), static_cast(scale_dtype), at::cuda::getCurrentCUDAStream()); } diff --git a/transformer_engine/pytorch/csrc/extensions/pybind.cpp b/transformer_engine/pytorch/csrc/extensions/pybind.cpp index 2817ef17ca3..133adae886c 100644 --- a/transformer_engine/pytorch/csrc/extensions/pybind.cpp +++ b/transformer_engine/pytorch/csrc/extensions/pybind.cpp @@ -476,15 +476,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", @@ -520,28 +511,15 @@ 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, - py::arg("scale_dtype") = transformer_engine::DType::kFloat8E4M3, - py::call_guard()); 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, optionally of the shards cast to BF16", + "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, @@ -553,16 +531,14 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { 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 in one launch per 24 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") = 16, + "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 in one launch per 24 tensors, optionally of the " - "shards cast to BF16", + "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, 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 45c312b3793..f6fa1f49c78 100644 --- a/transformer_engine/pytorch/tensor/utils.py +++ b/transformer_engine/pytorch/tensor/utils.py @@ -4,7 +4,6 @@ """Helper functions for using fp8/nvfp4 tensors as weights""" -import os from typing import Optional, Union, List import torch @@ -25,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): @@ -249,7 +248,6 @@ def quantize_master_weights( fsdp_shard_model_weights = [None] * len(model_weights) else: use_fsdp_shard_model_weights = True - fused_nvfp4_cast = _use_fused_nvfp4_master_weight_cast() and not use_fsdp_shard_model_weights # Validate the entire batch before clearing initialization state or # populating any per-format work buckets. for model_weight, master_weight, start_offset, fsdp_shard_model_weight in zip( @@ -287,14 +285,12 @@ def quantize_master_weights( quantizer = model_weight._get_quantizer() - if master_weight is not None and not ( - fused_nvfp4_cast and isinstance(quantizer, NVFP4Quantizer) - ): + 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 fused NVFP4 cast does this conversion in registers instead. + # The NVFP4 kernels do this conversion in registers instead. master_weight = master_weight.to(model_weight.dtype) if isinstance(quantizer, NVFP4Quantizer): @@ -759,39 +755,32 @@ 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. """ - if _use_fused_nvfp4_master_weight_cast() and not use_fsdp_shard_model_weights: - if _cast_master_weights_to_nvfp4_2d_fused(params, group, manual_post_all_gather_processing): - return - # Not eligible: cast the master weights to the model dtype here, as - # quantize_master_weights does without the fused cast. - params = [ - ( - model_weight, - master_weight.to(model_weight.dtype) if master_weight is not None else None, - start_offset, - fragment, - ) - for model_weight, master_weight, start_offset, fragment in params - ] - 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__}") @@ -799,80 +788,17 @@ 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") - - amaxes.append(amax) - scales.append(scale) - - 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, - h_list, - w_list, - start_offset_list, - block_len, - ) - - if packed_amaxes.numel() > 0: - torch.distributed.all_reduce(packed_amaxes, op=torch.distributed.ReduceOp.MAX, group=group) - - 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} + 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, " @@ -881,306 +807,112 @@ def _cast_master_weights_to_nvfp4_2d( # 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, - amaxes, - scales, - global_scale_views, - ) - 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, - block_len, - scale_dtype=scale_dtype, - ) - - -def _use_fused_nvfp4_master_weight_cast() -> bool: - """Whether NVTE_NVFP4_FUSED_MASTER_WEIGHT_CAST=1 selects the multi-tensor NVFP4 2D cast.""" - return os.getenv("NVTE_NVFP4_FUSED_MASTER_WEIGHT_CAST", "0") == "1" - - -def _cast_master_weights_to_nvfp4_2d_fused( - params, group, manual_post_all_gather_processing=False -) -> bool: - r"""Multi-tensor version of `_cast_master_weights_to_nvfp4_2d` (unsharded model weights). - - Produces the same FP4 data, scale-inverses and amaxes as `_cast_master_weights_to_nvfp4_2d` - applied to the master weights cast to the model weights' dtype, with one launch per 24 - tensors for each step: - - 1. tile amaxes, read from the master shards directly (FP32 masters are rounded to BF16 in - registers when the model weights are BF16); - 2. max all-reduce of the tile amaxes (unchanged); - 3. per-tensor global amaxes as the maximum of the reduced tile amaxes, which equals the - all-reduced amax of the tensor: this replaces the per-tensor amax kernels and the second - all-reduce; - 4. global encode scales (unchanged), fused scale and partial cast. - - Returns False without doing anything if the parameters are not eligible. Eligibility only - depends on the model weights, which every rank of ``group`` holds identically, so all ranks - make the same choice and run the same collectives. The master shards differ per rank: a rank - whose shards the multi-tensor kernels cannot read (non-contiguous, odd start offset, or a - master dtype other than a single FP32 or BF16) casts them to the model dtype and runs the - per-tensor kernels of `_cast_master_weights_to_nvfp4_2d` for its own tile amaxes and partial - cast instead, still within this function's collective schedule. - """ - block_len = NVFP4_BLOCK_SCALING_SIZE - model_dtypes = set() - input_dtypes = set() - local_fused = True - for model_weight, master_weight, start_offset, _ in params: - quantizer = model_weight._get_quantizer() - if not isinstance(quantizer, NVFP4Quantizer) or not quantizer.with_2d_quantization: - return False - if len(model_weight.shape) != 2: - return False - data = model_weight._rowwise_data - scale_inv = model_weight._rowwise_scale_inv - if data is None or scale_inv is None or model_weight._amax_rowwise is None: - return False - if not data.is_contiguous() or not scale_inv.is_contiguous(): - return False - if scale_inv.dim() != 2 or scale_inv.dtype != torch.uint8: - return False - model_dtypes.add(model_weight.dtype) - if master_weight is not None and master_weight.numel() > 0: - # Rank-local properties: never a reason to return False (see the docstring). - if not master_weight.is_contiguous() or start_offset % 2 != 0: - local_fused = False - input_dtypes.add(master_weight.dtype) - if len(model_dtypes) != 1: - return False - model_dtype = model_dtypes.pop() - if model_dtype not in (torch.float32, torch.bfloat16): - return False - if len(input_dtypes) > 1 or ( - input_dtypes and next(iter(input_dtypes)) not in (torch.float32, torch.bfloat16) - ): - local_fused = False - scale_dtypes = {p[0]._get_quantizer().scale_dtype for p in params} - if len(scale_dtypes) != 1: - return False - scale_dtype = tex.DType(int(scale_dtypes.pop())) - cast_dtype = tex.DType.kBFloat16 if model_dtype == torch.bfloat16 else tex.DType.kFloat32 - - device = params[0][0].device - tile_shapes = [] - cu_amax_sizes = [0] + 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_amax_sizes.append(cu_amax_sizes[-1] + tile_shapes[-1][0] * tile_shapes[-1][1]) - 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) - global_amaxes = torch.empty(len(params), dtype=torch.float32, device=device) - global_scales = torch.empty(len(params), dtype=torch.float32, device=device) + 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_amax_sizes[i] : cu_amax_sizes[i + 1]].view(tile_shapes[i]) + packed_amaxes[cu_tiles[i] : cu_tiles[i + 1]].view(tile_shapes[i]) for i in range(len(params)) ] scales = [ - packed_scales[cu_amax_sizes[i] : cu_amax_sizes[i + 1]].view(tile_shapes[i]) + 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))] - # Shards owned by this rank - owned = [ - i - for i, (_, master_weight, _, _) in enumerate(params) - if master_weight is not None and master_weight.numel() > 0 - ] - shard_inputs = [params[i][1] for i in owned] - shard_h = [params[i][0].shape[0] for i in owned] - shard_w = [params[i][0].shape[1] for i in owned] - shard_starts = [params[i][2] for i in owned] + # 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 local_fused: + 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( - shard_inputs, - [amaxes[i] for i in owned], - shard_h, - shard_w, - shard_starts, - block_len, - cast_dtype=cast_dtype, - ) - elif owned: - # Per-tensor kernels on the master shards cast to the model dtype, as in - # _cast_master_weights_to_nvfp4_2d. Their per-rank global amaxes are not needed: the - # global amaxes come from the reduced tile amaxes below. - shard_inputs = [params[i][1].to(params[i][0].dtype) for i in owned] - unused_global_amaxes = torch.zeros(len(owned), dtype=torch.float32, device=device) - tex.nvfp4_multi_tensor_compute_partial_amax( - shard_inputs, - [amaxes[i] for i in owned], - [unused_global_amaxes[j : j + 1] for j in range(len(owned))], - shard_h, - shard_w, - shard_starts, + inputs, + [amaxes[i] for i, _, _ in shards], + h_list, + w_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: - # See _cast_master_weights_to_nvfp4_2d: the transpose cache is rebuilt after the - # all-gather of the model weights. + # 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) + # 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) + ) + for model_weight, _, _, _ in params + ] tex.nvfp4_2d_multi_tensor_fused_scale( amaxes, global_amax_views, scales, - [p[0]._rowwise_scale_inv for p in params], - [p[0]._amax_rowwise for p in params], - [shape[0] for shape in tile_shapes], - [shape[1] for shape in tile_shapes], - [p[0]._rowwise_scale_inv.shape[0] for p in params], + [model_weight._rowwise_scale_inv for model_weight, _, _, _ in params], + target_amaxes, block_len, scale_dtype=scale_dtype, ) - outputs = [] - for i in owned: - model_weight, master_weight, start_offset, _ = params[i] - rowwise_bytes = model_weight._rowwise_data.view(-1) - outputs.append( - rowwise_bytes[start_offset // 2 : (start_offset + master_weight.numel() + 1) // 2] - ) - if local_fused: + 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( - shard_inputs, - outputs, - [scales[i] for i in owned], - [global_scale_views[i] for i in owned], - shard_h, - shard_w, - shard_starts, - block_len, - cast_dtype=cast_dtype, - scale_dtype=scale_dtype, - ) - elif owned: - tex.nvfp4_multi_tensor_2d_partial_cast( - shard_inputs, - outputs, - [scales[i] for i in owned], - [global_scale_views[i] for i in owned], - shard_h, - shard_w, - shard_starts, + 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, ) - return True def _identity_storage_data(tensor): From 1dcd25a905fbd7743ae6ed829caee54a16f875a9 Mon Sep 17 00:00:00 2001 From: Kirthi Shankar Sivamani Date: Fri, 4 Dec 2026 12:43:34 -0800 Subject: [PATCH 6/6] minor change Signed-off-by: Kirthi Shankar Sivamani --- qa/L1_pytorch_distributed_unittest/test.sh | 1 + .../test_nvfp4_master_weight_cast.py | 41 ++++++++++++++----- .../common/recipe/nvfp4_multi_tensor.cu | 11 +++-- 3 files changed, 38 insertions(+), 15 deletions(-) diff --git a/qa/L1_pytorch_distributed_unittest/test.sh b/qa/L1_pytorch_distributed_unittest/test.sh index 41ab6aeb444..4c518f7f536 100644 --- a/qa/L1_pytorch_distributed_unittest/test.sh +++ b/qa/L1_pytorch_distributed_unittest/test.sh @@ -55,6 +55,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 index e33fe2f77ea..24b4fd07ab1 100644 --- a/tests/pytorch/distributed/test_nvfp4_master_weight_cast.py +++ b/tests/pytorch/distributed/test_nvfp4_master_weight_cast.py @@ -68,17 +68,28 @@ def _masters(shapes): return masters -def _rank_slice(numels, rank, world, seed): - """Uneven contiguous slice of the flat space, cut at even offsets.""" +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 = sorted({int(x) // 2 * 2 for x in (torch.rand(world - 1, generator=g) * total).tolist()}) + 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, contiguous): - """This rank's master shards, their start offsets and their [start, end) element spans.""" +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: @@ -86,9 +97,13 @@ def _shards(masters, lo, hi, dtype, contiguous): s, e = max(lo, base), min(hi, base + n) if s < e: values = m.view(-1)[s - base : e - base].to(dtype) - if contiguous: + 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) @@ -149,13 +164,13 @@ 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, contiguous=True): +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) - shards, offsets, spans = _shards(masters, lo, hi, master_dtype, contiguous) + 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: @@ -174,7 +189,7 @@ def _check_cuda_graph(seed): 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, contiguous=True) + shards, offsets, spans = _shards(masters, lo, hi, torch.float32, layout="clone") stream = torch.cuda.Stream() stream.wait_stream(torch.cuda.current_stream()) @@ -222,7 +237,11 @@ def _worker(): # 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, contiguous=False) + _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() diff --git a/transformer_engine/common/recipe/nvfp4_multi_tensor.cu b/transformer_engine/common/recipe/nvfp4_multi_tensor.cu index 400d92ce18a..f7b4e9f241b 100644 --- a/transformer_engine/common/recipe/nvfp4_multi_tensor.cu +++ b/transformer_engine/common/recipe/nvfp4_multi_tensor.cu @@ -410,10 +410,13 @@ int64_t make_shard_args(ShardArgs *args, const Tensor *const *inp, Tensor *const } else { m.first_tile_row = 0; } - const uintptr_t in_ptr = reinterpret_cast(m.input); - m.vec_load = (m.w % 4 == 0) && (m.start % 4 == 0) && (in_ptr % (4 * elem_size) == 0); - const uintptr_t out_ptr = reinterpret_cast(m.output); - m.vec_store = (m.w % kTileDim == 0) && (m.start % kTileDim == 0) && (out_ptr % 8 == 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;