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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions qa/L1_pytorch_distributed_unittest/test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ python3 -m pytest -v -s --junitxml=$XML_LOG_DIR/pytest_test_fusible_ops_with_use
python3 -m pytest -v -s --junitxml=$XML_LOG_DIR/pytest_test_cp_utils.xml $TE_PATH/tests/pytorch/attention/test_cp_utils.py || test_fail "test_cp_utils.py"
python3 -m pytest -v -s --junitxml=$XML_LOG_DIR/pytest_test_cu_seqlens_cache.xml $TE_PATH/tests/pytorch/attention/test_cu_seqlens_cache.py || test_fail "test_cu_seqlens_cache.py"
python3 -m pytest -v -s --junitxml=$XML_LOG_DIR/pytest_test_cast_master_weights_to_fp8.xml $TE_PATH/tests/pytorch/distributed/test_cast_master_weights_to_fp8.py || test_fail "test_cast_master_weights_to_fp8.py"
python3 -m pytest -v -s --junitxml=$XML_LOG_DIR/pytest_test_nvfp4_master_weight_cast.xml $TE_PATH/tests/pytorch/distributed/test_nvfp4_master_weight_cast.py || test_fail "test_nvfp4_master_weight_cast.py"
python3 -m pytest -v -s --junitxml=$XML_LOG_DIR/pytest_test_newton_schulz.xml $TE_PATH/tests/pytorch/distributed/test_newton_schulz.py || test_fail "test_newton_schulz.py"
python3 -m pytest -v -s --junitxml=$XML_LOG_DIR/pytest_test_ep.xml $TE_PATH/tests/pytorch/distributed/test_ep.py || test_fail "test_ep.py"

Expand Down
275 changes: 275 additions & 0 deletions tests/pytorch/distributed/test_nvfp4_master_weight_cast.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,275 @@
# Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# See LICENSE for license information.

"""quantize_master_weights for NVFP4 2D weights against a full-tensor NVFP4 quantization.

Each rank owns an uneven, contiguous slice of the concatenated weights, as a distributed
optimizer does. The slice boundaries cut tensors in the middle of rows and of 16x16 tiles.
The FP32 masters are not representable in the model dtype and include all-zero tiles and
outliers. For several update steps, every rank's amaxes and scale-inverses, and the FP4 bytes of
its own shards, must equal those of NVFP4Quantizer applied to the full master weights cast to
the model dtype; the bytes outside its shards must be left unchanged.
"""

import argparse
import pathlib
import sys

sys.path.append(str(pathlib.Path(__file__).resolve().parent.parent))
from utils import run_distributed

import pytest
import torch
import torch.distributed as dist

import transformer_engine.pytorch as te
from transformer_engine.common.recipe import NVFP4BlockScaling
from transformer_engine.pytorch import NVFP4Quantizer, is_nvfp4_available
import transformer_engine.pytorch.tensor.utils as te_utils

SHAPES = [
(4096, 7168),
(7168, 2048),
(512, 512),
(256, 1536),
(48, 64), # scale rows padded beyond the tile rows
(1024, 2048),
(128, 7168),
(7168, 128),
(64, 4096),
(40, 96), # partial tile rows; the scale-inverse has 8 columns for 6 tile columns
(2112, 7168),
] * 3 # more tensors than one launch takes


def _make_weights(shapes, model_dtypes):
torch.manual_seed(1234)
with te.quantized_model_init(enabled=True, recipe=NVFP4BlockScaling()):
layers = [
te.Linear(w, h, bias=False, params_dtype=dtype, device="cuda")
for (h, w), dtype in zip(shapes, model_dtypes)
]
return [layer.weight for layer in layers]


