FSDP2 in Practice: From Sharded Loading to Checkpoint Recovery
This article provides a practical guide for engineers training large models with PyTorch FSDP2. It covers memory and communication budgeting, sharding mechanisms, staged model loading and scheduling, gradient communication overlapping, gradient synchronization and numerical validation, and checkpoint recovery. All configurations are reference starting points, not performance guarantees; measurements must be revalidated on your own cluster.
This article is intended for engineers training large models with PyTorch FSDP2. The content progresses through memory estimation, sharding boundaries, model loading, scheduling, gradient synchronization, and checkpoint recovery. The configurations provided are reference starting points—not performance guarantees. All numbers must be re-measured on your own cluster before adoption.
1. Estimate Memory and Communication Budgets First
Before configuring anything, estimate the memory required per GPU. Taking a 2.8-trillion-parameter model as an example, storing only the BF16 weights requires 2.8 × 10¹² × 2 bytes = 5.6 TB (decimal), or about 5.09 TiB (binary). This number covers weights only.
Training also accounts for other state. A typical mixed-precision setup with Adam results in the following per-parameter memory usage:
| Content | Bytes per parameter | Description |
|---|---|---|
| BF16 weights | 2 | Used for forward and backward |
| FP32 master weights | 4 | Used during optimizer updates |
| FP32 gradients | 4 | Gradient reduction precision; can be 2 if using BF16 gradients |
| Adam first and second moments | 8 | Two FP32 tensors |
| Total | 18 | 16 if gradients use BF16 |
Using 2.8 trillion parameters and 18 bytes per parameter, the total state is about 50.4 TB. Spread across 512 GPUs, that is approximately 98 GB per GPU (decimal). This does not include activations, communication buffers, or memory fragmentation. Activation memory depends on sequence length, batch size, and checkpointing strategy—it must be measured separately.
Communication also needs an upfront estimate. During each forward pass, every rank must gather the parameter shards it does not own locally, so the amount of data received in a single forward is close to the full BF16 weight size. During backward, gradients require a reduce-scatter operation. Inter-node bandwidth is typically lower than intra-node interconnect, and cross-node collective communication is often the primary bottleneck.
2. FSDP2 Sharding Mechanism and Version Boundaries
FSDP2 uses the fully_shard interface to shard modules. Parameters are represented as DTensor, which records the device mesh and the sharding placement. This allows the framework to describe the distribution of every tensor with a consistent set of rules.
Before starting, confirm the version boundaries:
- The import path for
fully_shardchanges across versions. Newer versions locate it intorch.distributed.fsdp, while earlier experimental versions usetorch.distributed._composable.fsdp. Always refer to the documentation for your specific version. - Parameters are sharded along dimension 0 by default. If you need to shard along a different dimension, check whether your version exposes a configuration interface. Support varies across versions; do not directly copy a usage pattern from one version to another.
- Sharding placement affects the checkpoint save format. After changing the sharding dimension, re-validate that loading still produces correct results.
The following configuration table is a starting point for comparison. These are initial values; final values must be determined through measurements.
| Configuration item | Starting point | Tuning basis |
|---|---|---|
| Computation precision | param_dtype=bf16 |
Aligns with training precision requirements |
| Gradient reduction precision | reduce_dtype=fp32 |
More numerically stable but increases communication volume |
| Sharding granularity | Apply fully_shard to each Transformer block individually, then wrap the outer module |
Finer granularity is not always faster; consider communication volume and memory |
| Device mesh | 1D mesh | If inter-node bandwidth is insufficient, switch to HSDP 2D mesh and restrict sharding groups within nodes |
reshard_after_forward |
Set to True when memory is tight |
If memory allows, can set to False for the last block |
| Activation checkpointing | Enabled for each block | Uses recomputation in backward to save memory; throughput will decrease and needs measurement |
| Prefetching | Prefetch 1 layer for forward and backward | More prefetching increases peak memory |
| Gradient accumulation | Disable gradient synchronization for earlier micro-batches; enable for the last micro-batch | Reduces communication frequency |
3. Staged Loading and Scheduling
Instantiating a 2.8-trillion-parameter model directly on CPU or GPU will exhaust memory during the loading phase. The recommended order is: first build the model structure on the meta device, shard it, and then load the weights.
- Build the model on the meta device. This does not allocate real memory; it only stores structure and shape information.
- Call
fully_shardon each block and the outer module. - Call
to_emptyto allocate sharded memory on the target device. This step only allocates memory; it does not write any valid values. - Load weights from a distributed checkpoint according to the sharding. Do not assemble the full weight on any single rank.
Example code:
import torchfrom torch.distributed.device_mesh import init_device_meshfrom torch.distributed.fsdp import fully_shard, MixedPrecisionPolicymesh = init_device_mesh("cuda", (world_size,))mp = MixedPrecisionPolicy(param_dtype=torch.bfloat16, reduce_dtype=torch.float32)with torch.device("meta"):model = build_model(cfg)for block in model.layers:fully_shard(block, mesh=mesh, mp_policy=mp)fully_shard(model, mesh=mesh, mp_policy=mp)model.to_empty(device="cuda")
Example weight loading:
import torch.distributed.checkpoint as dcpfrom torch.distributed.checkpoint.state_dict import (get_model_state_dict,set_model_state_dict,)state = {"model": get_model_state_dict(model)}dcp.load(state, checkpoint_id=ckpt_dir)set_model_state_dict(model, state["model"])
When training from scratch, after to_empty you must call each module’s own parameter initialization logic. Otherwise the model parameters contain uninitialized memory, and training results are meaningless.
For scheduling, FSDP2 modules provide set_modules_to_forward_prefetch and set_modules_to_backward_prefetch to specify which modules to prefetch next. The prefetch depth should be tuned together with memory headroom. Too much prefetching raises peak memory; too little exposes communication outside computation.
4. Gradient Bucketing and Communication Overlap
FSDP2 does not have a global bucketing parameter in megabytes like FSDP1. The basic communication unit is determined by how fully_shard groups modules; all parameters inside a single fully_shard module are all-gathered and reduce-scattered together. Therefore, the grouping method is the bucketing method. Refer to the documentation for your version for exact behavior.
Grain size tradeoffs:
- Too-coarse grouping: large communication per operation, and preceding computation may not fully cover it, exposing communication in step time.
- Too-fine grouping: more communication calls and kernel launch overhead, with lower bandwidth utilization for small messages.
Use torch.profiler to inspect the timeline for overlap. Place communication kernels and compute kernels on the same graph, and calculate the communication time not covered by compute. The ratio of this exposed time to step time is the core metric for scheduler quality.
If reduce_dtype is set to FP32, communication volume is higher than BF16 reduction. If communication becomes the bottleneck, compare throughput between the two settings, then confirm convergence is unaffected by examining training curves.
5. Gradient Synchronization and Numerical Validation
Correctness of gradient synchronization should be verified before speed. Follow this sequence:
- Gradient clipping:
torch.nn.utils.clip_grad_norm_handles DTensor parameters. Confirm that the norm computation is done on the correct device mesh. Validate with a single-step comparison: grad norm before and after clipping should match a single-GPU or DDP baseline. - Numerical alignment: On a reduced-scale model, use identical data and random seed, and compare loss and grad norm for the first several steps against a single-GPU or DDP baseline.
- Error tolerance: Define the acceptable error range under BF16 explicitly. Do not require exact FP32 parity for BF16 training results.
- Determinism settings: Deterministic algorithms reduce speed. Enable them only for alignment tests; disable for regular training.
6. Checkpoint Recovery
Checkpoints determine whether training can recover from failure and how much data is lost in the worst case. Verify the following items before deployment:
- Sharded saving: When using
dcp.save, each rank writes its own shard. Do not gather full weights before saving; this creates extra memory and time overhead. - Optimizer state: Save model weights and optimizer state together. Saving only model weights resets Adam momenta upon recovery, causing discontinuities in training curves. Use
get_optimizer_state_dictandset_optimizer_state_dictfor optimizer state. - Asynchronous saving:
dcp.async_savereduces blocking time. Ensure the previous save completes before starting the next, and keep at least one complete version. - Atomic writes: Write to a temporary directory, then rename to the final directory after all ranks finish writing and metadata is generated. If a save is interrupted, only the temporary directory remains, leaving the last complete checkpoint untouched.
- Cross-size recovery: After changing
world_sizeor the sharding grid, test whether DCP can correctly reshard and load. This is one of the most error-prone scenarios. - Recovery validation: Terminate the process mid-training, recover from the nearest checkpoint, and compare loss for the first few steps. It should be continuous with the original training trajectory.
Common mistakes include: forgetting to load or initialize weights after to_empty, resulting in random outputs; assembling full weights on rank 0, causing out-of-memory; and saving only model weights, losing optimizer state on recovery.
7. Risk Checklist
Confirm the following risks before adoption:
- Case data that has not been independently reproduced should not be treated as expected performance for your own environment.
- Memory estimation does not include activations, communication buffers, or fragmentation; actual usage will be higher.
- Non-default sharding dimensions can affect version support, checkpoint compatibility, and performance.
- HSDP group sizing must align with physical network topology. Misaligned groups increase cross-node traffic.
reshard_after_forwardand prefetching trade memory for speed; optimal values depend on model structure and memory headroom.- BF16 reduction or mixed precision may affect convergence; verify with sufficiently long training curves.
- Checkpoint save interruptions or format incompatibilities can prevent recovery.
- Framework version upgrades may change interfaces and default behavior; re-run alignment tests after upgrades.
8. Items That Must Be Tested in Your Own Environment
The following optimizations depend heavily on hardware and workloads; do not directly apply conclusions from others:
- Sharding granularity combined with
reshard_after_forward - Prefetch depth
- HSDP grouping
- Non-default sharding dimensions
reduce_dtypesetting- Asynchronous checkpoint frequency
Test each item with single-variable changes against a fixed baseline: change one parameter, record results, then change the next.
9. Validation Metrics and Pass Criteria
| Metric | Measurement method | Evaluation |
|---|---|---|
| Peak memory | torch.cuda.max_memory_allocated and max_memory_reserved |
Compare against estimates; leave headroom for activations and fragmentation |
| Per-GPU throughput | tokens/s/GPU, averaged over stable steps | Compare against baseline; define acceptable degradation in advance |
| MFU | Actual compute divided by hardware peak | Use for scaling comparison across sizes |
| Exposed communication ratio | torch.profiler timeline |
Lower is better for overlap; consider together with throughput |
| Loss and grad norm | Compare step-by-step against baseline | Error within predefined tolerance |
| Recovery continuity | Recover from checkpoint after process termination | Loss over subsequent steps should be continuous with original trajectory |
Before deployment, record all metrics in a configuration log, including framework version, hardware model, network topology, sharding configuration, and measurement results. If regression occurs, you can roll back to the last verified configuration.
