How-to guides

PyTorch FSDP training with fully_shard (FSDP2)

PyTorch FSDP training shards a model’s parameters, gradients and optimizer state across GPUs, so each GPU stores only a slice and gathers full layers when it needs them. In current PyTorch, call fully_shard on each transformer block and then on the root model, create the optimizer afterwards, launch with torchrun, and save checkpoints with torch.distributed.checkpoint.

NEURAMESH / COMPUTE FIELD NOTES00 / 10

Prerequisites and which GPU to rent

Use FSDP when the model, its gradients and optimizer state do not fit on one GPU, which is the limit for PyTorch DDP multi-GPU training. The PyTorch tutorial describes FSDP as a decomposition of DDP’s all-reduce into reduce-scatter and all-gather operations. Memory drops, and communication rises, so fast GPU links matter more than with DDP.

This guide follows the FSDP2 API, fully_shard in torch.distributed.fsdp, as documented for PyTorch 2.15. The API has docs back to PyTorch 2.6; check the page for your version, since some arguments changed. FSDP2 uses DTensor per-parameter sharding on dim 0 instead of FSDP1’s flat parameters, and the tutorial says it achieves lower and more deterministic GPU memory than FSDP1.

You need a Linux server with 2-8 NVIDIA GPUs of the same model, a CUDA build of PyTorch, and data on local disk. Estimate total training state with the VRAM calculator, then divide by GPU count for a first guess at per-GPU memory.

Prerequisites and which GPU to rent
ItemDDPFSDP (fully_shard)
Parameters per GPUFull copyOne shard, full layer gathered when used
Gradients per GPUFull copyOne shard after reduce-scatter
Optimizer state per GPUFull copyOne shard
Main collectivesAll-reduceAll-gather and reduce-scatter
Checkpoint formattorch.save from rank 0Distributed checkpoint, one file or more per rank

References: PyTorch tutorial: Getting started with Fully Sharded Data Parallel (FSDP2) · PyTorch docs: torch.distributed.fsdp.fully_shard

Step 1: check the server and PyTorch

Run nvidia-smi to confirm every GPU and its memory, and nvidia-smi topo -m to see whether GPUs connect over NVLink or PCIe. Then run python -c "import torch; print(torch.__version__, torch.cuda.device_count())". If the version is older than the docs you follow, upgrade before writing FSDP code.

Read LOCAL_RANK from the environment, call torch.cuda.set_device(local_rank), then dist.init_process_group("nccl"), exactly as in a DDP script. torchrun sets the rank variables for you.

References: NVIDIA System Management Interface · PyTorch docs: torchrun (Elastic Launch)

Step 2: shard the model with fully_shard

Import with from torch.distributed.fsdp import fully_shard. Build the model on the meta device so no GPU holds the full weights: with torch.device("meta"): model = Transformer(args). Then shard bottom-up: for layer in model.layers: fully_shard(layer), followed by fully_shard(model).

Each call creates one communication group for the parameters not already claimed by a child call, so calling it only on the root gathers the whole model at once and saves little memory. Shard each transformer block.

Materialize the weights after sharding with model.to_empty(device="cuda") and then your initializer, such as model.reset_parameters(). Only then create the optimizer, for example torch.optim.AdamW(model.parameters(), lr=3e-4). The tutorial stresses this order, because the optimizer must hold the sharded DTensor parameters.

The training loop is unchanged: forward, loss.backward(), optimizer.step(). Gradient clipping with torch.nn.utils.clip_grad_norm_ works on DTensor parameters.

References: PyTorch tutorial: Getting started with Fully Sharded Data Parallel (FSDP2) · PyTorch docs: torch.distributed.fsdp.fully_shard

Step 3: add mixed precision and optional CPU offload

Import MixedPrecisionPolicy from torch.distributed.fsdp and pass mp_policy=MixedPrecisionPolicy(param_dtype=torch.bfloat16, reduce_dtype=torch.float32) to each fully_shard call. The tutorial example computes in bfloat16 and reduces gradients in float32, while the sharded master weights stay in their original dtype.

