Trillion-Parameter Multimodal Model Adaptation to Domestic AI Accelerators: End-to-End Engineering Analysis

    This article examines the engineering challenges, methods, and acceptance criteria involved in training trillion-parameter multimodal Mixture-of-Experts models on domestic AI accelerators. It explains how memory pressure, parallel scheduling, and software-stack compatibility interact, why native FSDP2 provides a practical parameter-level sharding foundation, and how to verify correctness, convergence, scalability, and long-running stability before large-scale deployment.

    Introduction: How Does a Trillion-Parameter Multimodal Model Complete Training Adaptation on Domestic Accelerators?

    How can a trillion-parameter multimodal model complete training adaptation on domestic AI accelerators? What are the key acceptance points for FSDP2 sharding? As model size grows from hundreds of billions to trillions of parameters, especially in multimodal and MoE training scenarios, the real challenge is often not whether the model structure can be written, but whether the model can be trained stably, efficiently, and reproducibly on a specified domestic accelerator, software stack, and cluster topology.

    In one adaptation project, a domestic AI accelerator vendor completed training adaptation for an open-source flagship multimodal model with 2.8 trillion parameters on its flagship AI training and inference compute card and self-developed software stack. The adaptation used native FSDP2 to build a multimodal training path, covering the full chain from model loading to shard scheduling and gradient synchronization.

    This article abstracts that work into a general engineering problem: on a domestic compute platform, what problems must be solved, what methodology should be followed, and what validation standards should be met before a trillion-parameter multimodal MoE model can run reliably at scale?

    1. Where Is Adaptation Difficult? Three Compounding Pressures

    Trillion-parameter multimodal models put severe pressure on training systems, mainly across three dimensions: memory capacity, parallel scheduling, and the software-hardware ecosystem.

    1.1 Memory Is Not Enough: First Calculate Parameters and Optimizer States

    MoE architectures usually have a large total parameter count but activate only a small subset of parameters per token. This means the memory burden caused by model capacity is often much larger than the cost of a single forward computation.

    Using a mainstream mixed-precision Adam-family optimizer as an example, the memory footprint of model states can be estimated roughly as follows:

    1. Memory usage ≈ parameter count Q × 16 Bytes
    2. (BF16 parameters 2 Bytes + BF16 gradients 2 Bytes + FP32 master weights 4 Bytes + FP32 first moment 4 Bytes + FP32 second moment 4 Bytes)

    If Q = 2.8 × 10^12, the model states alone require about 44.8 TB of memory. If each card has 80 GB of memory, simply holding the model states would require about 560 cards. This estimate does not yet include activations, communication buffers, memory fragmentation, framework caches, or checkpoint staging space, so the actual cluster scale would be even larger.

    It is also important to clarify an often-misunderstood point: without sharding, if a forward pass is performed on a single card or in a single process, the model parameters must remain fully resident. With FSDP2, parameters are temporarily aggregated by layer or module, avoiding the need for the entire model to occupy memory at the same time. In this case, the instantaneous peak depends mainly on the size of the largest layer or module, activation memory, and temporary communication buffers, rather than on the full model being materialized simultaneously.

    Therefore, whether for training or large-scale inference, keeping all parameters resident on a single card is not feasible. This is precisely why parameter sharding is a foundational approach for large-scale model training infrastructure.

    1.2 How Should Parallelism Be Split? Load Balance Across Multiple Dimensions

    Memory must be partitioned, communication must be orchestrated, and computation must be balanced. These constraints affect each other:

    • Data parallelism increases throughput through gradient reduction, but full parameter replicas grow with the number of cards, which is impractical at the trillion-parameter scale.
    • Tensor parallelism splits matrix operations within a layer across multiple cards. It involves frequent communication and is sensitive to inter-card bandwidth, so it is usually constrained to a high-speed interconnect domain within a single node.
    • Pipeline parallelism assigns different layers to different device groups. It can significantly reduce per-card memory usage, but it introduces pipeline bubbles.
    • Expert parallelism distributes different experts across different cards. It introduces dynamic all-to-all communication, and whether the load is balanced directly determines utilization efficiency.

    In MoE models, routing often causes significant load imbalance. A small number of popular experts may receive a large number of tokens, overloading some devices while leaving others idle. To limit the number of tokens processed by a single expert, implementations often set expert capacity limits and drop overflow tokens. This affects both training efficiency and convergence quality.

    1.3 What If the Ecosystem Is Not Ready? From Operators to Framework Support

    Open-source models are usually written around mature ecosystems and depend on specific operator libraries, mixed-precision strategies, and distributed primitives. Whether a domestic AI accelerator can run such models depends on whether its software stack can support three levels:

    • Operator level: coverage of core operators such as attention, normalization, routing computation, and vision encoding, while maintaining numerical consistency with the reference implementation.
    • Communication level: stable collective and point-to-point communication, with support that is as close as possible to the underlying hardware interconnect topology.
    • Framework level: enabling device-independent code in upper-layer training frameworks to actually run on domestic hardware. If any step is missing, such as device registration, distributed backend binding, or custom communication primitives, the code may be readable but not runnable.

    Therefore, adaptation is not merely replacing a device name. It requires connecting the full path from model definition to training execution.

    2. Why Native FSDP2? Sharding Mechanism and Communication Logic

    This adaptation used native FSDP2 to build the multimodal training path. FSDP stands for Fully Sharded Data Parallel. FSDP2 is a newer parameter-level sharding paradigm.

    Its core idea is that each training process retains only 1/N of the parameter shards after backward propagation. When a layer’s parameters are needed, they are temporarily aggregated; once used, they are immediately released.

    2.1 From Flat Parameters to Per-Parameter Sharding: What Is the Difference?

    Early implementations often concatenated a group of parameters into a flat 1-D tensor and then sharded the tensor as a whole to simplify communication. This can reduce the number of communication operations, but it has two limitations:

    • The offsets of parameters inside the flat tensor are fixed, making it difficult to align with other partitioning schemes such as tensor parallelism or pipeline parallelism.
    • Once parameters are packed into a flat buffer, single-parameter-level sharding is hard for other parallelism strategies to recognize directly.

    The key improvement in FSDP2 is to use individual parameters as the unit of sharding. Parameters, gradients, and optimizer states are represented as distributed tensors partitioned along device mesh dimensions.

    Example pseudocode:

    1. # Complete parameter: shape [4096, 4096]
    2. param = Tensor(shape=[4096, 4096], device=GPU)
    3. # Shard along dimension 0 across the data-parallel mesh (8 ranks in the dp group)
    4. sharded_param = param.distribute(mesh=dp_mesh, placements=[Shard(dim=0)])
    5. # Each rank holds: [512, 4096]
    6. # Gradients and optimizer states use the same sharding scheme

    Parameters are no longer packed into flat buffers. Instead, they directly participate in the computation graph as sharded tensors. This brings three benefits:

    • More natural composition: sharded tensors can be further partitioned along tensor-parallel, expert-parallel, or other dimensions, forming a higher-dimensional device mesh.
    • More flexible precision control: different parameters can use different parameter groups and precision policies, making it easier to handle sensitive layers separately.
    • Independent state management: distributed checkpoints can be saved and loaded by parameter shard, making it easier to resume training after changing the number of cards.

    It is worth emphasizing that FSDP2 does not change the overall communication volume order of fully sharded data parallelism. Its advantage lies in clearer sharding semantics and stronger composition capabilities.

    2.2 How Do Parameters Flow Within One Training Step?

    The correct construction order is: first build the model structure on the meta device, then apply sharding to modules, and finally load sharded weights.

    Example pseudocode:

    1. dp_mesh = init_device_mesh("acc", (dp_size,))
    2. with torch.device("meta"):
    3. model = build_model(config)
    4. for block in model.blocks:
    5. fully_shard(block, mesh=dp_mesh)
    6. load_sharded_checkpoint(ckpt_path, model, mesh=dp_mesh)
    7. optimizer = AdamW(
    8. model.parameters(),
    9. lr=...,
    10. betas=...,
    11. weight_decay=...
    12. )
    13. for step in range(max_steps):
    14. loss = model(batch) / grad_accum_steps
    15. loss.backward()
    16. optimizer.step()
    17. optimizer.zero_grad(set_to_none=True)

    For a single training step:

    1. Initialization: Build the model structure on the meta device, generating only the computation graph without allocating real memory. Then apply fully_shard to modules and load the sharded weights corresponding to each rank.
    2. Forward pass: Before entering a layer, use all-gather to temporarily aggregate the complete parameters for that layer. After computation, release them immediately to free memory for the next layer.
    3. Backward pass: Gradients propagate in the reverse direction. Parameters are temporarily aggregated again when needed. If re-sharding is enabled, parameters aggregated during the forward pass are released immediately afterward and re-aggregated during backward.
    4. Gradient reduction: Once the gradient for a parameter is computed, reduce-scatter is executed. Each rank reduces gradients and keeps only the shard it owns.
    5. Parameter update: Each rank updates only its local parameter shard and the corresponding optimizer states. Sharded parameter consistency is guaranteed by the next all-gather and shard loading process, and additional cross-rank parameter synchronization is usually not required.

    This forms a complete closed loop:

    1. Distributed weight loading → Sharded parameters remain resident → Temporary aggregation during forward → Gradient reduction during backward → Sharded parameter update

    This is the core training chain connected in this adaptation: from model loading and shard scheduling to gradient synchronization.

    2.3 How Is the Communication Ratio Calculated, and How Is It Overlapped?

    Ignoring the coefficient of ring communication for a rough estimate, let P Bytes be the amount of parameter data involved in communication. If the model has Q parameters and parameters are communicated in BF16, then typically:

    1. P ≈ 2Q Bytes

    In each training step, forward all-gather, backward all-gather, and gradient reduce-scatter each involve about P Bytes, for a total of about 3P Bytes.

    Communication time, computation time, and communication ratio can be approximated as follows:

    1. Communication time T_comm ≈ 3P / B
    2. Computation time T_comp = C / R
    3. Communication ratio ≈ T_comm / (T_comm + T_comp) × 100%

    Here:

    • C is the computation amount per step, in FLOPs.
    • R is the peak compute capacity of a single card, in FLOPs/s.
    • B is the usable interconnect bandwidth of a single card, in Bytes/s.

    If using TFLOPS and GB/s, units must be converted consistently:

    1. 1 TFLOPS = 10^12 FLOPs/s
    2. 1 GB/s = 10^9 Bytes/s

    The larger this ratio is, the harder it is for computation to hide communication overhead.

    MoE models introduce additional communication from two main sources:

    • All-to-all communication for expert routing: tokens are dispatched to the devices where their assigned experts reside and then collected after computation.
    • Point-to-point transfer for pipeline parallelism: activations and gradients are transferred between adjacent pipeline stages.

    In practice, three common methods are used to reduce the communication ratio:

    • Increase computation per step: increase the global batch size or use sequence packing to improve the ratio of computation to communication.
    • Improve bandwidth capacity: use high-speed interconnect inside nodes to carry tensor-parallel aggregation, and minimize cross-node communication where possible.
    • Schedule overlap: when backward computation reaches a certain layer, start aggregating parameters for the next layer in advance. Once a gradient is ready, launch its reduction immediately so it overlaps with subsequent computation.

    For communication-heavy MoE layers, computation and communication streams can also be overlapped, allowing all-to-all communication to run in parallel with expert computation and reducing communication exposure.

    3. Multimodal Training Path: How Can Two Backbones Share One Foundation?

    A multimodal model is usually composed of a vision encoder, a cross-modal alignment module, and a language model backbone. Compared with a pure text model, it introduces additional challenges in the training path.

    3.1 Heterogeneous Structures and Inconsistent Gradient Scales

    Vision encoders usually have fewer layers and limited parameters, while language backbones have many more layers and a larger parameter count. During joint training, the magnitude and update rhythm of gradients on both sides may differ. This can cause one side to converge faster while the other remains underfit, or it can lead to vision feature drift.

    Common approaches include:

    • Using a differentiated learning rate for the vision encoder.
    • Freezing or gradually unfreezing some parameters and training in stages.
    • Balancing losses across modalities through loss weighting.

    3.2 Dynamic Sequence Lengths and High Padding Cost

    Text tokens are generated by the tokenizer, while vision tokens are usually generated based on the original resolution or a patch strategy. The higher the resolution and the more images per sample, the larger the token count. Different samples can vary significantly in length. If padding is aligned to the longest sample in each batch, a large amount of compute may be spent on padding positions.

    Sequence packing can mitigate this issue, but it requires attention implementations to support variable-length masks and position-encoding remapping. Otherwise, packed samples may interfere with each other.

    3.3 Vision Token Compression and Effective Sequence Length Control

    Compressing or resampling vision features into fewer tokens before feeding them into the language model can significantly reduce attention computation. This is one of the key design methods for multimodal models to control long-context overhead.

    In this solution, FSDP2, with parameters as the sharding unit, serves as the common foundation for both backbones. The vision encoder, alignment module, and language backbone can all use the same sharding semantics for parameter loading, gradient reduction, and optimizer updates. There is no need to maintain a separate parallel logic for the vision tower alone.

    Common debugging items in multimodal adaptation include abnormal image resolution or vision token length, zero gradients in the vision tower, overly small gradients in the alignment module, imbalanced modality loss weights, and mismatched batch statistics between vision and text.

    For troubleshooting, it is recommended to first fix single-modality inputs, then gradually introduce cross-modal losses, and print gradient norms for the vision tower, alignment layers, and language backbone separately.

    4. Training and Inference on the Same Stack: Can Adaptation Results Be Reused? Where Are the Boundaries?

    The hardware foundation in this adaptation is a flagship AI training and inference compute card. Its engineering significance is that training and inference can share the same hardware form factor and software stack, allowing model adaptation results to be reused across both stages.

    • Training stage: the focus is on parameter sharding, gradient reduction, checkpoint recovery, and long-running stability.
    • Inference stage: the focus shifts to weight loading, batch scheduling, context cache management, and latency control.

    Because the operator library, communication library, and framework adaptation layer are already connected during training, the model usually does not need to be adapted from the bottom up when moving into inference. However, reuse still has boundaries: inference operator requirements may differ from training requirements. KV cache management, memory budgeting, batch scheduling policies, and long-context inference can also change resource allocation patterns.

    Therefore, training adaptation results can be reused, but inference deployment still requires separate performance and memory validation.

    This also explains why adaptation is regarded as a prerequisite for large-scale model engineering, rather than a one-time migration task.

    5. Systematic Adaptation: Six Stages

    Engineering experience can be abstracted into six stages:

    1. Environment baseline: Unify versions of accelerator drivers, collective communication libraries, training frameworks, and operator libraries. Fix random seeds and record single-card and single-node baseline metrics. At minimum, retain driver version, communication library version, framework commit, configuration files, loss, grad_norm, throughput, memory usage, card count, and exception stack traces.
    2. Structure mapping: Map model definitions layer by layer to accelerator operators. Build an “operator-implementation-numerical error” mapping table and identify unsupported operators or operators with precision anomalies.
    3. Parallel strategy design: Choose the partitioning combination based on model structure and cluster topology. Try to constrain tensor parallelism to a high-speed interconnect domain within a single node. Deploy pipeline parallelism across nodes. Divide expert parallelism and data parallelism according to communication characteristics.
    4. Pipeline integration: Complete end-to-end validation of distributed weight loading, shard scheduling, gradient reduction, and parameter updates. Ensure that every step can be reproduced on a small cluster.
    5. Numerical alignment: Use a mature ecosystem reference implementation as the baseline. Compare loss curves, gradient norms, and outputs of key layers to verify numerical consistency.
    6. Performance and stability: Analyze bottlenecks in computation, communication, and memory. Run long-duration stability tests and establish training monitoring and fault recovery mechanisms.

    6. Acceptance Checklist: How to Determine That Adaptation Is Truly Complete?

    Whether adaptation is truly complete should not be judged only by whether the model “can run.” At minimum, the following checks are recommended:

    Check item Validation method Pass criteria
    Weight loading Compare shard contents and checksums of key parameter tensors before and after loading Shards on each rank match source weights element by element
    Shard scheduling Observe memory usage curves during forward and backward passes Parameters are released immediately after temporary aggregation, with no continuous memory growth
    Gradient synchronization Compare gradient norms between single-card no-sharding and multi-card FSDP2 Relative error is within an explainable tolerance
    End-to-end convergence Compare loss curves over several hundred steps on a small scale Trends are consistent, with no obvious divergence or abnormal plateau
    Scaling efficiency Keep global batch size fixed and gradually increase card count Throughput remains within a reasonable linear range
    Long-running stability Train continuously for hundreds of hours No interruption caused by software defects, and checkpoints can be saved and resumed

    Gradient synchronization validation is especially important. Under fully sharded schemes, gradients are reduced with reduce-scatter, and results can be affected by reduction order and precision settings. Normal floating-point differences between the result and a single-card baseline are expected.

    A reasonable explanatory threshold should be set first. In normal training scenarios, a relative error below 1e-2 in gradient norm is usually acceptable. For precision-sensitive tasks, the threshold can be tightened to 1e-3, but this should be validated together with the model and cluster.

    For scaling efficiency, with a fixed global batch size, if throughput remains above 80% when card count doubles, this is usually considered good linear scaling. If it falls below 70%, communication and load balancing should be investigated first. These thresholds depend on the model, cluster, and parallel strategy, and should not be treated as absolute universal standards.

    7. Performance Tuning: Four Main Levers

    After the pipeline is connected, efficiency can be further improved from four perspectives:

    • Computation side: operator fusion, FlashAttention-style IO-aware attention, and selective recomputation to balance memory and compute.
    • Communication side: overlap gradient reduction with backward computation, constrain tensor parallelism within a node, overlap expert all-to-all with expert computation, and use lower-precision gradient reduction when appropriate.
    • Memory side: configure forward re-sharding thresholds, offload optimizer states, and tune memory pools and fragmentation management.
    • Data side: use sequence packing to reduce padding waste, make data loading and preprocessing asynchronous, and bucket multimodal samples by length to reduce length variance within batches.

    Conclusion: The Key Path from “Usable” to “Usable at Scale”

    Training adaptation for trillion-parameter multimodal models is fundamentally systems engineering, not a single-point breakthrough. From weight loading to shard scheduling, and from gradient synchronization to parameter updates, any missing link can break the entire training pipeline. Native FSDP2 provides a unified foundation through parameter-level sharding, enabling heterogeneous modalities to share the same parallel semantics. Meanwhile, sequence organization and gradient balancing in multimodal scenarios determine training efficiency and convergence quality.

    For enterprise users evaluating whether a domestic compute platform can support trillion-parameter model training, four dimensions are especially important:

    • Operator coverage and numerical consistency.
    • Distributed communication stability.
    • Degree of native framework-level support.
    • Long-running stability and fault recovery capability.

    Together, these capabilities form the minimum complete set for large-model training infrastructure, and they represent the key path for domestic compute platforms to move from “usable” to “usable at scale.”