Training Trillion-Parameter Models on Domestic AI Accelerators: A Native FSDP2 Adaptation Guide

    This article examines how to adapt training for models exceeding one trillion parameters to domestic AI accelerator platforms. It covers the core constraints of memory, compute/communication, and ecosystem adaptation, then details a native FSDP2 sharding approach built on distributed tensors (DTensor). It walks through three key stages of the training pipeline—model loading, shard scheduling, and gradient synchronization—followed by a five-layer adaptation checklist spanning the hardware/driver, runtime, communication library, training framework, and operator layers, plus a generalized validation case for an open-source 2.8-trillion-parameter model. Readers will find pseudocode, configuration guidance, a performance-profiling example, and a list of common errors, together forming a transferable verification path: get it running first, make it stable, then optimize efficiency.

    In recent years, large-model parameter counts have grown rapidly from tens of billions to hundreds of billions and then to the trillions, shifting the focus of training engineering from “whether the algorithm can converge” to “whether the compute can support it, whether the software stack can run end to end, and whether training can be reliably reproduced.” When an open-source community releases a flagship model with 2.8 trillion parameters, the real challenge is often not the model architecture itself, but how to build a complete, verifiable, and debuggable training pipeline across domestic AI accelerators, vendor drivers, communication libraries, training frameworks, and the operator ecosystem.

    This article focuses on adapting trillion-parameter model training to domestic AI accelerator platforms. It emphasizes a native FSDP2 sharding training path, the key stages of a complete training pipeline, and the checklists and engineering methods involved in adapting to domestic AI accelerators. One point should be stated up front: there is no one-size-fits-all configuration that can be reused unconditionally on domestic compute platforms. Actual adaptation results depend on the specific hardware form factor, driver version, communication library implementation, degree of framework adaptation, and operator completeness. Accordingly, this article offers not absolute conclusions but a transferable verification path: get it running first, then make it stable, then optimize efficiency.

    1. Core Constraints of Trillion-Parameter Model Training Adaptation

    Training adaptation for a trillion-parameter model is first and foremost not an isolated technical problem but a systems engineering problem. Engineering teams usually face three hard constraints at the same time.

    1.1 The Memory Wall

    Storing the parameters of a trillion-parameter model alone in FP16 or BF16 requires several terabytes of memory. Once you also account for the Adam optimizer’s first and second moments, gradients, activations, temporary communication buffers, and the framework’s own overhead, the actual memory requirement far exceeds the size of the parameters themselves. For a single node with multiple cards or a small-scale cluster, this memory pressure directly determines whether training can even start.

    As a result, an adaptation plan cannot focus only on “whether the model parameters can be loaded.” It must also evaluate the following:

    • Whether parameters, gradients, and optimizer states are already sharded;
    • Whether activations need selective recomputation;
    • Whether All-Gather and Reduce-Scatter operations during the forward and backward passes create memory peaks;
    • Whether temporary tensors fail to be released in time;
    • Whether multimodal models use differentiated sharding strategies for the visual encoder, text decoder, and projection layers.

    1.2 The Compute Wall and the Communication Wall

    When a model must be split across hundreds or thousands of accelerators, inter-card communication becomes the core factor affecting throughput. If communication and computation cannot overlap, or if the device mesh is poorly planned, hardware utilization drops significantly. Common problems include:

    • High-frequency communication executed across nodes without being prioritized within the high-speed interconnect domain;
    • Insufficient overlap between All-Gather/Reduce-Scatter and backward computation;
    • Poor device mesh design when combining tensor parallelism, pipeline parallelism, and data parallelism;
    • MoE expert routing causing frequent All-to-All communication and load imbalance;
    • Improper gradient accumulation settings, leading to communication that is either too frequent or that introduces excessive update latency.

    1.3 The Ecosystem Adaptation Wall

    Between domestic AI accelerators and mainstream training frameworks, the relationship is usually not “install a driver and you can train right away.” Real adaptation requires working through the full vertical stack of hardware—driver—runtime—communication library—training framework—operator library. A gap at any layer can cause training to fail to start, produce precision anomalies, deliver low performance, or become unstable over long training runs.

    In essence, training adaptation means solving three dimensions at once: whether memory can hold the model, whether the compute can be kept fed, and whether the ecosystem can run end to end.

    2. The FSDP2 Sharding Training Path: Principles and Executable Configuration

    2.1 Core Principles of FSDP2

    FSDP stands for Fully Sharded Data Parallel. Its core idea is that, within a data-parallel framework, it shards not only the input data but also the model parameters, gradients, and optimizer states for storage. Each card holds only part of the complete model and gathers the needed parameters on demand during forward and backward computation, releasing them immediately after computation to significantly reduce per-card memory usage.

    Compared with earlier implementations, FSDP2 places more emphasis on being native and modular. One key change is the use of distributed tensors—DTensor—as the sharding abstraction. Note that “DTensor” should generally be understood as Distributed Tensor, a distributed tensor, rather than simply a “group of tensors.” Through DTensor, sharding semantics, the device mesh, and computation logic can be better decoupled.

    Typical benefits of FSDP2 include:

    • Clearer expression of parameter sharding, suitable for complex and multimodal models;
    • Easier combination with the device mesh, mixed precision, and automatic wrapping policies;
    • Better support for overlapping communication and computation by prefetching the next layer’s parameters;
    • Easier configuration of differentiated sharding and recomputation strategies for heterogeneous submodules in multimodal models.

    2.2 Differences on Domestic AI Accelerators

    When running FSDP2 on domestic AI accelerators, pay particular attention to the following differences:

    • The device type may not be the conventional cuda, but an accelerator device type defined by the vendor;
    • The communication backend may be a vendor communication library rather than nccl;
    • The operator library, memory allocator, and runtime environment may have version dependencies;
    • Device mesh creation must match the actual number of visible cards, node topology, and communication library capabilities;
    • Checkpoint formats, distributed storage interfaces, and framework adaptation versions need separate validation.

    Therefore, FSDP2 code cannot stop at a conceptual illustration; it must explicitly specify dependency versions, device initialization, communication backend, device mesh, and parameter sharding strategy.

    2.3 FSDP2 Training Initialization Pseudocode

    The following is pseudocode closer to an executable approach. In actual use, it needs to be adjusted according to the specific device type, communication backend, and PyTorch adaptation version of the domestic platform.

    1. import os
    2. import torch
    3. import torch.distributed as dist
    4. # Dependency note: PyTorch 2.4+ offers more complete FSDP2/DTensor support.
    5. # If the current version lacks the fully_shard interface, confirm the framework
    6. # version or fall back to an FSDP1 adaptation approach.
    7. from torch.distributed.device_mesh import init_device_mesh
    8. from torch.distributed.fsdp import fully_shard
    9. # RANK, LOCAL_RANK, WORLD_SIZE, etc. are set via torchrun or a similar launcher.
    10. dist.init_process_group(backend="ccl") # Replace the communication backend for domestic cards with the vendor communication library as appropriate
    11. rank = dist.get_rank()
    12. world_size = dist.get_world_size()
    13. local_rank = int(os.environ.get("LOCAL_RANK", 0))
    14. # If the device type is a cuda compatibility layer, cuda can be kept; if it is npu, xpu, etc., replace it with the corresponding device API.
    15. torch.cuda.set_device(local_rank)
    16. device_type = "cuda"
    17. # Create a 1D device mesh representing a pure data-parallel/FSDP scenario.
    18. # For multi-dimensional parallelism, a 2D or 3D mesh can be constructed further.
    19. mesh = init_device_mesh(
    20. device_type=device_type,
    21. mesh_shape=(world_size,),
    22. mesh_dim_names=("dp",)
    23. )
    24. # Pseudocode: build the model skeleton using a meta device or a sharded initialization
    25. # approach, to avoid instantiating the full trillion-parameter model on a single card.
    26. model = build_model_from_config(config) # Ensure initialization does not trigger a full memory allocation
    27. # fully_shard parameters depend on the actual version; common points of attention
    28. # include mesh, sharding_strategy, mp_policy, auto_wrap_policy, reshard_after_forward, etc.
    29. model = fully_shard(
    30. model,
    31. mesh=mesh,
    32. sharding_strategy="FULL_SHARD", # Illustrative; confirm the value against the current framework version
    33. mp_policy={
    34. "param_dtype": torch.bfloat16,
    35. "reduce_dtype": torch.float32,
    36. }, # Illustrative parameters; an actual strategy object may need to be passed
    37. )
    38. optimizer = torch.optim.AdamW(
    39. model.parameters(),
    40. lr=1e-4,
    41. betas=(0.9, 0.95),
    42. )
    43. # Single training step pseudocode
    44. for batch in dataloader:
    45. loss = model(batch["input_ids"], labels=batch["labels"])
    46. loss.backward()
    47. optimizer.step()
    48. optimizer.zero_grad()

    If the current framework version does not yet provide a stable fully_shard interface, engineering teams can first use FSDP1 for adaptation validation. Although FSDP1 uses a different abstraction, it can likewise achieve parameter sharding, gradient reduction, and memory optimization. What matters is not the interface name but whether it meets the requirements for sharding semantics, device mesh design, and communication overlap.

    3. Three Key Stages of a Complete Training Pipeline

    3.1 Model Loading

    A trillion-parameter model cannot be loaded onto a single card all at once and must use a sharded loading strategy. Model loading is not only about “whether it can be read in” but also about “whether the shard mapping is correct” and “whether checkpoint resumption is reliable.”

    In practice, pay attention to the following:

    • Checkpoints should preferably use a sharded format (sharded checkpoint), so each card reads only the shard that belongs to it;
    • During loading, validate the shard mapping to ensure rank, tensor name, shape, and dtype are consistent;
    • Do not silently ignore missing shards; instead, record them clearly and trigger conversion, completion, or an abort flow;
    • Save optimizer states, learning rate scheduler, training step, random seed, and data sampler state together;
    • Keep the checkpoint-resumption directory structure clear, making it easy for fault recovery and cross-platform migration.

    An illustrative checkpoint-resumption directory structure is shown below:

    1. checkpoint/
    2. step_1000/
    3. model/
    4. __0_0.distcp
    5. __1_0.distcp
    6. metadata.json
    7. optimizer/
    8. state.pt
    9. train_state.json
    10. dataloader_state.pt
    11. rng_state.pt

    During loading, it is recommended to perform the following validations:

    • Verify that world_size matches the number of checkpoint shards;
    • Verify that the total parameter shape matches the configuration;
    • Verify that optimizer states align with the current parameter shards;
    • Verify that the training step, learning rate, and gradient accumulation steps are restored;
    • Verify the data cursor or sampler state to avoid re-consuming or skipping data;
    • For precision-sensitive models, it is recommended to record parameter summaries or checksums before and after loading.

    3.2 Shard Scheduling

    Shard scheduling determines how the model is split, which devices it is placed on, and which parallelism strategies are used. It is not a single parameter setting but a combined trade-off among memory, throughput, and stability.

    Common parallelism strategies and their applicable scenarios can be summarized as follows:

    Parallelism strategy Main benefit Main risk Recommended use
    FSDP/ZeRO-style sharding Reduces memory for parameters, gradients, and optimizer states Frequent communication; relies on high-bandwidth interconnect Suited to cases with large parameter counts that do not fit in single-card memory
    Tensor parallelism (TP) Reduces per-layer or per-module memory; suitable for ultra-large models Frequent intra-layer communication; high interconnect demands Keep within a single node’s high-bandwidth domain where possible
    Pipeline parallelism (PP) Reduces cross-node communication pressure; suitable for deep models Complex scheduling; may produce bubbles Suited to deep, cross-node models with many layers
    Expert parallelism (EP) Suited to MoE model expert distribution Obvious routing imbalance and All-to-All pressure Requires expert load balancing and communication optimization

    When scheduling in practice, it is recommended to follow these principles:

    • Prioritize high-frequency communication within a single node or a high-bandwidth interconnect domain;
    • Prioritize recomputation or finer-grained sharding for the modules with the greatest memory pressure;
    • In multimodal models, configure the visual encoder and decoder with separate sharding strategies;
    • Activation recomputation is not better in greater quantity; balance computation overhead against memory savings;
    • For MoE models, additionally check expert load balancing, routing confidence, and All-to-All communication overhead.

    3.3 Gradient Synchronization

    Gradient synchronization is key to training stability. FSDP2 is usually combined with data parallelism, tensor parallelism, pipeline parallelism, or expert parallelism, so one must consider not a single communication primitive but the entire communication chain.

    When FSDP2 is combined with data parallelism, parameters and gradients are typically reduced via Reduce-Scatter or All-Reduce-style operations; in tensor parallelism, intra-layer computation may rely on All-Reduce, All-Gather, or Reduce-Scatter; in pipeline parallelism, P2P communication is the main reliance; and in MoE models, All-to-All expert routing communication is additionally introduced.

    The following configuration requirements need to be made explicit from an engineering standpoint:

    • Communication backend: On domestic platforms, confirm whether the communication library supports the current number of devices, node topology, and collective communication primitives;
    • Communication dtype: A common practice is to compute in BF16 and reduce in FP32 or higher precision to reduce numerical error;
    • Gradient accumulation: Accumulating multiple micro-batches before a single parameter update can lower communication frequency, but the loss must be scaled correctly and gradient explosion avoided;
    • Mixed precision: Distinguish among parameter, gradient, reduction, and master-weight precision to avoid precision loss on the critical path;
    • Deterministic reproducibility: Fix random seeds, data order, communication backend, and deterministic operator flags, and set acceptable tolerances for reductions that cannot guarantee bit-for-bit consistency;
    • Gradient clipping and anomaly detection: During long training runs, monitor gradient norms, loss spikes, and NaN/Inf.

    A simplified configuration approach is as follows:

    1. - Data parallelism: FSDP2 FULL_SHARD
    2. - Gradient reduction: BF16 compute, FP32 reduce
    3. - Gradient accumulation: perform one optimizer update after N micro-batches
    4. - Mixed precision: parameters BF16, optimizer states FP32
    5. - Determinism: fix the seed, enable deterministic algorithms, record environment versions
    6. - Fault tolerance: periodically save parameters, optimizer, scheduler, and data state

    It must be emphasized that after FSDP2 is combined with TP and PP, different parallelism dimensions may use different communication backends, and framework versions and communication library implementations also affect stability. Therefore, it is recommended to run a short smoke test before formal training to verify that gradients are correct, loss decreases, communication does not time out, and parameter updates are as expected.

    4. Five-Layer Adaptation Checklist and Case for Domestic AI Accelerators

    Adapting to domestic AI accelerators cannot stop at the “can the framework be imported” level. It is recommended to check according to a five-layer structure.

    4.1 The Five-Layer Checklist

    Layer Key checks How to locate issues Acceptance criteria
    Hardware/driver layer Whether cards are visible, health status, driver version, temperature and power Vendor management tools, lspci, device query commands All cards recognized by the system, with no abnormal offline status or frequent errors
    Runtime layer Whether the framework recognizes devices, whether versions match, whether device initialization succeeds Python version probing, device count probing, simple tensor operations Multiple cards can initialize, basic operators can execute
    Communication library layer Communication backend, topology recognition, collective communication stability, timeouts and error codes all-reduce/all-gather tests, communication logs, topology tools Stable small-scale communication; no frequent timeouts in large-scale communication
    Training framework layer Support for FSDP2, DTensor, optimizer, checkpoints, and mixed precision Import tests, unit tests, single-step training Forward, backward, and parameter update can be completed
    Operator layer Whether key operators exist, whether precision is consistent, whether there are performance regressions Operator unit tests, numerical alignment, performance profiling Key-path operators are usable; error is within an acceptable range

    On a practical level, you can refer to the following commands and log fields.

    Hardware/driver layer

    Use the vendor-provided device management tool to query card status and record the following log fields:

    1. device_id, driver_version, firmware_version, health_status, temperature, power

    Acceptance criteria:

    • All accelerators participating in training are visible;
    • No frequent card drops, ECC errors, or driver timeouts;
    • The driver version matches the runtime and communication library versions.

    Runtime layer

    You can use Python to probe whether the framework correctly recognizes devices:

    1. import torch
    2. print(torch.__version__)
    3. print(torch.cuda.is_available()) # May need to be replaced with the corresponding device-check interface on domestic platforms
    4. print(torch.cuda.device_count()) # Likewise, replace with the corresponding device-count interface

    Record fields:

    1. torch_version, runtime_version, device_count, device_type, allocator_status

    Acceptance criteria:

    • The device count matches the actual number of cards;
    • The framework version is compatible with the operator library and communication library;
    • Basic tensor creation, copying, and computation have no anomalies.

    Communication library layer

    It is recommended to use a standard collective communication test to verify communication library capabilities. Test with small messages first, then with large messages, and record:

    1. rank, world_size, backend, message_size, latency, bandwidth, timeout_count

    Acceptance criteria:

    • Small-message communication does not hang;
    • Large-message communication bandwidth is stable;
    • No persistent timeouts in multi-node, multi-card scenarios;
    • Communication logs can pinpoint the specific rank and topology.

    Training framework layer

    The training framework layer needs to focus on checking FSDP2, DTensor, optimizer, and checkpoint functionality. Record fields can include:

    1. fsdp_version, mesh_shape, sharding_strategy, mp_policy, world_size, local_rank

    Acceptance criteria:

    • One forward pass, backward pass, and optimizer update can be completed;
    • Memory usage decreases after parameter sharding;
    • Loss is finite with no NaN/Inf;
    • Checkpoints can be saved and successfully loaded.

    Operator layer

    The operator layer needs to be validated around the training critical path, including matrix multiplication, LayerNorm, Attention, RoPE, SwiGLU, and Loss. Record fields can include:

    1. op_name, input_dtype, output_dtype, shape, tolerance, status, fallback

    Acceptance criteria:

    • Key operators are usable at the target precision;
    • Key operator error is within the set tolerance;
    • If a fallback implementation exists, its impact on performance and precision needs to be evaluated;
    • No abnormal crashes occur in long-sequence or large-shape scenarios.

    4.2 Case: Validating an Open-Source 2.8-Trillion-Parameter Model on Domestic Accelerators

    The following provides a generalized domestic AI accelerator adaptation validation case. This case does not target a specific vendor’s interface but describes the executable steps an engineering team takes when validating a trillion-parameter model on a domestic platform.

    Case goal: On a domestic AI accelerator cluster, based on a PyTorch compatibility layer or a vendor adaptation framework, complete the multi-card sharded training startup of a certain open-source 2.8-trillion-parameter model, and verify model loading, forward/backward passes, gradient synchronization, checkpoint resumption, and stability.

    Validation steps:

    1. Freeze software versions

      • Record the OS, driver, runtime, communication library, Python, PyTorch, and vendor plugin versions;
      • Ensure all nodes use a consistent image to avoid version differences between nodes.
    2. Complete single-node multi-card recognition

      • Verify that all domestic accelerators within a single node are recognizable;
      • Run basic matrix operations and communication tests;
      • Check device temperature, power, and ECC status.
    3. Complete multi-node communication testing

      • Verify cross-node All-Reduce, All-Gather, Reduce-Scatter, and P2P communication;
      • Record bandwidth and latency under different message sizes;
      • Troubleshoot timeout, disconnection, and topology inconsistency issues.
    4. Verify model loading

      • Convert the 2.8-trillion-parameter model into a sharded checkpoint;
      • Verify the number of shards, parameter shapes, and mapping relationships;
      • Run a small-step loading test to confirm that no single-card OOM is triggered.
    5. Verify FSDP2 single-step training

      • Wrap the model using the device mesh and FSDP2 strategy;
      • Execute one forward pass, backward pass, and optimizer update;
      • Check whether the loss, gradient norm, and parameter update are normal.
    6. Verify checkpoint resumption

      • Save a checkpoint after training several steps;
      • Simulate a fault or restart;
      • Restore from the checkpoint and verify that the loss curve is continuous;
      • Check whether the optimizer state and random seed are restored.
    7. Form acceptance metrics

      • Training can start and run continuously;
      • Loss is finite and shows a downward trend;
      • No frequent NaN/Inf;
      • Training progress is continuous after checkpoint recovery;
      • Peak memory stays within the expected range;
      • Communication timeouts and driver errors can be located via logs.

    The significance of this case lies not in providing a fixed performance number but in establishing a reusable validation loop: each step has an input, an operation, logs, and acceptance criteria, avoiding trial-and-error based on experience in a complex domestic compute environment.

    5. Performance Profiling and Common Errors

    5.1 Example of Performance Profiling Output

    During adaptation, it is recommended to add structured logging to the training framework so that compute-bound, communication-bound, and load-imbalance situations can be distinguished. For example:

    1. [step=10][rank=0] loss=2.1345 grad_norm=0.8723
    2. [profile][stage=forward] compute_ms=120.3 all_gather_ms=80.2 overlap_ratio=0.61
    3. [profile][stage=backward] compute_ms=210.8 reduce_scatter_ms=95.4 overlap_ratio=0.58
    4. [memory][rank=0] allocated_gb=712.4 reserved_gb=730.1 peak_gb=718.9

    When interpreting this output, focus on the following:

    • If compute time is high while communication wait is low, it is usually compute-bound;
    • If All-Gather or Reduce-Scatter wait is significant, it is usually communication-bound;
    • If step time varies greatly across ranks and memory usage is uneven, load imbalance likely exists;
    • If memory keeps growing without dropping, there may be a cache that is not released in time or a checkpoint-loading anomaly;
    • If the loss suddenly becomes abnormal, prioritize checking the learning rate, gradient clipping, mixed precision, and communication reduction precision.

    5.2 Common Errors and Precautions

    The following errors are common in actual adaptation:

    • The device mesh shape does not match the actual world_size;
    • Incorrect calculation of single-node card count and multi-node node count;
    • The communication backend does not match the device type;
    • Operators are missing on the domestic platform, causing a mid-training fallback to inefficient implementations;
    • The checkpoint format is incompatible with the framework version;
    • Data sampler state is not saved during checkpoint resumption;
    • Sharding dimension conflicts arise when FSDP2 is combined with tensor parallelism;
    • Reduction precision is too low under mixed precision, causing gradient anomalies;
    • Loss scaling errors occur during gradient accumulation;
    • Performance optimization is done too early, before stability validation is complete.

    It is recommended that engineering teams prepare a troubleshooting table before formal training, mapping common symptoms, log fields, diagnostic commands, and handling actions. For example, when training cannot start, check the driver and device recognition first; when communication times out, check the communication library and topology first; when the loss is abnormal, check precision, gradient clipping, and checkpoint recovery first; and only when performance is low should you use performance profiling to distinguish compute, communication, and load problems.

    6. Summary

    The training adaptation of trillion-parameter models is a systems engineering effort centered on the memory, compute, and ecosystem constraints. The native FSDP2 sharding training path—through distributed tensor abstraction, parameter sharding, and communication-computation overlap—provides a mature approach to alleviating the memory wall and the communication wall; sharded model loading, fine-grained shard scheduling, and gradient synchronization together form a complete training loop from loading to convergence.

    For domestic AI accelerator platforms, the key to adaptation lies not in finding some single-point “acceleration switch” but in establishing a verifiable engineering process: first complete the five-layer check across hardware, driver, runtime, communication library, framework, and operators; then use short-step training to validate FSDP2, mixed precision, checkpoint resumption, and gradient synchronization; and finally continuously tune based on logs and performance profiling. Only when conditions are met, validation is thorough, and iteration continues can a trillion-parameter model achieve stable, scalable training capability on a domestic compute platform.