Adapting FSDP2 Training on Domestic GPUs: An Engineering Guide
This guide covers the engineering practices for adapting FSDP2 (Fully Sharded Data Parallel 2) training to domestic GPU platforms. It explains the differences between FSDP1 and FSDP2, the hardware and software versions that must be recorded for reproducibility, model loading, sharding granularity selection, gradient synchronization, mixed precision configuration, checkpointing, pre-launch checklists, performance measurement standards, and risk mitigation with rollback procedures.
1. Background and Scope
Open-source large models have reached the trillion-parameter scale. A model with 2.8 trillion parameters, stored in BF16 alone, requires roughly 5.6 TB (2.8 trillion × 2 bytes) for weights. This does not include gradients and optimizer states. Single-card memory is far from sufficient, so training must rely on parameter sharding, parallelism strategies, and offloading techniques.
Large-scale training typically faces three categories of problems:
- Insufficient memory: weights, gradients, and optimizer states together far exceed the capacity of a single card.
- High communication overhead: as clusters grow, gradient synchronization traffic increases, and network topology plus communication protocols directly affect scaling efficiency.
- High framework adaptation cost: mainstream distributed interfaces are usually optimized for a specific GPU ecosystem. When migrating to other platforms, operators, collective communication libraries, and memory management typically need re-validation.
This article is based on an engineering effort to adapt FSDP2 training on a domestic GPU platform. Specific platform models and versions are recorded here in a reproducible format, and readers should fill in values based on their own environments. This article does not provide ready-to-use performance conclusions; all performance data must be re-measured under your specific configuration.
The main difference between FSDP2 and FSDP1 is the sharding unit. FSDP1 flattens multiple parameters into a single FlatParameter, and sharding happens on that flat parameter. FSDP2 shards each individual parameter, represented as a DTensor, split along dimension 0 by default. FSDP2 therefore preserves the original parameter structure, making it easier to control mixed precision, checkpointing, and frozen parameters on a per-module basis. The trade-off is stronger dependence on framework versions and custom operators, so before migrating you must confirm the status of FSDP2 interfaces in your PyTorch version.
2. Hardware/Software Versions and Reproducibility
Fix versions first, then compare performance. The table below lists the fields that must be recorded when reproducing or evaluating this kind of adaptation. Missing fields make results incomparable.
| Field | Description | Example Format | Affected Metrics |
|---|---|---|---|
| Accelerator model and memory | Per-card memory determines the upper limit of shard group size | Model, per-card memory in GB | Peak memory, maximum unsharded block size |
| Interconnect and node count | Large bandwidth difference between intra-node and inter-node | Nodes × cards per node, interconnect type and bandwidth | AllGather latency, scaling efficiency |
| Driver and runtime versions | Affect operator and memory management behavior | Driver, runtime, compiler version numbers | Stability, per-card compute |
| Collective communication library version and topology | Determines communication algorithms and topology awareness | Version number, topology config file | Communication time share |
| Deep learning framework and FSDP2 dependencies | Determines available sharding interfaces and mixed precision strategies | PyTorch version, adapter plugin version | Interface availability, numerical consistency |
| Model and training configuration | Determines compute and memory requirements | Layers, hidden size, sequence length, global batch, mixed precision config | Throughput, MFU |
Collective communication primitives and operator fusion are prerequisites for the adaptation to work. If the platform lacks the corresponding AllGather and ReduceScatter implementations, or lacks fused operators for the Transformer architecture, the sharding strategy cannot run. Before going live, validate the correctness of these primitives with small single-machine test cases, then move to multi-node training.
3. Sharding, Synchronization, Mixed Precision, and Checkpoint Recovery
3.1 Model Loading
Weight files are too large to be read entirely into host memory before distribution. Each process reads only the shard it is responsible for, using asynchronous I/O to overlap disk reads with computation. Before loading, save the sharding metadata, including world size, device mesh shape, and each parameter’s name, shape, sharding dimension, and dtype. During recovery, compare against this metadata and reject loading if anything mismatches.
Peak host memory must be estimated separately. If each process simultaneously holds a read buffer and a shard copy, the peak is roughly the per-process shard size multiplied by the number of concurrent reads. For multimodal models, also check whether the sharding placements of the vision encoder, text embedding layer, and projection layer are consistent. If they are inconsistent, forward computation produces cross-shard indexing errors that usually do not raise exceptions—the only symptom is abnormal loss.
3.2 Choosing Sharding Granularity
Group granularity determines communication frequency and peak memory. Follow these steps:
- Count the parameters of each Transformer block. The per-card state after sharding is determined by the global configuration; the unsharded size of a single block is its parameter count multiplied by the parameter dtype size in bytes. For example, a block with 8 billion parameters unshards to about 16 GB in BF16.
- Estimate peak memory: peak ≈ persistent shard state + largest unsharded block + activations + communication buffers. Communication buffers and activations must be measured, not just derived from formulas.
- If the peak exceeds the budget, reduce group granularity by splitting large blocks into submodules that are sharded separately.
- Use a profiler to measure AllGather time and compute time for each group. If AllGather takes longer than compute, communication is not being overlapped by computation—enlarge the group, enable prefetching, or adjust the communication order.
- For the last block, you can set
reshard_after_forwardto False to eliminate one AllGather during the backward pass, at the cost of higher memory usage for that segment.
Groups that are too large raise peak memory and may directly cause OOM. Groups that are too small increase the number of communications, and the launch overhead of small messages is hard to overlap with computation. Both directions require measured data—do not rely on rules of thumb alone.
3.3 Gradient Synchronization Sequence
Each shard group executes in the following order:
- Forward: AllGather the current group to obtain the full parameters, compute the forward pass, then release non-local shards.
- Backward: AllGather the group again and compute local gradients.
- Gradient reduction: ReduceScatter the gradients; each process keeps only the reduced result for its own shard.
- Optimizer update: each process updates only the parameters and optimizer states of its local shard.
Gradient clipping must occur after gradient reduction across all shards is complete, using the global norm. If each process computes the norm using only its local shard, clipping results vary with world size, making training behavior inconsistent with single-machine runs.
3.4 Mixed Precision
Mixed precision requires configuring three categories of data separately:
- Compute dtype (param_dtype): the parameter precision used in forward and backward passes, commonly BF16.
- Reduction dtype (reduce_dtype): the precision of gradient ReduceScatter. If the numerical stability of BF16 reduction on the domestic platform has not been verified, start with FP32 reduction and compare incrementally.
- Master weights and optimizer state dtype: typically keep FP32 master weights plus FP32 first-order and second-order moments.
Take a dense model with 2.8 trillion parameters as an example. At 16 bytes per parameter (BF16 parameter 2, BF16 gradient 2, FP32 master weight 4, Adam first-order moment 4, second-order moment 4), total static state is about 44.8 TB. Sharded across 1024 cards, that is roughly 43.75 GB per card. This figure excludes activations, communication buffers, and fragmentation, so actual peaks will be higher. For sparse models where only part of the parameters is activated, compute is estimated based on activated parameters, but memory is still estimated based on all parameters.
3.5 Checkpoint Recovery
Use distributed checkpointing (such as torch.distributed.checkpoint) to save sharded state: each process writes its own shard along with global metadata. Saved content includes:
- Model shard state and optimizer shard state
- Learning rate scheduler state, training step count, and number of samples consumed
- Random number states, including per-process random seeds
- Data loader read positions
Save asynchronously and keep the most recent N checkpoints to avoid having no usable version if a write is interrupted. During recovery, validate metadata first, then load shards, and finally run one forward pass to verify the loss matches the record from before saving. If the world size at recovery differs from that at saving, use a loading path that supports resharding and validate the results separately.
4. Checklist and Performance Assessment
4.1 Pre-Launch Checklist
- Version table fully filled in and cross-checked against the actual runtime environment
- Collective communication primitives pass correctness tests on single and multiple machines
- Sharding metadata saved and verifiable at recovery time
- Unsharded size of a single block and peak memory estimate recorded
- Gradient clipping uses the global norm
- All three mixed precision dtypes confirmed separately
- Checkpointing has passed a full save-restart-recover cycle
- Loss in the first few steps after recovery matches the record from before saving
- Sharding placement consistency verified for multimodal models
4.2 Criteria for Trustworthy Performance Data
Whether performance data is trustworthy depends on the measurement method, not on how good the results look. At minimum, the following should be stated:
- Throughput: report tokens processed per card per second, with sequence length and batch size noted.
- MFU (Model FLOPs Utilization): achieved compute divided by the card’s theoretical peak. Compute is estimated at roughly 6 × parameter count per token (dense models); sparse models use activated parameters. The formula and assumptions must be stated in the report.
- Communication share: use a profiler to measure the proportion of AllGather and ReduceScatter time in a single step.
- Scaling efficiency: using per-card throughput at a smaller scale as the baseline, compute the ratio of per-card throughput at the larger scale to the baseline.
- Measurement method: discard the first 10–20 warmup steps, repeat at least 3 times, and report the mean and variance. If variance exceeds a certain proportion of the mean, first investigate data loading, network jitter, and thermal throttling.
Performance data must include hardware/software versions, topology, and configuration. Numbers lacking this information cannot be compared with other results or reproduced.
5. Risks and Rollback
The main risks during adaptation include:
- Numerical deviation: BF16 reduction or custom operators can cause the loss curve to deviate from baseline. Compare loss and gradient norms step by step against a standard implementation at small scale, and only proceed to large-scale training if deviation stays within expectations.
- Silent errors: issues such as inconsistent sharding placement or incorrect gradient clipping norms usually raise no errors. Set monitoring thresholds for loss and gradient norms and pause automatically when anomalies are detected.
- Checkpoint corruption: interrupted writes or inconsistent metadata make recovery impossible. Keep multiple versions and validate file integrity before recovery.
- Resource consumption: asynchronous saving and prefetching increase pressure on host memory and storage bandwidth. Measure peaks before production and reserve headroom.
The rollback principle is to restore a usable state first, then investigate the cause. When an anomaly occurs, stop the current task, roll back to the most recent checkpoint that passed validation, and preserve logs and shard metadata from the anomalous period. Do not overwrite the original checkpoint or delete logs before rolling back. After modifying the configuration, re-run the complete checklist rather than validating only the changed parts.
