FSDP2 Adaptation Guide for a 2.8-Trillion-Parameter MoE Model

    A practical guide to adapting a 2.8-trillion-parameter mixture-of-experts model for distributed training with FSDP2. It covers resource estimates, platform validation, parameter sharding, gradient synchronization, multimodal data pipelines, monitoring, and checkpoint recovery, with code examples and a deployment checklist. All estimates and tuning thresholds require validation on the target cluster.

    Introduction

    This guide outlines the training adaptation workflow and validation checklist for a 2.8-trillion-parameter mixture-of-experts (MoE) model. The workflow has five stages: estimate resource requirements, validate the platform and software stack, configure FSDP2 sharding and gradient synchronization, build the multimodal data pipeline, and establish monitoring and recovery procedures.

    The resource figures below are estimates derived from parameter counts. Available public information does not specify hardware models, software versions, network topology, or measured performance. Version selections, thresholds, and bucket sizes should therefore be treated as placeholders or initial tuning choices and validated on your own cluster.

    1. Challenges and Resource Limits

    Start by estimating the minimum training-state requirements. At BF16 precision, 2.8 trillion parameters require approximately 5.6 TB for weights:

    2.8 × 10^12 parameters × 2 bytes = 5.6 TB

    With AdamW, retaining FP32 master weights and first- and second-moment estimates requires approximately 12 bytes per parameter, or 33.6 TB for these states alone. Adding BF16 weights and gradients brings the complete training state to tens of terabytes.

    The table below estimates the per-device share of FP32 master weights and optimizer moments. It excludes activations, communication buffers, and memory fragmentation.

    Accelerator count Estimated optimizer-state memory per device
    1,024 Approximately 33 GB
    2,048 Approximately 16 GB
    4,096 Approximately 8 GB

    Device count is not the only constraint. Activations and communication buffers consume additional memory, so activation checkpointing is typically needed to reduce peak usage. A common starting target is to keep peak per-device memory below 85% of available memory, adjusting for observed fragmentation.

    Two additional constraints are critical:

    • Communication: MoE expert parallelism introduces All-to-All communication, sending each token to the device hosting its routed expert. Insufficient inter-node bandwidth can make this the primary bottleneck.
    • Collective ordering: Every rank must execute collectives in the same order at each layer. If one rank skips a collective, the entire job can hang, often without a clear error message.

    2. Validate the Platform and Software Stack

    Complete these checks before configuring distributed training code. Performance measurements are not meaningful until the platform passes validation.

    1. Record component versions. Capture the accelerator driver, device runtime, communication library, PyTorch, and device plugin versions. Use the vendor-provided version-query commands and save their output with the experiment records.
    2. Verify operator coverage. List the operators used by the model, including rotary position embeddings, scaled dot-product attention, expert FFNs, and routing operations. Confirm that each has a native implementation. Operators falling back to emulation typically show unusually high execution times in profiling results.
    3. Benchmark collectives. Test AllReduce, AllGather, ReduceScatter, and All-to-All on both single-node and multi-node configurations. Record bandwidth and latency.

    The following script measures AllReduce bus bandwidth for a 256 MB tensor. Replace the device type and backend name with the values provided by your accelerator plugin.

    1. import os
    2. import time
    3. import torch
    4. import torch.distributed as dist
    5. DEVICE_TYPE = os.environ.get("DEVICE_TYPE", "cuda") # Use the device name provided by the vendor plugin
    6. dist.init_process_group(backend=os.environ["DIST_BACKEND"])
    7. local_rank = int(os.environ["LOCAL_RANK"])
    8. device = torch.device(DEVICE_TYPE, local_rank)
    9. numel = 256 * 1024 * 1024 // 2 # 256 MB BF16 tensor
    10. x = torch.ones(numel, dtype=torch.bfloat16, device=device)
    11. sync = getattr(torch, DEVICE_TYPE).synchronize
    12. for _ in range(5): # Warm-up
    13. dist.all_reduce(x)
    14. sync()
    15. t0 = time.time()
    16. for _ in range(20):
    17. dist.all_reduce(x)
    18. sync()
    19. elapsed = (time.time() - t0) / 20
    20. world = dist.get_world_size()
    21. bytes_moved = x.numel() * x.element_size()
    22. busbw = 2 * (world - 1) / world * bytes_moved / elapsed / 1e9 # Bus bandwidth in GB/s
    23. if dist.get_rank() == 0:
    24. print(f"all_reduce 256MB: {elapsed * 1e3:.2f} ms, bus bandwidth {busbw:.1f} GB/s")
    25. dist.destroy_process_group()

    Use torchrun to test both single-node and two-node configurations, setting --nnodes accordingly. The two-node configuration uses torchrun --nnodes=2 --nproc_per_node=8. If inter-node bandwidth is substantially lower than intra-node bandwidth, investigate the network topology before changing the parallelism strategy.

    3. Configure FSDP2 Sharding and Gradient Synchronization

    FSDP2 Configuration

    FSDP2 applies parameter sharding through fully_shard. During the forward pass, each sharding unit uses AllGather to reconstruct its parameters. After computation, it releases nonlocal shards according to reshard_after_forward.

    When parameters have been resharded, the backward pass gathers them again. After gradient computation, ReduceScatter distributes gradient shards across devices. The primary gradient collective in FSDP2 is therefore ReduceScatter, not AllReduce. Hybrid sharding (HSDP) adds an AllReduce across sharding groups.

    1. import torch
    2. from torch.distributed.fsdp import fully_shard, MixedPrecisionPolicy
    3. mp = MixedPrecisionPolicy(
    4. param_dtype=torch.bfloat16, # Precision used for computation and AllGather
    5. reduce_dtype=torch.float32, # ReduceScatter precision to reduce gradient accumulation error
    6. )
    7. for block in model.blocks: # Adapt the attribute name; use roughly one Transformer layer per unit
    8. fully_shard(block, mp_policy=mp, reshard_after_forward=True)
    9. fully_shard(model, mp_policy=mp) # The root module handles remaining embeddings and output layers
    Setting Purpose Common starting point Tuning guidance
    reshard_after_forward Releases nonlocal parameter shards after the forward pass True Keep enabled when memory is tight. Set to False when memory permits to avoid an additional AllGather during backward.
    Sharding granularity Defines the layers in each sharding unit One unit per Transformer layer Units that are too large limit prefetching effectiveness; units that are too small create excessive communication calls.
    Prefetch depth Controls how many layers ahead parameters are fetched 1–2 layers Consider increasing it if traces show insufficient overlap between AllGather and the preceding layer’s computation.
    reduce_dtype Sets gradient reduction precision FP32 Use when insufficient gradient precision causes abnormal loss behavior.

    Expert Parallelism and All-to-All Tuning

    Expert parameters are typically partitioned across expert-parallel groups, while FSDP2 shards the dense components. Focus on four measurements:

    • Capacity factor: A common starting range is 1.0–1.25. Increasing it can reduce dropped tokens but also increases All-to-All traffic and memory usage.
    • Token drop rate: Track the fraction of tokens dropped at each step because expert capacity is exceeded. This should be close to zero during stable training.
    • Expert load imbalance: Compute the maximum number of tokens received by any expert divided by the mean across experts. If this ratio remains high, review the load-balancing loss coefficient.
    • All-to-All time share: Measure All-to-All duration in profiling traces as a fraction of total step time.

    Gradient Synchronization Procedure

    1. Use the framework’s default gradient bucketing and asynchronous communication. Do not insert global synchronization calls during backward, as they interrupt communication-compute overlap.
    2. During gradient accumulation, synchronize gradients only on the final microbatch. FSDP2’s FSDPModule provides set_requires_gradient_sync to control this behavior.
    3. Use a DTensor-compatible gradient-clipping implementation so the global gradient norm is consistent across shards. Clipping independently on each device can cause model states to diverge.
    4. Validate numerical correctness with a fixed random seed on a small configuration. Compare losses over the first several steps of single-node and multi-node runs. Relative error should remain below a predefined, precision-dependent threshold; 1e-3 can serve as an initial reference for BF16 training.

    4. Build the Multimodal Training Pipeline

    Treat the vision encoder, projector, and language-model backbone as separate FSDP2 sharding units. Apply freezing policies at the unit level. Mixing requires_grad settings within the same unit increases debugging complexity and is best avoided where practical.

    Training-stage transitions can be described in a configuration file:

    1. data:
    2. max_seq_len: 8192 # Maximum packed sequence length
    3. image_tokens_per_image: 256 # Must match the vision encoder output; assert at startup
    4. pack_strategy: greedy # Greedy packing to reduce padding
    5. loss_mask_modalities: [image, prompt]
    6. train:
    7. vision_encoder_frozen: true
    8. stages:
    9. - name: align # Stage 1: train only the projector
    10. trainable: [projector]
    11. - name: sft # Stage 2: unfreeze the language-model backbone
    12. trainable: [projector, llm]

    These values are examples and must be replaced with settings appropriate to the model.

    Multimodal Data Pipeline Checks

    • Image token count: The number of sequence positions allocated to each image must match the vision encoder output. Assert this at startup to prevent silent misalignment.
    • Sample boundaries: Record each sample’s start and end positions during packing. Use variable-length attention or block-diagonal masks to prevent cross-sample attention.
    • Modality mix: Monitor the ratio of text-only to image-text samples in each batch. Large changes can cause pronounced step-to-step loss fluctuations.
    • Data sharding and recovery: Each data-parallel rank must read a distinct data shard. After checkpoint recovery, each rank must resume at the correct position without duplicating or skipping samples.

    5. Monitoring and Failure Recovery

    Metric Definitions

    Metric Calculation Notes
    Throughput, in tokens/s Global effective tokens per step ÷ wall-clock step time Count only tokens contributing to the loss.
    Model FLOPs utilization (MFU) Estimated achieved FLOPs/s ÷ (peak FLOPs/s per device × device count) Estimate training FLOPs per token as approximately 6 × active parameter count. For MoE, use active parameters rather than total parameters.
    Exposed communication time Communication time in the trace that does not overlap compute kernels Indicates whether sharding and prefetching are working effectively.
    Peak device memory Maximum allocated device memory recorded per step Compare against available memory per device.

    Checkpointing and Recovery

    • Asynchronous saving: Use distributed checkpointing through torch.distributed.checkpoint to save weights and optimizer states. Confirm that your installed version supports asynchronous saving before enabling it.
    • Save interval: A common starting point is every 30–60 minutes. If a checkpoint write consumes too large a fraction of that interval, save less frequently or use faster storage.
    • Recovery drills: Perform a recovery test on a test cluster each week. Compare the first ten loss values after recovery and verify the data position.

    Failure Detection

    • Configure collective communication timeouts so stalled jobs can be detected promptly. The timeout must exceed the normal duration of a single All-to-All operation.
    • Shard-level partial degradation is not directly supported by standard FSDP2. The usual approach is to restart through an elastic launcher, such as torchrun in elastic mode, exclude the failed node, and restore the most recent checkpoint.
    • Deliberately terminate a worker on a test cluster. Measure the time from failure detection to completed recovery and compare it with the recovery objective.

    Common Troubleshooting Scenarios

    Symptom Common causes Investigation
    Job hangs without an error A rank skipped a collective, or ranks followed inconsistent branches Compare the name and sequence number of the last collective in each rank’s logs.
    Sudden peak-memory increase Activation checkpointing is disabled, or reshard_after_forward is disabled Record memory allocations by layer to locate the peak.
    Excessive communication time Sharding units are too small, or frequent communication crosses nodes Inspect the trace to identify the communication domain used by All-to-All.
    Loss spikes Attention leaks across sample boundaries, or data indices are incorrect after recovery Check packed-sample boundary masks and verify restored data indices.

    Validation Checklist

    Item Validation method Acceptance criterion
    Version records Check that experiment records contain every component version The complete software stack is reproducible.
    Operator coverage Inspect profiles for emulated operators All critical operators use native implementations.
    Collective communication Run the bandwidth benchmark within a node and across nodes Inter-node bandwidth is within an acceptable margin of vendor specifications.
    Memory Record peak memory for a training step Peak usage stays below 85% of available device memory.
    Numerical correctness Compare early-step losses between single-node and multi-node runs Relative error is below the predefined threshold.
    Expert load Measure load imbalance and token drop rate Token drops are close to zero, and the load ratio is stable.
    Checkpointing Complete an asynchronous save and recovery cycle Loss behavior and data positions are correct after recovery.
    Failure drill Deliberately terminate a worker Recovery time meets the operational target.

    The sharding, gradient synchronization, and multimodal workflow described here applies structurally to similar MoE models. However, every numerical threshold, software-version combination, and performance conclusion must be validated on the hardware and network used for training.