Training Pipeline Setup and Stability Validation with FSDP2 on Domestic GPUs

    This article provides a technical walkthrough for validating a full training pipeline on domestic GPU clusters, focusing on memory estimation, FSDP2 sharding, multi-node launch, checkpointing, and stability testing. It covers how to estimate per-GPU memory for model states, how to apply Fully Sharded Data Parallel 2 with mixed precision, and how to run multi-node training with fault recovery. The discussion also highlights key differences when adapting training workloads to domestic GPU environments, including communication libraries, operator coverage, and version constraints. A staged validation approach with concrete monitoring metrics and troubleshooting checklists is included for engineering reference.

    Introduction: Training Adaptation Requires More Than Inference

    Many teams refer to “adapting an open-source model” when the model can complete forward inference on a chip. Inference only reads weights. Training, on the other hand, requires executing the full forward pass, backward pass, and weight updates, while saving weights, gradients, and optimizer states and rewriting them at every step. Validation of a training adaptation comes down to three things: loss remains bounded after hundreds or thousands of steps, memory stays within device limits, multi-node communication remains stable, and training can recover after interruption.

    This article walks through four topics in order: estimating memory requirements, building an FSDP2 training pipeline, designing a two-node multi-GPU stability validation, and clarifying the boundaries of the conclusions. All figures in this article are derived from formulas rather than measured results.

    Step 1: Estimating Memory Requirements

    The first step in training adaptation is resource estimation, not writing code. For mixed-precision training, each parameter occupies roughly 16 bytes during training. The table below uses 3 trillion parameters as an example, with 1TB expressed as 10^12 bytes:

    Item Bytes per Parameter Total for 3T Parameters Per-GPU after Sharding across 16 GPUs
    BF16 weights 2 6TB 0.375TB
    BF16 gradients 2 6TB 0.375TB
    FP32 master weights 4 12TB 0.75TB
    AdamW first moment (FP32) 4 12TB 0.75TB
    AdamW second moment (FP32) 4 12TB 0.75TB
    Total 16 48TB 3TB

    The table only covers model states. It excludes activations, communication buffers, memory fragmentation, and alignment padding. These overheads depend on batch size, sequence length, and framework implementation, and they need to be measured separately in the actual environment.

    The per-GPU memory for model states can be estimated as follows, where Φ is the parameter count and N is the number of GPUs participating in sharding:

    1. Per-GPU model state memory ≈ 16 × Φ / N

    Peak per-GPU memory also includes activations A, communication buffers B, and fragmentation overhead F:

    1. Per-GPU peak memory ≈ 16 × Φ / N + A + B + F

    Activations are most heavily influenced by batch size and sequence length, and typically require activation recomputation to keep under control.

    Taking a single GPU with 64GB of memory as an example (where GB = 10^9 bytes), model states alone would require 48×10^12 ÷ 64×10^9 ≈ 750 GPUs. If the vendor-specified 64GB is measured in GiB, the equivalent is approximately 68.7×10^9 bytes, resulting in roughly 700 GPUs. The actual available memory reported by the device should be used instead.

    Small-scale validation also requires the same upfront calculation. In a 16-GPU experiment, assume model states may use at most 70% of the available per-GPU memory, leaving the remaining space for activations and buffers. In that case, 16Φ/16 = Φ bytes, so Φ ≤ 0.7 × 64×10^9, giving an upper bound of roughly 44.8 billion parameters. This is a theoretical ceiling; the practical scale will typically be smaller, and it is advisable to start with a significantly smaller model.

    A full checkpoint contains FP32 master weights and optimizer states, requiring about 12 bytes per parameter. For 3 trillion parameters, this is roughly 36TB. If BF16 weights are also saved, it becomes approximately 42TB. Checkpoint write and recovery time depends on the aggregated storage bandwidth. Assuming 10GB/s aggregated bandwidth, writing 36TB takes approximately 3600 seconds, or about one hour. This bandwidth figure is only an example; the actual value should be measured on the target storage system.

    Step 2: Building the Training Pipeline with FSDP2

    2.1 Environment and Versions

    FSDP2 is PyTorch’s next-generation fully sharded data parallel implementation, exposed through the fully_shard entry point. In PyTorch 2.6 and later, this function can be imported from torch.distributed.fsdp. Earlier versions use a different import path, so consult the documentation for the version in use.

    On domestic GPU platforms, the driver, firmware, runtime, communication library, and PyTorch build must be matched as a compatible set. When versions are mismatched, common symptoms include import failures or multi-node communication hangs. It is recommended to record all version numbers in the experiment log and retain them for every run.

    Start with a minimal test to confirm the environment is functional. The following code performs one all-reduce on each rank, with the result expected to equal the world size. The device name and communication backend name come from the vendor’s adapter layer:

    1. import os
    2. import torch
    3. import torch.distributed as dist
    4. dist.init_process_group(backend=os.environ["DIST_BACKEND"])
    5. world = dist.get_world_size()
    6. device = torch.device(os.environ["DEVICE_STR"]) # provided by vendor documentation
    7. x = torch.ones(1024 * 1024, device=device)
    8. dist.all_reduce(x)
    9. assert torch.all(x == world), "all_reduce result is incorrect"

    2.2 Launching Two-Node Multi-GPU Training

    The following command is executed separately on each machine, with NODE_RANK set to 0 and 1 respectively. The example uses 8 GPUs per node; adjust according to the actual hardware configuration:

    1. torchrun --nnodes=2 --nproc_per_node=8 --node_rank=$NODE_RANK \
    2. --master_addr=$MASTER_ADDR --master_port=29500 train.py

    Before launching, confirm that both machines can reach MASTER_ADDR and the specified port, and that environment variables are consistent across all nodes.

    2.3 Applying FSDP2 Sharding

    Sharding order matters. Apply fully_shard to each Transformer block first, and to the root module last. Reversing this order results in coarser sharding boundaries, affecting communication granularity and peak memory usage:

    1. import torch
    2. from torch.distributed.fsdp import fully_shard, MixedPrecisionPolicy
    3. mp_policy = MixedPrecisionPolicy(
    4. param_dtype=torch.bfloat16,
    5. reduce_dtype=torch.float32,
    6. )
    7. model = build_model() # can be constructed on CPU or meta device
    8. for block in model.blocks:
    9. fully_shard(block, mp_policy=mp_policy)
    10. fully_shard(model, mp_policy=mp_policy)
    11. # The optimizer must be created after sharding to see the sharded parameters
    12. optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4)

    Setting reduce_dtype to FP32 increases communication volume but reduces numerical error during gradient reduction. Whether to adopt this setting should be determined jointly by communication cost and loss curve behavior.

    2.4 Activation Recomputation

    Activation recomputation trades computation for memory. For each Transformer block, intermediate activations are not saved during the forward pass and are recomputed during the backward pass. This can be done by wrapping the block’s forward call with torch.utils.checkpoint.checkpoint and setting use_reentrant=False. In multimodal models, both the vision encoder and language model blocks can be handled in this way.

    2.5 Multimodal Data Loading

    Each rank must read a distinct data shard. Use DistributedSampler to partition the dataset and call set_epoch at the start of every epoch to ensure different shuffling across epochs. Image decoding and text tokenization should occur in DataLoader worker processes. Check whether data loading has become a bottleneck; if the proportion of time waiting for data within a single step is high, investigate storage throughput and preprocessing first rather than adjusting the model.

    2.6 Checkpoint Saving and Recovery

    When saving, use the distributed checkpoint API so each rank writes only its own shard. In addition to model and optimizer states, record the training step, learning rate scheduler state, random number generator state, and data sampler position. Missing any of these four items can cause the loss curve to jump noticeably after recovery.

    Follow three rules for saving: write to a temporary directory first and rename after all writes complete; compute a checksum for each shard; and keep only the most recent K checkpoints. The recovery flow must be tested separately. A checkpoint that has only been saved but never restored from cannot be treated as usable.

    Step 3: Key Differences in Domestic GPU Adaptation

    Adapting to domestic GPUs requires checking the following categories of differences, each of which must be verified independently in the target environment:

    1. Driver and firmware: Different versions can affect device visibility, memory management, and error reporting behavior.
    2. Communication library: Vendor-provided collective communication libraries typically replace NCCL, but interface semantics need to be verified item by item. Focus on whether all_gather and reduce_scatter produce correct results on large tensors, as FSDP2 depends on these two operations.
    3. Operator coverage: Some operators may be missing or only have inefficient implementations. If the framework silently falls back to CPU, loss may remain normal but training will be significantly slower. Check the framework’s fallback logs rather than only verifying that training runs.
    4. Data types: BF16 support varies by chip. The mixed-precision policy should follow what the vendor documentation lists as supported.
    5. Memory statistics: The API name and semantics of peak memory queries differ by platform. Confirm whether the reported value is allocated memory or reserved memory.
    6. Version constraints: The PyTorch version adapted by the vendor often lags upstream. This article’s version requirements follow upstream documentation; the actually usable version depends on vendor releases.

    This article does not provide measured data for any specific model. Readers should record the version combination of driver, firmware, framework, and communication library in the experiment log, along with the list of verified and unverified functionality.

    Step 4: Two-Node Multi-GPU Stability Validation

    4.1 Metrics and Thresholds

    The table below lists recommended metrics to observe. Thresholds are starting points only and should be calibrated against the model, data, and hardware baseline:

    Metric Collection Method What to Observe Starting Threshold (needs calibration)
    Loss Log every step NaN, Inf, trend over the first thousand steps Stop immediately if NaN or Inf appears
    Grad norm Global norm before clipping Ratio to the sliding median Investigate if it exceeds 10× the median for 3 consecutive steps
    Peak memory Framework’s peak statistics API Compare against formula estimates Alert if it exceeds 90% of available per-GPU memory
    Per-step time Time each step, sliding window statistics Coefficient of variation of fluctuation Alert if it exceeds 5%
    Communication time ratio Profiler or vendor tools Proportion of per-step time Check sharding granularity and compute/communication overlap if above 30%
    Communication errors Collect logs from all ranks Timeouts, reconnections, error codes Record and investigate on first occurrence
    Throughput Samples or tokens processed per second Compare against single-node baseline Investigate if two-node throughput is below 1.6× single-node
    Checkpoint Actual timing and restore test Save time, restore time, loss continuity after restore Loss deviation in the first 100 steps after restore should fall within random fluctuation

    4.2 Test Levels

    Validation is conducted in three levels:

    • Smoke test: Run 200 steps to confirm no crashes, no communication errors, and memory within the expected range.
    • Medium-term test: Run 2000 steps to observe per-step time variance and loss trends, and to establish baselines for each metric.
    • Recovery test: Force-terminate the process at step N, restore from the most recent checkpoint, and compare the post-restore loss curve against the uninterrupted baseline.

    These step counts are suggestions. Actual validation should be determined by project requirements and resource availability, and the chosen values should be noted in the report.

    4.3 Troubleshooting Checklist

    Symptom Possible Cause Investigation
    Hang after launch Unreachable address or port, firewall blocking, inconsistent communication backend Check MASTER_ADDR reachability, verify environment variables across nodes, run a minimal all-reduce test
    Operator not supported Operator not covered by the accelerator Check framework fallback logs, replace the operator or downgrade the module; do not let silent CPU fallback occur
    NaN in loss Learning rate too high, BF16 numerical overflow, anomalous data Inspect abnormal samples, reduce learning rate, check reduce precision settings
    Out of memory Activations too large, sharding granularity too coarse Enable activation recomputation, refine sharding, reduce batch size
    Loss jump after recovery Optimizer state not restored, RNG state or sampler position inconsistent Verify each item on the checkpoint recovery checklist
    Significant throughput jitter Slow data loading, one node underperforming Time per-rank separately, check storage read speed

    Conclusions and Boundaries

    The approach described in this article answers three questions: whether the FSDP2 pipeline runs on the target domestic GPU environment, whether memory estimates match measured values, and whether two-node multi-GPU training remains stable over the tested number of steps.

    These conclusions apply only to the model scale, GPU count, version combination, and step count used in the experiment. Results from a 16-GPU, single-digit-billion-parameter experiment cannot be extrapolated to decide the feasibility of full-scale 3-trillion-parameter training, nor its throughput or long-term stability. Full 3-trillion-parameter training requires at least several hundred GPUs. By the formulas shown earlier, model states alone require approximately 750 GPUs, in addition to solving checkpoint storage bandwidth and recovery time. That level of validation requires a dedicated large-scale effort and cannot be inferred from small-scale experiments.