FSDP2 Sharding in Practice: Key Adaptations for Very Large-Scale Model Training

    This article uses a hypothetical 2.8-trillion-parameter multimodal model to examine FSDP2 sharding for very large-scale training. It covers memory estimation, communication bottlenecks, HSDP configuration, model loading, sharding scheduling, training stability, data loading, resource management, monitoring, and future directions. The figures are for estimation only and do not represent any released model.

    1. Background and Assumptions

    This article uses a hypothetical multimodal model with 2.8 trillion parameters as a case study. The numbers are used for estimation and do not represent the real specifications of any released model. When applying them, readers should replace them with their own model parameter count, hardware, and network configuration.

    As model parameters continue to grow, hundred-billion-parameter models are already common, and trillion-parameter models have begun to appear. As parameter scale increases, three training problems become more prominent: a full model does not fit in single-GPU memory, cross-GPU communication volume rises quickly, and the combination of data parallelism and model parallelism requires repeated tuning. Training adaptation has therefore shifted from “getting it to run” to an engineering problem of efficiency, stability, and scalability.

    2. Core Technical Challenges

    2.1 Estimating Memory Requirements

    Memory requirements depend on the calculation basis. Under a common AdamW configuration for mixed-precision training, each parameter usually occupies about 16 bytes:

    • Low-precision weights (bf16): 2 bytes
    • Low-precision gradients (bf16): 2 bytes
    • Full-precision master weights (fp32): 4 bytes
    • Adam first moment (fp32): 4 bytes
    • Adam second moment (fp32): 4 bytes

    The total is about 16 bytes. For 2.8 trillion parameters, the estimate is:

    Total memory ≈ parameter count × bytes per parameter = 2.8 × 10¹² × 16 bytes ≈ 44.8 TB

    Saving only the bf16 weights requires about 5.6 TB. This estimate does not include activations, temporary buffers, or communication buffers, so actual requirements will be higher.

    Based on vendor-specified memory, common GPU capacities are as follows: H100 PCIe has 80 GB, H200 has 141 GB, and B200 has 192 GB. Using 192 GB per GPU as an estimate, storing only the training state above requires at least 233 GPUs (44.8 TB ÷ 192 GB ≈ 233), before activations are included.

    The essence of the memory wall is the gap between compute capability and memory capacity growth. GPU compute performance improves significantly faster than per-GPU memory capacity, so parameters must be distributed across multiple GPUs.

    2.2 Communication Bottlenecks

    Every data-parallel step requires gradient synchronization. If each GPU keeps a complete model replica, the gradient size is on the same order as the parameter count. In bf16, one complete gradient for 2.8 trillion parameters is about 5.6 TB. Using one 400 Gbps network interface (about 50 GB/s) as an estimate, one transfer takes about 112 seconds, and AllReduce usually transmits about twice the data volume. At this scale, pure data parallelism is therefore infeasible, and parameter sharding must be used together with it.

    Model parallelism, including tensor parallelism and pipeline parallelism, must pass activations and gradients during the forward and backward passes of each micro-batch. Communication frequency is higher, and latency sensitivity is greater.

    2.3 Heterogeneous Multimodal Inputs

    Text, images, audio, and video differ greatly in feature dimensions, value distributions, and sequence lengths. The training framework needs to provide unified interfaces in data loading, preprocessing, and input adaptation. A common approach is to design an independent encoder for each modality, project the outputs to a unified hidden dimension, and then concatenate them into the input sequence for the Transformer.

    3. FSDP2 Sharding Strategy

    3.1 Basic Approach of FSDP2

    FSDP (Fully Sharded Data Parallel) stores parameters, gradients, and optimizer states in shards. Each GPU holds only a portion. Before computing a layer, the full parameters of that layer are temporarily retrieved through all-gather, and they are released after computation.

    Compared with first-generation FSDP, FSDP2 in PyTorch (torch.distributed.fsdp.fully_shard) has the following main changes:

    • Per-parameter sharding: each parameter is independently sharded based on DTensor, making state dict and distributed checkpoint handling more direct.
    • Composable parallel interface: DeviceMesh describes the device topology, making it easier to combine with tensor parallelism and pipeline parallelism.
    • Finer memory control: mixed-precision policy, whether to reshard after forward (reshard_after_forward), and CPU offload can be configured per module.

    In practice, fully_shard is usually called layer by layer for Transformer layers and then called once more for the root module. PyTorch 2.6 or later is recommended. Interface details may vary between versions, so the official documentation for the version in use should be consulted.

    3.2 Hybrid Sharded Data Parallel (HSDP)

    HSDP (Hybrid Sharded Data Parallel) uses a two-dimensional device mesh with two dimensions:

    • Shard dimension: usually placed within the same node, using the high bandwidth of NVLink and NVSwitch for parameter sharding and all-gather.
    • Replicate dimension: stores replicas of the sharded parameters across nodes, with cross-node communication mainly used for gradient reduction.

    This confines high-frequency parameter communication to within nodes, while cross-node traffic is mainly gradient reduction. With many nodes, this structure balances memory usage and cross-node communication volume. HSDP does not change the model-parallel approach. Tensor parallelism and pipeline parallelism must be configured separately.

    The following code shows the basic HSDP structure. It must be replaced with a real model definition and launched with torchrun in a multi-node environment:

    1. import torch
    2. from torch.distributed.device_mesh import init_device_mesh
    3. from torch.distributed.fsdp import fully_shard, MixedPrecisionPolicy
    4. # Example cluster: 8 nodes, 8 GPUs per node
    5. mesh = init_device_mesh("cuda", (8, 8), mesh_dim_names=("replicate", "shard"))
    6. mp_policy = MixedPrecisionPolicy(
    7. param_dtype=torch.bfloat16, # Parameter precision for forward and backward computation
    8. reduce_dtype=torch.float32, # Precision for gradient reduction
    9. )
    10. # model is built on the meta device and matches the structure of the real model
    11. for block in model.blocks:
    12. fully_shard(block, mesh=mesh, mp_policy=mp_policy)
    13. fully_shard(model, mesh=mesh, mp_policy=mp_policy)
    14. # Allocate storage for local shards, then load parameters from a distributed checkpoint
    15. model.to_empty(device="cuda")
    16. # The optimizer must be created after sharding so it receives the sharded parameters
    17. optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4, fused=True)

    3.3 Prefetching and Communication Overlap

    By default, FSDP2 asynchronously initiates the all-gather for the next layer’s parameters while computing the current layer, overlapping communication with computation. If the profiler shows compute units waiting for communication, the prefetch order can be adjusted through the prefetch interface provided by the FSDP module. Such optimizations should be verified with a profiler and should not be assumed to be effective by default.

    4. Complete Training Pipeline

    4.1 Model Loading

    For a 2.8-trillion-parameter model, loading complete weights directly on a single GPU or single node is infeasible. The recommended loading process is:

    1. Build the model on the meta device, generating only structural information without allocating actual storage.
    2. Call fully_shard on each Transformer layer and the root module to declare sharding.
    3. Call to_empty to allocate local shard storage on each GPU.
    4. Load parameters from a distributed checkpoint (torch.distributed.checkpoint) by shard, so each GPU reads only the part it is responsible for.
    5. Validate that parameter names, shapes, and data types match the checkpoint metadata.

    Step 5 is easy to skip, but parameter name or shape inconsistencies often surface late in training and are costly.

    4.2 Sharding Scheduling and Communication

    Sharding scheduling concerns when each parameter shard is transferred. The main mechanisms include:

    • Prefetching: while computing the previous layer, asynchronously retrieve the complete parameters of the next layer.
    • Release: after forward computation, release unnecessary parameters according to the reshard_after_forward policy, and retrieve them again during backward propagation.
    • Gradient reduction: at the end of backward, gradients are distributed to each GPU through reduce-scatter, and each GPU keeps only the gradients corresponding to its own shard. FSDP2 handles gradient bucketing internally, so users usually do not need to manage it manually. If a large number of small communications is observed, check whether the module partitioning granularity is too fine.

    4.3 Gradient Synchronization and Optimizer States

    In HSDP scenarios, gradients first complete reduce-scatter within a node and are then reduced across nodes over the replicate dimension. Optimizer states are stored with parameter shards, and each GPU updates only the state corresponding to its local shard. Therefore, Adam state memory decreases as the number of shards increases, and a complete copy is not repeated on every GPU.

    4.4 Ensuring Training Stability

    Training stability depends on the following measures:

    • Gradient clipping: clip by global gradient norm. A threshold of 1.0 is a common starting point but not a universal fixed value. It should be adjusted based on the task, model scale, and loss curve.
    • Loss scaling: the dynamic range of bf16 is close to fp32, so GradScaler is usually not required. Dynamic loss scaling is mainly used for fp16 training.
    • Checkpointing: periodically save model shards, optimizer states, learning rate scheduler state, and random number generator state. When restoring, validate the world size. To resume training with a different GPU count, the checkpoint format must support resharding.

    The following is an example of a training step:

    1. def train_step(batch):
    2. # bf16 training usually does not require GradScaler
    3. with torch.autocast("cuda", dtype=torch.bfloat16):
    4. loss = model(batch)
    5. loss.backward() # FSDP performs gradient reduce-scatter and cross-node reduction during backward
    6. # In newer PyTorch versions, clip_grad_norm_ can operate directly on sharded parameters and return the global norm
    7. grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
    8. optimizer.step()
    9. optimizer.zero_grad(set_to_none=True)
    10. return loss.detach(), grad_norm

    5. Common Engineering Considerations

    5.1 Data Loading

    Multimodal datasets can reach TB or even PB scale, and data loading can easily become a bottleneck. The following practices are recommended:

    • Sharded reading: each data-parallel group reads only the sample subset it is responsible for, which can be implemented with DistributedSampler or an equivalent mechanism.
    • Offline feature extraction: features for unstructured data such as images and audio can be extracted in advance and cached. Preprocessing versions should also be recorded to avoid inconsistency between training and inference preprocessing.
    • Prefetching and concurrency: the number of prefetch threads should match storage bandwidth. Use the ratio of data-loading time to per-step compute time to determine whether loading is slowing down training.
    • Memory mapping: mmap is suitable for read-only, randomly accessed data formats. If data is stored on a network file system, access latency should be tested first.

    5.2 Containerization and Resource Management

    • Each training job should use an independent namespace and resource quota to prevent jobs from competing for resources.
    • The scheduler should consider network topology. The same HSDP shard group should be placed within the same node or under the same switch as much as possible to reduce cross-switch communication.
    • Fault self-healing depends on checkpoints. After a node failure, the job should automatically restart and recover from the latest checkpoint. The restart policy needs a maximum retry count to prevent repeated failures from consuming resources.
    • Elastic scaling requires checkpoints to support changes in GPU count. After scaling, the relationship between learning rate and global batch size must also be rechecked.

    5.3 Monitoring and Alerting

    The monitoring system should cover three layers: infrastructure (GPU utilization, memory, network), framework (gradient norm, communication time), and model (loss curve, convergence trend). The thresholds in the table below are initial suggestions and should be calibrated against the cluster’s historical baseline.

    Metric category Specific metric Suggested alert condition
    Compute resources GPU utilization Continuously below 60% for 10 minutes; consider together with data loading and synchronization waits
    Memory usage Memory utilization Continuously above 90%
    Communication time Cross-node all-gather or reduce time A single occurrence exceeds 500 ms, or exceeds 20% of per-step time
    Model stability Global gradient norm Continuously above 10.0
    Data loading Data-loading time P95 exceeds 80% of per-step compute time for 5 minutes

    6. Future Directions

    Several directions for very large-scale training are still evolving, with different levels of maturity.

    1. Composable parallel strategies: represent data, tensor, pipeline, and sequence parallelism as a configurable device mesh, with tools providing an initial configuration based on model structure. Most teams still need manual tuning today.
    2. Communication offload: DPUs or smart NICs can handle some collective communication. This requires specific hardware, drivers, and network topology support; retrofit costs are high, and compatibility must be verified item by item.
    3. Fault tolerance: identifying anomalous nodes based on gradient statistics remains a research topic. In production, the more common approach is still health checks plus checkpoint recovery.

    The difficulty of very large-scale training lies in designing memory, communication, data, and fault tolerance as a whole. Optimizing any one of them in isolation often exposes new bottlenecks elsewhere.