If the model still does not fit, pass offload_policy=CPUOffloadPolicy() to move sharded parameters, gradients and optimizer state to host memory. It pins CPU memory by default; the docs say to set pin_memory=False if you lack CPU memory. Expect slower steps, and check that the server has enough RAM.

References: PyTorch tutorial: Getting started with Fully Sharded Data Parallel (FSDP2) · PyTorch docs: torch.distributed.fsdp.fully_shard

Step 4: launch PyTorch FSDP training with torchrun

On one server, run torchrun --standalone --nproc-per-node=gpu train.py, which starts one process per GPU. The official example in the pytorch/examples repository, under distributed/FSDP2, runs with torchrun --nproc_per_node 2 train.py and adds flags such as --mixed-precision or --explicit-prefetching.

For several servers, run on each node: torchrun --nnodes=2 --nproc-per-node=8 --rdzv-id=job1 --rdzv-backend=c10d --rdzv-endpoint=HOST:29400 train.py. Across nodes, consider HSDP: passing a 2D device mesh to fully_shard shards within a node and replicates across nodes, which keeps the heaviest traffic on the fast intra-node links.

References: PyTorch docs: torchrun (Elastic Launch) · PyTorch tutorial: Getting started with Fully Sharded Data Parallel (FSDP2) · PyTorch docs: torch.distributed.fsdp.fully_shard

Step 5: save and load distributed checkpoints

Do not call torch.save on a sharded model from rank 0; it only holds a shard. Use torch.distributed.checkpoint. Import it as dcp, then dcp.save(state_dict, checkpoint_id=CHECKPOINT_DIR) on every rank and dcp.load(state_dict=state_dict, checkpoint_id=CHECKPOINT_DIR) to resume. Build state_dict with get_state_dict(model, optimizer) and restore with set_state_dict.

DCP writes at least one file per rank, and it can load into the same or a different world size, so a job saved on 8 GPUs can resume on 16. To get a single file for inference, call dcp_to_torch_save from torch.distributed.checkpoint.format_utils, or use get_model_state_dict with full_state_dict=True and cpu_offload=True. Interval and storage choices are in GPU training checkpoints.

References: PyTorch recipe: Getting started with Distributed Checkpoint (DCP) · PyTorch tutorial: Getting started with Fully Sharded Data Parallel (FSDP2)

Settings that matter

Start with the defaults and change one setting at a time, recording step time and peak memory from torch.cuda.max_memory_allocated().

Settings that matter
SettingDefaultEffect
reshard_after_forwardNone: True for layers, False for rootTrue frees gathered weights after forward; False keeps them, using more memory and less communication
reshard_after_forward as an intNot setReshards to a smaller group, such as GPUs per node, to cut backward traffic
mp_policy param_dtypeNone (original dtype)bfloat16 for faster compute and smaller gathers
mp_policy reduce_dtypeNonefloat32 for more stable gradient reduction
offload_policyNo offloadCPUOffloadPolicy() when GPU memory runs out
meshNone (1D, all GPUs)2D mesh for HSDP across nodes
set_requires_gradient_sync(False)Sync every backwardSkip gradient communication on accumulation micro-steps

References: PyTorch docs: torch.distributed.fsdp.fully_shard · PyTorch tutorial: Getting started with Fully Sharded Data Parallel (FSDP2)

Common errors and fixes

Most FSDP problems come from ordering or from treating a shard like a full tensor. For memory errors in general see CUDA out of memory, and for distributed hangs see NCCL timeout.

Common errors and fixes
SymptomLikely causeFix
Out of memory while building the modelFull model created on GPU before shardingBuild on meta device, shard, then to_empty
Weights do not update as expectedOptimizer created before fully_shardCreate the optimizer after sharding
Little memory savedfully_shard applied only to the rootApply it to each block, then the root
Checkpoint holds only part of the weightstorch.save from one rankUse dcp.save on all ranks
Cannot resume on a new GPU countSingle-rank or custom shard filesSave with DCP, which reshards on load
Slow steps with accumulationGradients synced every micro-stepCall set_requires_gradient_sync(False) until the last micro-step
Host runs out of RAM with offloadPinned CPU memoryUse CPUOffloadPolicy(pin_memory=False) or more RAM

