AI State of the Art
SOTA/Training: Modern Training Techniques/28 min
Section 92

FSDP (Fully Sharded Data Parallel), PyTorch native

Listen as a podcast →

The problem: memory is gone before the first token

A 7-billion-parameter model consumes 84 GB of graphics memory before storing a single activation: 14 GB of weights, 14 GB of gradients, 56 GB of optimizer state. A common datacenter card tops out at 80 GB. That accounting, with the bytes-per-parameter breakdown behind it, is established once and for all in ZeRO and is not redone here.

Classic data parallelism (DP, Data Parallelism, and its standard implementation DDP, Distributed Data Parallel, described in Data Parallelism) does nothing about this. It splits the batch: each card gets different training examples, but keeps a complete copy of the model. Across 64 cards, the same 84 GB is duplicated 64 times.

FSDP (Fully Sharded Data Parallel) changes what gets split.

What FSDP splits, and what it must then communicate

This is the only question that matters for understanding any parallelism scheme. The answer takes two lines.

What FSDP splits: the batch and the parameter. Like DDP, each card gets its share of the training examples. But on top of that, the weights, the gradients and the optimizer state are cut into slices, one per card. One card out of 64 holds one sixty-fourth of every weight tensor. It does not hold a usable model.

What it must then communicate: right before computing a layer, the card holds only a fragment of that layer's weights. You cannot do anything with a fragment of a matrix. So it must gather the layer's full weights from the other 63 cards, run the computation, then immediately discard the 63 borrowed fragments. And start over at the next layer. Then start over again for the backward pass.

That is where the rhythm of communication sits: DDP communicates once per training step, at the very end of the backward pass. FSDP communicates once per layer per pass. Total volume only goes up by half (see below), but the number of opportunities to sit waiting on the network is multiplied by the layer count.

The opening image: instead of handing every mover a copy of the full floor plan, you hand each one a single piece of furniture. When a whole room has to be reassembled to check that everything fits, you gather the furniture for the length of the check, then everyone leaves with their piece again. The complete room exists for an instant only.

The three collective operations

These exchanges carry names inherited from NCCL (NVIDIA Collective Communications Library), the software layer that executes them on NVIDIA cards. What matters is the operation, not the name. Picture each card holding a four-line ledger.

  • All-reduce. The four ledgers are added line by line, and every card walks away with all four lines of the result. Everybody holds the complete total. This is what DDP does with gradients.
  • Reduce-scatter. Same addition, but each card receives only one line of the result: card 0 keeps the sum of the first lines, card 1 the sum of the second lines, and so on. Same arithmetic, one quarter of the data brought back.
  • All-gather. The reverse, and with no addition: each card starts with a single line and ends up with all four, simply copied side by side. It is the reconstruction of a complete tensor from its fragments.

The relationship that explains everything: an all-reduce is exactly a reduce-scatter followed by an all-gather. That is why partitioning gradients is free, you are only cutting in two an operation that was happening anyway.

Three side-by-side diagrams comparing communication primitives across four GPUs. Left, All Reduce: four columns A, B, C, D become four identical columns each holding A plus B plus C plus D. Center, Reduce-Scatter: each GPU starts with four blocks numbered 0 to 3 and keeps only one cell, the sum of the matching slice, for example A0 plus B0 plus C0 plus D0 on the first GPU. Right, All-gather: each GPU starts with a single cell A, B, C or D, and all end up holding the four cells A, B, C, D.
The two communication primitives FSDP relies on, compared with the all-reduce of classic DDP. All-gather (right) temporarily rebuilds the full tensor from the fragments held by each card: that is what FSDP does before every computation. Reduce-scatter (center) sums the contributions of all cards but hands each one only its own slice of the result, which avoids ever storing the full gradients.Source : Meta Engineering, Fully Sharded Data Parallel: faster AI training with fewer GPUs
PyTorch FSDP: Experiences on Scaling Fully Sharded Data Parallel (Zhao et al., 2023)

FSDP and ZeRO: one idea, two houses

ZeRO (Zero Redundancy Optimizer) is the original idea, published by Microsoft and shipped in the DeepSpeed library. FSDP is Meta's implementation, built into PyTorch. What they share is the substance:

  • the same starting observation: DDP replicates 64 times an amount of information that only exists once;
  • the same split of the three fixed memory items, weights, gradients, optimizer state;
  • the same collective operations, in the same order: all-gather the weights before using them, reduce-scatter the gradients after computing them;
  • the same communication overhead, one and a half times DDP for the most aggressive variant.

What differs is not conceptual:

AspectZeRO-3 (DeepSpeed)FSDP (PyTorch)
Natureexternal library to installbuilt into PyTorch
ConfigurationJSON config filePython interface
Unit of shardingthe parameter tensorthe wrapped module (FSDP1), the parameter tensor (FSDP2)
Offload to CPU and diskmore complete (ZeRO-Infinity)more limited
Composition with the rest of PyTorchthrough the librarynative

