Adapting Large Model Training: Sharding and Communication Practices

    Training ultra-large models is heavily constrained by GPU memory and communication overhead. This article outlines practical approaches to estimate memory and communication requirements for large-scale training. It covers the implementation of FSDP2 for parameter sharding, communication volume estimation, all-to-all communication in Mixture of Experts (MoE) layers, and strategies for mixed and sparse attention. Additionally, it discusses multi-modal adaptation for vision encoders, training stability safeguards, and a rigorous validation methodology to ensure reproducible performance metrics.

    1. Calculate the Two Core Constraints First

    When training ultra-large models, GPU memory and communication are the two primary constraints. Before modifying code, it is essential to estimate both to determine if the proposed solution is feasible on the existing cluster.

    2. Memory Accounting

    Taking standard mixed precision training as an example, each parameter typically consumes the following space:

    • bf16 parameters: 2 bytes
    • bf16 gradients: 2 bytes
    • fp32 master weights: 4 bytes
    • Adam first and second moments: 4 bytes each

    Totaling approximately 16 bytes. A dense model with 7 billion parameters requires about 112 GB (7×10⁹ × 16 bytes) for parameter states alone. This exceeds the capacity of a single 80 GB GPU, necessitating sharding. With 8 GPUs, each holds about 14 GB; with 16 GPUs, each holds about 7 GB. Activation memory is calculated separately; it grows with sequence length and is typically compressed using activation recomputation.

    For MoE models, total parameters and activated parameters must be distinguished. Memory is calculated based on total parameters, while compute load depends on activated parameters. For a model with 2.8 trillion total parameters, parameter states alone require about 44.8 TB (2.8×10¹² × 16 bytes). Even with 80 GB per GPU, this requires at least 560 GPUs, excluding activations. Therefore, such models cannot be fully trained on 16 GPUs. A 16-GPU environment is suitable for pipeline validation, training small to medium models, or training a fraction of a large model.

    3. Sharding and Communication Paths in FSDP2

    FSDP2 is PyTorch’s fully sharded data parallel solution, accessed via fully_shard. It shards parameters at each layer, so each GPU only permanently stores its local shard.

    • Forward pass: Executes AllGather for the current layer to collect full parameters, which are released after computation.
    • Backward pass: Executes AllGather again to retrieve parameters, calculates gradients, and then executes ReduceScatter, allowing each GPU to directly obtain its gradient shard.

    AllReduce is not used here. AllReduce would provide every GPU with the full gradient, incurring greater memory and bandwidth overhead. ReduceScatter ensures each GPU only keeps its shard, making it more suitable for sharded training.

    Consider an 8192×8192 bf16 weight matrix: its full size is 8192 × 8192 × 2 bytes, approximately 128 MB. If sharded across 16 GPUs by rows, each GPU handles 8192 ÷ 16 = 512 rows, meaning a 512×8192 slice of about 8 MB.

    Below is a basic integration example. Note that build_model is a placeholder function and should be replaced with actual model building code.

    1. import torch
    2. import torch.distributed as dist
    3. from torch.distributed.fsdp import fully_shard, MixedPrecisionPolicy
    4. dist.init_process_group("nccl")
    5. # Use bf16 for parameters and forward pass, fp32 for gradient reduction to minimize precision loss
    6. mp = MixedPrecisionPolicy(param_dtype=torch.bfloat16, reduce_dtype=torch.float32)
    7. model = build_model(config) # Placeholder function, implement as needed
    8. for block in model.blocks:
    9. fully_shard(block, mp_policy=mp)
    10. fully_shard(model, mp_policy=mp)
    11. # Create the optimizer after sharding so optimizer states are sharded with the parameters
    12. optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4)

    Example launch command: torchrun --nproc_per_node=8 --nnodes=2 --node_rank=0 --master_addr=... train.py.

    4. Communication Volume Estimation

    During each training step, the communication volume per GPU can be roughly estimated as:

    Communication Volume ≈ 3 × Parameter Bytes × (W − 1) / W

    Here, W is the number of GPUs. The multiplier 3 comes from two AllGather operations and one ReduceScatter. Taking a 7-billion parameter bf16 model as an example, parameters are about 14 GB. With 16 GPUs, each GPU communicates roughly 39 GB per step. Assuming a cross-node effective bandwidth of 50 GB/s (approx. 400 Gb/s), communication takes about 0.8 seconds without considering overlap. Actual latency depends on the overlap between computation and communication; FSDP2 prefetches AllGather for the next layer by default to hide some latency. These figures are estimates, and actual measurements should be used as the standard.

    5. All-to-All Communication in MoE Layers

    The expert routing in MoE layers does not require collecting global routing probabilities. Each GPU first computes top-k experts for local tokens, then uses all-to-all to send tokens to the GPUs hosting the target experts. After expert computation, a second all-to-all sends the results back to the original GPUs.

    The communication volume during the dispatch phase is proportional to the number of tokens, the hidden dimension, and k. Therefore, in practical deployment, it is best to place the same group of experts within the same node, allowing high-frequency all-to-all operations to utilize intra-node NVLink, while low-frequency global gradient synchronization is executed across nodes.

    Load balancing is typically achieved using auxiliary loss. At the beginning of training, the auxiliary loss weight can be set low and gradually increased with steps to avoid prematurely suppressing expert differentiation. Additionally, a capacity factor can be set to limit the maximum number of tokens each expert receives per step; excess tokens are dropped or rerouted based on predefined strategies.

    6. Mixed Attention and Sparse Access

    A common practice for mixed attention is to apply global dense attention to some layers while using local window attention for the rest. Local layers only require nearby KV shards, resulting in significantly lower communication volume during sequence parallelism compared to global layers.

    The challenge with sparse attention is that the key positions accessed by each query are dynamic. If KV is gathered by element index, memory access is non-contiguous, leading to low efficiency and unpredictable gather volumes. Two more practical approaches are:

    1. Perform sparsity in blocks (e.g., 64 or 128 positions per block) so that gather operations read contiguous memory.
    2. Estimate the gather volume. The data volume gathered per layer is approximately: Number of queries × Number of sparse blocks per query × Block size × Head dimension × 2 (K and V) × Bytes. If this exceeds the memory budget, process in chunks along the query dimension—gathering, computing, and releasing chunk by chunk.

    7. Vision Encoding and Modal Loss

    Image tokens are typically far fewer than text tokens, and the loss magnitude differs between the two modalities. If the loss is calculated based on the modal average within a batch, short samples will be amplified. A more robust approach is to normalize the loss based on the global effective token count, ensuring consistent weight per token.

    Since the vision encoder has fewer parameters than the language backbone, it is recommended to treat it as a separate FSDP unit. If the encoder fits into a single GPU, consider replication rather than sharding to reduce communication overhead for small tensors. The input and output dimensions of the cross-modal projection layer should be checked for shape compatibility during initialization to avoid runtime errors midway through execution.

    8. Stability Safeguards

    Training stability relies on the following infrastructure:

    • Gradient clipping: A maximum norm of 1.0 is commonly used. Record the pre-clip gradient norm to monitor for continuous growth.
    • Learning rate warmup: Linearly increase to the peak over the initial steps. The number of warmup steps should be set based on total steps and batch size.
    • Per-modal loss monitoring: Record text loss and image loss separately to promptly investigate if one modality stagnates.
    • NaN detection: Check if the loss is NaN or Inf at each step; if so, automatically roll back to the previous checkpoint.
    • Distributed checkpoints: Use torch.distributed.checkpoint to save sharded states. Each GPU writes only its own shard, avoiding a single-point write bottleneck.

    9. Validation Methods and Reporting Standards

    This article does not provide universal performance improvement figures, as throughput, memory, and communication ratios depend on the GPU type, model architecture, sequence length distribution, and data. It is recommended to validate on a 2-node, 16-GPU setup using the following steps:

    1. Run the entire pipeline using a model with 100 million to 7 billion parameters.
    2. Record throughput per step (token/s), peak memory (torch.cuda.max_memory_allocated), and communication time ratio.
    3. Compare against an unoptimized baseline version, keeping the data, learning rate, and random seeds identical.
    4. When reporting, specify the GPU type, precision, sequence length distribution, parallel strategy, and baseline version.

    Results are only reproducible if all these conditions are fully documented.

    10. Conclusion

    Successful large model training adaptation requires a systematic evaluation of memory and communication constraints, combined with robust implementation of sharding and stability practices to ensure efficient and reproducible outcomes.