Stable Multi-Node Multi-GPU Training: FSDP2 Practices and Troubleshooting Guide

    This guide explores practical strategies for stabilizing multi-node, multi-GPU training using FSDP2 in PyTorch. It covers the differences between training and inference adaptation, common training challenges like memory pressure and numerical instability, and provides a complete code example for building an FSDP2 training pipeline. Additionally, it includes a stability checklist, a step-by-step troubleshooting guide for numerical overflow, and a template for comprehensive test reporting to ensure reliable and reproducible training runs.

    1. Training Adaptation vs. Inference Adaptation

    Inference adaptation primarily verifies forward computation accuracy and throughput. Training adaptation, however, must verify backward propagation, cross-GPU communication, and optimizer state updates to ensure continuous operation over several days. A model completing inference or running a few dozen training steps on a specific chip does not guarantee it can complete full pre-training. Successful training adaptation requires the entire pipeline to run continuously at the target scale with reproducible results.

    Large model training typically encounters three main types of issues:

    1. Memory Pressure: Parameters, gradients, and optimizer states often exceed single-GPU capacity and require sharding. For mixed-precision AdamW, the optimizer states consume significant VRAM, so sharding primarily benefits optimizer states and gradients.
    2. Communication Overhead: If bandwidth is insufficient or improperly configured, parameter gathering and gradient reduction across GPUs will degrade throughput. In severe cases, processes hang, with all GPUs stuck at the same communication call and no further log output.
    3. Numerical Stability: In mixed-precision training, gradients may explode, vanish, or overflow into NaN/Inf. Once a non-finite value appears on any rank, the parameters are polluted, rendering subsequent training meaningless.

    2. Building a Training Pipeline with FSDP2

    FSDP2 is PyTorch’s fully sharded data parallel solution that shards parameters by module. In PyTorch 2.6 and above, it can be invoked via torch.distributed.fsdp.fully_shard. Before forward computation, the system gathers the full parameters needed for the current module (All-Gather) and releases them after computation. During backward propagation, gradients undergo Reduce-Scatter, so each GPU only retains its responsible gradient shard. The optimizer acts directly on the sharded parameters, meaning optimizer states are also sharded without additional copying.

    A crucial ordering constraint to note: fully_shard must be called before creating the optimizer. If the optimizer is created first, it receives unsharded parameters, leading to training errors or incorrect updates.

    The following code is written for NVIDIA GPUs. For vendor-specific GPUs, you need to replace two components: the communication backend name and the device interface (calls related to torch.cuda). The code assumes the model has a layers attribute (each element being a Transformer block) and that the model’s forward method accepts batch fields and returns an object with a loss attribute. Align these assumptions with your specific model. The code is written based on the PyTorch 2.6 API; test it with small-scale data in your target environment first.

    1. # train_fsdp2.py
    2. # Execute once per machine, with NODE_RANK taking 0, 1, ... respectively
    3. # torchrun --nnodes=2 --nproc_per_node=8 --node_rank=$NODE_RANK \
    4. # --master_addr=$MASTER_ADDR --master_port=29500 train_fsdp2.py
    5. import os
    6. from datetime import timedelta
    7. import torch
    8. import torch.distributed as dist
    9. import torch.distributed.checkpoint as dcp
    10. from torch.distributed.checkpoint.state_dict import get_state_dict, set_state_dict
    11. from torch.distributed.device_mesh import init_device_mesh
    12. from torch.distributed.fsdp import fully_shard, MixedPrecisionPolicy
    13. from torch.utils.data import DataLoader, DistributedSampler
    14. def setup_distributed():
    15. # timeout must be greater than the slowest single-step time plus checkpoint saving time; too short will misjudge normal waiting as a hang
    16. dist.init_process_group(backend="nccl", timeout=timedelta(minutes=30)) # Replace with vendor communication backend for vendor-specific GPUs
    17. local_rank = int(os.environ["LOCAL_RANK"])
    18. torch.cuda.set_device(local_rank) # Replace with vendor device interface for vendor-specific GPUs
    19. return torch.device("cuda", local_rank), local_rank
    20. def build_fsdp2_model(model, world_size):
    21. mesh = init_device_mesh("cuda", (world_size,))
    22. mp_policy = MixedPrecisionPolicy(
    23. param_dtype=torch.bfloat16, # Parameter precision used for forward computation
    24. reduce_dtype=torch.float32, # Use FP32 for gradient reduction to reduce cumulative errors
    25. )
    26. for block in model.layers: # Shard block by block; parameters are gathered only when needed
    27. fully_shard(block, mesh=mesh, mp_policy=mp_policy)
    28. fully_shard(model, mesh=mesh, mp_policy=mp_policy)
    29. return model
    30. def all_ranks_ok(tensors, device):
    31. # All ranks must consistently decide whether to skip this step. Some ranks updating while others do not will cause parameter inconsistency or communication misalignment
    32. ok = all(torch.isfinite(t).all().item() for t in tensors)
    33. flag = torch.tensor(1.0 if ok else 0.0, device=device)
    34. dist.all_reduce(flag, op=dist.ReduceOp.MIN)
    35. return flag.item() == 1.0
    36. def save_checkpoint(model, optimizer, step, ckpt_dir):
    37. # All ranks must call dcp.save; each rank writes its own shard
    38. model_sd, optim_sd = get_state_dict(model, optimizer)
    39. dcp.save({"model": model_sd, "optim": optim_sd},
    40. checkpoint_id=os.path.join(ckpt_dir, f"step_{step}"))
    41. def load_checkpoint(model, optimizer, path):
    42. model_sd, optim_sd = get_state_dict(model, optimizer)
    43. state = {"model": model_sd, "optim": optim_sd}
    44. dcp.load(state, checkpoint_id=path)
    45. set_state_dict(model, optimizer,
    46. model_state_dict=state["model"],
    47. optim_state_dict=state["optim"])
    48. def train(model, dataset, device, rank, world_size, epochs,
    49. ckpt_dir, save_every=500, resume_path=None,
    50. lr=1e-4, max_norm=1.0):
    51. model = build_fsdp2_model(model.to(device), world_size)
    52. # Optimizer must be created after fully_shard; it gets the sharded parameters held by this GPU
    53. optimizer = torch.optim.AdamW(model.parameters(), lr=lr)
    54. if resume_path:
    55. load_checkpoint(model, optimizer, resume_path)
    56. sampler = DistributedSampler(dataset, num_replicas=world_size,
    57. rank=rank, shuffle=True)
    58. loader = DataLoader(dataset, batch_size=4, sampler=sampler,
    59. num_workers=4, pin_memory=True, drop_last=True)
    60. step, skipped = 0, 0
    61. for epoch in range(epochs):
    62. sampler.set_epoch(epoch) # Shuffle order changes every epoch, and the split among ranks remains consistent
    63. for batch in loader:
    64. batch = {k: v.to(device, non_blocking=True) for k, v in batch.items()}
    65. optimizer.zero_grad(set_to_none=True)
    66. loss = model(**batch).loss
    67. loss.backward() # Backward: Reduce-Scatter shards gradients
    68. grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=max_norm)
    69. if not all_ranks_ok([loss, grad_norm], device):
    70. skipped += 1
    71. if rank == 0:
    72. print(f"step {step}: Non-finite value detected, skipping this step. Total skips: {skipped}")
    73. step += 1
    74. continue
    75. optimizer.step()
    76. step += 1
    77. if rank == 0 and step % 10 == 0:
    78. print(f"step {step} loss {loss.item():.4f} grad_norm {float(grad_norm):.4f}")
    79. if step % save_every == 0:
    80. save_checkpoint(model, optimizer, step, ckpt_dir)
    81. return model
    82. def main():
    83. device, local_rank = setup_distributed()
    84. rank, world_size = dist.get_rank(), dist.get_world_size()
    85. ckpt_dir = "/data/ckpt"
    86. if rank == 0:
    87. os.makedirs(ckpt_dir, exist_ok=True)
    88. dist.barrier()
    89. model = build_model() # Replace with your model constructor; the model needs a layers attribute
    90. dataset = build_dataset() # Replace with your dataset; sample fields must align with model forward
    91. train(model, dataset, device, rank, world_size, epochs=1, ckpt_dir=ckpt_dir)
    92. dist.destroy_process_group()
    93. if __name__ == "__main__":
    94. main()

    There are a few points in the code you need to confirm:

    1. The return type of clip_grad_norm_ may have varying support for DTensor across different versions. On the first run, print type(grad_norm) to ensure float(grad_norm) executes correctly.
    2. When resuming training, the code only restores the model and optimizer states. To precisely resume the data sequence, you need to write the current epoch and step into the checkpoint and skip already trained samples upon resumption. This part is not included in the example above.
    3. The batch_size in DataLoader is the per-GPU batch. The global batch size equals the per-GPU batch multiplied by the number of GPUs, and then by the gradient accumulation steps (this example does not use gradient accumulation).

    3. Multi-Node Multi-GPU Stability Checklist

    Getting the code to run does not mean the cluster is stable. Complete the following checklist before starting an official long-run. Every item should have a recordable result.

    Check Item Method Pass Criteria
    Communication backend connectivity Run a small all_reduce test across machines, covering all nodes and GPUs Each rank gets the same result with no timeout
    Rank to device mapping Each rank prints hostname, LOCAL_RANK, and device ID Each rank uniquely corresponds to one GPU, with no duplicates or omissions
    Process group timeout Check the timeout setting in init_process_group Greater than the sum of the slowest single-step time and checkpoint saving time, with a buffer
    VRAM monitoring Record torch.cuda.max_memory_allocated() at fixed step intervals Peak is below the single-GPU available VRAM, with a buffer
    Throughput monitoring Record tokens processed per second Compare with the single-node baseline; no continuous decline during the long run
    Long-run stability Run continuously for the duration required by the project No hangs, no crashes, throughput fluctuations within a pre-agreed range
    Log attribution Metrics are printed only by rank 0; other ranks write to their respective files Issues can be located by rank when they occur
    Checkpoint recovery Stop the process mid-run and recover from the latest checkpoint Loss resumes near the interruption point without significant jumps

    The duration of the long-run is determined by project requirements. The checklist narrows down the problem scope but cannot guarantee that any cluster will be stable under any load. Every time you change drivers, SDKs, PyTorch versions, or network configurations, you must run the checklist again.

    4. Troubleshooting Order for Numerical Overflow

    When encountering NaN or Inf during training, follow this troubleshooting order instead of simply lowering the learning rate or disabling mixed precision.

    1. Confirm the scope. Determine whether the loss is non-finite or the grad_norm is non-finite. Record the step number and corresponding batch number of the first occurrence.
    2. Check input data. Inspect whether the batch contains empty samples, excessively long sequences, out-of-bounds labels, or abnormal feature values. Many NaNs originate from the data, not the model itself.
    3. Reproduce the problem. Fix the random seed and run a forward and backward pass using only the problematic batch. If it stably reproduces, the issue is related to that batch. If it cannot be reproduced, it is likely related to the training state or communication.
    4. Observe grad_norm trends. If grad_norm continuously rises over a few dozen steps and then suddenly becomes non-finite, it usually indicates the learning rate is too high, warmup is insufficient, or a gradient explosion occurred.
    5. Locate layer by layer. In a debugging environment, register forward hooks for each module to check if each layer’s output is finite, finding the first module with a non-finite value. Backward direction issues can be located using torch.autograd.set_detect_anomaly(True), but it significantly slows down speed and should only be used for debugging.
    6. Adjust precision and hyperparameters. When using bf16 for parameters and activations, loss scaling is typically not needed. If using fp16, you must use it with GradScaler and first verify that the combination of FSDP2 and GradScaler in your specific version has been tested. After adjusting the learning rate, warmup steps, or max_norm, rerun the same batch of data and compare the changes in grad_norm.

    The all_ranks_ok in the code skips the step when non-finite values appear. Skipping is a protective measure, not a solution. If the number of skips continuously increases, return to the steps above to find the root cause.

    5. What Conditions Should a Test Report Record?

    The same code can yield vastly different results under different conditions. Without recording run conditions, conclusions cannot be reproduced. Record the following template for every long-run stability test.

    • Hardware: GPU model, GPUs per node, number of nodes, intra-node and inter-node interconnect methods.
    • Software: PyTorch version, CUDA or vendor SDK version, driver version, communication library version.
    • Parallel strategy: FSDP2, sharding granularity (in this example, per Transformer block), device mesh shape.
    • Precision: param_dtype, reduce_dtype, whether loss scaling is used.
    • Data and batch: Dataset version, per-GPU batch size, global batch size, sequence length.
    • Hyperparameters: Optimizer, learning rate, warmup steps, max_norm.
    • Communication settings: Communication backend, process group timeout.
    • Run results: Run duration, total steps, throughput (tokens/s), peak VRAM.
    • Numerical anomalies: Number of NaN/Inf occurrences, first occurrence step, handling method, whether it affected subsequent training.
    • Checkpoint recovery: Number of interruptions, checkpoint used for recovery, whether loss resumed after recovery.

    Recording these conditions is the only way to determine if a training pipeline has truly succeeded. Missing any of these makes it impossible to evaluate the stability and reproducibility of the training run.