FSDP2 Training Stability Validation and Recovery Guide on Dual-Node 16-GPU Setups

    This guide provides a comprehensive approach to validating and recovering FSDP2 (Fully Sharded Data Parallel 2) training on a dual-node 16-GPU configuration. It covers the boundary between training and inference adaptation, version and interface matrices, setting up a multimodal training pipeline, network connectivity checks, gradient synchronization, stability validation checklists, and troubleshooting recovery procedures. Readers will learn how to ensure robust large model training and seamless recovery from interruptions.

    1. Clarifying the Boundary Between Training and Inference Adaptation

    Successful adaptation does not mean that the base pre-training has been completed on the target chip. Many technical reports comparing multiple chips only cover inference operators without specifying the computing power source for base pre-training. To determine if a computing architecture can handle training tasks, check whether it covers the complete loop: data preprocessing, model loading, forward computation, backward propagation, optimizer update, and state saving/restoring. A loop missing any part cannot be considered full-pipeline training.

    Before selection, answer three questions. First, does the operator library cover the backward operators required for training? Second, can the distributed communication library support multi-node multi-GPU topologies? Third, can the training state be stably saved and restored? These three points determine the difficulty of subsequent work and whether the code skeleton in this article can be directly used on the target platform.

    The table below is the closed-loop checklist. Each step should be passed in small-scale tests before entering the dual-node experiment.

    Phase What to Confirm Verification Method
    Data Preprocessing Whether samples can be split by rank, and whether sampling results are reproducible under the same seed Run twice and print the first few sample indices to compare consistency
    Model Loading Whether weight shapes match exactly, with no missing or unexpected parameters Check missing_keys and unexpected_keys returned by load_state_dict
    Forward Computation Whether all module operators are supported on the target platform Run one step to confirm there are no unsupported operators or errors/warnings falling back to CPU
    Backward Propagation Whether all trainable parameters receive gradients Iterate model.parameters(), check that grad is not None and is finite
    Optimizer Update Whether parameters change after the update and remain finite Record the difference in parameter norm before and after the update
    Save and Restore Whether the state can be completely written and read back Interrupt and resume, compare whether the first few steps of loss are continuous with before the interruption

    2. Version and Interface Matrix

    The import path for FSDP2 changes with the PyTorch version. An incorrect path will directly cause startup failure, so confirm the version before starting.

    Environment Import Path Description
    PyTorch 2.6 and above fully_shard in torch.distributed.fsdp The code skeleton in this article uses this syntax
    PyTorch 2.4, 2.5 torch.distributed._composable.fsdp Interface location and parameter names may differ; modify according to the official documentation of that version
    Specific hardware platforms Distributed backend and PyTorch adaptation version provided by the vendor Communication backend names, environment variables, and version numbers are subject to vendor documentation

    Run python -c "import torch; print(torch.__version__)" in the target environment to confirm the version before selecting the corresponding interface. Do not mix two generations of APIs in the same project. The communication backend on specific hardware platforms might not be called nccl; the backend="nccl" in the example and related NCCL environment variables need to be replaced with the corresponding items in the vendor documentation.

    3. Setting Up the FSDP2 Multimodal Training Pipeline

    In large model training, a single GPU usually cannot hold the full parameters, gradients, and optimizer states. Fully Sharded Data Parallel (FSDP) shards these three types of states across the GPUs in the data parallel group, thereby reducing single-GPU memory usage. FSDP2 is implemented based on the composable interface, and sharding is performed at the module level. Compared to the earlier FSDP1 wrapping method, it is easier to apply differentiated configurations to different sub-modules.

    Multimodal models usually consist of a vision encoder, projection layer, and language model, with significant differences in parameter count and computation characteristics across parts. A common practice is to call the shard interface separately for each Transformer block, and finally call it once on the root module so that parameters not covered by child blocks are also sharded. The optimizer must be created after sharding because it saves the sharded parameters.

    The code skeleton below has three key designs. First, the dataset uses DistributedSampler to ensure each rank reads non-overlapping samples. Second, DTensor conversion is executed on all ranks. full_tensor() internally triggers collective communication; if only rank 0 calls it, other ranks may wait indefinitely, eventually causing a deadlock. Third, the gradient norm is consistent across all ranks after reduction and can be used as a common stopping criterion.

    1. # Environment: PyTorch >= 2.6, NCCL backend (replace with vendor backend for specific hardware platforms), launch with torchrun
    2. import json
    3. import math
    4. import os
    5. from datetime import timedelta
    6. import torch
    7. import torch.distributed as dist
    8. import torch.distributed.checkpoint as dcp
    9. from torch.distributed.checkpoint.state_dict import get_state_dict, set_state_dict
    10. from torch.distributed.device_mesh import init_device_mesh
    11. from torch.distributed.fsdp import fully_shard, MixedPrecisionPolicy
    12. from torch.utils.data import DataLoader, DistributedSampler
    13. CKPT_DIR = "/shared/ckpt/run01" # Must be a shared path readable and writable by all nodes
    14. PER_GPU_BS = 2 # Micro batch per GPU, adjust based on memory
    15. MAX_STEPS = 2000
    16. SAVE_EVERY = 500
    17. LOG_EVERY = 10
    18. SEED = 42
    19. def to_scalar(x):
    20. # Must be called on all ranks, DTensor.full_tensor() includes collective communication
    21. if hasattr(x, "full_tensor"):
    22. x = x.full_tensor()
    23. return x.item()
    24. def infinite_batches(loader, sampler, start_epoch):
    25. epoch = start_epoch
    26. while True:
    27. sampler.set_epoch(epoch) # Use a different shuffle order for each epoch
    28. for batch in loader:
    29. yield epoch, batch
    30. epoch += 1
    31. def save_checkpoint(model, optimizer, step, epoch):
    32. model_sd, optim_sd = get_state_dict(model, optimizer)
    33. path = os.path.join(CKPT_DIR, f"step_{step}")
    34. dcp.save({"model": model_sd, "optim": optim_sd}, checkpoint_id=path)
    35. dist.barrier() # Wait for all ranks to finish writing their shards
    36. if dist.get_rank() == 0:
    37. with open(os.path.join(path, "meta.json"), "w") as f:
    38. json.dump({"step": step, "epoch": epoch}, f)
    39. with open(os.path.join(CKPT_DIR, "latest"), "w") as f:
    40. f.write(f"step_{step}") # Write latest last to ensure it only points to a complete checkpoint
    41. dist.barrier()
    42. def load_checkpoint(model, optimizer):
    43. latest = os.path.join(CKPT_DIR, "latest")
    44. if not os.path.exists(latest):
    45. return 0, 0
    46. with open(latest) as f:
    47. path = os.path.join(CKPT_DIR, f.read().strip())
    48. with open(os.path.join(path, "meta.json")) as f:
    49. meta = json.load(f)
    50. model_sd, optim_sd = get_state_dict(model, optimizer)
    51. state = {"model": model_sd, "optim": optim_sd}
    52. dcp.load(state, checkpoint_id=path)
    53. set_state_dict(model, optimizer,
    54. model_state_dict=state["model"],
    55. optim_state_dict=state["optim"])
    56. return meta["step"], meta["epoch"]
    57. def main():
    58. dist.init_process_group(backend="nccl", timeout=timedelta(minutes=30))
    59. local_rank = int(os.environ["LOCAL_RANK"])
    60. torch.cuda.set_device(local_rank)
    61. rank = dist.get_rank()
    62. world_size = dist.get_world_size()
    63. mesh = init_device_mesh("cuda", (world_size,))
    64. mp_policy = MixedPrecisionPolicy(
    65. param_dtype=torch.bfloat16,
    66. reduce_dtype=torch.float32, # Use FP32 for gradient reduction, keep this setting when troubleshooting
    67. )
    68. model = build_multimodal_model().cuda() # User-defined, returns FP32 model
    69. for block in model.transformer_blocks:
    70. fully_shard(block, mesh=mesh, mp_policy=mp_policy, reshard_after_forward=True)
    71. fully_shard(model, mesh=mesh, mp_policy=mp_policy)
    72. optimizer = torch.optim.AdamW(
    73. model.parameters(), lr=1e-4, betas=(0.9, 0.95), weight_decay=0.1
    74. )
    75. dataset = build_dataset() # User-defined
    76. sampler = DistributedSampler(
    77. dataset, num_replicas=world_size, rank=rank,
    78. shuffle=True, seed=SEED, drop_last=True,
    79. )
    80. loader = DataLoader(
    81. dataset, batch_size=PER_GPU_BS, sampler=sampler,
    82. num_workers=4, pin_memory=True, drop_last=True,
    83. )
    84. start_step, start_epoch = load_checkpoint(model, optimizer)
    85. batches = infinite_batches(loader, sampler, start_epoch)
    86. for step in range(start_step, MAX_STEPS):
    87. epoch, batch = next(batches)
    88. inputs = batch["inputs"].cuda(non_blocking=True)
    89. labels = batch["labels"].cuda(non_blocking=True)
    90. loss = model(inputs, labels=labels)
    91. loss.backward()
    92. grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
    93. optimizer.step()
    94. optimizer.zero_grad(set_to_none=True)
    95. gn = to_scalar(grad_norm) # All ranks execute this every step
    96. if not math.isfinite(gn):
    97. # The reduced gradient norm is consistent across ranks, all ranks will exit simultaneously to avoid a single rank hanging
    98. raise RuntimeError(f"step={step} grad_norm is not finite, stopping training")
    99. if rank == 0 and step % LOG_EVERY == 0:
    100. print(f"step={step} loss={loss.item():.4f} grad_norm={gn:.4f}")
    101. if (step + 1) % SAVE_EVERY == 0:
    102. save_checkpoint(model, optimizer, step + 1, epoch)
    103. dist.barrier()
    104. dist.destroy_process_group()
    105. if __name__ == "__main__":
    106. main()

    Two points in the code require special attention. First, the AdamW state dictionary is only generated after the first optimizer.step(). When starting from scratch, the restore logic is not triggered, so the problem is hidden. However, in some versions, loading a checkpoint for an optimizer that has not yet generated states may cause an error. Before the first use, verify the full process of “save, interrupt, restore, continue training” on a small model. Second, data recovery is approximate. The example only saves the epoch, and upon recovery, it will iterate from the beginning of that epoch, meaning some samples will be repeated. If strict continuation is required, the data reading position should be additionally recorded.

    4. Dual-Node 16-GPU Launch and Connectivity Check

    Dual-node 16-GPU refers to two nodes, each with 8 GPUs. Before launching, confirm that the two machines can access the master node’s port and use the same code and data path.

    On the master node, first confirm the port is not occupied:

    1. ss -lnt | grep 29500 # No output means the port is free
    2. ip -br addr # Confirm the network interface name and IP used for training

    On the worker node, check if the master node is reachable:

    1. ping -c 3 $MASTER_ADDR
    2. nc -zv $MASTER_ADDR 29500 # This port will only be in a listening state after the master node's training process starts

    Execute the launch command once on both nodes, with node ranks 0 and 1 respectively:

    1. torchrun --nnodes=2 --nproc_per_node=8 --node_rank=$NODE_RANK \
    2. --master_addr=$MASTER_ADDR --master_port=29500 train.py

    Before launching, you can set NCCL_DEBUG=INFO and specify the training network interface via NCCL_SOCKET_IFNAME. If port 29500 is occupied, both nodes must simultaneously change to the same new port. The names and functions of environment variables like TORCH_NCCL_ASYNC_ERROR_HANDLING change across versions, so refer to the documentation for the version you are using.

    5. Gradient Synchronization and Communication

    FSDP2 communication is divided into two categories. Before the forward and backward computation of a block, the framework collects the full parameters of that block via All-Gather. After the block computation, if reshard_after_forward=True is set, the full parameters are released to save memory, and must be collected again during backward computation. After backward computation, gradients are reduced via Reduce-Scatter and split back to each GPU’s shard.

    The framework prefetches the next block’s parameters while computing the current block, provided that communication and computation run on different CUDA streams and network bandwidth is sufficient. Cross-node communication bandwidth is usually the bottleneck, so confirm that NCCL actually uses the RDMA network. After setting NCCL_DEBUG=INFO, you can check the transport type in the logs. If the logs show Socket transport, meaning it fell back to TCP, check the network interface configuration and network plugins. The log format for specific hardware platforms differs; refer to the vendor’s troubleshooting guide.

    Gradient reduction precision is a trade-off. When reduce_dtype is set to FP32, the reduction result is more stable, but the communication data volume is about twice that of BF16 reduction.

    The communication volume can be roughly estimated using the following formula. Let the model parameter count be Ψ and the data parallel group size be N. In a single step, the total data volume collected by each rank for parameters in forward and backward is approximately 2×(N-1)/N×Ψ×parameter_bytes. During gradient reduction, the data volume sent by each rank is approximately (N-1)/N×Ψ×reduce_bytes. BF16 parameters take 2 bytes, and FP32 reduction takes 4 bytes. These are theoretical values, not accounting for communication and computation overlap, protocol overhead, and topology differences; actual values must be measured. When measuring, fix the model, batch size, and sequence length, run several steps for both reduction precisions, and compare the median step time and communication time in the stable phase.

    If gradient anomalies occur during training, first switch reduce_dtype to FP32 for troubleshooting. If the anomaly disappears, reduction precision is one of the triggers, and you can then decide the final configuration based on the step time increase. If the anomaly persists after switching, prioritize checking the data, learning rate, and model initialization.

    6. Dual-Node 16-GPU Stability Validation Checklist

    Before testing, fill out the table below. The results are only valid under the conditions listed.

    Item Description Current Value
    Model Size Parameter count and multimodal component composition Filled by tester
    Global Batch Size Micro batch per GPU multiplied by data parallel group size, then by gradient accumulation steps Filled by tester
    Sequence Length Maximum number of tokens in training samples Filled by tester
    Precision Configuration Parameter computation precision and reduction precision Filled by tester
    Nodes and GPUs Number of nodes, number of accelerator GPUs per node Filled by tester
    Network Type Inter-node interconnect and network interface model Filled by tester
    Communication Library Version NCCL or vendor communication library version Filled by tester
    PyTorch Version Framework version number Filled by tester
    Driver and Firmware Version Accelerator driver and firmware versions Filled by tester
    Random Seed Seed value for reproduction Filled by tester

    Perform validation according to the following steps, moving to the next step only after the previous one passes.

    Step Operation Pass Criteria
    1. Single-node run Run 100 steps on a single node with 8 GPUs Both loss and grad_norm are finite, no errors
    2. Connectivity check Check ports and network interfaces per Section 4 Port reachable, device count consistent across nodes
    3. Dual-node short run Run about 500 steps No timeout, all ranks exit normally
    4. Communication check Check transport type in NCCL logs Cross-node communication uses RDMA, no Socket fallback
    5. Long run Run target number of steps Metrics within thresholds, no interruptions
    6. Interruption recovery Manually interrupt at an intermediate step and restart Loss after recovery is continuous with before interruption
    7. Retest Repeat steps 3 to 6 Results are reproducible, deviation within tester-defined range

    The judgment method for each metric is as follows. Thresholds are determined by the tester based on the single-node baseline; specific values are not given in this article.

    Metric Judgment Method Failure Criteria
    loss Finite value, trend consistent with single-node baseline NaN or Inf occurs, or significantly higher than baseline
    grad_norm Finite value, fluctuation within baseline range NaN or Inf occurs, or continuous large jumps
    step time Median in the stable phase compared to single-node scaled value Fluctuation exceeds threshold
    Peak Memory Peak per GPU is below the upper limit with margin Close to the limit, or one GPU significantly higher than others
    Process Exit All ranks exit with code 0 Any rank exits non-zero or times out
    Logs No NCCL timeout and transport fallback warnings Timeout or Socket fallback occurs

    The output of each node should be saved for post-analysis. Example command:

    1. torchrun --nnodes=2 --nproc_per_node=8 --node_rank=$NODE_RANK \
    2. --master_addr=$MASTER_ADDR --master_port=29500 train.py 2>&1 | tee logs/node${NODE_RANK}.log

    7. Troubleshooting and Recovery After Training Interruption

    When troubleshooting, first find the rank that reported the error first. In multi-rank training, after one rank fails, others often report errors due to collective communication timeouts. The earliest exception in the logs is usually the cause; subsequent timeout messages are often just consequences.

    The suggested troubleshooting order is as follows:

    1. Memory issues: Search for “out of memory”. If found, reduce the micro batch per GPU or enable activation recomputation.
    2. Network issues: Check NCCL timeout records, inspect network interface status, and re-run the connectivity check from Section 4.
    3. Data issues: Check for data reading exceptions, empty batches, and whether NaN exists in inputs.
    4. Numerical issues: Search for records of non-finite grad_norm, review the loss changes in the last few steps before the interruption.
    5. Storage issues: Checkpoint write failures usually manifest as errors during saving or incomplete files. Confirm the free space of the shared storage.

    Recover training according to the following steps:

    1. Read CKPT_DIR/latest to confirm that the directory it points to exists and contains meta.json.
    2. Ensure all nodes use the same shared path and consistent code versions.
    3. Restart using the launch command from Section 4. The code will automatically load the checkpoint pointed to by latest.
    4. Observe the loss and grad_norm for the first 10 steps after recovery and compare them with the last few steps before the interruption. If there is a significant jump, stop training and check if the data recovery position and optimizer state are loaded correctly.
    5. Confirm that the recovered step matches the record in meta.json.

    If the checkpoint pointed to by latest is incomplete, manually roll back to an earlier step directory. Do not delete old checkpoints until successful recovery is confirmed, so they can be used for rollback.

    8. Conclusion and Retest Conditions

    This article does not provide performance numbers. The code skeleton needs to be completed with the reader’s own model and data before it can run. The checkpoints and recovery processes in the text also need to be actually executed in the reader’s environment. Only after completing the closed-loop check, dual-node short run, and interruption recovery test can it be determined whether the conclusions hold in that environment.

    The conclusions only apply to the combination of conditions during testing. A change in any of the following requires retesting: model structure or parameter count, batch size and sequence length, number of nodes or GPUs per node, network topology, driver, PyTorch or communication library version, and reduction precision configuration.