def _masters(shapes):
torch.manual_seed(999) # same full masters on every rank
masters = []
for i, (h, w) in enumerate(shapes):
m = torch.randn(h, w, device="cuda", dtype=torch.float32) * (0.02 * (1 + i % 3))
if i % 4 == 1:
m[: h // 3] *= 1e-3
if i % 5 == 2:
m[:16, :16] = 0 # all-zero tile
if i == 0:
m[5, 7] = 3.7 # outlier
masters.append(m)
return masters


def _rank_slice(numels, rank, world, seed, cuts_2_mod_4=False):
"""Uneven contiguous slice of the flat space, cut at even offsets (all of them 2 mod 4 with
cuts_2_mod_4, which no tensor boundary is, since every numel is a multiple of 16)."""
total = sum(numels)
g = torch.Generator().manual_seed(seed)
cuts = (torch.rand(world - 1, generator=g) * total).tolist()
if cuts_2_mod_4:
cuts = sorted({int(x) // 4 * 4 + 2 for x in cuts})
else:
cuts = sorted({int(x) // 2 * 2 for x in cuts})
bounds = [0] + cuts + [total] * (world - len(cuts))
return bounds[rank], bounds[rank + 1]


def _shards(masters, lo, hi, dtype, layout):
"""This rank's master shards, their start offsets and their [start, end) element spans.

layout "clone": each shard in its own allocation, so a shard that starts at an offset of
2 mod 4 is misaligned for vector loads. "view": each shard is a view into a buffer of the
whole tensor, as in a distributed optimizer's flat buffer, so its tile rows stay aligned
at any even offset. "strided": non-contiguous shards.
"""
shards, offsets, spans = [], [], []
base = 0
for m in masters:
n = m.numel()
s, e = max(lo, base), min(hi, base + n)
if s < e:
values = m.view(-1)[s - base : e - base].to(dtype)
if layout == "clone":
shard = values.clone()
elif layout == "view":
shard = torch.empty(n, dtype=dtype, device="cuda")[s - base : e - base]
shard.copy_(values)
else:
assert layout == "strided", layout
shard = torch.empty(2 * values.numel(), dtype=dtype, device="cuda")[::2]
shard.copy_(values)
shards.append(shard)
offsets.append(s - base)
spans.append((s - base, e - base))
else:
shards.append(None)
offsets.append(None)
spans.append(None)
base += n
return shards, offsets, spans


def _update(masters, shards, spans, generator):
"""An optimizer step: the same update of the full masters on every rank, copied in place
into this rank's shards."""
for m, shard, span in zip(masters, shards, spans):
m.add_(torch.randn(m.shape, device="cuda", generator=generator) * 1e-3)
if shard is not None:
shard.copy_(m.view(-1)[span[0] : span[1]])


def _quantize(weights, shards, offsets, group):
te_utils.quantize_master_weights(
weights, shards, offsets, group, manual_post_all_gather_processing=True
)


def _check(weights, data_before, masters, master_dtype, spans, tag):
rank = dist.get_rank()
reference_quantizer = NVFP4Quantizer(rowwise=True, columnwise=False, with_2d_quantization=True)
bad = []
for i, (weight, before, master, span) in enumerate(zip(weights, data_before, masters, spans)):
ref = reference_quantizer(master.to(master_dtype).to(weight.dtype))
h, w = weight.shape
tile_cols = (w + 15) // 16
name = f"[rank {rank}] {tag} tensor {i} {(h, w)} {weight.dtype}"
if not torch.equal(weight._amax_rowwise, ref._amax_rowwise):
bad.append(f"{name} amax")
scale_inv = weight._rowwise_scale_inv.view(torch.uint8)[:h, :tile_cols]
if not torch.equal(scale_inv, ref._rowwise_scale_inv.view(torch.uint8)[:h, :tile_cols]):
bad.append(f"{name} scale_inv")
expected = before.clone()
if span is not None:
s, e = span
ref_data = ref._rowwise_data.view(torch.uint8).view(-1)
expected[s // 2 : e // 2] = ref_data[s // 2 : e // 2]
if e % 2: # the high nibble of the last byte belongs to the next rank
expected[e // 2] = (expected[e // 2] & 0xF0) | (ref_data[e // 2] & 0x0F)
if not torch.equal(weight._rowwise_data.view(torch.uint8).view(-1), expected):
bad.append(f"{name} rowwise data")
flag = torch.tensor([len(bad)], device="cuda")
dist.all_reduce(flag)
assert flag.item() == 0, "\n".join(bad) or "mismatch on another rank"


def _snapshot(weights):
return [w._rowwise_data.view(torch.uint8).view(-1).clone() for w in weights]


def _check_cast(model_dtypes, master_dtype, seed, layout="clone", cuts_2_mod_4=False):
rank, world = dist.get_rank(), dist.get_world_size()
group = dist.new_group(ranks=list(range(world)))
weights = _make_weights(SHAPES, model_dtypes)
masters = _masters(SHAPES)
lo, hi = _rank_slice([h * w for h, w in SHAPES], rank, world, seed, cuts_2_mod_4)
shards, offsets, spans = _shards(masters, lo, hi, master_dtype, layout)
generator = torch.Generator(device="cuda").manual_seed(seed)
for step in range(3):
if step > 0:
_update(masters, shards, spans, generator)
before = _snapshot(weights)
_quantize(weights, shards, offsets, group)
torch.cuda.synchronize()
_check(weights, before, masters, master_dtype, spans, f"{master_dtype} step {step}")


def _check_cuda_graph(seed):
"""Capture the cast once and replay it after in-place master updates."""
rank, world = dist.get_rank(), dist.get_world_size()
group = dist.new_group(ranks=list(range(world)))
shapes = SHAPES[:11]
weights = _make_weights(shapes, [torch.bfloat16] * len(shapes))
masters = _masters(shapes)
lo, hi = _rank_slice([h * w for h, w in shapes], rank, world, seed)
shards, offsets, spans = _shards(masters, lo, hi, torch.float32, layout="clone")

stream = torch.cuda.Stream()
stream.wait_stream(torch.cuda.current_stream())
with torch.cuda.stream(stream):
for _ in range(2): # warm up NCCL and the allocator outside the capture
_quantize(weights, shards, offsets, group)
torch.cuda.current_stream().wait_stream(stream)
torch.cuda.synchronize()
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph, stream=stream):
_quantize(weights, shards, offsets, group)

generator = torch.Generator(device="cuda").manual_seed(seed)
for step in range(3):
_update(masters, shards, spans, generator)
before = _snapshot(weights)
graph.replay()
torch.cuda.synchronize()
_check(weights, before, masters, torch.float32, spans, f"cuda graph replay {step}")


def _check_odd_offset_rejected():
"""Two FP4 values share a byte, so a shard that starts at an odd offset is an error."""
group = dist.new_group(ranks=list(range(dist.get_world_size())))
weight = _make_weights([(64, 64)], [torch.bfloat16])[0]
shard = torch.zeros(64 * 64 - 1, device="cuda")
# Every rank passes an odd offset, so every rank raises before the all-reduce.
with pytest.raises(ValueError, match="even element offset"):
_quantize([weight], [shard], [1], group)


def _worker():
dist.init_process_group("nccl")
torch.cuda.set_device(dist.get_rank() % torch.cuda.device_count())
try:
n = len(SHAPES)
bf16, fp32, fp16 = torch.bfloat16, torch.float32, torch.float16
# BF16 model weights with FP32 masters: values are rounded to BF16 in registers.
_check_cast([bf16] * n, fp32, seed=77)
_check_cast([bf16] * n, fp32, seed=78)
# FP32 model weights: no rounding.
_check_cast([fp32] * n, fp32, seed=79)
# BF16 masters.
_check_cast([bf16] * n, bf16, seed=80)
# Mixed model dtypes in one call, including FP16.
_check_cast([(bf16, fp32, fp16)[i % 3] for i in range(n)], fp32, seed=82)
# Non-contiguous master shards.
_check_cast([bf16] * n, fp32, seed=83, layout="strided")
# Shards that start at offsets of 2 mod 4: vector loads and stores as views into
# whole-tensor buffers, per-element accesses as separate allocations.
_check_cast([bf16] * n, fp32, seed=84, layout="view", cuts_2_mod_4=True)
_check_cast([bf16] * n, fp32, seed=85, layout="clone", cuts_2_mod_4=True)
_check_odd_offset_rejected()
_check_cuda_graph(seed=81)
dist.barrier()
finally:
dist.destroy_process_group()


@pytest.mark.parametrize("world_size", [1, 2, 4])
def test_nvfp4_master_weight_cast(world_size: int) -> None:
"""Launch the distributed NVFP4 master-weight cast test."""
available, reason = is_nvfp4_available(return_reason=True)
if not available:
pytest.skip(reason)
if torch.cuda.device_count() < world_size:
pytest.skip(f"needs {world_size} GPUs")
command = [
sys.executable,
"-m",
"torch.distributed.run",
f"--nproc_per_node={world_size}",
str(pathlib.Path(__file__).resolve()),
"--worker",
]
run_distributed(command)


if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--worker", action="store_true")
if parser.parse_args().worker:
_worker()
1 change: 1 addition & 0 deletions transformer_engine/common/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -382,6 +382,7 @@ list(APPEND transformer_engine_cuda_arch_specific_sources
normalization/rmsnorm/rmsnorm_fwd_mxfp8.cu
recipe/mxfp8_scaling.cu
recipe/nvfp4.cu
recipe/nvfp4_multi_tensor.cu
transpose/quantize_transpose_square_blockwise.cu
transpose/quantize_transpose_vector_blockwise_fp4.cu)

Expand Down
Loading
Loading