Plainly: if you understand ZeRO, you understand FSDP. The vocabulary changes, the mechanism does not. For a new project FSDP is the sensible default because it is native; DeepSpeed keeps the edge when you need to spill onto disk.

The lifecycle of one layer

For each FSDP unit (a group of layers, in practice one transformer block) here is the full sequence:

  1. All-gather: the weight fragments held by every card are gathered, and the unit finally exists in full.
  2. Forward: the computation runs on the complete weights and produces the activations.
  3. Free: the fragments borrowed from other cards are erased. Only the local fragment remains.
  4. All-gather (again): the weights are gathered a second time, because the backward pass needs them and we threw them away.
  5. Backward: gradients are computed on the complete weights.
  6. Reduce-scatter: gradients from all cards are summed, and each card receives only its slice of the result. The rest is discarded immediately.
  7. Free: the borrowed weights are erased again.

Step 4 is the heart of the trade. The same weights are gathered twice because holding on to them between forward and backward would cost exactly the memory we set out to save. We pay in network traffic so as not to pay in memory.

FSDP flow diagram on two GPUs, drawn as two identical horizontal lanes starting from a Data block. Each lane chains LOAD-MODEL SHARD, ALL-GATHER, FORWARD (LOCAL), FREE FULL WEIGHTS for FSDP instance 1 of N layers, then ALL-GATHER, BACKWARD (LOCAL), REDUCE-SCATTER, FREE FULL WEIGHTS for the same instance, then the following instances, and finally UPDATE WEIGHTS (LOCAL). Dashed vertical arrows connect the two lanes and are labelled GATHER WEIGHTS (ALL_GATHER) and SYNC GRADS (REDUCE_SCATTER). Callout bubbles read Load shard from CPU if CPU offloaded and Offload grads to CPU if CPU offload is enabled.
The official PyTorch diagram maps exactly onto the seven steps above. You can see the two all-gathers (one before the forward, one before the backward), the two FREE FULL WEIGHTS boxes that immediately follow each computation, and the reduce-scatter that synchronises gradients. The grey rectangles delimit FSDP units: this is the granularity at which the whole cycle repeats.Source : PyTorch documentation, Getting Started with Fully Sharded Data Parallel (FSDP)
Peak memory, and where it comes from

At any instant a card holds three things: its permanent slice of the model, that is the 84 GB divided by the number of cards; the full weights of a single unit, materialised for the duration of the computation and discarded afterwards; and the activations, which FSDP does not partition at all.

peak≈model statesP⏟permanent slice+full weights of one unit⏟temporary+activations⏟not partitioned\text{peak} \approx \underbrace{\frac{\text{model states}}{P}}_{\text{permanent slice}} + \underbrace{\text{full weights of one unit}}_{\text{temporary}} + \underbrace{\text{activations}}_{\text{not partitioned}}

where PP is the number of cards. The middle term is the one the choice of units controls: the larger the units, the more must be gathered at once, the higher the peak. The right-hand term does not move, which is why it needs a different tool, activation recomputation.

Choosing granularity: wrapping policies

FSDP "wraps" chunks of the model to decide what counts as a unit of sharding. That choice sets how often you communicate, and how high peak memory climbs.

  • Size-based automatic wrapping: any module above a parameter threshold becomes a unit. Simple, rarely optimal.
  • Per-transformer-block wrapping (the common case): each block (attention, feed-forward network, normalisations) becomes a unit. It is the natural computational unit of these architectures.
  • Manual wrapping: you name the modules explicitly. Useful for unusual architectures.
Why the transformer block is the right balance

Too fine, one unit per linear layer, and every tiny module fires its own all-gather: the network is hit constantly with minuscule transfers and latency dominates. Too coarse, the whole model as one unit, and you have to gather every weight at once, which cancels the entire benefit. The transformer block amortises the communication over a substantial amount of useful computation, while keeping the peak down to one reconstructed block at a time.

The sharding strategies

StrategyZeRO equivalentWhat is splitVolume exchanged
FULL_SHARDZeRO-3weights + gradients + optimizer state1.5x DDP
SHARD_GRAD_OPZeRO-2gradients + optimizer state; weights replicated1x DDP
NO_SHARDclassic DDPnothing (the batch only)1x DDP

SHARD_GRAD_OP never gathers weights, since they are not split: that is why it costs nothing in communication. FULL_SHARD adds the weight all-gathers from the previous section, and that is where the extra half comes from.

