Trillion-Parameter Model Training: End-to-End Sharded Loading and Gradient Synchronization
As models scale from tens of billions to trillions of parameters, adding more devices alone no longer delivers linear training efficiency. This article examines the engineering workflow for adapting trillion-parameter training to heterogeneous AI accelerators, covering memory constraints, sharded model loading, parameter scheduling, gradient synchronization, multimodal training, and practical validation methods. It focuses on numerical correctness, memory usage, throughput, and recoverability as the core criteria for a successful adaptation.
As model sizes grow from tens of billions to trillions of parameters, simply adding more devices can no longer provide linear improvements in training efficiency. Model weights, gradients, and optimizer states consume large amounts of accelerator memory, while communication overhead increases rapidly with cluster size.
Recent industry efforts have adapted trillion-parameter open-source models to domestic AI acceleration hardware. A common characteristic of these projects is that every stage of distributed training is isolated and validated independently. This article presents a complete engineering workflow, covering the background constraints, adaptation targets, model loading, sharding strategies, gradient synchronization, and multimodal training paths. It also provides practical checks that can be applied during implementation.
1. Background: Four Constraints Introduced by Scale
1.1 Memory Constraints
In mixed-precision training, each parameter typically requires storage for low-precision weights, high-precision master weights, gradients, and the first- and second-order optimizer moments.
A common estimate is approximately 16 bytes per parameter. For a trillion-parameter model, the static training state alone can reach the scale of tens of terabytes. A single device cannot store all of this data, so sharded storage across devices is required.
1.2 Communication Constraints
After parameters are sharded, each layer must temporarily gather its complete parameters before computation and release them afterward. The process is repeated during backpropagation.
Because communication volume is correlated with the number of parameters, network bandwidth and topology become major bottlenecks.
1.3 Hardware Heterogeneity
Different AI accelerators vary significantly in operator implementations, collective communication libraries, and compiler-toolchain maturity.
When the same training code is migrated to new hardware, common problems include:
- Missing implementations for individual operators
- Numerical results that differ from the reference implementation
- Communication paths whose performance is substantially below expectations
1.4 Multimodal Training Constraints
Image, video, and text encoders have substantially different architectures, and their sequence-length distributions are also inconsistent.
As a result, data loading, batch construction, and sharding boundaries across modules are more complex than in text-only models.
2. Define Adaptation Success Before Implementation
The goal of adaptation is not merely to make the program start. A successful adaptation should satisfy all four of the following requirements.
| Goal | Evaluation criteria | Common failure symptoms |
|---|---|---|
| Numerical correctness | With the same seed and data, the loss and gradient norm over the first several steps match the reference implementation | The loss curve diverges or individual steps produce NaN |
| Controlled memory usage | Peak memory remains within a safe margin and supports the target sequence length and batch size | Out-of-memory errors during training |
| Sufficient throughput | Tokens processed per unit of time approach a reasonable proportion of the hardware’s theoretical capability | Excessive time spent waiting for communication |
| Recoverability | Training remains continuous after saving and restoring a checkpoint | The loss changes abruptly after recovery |
These four goals must be validated separately. Looking only at throughput while ignoring numerical consistency can allow problems to remain hidden until long-running training.
3. Model Loading and Initialization
A model of this size cannot be fully constructed in the memory of a single machine. The loading process therefore needs to follow the sharding rules.
A common approach consists of three steps:
- Build the model structure on the meta device. This records tensor shapes without allocating actual storage.
- Allocate the corresponding parameter shards on the target devices according to the sharding rules.
- Read weights from the checkpoint by shard and write them into the local shards.
This approach keeps the memory peak during startup within an acceptable range and can also significantly reduce initialization time.
The following details require particular attention during loading:
- Key mapping: Parameter names in the checkpoint must correspond one-to-one with the model structure. Before loading, validate the mapping and report missing and unexpected entries to avoid silently dropping weights.
- On-demand reading: Each process should read only the shards for which it is responsible. If every process reads the complete file at the same time, the storage system will experience unnecessary pressure.
- Consistent precision: Use a consistent target precision during loading to avoid extra temporary tensors caused by implicit type conversions.
Illustrative pseudocode:
def load_sharded(model, ckpt_dir, rank, world_size):index = read_index(ckpt_dir)for name, param in model.local_params(rank, world_size):tensor = read_tensor(index[name], name)assert tensor.shape == param.global_shape, f"Shape mismatch: {name}"param.copy_(tensor.to(param.dtype))
4. Sharding Strategies and Scheduling
Sharding Granularity
Layer-wise sharding is a common choice. Gathering the parameters of a layer together reduces the number of communication operations and simplifies management.
Parameters, gradients, and optimizer states can be partitioned uniformly. Alternatively, only optimizer states can be sharded in exchange for lower communication overhead. The choice depends on the relative balance between available memory and network bandwidth.
Scheduling Considerations
- Prefetching: While computing layer i, asynchronously gather the parameters required by layer i+1 so that communication is hidden as much as possible behind computation.
- Timely release: Release complete parameters immediately after the forward computation no longer needs them to reduce the memory peak.
- Pipeline overlap: Run communication and computation on separate execution streams, synchronizing only where data dependencies require it.
- Communication aggregation: Combine many small tensors into larger communication blocks to reduce the startup overhead of each operation.
The following pseudocode illustrates the order of these actions during a training step:
def train_step(batch):for layer in model.layers:full_params = gather_shards(layer) # Gather parameters on demand before the forward passx = layer.forward(full_params, x)release(full_params) # Release them immediately after useloss = compute_loss(x, batch.labels)loss.backward() # Gather again during backpropagation and compute gradientslocal_grads = reduce_scatter(grads) # Reduce gradients and scatter them across devicesoptimizer.step(local_grads) # Each device updates only its own shard
5. Gradient Synchronization
The purpose of gradient synchronization is to ensure that every device receives the globally averaged gradient for the shard it manages.
Several points are especially important:
- Reduce-scatter: Devices first sum the gradients and then partition the result across the corresponding devices. Compared with performing a full all-reduce followed by partitioning, this approach reduces both communication and storage overhead.
- Gradient accumulation: When memory is limited, gradients can be accumulated over multiple micro-batches to effectively increase the global batch size. When the number of accumulation steps changes, the learning rate generally needs to be adjusted accordingly.
- Global gradient norm: The norm used for gradient clipping must be reduced across all shards. If it is calculated locally, the clipping strength will vary with the number of shards, leading to inconsistent training behavior. This is one of the easiest parts of sharded training to implement incorrectly.
- Loss scaling at low precision: Low-precision gradients may underflow. Dynamic loss scaling can mitigate this issue. When an overflow is detected, the update for that step should be skipped and the event should be recorded.
6. Multimodal Training Paths
Multimodal models typically consist of a text backbone, one or more vision encoders, and projection modules that map visual features into the language representation space.
The following issues must be addressed during training:
- Data organization: Bucket samples by modality and sequence length to reduce invalid computation caused by padding.
- Training-stage separation: The vision encoder can remain frozen during the early stage of training. After the projection layers stabilize, joint training can begin to reduce early gradient instability.
- Sharding boundaries: Vision encoders and language backbones often differ significantly in parameter scale. They should use separate sharding groups to prevent small modules from participating in large-scale communication.
- Loss composition: Multimodal or multitask losses require appropriate weighting. Each loss curve should be monitored separately to prevent one component from dominating the training direction.
7. Validation Methods
After the adaptation is complete, validate each item in sequence:
- Single-step alignment: Fix the random seed and input data, then compare the loss and gradient norm over the first several steps. For low-precision training, the acceptable error threshold should be looser than for high-precision training, and the threshold should be defined separately for each precision type.
- Operator-level validation: Verify operators individually against the reference implementation to identify missing implementations and numerical deviations before running long training jobs.