References: PyTorch tutorial: Getting started with Fully Sharded Data Parallel (FSDP2) · PyTorch docs: torch.distributed.fsdp.fully_shard · PyTorch recipe: Getting started with Distributed Checkpoint (DCP)

Estimate memory, time and GPU-hours

Memory first. Take your estimate of parameters, gradients and optimizer state together and divide by GPU count; then add activations, which do not shrink with sharding, and the largest gathered layer. Confirm with peak memory over 20 steps.

Time second. Run 100 steps on the full server and record tokens or samples per second, then divide the total dataset by that rate. The example below is illustrative with assumed numbers: 120 GB of training state across 8 GPUs is about 15 GB of state per GPU before activations. If the measured rate is 20,000 tokens per second and the run covers 2 billion tokens, training takes about 27.8 hours.

Estimate memory, time and GPU-hours
ItemAssumed value
Training state, all GPUs120 GB
State per GPU with 8 GPUs15 GB plus activations
Measured throughput20,000 tokens/s
Training time for 2B tokens27.8 hours
GPU-hours with 1 hour of setup230.4
Cost at an assumed $2 per GPU-hour$460.80

Checklist and next step

Confirm the model does not fit for DDP. Check GPUs, topology and PyTorch version. Build on meta, call fully_shard per block then root, materialize, then create the optimizer. Add bfloat16 mixed precision. Save with DCP and resume at start-up. Measure peak memory and throughput, then estimate GPU-hours.

When the plan is ready, choose a multi-GPU server on rent GPUs: pick the GPU, plan, GPU count, hours and region, and you receive a confirmed quotation, typically within one business day, with nothing charged until you approve. If you are unsure which GPU or count fits, ask the compute advisor.

NeuraMesh prices for these GPUs

NeuraMesh prices per GPU-hour in USD, excluding taxes, as of 2026-11-27. Live prices are on the rental pages.
GPUMemoryData centerValue
RTX 409024 GB$0.46$0.40
L40S48 GB$1.26$0.54
A10080 GB$1.56$0.98
H10080 GB$2.88$2.00

Every order is confirmed in a quotation before you pay. See all GPU prices.

Questions readers ask

What is the difference between FSDP and FSDP2?

FSDP1 is the FullyShardedDataParallel wrapper class, which shards flattened parameter groups. FSDP2 is the fully_shard function, which shards each parameter on dim 0 as a DTensor. PyTorch’s tutorial says FSDP2 gives lower, more deterministic memory.

When should I use FSDP instead of DDP?

Use FSDP when the model, gradients and optimizer state do not fit on one GPU. If they fit, DDP is simpler and usually communicates less.

How do I launch PyTorch FSDP training on multiple GPUs?

Use torchrun, the same launcher as DDP: torchrun --standalone --nproc-per-node=gpu train.py on one server, or add --nnodes and rendezvous flags across servers.

How do I save an FSDP model for inference?

Save training checkpoints with torch.distributed.checkpoint. For one file, convert with dcp_to_torch_save, or call get_model_state_dict with full_state_dict=True and cpu_offload=True.

Does FSDP reduce activation memory?

Not by itself. It shards parameters, gradients and optimizer state. Reduce activations with smaller micro-batches or activation checkpointing.

Sources and editorial notes

Primary documentation reviewed November 24, 2026. Provider descriptions reflect published documentation. Recommendations are our analysis; worked figures are illustrative unless explicitly stated otherwise. No independent provider benchmark or uptime ranking is claimed.

Read the editorial policy.

Need this GPU? Rent it from NeuraMesh: choose a GPU and plan, get a confirmed quotation, and pay only when you approve. See pricing.