Four rows of three GPUs illustrating memory occupancy. Row 1, Distributed Data Parallelism: each GPU holds a purple params block, an orange gradients block and a large green optimizer-state block, all at full size. Row 2, ZeRO Type 1, Optimizer Sharded: params and gradients stay full but the green block shrinks to one third on each GPU, the missing parts shown as dashed outlines linked by arrows. Row 3, ZeRO Type 2, Optimizer plus Gradients Sharded: the orange and green blocks both shrink to one third. Row 4, ZeRO Type 3 slash FSDP, Parameters plus Optimizer plus Gradients sharded: all three purple, orange and green blocks shrink to one third on each GPU.
The mapping between ZeRO stages and the FSDP strategies in the table. At the top, classic DDP (NO_SHARD): every card keeps a full copy of everything. In the middle, ZeRO-2, the equivalent of SHARD_GRAD_OP: only gradients and optimizer states are split. At the bottom, ZeRO-3, the equivalent of FULL_SHARD: the weights themselves are split, and the dashed areas show what each card no longer stores and will have to fetch from its neighbours.Source : Vectors and Verbs, Fitting Trillion-Parameter Giants into 80GB GPUs

The precision of the exchanges

FSDP separates three numerical precisions, which is finer-grained than the usual mixed precision switch:

  • param_dtype: the precision of the weights during computation, in practice BF16.
  • reduce_dtype: the precision of the numbers that travel over the network. Dropping it to BF16 halves the traffic, at the cost of a slightly less accurate summation during the gradient reduce-scatter.
  • buffer_dtype: the precision of small persistent buffers, such as normalisation statistics. Keep them in FP32, they are tiny and sensitive.

FSDP2: the rewrite

  • Per-parameter sharding: FSDP1 shards whole modules, concatenating their parameters into a single flat buffer; FSDP2 shards each parameter tensor separately. That is more flexible, and it fixes several cases where FSDP1 coped badly with tensors of very different shapes.
  • Composition: FSDP2 combines natively with tensor parallelism (see Megatron-LM) and with torch.compile, both of which FSDP1 supported poorly.
  • DTensor: PyTorch's distributed tensor serves as the base abstraction, giving every parallelism scheme a shared vocabulary.
Incompatible interface

FSDP2 rethinks the programming interface: FSDP1 wraps modules manually with wrapper classes, FSDP2 relies on policies and DTensor. Migrating means rewriting the distributed configuration code. A new project should start from FSDP2 directly.

Two settings that decide performance

Prefetching

FSDP can launch the all-gather for layer N+1N+1 while layer NN is still computing. Transfer and computation overlap, and the card no longer idles on the network between layers. This is what makes FULL_SHARD practical despite its per-layer communication rhythm.

Hybrid sharding: HSDP

Across a multi-machine cluster, the links are nothing alike. You have to compare in the same unit, which is the classic source of error, network links are advertised in gigabits per second, internal buses in gigabytes per second, and a byte is eight bits:

LinkAs advertisedIn gigabytes per second
NVLink 4, between cards in one machine900 GB/s900
InfiniBand NDR, between machines400 Gb/s50

The ratio is therefore roughly 18x, not the 2x a careless reading of the two numbers would suggest. These interconnects are covered in detail in Scaling infrastructure.

HSDP (Hybrid Sharded Data Parallel) exploits that hierarchy. Full sharding happens inside a machine, where all-gathers ride the fast link. Between machines you fall back to DDP: one gradient all-reduce per training step, over the slow link. You accept replicating the model once per machine so that no weights ever cross the weak link.

Starting point for a 7-to-13-billion model

FULL_SHARD, per-transformer-block wrapping, BF16 mixed precision, activation recomputation and prefetching. Always pair FSDP with activation recomputation: FSDP attacks the three fixed memory items, recomputation attacks the fourth. Either one alone leaves a bottleneck untouched. Past 70 billion parameters you also need tensor parallelism.

Summary

FSDP splits the batch and the parameter, where DDP split only the batch. The price is one round of communication per layer per pass instead of one per training step: just before using a layer, the card gathers its full weights from the others with an all-gather, computes, then releases them. It is the same idea as ZeRO in a native PyTorch implementation. Start with SHARD_GRAD_OP, which is free on the network, and move to FULL_SHARD when memory is still short. And remember that FSDP never touches the activations: that is a separate job.

Check your understanding0 / 5

1. A 7-billion-parameter model needs 84 GB per card. You scale from 8 to 64 cards with classic DDP. What happens to the per-card memory requirement?

2. Why does sharding the gradients (SHARD_GRAD_OP, the ZeRO-2 equivalent) add zero communication cost over DDP?

3. Under FULL_SHARD, a unit's full weights are gathered once for the forward pass, then gathered again for the backward pass. Why not just keep them in between?

4. FULL_SHARD is on, and memory still overflows. Which memory item does FSDP not shard at all?

5. A new distributed training project is starting in PyTorch. What does the page say about choosing between FSDP1 and FSDP2?