Trillion-Parameter Large Model Training with FSDP2 on Domestic Compute Platforms: A Practical Adaptation Guide

    This article explains how to adapt trillion-parameter large model training on domestic compute platforms with FSDP2. It focuses on stable throughput, controllable memory usage, verifiable numerical accuracy, and recoverable failures during long training runs. The article covers memory estimation, operator alignment, precision validation, software stack compatibility, FSDP1 versus FSDP2 selection, model loading, sharding scheduling, gradient synchronization, multimodal training, infrastructure selection, monitoring baselines, and troubleshooting for OOM, slow nodes, and communication bottlenecks. It provides practical checklists and reference thresholds for engineers preparing large-scale training workloads on custom or vendor-specific hardware.

    1. Start with the conclusion: the goal is controlled completion, not just getting the job running

    When adapting trillion-parameter large models on domestic compute platforms, the goal should not be merely to start the training job. The real objective is to keep throughput stable, memory usage controllable, numerical accuracy verifiable, and failures recoverable during long training cycles.

    Engineers need to address five types of problems at the same time:

    • GPU memory
    • Communication
    • Operator accuracy
    • Software stack compatibility
    • Operations and monitoring

    This article is organized around model loading, sharding scheduling, gradient synchronization, FSDP2 adaptation, and troubleshooting. It provides an actionable checklist to help readers answer several practical questions:

    • How should FSDP2 be selected?
    • How should domestic platforms be aligned with mainstream software stacks?
    • How should common OOM and communication bottlenecks be handled?
    • Which monitoring metrics should be configured?

    2. Why trillion-parameter models are difficult: define the memory estimation scope first

    Once a model reaches the trillion-parameter scale, a single GPU can no longer hold the complete model state. A common mistake is to estimate only the memory used by weights. In real training, memory usage also includes master weights, gradients, optimizer states, activations, temporary communication buffers, and framework reserves.

    Using Adam-like optimizers and mixed-precision training as an example, let N be the total number of parameters.

    Memory component Typical precision Estimated formula
    Model weights BF16/FP16 2N
    FP32 master weights FP32 4N
    Gradients BF16/FP16 2N
    First moment FP32 4N
    Second moment FP32 4N
    Subtotal model states - approximately 16N

    If gradients are stored in FP32, the model state memory is approximately 18N. If N = 1e12, the model state memory is approximately 16 TB to 18 TB. This still does not include activations, temporary buffers, communication buckets, or additional optimizer states.

    A more complete estimate can be expressed as:

    1. Total memory ≈ Model state memory + Activation memory + Temporary buffer memory + Framework reserve memory
    2. Model state memory ≈ (Weights + master weights + gradients + first moment + second moment) × N

    Activation memory usually depends on batch size, sequence length, number of layers, hidden dimension, attention implementation, and whether recomputation is enabled. For long-context or multimodal inputs, activation memory may become significantly larger than model state memory, so it needs to be evaluated carefully.

    Conclusion: before adapting trillion-parameter training, engineers must clarify what “16 TB” actually includes. Whether it includes gradients, optimizer states, activations, and communication buffers directly affects the sharding strategy, parallelism strategy, and checkpoint plan.

    3. Adapting to domestic compute platforms: three alignment layers

    The core of adapting to domestic or self-developed compute platforms is to bridge the gap between model definition and hardware execution. It is recommended to work through three alignment layers:

    1. Operator alignment
    2. Precision alignment
    3. Software stack alignment

    Each layer should have an acceptance checklist.

    3.1 Operator alignment: high-frequency operators must be benchmarkable

    Special attention should be paid to high-frequency operators such as matrix multiplication, LayerNorm, Softmax, Attention, RoPE, SwiGLU, Embedding, AllReduce, AllGather, and ReduceScatter.

    Recommended acceptance items:

    • Does the operator have a high-performance implementation on the target hardware?
    • Is its numerical behavior consistent with mainstream platforms?
    • Does it support the required data types, such as BF16, FP16, or FP8?
    • Does it support common patterns such as variable-length sequences, masks, and causal attention?
    • Are operator-level benchmarks and regression tests available?

    3.2 Precision alignment: convergence alone is not enough; convergence curves should also be compared

    The floating-point implementation, accumulation order, and compiler optimizations on domestic hardware may differ from mainstream platforms. It is recommended to establish a layered validation mechanism.

    Validation layer Recommended method Reference threshold
    Single-operator forward Compare with reference implementation For key operators, initial maximum relative error should preferably be around 1e-3
    Single-operator backward Compare gradient direction and values Use 1e-2 as a coarse filter first, then tighten gradually
    Single-layer module Compare LayerNorm and Attention outputs Monitor NaN, Inf, and norm drift
    Small-model convergence Fix random seeds and compare loss curves Early-stage loss difference should not be too large
    Full training pipeline Observe multiple GPUs, multiple nodes, and long steps Use loss, grad norm, and throughput stability as criteria

    Note: error thresholds are not absolute standards. The final judgment should be based on model convergence, numerical stability, and business evaluation.

    3.3 Software stack alignment: version matrix and rollback plan must be prepared in advance

    The software stack for domestic compute platforms often includes training frameworks, communication libraries, operator libraries, compiler optimizations, drivers, and firmware. A version matrix should be established.

    Software layer Acceptance content Rollback method
    Training framework API compatibility and availability of distributed interfaces Switch to a compatible version or patch package
    Communication library Stable AllReduce, AllGather, and ReduceScatter Switch to an alternative communication backend
    Operator library Performance and numerical correctness of high-frequency operators Roll back the operator library or disable fused optimizations
    Compiler optimization Graph optimization, memory reuse, kernel fusion Disable some compiler options
    Driver and firmware Device recognition, fault isolation, and monitoring reporting Roll back the driver version or isolate the node

    3.4 Domestic platform adaptation checklist

    Layer Common components Acceptance criteria Common failures Handling approach
    Operator library GEMM, Attention, LayerNorm Performance, numerical results, and boundary inputs pass Result deviation or performance regression Roll back operator version or disable fusion
    Communication library Collective communication, topology awareness Stable multi-GPU bandwidth without long-tail latency Communication stalls or timeouts Adjust process groups, reconnect, or switch backends
    Compiler optimization Graph compilation, memory reuse Controllable peak memory OOM or numerical anomalies Disable optimizations or reduce fusion level
    Driver and firmware Device management and monitoring Observable device status Device loss or slow nodes Isolate nodes or replace hardware
    Training framework Distributed training interfaces Correct loading, sharding, and synchronization Checkpoint failure or abnormal gradients Roll back framework version or apply patches

    4. How to use FSDP2: differences from FSDP1 and selection advice

    Fully Sharded Data Parallel, or FSDP, is a common solution for ultra-large model training. It shards parameters, gradients, and optimizer states across compute units and gathers the required shards during forward and backward computation, reducing memory pressure on each GPU.

    Compared with the previous generation, FSDP2 emphasizes per-parameter sharding and a sharding abstraction based on DTensor. For complex training scenarios that need to combine tensor parallelism, pipeline parallelism, expert parallelism, or other strategies, FSDP2 is usually easier to compose and extend.

    However, if you already have a stable FSDP1 pipeline and the model scale, parallelism strategy, and software stack have all been validated, there is no need to migrate immediately just because a new version exists.

    Common FSDP2 selection advice:

    Scenario Recommendation
    Single model, single parallelism dimension FSDP2 or stable FSDP1 is acceptable
    Need to combine heterogeneous multimodal modules Prefer FSDP2 per-parameter sharding
    Need to combine with Tensor Parallel or Pipeline Parallel Prefer FSDP2
    Already have a long-running FSDP1 baseline Keep the baseline first and migrate gradually
    Operators on domestic hardware are not fully validated Run small-scale comparison experiments first

    The following code is an API-level illustration and is not intended to be run as-is. The minimum prerequisites include installing a compatible PyTorch version, initializing the distributed process group, creating a device mesh, and ensuring the model, optimizer, and data loader are ready. On domestic platforms, the communication backend and device type must be replaced with the corresponding implementations.

    1. import torch
    2. import torch.distributed as dist
    3. from torch.distributed.fsdp import fully_shard
    4. from torch.distributed.device_mesh import init_device_mesh
    5. # Example only: replace the backend and device type based on the target hardware.
    6. dist.init_process_group(backend="nccl")
    7. world_size = dist.get_world_size()
    8. mesh = init_device_mesh("cuda", (world_size,), mesh_dim_names=("dp",))
    9. # After the model is built, apply sharding to each Transformer block.
    10. for block in model.layers:
    11. fully_shard(block, reshard_after_forward=True)
    12. # Apply sharding to the whole model.
    13. fully_shard(model)
    14. # Forward and backward are handled by the framework, including All-Gather and Reduce-Scatter.
    15. loss = model(input_ids, attention_mask)
    16. loss.backward()

    Key points:

    • Modules wrapped by fully_shard register their parameters in a sharded state.
    • Before the forward pass, parameters are gathered with All-Gather.
    • After the forward pass, parameters can be resharded according to policy.
    • During backward, gradients are reduced and scattered with Reduce-Scatter.

    5. Configuring the complete training pipeline: loading, scheduling, and synchronization

    5.1 Model loading: avoid blowing up peak memory

    A trillion-parameter model cannot be fully loaded and then sharded. Two common approaches are:

    • Sharded construction: build layer by layer and shard immediately after construction. This is suitable for building the model from scratch.
    • Sharded checkpoint: load pre-sharded checkpoints directly. This is suitable for resuming training.

    Engineering teams should also pay attention to data security and compliance:

    • Training data access should have permission isolation.
    • Checkpoint directories should follow the principle of least privilege.
    • Important checkpoints should include integrity verification.
    • When sensitive data or domestic supply chain requirements are involved, version lists and audit records should be retained.

    5.2 Sharding scheduling: when to gather and when to release

    Sharding scheduling determines the balance between memory and communication. If parameters are not currently used by the compute unit, they should remain sharded. If they are about to participate in forward or backward computation, they can be prefetched in advance.

    Illustrative configuration:

    1. # Whether to reshard immediately after forward pass; balance memory usage against additional communication.
    2. fully_shard(block, reshard_after_forward=True)
    3. # Increasing prefetch can improve communication-computation overlap but may increase memory pressure.
    4. # Refer to the official FSDP2 documentation for API details.

    Recommendations:

    • When memory is tight, enable more aggressive resharding.
    • When communication is the bottleneck, increase prefetch and bucketing appropriately.
    • For long-sequence training, pay close attention to peak activation memory.
    • For multimodal training, use different strategies for different submodules.

    5.3 Gradient synchronization: hide communication behind computation

    After backward propagation, each shard produces local gradients. These gradients need to be reduced and scattered back to the corresponding shards through Reduce-Scatter. Then a distributed optimizer updates the corresponding parameter shards.

    Common optimizations include:

    • Bucketing: combine many small gradients into larger buckets to improve communication efficiency.
    • Communication compression: reduce communication volume in bandwidth-limited scenarios, but evaluate the impact on accuracy.
    • Topology-aware process groups: prioritize communication within the same node or high-bandwidth domain.
    • Communication-computation overlap: a key technique for improving throughput.

    6. Special considerations for multimodal training

    Multimodal models are more complex than pure text training. Vision encoders, text encoders, and cross-modal fusion modules differ significantly in structure, operator density, and memory distribution. The same sharding strategy cannot simply be applied to all of them.

    Recommendations:

    • Use different parallelism strategies for vision towers and language towers.
    • Image and video inputs produce larger activations, so activation recomputation should be considered.
    • Data decoding, alignment, and augmentation may become CPU bottlenecks and need to overlap with training computation.
    • Fusion modules should be monitored carefully for cross-modal communication and memory peaks.

    Illustration:

    1. # Vision towers often receive high-resolution inputs and produce large activations, so more aggressive sharding and recomputation may help.
    2. for block in vision_model.blocks:
    3. fully_shard(block, reshard_after_forward=True)
    4. # Language towers may have long sequences and heavy context, so sequence parallelism and activation recomputation can be considered.
    5. for block in llm_model.layers:
    6. fully_shard(block, reshard_after_forward=False)
    7. # Manage memory peaks for fusion modules separately.
    8. for module in fusion_model.modules():
    9. fully_shard(module, reshard_after_forward=True)

    7. Software stack and infrastructure: a neutral selection perspective

    Large-scale training usually depends on containerized scheduling, distributed storage, object storage, logging and monitoring, message queues, and other infrastructure capabilities. Cloud infrastructure platforms can provide unified resource management, observability, and operational support. However, selection should be based on task scale, compliance requirements, ecosystem compatibility, and cost boundaries.

    Suitable conditions:

    • Training tasks are large and require unified scheduling and fault isolation.
    • Training data volume is large and requires high-throughput storage and fast checkpoint read/write.
    • Real-time monitoring of compute utilization, GPU memory, communication, and failures is required.
    • Containerized delivery and versioned rollback are required.

    Alternative options:

    • Self-built clusters
    • Private cloud environments
    • Other public cloud platforms
    • Hybrid cloud combined with local IDC

    Selection boundaries:

    • For small-model experiments, prioritize ease of use.
    • For trillion-parameter training, focus more on network topology, storage bandwidth, and fault recovery.
    • If domestic supply chain requirements apply, confirm compliance lists for chips, drivers, operator libraries, and communication libraries.
    • For data-sensitive workloads, prioritize permission isolation, encryption, auditing, and checkpoint protection.

    8. Best practices and troubleshooting: handling OOM, slow nodes, and communication bottlenecks

    8.1 Tuning recommendations

    • First validate loading, sharding, synchronization, and backward across the full pipeline with a small model.
    • When numerical anomalies occur, investigate precision and operator behavior first instead of blindly tuning parameters.
    • Communication-computation overlap is key to throughput.
    • Checkpoints should be saved in smaller, more frequent steps to reduce recovery cost.
    • Establish metric baselines and continuously track throughput, memory usage, communication ratio, and slow nodes.

    8.2 Troubleshooting table

    Symptom Detection metrics Log fields Handling steps
    Training becomes slower Per-step time, tokens/s, P50/P95 latency step, rank, host, device, elapsed Compare against historical baseline, locate slow nodes, isolate abnormal nodes, check data reading and network
    GPU OOM allocated, reserved, peak memory, sharding state peak_memory, batch, seq_len, reshard Reduce batch size, enable activation recomputation, adjust prefetch, enable resharding, evaluate offload
    Communication bottleneck Communication ratio, AllGather/ReduceScatter time comm_time, bucket, rank, topology Adjust bucketing, increase prefetch, optimize process groups, check network congestion
    Numerical anomaly loss, grad norm, loss scale, NaN/Inf loss, grad_norm, step, optimizer Disable abnormal optimizations, fix random seeds, compare layer by layer, roll back software stack version
    Checkpoint failure Write time, failure rate, integrity verification ckpt_time, rank, path, status Check storage permissions and bandwidth, add retries, switch to backup checkpoint

    8.3 Monitoring metric baselines and threshold suggestions

    Metric Recommended focus Reference threshold
    Throughput tokens/s, steps/s Investigate if fluctuation exceeds 20% compared with baseline
    Peak GPU memory Peak memory per GPU Sustained usage above 90% should be treated as high risk
    Communication ratio Communication time / per-step time Optimize if continuously above 30% to 40%
    Slow nodes Per-GPU per-step time relative to median Investigate if more than 2 times the median
    Checkpoint time Save and recovery time per operation Should be kept within an acceptable window, such as 15 minutes or less

    9. FAQ: how to choose FSDP2 and avoid common mistakes

    1. Is FSDP2 always required?

    Not necessarily. If the existing FSDP1 pipeline is stable and the model scale and parallelism strategy have been validated, you can continue using FSDP1. If you need more flexible per-parameter sharding and composable parallelism, you can evaluate FSDP2.

    2. What are the main differences between FSDP2 and FSDP1?

    FSDP1 often flattens parameters to improve communication efficiency. FSDP2 emphasizes per-parameter sharding and the DTensor abstraction, making it more suitable for complex parallelism combinations.

    3. What should I do when OOM occurs?

    Check activation memory, batch size, sequence length, prefetch depth, whether activation recomputation is enabled, whether resharding after forward is enabled, and whether optimizer sharding or CPU offload is enabled.

    4. How should I locate communication bottlenecks?

    First check the communication ratio and the time spent on AllGather and ReduceScatter. Then check process group topology, inter-node bandwidth, bucket size, and prefetch strategy. If there is obvious long-tail latency, prioritize checking slow nodes and network congestion.

    5. How can I verify whether adaptation to a domestic platform is reliable?

    It is recommended to perform three layers of validation:

    1. Operator benchmarks
    2. Module-level numerical comparisons
    3. Small-model convergence tests

    After these pass, expand to multiple GPUs, multiple nodes, and the full training pipeline.

    10. Conclusion

    Adapting trillion-parameter large model training on domestic compute platforms is a system engineering problem that requires collaboration between software and hardware.

    FSDP2 provides a flexible foundation for large-scale, multimodal, and mixed-parallel training through sharding abstractions and composability. However, efficient and stable training ultimately depends on a complete closed loop covering:

    • Memory estimation
    • Operator accuracy
    • Software stack alignment
    • Sharding scheduling
    • Communication optimization
    • Checkpoint protection
    • Troubleshooting and monitoring

    For developers, building engineering methodology is more important than memorizing individual APIs:

    • Validate the pipeline before scaling up.
    • Ensure numerical stability before pursuing peak throughput.
    • Establish metric baselines before tuning and rollback.