Training Trillion-Parameter LLMs on Domestic AI Accelerators: FSDP2 Sharding, Adaptation, and Tuning
As large-model parameter counts scale from hundreds of billions into the trillions, training engineering shifts from "can a single GPU do more" to "how do we load, shard, compute, synchronize, and stably converge a full model under limited memory, limited interconnect bandwidth, and a complex software stack." Using Fully Sharded Data Parallel (FSDP2) as its main thread, this article covers three core areas—model loading, sharding scheduling, and gradient synchronization—alongside engineering notes on multimodal training, adapting to domestic AI accelerators, monitoring and tuning, and risk control, to help developers build a runnable, scalable, reproducible, and debuggable training pipeline.
Introduction: A New Problem, from Single Machine to Distributed
When large-model parameter counts grow from the hundreds-of-billions range into the trillions, the training-engineering problem is no longer “can a single card compute a little more.” It becomes “how do we fully load, shard, compute, synchronize, and stably converge the model under limited memory, limited interconnect bandwidth, and a complex software stack.” For domestic train-and-inference accelerator cards, adaptation is not simply a matter of porting model code; it means rebuilding a runnable, scalable, reproducible, and debuggable training pipeline within a new hardware and software ecosystem.
This article uses Fully Sharded Data Parallel (FSDP2) as its main thread and centers on three key areas—model loading, sharding scheduling, and gradient synchronization—supplemented by engineering points on multimodal training, domestic accelerator adaptation, monitoring and tuning, and risk control, to help developers form a practical, deployment-oriented training-adaptation methodology.
1. Three Engineering Challenges of Trillion-Parameter Training
1.1 The Memory Wall: Parameters, Gradients, and Optimizer States Must Be Sharded
The first hurdle for trillion-parameter training is memory capacity. Taking mixed-precision training as an example, GPU memory is mainly consumed by weights, gradients, optimizer states, activations, communication buffers, and framework runtime overhead.
A rough estimate can be expressed with this formula:
M_device ≈ (B_weight + B_grad + B_opt) × P / S + M_activation + M_comm + M_runtime
where P is the number of model parameters, S is the effective sharding or parallelism capacity, and B_weight, B_grad, and B_opt are the per-parameter byte counts for weights, gradients, and optimizer states respectively. At the trillion-parameter scale, even with a low-memory optimizer, the optimizer states and gradients alone can still reach the TB range. Therefore, parameters, gradients, and optimizer states must be sharded and stored across devices rather than fully resident on a single card.
Three preconditions deserve attention. First, whether the model uses mixed precision. Second, whether the optimizer states and gradients use low-precision or low-memory representations. Third, whether there are additional sharding dimensions such as tensor parallelism, pipeline parallelism, or expert parallelism. If these conditions are unclear, both the memory estimate and the sharding strategy are prone to distortion.
1.2 The Communication Wall: Communication Overhead Determines Scaling Efficiency
Naive data parallelism is simple to implement but fully replicates model parameters, so memory usage rises linearly with model size. Introducing parameter sharding relieves memory pressure but adds new communication patterns: parameters must be aggregated before the forward pass, and gradients must be reduced after the backward pass. If communication cannot overlap with computation, a large amount of compute in the cluster sits idle waiting for communication, and scaling efficiency drops quickly.
Thus the optimization goal for sharded training is not merely “splitting it apart,” but also “keeping it computing” and “keeping the waiting low.” Communication topology, interconnect bandwidth, communication-library implementation, and how parallelism dimensions are partitioned all affect final throughput.
1.3 Convergence and Stability: Once It Runs, It Must Run Steadily
Ultra-large models are highly sensitive to numerical precision, learning-rate scheduling, gradient clipping, and mixed-precision strategy. Differences in operator implementations, reduction order, loss-scaling strategies, or data-sampling logic can all manifest as loss oscillation, abnormal gradient norms, or even training divergence.
The goal of adaptation should therefore not stop at “it starts,” but must ensure numerical alignment, reproducible training, diagnosable anomalies, and actionable recovery.
2. FSDP2: Core Mechanisms and Adaptation Boundaries of Fully Sharded Data Parallel
Fully Sharded Data Parallel is one of the mainstream paradigms for resolving the tension between memory and communication in trillion-parameter training. Its basic idea is to evenly shard model parameters, gradients, and optimizer states across the parallel group, so that each card stores only one shard of the full state. As the number of participating devices grows, the resident per-card parameter state decreases approximately linearly.
Note that in the context of this article, FSDP2 mainly refers to implementations represented by the fully_shard family of interfaces in the PyTorch ecosystem. Across different training frameworks and different domestic accelerator software stacks, the specific function names, wrappers around communication primitives, and memory-management mechanisms may differ. So when migrating and adapting, don’t just look at API names—also check whether the underlying collective communication, memory allocation, asynchronous execution, and operator implementations are equivalent.
2.1 Key Designs of FSDP2
Compared with earlier sharding schemes, FSDP2 usually emphasizes the following capabilities:
- Sharding at single-parameter granularity, which makes it easier to handle mixed precision, resharding, and memory release more flexibly.
- Introducing a distributed-tensor abstraction so that sharded parameters and gradients still retain logical-shape information, making it easier to combine with strategies such as tensor parallelism and pipeline parallelism.
- Prefetching communication across the forward and backward phases to hide parameter aggregation and gradient reduction as much as possible under computation.
Its core communication primitives mainly come in two kinds. Before the forward or backward computation, all-gather temporarily reconstructs complete parameter blocks. After the backward computation finishes, reduce-scatter performs gradient reduction and shard distribution. Understanding when these two primitives fire is the prerequisite for sharding scheduling and performance tuning.
2.2 Common Questions and Issues
What is FSDP2?
It is a data-parallel approach that shards model state across multiple devices for storage, suited to cases where the model is too large to fit on a single card.
How do you configure it?
You generally need to specify the device mesh, sharding dimension, mixed-precision policy, communication-overlap strategy, and optimizer-state sharding scheme. If combined with tensor or pipeline parallelism, you must also define the communication groups and topology for each parallelism dimension.
What are common errors?
Typical problems include poorly designed device-mesh dimensions, parameters being aggregated too early (which raises the memory peak), incorrect resharding timing, gradient reduction not properly chained, gradient overflow under mixed precision, and checkpoints inconsistent with the sharding strategy.
3. Breaking Down the Key Stages of the Training Pipeline
3.1 Model Loading: From Full Weights to a Shardable State
The first step of the training pipeline is to load the full weights from disk and convert them into a shardable distributed state. At the trillion-parameter scale, loading the full weights in a single process will almost certainly hit memory or GPU limits, so sharded loading is typically used: each process reads and holds only the parameter shard that belongs to it.
Illustrative pseudocode:
# Example: building a fully sharded data-parallel training statemodel = build_model(config)mesh = build_device_mesh(mesh_config)shard_model = fully_shard(model, mesh=mesh)optimizer = build_optimizer(shard_model)load_sharded_checkpoint(shard_model, optimizer, checkpoint_path)
To guarantee reproducibility and operability, the following preconditions must be added beyond the pseudocode:
- Distributed launch method: clarify whether the job is launched inside a container, via a job scheduler, or via a command-line launcher, and confirm that node discovery, environment variables, port communication, device-ID mapping, and process-count configuration are correct.
- Device-mesh dimensions: the mesh should make the meaning of each dimension explicit. For example, one dimension can be used for data parallelism or replication, and another for parameter sharding; if combined with tensor or pipeline parallelism, the mesh should be extended accordingly, ensuring clear communication groups per dimension.
- Checkpoint format: a sharded checkpoint is recommended, saving model shards, optimizer states, the learning-rate scheduler, RNG states, the data-loader cursor, config version, and checksum information. The checkpoint layout must stay consistent with the current sharding strategy.
- Rollback on load failure: before loading, validate the manifest, shard count, parameter version, and integrity checksums. On failure, do not overwrite the last stable checkpoint—roll back to the most recent usable version and record the failure reason, process ID, and failed shard for easier diagnosis.
3.2 Sharding Scheduling: Hiding Communication Under Computation
Sharding scheduling determines when a card aggregates parameters and when it releases them. Poor scheduling can degrade all-gather into serial waiting, blocking expensive compute.
Three points to watch in practice:
First, prefetch depth. In the forward or backward pass, issuing parameter aggregation several modules ahead lets communication overlap with the current module’s computation. Too shallow a prefetch increases exposed communication; too deep a prefetch lengthens the time full parameters stay resident, raising the memory peak.
Second, resharding timing. Once a module finishes computing, the reconstructed full parameters should be released as soon as possible to reclaim memory, avoiding a peak overflow caused by multiple modules’ parameters being resident simultaneously.
Third, tuning observation metrics. When adjusting prefetch depth, observe communication exposure time, per-card memory peak, training throughput, and OOM risk. If throughput drops while the memory peak rises markedly, prefetching is too deep; if memory stays flat but throughput drops with clear communication waits, prefetching is insufficient.
3.3 Gradient Synchronization: Correctness and Efficiency of Reduction
After backpropagation finishes, each card holds the gradients for its data shard. A reduce-scatter is then needed to sum and reduce the gradients and distribute the corresponding shards to the optimizer for parameter updates.
Gradient synchronization requires checking the following:
- Overlap of reduction with the backward pass: ideally, when the backward pass reaches a given layer, that layer’s gradient reduction is triggered, rather than waiting for the entire backward pass to finish and then communicating all at once.
- Global consistency of gradient clipping: if global gradient clipping is used, ensure the gradient norm is computed at the global scale rather than clipping each local shard first. Different frameworks may implement this via distributed-norm computation; when adapting, confirm whether it correctly participates in reduce-scatter or global reduction.
- Handoff between mixed precision and loss scaling: low-precision gradients may underflow or overflow and must be correctly paired with the loss-scaling mechanism. With bf16, some scenarios may not need dynamic loss scaling, but you should still confirm that the gradient range, norm, and overflow-handling logic behave as expected.
Recommended numerical-alignment checks:
- Small-scale alignment: first compare forward outputs, loss, and gradients against a reference implementation using a smaller model or lower parallelism.
- Gradient finiteness: check whether grad_norm shows NaN, Inf, or abnormal spikes.
- Reduction correctness: for the same input, compare whether gradient-update directions match across different parallel configurations.
- Clipping order: confirm clipping happens on the post-reduction global view, avoiding scale inconsistency from local clipping.
- Loss-scaling chain: check whether scale-factor updates, unscaled loss, overflow counts, and skip-update logic are correct.
For debugging, proceed in this order. First disable mixed precision and verify the basic numerical chain. Then enable mixed precision to locate whether precision conversion or loss scaling is the cause. Next, check gradient clipping and reduction order. Finally, check whether communication groups, data order, or random seeds cause nondeterministic differences.
4. Special Considerations for Multimodal Training
Beyond the language branch, a multimodal model may also include a vision tower, an audio tower, or other encoders. Adapting such models is more complex and requires extra attention to:
- Uneven memory allocation: the language, vision, and audio towers differ in parameter count and activation volume, so sharding, micro-batching, and activation-recompute strategies must be evaluated separately.
- Batch allocation: input lengths vary widely across modalities; if one modality becomes a long tail, it drags down overall throughput. Record each modality’s maximum length, average length, padding rate, and sampling ratio.
- Sampling and alignment: cross-modal sample alignment, sampling ratios, and data mixes affect convergence and throughput, so maintain sampling logs.
- Operator validation: different modality modules may rely on different operators; validate correctness, performance, and support scope one by one on the target accelerator.
A reference checklist:
- Vision tower: parameter count, activation peak, input-resolution range, maximum batch.
- Language tower: sequence length, attention implementation, KV-cache or recompute strategy.
- Audio tower: sampling rate, frame length, variable-length input handling.
- Multimodal fusion: alignment layers, projection layers, loss weights, and gradient sources.
- Long-tail governance: monitor per-modality throughput, padding rate, and per-sample time distribution.
5. Engineering Practices for Adapting to Domestic AI Accelerators
Adapting on a domestic train-and-inference accelerator card usually goes through three stages: getting it to run, getting it to run stably, and getting it to run fast.
5.1 Getting It to Run: Operator Completeness and Functional Validation
A model involves a large number of operators, each of which must be checked for an equivalent implementation in the target software stack. Missing operators can be filled in via equivalent combinations, graph optimization, or custom kernels. After filling gaps, validate functional correctness first, then assess performance, to avoid diving into large-scale training with unaligned numerics.
5.2 Getting It to Run Stably: Numerical Consistency and Long-Run Stability
Numerical consistency is the foundation of training trustworthiness. Use a small-scale configuration to compare against a reference implementation, checking forward outputs, backward gradients, and parameter updates layer by layer. When no clear error threshold exists, use a small-scale result on the reference environment (within the same framework) as the baseline rather than judging correctness directly from large-scale runs.
Long training runs also need periodic checkpoints, resume-from-checkpoint, and monitoring of key metrics. At minimum, monitor loss, grad_norm, throughput, memory peak, communication exposure time, data-read time, and checkpoint-save status.
5.3 Getting It to Run Fast: Communication Library and Topology Adaptation
Collective communication primitives must be performance-validated on the target hardware topology. During adaptation, set communication grouping, stream parallelism, and communication concurrency sensibly, and try to keep high-frequency communication within high-bandwidth domains. If cross-node bandwidth in the cluster is limited, avoid placing high-frequency parameter aggregation or gradient reduction on cross-node paths.
5.4 Verifying Platform Capabilities: Scheduling, Storage, and Monitoring
Adapting to domestic compute is not only a single-card software-stack problem; it also involves job scheduling, storage, and observability. Such capabilities are usually provided by the cloud platform as general-purpose features, so engineering teams should verify the following interfaces or metrics:
- Compute scheduling: whether it supports multi-node, multi-card jobs, topology awareness, priority, queuing, preemption, and fault rescheduling.
- Storage: whether object storage or a shared file system supports sharded reads and writes of large files, version management, checksums, and resume recovery.
- Monitoring and alerting: whether it provides node, device, task, communication, throughput, and storage metrics, plus log search and alert configuration.
- Fault recovery: whether it supports job restart, checkpoint recovery, faulty-card isolation, and retry on failure.
These are general engineering capabilities; during selection, base decisions on actual interfaces, metric definitions, and verifiable capabilities.
6. Deployment-Oriented Optimization and Tuning
Once the training pipeline works end to end, you can optimize further around parallel strategy, memory optimization, communication scheduling, and monitoring metrics.
6.1 Combining Parallel Strategies
FSDP2 can be combined with tensor parallelism, pipeline parallelism, and other strategies. For trillion-parameter models, relying on data-parallel sharding alone may not meet both memory and communication requirements. Choose a suitable combination based on model structure, hardware topology, and communication bandwidth.
6.2 Activation and Memory Optimization
Activation recomputation or selective recomputation trades extra computation for a lower memory peak. During tuning, observe whether throughput drops significantly due to recomputation and whether the memory peak truly falls.
6.3 Topology-Aware Communication Scheduling
Arrange parallelism dimensions according to the cluster’s interconnect structure. For example, keep parameter aggregation and gradient reduction within the high-bandwidth in-node domain as much as possible, and leave low-bandwidth cross-node communication for infrequent operations.
6.4 Monitoring Metrics and Alert-Threshold Templates
Recommended monitoring table:
- Throughput: samples/sec/card or tokens/sec/card. Abnormal signals: sustained decline, irregular fluctuation, no recovery after job restart.
- Communication exposure time: time spent waiting for parameter aggregation or gradient reduction. Abnormal signals: markedly higher than baseline with a simultaneous throughput drop.
- Memory peak: the highest per-card memory usage during training. Abnormal signals: approaching or exceeding the memory budget, rising OOM risk.
- loss: training loss. Abnormal signals: NaN, Inf, no decrease for a long time, or severe oscillation.
- grad_norm: gradient norm. Abnormal signals: NaN, Inf, sudden spikes, or sustained abnormally high values.
- Checkpoint-save status. Abnormal signals: save failure, incomplete files, failed checksums.
Suggested thresholds: alert when the memory peak exceeds a high fraction of the budget; alert when throughput drops across several consecutive windows from baseline without resource changes; pause and analyze immediately when loss or grad_norm becomes non-finite; forbid overwriting the last stable version when a checkpoint checksum fails.
7. Risk Warnings: Long Training Runs Cannot Rely on Manual Inspection Alone
Trillion-parameter model training runs for a long time and is expensive, so risk-control processes must be designed in advance. Focus especially on data loss, checkpoint corruption, and recovery failure.
Recommended measures:
- Save checkpoints periodically, storing model state, optimizer state, and metadata separately.
- Keep multiple checkpoints, retaining at least the most recent several stable versions, so a single corruption doesn’t make recovery impossible.
- Add integrity checks to checkpoints, such as a manifest, shard counts, and checksums.
- Periodically rehearse the recovery process to confirm resume-from-checkpoint correctly restores the optimizer state, learning-rate scheduler, and data cursor.
- Set alerts on key metrics so problems don’t accumulate until late in training.
- Establish retry and manual-confirmation processes for job failures, node failures, and storage anomalies, avoiding auto-recovery overwriting valid state.
Conclusion
Adapting trillion-parameter model training is essentially about rebuilding a correct, stable, and efficient training pipeline under the triple constraints of memory, compute, and communication. With FSDP2 as the core—combined with rigorous model loading, sharding scheduling, gradient synchronization, numerical alignment, and monitoring-and-recovery mechanisms—plus engineering polish against the domestic accelerator’s software stack and the cluster topology, a huge parameter scale can truly translate into usable large-model capability.
For engineering teams, understanding the trade-offs, boundaries, and debugging paths of each stage matters more than relying on any single tool. That is also the core methodology of ultra-large-scale training adaptation.
