Multi-Node, Multi-GPU Training on Domestic AI Accelerators: A Setup and Troubleshooting Guide

    This guide explains how to build a reproducible training pipeline for multi-node, multi-GPU training on domestic AI accelerators such as Huawei Ascend, Cambricon, and Hygon. It shows why single-node demos often fail once you scale to a cluster, how to localize common failures by affected layer (environment, communication, parallelism, numerics), and how to align driver/runtime versions and confirm device topology before writing training code. It walks through choosing and deriving DP/TP/PP/ZeRO parallel groups from the hardware topology, verifying the pipeline in stages from a single card up to full scale, checking numerical alignment against a single-card baseline, tuning stability and performance, and saving checkpoints safely with atomic publish and rollback. Runnable Python examples and configuration tables are included so teams can turn an accidental success into a stable, reproducible, rollback-capable engineering capability.

    1. Start with a Reproducible Pipeline

    As domestic AI accelerators (such as Huawei Ascend, Cambricon, and Hygon) move into training clusters, many teams hit the same problem: a single-node demo runs fine, but as soon as they move to a multi-node, multi-GPU setup, training either errors out, or it starts but the loss behaves abnormally, hangs for a long time, or hits frequent OOM. A “training pipeline” is not just a launch script—it is a complete loop that spans environment setup, data loading, model construction, distributed initialization, parallel partitioning, forward/backward passes, gradient synchronization, checkpoint saving, and resuming from checkpoints.

    One point needs to be stressed up front: domestic AI accelerators are not a single ecosystem. Vendors, card models, and framework adaptation layers can differ significantly. Ascend, Cambricon, and Hygon, for example, may all differ in device APIs, communication libraries, operator libraries, mixed-precision interfaces, and logging tools. So you cannot simply treat it as “rename CUDA to something else”; you should rely on the actual card model and the vendor’s framework documentation.

    This article focuses on practical problems around domestic AI accelerators, multi-node multi-GPU training, the training pipeline, environment configuration, and common errors, and gives actionable setup and verification methods. The goal is not just to get training “to run,” but to turn an accidental success into a stable, reproducible, rollback-capable engineering capability.

    2. Localizing Common Errors: Look at the Symptom First, Then the Affected Layer

    Multi-node, multi-GPU training failures usually fall into four categories: hardware/runtime adaptation, the communication link, parallel strategy configuration, and precision/numerical issues. Rather than blindly changing settings, start by identifying the affected layer using the table below.

    Symptom Affected layer Quick check command / method Recovery action
    Errors at startup about missing operators or version mismatch Driver, runtime, operator library, framework plugin python -c "import torch; print(torch.__version__)"; for domestic cards check npu-smi info and the torch_npu version; if needed, capture pip freeze Align node images, pin dependency versions, redistribute the base environment
    Single node works, multi-node hangs or communication times out Network, NIC binding, communication backend Check NCCL_* / HCCL_* config; run a benchmark with nccl-tests or hccl-tests; if needed enable NCCL_DEBUG=INFO for detailed logs Fix communication backend, NIC binding, timeout thresholds, and retry policy
    Out of memory (OOM) Parallel partitioning, micro-batch, optimizer state Observe the memory curve with nvidia-smi or npu-smi info Reduce micro-batch, enable gradient accumulation, adjust TP/PP, enable ZeRO
    Loss not decreasing, spiking, or NaN Data pipeline, learning rate, mixed precision First run a small-step overfit check on a tiny dataset, with the random seed and sample order fixed Fix the data, lower the learning rate, check loss scaling, add gradient clipping

    The value of this approach is that you first determine whether the problem sits at the “environment,” “communication,” “parallel,” or “numerical” layer, avoiding repeated trial-and-error at the wrong layer. Multi-node hangs in particular are often not a bug in the model code itself, but come from environment drift between nodes, incorrect NIC binding, broken container networking, or mismatched communication-backend versions.

    3. Environment Preparation: Version Alignment and Topology Confirmation Come First

    Getting the domestic-card multi-node, multi-GPU pipeline to run starts not with writing training code, but with making the environment reproducible, verifiable, and rollback-capable.

    1. Align driver and runtime: the accelerator driver, communication library, operator library, and framework plugin must be identical across nodes. Many “single-node works, multi-node hangs” cases are not network problems but version drift between nodes.
    2. Lock dependencies: use requirements.txt, constraints.txt, or fixed versions inside an image to avoid implicit upgrades. For domestic cards in particular, lock the vendor adaptation packages, communication library, and operator library versions.
    3. Network and device visibility: confirm that all nodes can reach each other, that every card is visible to its peers, and that RDMA/NIC binding is correct. Beyond a basic ping, also check container networking, firewall rules, RDMA port connectivity, and clock synchronization between nodes.
    4. Do an isolation check before benchmarking: communication benchmarks consume bandwidth, so run them on a test node or in an isolated environment and record a baseline, rather than benchmarking directly on critical production nodes.

    Choose example commands based on the card type:

    1. # [NVIDIA] Inspect inter-card topology
    2. nvidia-smi topo -m
    3. # [Domestic Ascend] Inspect device status and topology
    4. npu-smi info
    5. npu-smi info -t topo
    6. # [NVIDIA] Collective communication benchmark (compile and install nccl-tests first)
    7. all_reduce_perf -b 8 -e 4G -f 2 -g 8
    8. # [Domestic Ascend] Use hccl-tests to validate collective communication
    9. # Configure card count, data size, and test cases per the official documentation
    10. # To debug communication, you can try enabling verbose logs, e.g.:
    11. NCCL_DEBUG=INFO python train.py
    12. # Different domestic-card communication libraries may use their own log switches and log
    13. # paths, so follow the vendor documentation.

    Here it is worth stressing again: domestic AI accelerators are not simply CUDA with cuda renamed to something else. Vendors adapt differently, and the common differences look like this.

    Item NVIDIA CUDA approach Domestic Ascend example Other domestic card approach
    Device selection torch.cuda.set_device(local_rank) import torch_npu; torch.npu.set_device(local_rank) Use the vendor’s PyTorch extension or dedicated device API
    Communication backend nccl hccl Use the vendor’s communication library and corresponding backend name
    Device tensor torch.device("cuda:0") torch.device("npu:0") Use the vendor-supported device string or tensor placement
    Mixed precision torch.cuda.amp.autocast, GradScaler Use the equivalent autocast/GradScaler provided by torch_npu, or the vendor-recommended interface; if unsure, disable AMP Replace per the vendor documentation; do not assume CUDA AMP works directly
    Training framework PyTorch / DeepSpeed / Megatron PyTorch + torch_npu, or a vendor-adapted framework Use framework and version combinations certified by the vendor

    If your team uses MindSpore, PaddlePaddle, or another domestic framework, base your distributed initialization and mixed-precision APIs on the corresponding framework’s documentation, and do not mix in CUDA-ecosystem commands.

    4. Choosing a Parallel Strategy: Make Partitioning Match the Hardware Topology

    At a 16-card scale, a single parallel strategy is often not enough. Common choices are as follows.

    Strategy Suitable scenario Communication characteristics Memory benefit Common pitfalls
    DP (data parallelism) Model fits on a single or a few cards Gradient sync all-reduce, high communication volume Mainly scales the global batch A too-large global batch causes loss spikes
    TP (tensor parallelism) Large per-layer parameters, need intra-layer partitioning Intra-layer all-gather/reduce, communication-intensive Reduces per-card parameters and activation memory Cross-node use hangs easily; needs high-speed intra-node interconnect
    PP (pipeline parallelism) Many layers, a single card cannot hold some of them Point-to-point activation/gradient passing Reduces per-card layer count and memory Too few micro-batches cause large bubbles; uneven boundary layers
    ZeRO / sharded optimizer Optimizer state uses a lot of memory Parameter, gradient, and optimizer-state sharding communication Significantly reduces optimizer-state memory Checkpoint saving and loading become more complex

    A practical rule: put communication-heavy parallelism inside a node, and communication-light parallelism across nodes. For example, doing TP within the eight cards of a single node and DP between two nodes keeps the most expensive cross-node communication low.

    You also need to pay attention to how the global batch is computed. The common formula is:

    1. Global batch = micro-batch size × gradient accumulation steps × DP degree

    If your parallel strategy includes TP or PP, they usually do not directly increase the data-parallel global batch, but instead partition the same model state. To choose a strategy, you can follow this simple decision tree:

    1. Does the model fit on a single card?
      • Yes: prefer DP, or DP + ZeRO.
      • No: continue to identify the bottleneck.
    2. Are the per-layer parameters too large?
      • Yes: consider intra-node TP.
      • No: continue to consider the number of layers.
    3. Are there too many layers, so a single card cannot hold a subset of them?
      • Yes: consider PP.
      • No: continue to observe optimizer state and activation memory.
    4. Does the optimizer state use too much memory?
      • Yes: consider ZeRO or parameter/optimizer-state sharding.
      • No: start with conventional measures such as micro-batch, gradient accumulation, and activation recomputation.

    If the examples in this article use world_size=16 and tp_size=8, the premise is a single node with 8 cards and high-speed interconnect between cards, and a model on the order of tens of billions of parameters. If your topology differs, adjust tp_size and do not copy it across topologies directly.

    5. Distributed Initialization: Derive TP/DP Groups from the Topology

    The example below shows a more explicit distributed initialization. First, the topology assumption: the example assumes 8 cards per node and 16 cards across two nodes, with rank from 0 to 15 and local_rank being the in-node card number 0 to 7. If your deployment topology differs—say 4 cards per node, or 32 cards across four nodes—you need to re-derive the parallel groups.

    1. import os
    2. from datetime import timedelta
    3. import torch
    4. import torch.distributed as dist
    5. def detect_backend_and_device():
    6. # Ascend example; other domestic cards such as Cambricon and Hygon need
    7. # their vendor package and device type substituted here
    8. try:
    9. import torch_npu # noqa
    10. if torch.npu.is_available():
    11. return "hccl", "npu"
    12. except Exception:
    13. pass
    14. return "nccl", "cuda"
    15. def init_distributed(tp_size=8):
    16. backend, device_type = detect_backend_and_device()
    17. world_size = int(os.environ["WORLD_SIZE"])
    18. rank = int(os.environ["RANK"])
    19. local_rank = int(os.environ["LOCAL_RANK"])
    20. assert world_size % tp_size == 0, "world_size must be divisible by tp_size"
    21. dist.init_process_group(
    22. backend=backend,
    23. world_size=world_size,
    24. rank=rank,
    25. timeout=timedelta(minutes=30),
    26. )
    27. if device_type == "npu":
    28. torch.npu.set_device(local_rank)
    29. device = torch.device(f"npu:{local_rank}")
    30. else:
    31. torch.cuda.set_device(local_rank)
    32. device = torch.device(f"cuda:{local_rank}")
    33. # TP groups: ranks within each group are contiguous, e.g. world_size=16, tp_size=8
    34. # TP0 = [0,1,2,3,4,5,6,7]
    35. # TP1 = [8,9,10,11,12,13,14,15]
    36. tp_groups = [
    37. dist.new_group(ranks=list(range(i, i + tp_size)))
    38. for i in range(0, world_size, tp_size)
    39. ]
    40. # DP groups: cards with the same local rank across nodes form a data-parallel group
    41. # e.g. world_size=16, tp_size=8:
    42. # DP0 = [0, 8], DP1 = [1, 9], ..., DP7 = [7, 15]
    43. dp_groups = [
    44. dist.new_group(ranks=list(range(i, world_size, tp_size)))
    45. for i in range(tp_size)
    46. ]
    47. tp_group = tp_groups[rank // tp_size]
    48. dp_group = dp_groups[rank % tp_size]
    49. return {
    50. "world_size": world_size,
    51. "rank": rank,
    52. "local_rank": local_rank,
    53. "device": device,
    54. "device_type": device_type,
    55. "backend": backend,
    56. "tp_group": tp_group,
    57. "dp_group": dp_group,
    58. }

    The key point here: a DP group is not simply “the last eight cards treated as one unit,” but data-parallel replicas formed by the same local card position across nodes. This way, TP groups do intra-layer parallelism while DP groups do gradient synchronization, and the topology semantics are clearer.

    6. Phased Verification: Go from a Single Card to Multi-Node; Don’t Start at 16 Cards

    Verifying the training pipeline should follow a “small to large, converging step by step” approach. A recommended path:

    1. Single card, small scale: a tiny model with a very short sequence, confirming the closed loop of forward, backward, and parameter update.
    2. Single node, multi-card: verify intra-node communication correctness, comparing single-card and multi-card loss curves.
    3. Multi-node, multi-card: verify cross-node collective communication and data-parallel gradient synchronization.
    4. Hundreds of steps for stability: observe whether memory, throughput, and loss remain stable.

    The minimal training skeleton below should be read with a caveat: this example does not use tp_group / dp_group to partition the model by tensors, nor does it do gradient communication per parallel group; it only demonstrates the minimal closed loop of data loading, model, optimizer, distributed initialization, and log aggregation. To actually enable TP/DP, you still need to wrap the model per the initialization groups, configure gradient synchronization, and adapt log aggregation to the parallel groups.

    1. import os
    2. import contextlib
    3. from datetime import timedelta
    4. import torch
    5. import torch.distributed as dist
    6. from torch.utils.data import TensorDataset, DataLoader
    7. from torch.utils.data.distributed import DistributedSampler
    8. class ToyLM(torch.nn.Module):
    9. def __init__(self, vocab_size=32, seq_len=16, hidden=64):
    10. super().__init__()
    11. self.embed = torch.nn.Embedding(vocab_size, hidden)
    12. self.head = torch.nn.Linear(seq_len * hidden, vocab_size)
    13. def forward(self, input_ids):
    14. h = self.embed(input_ids)
    15. h = h.reshape(h.size(0), -1)
    16. return self.head(h)
    17. def run_min_loop(cfg):
    18. rank = cfg["rank"]
    19. local_rank = cfg["local_rank"]
    20. world_size = cfg["world_size"]
    21. device = cfg["device"]
    22. device_type = cfg["device_type"]
    23. torch.manual_seed(2024 + rank)
    24. # Build toy data; in real training replace this with your data pipeline
    25. seq_len = 16
    26. vocab_size = 32
    27. num_samples = 256
    28. input_ids = torch.randint(0, vocab_size, (num_samples, seq_len))
    29. labels = torch.randint(0, vocab_size, (num_samples,))
    30. dataset = TensorDataset(input_ids, labels)
    31. sampler = DistributedSampler(
    32. dataset,
    33. num_replicas=world_size,
    34. rank=rank,
    35. shuffle=True,
    36. seed=2024,
    37. )
    38. dataloader = DataLoader(dataset, batch_size=2, sampler=sampler)
    39. model = ToyLM(vocab_size, seq_len).to(device)
    40. optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4)
    41. # Mixed-precision example:
    42. # On NVIDIA cards you can use CUDA AMP directly;
    43. # for domestic Ascend or other domestic cards, if the vendor provides an
    44. # equivalent autocast/GradScaler, substitute the vendor interface;
    45. # if unsure, keep AMP off by default to avoid startup failures from an
    46. # unsupported device_type.
    47. amp_enabled = False
    48. scaler = None
    49. autocast_ctx = contextlib.nullcontext()
    50. if amp_enabled and device_type == "cuda":
    51. autocast_ctx = torch.autocast(device_type="cuda", enabled=True)
    52. scaler = torch.cuda.amp.GradScaler()
    53. elif amp_enabled and device_type == "npu":
    54. # Example: use only if torch_npu provides an equivalent interface, e.g.:
    55. # autocast_ctx = torch_npu.npu.amp.autocast(enabled=True)
    56. # scaler = torch_npu.npu.amp.GradScaler()
    57. # If the vendor interface is uncertain, keep amp_enabled=False.
    58. pass
    59. log_interval = 10
    60. for step, batch in enumerate(dataloader):
    61. batch_input_ids = batch[0].to(device, non_blocking=True)
    62. batch_labels = batch[1].to(device, non_blocking=True)
    63. with autocast_ctx:
    64. logits = model(batch_input_ids)
    65. loss = torch.nn.functional.cross_entropy(logits, batch_labels)
    66. optimizer.zero_grad(set_to_none=True)
    67. if scaler is not None:
    68. scaler.scale(loss).backward()
    69. scaler.step(optimizer)
    70. scaler.update()
    71. else:
    72. loss.backward()
    73. optimizer.step()
    74. if step % log_interval == 0:
    75. # Simple aggregation: assume each card's loss can be averaged directly
    76. loss_tensor = torch.tensor([loss.detach().item()], device=device)
    77. dist.all_reduce(loss_tensor, op=dist.ReduceOp.SUM)
    78. global_loss = loss_tensor.item() / world_size
    79. if rank == 0:
    80. print(f"step={step} global_loss={global_loss:.4f}")

    This aggregation is a teaching example. If the loss is averaged per token and the token counts differ across cards, you should aggregate weighted by token count instead of simply dividing by world_size. If you enable a combination of TP/PP/DP, you also need to distinguish which losses should be averaged across the DP group and which states should be combined across TP/PP, avoiding mixing different parallel semantics together.

    7. Judging Numerical Alignment: Run a “Health Check” with Fixed Criteria

    To judge whether the pipeline is “running correctly,” you cannot look only at whether the loss decreases; you must check whether multi-card results are consistent with a single-card baseline. Fix the following measurement criteria:

    • Random seed: fix torch.manual_seed, the numpy seed, and the DataLoader sampling seed.
    • Global batch: record the single-card batch, DP degree, and gradient accumulation steps, then derive the global batch.
    • Sequence length and model structure: must be exactly identical to the baseline.
    • Precision settings: whether BF16, FP16, or FP32 is enabled, and whether loss scaling is on.
    • Data loading: whether it is shuffled, whether sample order is fixed, and whether the same data split is used.
    • Loss aggregation: is it an all-reduce sum divided by the card count, or token-weighted?
    • Initialization: is parameter initialization consistent, and are there random-initialization differences?

    On judging “first-step loss deviation,” one point needs special emphasis: you cannot apply a fixed percentage without a unified baseline. Whether first-step deviation is acceptable depends on model size, sequence length, global batch, precision settings, dataset size, card count, and initialization. If the project has a stable single-card baseline, use the project’s internal single-card baseline as the primary reference; if you are validating the pipeline in a small toy model, you can record the first-step deviation and the average deviation over the first several steps as an auxiliary signal for whether the pipeline is wired up incorrectly, but you should not present it as a universal metric.

    A more robust numerical-alignment flow is:

    1. Run a fixed-config baseline on a single card, saving the model structure, data slice, random seed, initialization, and loss curve.
    2. In two-card, four-card, and multi-node scenarios, keep the same model structure, sequence length, global batch, and precision settings.
    3. Compare loss, gradient norm, and parameter update magnitude at each step or at key steps.
    4. If the difference is obvious, first check data splitting, loss aggregation, random seeds, and device precision, then check parallel partitioning.
    5. All measurements should record the complete configuration, for easy reproduction and auditing.

    8. Tuning Stability and Performance: Common Hangs, Loss Spikes, and Parameter Choices

    After numerical alignment, you also need to solve “running long and running fast.” Common stability and performance problems can be handled as follows.

    Communication hangs: check NICs, timeout thresholds, slow nodes, and the collective-communication backend. Set a reasonable timeout on init_process_group and combine it with a retry mechanism to avoid false judgments. If a single node works but multi-node hangs, prioritize checking the network, container networking, RDMA ports, communication-library version, and vendor logs. For NVIDIA cards you can enable NCCL_DEBUG=INFO; for domestic cards, check the vendor-provided log paths and debug switches.

    Loss spikes: commonly caused by too high a learning rate, abnormal data, gradient explosion, or abnormal mixed-precision loss scaling. You can enable gradient clipping and learning-rate warmup, and watch for loss spikes early in training. If the loss suddenly goes abnormal at a specific step, first check the data batches near that step—sample labels, anomalous tokens, or dirty data.

    Out of memory: first reduce the micro-batch, then enable gradient accumulation; if that is still not enough, enable ZeRO or parameter sharding; if inter-card bandwidth within a node is insufficient, do not blindly increase TP. TP suits high-speed intra-node interconnect, and using TP across nodes often amplifies communication overhead or even causes hangs.

    Performance optimization: find a balance between throughput and memory through operator fusion, compute/communication overlap, reasonable micro-batches, gradient accumulation, and memory sharding. Do not chase single-step speed alone; also watch memory jitter, communication jitter, and loss stability during long runs.

    The following are empirical parameter ranges; the actual optimum requires a small-step search based on model structure, parallelism degree, inter-card bandwidth, and batch size:

    • Gradient clipping threshold: commonly 1.0; tighten to 0.5 if the loss spikes frequently.
    • Learning-rate warmup steps: can be 1%~5% of total steps; for a few thousand steps of training, try 100~500 steps.
    • Collective-communication timeout: start at minutes, e.g. 30~60 minutes, combined with retries.
    • Micro-batch size: prioritize compute/communication overlap, and avoid being too small, which underutilizes the hardware.
    • Data-loading worker threads: tune based on CPU, storage, and network capacity, so data loading does not become the bottleneck in multi-node environments.

    9. Safe Checkpoint Operations: Write to a Temp Directory, Verify, Back Up or Use Incremental Names, and Keep History

    Checkpoint saving is the last safeguard of the training pipeline. Overwrite saves, interruptions mid-write, and disk failures can all lose training progress. The recommended approach is “temp directory + verification + backup or incremental naming + keep history versions.”

    The example below applies to non-sharded or already-aggregated model checkpoints. If training uses sharded parallelism such as TP, PP, or ZeRO, each rank must save its own shard, and rank 0 saves the metadata or completion marker. When resuming, you must verify that all shards exist and are version-consistent.

    1. import os
    2. import glob
    3. import shutil
    4. import torch
    5. def safe_save_checkpoint(model, optimizer, scaler, step, out_root, keep=3):
    6. """
    7. This function only applies to non-sharded or already-aggregated model checkpoints.
    8. For TP/PP/ZeRO sharded scenarios, each rank should save its own shard,
    9. and rank 0 should save meta, a file manifest, and verification info.
    10. """
    11. if not torch.distributed.is_initialized():
    12. rank = 0
    13. else:
    14. rank = torch.distributed.get_rank()
    15. if rank != 0:
    16. return
    17. final_dir = os.path.join(out_root, f"ckpt-step{step}")
    18. tmp_dir = os.path.join(out_root, f".ckpt-step{step}.tmp")
    19. if os.path.exists(tmp_dir):
    20. shutil.rmtree(tmp_dir)
    21. try:
    22. os.makedirs(tmp_dir, exist_ok=False)
    23. ckpt = {
    24. "step": step,
    25. "model": model.state_dict(),
    26. "optimizer": optimizer.state_dict(),
    27. }
    28. if scaler is not None:
    29. ckpt["scaler"] = scaler.state_dict()
    30. state_path = os.path.join(tmp_dir, "state.pt")
    31. torch.save(ckpt, state_path)
    32. with open(os.path.join(tmp_dir, "meta.json"), "w", encoding="utf-8") as f:
    33. f.write(f'{{"step": {step}}}')
    34. # Verification: ensure the saved file is readable and metadata matches
    35. loaded = torch.load(state_path, map_location="cpu", weights_only=False)
    36. if loaded["step"] != step:
    37. raise RuntimeError("checkpoint step mismatch")
    38. # Note: os.replace(tmp_dir, final_dir) cannot safely overwrite an existing
    39. # non-empty directory. If final_dir already exists, back up the old directory
    40. # first, then publish the new one; in production, incremental directory names,
    41. # a manifest file, or a pointer file are preferred for atomic publish.
    42. if os.path.exists(final_dir):
    43. backup_dir = final_dir + ".backup"
    44. if os.path.exists(backup_dir):
    45. shutil.rmtree(backup_dir)
    46. os.replace(final_dir, backup_dir)
    47. os.replace(tmp_dir, final_dir)
    48. except Exception:
    49. if os.path.exists(tmp_dir):
    50. shutil.rmtree(tmp_dir)
    51. raise
    52. # Keep the most recent `keep` checkpoints to avoid unbounded history growth
    53. ckpts = sorted(
    54. p for p in glob.glob(os.path.join(out_root, "ckpt-step*")) if os.path.isdir(p)
    55. )
    56. for old_ckpt in ckpts[:-keep]:
    57. shutil.rmtree(old_ckpt)

    Here it is worth stressing: os.replace(tmp_dir, final_dir) is not suitable for directly overwriting a directory that already exists and is non-empty. If final_dir already exists, replacing it directly may fail and interrupt checkpoint saving. Three common safer approaches:

    1. Incremental directory names: e.g. ckpt-step-1000, ckpt-step-2000; write to a new directory each time and do not overwrite the old one.
    2. Back up the old directory: rename the old directory to .backup or .old before publishing the new checkpoint, then clean up after success.
    3. Manifest-style atomic publish: write to a temp directory first, then after verification write a manifest file, e.g. manifest.json, and have the recovery logic read only directories marked ready in the manifest.

    For distributed sharded checkpoints, it is recommended to include at least the following fields:

    1. {
    2. "step": 1000,
    3. "world_size": 16,
    4. "parallel_config": {
    5. "tp_size": 8,
    6. "dp_size": 2
    7. },
    8. "shards": [
    9. "shard-rank0.pt",
    10. "shard-rank1.pt"
    11. ],
    12. "created_at": "2026-01-01T00:00:00"
    13. }

    When resuming, you cannot just check that the directory exists; you must also verify:

    • Whether every rank’s shard file exists.
    • Whether the step in each shard is consistent.
    • Whether the model structure, parallel config, and optimizer type match.
    • Whether there are half-written files, empty files, or files that fail verification.

    The failure-rollback strategy is: delete this run’s temp directory, keep the last verified checkpoint, and resume from the most recent usable version. For sharded scenarios, if any shard is missing or version-inconsistent, roll back the whole thing rather than trying to stitch together an incomplete state.

    10. Summary: Turn “It Ran” into a Reproducible, Automated Capability

    Building a domestic-card multi-node, multi-GPU training pipeline is not a single trick but a whole systems-engineering effort: consistent environment versions are the prerequisite, topology-matched parallel strategies are the core, phased verification is the safeguard, and numerical alignment plus checkpoint safety are the delivery standard.

    In real projects, it is recommended that teams distill the environment checks, topology confirmation, distributed initialization, minimal training loop, numerical-judgment criteria, and checkpoint-saving scripts from this article into an automated workflow. Before going live, complete at least the following checks:

    • Are node images and dependency versions consistent?
    • Are device visibility and inter-card topology as expected?
    • Do communication benchmarks pass, and are logs traceable?
    • Have single-card, single-node multi-card, and multi-node multi-card been verified stage by stage?
    • Is numerical alignment based on the project’s internal baseline?
    • Do checkpoints support verification, backup, atomic publish, and failure rollback?

    Once these steps are fixed into scripts, templates, and checklists, a team can turn “an accidental success” into a “stable, deliverable” engineering capability, laying the groundwork for larger-scale training, long-run training, and failure recovery later on.