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:
- 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.
- 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.
- 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.
# train_fsdp2.py# Execute once per machine, with NODE_RANK taking 0, 1, ... respectively# torchrun --nnodes=2 --nproc_per_node=8 --node_rank=$NODE_RANK \# --master_addr=$MASTER_ADDR --master_port=29500 train_fsdp2.pyimport osfrom datetime import timedeltaimport torchimport torch.distributed as distimport torch.distributed.checkpoint as dcpfrom torch.distributed.checkpoint.state_dict import get_state_dict, set_state_dictfrom torch.distributed.device_mesh import init_device_meshfrom torch.distributed.fsdp import fully_shard, MixedPrecisionPolicyfrom torch.utils.data import DataLoader, DistributedSamplerdef setup_distributed():# timeout must be greater than the slowest single-step time plus checkpoint saving time; too short will misjudge normal waiting as a hangdist.init_process_group(backend="nccl", timeout=timedelta(minutes=30)) # Replace with vendor communication backend for vendor-specific GPUslocal_rank = int(os.environ["LOCAL_RANK"])torch.cuda.set_device(local_rank) # Replace with vendor device interface for vendor-specific GPUsreturn torch.device("cuda", local_rank), local_rankdef build_fsdp2_model(model, world_size):mesh = init_device_mesh("cuda", (world_size,))mp_policy = MixedPrecisionPolicy(param_dtype=torch.bfloat16, # Parameter precision used for forward computationreduce_dtype=torch.float32, # Use FP32 for gradient reduction to reduce cumulative errors)for block in model.layers: # Shard block by block; parameters are gathered only when neededfully_shard(block, mesh=mesh, mp_policy=mp_policy)fully_shard(model, mesh=mesh, mp_policy=mp_policy)return modeldef all_ranks_ok(tensors, device):# All ranks must consistently decide whether to skip this step. Some ranks updating while others do not will cause parameter inconsistency or communication misalignmentok = all(torch.isfinite(t).all().item() for t in tensors)flag = torch.tensor(1.0 if ok else 0.0, device=device)dist.all_reduce(flag, op=dist.ReduceOp.MIN)return flag.item() == 1.0def save_checkpoint(model, optimizer, step, ckpt_dir):# All ranks must call dcp.save; each rank writes its own shardmodel_sd, optim_sd = get_state_dict(model, optimizer)dcp.save({"model": model_sd, "optim": optim_sd},checkpoint_id=os.path.join(ckpt_dir, f"step_{step}"))def load_checkpoint(model, optimizer, path):model_sd, optim_sd = get_state_dict(model, optimizer)state = {"model": model_sd, "optim": optim_sd}dcp.load(state, checkpoint_id=path)set_state_dict(model, optimizer,model_state_dict=state["model"],optim_state_dict=state["optim"])def train(model, dataset, device, rank, world_size, epochs,ckpt_dir, save_every=500, resume_path=None,lr=1e-4, max_norm=1.0):model = build_fsdp2_model(model.to(device), world_size)# Optimizer must be created after fully_shard; it gets the sharded parameters held by this GPUoptimizer = torch.optim.AdamW(model.parameters(), lr=lr)if resume_path:load_checkpoint(model, optimizer, resume_path)sampler = DistributedSampler(dataset, num_replicas=world_size,rank=rank, shuffle=True)loader = DataLoader(dataset, batch_size=4, sampler=sampler,num_workers=4, pin_memory=True, drop_last=True)step, skipped = 0, 0for epoch in range(epochs):sampler.set_epoch(epoch) # Shuffle order changes every epoch, and the split among ranks remains consistentfor batch in loader:batch = {k: v.to(device, non_blocking=True) for k, v in batch.items()}optimizer.zero_grad(set_to_none=True)loss = model(**batch).lossloss.backward() # Backward: Reduce-Scatter shards gradientsgrad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=max_norm)if not all_ranks_ok([loss, grad_norm], device):skipped += 1if rank == 0:print(f"step {step}: Non-finite value detected, skipping this step. Total skips: {skipped}")step += 1continueoptimizer.step()step += 1if rank == 0 and step % 10 == 0:print(f"step {step} loss {loss.item():.4f} grad_norm {float(grad_norm):.4f}")if step % save_every == 0:save_checkpoint(model, optimizer, step, ckpt_dir)return modeldef main():device, local_rank = setup_distributed()rank, world_size = dist.get_rank(), dist.get_world_size()ckpt_dir = "/data/ckpt"if rank == 0:os.makedirs(ckpt_dir, exist_ok=True)dist.barrier()model = build_model() # Replace with your model constructor; the model needs a layers attributedataset = build_dataset() # Replace with your dataset; sample fields must align with model forwardtrain(model, dataset, device, rank, world_size, epochs=1, ckpt_dir=ckpt_dir)dist.destroy_process_group()if __name__ == "__main__":main()
There are a few points in the code you need to confirm:
- The return type of
clip_grad_norm_may have varying support for DTensor across different versions. On the first run, printtype(grad_norm)to ensurefloat(grad_norm)executes correctly. - 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.
- The
batch_sizeinDataLoaderis 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.
- 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.
- 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.
- 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.
- 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.
- 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. - 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.
