FSDP2 Training Adaptation Acceptance Guide for AI Compute Cards: Differences, Code, and Checklist
This article targets engineers responsible for selecting and validating AI compute cards for training workloads. It outlines the differences between training and inference adaptation, provides an FSDP2-based code skeleton for small-scale validation, and details the necessary metrics and a phased acceptance checklist.
This article is designed for engineers responsible for selecting and validating AI compute cards. Determining whether a solution is suitable for training requires verifying that it covers the complete training pipeline, not just inference. The provided code and checklists can be directly applied to small-scale acceptance testing, though specific thresholds must be determined by the project team based on baselines.
1. Differences Between Training and Inference Adaptation
What the industry often calls “Day 0 adaptation” refers to verifying and deploying inference operators on the day a new open-source model is released. This type of validation primarily proves that the chip can execute forward passes and typically does not involve pre-training the base model. The hardware listed in a model’s technical report may not reflect the actual compute used during its pre-training.
Training adaptation demands much more. The software stack must support a complete training loop—including model loading, forward propagation, backward propagation, and optimizer updates—and must run stably for extended periods. Inference only requires forward computation, while training must also store gradients and optimizer states, consuming significantly more memory.
Using mixed-precision Adam as an example, based on common estimates from the ZeRO paper, the model state per parameter takes about 16 bytes, excluding activations and communication buffers. The breakdown is: 2 bytes for fp16 parameters, 2 bytes for fp16 gradients, and 12 bytes for fp32 master weights, momentum, and variance. For a 3-trillion-parameter model, the model states alone require about 48TB. Even with 64GB of memory per card, at least 750 cards are needed to distribute these states. Since a single card cannot hold the entire model, the software stack must provide distributed training strategies.
To evaluate if a solution has training capabilities, you should inspect each stage in the table below.
| Stage | Inference Adaptation | Training Adaptation | Acceptance Evidence |
|---|---|---|---|
| Goal | Correct forward results, meets latency | Converges after long training, reproducible | Training loss curve, rerun results under same config |
| Memory | Model weights + activations | Weights, gradients, optimizer states, activations | Peak memory record |
| Distributed | Usually not required | Requires parameter sharding, collective communication, checkpoint recovery | Multi-card logs, checkpoint recovery drill records |
| Backward & Optimizer | Not involved | Must verify gradient calculation and parameter updates | grad_norm curve, parameter comparison before/after update |
| Stability | Correct results for single request | Runs continuously for days, no numerical overflow, no process hangs | Long-running logs, exception counts |
If a solution lacks evidence in the “Backward & Optimizer” or “Distributed” rows, it should be deemed as failing training adaptation.
2. FSDP2 Training Pipeline
FSDP2 is PyTorch’s fully sharded data parallel solution, implemented via the fully_shard interface. It shards parameters, gradients, and optimizer states across cards, with each card holding only a fraction. During forward and backward passes, it gathers parameters via collective communication on demand and releases them after computation.
Versions and Dependencies
- PyTorch 2.6 or later. From version 2.6 onwards,
fully_shardis located undertorch.distributed.fsdp. In versions 2.4 to 2.5, this interface was located undertorch.distributed._composable.fsdp; the import path and certain behaviors differ, so it is not recommended for acceptance testing. - Use the vendor-provided PyTorch adaptation package and ensure it includes a distributed backend.
- Example install command:
pip install torch==2.6.0. For AI compute cards, replace the installation source according to the vendor’s instructions.
Code Skeleton
The following script can serve as a starting point for acceptance. The backend name, device interface, and device visibility variables must be replaced according to the vendor’s documentation. Synthetic data is used to isolate software stack issues without relying on a data pipeline.
# train_fsdp2.pyimport osimport torchimport torch.distributed as distimport torch.nn as nnfrom torch.distributed.device_mesh import init_device_meshfrom torch.distributed.fsdp import fully_sharddef build_model(dim=1024, depth=8):# Replace with project model; here using stacked linear layers to simulate Transformer blocksreturn nn.Sequential(*[nn.Linear(dim, dim) for _ in range(depth)])def main():dist.init_process_group(backend="nccl") # For AI compute cards, fill in the vendor-provided communication backendlocal_rank = int(os.environ["LOCAL_RANK"])rank = dist.get_rank()device = torch.device("cuda", local_rank) # For AI compute cards, replace with the corresponding device interfacetorch.cuda.set_device(device)world_size = dist.get_world_size()mesh = init_device_mesh("cuda", (world_size,))# Build model on the device first, then shard, finally create optimizermodel = build_model().to(device)# Wrapping order: shard submodules first, then the root modulefor block in model:fully_shard(block, mesh=mesh)fully_shard(model, mesh=mesh)# Optimizer must be created after sharding, with the sharded parametersoptimizer = torch.optim.AdamW(model.parameters(), lr=1e-4)loss_fn = nn.MSELoss()num_steps, log_every, batch, dim = 200, 20, 32, 1024for step in range(num_steps):x = torch.randn(batch, dim, device=device)y = torch.randn(batch, dim, device=device)loss = loss_fn(model(x), y)loss.backward()grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)optimizer.step()optimizer.zero_grad(set_to_none=True)if rank == 0 and step % log_every == 0:gn = grad_norm.full_tensor().item() if hasattr(grad_norm, "full_tensor") else grad_norm.item()peak_gb = torch.cuda.max_memory_allocated(device) / 1e9print(f"step={step} loss={loss.item():.4f} grad_norm={gn:.4f} peak_mem_GB={peak_gb:.2f}")dist.destroy_process_group()if __name__ == "__main__":main()
Wrapping Order Explanation
- Place the model on the target device before calling
fully_shard. - Call
fully_shardon each submodule (e.g., each Transformer block) first, then on the root module. After the root module is sharded, any parameters not individually sharded will fall under the root module. - Create the optimizer after sharding and use
model.parameters(). If the order is reversed, the optimizer may hold references to pre-sharded parameters, rendering updates ineffective.
For extremely large models, initialize using the meta device to avoid filling a single card’s memory with the complete model first. This is a project implementation detail not expanded upon in this example.
Launch Commands
Single node, 2 cards:
torchrun --standalone --nproc_per_node=2 train_fsdp2.py
Multi-node, multi-card (e.g., 2 nodes, 8 cards per node; execute on each node separately, with NODE_RANK set to 0 or 1):
torchrun --nnodes=2 --nproc_per_node=8 --node_rank=${NODE_RANK} \--rdzv_backend=c10d --rdzv_endpoint=${MASTER_ADDR}:29500 \train_fsdp2.py
3. Cross-node Training Metrics
When cross-node training issues arise, looking solely at the loss is often insufficient to locate the root cause. The table below lists metrics that should be recorded during acceptance.
| Metric | Meaning | Collection Method | Frequency |
|---|---|---|---|
| loss | Training loss, determines if converging | Step log | Every step |
| NaN/Inf count | Occurrences of non-finite values in loss or gradients | Check loss and grad_norm | Every step |
| grad_norm | Gradient norm, detects gradient explosion or vanishing | Return value of clipgrad_norm | Every step |
| Throughput (tokens/s) | Tokens processed per second | Step time statistics | 100-step moving average |
| Peak memory | Max allocated memory per card | max_memory_allocated | Every 100 steps |
| Comm time ratio | Collective communication time as a percentage of single step time | Sampling via torch.profiler or vendor tools | Sampling during acceptance |
| Comm errors | Timeouts, disconnections, reconnections, etc. | Vendor backend log keyword stats | Real-time |
| Process hang | Interval between adjacent steps exceeds threshold | Watchdog or external monitoring | Real-time |
| Checkpoint recovery success rate | Ratio of successful recoveries to drills, checking loss continuity after recovery | Manually kill process and recover | Every drill |
Throughput and communication ratio will vary with the network, card type, and model structure. During acceptance, compare these with vendor baselines or same-scale reference values rather than directly applying fixed numbers.
4. Small-Scale Acceptance Checklist
Acceptance is divided into three levels; proceed to the next level only after the previous one passes.
| Scenario | Pass Criteria | Evidence | Troubleshooting on Failure |
|---|---|---|---|
| Single node, single card | Correct backward and optimizer updates; loss decreases overall with steps; loss deviation from reference implementation under same config is within project tolerance | Training logs, loss curve, reference comparison | Check dtype, whether gradients are None, learning rate, and random seed |
| Single node, multi-card (from 2 cards) | Multi-card loss trend consistent with single card; |
