|
| 1 | +#!/usr/bin/python3 |
| 2 | + |
| 3 | +# Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 4 | +# |
| 5 | +# See LICENSE for license information. |
| 6 | + |
| 7 | +""" |
| 8 | +Standalone test for FP8 FSDP2 all-gather correctness. |
| 9 | +
|
| 10 | +Verifies that FSDP2's internal all-gather of FP8 parameters produces the same |
| 11 | +result as a manual all-gather of dequantized FP32 values. |
| 12 | +""" |
| 13 | + |
| 14 | +import argparse |
| 15 | +import os |
| 16 | +import sys |
| 17 | +from contextlib import nullcontext |
| 18 | + |
| 19 | +import transformer_engine.pytorch as te |
| 20 | +import transformer_engine.common.recipe |
| 21 | +from transformer_engine.pytorch import fp8_model_init |
| 22 | +import torch |
| 23 | +import torch.distributed as dist |
| 24 | +import torch.nn.functional as F |
| 25 | +from torch import optim |
| 26 | +from torch.distributed.tensor import DTensor |
| 27 | +from torch.distributed._composable.fsdp import fully_shard |
| 28 | +from torch.distributed.device_mesh import init_device_mesh |
| 29 | +from torch import nn |
| 30 | + |
| 31 | +LOCAL_RANK = None |
| 32 | + |
| 33 | +# Fixed model dimensions — this test focuses on allgather correctness, not model flexibility. |
| 34 | +_NUM_HEADS = 8 |
| 35 | +_HEAD_DIM = 64 |
| 36 | +_HIDDEN_SIZE = _NUM_HEADS * _HEAD_DIM # 512 |
| 37 | +_FFN_SIZE = _HIDDEN_SIZE * 4 # 2048 |
| 38 | +_NUM_LAYERS = 2 |
| 39 | +_BATCH_SIZE = 4 |
| 40 | +_SEQ_LEN = 32 |
| 41 | + |
| 42 | + |
| 43 | +def dist_print(msg): |
| 44 | + if LOCAL_RANK == 0: |
| 45 | + print(msg) |
| 46 | + |
| 47 | + |
| 48 | +def _parse_args(): |
| 49 | + parser = argparse.ArgumentParser( |
| 50 | + description="Test FP8 FSDP2 all-gather correctness with TransformerLayer." |
| 51 | + ) |
| 52 | + parser.add_argument( |
| 53 | + "--recipe", |
| 54 | + type=str, |
| 55 | + default="DelayedScaling", |
| 56 | + choices=[ |
| 57 | + "DelayedScaling", |
| 58 | + "Float8CurrentScaling", |
| 59 | + "Float8BlockScaling", |
| 60 | + "MXFP8BlockScaling", |
| 61 | + "NVFP4BlockScaling", |
| 62 | + ], |
| 63 | + ) |
| 64 | + parser.add_argument( |
| 65 | + "--sharding-dims", |
| 66 | + type=int, |
| 67 | + nargs="+", |
| 68 | + required=True, |
| 69 | + help=( |
| 70 | + 'Sharding mesh dimensions: ("dp_shard",), ("dp_replicate", "dp_shard"), ' |
| 71 | + 'or ("dp_replicate", "dp_shard", "tp")' |
| 72 | + ), |
| 73 | + ) |
| 74 | + parser.add_argument("--seed", type=int, default=42) |
| 75 | + args = parser.parse_args() |
| 76 | + assert len(args.sharding_dims) <= 3 |
| 77 | + args.tp_size = args.sharding_dims[2] if len(args.sharding_dims) >= 3 else 1 |
| 78 | + return args |
| 79 | + |
| 80 | + |
| 81 | +def _get_recipe(name): |
| 82 | + return getattr(transformer_engine.common.recipe, name)() |
| 83 | + |
| 84 | + |
| 85 | +def _get_device_mesh(world_size, sharding_dims): |
| 86 | + dist_print(f"sharding-dims: {sharding_dims}") |
| 87 | + if len(sharding_dims) == 1: |
| 88 | + assert sharding_dims[0] == world_size |
| 89 | + return init_device_mesh("cuda", (world_size,), mesh_dim_names=("dp_shard",)) |
| 90 | + elif len(sharding_dims) == 2: |
| 91 | + assert sharding_dims[0] * sharding_dims[1] == world_size |
| 92 | + return init_device_mesh( |
| 93 | + "cuda", |
| 94 | + (sharding_dims[0], sharding_dims[1]), |
| 95 | + mesh_dim_names=("dp_replicate", "dp_shard"), |
| 96 | + ) |
| 97 | + else: |
| 98 | + assert sharding_dims[0] * sharding_dims[1] * sharding_dims[2] == world_size |
| 99 | + return init_device_mesh( |
| 100 | + "cuda", |
| 101 | + (sharding_dims[0], sharding_dims[1], sharding_dims[2]), |
| 102 | + mesh_dim_names=("dp_replicate", "dp_shard", "tp"), |
| 103 | + ) |
| 104 | + |
| 105 | + |
| 106 | +def _build_model(args): |
| 107 | + kwargs = { |
| 108 | + "params_dtype": torch.float32, |
| 109 | + "device": "meta", |
| 110 | + "tp_size": args.tp_size, |
| 111 | + "fuse_qkv_params": True, |
| 112 | + } |
| 113 | + if args.tp_size > 1: |
| 114 | + kwargs["tp_mesh"] = args.mesh["tp"] |
| 115 | + kwargs["weight_mesh"] = args.mesh["dp_shard", "tp"]._flatten("weight_mesh") |
| 116 | + kwargs["set_parallel_mode"] = True |
| 117 | + elif "dp_replicate" in args.mesh.mesh_dim_names: |
| 118 | + kwargs["weight_mesh"] = args.mesh["dp_shard"] |
| 119 | + |
| 120 | + model = nn.Sequential( |
| 121 | + *[ |
| 122 | + te.TransformerLayer(_HIDDEN_SIZE, _FFN_SIZE, _NUM_HEADS, **kwargs) |
| 123 | + for _ in range(_NUM_LAYERS) |
| 124 | + ] |
| 125 | + ) |
| 126 | + inp_shape = [_SEQ_LEN, _BATCH_SIZE, _HIDDEN_SIZE] |
| 127 | + return model, inp_shape |
| 128 | + |
| 129 | + |
| 130 | +def _shard_model(model, mesh): |
| 131 | + dp_dims = ( |
| 132 | + ("dp_replicate", "dp_shard") if "dp_replicate" in mesh.mesh_dim_names else ("dp_shard",) |
| 133 | + ) |
| 134 | + for child in model.children(): |
| 135 | + fully_shard(child, mesh=mesh[dp_dims]) |
| 136 | + fully_shard(model, mesh=mesh[dp_dims]) |
| 137 | + return model |
| 138 | + |
| 139 | + |
| 140 | +@torch.no_grad() |
| 141 | +def _test_fp8_fsdp2_allgather(model): |
| 142 | + """ |
| 143 | + Compare the result of the FP8 AG by FSDP2 with a manual AG in FP32 |
| 144 | + after dequantizing the FP8 values. |
| 145 | + """ |
| 146 | + # FP32 manual weight allgather |
| 147 | + fp32_allgathered_params = {} |
| 148 | + for name, param in model.named_parameters(): |
| 149 | + assert isinstance( |
| 150 | + param, DTensor |
| 151 | + ), f"[test_fp8_fsdp2_allgather] {param} should be a DTensor." |
| 152 | + local_tensor = param._local_tensor |
| 153 | + device_mesh = param.device_mesh |
| 154 | + dist_group = ( |
| 155 | + device_mesh.get_group(mesh_dim="dp_shard") |
| 156 | + if device_mesh.ndim > 1 |
| 157 | + else device_mesh.get_group() |
| 158 | + ) |
| 159 | + # Perform manual allgather on local_tensor. zeros_like will create hp tensor since torch_dispatch |
| 160 | + # for local_tensor will go down the dequantization route. |
| 161 | + gathered_tensor = [ |
| 162 | + torch.zeros_like(local_tensor) for _ in range(dist.get_world_size(group=dist_group)) |
| 163 | + ] |
| 164 | + dist.all_gather(gathered_tensor, local_tensor.dequantize(), group=dist_group) |
| 165 | + full_tensor = torch.cat(gathered_tensor, dim=0) |
| 166 | + fp32_allgathered_params[name] = full_tensor |
| 167 | + # FP8 allgather using FSDP2 |
| 168 | + for module in model.modules(): |
| 169 | + # Not all modules are wrapped/sharded with FSDP2. |
| 170 | + if hasattr(module, "unshard"): |
| 171 | + module.unshard() |
| 172 | + # Make sure allgathered parameters match exactly |
| 173 | + for name, param in model.named_parameters(): |
| 174 | + if isinstance(param, DTensor): |
| 175 | + # Will still be a DTensor in the case of TP, even after FSDP2 AG, |
| 176 | + # because we wrap our weights as DTensor shards over the TP group. |
| 177 | + param = param._local_tensor |
| 178 | + torch.testing.assert_close(param.dequantize(), fp32_allgathered_params[name]) |
| 179 | + # Revert model to original sharded state |
| 180 | + for module in model.modules(): |
| 181 | + # Not all modules are wrapped/sharded with FSDP2. |
| 182 | + if hasattr(module, "reshard"): |
| 183 | + module.reshard() |
| 184 | + |
| 185 | + |
| 186 | +def _main(args): |
| 187 | + global LOCAL_RANK |
| 188 | + assert "TORCHELASTIC_RUN_ID" in os.environ |
| 189 | + WORLD_RANK = int(os.getenv("RANK", "0")) |
| 190 | + WORLD_SIZE = int(os.getenv("WORLD_SIZE", "1")) |
| 191 | + LOCAL_RANK = int(os.getenv("LOCAL_RANK", "0")) |
| 192 | + |
| 193 | + torch.cuda.set_device(WORLD_RANK) |
| 194 | + torch.manual_seed(args.seed) |
| 195 | + torch.cuda.manual_seed(args.seed) |
| 196 | + |
| 197 | + dist.init_process_group(backend="nccl", rank=WORLD_RANK, world_size=WORLD_SIZE) |
| 198 | + device = torch.device(f"cuda:{LOCAL_RANK}") |
| 199 | + |
| 200 | + mesh = _get_device_mesh(WORLD_SIZE, args.sharding_dims) |
| 201 | + args.mesh = mesh |
| 202 | + |
| 203 | + fp8_recipe = _get_recipe(args.recipe) |
| 204 | + |
| 205 | + with fp8_model_init(enabled=True, recipe=fp8_recipe): |
| 206 | + model, inp_shape = _build_model(args) |
| 207 | + |
| 208 | + model = _shard_model(model, mesh) |
| 209 | + |
| 210 | + for module in model.modules(): |
| 211 | + if hasattr(module, "reset_parameters"): |
| 212 | + module.reset_parameters() |
| 213 | + |
| 214 | + # Run a training step to initialize FSDP2 lazy state and update quantization |
| 215 | + # scales before testing the allgather. Block-scaling formats (Float8BlockScaling, |
| 216 | + # NVFP4BlockScaling) only exhibit allgather inconsistencies after weight updates. |
| 217 | + input_data = torch.randn(inp_shape, device=device) |
| 218 | + target = torch.randn(inp_shape, device=device) |
| 219 | + nvfp4_ctx = ( |
| 220 | + torch.autocast(device_type="cuda", dtype=torch.bfloat16) |
| 221 | + if args.recipe == "NVFP4BlockScaling" |
| 222 | + else nullcontext() |
| 223 | + ) |
| 224 | + optimizer = optim.Adam(model.parameters(), lr=1e-3) |
| 225 | + optimizer.zero_grad() |
| 226 | + with nvfp4_ctx, te.autocast(enabled=True, recipe=fp8_recipe): |
| 227 | + output = model(input_data) |
| 228 | + loss = F.mse_loss(output, target) |
| 229 | + loss.backward() |
| 230 | + optimizer.step() |
| 231 | + |
| 232 | + _test_fp8_fsdp2_allgather(model) |
| 233 | + dist_print("test_fp8_fsdp2_allgather passed.") |
| 234 | + |
| 235 | + dist.destroy_process_group() |
| 236 | + return 0 |
| 237 | + |
| 238 | + |
| 239 | +if __name__ == "__main__": |
| 240 | + sys.exit(_main(_parse_args())) |
0 commit comments