FSDP2 Multi-Node, Multi-GPU Training for Large Models: Sharding, Gradient Sync, and Numerical Stability
A practical guide to multi-node, multi-GPU training of large models with PyTorch FSDP2. It covers memory estimation and sharded loading, diagnosing gradient synchronization and throughput, a training script template with non-finite loss handling, launch commands, and common error troubleshooting. The template and parameters are starting points that need validation on your own model, data, and cluster.
Key Takeaways
Training large models across multiple machines comes down to three problems: keeping memory within limits while loading sharded weights, keeping gradient synchronization from slowing down training, and keeping values finite during long runs. This guide is organized around these three problems. It closes with launch commands, a troubleshooting table, and a pre-launch checklist.
The training script in this article is a template, not production-tested code. The author ran the workflow only in a short 200-step test and has no data on long-term stability. The version recommendations, parameters, thresholds, and pass/fail criteria are starting points. Validate them on your own model, data, and cluster.
When to Use FSDP2
FSDP2 fits these cases: the model parameters plus optimizer states do not fit on a single GPU; you need to scale training across multiple machines; and you want to shard parameters, gradients, and optimizer states across GPUs with relatively few code changes.
Consider other options in these cases. If the full training state fits on a single machine, DDP is simpler and easier to debug. If the model needs tensor or pipeline parallelism, the design must account for FSDP2 as well. If your team already has a mature DeepSpeed ZeRO configuration, the migration cost may outweigh the benefits.
FSDP2 is the second generation of Fully Sharded Data Parallel. Its public API is torch.distributed.fsdp.fully_shard. This article refers to it as FSDP2. The older FSDP1 wraps models with FullyShardedDataParallel. The two interfaces differ, so do not mix them.
1. Environment and Version Requirements
| Component | Recommended Version | Notes |
|---|---|---|
| PyTorch | 2.6 or later | fully_shard entered the public API in this version. Earlier versions may have a different interface. |
| CUDA | Same as the official PyTorch prebuilt binary | A mismatch between driver and runtime versions often causes NCCL errors. |
| NCCL | Use the version bundled with PyTorch | Do not replace it separately unless you have a specific need. |
| Python | Follow the supported list for your PyTorch version | Do not assume a compatibility range. |
| Node network | InfiniBand or RoCE preferred | On standard Ethernet, gradient synchronization can easily become a bottleneck. |
All nodes should use the same image, driver, and dependency versions. When versions differ, the most common symptom is some nodes hanging for a long time after startup.
Record the hardware details so you can reproduce and compare runs later: the number of nodes, the GPUs per node and their model, memory per GPU, bandwidth between nodes, and the mapping between GPUs and network cards. For example, “2 machines, each with 8 80GB GPUs, connected by InfiniBand” is a usable record. This describes the environment only and does not represent any performance result.
2. Sharded Loading and Memory Estimation
With mixed precision and AdamW, each parameter takes about 16 bytes. This covers a bf16 parameter copy, fp32 gradients, fp32 master weights, and two Adam state tensors. This is a rough estimate. The actual value depends on the implementation and precision settings.
For a 7B-parameter model, 16 bytes per parameter gives about 112 GB of training state. Sharding across 8 GPUs leaves about 14 GB per GPU. This figure excludes activations, communication buffers, and memory fragmentation. Activation memory depends heavily on sequence length and batch size, and it is often the main cause of out-of-memory (OOM) errors.
Shard the model layer by layer with the following code. The code assumes model.layers is a ModuleList. Modify it to match your model structure.
import torchfrom torch.distributed.fsdp import fully_shard, MixedPrecisionPolicydef apply_fsdp2(model: torch.nn.Module) -> torch.nn.Module:mp_policy = MixedPrecisionPolicy(param_dtype=torch.bfloat16,reduce_dtype=torch.float32,)# Shard layer by layer; gather each layer's parameters on demand during forwardfor block in model.layers:fully_shard(block, mp_policy=mp_policy, reshard_after_forward=True)# Shard the outermost module once more to cover the embedding, output head, and other remaining parametersfully_shard(model, mp_policy=mp_policy, reshard_after_forward=True)return model
reshard_after_forward=True reduces memory use after the forward pass. The cost is an extra parameter all-gather during the backward pass, which increases communication. If you have enough memory, set it to False and measure the speed difference.
For large models, build the model on the meta device first, then shard it and allocate memory. This avoids materializing the full model on a single GPU:
with torch.device("meta"):model = build_model()model = apply_fsdp2(model)model.to_empty(device="cuda")# Load weights from a checkpoint here, or re-initialize them according to your init logic# Non-persistent buffers (such as the rotary position embedding cache) must be recomputed
Create the optimizer after sharding. If you create it first, it may hold references to the parameters from before sharding, and its states cannot be split by parameter.
3. Gradient Synchronization and Throughput Troubleshooting
FSDP2 uses all-gather before the forward pass to assemble the current layer’s parameters. During the backward pass, it uses reduce-scatter to shard gradients across GPUs. Whether communication overlaps with computation determines the speed of multi-node training.
Check these areas when troubleshooting:
- Data loading slowing training. Check the
num_workersandpin_memorysettings, and measure how long each step waits for data before it starts. - Cross-node bandwidth. Measure bandwidth between nodes with
all_reduce_perffrom nccl-tests, for example:all_reduce_perf -b 8 -e 1G -f 2 -g 8. If measured bandwidth is clearly below the NIC’s rated speed, check NIC bonding and network topology first. - Micro batch size per GPU that is too small. A larger micro batch lets computation cover communication, but first confirm you have spare memory.
- Gradient synchronization on every micro step during gradient accumulation. Reducing synchronization on non-final steps cuts communication. For the exact interface, see the documentation for your PyTorch version.
Throughput numbers need a stated measurement method to be comparable. Use these conventions:
- Express throughput in tokens/s. Compute it as the number of tokens in the global batch divided by the step time.
- Skip the first 20 warm-up steps, then record at least 100 steps and report the median and P95.
- Call
torch.cuda.synchronize()before and after each timing measurement. CUDA operations are asynchronous. Without synchronization, you measure the time to submit work, not the time to finish it.
4. Training Script Template
The script below shows the full workflow: sharding, data partitioning, skipping non-finite losses, gradient clipping, and logging. Replace build_model and build_dataset with your own implementations. The script assumes the model’s output includes loss.
```python
import os
import torch
import torch.distributed as dist
from torch.utils.data import DataLoader, DistributedSampler
from torch.distribut
