Trillion-Parameter Multimodal Training on Domestic AI Accelerators: A Practical Adaptation Guide
This guide walks through the engineering work required to train trillion-parameter multimodal models on domestic AI accelerators. It explains why memory usage far exceeds raw parameter size once optimizer states, activations, and communication buffers are counted; how Fully Sharded Data Parallel (FSDP) works and how to combine it with ZeRO-3, tensor parallelism, and pipeline parallelism; how to land the full training pipeline across model loading, sharding, gradient synchronization, and fault tolerance; how to validate a domestic software stack across drivers, runtimes, operator libraries, and communication libraries; and how to scale up through a five-stage path gated by three acceptance metrics (it runs, it aligns, it scales). You will find concrete code for device-agnostic initialization and FSDP wrapping, troubleshooting tables for gradient-norm anomalies, communication timeouts, and loss drift, and a set of quantitative acceptance metrics for long-running training.
1. Background: The Dual Pressure of Trillion-Parameter Models and Multimodality
As models grow from hundreds of billions to trillions of parameters, the engineering complexity of training rises quickly. This is especially true for multimodal models, which contain text, image, and audio/video branches at the same time. Parameter count, activations, and intermediate tensors can grow severalfold.
Many teams focus only on “how many parameters the model has” and underestimate what actually drives out-of-memory (OOM) errors on domestic AI cards: optimizer states, gradients, activations, temporary communication buffers, and memory fragmentation.
Take a model of roughly one trillion parameters as an example. If it uses BF16/FP16 compute precision, the model parameters alone require about 2×10¹² × 2 bytes ≈ 2 TB of GPU memory. That is only the parameter footprint, not the total training footprint. With common mixed-precision training, several more components stack on top:
| Memory item | Typical scale | Notes |
|---|---|---|
| Parameters | ~2 TB | BF16/FP16 weights |
| Gradients | ~2 TB | Same precision as parameters |
| Optimizer states | ~12 TB | If keeping FP32 master weights plus first and second moments |
| Activations | Several TB to over ten TB | Depends on sequence length, batch, recomputation, and multimodal branches |
| Communication buffers | Hundreds of GB to several TB | All-Gather, Reduce-Scatter, and temporary tensors from fused modules |
| Fragmentation and reserve | Depends on framework and driver | Memory fragmentation amplifies the probability of OOM |
Because of this, trillion-parameter multimodal training on domestic accelerators must answer three questions at once:
- Fitting it in: How do you hold an ultra-large model within limited GPU and host memory?
- Computing fast enough: How do you partition the computation so domestic card operators deliver performance?
- Communicating smoothly: How do you efficiently perform parameter aggregation and gradient reduction across multiple cards and machines?
In a domestic accelerator environment, there is one additional prerequisite: the model must run correctly, produce correct results, and stay stable on the domestic card and its supporting software stack. In other words, being able to start is only the first step. The core of production-grade domestic compute adaptation is whether the model can converge over the long term, whether experiments can be reproduced, and whether training can recover after failures.
2. Core Approach: How FSDP Works, and How to Choose Among ZeRO-3, Tensor Parallelism, and Pipeline Parallelism
Traditional data parallelism keeps a full model replica on every card. It works well for small and medium models, but a single card cannot hold a complete replica of a trillion-parameter model. Fully Sharded Data Parallel (FSDP) solves this by sharding parameters, gradients, and optimizer states. Its basic logic is:
- During the forward pass, All-Gather the sharded parameters of the current layer on demand.
- Once computation finishes, release the full parameters immediately and keep only the shards.
- During the backward pass, use Reduce-Scatter to accumulate gradients and distribute them to the corresponding shards.
FSDP is not the only option. Real projects often need to combine approaches:
| Approach | Memory savings | Communication frequency | Implementation complexity | Best fit (layers/scenarios) |
|---|---|---|---|---|
| FSDP | High | Relatively high | Medium | Many layers, large parameter scale, unified shard management |
| ZeRO-3 | High | Relatively high | Medium | Similar in spirit to FSDP; depends on the software stack and vendor support |
| Tensor parallelism | Medium to high | High | Relatively high | Single-layer attention, MLP, GEMM-heavy workloads |
| Pipeline parallelism | Medium | Medium | High | Many layers that can be split into stages; good for multi-machine scaling |
A trillion-parameter multimodal model usually does not rely on FSDP alone. It typically uses a hybrid strategy of “FSDP + tensor parallelism/pipeline parallelism.” The reason is that multimodal models generally contain a text tower, a vision tower, an audio tower, and a fusion module, and these modules differ greatly in operator density, memory hotspots, and communication patterns. In practice, engineers usually settle on the primary parallelism strategy first, then separately optimize local hotspots such as the vision encoder, cross-modal fusion layers, and long-sequence attention.
3. Landing the Complete Training Pipeline: Model Loading, Sharding Scheduling, Gradient Synchronization, and Fault Tolerance
1. Model Loading and Initialization: Avoid Wrapping a Meta Model That Cannot Train
A trillion-parameter model cannot be loaded into memory all at once. A common approach is to build the model structure on the meta device first, then place the weights or parameter initialization onto real devices. Note that the meta device holds only structural information and no real parameters, so it cannot be used for training directly. You must first materialize the weights through to_empty, parameter initialization functions, or load_state_dict.
More importantly, in distributed training the model structure, initialization method, random seed, weight-loading path, and buffer state must be identical across all ranks. Otherwise you can see issues such as loss drift, abnormal gradient norms, or inference results on some ranks that disagree with the reference implementation. Two recommended approaches:
- Production training: Prefer loading a unified sharded checkpoint so every rank receives the correct weights.
- Random initialization: Explicitly initialize all parameters, and use broadcasting or framework synchronization to guarantee consistency across ranks.
The example below shows an initialization pattern that can be swapped out for a domestic card adaptation layer. Note that domestic cards generally should not hardcode torch.cuda; instead, obtain the device through the vendor runtime or an adaptation layer.
import osimport torchimport torch.distributed as distfrom functools import partialfrom torch.distributed.fsdp import FullyShardedDataParallel as FSDPfrom torch.distributed.fsdp import MixedPrecision, ShardingStrategyfrom torch.distributed.fsdp.wrap import transformer_auto_wrap_policydef get_device(local_rank: int):# Do not hardcode torch.cuda; domestic cards return the device via the vendor adapterif hasattr(torch, "cuda") and torch.cuda.is_available():return torch.device("cuda", local_rank)# Example: a domestic runtime may expose set_device/current_device interfaces# import vendor_runtime# vendor_runtime.set_device(local_rank)# return vendor_runtime.current_device()raise RuntimeError("Implement get_device according to the target domestic card adapter")def init_distributed():if not dist.is_initialized():# Domestic cards may use a vendor collective communication backend; the backend name must be replaced per the actual software stackbackend = os.getenv("DIST_BACKEND", "nccl")dist.init_process_group(backend=backend)def init_module(module):# Prefer the module's own initializationif hasattr(module, "reset_parameters"):module.reset_parameters()return# Explicitly initialize common layers to avoid uninitialized memory left after to_emptyif isinstance(module, torch.nn.Linear):torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)if module.bias is not None:torch.nn.init.zeros_(module.bias)elif isinstance(module, torch.nn.Embedding):torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)elif isinstance(module, torch.nn.LayerNorm):if module.weight is not None:module.weight.data.fill_(1.0)if module.bias is not None:module.bias.data.zero_()else:# Unknown modules must be explicitly initialized; otherwise direct training is forbiddenfor name, p in module.named_parameters(recurse=False):if p.numel() > 0:raise RuntimeError(f"Initialization not implemented: {module.__class__.__name__}.{name}")def build_model(use_pretrained=False):init_distributed()local_rank = int(os.environ.get("LOCAL_RANK", "0"))device = get_device(local_rank)# 1. Build the structure on the meta device only, to avoid large memory usage during initwith torch.device("meta"):model = build_trillion_param_multimodal_model()# 2. A meta model cannot train directly; first allocate real parametersmodel = model.to_empty(device=device)if use_pretrained:# Option A: load a pretrained sharded checkpoint; ideally each rank loads only its own shard# Note: load_sharded_checkpoint must be implemented for the domestic card and framework adapter layer# state = load_sharded_checkpoint("ckpt_dir", rank=dist.get_rank(), device=device)# model.load_state_dict(state, assign=True)passelse:# Option B: random initialization# All modules must be fully initialized; add a failure guard for modules without reset_parametersmodel.apply(init_module)# If the framework cannot guarantee identical initial parameters across ranks, broadcast parameters and buffers explicitly# for p in model.parameters():# dist.broadcast(p.data, src=0)# for b in model.buffers():# dist.broadcast(b.data, src=0)# 3. Use the Transformer block as the smallest sharding unitauto_wrap_policy = partial(transformer_auto_wrap_policy,transformer_layer_cls={TransformerBlock},)# 4. Wrap the model with FSDPmodel = FSDP(model,auto_wrap_policy=auto_wrap_policy,sharding_strategy=ShardingStrategy.FULL_SHARD,mixed_precision=MixedPrecision(param_dtype=torch.bfloat16,reduce_dtype=torch.float32,buffer_dtype=torch.bfloat16,),device_id=device,# Fallback synchronization: ensure all ranks start from a consistent module state# In production, loading a sharded checkpoint is preferred to avoid the overhead of large-scale broadcastingsync_module_states=True,)return model
Three key points here:
- All ranks must complete distributed initialization before entering FSDP wrapping.
- If using pretrained weights, prefer loading a unified sharded checkpoint to avoid weight inconsistency across ranks.
- If using random initialization, the initialization functions must be complete, and broadcasting or a framework synchronization mechanism must ensure consistency across ranks.
Sharding granularity cannot be set arbitrarily. Too coarse, and peak memory stays high; too fine, and communication frequency rises. In practice, the Transformer block is often used as a balanced unit, then adjusted separately for memory pressure in the text tower, vision tower, and fusion module. For memory optimization on domestic cards, measure the peak usage of each subnetwork first, then decide which layers need more aggressive checkpointing or finer sharding.
2. Sharding Scheduling and Memory Management: How to Reduce the Chance of OOM on Domestic Cards?
After parameters are sharded, the training framework must precisely control “when to aggregate and when to release.” Common optimizations include:
- Gradient checkpointing: Do not store all activations; recompute them during the backward pass.
- Computation/communication overlap: Overlap the next layer’s All-Gather with the current layer’s computation.
- Shard prefetching: Prepare subsequent parameters in advance to reduce waiting on communication.
- Limiting fragmentation: Use stable batch shapes, sequence lengths, and memory pool configuration to reduce fragmentation.
Sharding granularity trade-offs:
| Sharding granularity | Peak memory | Communication overhead | Best fit |
|---|---|---|---|
| Coarser | Higher | Lower | Ample memory, limited communication resources |
| Finer | Lower | Higher | Tight memory, ample interconnect bandwidth |
Multimodal models are often structurally heterogeneous, and the text tower, vision tower, and fusion module cannot simply share one strategy. A more robust approach is to first measure memory hotspots per subnetwork, then enable more aggressive checkpointing and finer sharding for the hotspot modules. For example, the vision encoder’s activations grow noticeably when there are many image tokens, and the fusion module tends to produce temporary tensor peaks during cross-modal attention. These spots usually need dedicated memory optimization.
3. Gradient Synchronization and Numerical Consistency: Handling Gradient-Norm Anomalies, Communication Timeouts, and Loss Drift?
The backward phase relies on collective communication for gradient reduction. Common failures can be broken down into “symptom, likely cause, and diagnostic steps.”
| Symptom | Likely cause | Diagnostic steps |
|---|---|---|
| Abnormal gradient norm | Mixed-precision overflow, learning rate too high, abnormal samples, improper gradient-clipping configuration | Check FP32 reduce, gradient clipping, loss scale, and abnormal batches |
| Communication timeout | Network links, communication library version, timeout parameters, abnormal topology configuration | Check the communication backend, rank mapping, link bandwidth, and timeout environment variables |
| Loss drift | Numerical precision mismatch, optimizer states not aligned, data order changed, incorrect shard loading | Compare against a single-card small model, check reduce_dtype, verify checkpoint loading |
When troubleshooting FSDP communication timeouts, work through the following steps in order:
- Compare against a single-card small model to confirm the model structure and data pipeline are correct.
- Check whether reduce_dtype is FP32 to avoid error amplification from low-precision accumulation.
- Check the communication group partitioning, and prefer routing intra-machine communication over high-speed interconnects.
- Capture gradient norms, loss, communication timings, and memory curves to locate the first anomalous step.
- Verify that random seeds, data order, optimizer states, and learning-rate schedules are consistent across all ranks.
In a domestic card environment, a communication timeout is often not just “a slow network.” It may also stem from mismatches in vendor communication library versions, driver versions, topology discovery, container permissions, or device mapping. When troubleshooting, record hardware logs, communication library logs, and framework logs together.
4. Training Stability and Fault Tolerance: How to Keep Long-Running Training from Being Wasted?
Trillion-parameter training often runs for weeks, so stability engineering is indispensable:
- Checkpoint persistence: Periodically save sharded state to support resuming from a checkpoint.
- Monitoring and alerting: Continuously track loss, gradient norm, memory usage, communication throughput, and hardware logs.
- Fast recovery: Tasks should automatically restart from the most recent checkpoint to reduce wasted compute.
- Data and version management: Lock dependency versions and keep a rollback path so upgrades do not break reproducibility.
- Permissions and backups: Grant least privilege on checkpoint directories, and training processes should not have permission to accidentally delete production checkpoints. Back up regularly to independent storage.
For long-running training, establish a mechanism of “checkpoint retention policy + checksum verification + rollback drills.” If a training task exits abnormally, the system should automatically locate the most recent usable checkpoint and verify file integrity before resuming. In a domestic card environment, driver upgrades, firmware upgrades, and communication library upgrades can all affect long-running jobs. Run a short-step regression test before upgrading, and keep a rollback path to the previous version.
4. Validating a Domestic Compute Software Stack: Drivers, Runtime, Operator Libraries, and Communication Libraries Are All Essential
Many readers ask: How do you adapt training for domestic AI accelerators? What are the common mistakes? How do you choose the software stack? The answer usually does not lie in a single algorithm, but in the coordination of hardware, drivers, runtime, operator libraries, communication libraries, and the training framework. Validation should not stop at “it runs”; it must check “it runs stably, it aligns, and it scales.”
Build a domestic compute acceptance checklist. In the command examples below, replace the vendor tool names with those for your actual domestic card.
| Validation item | Command/tool example | Validation goal | ||||||
|---|---|---|---|---|---|---|---|---|
| Driver and firmware | vendor-smi info or npu-smi info, recording driver, firmware, ECC, and temperature |
Driver version, firmware version, and device state are traceable | ||||||
| Device discovery | `lspci | grep -i accelerator`, or a vendor device enumeration tool | All target devices are visible with stable numbering | |||||
| Error logs | `dmesg | grep -Ei “ecc | fault | reset | xid | npu | oom”` | No anomalies such as ECC errors, dropped cards, resets, or OOM |
| Topology | vendor-smi topo -m or a vendor topology tool |
High-speed interconnect paths within a machine are clear | ||||||
| Runtime | python -c "import torch; print(torch.__version__)" |
Framework and runtime versions are consistent | ||||||
| Operator libraries | Run small benchmarks for gemm, attention, layernorm, and softmax |
Both correctness and performance meet the project budget | ||||||
| Communication library | Use a vendor collective communication test tool or an nccl-tests-style tool |
AllGather, ReduceScatter, and AllReduce semantics are consistent | ||||||
| Framework compatibility | Run a minimal FSDP case, an AMP case, and checkpoint save/load cases | FSDP, mixed precision, and checkpoints work stably |
More concretely, you can run the following examples:
# 1. Driver, devices, ECC, error logs (replace tool names per domestic card)vendor-smi infovendor-smi topo -mdmesg | grep -Ei "ecc|fault|reset|oom"# 2. Python and deep learning framework environmentpython -c "import torch; print(torch.__version__)"python -c "import torch; print(torch.cuda.is_available() if hasattr(torch, 'cuda') else 'check vendor adapter')"# 3. Small operator benchmark example; the actual script must adapt to the vendor operator librarypython tools/op_bench.py --op gemm,attention,layernorm --dtype bf16 --repeat 100# 4. Collective communication test example; replace the tool name per domestic cardvendor-collective-test --op allgather,reduce_scatter,allreduce --size 8 --dtype bf16
When choosing a domestic card software stack, prefer solutions with locked versions, traceable issues, and rollback support, and assess data security, downtime recovery, and upgrade risk in advance. In particular, the driver, firmware, compiler, operator library, communication library, and training framework should form a reproducible version combination rather than a temporary mix from multiple sources.
Precision validation is also critical. Start by aligning a small model on a single card and set an acceptable threshold. For example, you can use the maximum relative error of key forward/backward tensors against a reference implementation, along with the relative deviation of loss in the early training phase, as acceptance criteria. Concrete thresholds should be fixed according to the project’s precision budget rather than judged by feel. A common practice is to separately record BF16 training tensor errors, loss deviation, and gradient-norm deviation, then re-check them after scaling to multiple machines.
5. Recommended Path: Pass the Three Acceptance Metrics First, Then Scale Up in Five Stages
For a rigorous adaptation, first define three acceptance metrics: it runs, it aligns, and it scales. Then proceed along this path:
- Operator-level validation: Verify the correctness and performance of basic operators.
- Single-card alignment: Use a small model to confirm the forward pass, backward pass, and optimizer updates are numerically correct.
- Single-machine, multi-card: Verify sharding, All-Gather, Reduce-Scatter, and checkpoint mechanisms.
- Multi-machine scaling: Add nodes incrementally to validate cross-machine communication, topology, and scaling efficiency.
- Full-scale short-step trial: Do a short-step trial run at trillion-parameter scale, confirm there are no anomalies, and only then start long-running training.
Step 5 requires quantitative acceptance and cannot rely on “it runs” alone. Record at least the following fields:
| Metric | Reference range/recommendation | Measurement method | Recorded fields |
|---|---|---|---|
| Peak memory | Ideally below 80%–85% of single-card capacity, leaving an OOM safety margin | Read framework memory statistics or vendor monitoring | step, peak_mem, reserved_mem, capacity |
| Throughput | Use the target hardware or reference implementation as a baseline; multi-machine scaling efficiency can initially reference ~1.7× per node doubling | tokens/s or samples/s |
total_tokens, elapsed, seq_len, global_batch |
| Communication share | Keep it within the project’s threshold, e.g., not more than 20%–30%, depending on interconnect bandwidth | Framework communication timing or profiler | allgather_time, reduce_scatter_time, step_time |
| Relative loss deviation | Example: key tensor max relative error around the 1e-3 scale, loss relative deviation around 0.1%–1%; ultimately governed by the project precision budget | Compare step-by-step against a reference implementation | reference_loss, current_loss, relative_diff |
| Gradient norm | No persistent NaN, Inf, or sharp spikes | Record grad_norm every step | step, grad_norm, lr, clip_value |
| Scaling efficiency | Throughput growth should be near-linear when scaling to multiple machines; investigate communication and topology if it drops abnormally | Compare throughput across node counts | node_num, tokens_per_sec, scaling_ratio |
Turn these metrics into an automated report. Before each training task starts, run a short-step smoke test; after each node expansion, rerun multi-machine acceptance; and after each driver or software-stack upgrade, rerun single-card alignment and multi-machine scaling validation. This surfaces problems such as domestic card OOM, FSDP communication timeouts, and loss drift early, when they are cheap to fix.
6. Summary
Adapting trillion-parameter multimodal models to domestic hardware centers on FSDP as the main thread, connecting four areas: model loading, sharding scheduling, gradient synchronization, and fault-tolerant stability. In real deployment, combine this with tensor parallelism, pipeline parallelism, operator validation, communication library validation, and version management to form a complete engineering loop.
In practice, keep three principles in mind:
- Memory planning cannot count parameters alone; it must include optimizer states, activations, communication buffers, and a safety margin in the budget.
- Multi-machine training cannot stop at a successful launch; you must quantify throughput, communication share, peak memory, and loss deviation.
- Domestic compute validation cannot rely on single operators alone; it must cover the driver, runtime, compiler, operator library, communication library, and training framework.
By validating stage by stage from single-card alignment to multi-machine scaling, and by quantifying memory, throughput, communication, and convergence deviation into acceptance criteria, you can establish a reusable path for ultra-large model training on domestic AI accelerators and significantly reduce the risk of domestic card OOM, FSDP communication timeouts, and non-reproducible multi-machine training.
