# Trillion-Parameter MoE Training on Domestic AI Accelerators: A Practical Adaptation Guide

    This article walks through the engineering work involved in adapting a 2.8-trillion-parameter MoE (Mixture-of-Experts) model to train on domestic AI accelerators. It covers how to profile the model's structural characteristics (total vs. activated parameters, expert parallelism, router numerics, multimodal inputs), how to align operators and precision across the hardware and software stack, how native FSDP2 sharding combines with tensor, expert, pipeline, and context parallelism, and how to wire model loading, shard scheduling, forward/backward execution, and gradient synchronization into one unbroken training path. It also details memory-ledger and MFU-based performance tuning, MoE and multimodal engineering pitfalls, checkpointing and elastic-scaling practices for long-running jobs, plus troubleshooting guidance and a three-step path to cloud-scale training.

    1. Background and Industry Trend

    A domestic AI chip vendor recently announced that it had completed training adaptation for a 2.8-trillion-parameter flagship MoE (Mixture-of-Experts) large model released by an open-source team. The adaptation ran on the vendor’s flagship AI training-and-inference accelerator along with its in-house software stack, and established a native FSDP2 multimodal training path that connects the entire chain from model loading and shard scheduling through to gradient synchronization. This kind of adaptation work is becoming a routine part of building out domestic compute ecosystems.

    What deserves attention is not the “adaptation succeeded” result, but the capability evolution behind it. Training a trillion-parameter model no longer stresses single-card compute alone; it simultaneously stresses operator completeness, the soundness of the parallelism strategy, the granularity of communication scheduling, and the numerical stability of the computation.

    From an engineering perspective, training a trillion-parameter model well on domestic accelerators is essentially the sum of three capabilities:

    • Software stack maturity: whether it provides the full set of operators required for training, mixed-precision support, and multi-card communication;
    • Depth of training framework adaptation: whether it can effectively use capabilities such as sharded parallelism and expert parallelism;
    • Systematic engineering operations: whether it can keep large-scale jobs stable, observable, and recoverable over long runs.

    The rest of this article is organized around these three layers.

    2. Step One: Understand the Structural Profile of the Trillion-Parameter MoE Model

    Adaptation starts with a clear technical profile of the model: parameter count, activation ratio, layer structure, attention variants, positional encoding scheme, and modality composition. Using the model adapted here as an example, the following characteristics deserve particular attention.

    2.1 Total and activated parameters are highly asymmetric

    The 2.8 trillion figure is the total parameter count, but each token only activates a small fraction of those parameters — typically a handful of experts plus the shared experts. This sparse structure has two direct consequences:

    • Memory pressure scales with total parameters, while compute scales with activated parameters. Parameter shards, optimizer states, and gradients fill up device memory, but MFU estimates must be computed from the actual activated parameter count, or they will be seriously overstated.
    • Memory and bandwidth bottlenecks appear before compute bottlenecks.

    2.2 Expert parallelism introduces an extra communication dimension

    Experts are typically distributed across different devices. Each token has to go through route → dispatch to the target expert → compute → collect the result, which corresponds to two global all-to-all communications. MoE training involves three main classes of communication:

    1. all-gather / reduce-scatter introduced by parameter sharding;
    2. all-reduce introduced by tensor parallelism;
    3. all-to-all introduced by expert parallelism.

    All three compete for the same interconnect bandwidth during the same time windows, and poor scheduling leaves many devices idle and waiting.

    2.3 Routing and load balancing are numerically sensitive

    The routing network (router) is usually a linear transformation followed by Softmax / Top-K. Under bf16 it easily produces a large number of “ties,” which can make the same token be assigned inconsistently across devices. MoE models may also use a load-balancing strategy with learnable biases. As a result, routing decisions must be computed in fp32 — a detail that directly determines whether parallel training can reproduce single-card results.

    2.4 Multimodal inputs make data shapes more complex

    Mixed text-and-image training has the following characteristics:

    • the vision encoder takes a sequence of image patches as input;
    • images are concatenated with text tokens after projection;
    • different samples contain different numbers of images at different resolutions, so sequence lengths vary widely.

    This affects both peak memory usage and sample packing and masking strategies.

    3. Hardware and Software Stack: Operator Coverage and Precision Alignment

    The basic operators required for training — matrix multiplication, normalization, activation functions, positional encoding, and so on — are not the hard part. The hard part is covering every operator in the training path:

    • Backward operators: a complete set of forward operators does not mean a model is trainable. Every forward operator needs a correct and efficient gradient implementation.
    • Fused operators: attention kernels and MoE grouped GEMM, for example, directly determine performance.
    • Communication primitives: all-gather, reduce-scatter, all-reduce, all-to-all and similar must be fully implemented and must support multi-node topologies.

    Beyond operators, framework feature support should also be verified, including autograd automatic differentiation, mixed-precision strategies, activation recomputation, and checkpoint saving and loading.

    Precision alignment is best done in the following order:

    1. Single-operator alignment: use the high-precision (fp32) implementation as the reference, and check both forward error and the relative error of backward gradients;
    2. Single-card model alignment: on a small or scaled-down model, compare loss curves and gradient norms across several steps;
    3. Small-scale parallel alignment: enable sharded parallelism, tensor parallelism, and expert parallelism one at a time, re-comparing after each dimension is enabled so that the source of any problem can be located quickly.

    4. Parallelism Strategy: Native FSDP2 and Hybrid Parallelism

    4.1 Why native sharding is needed

    Data parallelism comes in several forms, with very different memory and communication requirements:

    Form Params / gradients / optimizer states per card Main communication Characteristics
    Pure data parallelism Fully replicated Gradient all-reduce Simple to implement; memory grows linearly with model size; cannot carry trillion-parameter models
    Optimizer state sharding Params and gradients complete, optimizer states sharded all-gather + reduce-scatter Saves substantial memory, but each card must still hold the full parameter set
    Native parameter sharding (FSDP2) All three sharded by parameter all-gather + reduce-scatter Lowest memory footprint; combines freely with other parallelism strategies

    FSDP2 is the newer generation of sharded data parallelism in mainstream deep learning frameworks. It shards at the granularity of individual parameters and abstracts them uniformly as sharded tensors, which — compared with earlier flat-parameter schemes — makes it much easier to combine with tensor parallelism, expert parallelism, and other strategies.

    “Native” support matters just as much on domestic accelerators: the framework’s sharding abstraction must map correctly onto the vendor’s software stack, including the communication library, stream and event mechanisms, and memory allocators.

    4.2 Combining sharded parallelism with other parallelism strategies

    Sharded parallelism alone is not optimal; real training usually combines multiple parallelism dimensions:

    • Sharded parallelism (FSDP2): shards parameters, gradients, and optimizer states;
    • Tensor parallelism (TP): splits matrix multiplications within a node’s high-speed interconnect domain to reduce per-card compute;
    • Expert parallelism (EP): distributes different experts across devices to carry the full parameter scale;
    • Pipeline parallelism (PP): further splits layers and memory; in domestic accelerator training it is often introduced last;
    • Context / sequence parallelism: for very long contexts, splits the sequence and pairs with ring-attention-style algorithms to control activation memory and the quadratic cost of attention.

    A common combination is “sharded parallelism + tensor parallelism + expert parallelism”: tensor parallelism first constrains per-card compute, then sharded parallelism and expert parallelism together carry the overall parameter scale.

    4.3 Mixed precision and master weights

    bf16 is the usual precision for large-scale training. The general recommendation is:

    • store and compute model shards in bf16;
    • use fp32 master weights for parameter updates;
    • choose bf16 or fp32 for gradient reduction depending on training stability needs.

    bf16 has the same number of exponent bits as fp32, so the overflow risk is low, but it has only 7 mantissa bits, and fine-grained parameter updates can easily be rounded away. Keeping fp32 master weights and running optimizer computation in higher precision is therefore a prerequisite for stable training.

    5. The Full Training Path: From Model Loading to Gradient Synchronization

    The core of the adaptation work is to chain the following four stages into a single path with no breaks.

    5.1 Model loading

    1. Meta-device initialization: build the model structure on the meta device from the configuration first, so that full weights do not exhaust memory during loading.
    2. Configuration parsing: unify total and activated parameters, number of experts and shared experts, router Top-K, attention variants, positional encoding, multimodal projection layers, and similar settings, ensuring the training side matches the official configuration.
    3. Weight mapping: map tensor names and shapes from the public weight format to the local model. Pay particular attention to how MoE weights are organized, such as the stacking of expert weights and the router weights — mapping errors do not raise an exception immediately, but silently wreck convergence.
    4. Sharded loading: shard each parameter at load time and place only the slice owned by the current rank into memory, avoiding the peak caused by “load everything first, shard later.”
    5. Data type conversion: convert to training precision on load, and create fp32 master weights as needed.
    6. Weight integrity checks: compare parameter counts, means, and standard deviations tensor by tensor to guard against mapping errors.

    5.2 Shard scheduling

    • Device mesh: build a multi-dimensional device mesh from the node count and cards per node, so that shard groups, tensor-parallel groups, and expert-parallel groups land within the same node wherever possible.
    • Communication group mapping: map communication groups by interconnect tier so that high-frequency, high-volume communication (such as tensor-parallel all-reduce and expert-parallel all-to-all) stays within nodes as much as possible.
    • Policy configuration: set resharding policies, for example resharding between the forward-operator compute phase and the backward-operator compute phase; configure bucket sizes and prefetch steps.
    • Resharding and prefetching: buckets that are too small increase the number of communications, while buckets that are too large are hard to overlap with computation. Too many prefetch steps also squeeze memory, so profiling is required to decide.
    • Memory and activation management: wrap saved activations in autograd nodes, include memory-heavy modules such as attention and the MoE FFN in the recomputation scope, and set memory pool ratios to reduce fragmentation.

    5.3 Forward and backward passes

    During the forward pass, prefetch the next group of parameter shards in execution order and complete the all-gather. Inside MoE layers:

    1. compute the router in fp32 to obtain the Top-K result;
    2. decide, based on the capacity factor, whether to drop tokens beyond capacity;
    3. dispatch tokens to their experts;
    4. execute the grouped matrix multiplication;
    5. collect results and merge them with weighting.

    During the backward pass, MoE layers must redo routing and dispatch in order to compute expert gradients. Forward and backward therefore must use fully consistent deterministic routing, otherwise gradients are wrong and extremely hard to debug.

    5.4 Gradient synchronization

    • Reduction method: trigger reduce-scatter per bucket during the backward pass, so each rank keeps only the gradient shard it owns.
    • Gradient handling: after all micro-batches have been accumulated, apply global gradient-norm clipping, then hand the sharded gradients to the optimizer.
    • Optimizer update: each rank updates only the parameter shard it holds.
    • Communication overlap: overlap reduction with backward computation, and parameter updates with forward computation.

    Illustrative code (pseudocode, showing call relationships only, not the API of any specific framework):

    1. # 1) Build the model on the meta device to avoid full weights occupying memory
    2. with device("meta"):
    3. model = build_moe_model(config)
    4. # 2) Build a multi-dimensional device mesh so communication groups stay within nodes
    5. mesh = init_device_mesh(
    6. shape=(dp_replicate, dp_shard, tp_size, ep_size),
    7. dim_names=("dp_r", "dp_s", "tp", "ep"),
    8. )
    9. # 3) Shard per parameter; keep params in bf16, reduce gradients in fp32,
    10. # and maintain separate fp32 master weights
    11. shard_fully(model, mesh=mesh["dp_r", "dp_s"],
    12. param_dtype=BF16, reduce_dtype=FP32)
    13. optimizer = AdamW(model.parameters(), lr=lr, betas=(0.9, 0.95), eps=1e-8)
    14. for step, batch in enumerate(train_loader):
    15. loss = 0.0
    16. for micro in batch: # gradient accumulation
    17. with recompute(modules=model.activation_checkpointed_modules()):
    18. loss += model(micro) / len(batch)
    19. loss.backward() # per-bucket reduce-scatter, overlapped with backward
    20. grad_norm = clip_grad_norm_(model.parameters(), max_norm=1.0)
    21. optimizer.step() # updates only the shard owned by this rank
    22. optimizer.zero_grad(set_to_none=True)
    23. # 4) Layered observation: throughput, loss, grad norm, expert load,
    24. # communication time, memory
    25. log_metrics(step, loss, grad_norm, expert_load(model))

    6. Key Engineering Points for MoE and Multimodal Scenarios

    6.1 Coordinating expert parallelism with sharded parallelism

    If expert parameters are distributed by expert parallelism and then sharded again by sharded parallelism, double sharding or load imbalance can easily occur. The usual approach is:

    • place different experts across expert-parallel groups;
    • shard expert parameters within each expert-parallel group;
    • handle non-expert parameters with sharded parallelism and tensor parallelism together.

    In addition, non-expert parameters are far smaller than expert parameters in volume but much more numerous, which makes them prone to becoming a synchronization bottleneck. They need to be scheduled so their communication is staggered against expert communication.

    6.2 Optimizing all-to-all communication

    • Capacity factor: set a capacity limit per expert based on expert load, trading a small number of dropped tokens for stable communication shapes and avoiding recompilation and synchronization waits caused by dynamic shapes;
    • Communication overlap: overlap dispatch with the previous batch’s combine, or expert computation with the next batch’s dispatch;
    • Expert placement: balance hot experts across devices to reduce long-tail waits on individual devices;
    • Grouped matrix multiplication: group along the expert dimension first and then run the matrix multiplication, avoiding a separate kernel launch per expert.

    6.3 Numerical stability checklist

    • Compute router logits, Top-K, and load-balancing biases in fp32;
    • Accumulate attention Softmax and LayerNorm/RMSNorm in fp32;
    • Compute positional encoding (such as rotary positional encoding) in fp32;
    • Set the coefficients for the load-balancing loss and the router z-loss sensibly;
    • Apply global gradient-norm clipping so that amplified gradients from individual experts do not cause loss spikes;
    • Do not set the epsilon of Adam’s first- and second-order moments too large, or the effective updates to bf16 parameters will be suppressed.

    6.4 Specific considerations for multimodal training

    • Modality ratio: the mix of text and text-image data and the distribution of image resolutions directly affect the training rhythm and need to be tracked separately;
    • Sample packing: after image tokens and text tokens are concatenated, modality boundaries must be recorded and corresponding attention masks built to prevent samples from “seeing” each other;
    • Vision encoder: its parallelism strategy differs from the main model; it usually runs with data parallelism or a smaller tensor-parallel degree and needs its own parameter sharding and gradient synchronization design;
    • Projection layers: the vision projection layer is small in parameter count but updated frequently, so it can be kept at higher precision to reduce rounding loss.

    7. Performance Tuning: The Memory Ledger and the MFU Perspective

    7.1 The memory ledger

    Training memory at scale splits into a part that can be estimated and a part that is hard to estimate:

    Component Bytes per parameter (bf16 mixed precision + Adam-family optimizer) Notes
    Parameter shard 2 Each rank holds only a slice
    Gradient shard 2 Retained after reduce-scatter
    fp32 master weights 4 Used for optimizer updates
    First moment 4 Adam-family optimizer
    Second moment 4 Adam-family optimizer
    Total 16 Excludes activations, communication buffers, and memory pool fragmentation

    Worked estimate: 2.8 trillion parameters require roughly 2.8×10¹² × 16 B ≈ 44.8 TB of memory to hold parameters, gradients, and optimizer states. With 1024 cards of 80 GB (about 80 TB in total), less than half remains for activations, communication buffers, and fragmentation, so activation recomputation and selective activation checkpointing are mandatory, and low-bit optimizer states or offloading strategies may be needed.

    Parallelism degrees are only a floor; activation memory, communication buffers, and memory pool fragmentation are the real battleground for tuning.

    7.2 Throughput and MFU

    The training compute per token can be approximated as:

    C ≈ 6 × N_active + 12 × L × d × s

    where N_active is the activated parameter count, L is the number of layers, d is the hidden dimension, and s is the sequence length.

    Model FLOPs Utilization (MFU) is computed as:

    MFU ≈ measured tokens/s × C ÷ (number of cards × peak compute per card)

    For MoE models, C must be computed from the activated parameter count, otherwise the resulting MFU is inflated and misleads tuning.

    When MFU is low, troubleshoot qualitatively first and quantitatively second:

    1. device idle time (waiting on communication or data);
    2. low operator efficiency (lack of fusion, memory-bound kernels);
    3. recompilation (frequent dynamic shape changes);
    4. synchronization points (frequent CPU-GPU syncs or log printing);
    5. paging triggered by insufficient memory.

    The corresponding remedies are: increase compute-communication overlap, optimize operators and fusion strategies, fix shapes or use bucketing, reduce synchronization points, and adjust recomputation and bucketing strategies.

    8. Stability and Operability

    8.1 Layered observability

    • Hardware layer: temperature, power draw, memory usage, interconnect errors;
    • Framework layer: throughput, loss, gradient norm, expert load distribution, communication time;
    • Data layer: per-modality sample ratios, sequence length distribution, token count statistics.

    Layered monitoring makes it possible to quickly separate hardware problems, communication problems, and data problems.

    8.2 Checkpoint-resume training and elastic scaling

    • Checkpoint contents: model shards, optimizer states, data-loader progress, random number states, and the training step — none can be omitted;
    • Resharding: a key advantage of native sharding is that checkpoints can be re-sharded and loaded at a new parallelism degree. When a node fails and is replaced or the job scales elastically, training does not have to restart from zero;
    • Asynchronous saving: overlap save overhead with training to reduce blocking time;
    • Periodic validation: restore sampled checkpoints to verify optimizer state consistency.

    8.3 Common failures and troubleshooting order

    Symptom Common causes Troubleshooting order
    Loss spikes Data anomalies, router flips, gradient amplification Data → routing → gradient norm → learning rate
    NaN/Inf gradients Overflow, division by zero, optimizer epsilon Locate the first anomalous operator → check precision configuration
    Throughput jitter Communication long tail, expert load skew, recompilation from dynamic shapes Profiling → expert load → operator shapes
    Job interruption Hardware failure, communication timeout Hardware metrics → communication logs → automatic replacement

    9. Recommendations for Cloud Deployment

    After completing single-node or small-scale training adaptation, organizations often need to run large-scale training in the cloud. General-purpose cloud platform capabilities cover the following areas:

    • Compute scheduling: heterogeneous compute platforms handle multi-node, multi-card job orchestration, faulty-card isolation, and task self-healing;
    • Data storage: object storage holds training data and checkpoints, with data caching and acceleration services used to shorten data-read latency;
    • Containers and orchestration: container platforms host training images and job management, making it easy to replicate training environments;
    • Monitoring and alerting: logging and monitoring/alerting components provide unified collection and alerting for hardware metrics, training metrics, and abnormal events.

    Baidu AI Cloud, for instance, offers general-purpose capabilities such as its AI heterogeneous computing platform, object storage, containers, and monitoring and alerting, which can support the large-scale resource orchestration, data read/write, and observability that large model training requires. Refer to the official documentation for specific product forms and specifications.

    Three steps are recommended for rollout:

    1. Small-scale validation: complete precision alignment and functional verification on a single node with multiple cards;
    2. Mid-scale stability: run the parallel combination across tens to hundreds of cards, and observe long-run stability and expert load;
    3. Full-scale training: stable training beyond thousands of cards, combined with checkpointing, failure self-healing, and layered monitoring.

    10. Conclusion

    A domestic AI chip completing training adaptation for a trillion-parameter MoE model looks, on the surface, like a one-off “handshake” between hardware and a model. In substance, it demonstrates the maturity of three capabilities: the software stack capability of operator coverage and precision alignment, the framework capability of native sharded parallelism and communication scheduling, and the engineering-operations capability of layered monitoring and checkpoint-resume training.

    For developers and enterprises, the genuinely reusable lessons are:

    • Read the model first, adapt second: structural characteristics determine the parallelism strategy;
    • Align layer by layer, enable dimension by dimension: validating each dimension separately is what makes problems quickly locatable;
    • Decide with the memory ledger and MFU: avoid tuning by gut feeling;
    • Treat stability as a first-class concern: checkpointing, elasticity, and observability determine whether a long run reaches the finish line.

    As the domestic compute software ecosystem continues to mature, “training a trillion-parameter model on domestic accelerators” is shifting from a one-off sprint into a reproducible, operable engineering practice.