Trillion-Parameter Training Adaptation: FSDP2 Mechanisms and Implementation Checklist
As large model parameters scale to the trillion level, Fully Sharded Data Parallel (FSDP) has become essential for managing compute, memory, and bandwidth requirements. This article explores the core mechanisms of PyTorch's FSDP2, detailing its parameter sharding, forward/backward communication flows, and key differences from FSDP1. It further examines sharding scheduling, multimodal training considerations, fault tolerance, and checkpoint strategies. Finally, it provides a practical implementation checklist to help teams validate hardware and software stacks for large-scale training tasks.
Background: What the Report Said and What It Didn’t
After large model parameters grew from the hundred-billion to the trillion level, the demands of training on compute, GPU memory, interconnect bandwidth, and software stacks have significantly increased. A common industry practice is Data Parallelism combined with Fully Sharded Data Parallel (FSDP), which shards parameters, gradients, and optimizer states across multiple GPUs, with each GPU only retaining a portion.
According to public reports, a domestic GPU vendor announced that it completed training adaptation for an open-source 2.8-trillion-parameter model using its training and inference integrated computing cards and self-developed software stack. The report mentioned the pipeline for model loading, sharding scheduling, and gradient synchronization, but did not provide the number of GPUs, cluster topology, precision settings, framework version, or convergence curves. Therefore, this article can only explain the scope of the adaptation as reported; it cannot be inferred that trillion-parameter models can already be stably and fully trained on domestic computing power.
The term “adaptation” also needs to be clearly scoped. It might mean completing a single forward and backward pass, completing a short fine-tuning session, or completing a full multi-week pre-training. The engineering difficulty of these three varies greatly, so teams should confirm exactly which one is being referred to before citing.
FSDP2’s Sharding and Communication Flow
FSDP2 is PyTorch’s implementation of fully sharded data parallelism. Its core principle is on-demand parameter aggregation and immediate release upon use. Understanding this is key to grasping the changes in memory and communication.
How Parameters Are Sharded
FSDP2 shards parameters on a per-module basis. Each parameter is sliced into several parts along the data parallel dimension of the DeviceMesh, and each GPU only stores its own shard. FSDP2 is implemented based on DTensor, and the sharded state is directly reflected in the tensor representation of the parameters, making it easier to combine with other parallel strategies like Tensor Parallelism.
Forward: On-Demand Parameter Aggregation
When entering the forward computation of a module, the system first performs an all-gather on that module’s parameters to temporarily reconstruct the full parameters. After computation, if reshard_after_forward=True is set, the full parameters are released, leaving only the shards. This ensures that only a few layers’ full parameters are kept in memory at any given moment.
Backward: Re-Aggregate, Then Reduce Gradients
During backpropagation through a module, if the full parameters were released during the forward pass, the system needs to perform another all-gather to reconstruct the full parameters for gradient computation. Once the gradients are calculated, the system performs a reduce-scatter, summing the gradients across GPUs and scattering them back into sharded form, with each GPU retaining only the portion of the gradient it is responsible for. Once done, the full parameters and intermediate gradients are released, and the optimizer only updates the local shard.
The trade-off here is straightforward. reshard_after_forward=True saves memory but requires an extra all-gather during the backward pass. Setting it to False eliminates one communication step, at the cost of keeping the full parameters in memory after the forward pass. The framework handles root modules specially, so refer to the documentation of your specific version for default values.
Differences Between FSDP1 and FSDP2
FSDP1 wraps modules using FullyShardedDataParallel, internally combining multiple parameters into a single FlatParameter before sharding. This approach is relatively limited in terms of parameter combination and mixed precision control. FSDP2 uses the fully_shard function to shard by parameter, with configuration specified via DeviceMesh and MixedPrecisionPolicy. Because the parameter names and behaviors differ between the two, you cannot simply swap them out during migration; you must verify each item individually.
Code Implementation and Parameter Explanation
The code below demonstrates a typical FSDP2 implementation. Refer to the official PyTorch documentation for version requirements, as a newer 2.x version is needed to provide a stable torch.distributed.fsdp.fully_shard interface.
import torchfrom torch.distributed.device_mesh import init_device_meshfrom torch.distributed.fsdp import fully_shard, MixedPrecisionPolicy# 1D data parallel mesh, world_size is the total number of processesmesh = init_device_mesh("cuda", (world_size,))# Use bf16 for compute and forward params, fp32 for gradient reduction to reduce numerical error accumulationmp_policy = MixedPrecisionPolicy(param_dtype=torch.bfloat16,reduce_dtype=torch.float32,)# Shard each Transformer block individually so the full params of that block can be released after forwardfor block in model.layers:fully_shard(block, mesh=mesh, mp_policy=mp_policy, reshard_after_forward=True)# Apply sharding to the root module to take over params not in layers, like embedding and lm_headfully_shard(model, mesh=mesh, mp_policy=mp_policy)
There are three key points to note in this code. First, the sharding granularity must align with the model structure. It is typically done at the Transformer block level; a granularity that is too coarse will cause memory peaks to be too high, while one that is too fine will increase communication overhead. Second, the final call to model is not redundant sharding; it establishes a sharding unit for remaining parameters. If omitted, these parameters will remain unsharded, resulting in higher memory usage than expected. Third, the mixed precision strategy must be viewed in tandem with the optimizer’s master weights. Master weights are usually kept in fp32, while computation uses bf16; the synchronization between the two consumes memory and bandwidth and must be factored into the memory budget.
Sharding Scheduling: Topology Determines Parallel Combinations
At a scale of 2.8 trillion parameters, using data parallelism alone is usually insufficient. Common combinations include Data Parallelism (DP), Tensor Parallelism (TP), Pipeline Parallelism (PP), and Expert Parallelism (EP, applicable to MoE architectures).
The sharding strategy should match the hardware topology. Intra-node GPUs have high bandwidth and are suitable for Tensor Parallelism, which requires frequent communication. Cross-node bandwidth is lower, making it more suitable for Pipeline Parallelism or Data Parallelism, as their communication volume is relatively small or can be overlapped with computation.
| Parallel Method | Communication Pattern | Communication Frequency | Suggested Placement |
|---|---|---|---|
| Tensor Parallelism | all-reduce or all-gather per layer forward/backward | High | Intra-node high-speed interconnect |
| Data Parallelism (FSDP) | Parameter all-gather, gradient reduce-scatter | Medium | Cross-node, needs to overlap with compute |
| Pipeline Parallelism | Inter-layer activation point-to-point transfer | Low to Medium | Cross-node |
| Expert Parallelism | Token routing dispatch and aggregation | Varies with routing | Depends on expert count and bandwidth |
Communication volume estimates must clarify their methodology. Is it calculated per step or for the entire training cycle? Does it include the second all-gather in the backward pass? If these metrics are not standardized, numbers from two different teams cannot be directly compared.
Multimodal Training Data and Loss
Multimodal training mixes data like text and images, bringing three specific challenges.
First, heterogeneous encoders handle parameters differently. Vision encoders and language backbones usually use different learning rates, and sometimes certain layers need to be frozen. Learning rate groups should be written into the configuration file, and the gradient norms for each group should be logged separately to facilitate troubleshooting.
Second, sample length varies greatly. The number of tokens after image encoding may far exceed that of short text. Packing them directly by batch will cause massive padding waste. A common practice is bucketed sampling by length, with dynamic packing within the same bucket. Before launch, the average effective token ratio for each bucket should be measured to determine if the packing strategy is effective.
Third, the weights of multi-task losses need to be determined experimentally. For example, if the ratio of image-text alignment loss to text generation loss is unbalanced, one will overpower the other. You can first run small-scale experiments to scan several sets of weights, record the validation metrics for each task, and then determine the ratio for large-scale training.
Fault Tolerance and Checkpoints
In long-term training, hardware failures, numerical overflow, and sudden loss spikes are inevitable. The design of the checkpoint mechanism directly determines whether training can recover quickly after a failure.
Asynchronous checkpointing can reduce training interruption time, but it carries consistency risks. If training advances while saving is in progress, the saved content might mix parameter and optimizer states from different steps. Therefore, the step number should be recorded during saving, and the metadata of each shard should be verified for consistency.
Rollback mechanisms require periodic rehearsal. Randomly select a historical checkpoint, restore it, and compare the loss and output of the first few steps to confirm consistency with the original training trajectory. A checkpoint that is only written and never read cannot prove to be usable.
NaN or Inf detection should have clear thresholds. For example, if NaN appears for several consecutive steps, or if the grad norm exceeds a certain multiple of the historical moving average, the system should automatically roll back to the most recent healthy weights and log the trigger reason. Thresholds must be set based on the historical curves of the specific task, not copied from other projects.
Pre-Launch Checklist
The following items can serve as a starting point for team self-assessment. The specific values provided are just examples and should be calibrated according to your own model and cluster.
- Operator Compatibility Matrix: List all operators used by the model, record the forward and backward results on the target hardware for each, compare the relative error with the reference implementation, and specify the dtype used.
- Single-Node Multi-GPU Convergence Threshold: Run a full training pipeline with a small model on a single node with multiple GPUs, record the loss curve for the first few thousand steps, and compare it with a reference GPU or reference implementation. The threshold should be a specific number (e.g., relative deviation does not exceed a preset value) rather than just “basically consistent.”
- Communication Topology Verification: Use nccl-tests or similar tools to measure intra-node and cross-node bandwidth and latency, and compare them with theoretical values. Use a profiler to confirm whether communication and computation are effectively overlapped, and record the proportion of communication time per step.
- Memory Budget: Separately record the forward peak, backward peak, and optimizer state memory usage to ensure the
reshard_after_forwardsetting is within budget. - Checkpoint Recovery SLA: Define the save interval, maximum save duration, and maximum recovery duration, and conduct a recovery rehearsal at least once a month.
- Monitoring Items: At a minimum, monitor loss, grad norm, NaN/Inf counts, step duration, communication time proportion, and memory peak. Each item should have an alert threshold and a designated handler when triggered.
- Rollback Strategy: Clearly state the trigger conditions, the target checkpoint for rollback, and the verification steps after recovery.
Conclusion: Verifiable Conclusions Are More Valuable Than Claims
The aforementioned report indicates that domestic computing software stacks have the capability to support certain stages of ultra-large-scale training under specific models and configurations. However, there is still a gap before achieving universal, stable full-scale training. To make a definitive judgment, public data such as GPU count, topology, precision, framework version, training steps, and convergence curves are needed—none of which are currently complete.
For developers, the most useful approach is to run through the checklist provided above. Validate operators, communication, and checkpoints using small-scale experiments on your own hardware, and then gradually scale up to the full cluster. Only by leaving reproducible records at each step can you determine whether a hardware-software combination is truly suitable for your training tasks.
