Adapting Domestic AI Accelerators for Trillion-Parameter Multimodal Model Training: A Practical Guide

    As model parameters scale from hundreds of billions toward trillions, training shifts from "can the model architecture be written correctly" to "can the system run stably." This article breaks down the three core barriers of large-scale training—the memory wall, the communication wall, and the hardware-software coordination wall—and shows how to adapt Fully Sharded Data Parallel (FSDP2) on domestic AI accelerators. It covers prerequisites, a reference training loop, common failure modes, differentiated parallelism for multimodal modules (vision encoder, text backbone, cross-modal fusion), full-pipeline acceptance criteria, numerical alignment methods, operator and graph-compilation troubleshooting, and performance measurement standards. Readers will gain a reusable engineering checklist for loading, scheduling, gradient synchronization, checkpointing, and validation when running trillion-parameter multimodal models on domestic training-inference accelerators and their software stacks.

    1. Why Training Stalls: Breaking Through the Memory Wall, Communication Wall, and Hardware-Software Coordination

    When model parameters grow from hundreds of billions toward trillions, the training problem rapidly shifts from “can we write the model structure correctly” to “can the system run stably.” In public community discussions, you often see statements like: a domestic compute platform has completed adaptation for training an open-source trillion-parameter multimodal model. To avoid attributing the work to a specific vendor or event without a verifiable source, this article treats it as a generic engineering case; if used for a formal release, official announcements, code commit records, or evaluation reports should be added as sources.

    The difficulties of ultra-large-scale training can be grouped into three barriers:

    Barrier Typical Symptoms Optimization Direction Acceptance Criteria
    Memory wall Weights, gradients, optimizer states, and activations add up beyond a single card’s capacity Parameter sharding, optimizer state sharding, activation recomputation, low-precision storage Predictable peak memory; no spikes during loading or forward pass
    Communication wall Frequent all-gather, reduce-scatter, and gradient synchronization block computation Communication-compute overlap, bucketing, topology-aware scheduling, prefetching Controllable communication ratio; no obvious hangs during long runs
    Hardware-software coordination wall Missing operators, numerical deviation, graph compilation failures, unstable collective communication Operator completion, version matrix, precision alignment, graph compilation fallback Pass small-model alignment before scaling up

    For a domestic compute platform, adaptation is not simply “making the model start.” It means proving that on domestic training-inference accelerators and their supporting software stack, a trillion-parameter multimodal model can stably complete loading, forward and backward passes, gradient synchronization, and checkpoint saving and recovery.

    2. How to Adapt FSDP2 on Domestic Accelerators: Prerequisites, Code, and Common Pitfalls

    To tackle the memory wall, the industry commonly uses Fully Sharded Data Parallel (FSDP). The second-generation approach, generally referred to as FSDP2, is better suited to ultra-large model adaptation than earlier implementations. Its key change is per-parameter sharding: each parameter participates in sharding management at a finer granularity, typically appearing as a sharded tensor or a local state on a device mesh. The benefits are fewer memory fragments, more natural composition with tensor parallelism and pipeline parallelism, and a clearer structure for checkpoint saving and recovery.

    However, before writing FSDP2 code on a domestic accelerator, you must first confirm a set of prerequisites. Otherwise, even syntactically correct pseudocode will be hard to reproduce directly.

    2.1 Prerequisites to Confirm First

    1. Framework and driver versions
      You need to confirm that the PyTorch (or corresponding deep learning framework) version, the domestic accelerator driver, the vendor software stack, and the collective communication library form a compatible matrix. Before formal adaptation, it is recommended to record: framework version, driver version, communication library version, and operator library version.

    2. Communication backend
      You need to confirm whether the collective communication backend matches the device topology and whether it supports core primitives such as all-gather, reduce-scatter, and all-reduce. On domestic platforms, the communication backend name may differ from the mainstream NCCL ecosystem; rely on the vendor software stack documentation.

    3. Device mesh
      Trillion-parameter training usually requires combining data parallelism, tensor parallelism, and pipeline parallelism. Before FSDP2 adaptation, you must define the device mesh clearly—for example, the data parallel degree, tensor parallel degree, pipeline parallel degree, and which shard each card maps to.

    4. Parameter and optimizer sharding
      Parameters need to be sharded, and optimizer states should be sharded accordingly. Optimizers like Adam and AdamW maintain first-order and second-order moments; if optimizer states are not sharded, memory pressure increases significantly.

    5. Mixed precision and loss scaler
      A common practice is to use BF16/FP16 to reduce memory usage for parameters and activations while keeping high precision for critical accumulation steps. If you use FP16, you need a loss scaler; if you use BF16, a traditional loss scaler is usually unnecessary, but you should still monitor overflow and NaN/Inf.

    6. Gradient clipping and anomaly detection
      Large-model training should retain gradient clipping and enable anomaly detection. Otherwise, once gradients explode, the problem may only surface several steps later through abnormal loss, increasing the cost of diagnosis.

    7. Checkpoint saving and recovery
      You need to confirm the framework supports sharded state saving and recovery, and that the saved metadata maps to the current device mesh and parallel strategy. Otherwise the model may train but be difficult to recover after a failure.

    2.2 Reference Code and Runnable Prerequisites

    The code below only expresses a training paradigm and does not indicate that it runs directly. Actual API names, configuration options, and behavior vary with framework version and domestic software stack version.

    1. # Reference code: expresses engineering intent only; not directly runnable.
    2. # Prerequisites:
    3. # 1. Framework, driver, communication backend, and operator library versions are compatible;
    4. # 2. Process group and device mesh are initialized;
    5. # 3. Parameter sharding, optimizer state sharding, mixed precision, and checkpoint interfaces are confirmed.
    6. # from torch.distributed.device_mesh import init_device_mesh
    7. # from torch.distributed.fsdp import fully_shard, MixedPrecisionPolicy
    8. # mesh = init_device_mesh(device_type, (world_size // tp_size, tp_size))
    9. # model = build_multimodal_model()
    10. # mp_policy = MixedPrecisionPolicy(param_dtype=bf16, reduce_dtype=fp32)
    11. # model = fully_shard(model, mesh=mesh, mp_policy=mp_policy)
    12. # optimizer = ShardedOptimizer(model.parameters(), lr=lr)
    13. # scaler = LossScaler() # Enabled for FP16; for BF16, replace with high-precision accumulation and anomaly detection
    14. # for step, batch in enumerate(loader):
    15. # with autocast():
    16. # loss = model(batch)
    17. # loss = scaler.scale(loss)
    18. # loss.backward()
    19. # scaler.unscale_(optimizer)
    20. # clip_grad_norm_(model.parameters(), max_norm=1.0)
    21. # scaler.step(optimizer)
    22. # scaler.update()
    23. # optimizer.zero_grad(set_to_none=True)
    24. # if step % save_every == 0:
    25. # save_sharded_checkpoint(model, optimizer, step)

    The core of this code is not syntax but the expression of a training paradigm: developers do not need to manually handle every parameter all-gather, release, and gradient reduction, but they must prepare the correct device mesh, sharding strategy, mixed precision strategy, and saving/recovery interfaces for the parallel framework.

    2.3 Common FSDP2 Problems on Domestic Accelerators

    Problem Possible Cause Priority Check
    OOM at startup Optimizer state not sharded, activations too large, loading holds full weights redundantly Check sharding granularity, recomputation, and loading method
    Forward passes but backward OOMs Activation recomputation not enabled or granularity too coarse Add computation layer by layer for the vision tower and fusion modules
    Communication hang Communication backend doesn’t match topology, inconsistent collective communication order Check process group, device mesh, and timeout configuration
    Precision drift Mixed-precision accumulation error, operator implementation differences, graph compilation anomalies Fix seeds; compare inputs and outputs layer by layer
    Checkpoint recovery failure Checkpoint metadata inconsistent with the current parallel strategy Verify shard mapping and optimizer state keys

    3. The Native Multimodal Training Path: How to Parallelize and Align Different Modules

    A multimodal model is not a single Transformer stack, but a combination of a text encoder, a vision/image encoder, and a cross-modal fusion module. These parts differ greatly in parameter scale, activation scale, and operator characteristics, so you cannot force one parallel configuration onto the entire model.

    3.1 Differentiated Parallel Strategies

    Module Typical Characteristics Adaptation Advice
    Vision encoder Parameters may be small, but activations are large after image patching Prioritize activation recomputation; shard the vision tower separately if needed
    Text backbone Parameter-dense and deep, with memory pressure concentrated in parameters and optimizer states Use finer FSDP sharding; watch all-gather communication
    Cross-modal fusion Complex data flow involving modality token concatenation and alignment Define the fusion layer’s parallel strategy clearly; avoid conflicts between different modules’ communication models

    The significance of the native multimodal training path is that it allows applying different strategies to different submodules, rather than stuffing all modules into a single parallel configuration.

    3.2 Multimodal Structure Alignment Checklist

    When adapting a multimodal model, structural alignment is often more critical than pure performance tuning. At minimum, check the following:

    1. Image patching
      Check patch size, patch boundaries, channel order, dtype, and whether padding is needed. Misaligned patching causes inconsistency between visual tokens and position encodings.

    2. Position encoding
      The vision side may involve two-dimensional or three-dimensional position encoding, and the text side may involve long-sequence position extrapolation. Confirm the computation precision of position encoding, the index generation method, and whether encodings are shared or aligned across modalities.

    3. Modality token concatenation
      Check the concatenation order of text tokens, image tokens, special tokens, and masks. Changes in modality order can lead to incorrect attention computation.

    4. Operator coverage for vision and text encoders
      Systematically check whether operators such as normalization, attention, activation functions, convolution/patching, and embedding lookup are correctly implemented on the domestic accelerator. For missing operators, don’t just check whether they run—also check whether the numerics are aligned.

    5. Fusion module parallel strategy
      The fusion module may receive multimodal features simultaneously; confirm whether its tensor parallelism, sequence parallelism, or expert parallelism introduces extra communication.

    6. Loss and mask
      Check whether different modality loss weights, ignored positions, and length truncation are consistent. In multimodal tasks, an incorrect mask is more subtle than a gradient synchronization error.

    4. How to Validate the Full Training Pipeline: Loading, Scheduling, and Gradient Synchronization

    An adaptable training system must work end to end. Any single broken point manifests as a startup failure, training interruption, or non-reproducible results.

    4.1 Model Loading and Weight Initialization

    Trillion-parameter weights cannot be loaded in full onto a single card at once. During adaptation, ensure the checkpoint can be split according to the sharding strategy and distributed to each compute node. The key point is consistent shard mapping: each card must receive the correct shard for the current device mesh, aligned with the subsequent FSDP layout.

    4.2 Sharded Scheduling and Forward/Backward Computation

    After loading, the framework schedules according to the sharding tree: the forward pass aggregates parameters layer by layer, executes computation, and releases parameters; the backward pass aggregates parameters layer by layer, computes gradients, and performs reduce-scatter. Here you need to control peak memory carefully, avoiding spikes at the end of the forward pass, the start of the backward pass, or during gradient reduction.

    4.3 Gradient Synchronization and Optimizer Update

    The sharded gradients produced by the backward pass must be aggregated via reduce-scatter onto the shards each card is responsible for. The optimizer updates state only on local shards, then proceeds to the next round of parameter aggregation. The correctness of gradient synchronization is the baseline for whether training can converge, but this baseline cannot rely on experience alone—there must be a validation method.

    4.4 Training Pipeline Acceptance Checklist

    Stage Acceptance Item Common Problem Recommended Action
    Model loading Shard index, weight keys, and checkpoint metadata are consistent A card loads empty or loads redundantly Print shard mapping; do hash or sampling comparison
    Forward scheduling Output is reproducible after layer-by-layer parameter aggregation A layer’s output drifts or is misaligned Fix the input; save outputs layer by layer
    Backward scheduling Parameter update direction is reasonable after gradient reduction Local gradients deviate significantly from the reference implementation Disable graph compilation and communication overlap, then compare again
    Gradient synchronization Sharded gradients aggregate without omission Loss does not decrease after parameter update Compare against single-card/small-cluster reference results
    Checkpoint recovery Step, loss, and optimizer state are continuous after recovery Loss jumps after recovery Verify optimizer state and RNG state
    Monitoring and alerts Memory, communication, throughput, and NaN/Inf are observable No logs after a failure Add layered monitoring and error-code collection

    5. Engineering Essentials on Domestic Compute: Numerics, Operators, Graph Compilation, and Measurement

    5.1 Numerical Consistency Verification Checklist

    Do not scale a new platform directly to trillion parameters. First align at a small scale, then gradually scale up.

    1. Fix random seeds
      Fix random sources such as Python, the framework, data loading, initialization, and dropout. Record the seeds and framework version.

    2. Small-model alignment
      Use a small model or a truncated layer set that reproduces quickly; compare the domestic accelerator’s output against a reference implementation under the same input.

    3. Layer-by-layer forward comparison
      For key layers, save intermediate results such as inputs, outputs, masks, position encodings, and attention weights; compare shapes, dtypes, and numerical errors.

    4. Gradient comparison
      Run one forward and backward pass on the small model and compare the gradients of key parameters. Focus on the fusion modules, vision tower, normalization layers, and communication shard boundaries.

    5. Error criteria
      Don’t look only at the final loss. Record maximum absolute error, maximum relative error, cosine similarity, or a specified quantile error. For BF16/FP16 scenarios, state the basis for error tolerance.

    6. Failure localization steps
      If results are inconsistent, first disable graph compilation, communication overlap, and complex fusion operators; then switch to the reference implementation or the vendor-recommended implementation; then use bisection to localize layer by layer, rather than directly modifying the entire model configuration.

    5.2 Operator Investigation and Graph Compilation Table

    Risk Point Typical Symptoms Replacement or Rewrite Approach Graph Compilation and Fallback Measurement Criteria
    Image patching/concatenation Patch boundary misalignment, dtype inconsistency Use native slicing or a fused kernel Graph compilation may change memory layout; fall back to dynamic execution on anomaly Single-layer latency, peak memory
    Position encoding Wrong position indices, precision drift Compute position encoding in high precision, store in low precision Disable optimization and fall back if graph compilation fails Output error, first-step latency
    Attention mask Wrong modality order, broken causality Explicitly construct and validate the mask Fall back to a general attention implementation Forward output, gradients
    Normalization layer Mean/variance deviation, unstable gradients Accumulate in high precision; keep FP32 if needed Graph compilation can fuse, but numeric regression is required Activation distribution, loss fluctuation
    Collective communication Hang, timeout, throughput collapse Check communication backend, bucketing strategy, topology mapping Disable overlap first to verify correctness Communication time ratio
    Dynamic shapes Frequent recompilation, memory fluctuation Fix shapes or use a padding strategy Disable graph compilation if stability can’t be maintained Steady-state throughput, peak memory

    5.3 Mixed Precision, Recomputation, and Fault Tolerance

    Mixed precision can significantly reduce memory pressure, but critical high-precision paths must be retained. Parameters and activations can use low precision, while sensitive stages such as reductions, normalization, and loss accumulation should keep high precision or adopt a vendor-validated mixed strategy.

    Activation recomputation trades compute for memory. The vision tower, fusion modules, and long-sequence text layers usually need finer-grained recomputation than a pure text backbone. But recomputation should not be enabled blindly everywhere, or throughput will drop.

    Trillion-parameter training has long cycles and many devices, so hardware jitter is almost unavoidable. FSDP2’s sharded structure is favorable for periodic saving and fast recovery. Combined with monitoring, alerting, logging, and automatic failure classification, it reduces the cost of recomputing after a failure.

    5.4 Performance Measurement Criteria

    Performance cannot be described only as “it got faster.” A unified set of criteria is recommended:

    • Model: parameter scale, modality ratio, sequence length, batch configuration;
    • Hardware: card type, cards per node, number of nodes, network topology;
    • Software: framework version, communication backend, graph compilation switches, mixed precision strategy;
    • Metrics: sample throughput, token throughput, peak memory, communication ratio, effective utilization or MFU;
    • Stage: first-step latency, steady-state throughput, long-run stability.

    6. Common Troubleshooting and Conclusion

    Fault Priority Check Recommended Action
    Common OOM Optimizer state sharding, activation recomputation, loading method Lower batch or sequence length; use fine-grained recomputation; shard saving
    Communication hang Communication backend, device mesh, collective communication order Check timeout configuration; disable overlap; verify topology mapping
    Precision drift Mixed precision, operator implementation, graph compilation Fix seeds; compare layer by layer; fall back to the reference implementation
    Performance collapse Inefficient operators, serialized communication, dynamic shapes Replace operators; tune graph compilation; fix shapes

    Adapting trillion-parameter multimodal models on domestic compute is, in essence, a systematic validation of hardware-software coordination. The key is not just completing a single model load, but proving that Fully Sharded Data Parallel, the native multimodal path, and the complete training pipeline can run stably on domestic training-inference accelerators and a unified software stack. For developers and enterprises, understanding the engineering logic behind the memory wall, communication wall, and hardware-software coordination wall—and mastering FSDP2 sharding principles, numerical alignment methods, operator investigation workflows, and acceptance checklists—is the core of landing ultra-large-scale model training.