FSDP2 Training on Two Nodes and 16 GPUs: Key Requirements and Common Errors
This article explains why successful inference does not guarantee successful training, outlines the main memory, communication, and numerical-stability challenges of large-model training, and describes how FSDP2 shards parameters, gradients, and optimizer states. It provides a two-node 16-GPU launch example, monitoring recommendations, a 400-step validation checklist, and troubleshooting guidance for common FSDP2 training errors.
A successful inference run does not mean training will also run successfully. A domestically developed full-featured GPU can complete inference deployment on the day a model is released, which shows that the operator and framework layers already have basic capability. Training also has to handle backpropagation, gradient synchronization, optimizer states, and long-run numerical stability, making it clearly harder than inference.
It is also important to distinguish two things. Successful training adaptation only means the software stack can support the model’s training workflow; it does not mean the model was pre-trained from scratch on this chip. The original compute source of a base model is usually not public. When reading technical reports, separate “can adapt to training” from “which compute was used for pre-training.”
1. Three Core Challenges in Very Large Model Training
1. Memory pressure
During training, GPU memory mainly holds four types of data: model weights, gradients, optimizer states, and activations. Taking common BF16 mixed precision with AdamW as an example, weights and gradients each take about 2 bytes per parameter. AdamW’s FP32 master weights, first-order momentum, and second-order variance together take about 12 bytes per parameter. Therefore, model state requires about 16 bytes per parameter. Activations are counted separately, and they grow with batch size, sequence length, and number of layers.
2. Communication overhead
In multi-node training, inter-node bandwidth is usually lower than intra-node bandwidth. FSDP performs parameter aggregation and gradient reduction at every step. Whether communication and computation can overlap directly affects the speedup achieved when scaling across multiple machines.
3. Numerical stability
BF16 has the same exponent bits as FP32 and a large dynamic range, so loss scaling is generally not required. FP16 has a smaller dynamic range and needs to be used with GradScaler. Regardless of the precision used, gradient norms should be monitored and gradient clipping should be configured.
Checking the Claim: Does Parameter Scale Match the 16-GPU Configuration?
At about 16 bytes per parameter, the model state for a 3-trillion-parameter model is about 48 TB. Even if all 16 GPUs participate in sharding, each GPU still has to hold about 3 TB, far exceeding current per-GPU memory. Therefore, the claim that “a model with nearly 3 trillion parameters was trained on 16 GPUs” needs its basis checked. Possible explanations include: the figure counts trainable parameters or activated parameters, only some submodules were actually trained, CPU or SSD offloading was used, or the reported parameter scale does not match the actual training target. Before citing such numbers, ask the original source for the model structure, parallel configuration, and memory data.
2. Basic Principles of FSDP2
The core idea of FSDP is to shard parameters, gradients, and optimizer states across GPUs, with each GPU storing only its own share. The table below compares several common sharding approaches.
| Comparison item | FSDP1 | FSDP2 | ZeRO-3 (DeepSpeed) |
|---|---|---|---|
| Sharding target | Multiple parameters are flattened and sharded together (FlatParameter) | Each parameter is sharded separately and represented as a DTensor | Parameters, gradients, optimizer states |
| Interface form | Wrapper class | Compositional function fully_shard |
Controlled by configuration files and the engine |
| Memory behavior | Affected by flattening strategy, with large fluctuations | Per-layer aggregation and release are more predictable | Depends on configuration and requires tuning |
An FSDP2 training step works roughly as follows. During the forward pass, the system performs All-Gather layer by layer to collect the full parameters of the current layer. After that layer’s computation finishes, if reshard_after_forward is set, the full parameters are released and only the local shard is retained. During the backward pass, the system gathers parameters again, computes gradients, and then uses Reduce-Scatter to reduce and shard gradients across GPUs. Therefore, the per-GPU memory occupied by parameters is roughly proportional to total parameter count divided by the number of GPUs, but activations are not covered by this ratio.
The following code is a training skeleton that can serve as a starting point. It uses the official PyTorch fully_shard interface. It assumes each Transformer layer of the model is stored in model.layers, and that the model forward pass returns an object containing loss. These two points need to be adjusted for the actual model.
import osimport torchimport torch.distributed as distfrom torch.distributed.fsdp import fully_shard, MixedPrecisionPolicydef init_distributed():# Use LOCAL_RANK as the device index, i.e., the GPU index within the current node.# Across nodes, RANK may exceed the number of GPUs per node; using RANK to select a device can go out of bounds.local_rank = int(os.environ["LOCAL_RANK"])rank = int(os.environ["RANK"])world_size = int(os.environ["WORLD_SIZE"])torch.cuda.set_device(local_rank)# The backend name in vendor-adapted builds may differ; refer to vendor documentation.dist.init_process_group(backend="nccl", rank=rank, world_size=world_size)return local_rank, rank, world_sizedef wrap_with_fsdp2(model):mp_policy = MixedPrecisionPolicy(param_dtype=torch.bfloat16, # Computation precision for forward and backwardreduce_dtype=torch.float32, # Use FP32 for gradient reduction for better numerical stability)# First shard each layer, then wrap the whole model so each layer can be gathered and released independently.for layer in model.layers:fully_shard(layer, mp_policy=mp_policy)fully_shard(model, mp_policy=mp_policy)return modeldef main():local_rank, rank, world_size = init_distributed()device = torch.device("cuda", local_rank)model = build_model() # User-defined; for very large models, consider building on the meta device and then loading sharded weightsmodel = wrap_with_fsdp2(model)optimizer = torch.optim.AdamW(model.parameters(), lr=1e-5, weight_decay=0.01)loader = build_dataloader(rank, world_size) # User-defined; split data by rankfor step, batch in enumerate(loader):batch = {k: v.to(device, non_blocking=True) for k, v in batch.items()}loss = model(**batch).lossloss.backward()# Returns the global gradient norm across shardsgrad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)if torch.isfinite(grad_norm):optimizer.step()optimizer.zero_grad(set_to_none=True)if rank == 0 and step % 10 == 0:print(f"step={step} loss={loss.item():.4f} grad_norm={grad_norm.item():.4f}")if __name__ == "__main__":main()
Two-Node Launch
Assume each node has 8 GPUs, for 16 GPUs in total. Node 0 has NODE_RANK 0, and node 1 has NODE_RANK 1. MASTER_ADDR should be the internal IP address of node 0, and it must be the same on both nodes.
# Node 0export MASTER_ADDR=10.0.0.1torchrun --nnodes=2 --nproc_per_node=8 --node_rank=0 \--master_addr=$MASTER_ADDR --master_port=29500 train.py# Node 1export MASTER_ADDR=10.0.0.1torchrun --nnodes=2 --nproc_per_node=8 --node_rank=1 \--master_addr=$MASTER_ADDR --master_port=29500 train.py
Before launching, confirm the following. The PyTorch versions and vendor adaptation package versions on both nodes must match. Port 29500 must be reachable between the nodes and not occupied by another process. Firewalls and security groups must allow inter-node communication. If the number of GPUs per node is not 8, update --nproc_per_node accordingly.
3. Gradient Synchronization and Numerical Monitoring
Gradient synchronization is completed automatically by the framework during backpropagation. What users need to monitor is whether the numerical values are healthy.
- Gradient norm: Record it every few steps. A sudden increase in the norm is often a signal of too high a learning rate or abnormal data.
- NaN and Inf counts: Count occurrences. When an abnormal step appears, skip the update and record the data batch for that step to make reproduction easier.
- Learning rate warmup: At the beginning of large-model training, the learning rate should rise gradually from a small value to avoid severe gradient fluctuations early on.
- Reduction precision: If numerical anomalies appear under BF16, first check whether
reduce_dtypeis FP32, then consider adjusting other configurations.
Regarding computation and communication overlap, FSDP2 tries to overlap parameter All-Gather with computation of the previous layer. Whether overlap actually happens depends on network bandwidth, layer size, and compute intensity. Confirm it with profiling tools rather than relying only on configuration items.
4. What 400 Consecutive Training Steps Show
The original report mentions that all processes on two nodes and 16 GPUs completed 400 consecutive optimizer updates. This shows that the training flow did not crash within 400 steps, which is a necessary basic check. However, it cannot alone prove training stability, nor can it show the model’s convergence quality. The original report did not provide throughput, memory, or network data, so it is not possible to judge whether performance is reasonable.
To reproduce or evaluate a similar experiment, record at least the metrics in the table below.
| Metric | Meaning | How to record |
|---|---|---|
| Per-GPU throughput (tokens/s) | Measures training efficiency | Count effective tokens and step time, excluding the first few warmup steps |
| Peak memory | Indicates whether there is headroom | Record periodically with torch.cuda.max_memory_allocated |
| Step time | Observes the share of communication and computation | Include communication time and average over multiple runs |
| Loss and gradient norm | Judges convergence trends | Record every step or every few steps |
| NaN/Inf count | Judges numerical health | Count and record abnormal steps |
| Interruption recovery | Verifies checkpoint usability | Interrupt and resume, then compare whether loss is continuous before and after recovery |
The last item is easy to overlook. In long-cycle training, node failures and job restarts are unavoidable. If checkpoints cannot be restored correctly, previous training results may be lost. It is recommended to run a complete save-and-restore test before formal training.
The original text also mentions several projects that have been implemented, including scientific foundation model training, 5D world model training, and embodied brain model training. The original text does not provide public sources, dates, or scale definitions, so this article does not rely on them. When citing such claims, use formal release materials.
5. Common Errors and Troubleshooting
Startup hangs for a long time
Check whether MASTER_ADDR is consistent on both nodes, whether the port is occupied, and whether the firewall allows traffic. Also confirm that WORLD_SIZE on both nodes matches the sum of actual GPU counts.
Device index out of bounds
In multi-node training, use LOCAL_RANK to select the device. If RANK is used to select the device, processes on node 1 will access nonexistent GPU indices.
Out of memory (OOM)
First confirm that fully_shard is called for every Transformer layer, and that the embedding layer and output head are also sharded separately. Then check whether activation checkpointing is enabled, and consider reducing batch size or sequence length. If OOM persists, re-estimate the memory usage of model states and activations.
Loss becomes NaN
First check whether learning rate warmup and gradient clipping are in effect, then inspect changes in gradient norm. If FP16 is used, confirm that GradScaler is enabled. If BF16 is used, check the reduction precision setting.
Checkpoint loading fails
Sharded state dictionaries need to be saved and loaded with the corresponding distributed checkpoint interface. The parallel configuration, GPU count, and model structure at save time and load time must match; otherwise loading will fail or produce incorrect weights.
Low throughput
Check inter-node bandwidth, whether data loading is blocking training, and whether communication and computation overlap. Profiling tools can help locate the bottleneck; do not rely on guesswork.
6. FAQ
If inference runs successfully, can training run directly?
No. Inference only requires the forward pass. Training also requires backpropagation, gradient synchronization, optimizer states, and numerical stability safeguards. The memory and communication requirements differ greatly.
How large a model can 16 GPUs train?
It depends on parameter count, precision, optimizer, activations, and sequence length. First estimate model state with the formula above, then estimate activations. If model state exceeds total memory, consider offloading or more GPUs.
What monitoring is needed for two-node training?
At minimum, monitor per-GPU throughput, peak memory, step time, loss, gradient norm, and NaN count. Container orchestration, high-speed networking, and failure restart capabilities provided by cloud platforms can help long-cycle jobs recover, but actual results depend on the specific configuration and should be based on measured data.
Conclusion
Under specific software, hardware, and operations conditions, domestically developed heterogeneous computing is expected to gradually lower the barrier to large-model training. For a specific project, it is advisable to first run a small two-node setup through all the checks listed in this article, confirm that throughput, memory, numerical behavior, and recovery capability meet expectations, and then scale up gradually.
