Trillion-Parameter LLM Training on Domestic AI Accelerators: Parallelism Strategy, FSDP Pipeline, and Debugging Guide

    A practical, system-level guide to adapting China's domestic AI accelerators for trillion-parameter LLM training. It walks through the three-stage adaptation path (software stack, parallelism strategy, training pipeline), provides an operator coverage matrix with validation methods and fallbacks, compares DDP/FSDP/TP/PP/EP, shows an illustrated FSDP training loop with its memory-timing details, gives a per-device memory estimation formula with a worked 2.8-trillion-parameter example, and covers checkpoint loading and resume validation, gradient-synchronization risk handling, and a symptom-based troubleshooting table. Readers get concrete pre-flight checks, acceptance criteria, and a troubleshooting order they can apply before launching large-scale training.

    1. Bottom Line First: Adapt Domestic Accelerators in Three Stages

    Bringing domestic AI accelerators up to trillion-parameter models is not a point optimization. It is a three-stage serial project: software stack adaptation (making the hardware visible to the framework) → parallelism strategy (making the model shardable and computable) → training pipeline (loading, scheduling, and synchronization all working end to end). If any of the first three falls short, the effort invested in the next one is wasted.

    Before launching large-scale training, clear five checkpoints:

    1. Key operators (attention, normalization, matmul, MoE routing, collective communication) have implementations on the target chips, and each has been validated against a reference implementation.
    2. Memory has been estimated item by item with the formula below; sharding size and parallelism degrees are fixed, with 10%–20% headroom.
    3. The parallelism combination is explicit (FSDP as the base, TP/PP/EP layered on as needed) rather than default full data parallelism.
    4. Checkpoint shard mapping, length and hash validation scripts are ready, and the resume-from-checkpoint rollback path has been verified.
    5. Monitoring covers per-device memory, communication time, per-step throughput, gradient norm, and NaN/Inf counts, with alerts that actually reach the on-call engineer.

    2. Why Trillion-Parameter Models Stress the System, Not the Algorithm

    At 2.8 trillion parameters, even with mixed-precision storage, parameters alone take roughly 5.6 TB (BF16, 2 bytes per parameter, decimal). Add gradients and optimizer states and the total reaches tens of terabytes — far beyond the physical memory of any single server. “Fit the whole model on one card” is dead. The model must be split across hundreds to thousands of accelerators that compute in coordination.

    Multimodal architectures amplify the difficulty further: heterogeneous encoding branches for text, image, and audio differ markedly in operator structure and memory footprint, which leads to unevenly distributed memory peaks and more complex communication patterns. The real bottleneck is therefore no longer “can it be computed” but three questions: how to split the computation, how to schedule data across hardware with minimal overhead, and how to update parameters while preserving numerical correctness.

    3. Three Gaps in Domestic Accelerator Adaptation

    • Hardware capability gap: accelerator cards from different vendors differ in precision support, memory bandwidth, and inter-card interconnect topology. Training frameworks cannot reuse code directly; the low-level operator libraries need targeted adaptation and optimization.
    • Software stack gap: mainstream frameworks’ parallelism primitives are often deeply coupled to a specific hardware ecosystem. A domestic chip must supply a complete, stable supporting stack that “translates” hardware capabilities into computation interfaces the framework can recognize.
    • Parallelism strategy gap: pure data parallelism is infeasible at trillion-parameter scale because of memory redundancy. Parameter, gradient, and optimizer-state sharding is mandatory, which depends on strong framework support for sharded parallelism.

    The value of adaptation is bridging these three layers so the model can “run, run stably, and run correctly.”

    4. Software Stack Adaptation: The Translation Layer and the Operator Coverage Matrix

    The supporting stack consists of the driver, runtime, operator library, communication library, and framework adaptation layer. It converts the upper framework’s compute and communication instructions into low-level operations the domestic accelerators can execute. The work falls into three main lines:

    1. Operator coverage and correctness validation: every operator in the computation graph has an implementation, and its numerical consistency is verified against a reference implementation.
    2. Communication primitives: reliable AllGather, ReduceScatter, AllReduce, AllToAll, and P2P for intra-node and inter-node data exchange — this is what makes scaling possible.
    3. Framework-level integration: parallel scheduling, memory management, mixed precision, and gradient accumulation all behave correctly on the domestic cards.

    Early in a migration, use a coverage matrix to accept items one by one, so you don’t discover a missing operator only after things start running:

    Operator category Typical operators Verification method Fallback if it fails
    Attention FlashAttention/SDPA, variable-length masks Compare against an eager implementation, including long sequences and variable-length batches Fall back to a blocked implementation, or reduce sequence length and split into batches
    Normalization RMSNorm/LayerNorm Extreme-value tests (including inf inputs) and dtype boundary tests Replace with an elementwise composition
    Matmul GEMM, GroupedGEMM Cover common tile sizes and transpose combinations, compare against an error threshold Change layout, split the operator
    MoE Routing, TopK, capacity dropping Compare against single-expert results, check load balance Disable the capacity limit, reduce the expert count
    Communication AllGather/ReduceScatter/AllToAll Correctness comparison on a small device count plus a bandwidth stress test on a large device count Degrade to hierarchical or two-stage communication
    Sparse and positional encoding RoPE, sparse attention Compare against a reference implementation Precompute and cache

    Set explicit pass/fail criteria for the comparison: use the fp32 reference as the baseline, fix the BF16 forward relative-error threshold and the gradient relative-error threshold in advance, and treat any exceedance as a failure while keeping the minimal reproduction case. Record results separately for each shape, so a failure can be traced to a specific tile or kernel selection problem.

    5. How to Choose a Parallelism Strategy: A Comparison Table

    Strategy What is split When it applies Main communication cost Typical problems
    Data parallel (DDP) Model is not split; a full replica per device Per-device memory holds params + gradients + optimizer states AllReduce of gradients once per step Memory redundancy; infeasible as the model grows
    Fully sharded data parallel (FSDP) Params, gradients, and optimizer states sharded along the DP dimension Memory constrained, a single layer fits, good inter-device bandwidth Per-layer AllGather + ReduceScatter in forward and backward Many communication ops; high demands on scheduling and overlap
    Tensor parallel (TP) Operators inside a single layer split along tensor dimensions A single layer does not fit on one device; high-bandwidth interconnect within the domain Multiple AllReduce/AllGather per layer, communication-intensive Communication-sensitive; gains drop sharply across nodes
    Pipeline parallel (PP) Layers or stages split across device groups Many layers, load can be balanced per stage P2P send/receive between adjacent stages Pipeline bubbles, load imbalance
    Expert parallel (EP) MoE experts spread across devices MoE architecture with enough experts AllToAll for routing and back-propagation Load skew, hot experts

    In practice the combination is usually TP (high bandwidth inside a node) + PP (stage split across nodes) + FSDP (sharding along the DP dimension) + EP (the MoE dimension): fix TP/PP/EP first, then let FSDP consume the remaining memory.

    6. Fully Sharded Data Parallel: Balancing Memory and Compute

    Fully sharded data parallel is the mainstream solution for ultra-large model training under memory constraints. It shards model parameters, gradients, and optimizer states across devices along the data-parallel dimension, so each device normally holds and updates only the portion it owns. Compared with conventional data parallelism it delivers two benefits:

    • Large memory reduction: the three state categories are spread across all devices, so per-device pressure drops proportionally, and a trillion-parameter model can be trained within limited memory.
    • Predictable communication: communication volume scales linearly with model size, which makes it feasible to hide latency through compute–communication overlap.

    The cost is that forward and backward passes must dynamically all-gather full parameters layer by layer, then release the memory after computing and reduce-scatter the gradients. The granularity of the sharding schedule therefore determines training efficiency directly.

    A schematic training loop follows (when the framework natively supports sharded parallelism, the runtime orchestrates this sequence automatically):

    1. for step in range(total_steps):
    2. # ---------- Forward: all-gather layer by layer -> compute -> release immediately ----------
    3. for layer in model.layers:
    4. params = all_gather(layer.shard) # all-gather the full parameters of this layer
    5. out = layer.forward(inputs, params)
    6. del params # release the gathered buffer as soon as forward ends
    7. save_for_backward(out) # cache the activations needed by backward
    8. # ---------- Backward: re-gather layer by layer -> compute grads -> shard-reduce ----------
    9. for layer in reversed(model.layers):
    10. params = all_gather(layer.shard) # re-gather in backward (or recompute forward)
    11. grad_full = layer.backward(pop_activation(), params)
    12. grad_shard = reduce_scatter(grad_full) # shard-reduce gradients across devices
    13. layer.grad = grad_shard # keep only the shard this device owns
    14. del params, grad_full
    15. # ---------- Update: only the local shard ----------
    16. check_grad_finite() # NaN/Inf check, see section 7
    17. optimizer.step() # update only the local shard
    18. optimizer.zero_grad()
    19. scheduler.step()

    Important: the code above is conceptual. It is simplified to focus on memory timing, and a production implementation must fill in the following details or it cannot be used for real training:

    • Per-layer re-gathering: backward does not reuse the parameters gathered during forward (that would cancel out the memory savings); it all-gathers again and releases immediately. If activation recomputation is enabled, forward runs a second time using re-gathering.
    • Gradient shard reduction: after reduce-scatter each device holds only the gradients for its own shard. Gradient accumulation must happen on the same shard to avoid redundant reduction across micro-batches.
    • Parameter update: the optimizer steps only on the local shard, and optimizer state (first and second moments, fp32 master weights) is stored sharded in exactly the same layout as the model shards.
    • Memory reclamation timing: the lifetimes of three kinds of memory — gathered buffers, communication scratch space, and activation caches — must be managed explicitly. Too deep a prefetch trades memory for throughput and has to be tuned against the formulas in section 8.
    • Mixed-precision details: the dtype of gradient reduction, scaling before reduction (to avoid fp16 overflow), and the mapping between fp32 master weights and BF16 compute weights must all be specified explicitly at the framework layer.

    7.1 Model Loading: Turn “Hope It Doesn’t Crash” into Verifiable Steps

    Model loading splits hundreds of billions or trillions of weight parameters according to the sharding rules and places each shard on its target accelerator. Do not rely on “run it once and see if it breaks.” Execute these verifiable steps:

    1. Shard format check: confirm each rank’s shard file naming rules and shard index match the global metadata, and that the summed parameter count exactly equals the declared model parameter count.
    2. Shard mapping validation: generate a “global parameter name → (rank, offset, shape)” mapping table and verify that the parallelism degrees (TP/PP/DP) match those used when the checkpoint was saved. If you need to reshard to a different parallelism degree, validate the resulting mapping offline first.
    3. Memory alignment: read shards on the alignment boundary the framework requires (commonly 128 or 256 bytes) and stream large tensors in blocks, avoiding unaligned mmap or a single bulk read that spikes host memory.
    4. Length and hash validation: per shard, verify file length, CRC32/xxHash checksum, parameter element count (product of the shape), and dtype. Any mismatch means the shard is corrupt.
    5. Load order and peak control: load in a “read a shard → validate → copy to device → release the host buffer” pipeline so nothing stays resident in CPU memory and causes an OOM abort.
    6. Rollback on failed resume: write with a temporary file plus atomic rename (.tmp → final) and keep the last N complete checkpoints. If loading fails, use the validated shard list to locate what is missing and roll back directly to the most recent checkpoint that passed validation — never continue training from a half-loaded state.
    7. Consistency of auxiliary state: optimizer state, learning-rate scheduler, RNG state, and the data loader cursor must come from the same source and version as the model shards. Otherwise you get the silent failure of “weights are right but the training trajectory is broken.”

    7.2 Shard Scheduling: It Determines the Memory Peak and Overlap Efficiency

    Scheduling dynamically all-gathers parameters during computation and frees memory afterward, while keeping gather order strictly aligned with computation dependencies. Schedule quality directly determines both the memory peak and communication overlap efficiency, which makes it central to stability and throughput. The tunable items are: prefetch depth (number of layers prefetched), the offset between gathering and backward computation, the degree of parallelism between communication streams and compute streams, and — in MoE settings — the staggering of AllToAll against expert computation.

    7.3 Gradient Synchronization: Results and Risk Handling

    After backward completes, each device shard-reduces its local gradients so every shard holds globally consistent gradients, then hands them to the optimizer for the update. Synchronization must be complete and free of duplicates; otherwise numerical errors accumulate silently.

    Risk checks and responses to build into the training loop:

    • Gradient NaN/Inf: compute the global gradient norm every step and run an isfinite check. On a non-finite value, skip that step’s update immediately and log the step, layer name, and input sample. Repeated triggers indicate a data or numerical problem and should go to manual investigation.
    • Missing or duplicated shards: before and after reduce-scatter, validate the number of shards received on this device and the contribution bitmap, confirming each shard is covered by exactly one reduction. Where possible, compare checksums over the full gradient periodically.
    • Communication timeouts: set explicit timeouts for collectives. On timeout, dump each device’s heartbeat and last completed communication op to identify a slow card, a faulty link, or a throttled node; isolate the node before restarting the job.
    • Inconsistent optimizer state: periodically log each device’s step count and a lightweight checksum of its optimizer state. On mismatch, resynchronize to the majority rather than letting each device continue on its own.
    • Unified response: any of the above triggers “alert → save a checkpoint → roll back to the last stable version,” and the offending step goes on an isolation list so bad samples do not keep contaminating training.

    8. Memory Estimation Formula and Conventions

    Before launch, estimate per-device memory item by item with the conventions below, then decide sharding size and parallelism degrees:

    1. Per-device memory ≈ (parameter bytes + gradient bytes + optimizer state bytes + activations + communication buffers) / number of data-parallel shards
    2. + non-shardable portion (the shards TP/PP leave on this device)

    Conventions for each term:

    • Parameter bytes = parameter count × precision factor (BF16/FP16: 2, FP32: 4)
    • Gradient bytes = parameter count × gradient precision factor (usually the same precision as parameters; under mixed precision, an fp32 copy must be counted separately)
    • Optimizer state bytes = parameter count × bytes per parameter (Adam commonly uses fp32 master weights 4 + first moment 4 + second moment 4 = 12)
    • Activations ≈ layers × per-layer activation × micro-batch × sequence length, strongly affected by the activation recomputation strategy
    • Communication buffers = prefetch depth × per-layer parameter bytes + collective scratch space

    Take 2.8 trillion parameters with BF16 training and Adam as an example: parameters ≈ 5.6 TB, gradients ≈ 5.6 TB, optimizer states ≈ 33.6 TB, total ≈ 44.8 TB. Spread over 1024 devices that is about 44 GB per device (decimal), leaving roughly 20 GB on a 64 GB card for activations and communication buffers.

    Important: these figures depend on model structure, the parallelism combination, sequence length and batch partitioning, and framework implementation details (whether all-gather is blocked, whether gradient accumulation is used, whether activation recomputation is enabled). They are an order-of-magnitude reference only. In practice, measure peak memory on a small model, extrapolate linearly by parameter count, and reserve 10%–20% headroom.

    9. Common Problems and Troubleshooting Order

    Symptom Check first Common causes and fixes
    Out-of-memory (OOM) Memory breakdown Lower micro-batch and prefetch depth first, then enable activation recomputation, and adjust the parallelism combination last
    all-gather timeout Device heartbeats and last op Isolate the slow card or faulty link; check whether prefetch depth is too large and causing queuing
    Gradients do not converge Gradient norm curve, data shard cursor Check whether checkpoint state is complete, whether LR scaling follows device count, and whether data is duplicated or misaligned
    Throughput jitter Per-step time distribution and communication share Check hot experts, load imbalance, storage/network jitter, and logging/monitoring collection overhead
    Checkpoint restore fails Shard validation list Locate the corrupt shard using the validation steps in section 1 and roll back to the last stable version

    Troubleshoot in the order “observe first, reproduce second, tune parameters last”: collect the metrics, reproduce with a minimal model, and only then change high-cost variables such as parallelism degrees.

    10. Scope and Closing

    The boundaries need to be stated clearly: fully sharded data parallel mainly solves the memory footprint and communication overhead problem. It does not automatically resolve every scaling bottleneck. Trillion-parameter multimodal training still needs tensor parallelism (splitting a single layer), pipeline parallelism (splitting layers), expert parallelism (splitting MoE experts), operator fusion (reducing kernel launch and memory-access overhead), and communication optimization (topology-aware, hierarchical reduction, preferring high bandwidth within a topology domain). If the model fits on one card, if the bottleneck is operator efficiency, or if a single layer is too large to all-gather inside one node, FSDP is not the first choice.

    Engineering rollout also means managing risk: large-scale training needs off-site backup of data and checkpoints, a defined rollback plan for failed resumes, monitoring of numerical drift (long-term shifts in loss and gradient distributions), and budget/quota alerts for insufficient compute capacity and cost overruns.

    Adapting domestic accelerators for trillion-parameter models is fundamentally systems engineering. It tests not just raw hardware compute, but the completeness of the software stack, the precision of the parallelism strategy, and the reliability of the training pipeline. With fully sharded data parallelism at the core, getting model loading, shard scheduling, and gradient synchronization right one link at a time — each backed by executable validation — is the critical path to putting an ultra-large model on domestic hardware.

    FAQ

    How does fully sharded data parallel differ from ordinary data parallelism?
    Ordinary data parallelism keeps a full model replica on every device and synchronizes only gradients. Fully sharded data parallel shards parameters, gradients, and optimizer states across devices, and temporarily all-gathers parameters layer by layer during forward and backward, releasing them right after. Memory usage drops to roughly 1/N, at the cost of significantly more communication.

    How should you select domestic accelerators for training?
    Start with four things: operator coverage and measured accuracy for the target model, intra-node and inter-node interconnect bandwidth, per-device memory and memory bandwidth, and the stability of the software stack version plus community support. Before deciding, run the same small model end to end on each candidate platform and compare throughput, peak memory, and numerical comparison results — not just paper peak compute.

    When is fully sharded data parallel not a good fit?
    When the model fits on a single device (DDP communicates less); when a single layer is too large to all-gather within one node (use tensor parallelism instead); when the bottleneck is operator efficiency rather than memory; and in MoE workloads with severe load skew, where expert parallelism should take priority.