AI Logic

Distributed Training and Memory Saving

FSDP

Updated:

How FSDP works. Left: what happens for one unitβ€”weights are gathered with All-Gather before the forward pass, computed, and discarded; before the backward pass they are gathered again and computed, then the gradients are Reduce-Scattered and only the GPU's own share of the weights is updated. Right: the weights on GPU 1 with 4 GPUs and 3 units while unit 2 is being computedβ€”only the unit being computed is gathered in full, and the other units keep just their own 1/4

Background and overview

FSDP (Fully Sharded Data Parallel) is a data-parallel method built into PyTorch that shards all of a model's weights, gradients, and optimizer states across GPUs, and gathers only the weights of the part needed right before computing it. The computation stays the same as in data parallelism, yet it can train large models that do not fit on a single GPU.

In PyTorch's DDP (DistributedDataParallel), every GPU holds all of the model's weights, gradients, and optimizer states. According to the paper, on 40GB GPUs, trying to train a model with more than 1 billion parameters with DDP tends to run out of memory.

In a 2023 paper (PVLDB), Zhao et al. described the design and implementation of PyTorch FSDP. FSDP takes DeepSpeed's ZeRO as its starting point and redesigns it to fit with the rest of PyTorch. The PyTorch documentation also explains that it was inspired by ZeRO Stage 3 (Pos+g+pP_{os+g+p} in the ZeRO paper, the stage that shards the weights as well).

The idea is like taking a large cookbook apart page by page and splitting the pages among several cooks in a kitchen. Everyone copies only the pages for the dish being cooked right now, and throws the copies away when the dish is done. Since each cook keeps only their own pages, each person's load is much lighter.

Theory

One training step of FSDP proceeds as follows (left of the figure above; Figure 1 and Section 3 of the paper).

  1. Split the model into several units. A unit is a self-contained submodule such as a Transformer block.
  2. Lay out the weights of each unit as one long tensor (a FlatParameter) and divide it evenly by the number of GPUs FF. Each GPU holds only its own 1/F1/F.
  3. Forward pass: right before computing a unit, gather the shares held by the other GPUs with All-Gather to form the full weights of the unit. When the computation is done, discard the gathered shares.
  4. Backward pass: right before back-propagating through a unit, gather the weights again with All-Gather. When the backward pass is done, discard the gathered shares, and use Reduce-Scatter to sum the gradients across all GPUs while splitting them, so that each GPU receives only its own 1/F1/F.
  5. Each GPU updates only its own 1/F1/F of the weights, using its own 1/F1/F of the optimizer states.

The mini-batch is split across GPUs just as in data parallelism. Each GPU computes its share of the data using the gathered full-model weights, so the computation itself is the same as in DDP.

Let Ξ¨\Psi be the number of parameters and ψ1,…,ψN\psi_1, \dots, \psi_N the numbers of weights in the units (βˆ‘iψi=Ξ¨\sum_i \psi_i = \Psi). As in Section 3.2.1 of the paper, the peak weight memory is

O ⁣(βˆ‘i=1NψiF+max⁑iψi)O\!\left(\sum_{i=1}^{N} \frac{\psi_i}{F} + \max_{i} \psi_i\right)

The first term is the GPU's own share, which it keeps at all times; the second term is the weights of one unit being computed, which are gathered temporarily. Since the first term is fixed at Ξ¨/F\Psi / F, the peak memory is determined by the size of the largest unit.

The finer the units, the smaller the temporarily gathered weights, and the lower the memory. In exchange, the number of communications per training step grows in proportion to the number of units NN, which can reduce speed. Choosing which submodules become units lets you trade off memory against speed.

Communication and memory techniques

Sharding the weights always adds communication to gather them before computation. FSDP uses the following techniques to hide this communication behind computation and to use memory efficiently.

TechniqueMechanismPurpose
FlatParameterConcatenates a unit's weights into one tensor, pads the end so it is divisible by the number of GPUs, and splits it evenlyCombines communication into a single call of uniform size for efficiency
Overlapping computation and communicationRuns All-Gather on a CUDA stream separate from computationGathers the next unit's weights while the previous unit is being computed
Backward prefetchingStarts the next unit's All-Gather before the current unit's Reduce-ScatterPrevents two back-to-back communications from stalling the backward pass
Forward prefetchingStarts the next unit's All-Gather early, based on the order in the previous iterationKeeps communication flowing even when CPU-side processing is slow
Rate limitingLimits concurrent All-Gathers to at most 2Prevents GPU memory fragmentation and the large slowdowns it causes
Deferred initializationBuilds the model on a fake device that uses no real memory, then moves it to the GPU unit by unit to initialize and shard itLets models that do not fit on one GPU be built with the same code as ordinary models

The sharding strategy can also be chosen. The number of GPUs the weights are sharded across (the paper's sharding factor FF) determines the trade-off between memory and communication.

StrategySharding scopeMemoryCommunication
Full sharding (FF = total number of GPUs)All GPUsLowest1.5Γ— DDP
Hybrid sharding (1<F<1 < F < total number of GPUs)Shard within a machine, replicate across machinesIn betweenLess cross-machine communication
No sharding (F=1F = 1)None (same as DDP)HighestSame as DDP

In hybrid sharding, the weights are sharded across the GPUs inside a machine, which are connected by fast links, while the same shards are replicated across machines and their gradients are All-Reduced. Because this reduces the amount of communication between machines, it is advantageous on clusters with slow inter-machine links.

You can also choose whether to discard the gathered weights after the forward pass (RAF) or keep them until the backward pass (NRAF). Discarding reduces memory but requires gathering them again before the backward pass. In PyTorch's fully_shard, this is chosen with the reshard_after_forward argument.

Experimental results

The paper's experiments were run on up to 512 A100 GPUs (80GB).

ExperimentResult
T5 (611M–11.3B parameters) compared with DDPAt 611M and 2.28B parameters, about as fast as DDP. DDP ran out of memory beyond 2.28B, while FSDP could train 11.3B parameters
GPT-175B (175B parameters), backward prefetchingPrefetching made it about 18% faster
GPT-175B, 128–512 GPUs173 TFLOPS per GPU (batch 1) and 186 TFLOPS (batch 2), about 55% and 60% of the A100's BF16 peak (312 TFLOPS). Throughput scaled linearly from 128 to 512 GPUs
T5-11B, 8–512 GPUsAt 512 GPUs, per-GPU throughput was 7% lower than at 8 GPUs
Rate limitingUp to 5Γ— faster for T5, but 5% slower for DeepViT

The large-model experiments combined the full sharding strategy with backward prefetching, rate limiting, gradient checkpointing, and BF16 mixed precision training, using Adam as the optimizer.

The paper explains that T5-11B slowed down as more GPUs were added because, with more GPUs, communication becomes heavier than computation and can no longer be fully hidden behind it.

Practical considerations

Create the optimizer after wrapping the model with FSDP. FSDP replaces the model's weights with sharded ones, so an optimizer created before wrapping still points to the original (unsharded) weights. The PyTorch documentation also requires creating the optimizer after wrapping the model.

  • Decide the unit granularity. If the whole model is a single unit, the entire model is gathered during computation and memory is not reduced. The PyTorch fully_shard documentation asks you to apply fully_shard to each layer (such as each Transformer block) first, and to the whole model last.
  • Use rate limiting only after confirming its effect. In the paper, it helped some models and slowed down others. Whether GPU memory fragmentation is occurring can be checked with num_alloc_retries in torch.cuda.memory_stats().
  • Consider the hybrid strategy in environments with slow communication. Full sharding makes communication 1.5Γ— that of DDP. If the model barely fails to fit, hybrid sharding, which shards only within a machine, keeps communication down.
  • PyTorch has two APIs. FullyShardedDataParallel, which wraps the whole model (its default strategy is FULL_SHARD, which shards across everything), and fully_shard, which is applied per submodule. The PyTorch documentation recommends that users of FullyShardedDataParallel consider migrating to fully_shard.

Comparison with other methods

FSDP is compared here with other memory-reducing methods from the same perspectives.

MethodWhat is splitComputationCommunication (relative to DDP)Ease of adoption
Data parallelism (DDP)Data onlyWhole model on each GPU1Γ—Easiest
FSDP (full sharding)All weights, gradients, and optimizer statesSame as DDP (weights gathered right before computation)1.5Γ—Decide the unit granularity
ZeROChosen by stage (optimizer states β†’ gradients β†’ weights)Same as DDP1Γ— (1.5Γ— when weights are sharded too)Chosen in DeepSpeed or similar configs
Tensor parallelism (Megatron-LM)Matrices inside layersEach GPU computes part of a matrixCommunication per layerRequires rewriting each layer
Pipeline parallelism (GPipe)Sequence of layersEach GPU computes some layersOnly activations at boundariesDecide how to partition stages
  • If the model fits on one GPU, DDP is the fastest and simplest.
  • If it does not fit and you want to train a large model with almost no changes to the model code, FSDP is the first choice. It works entirely within PyTorch.
  • FSDP assumes that the weights of one unit can be gathered on a single GPU. When a single layer is too large to gather on one GPU, combine it with tensor parallelism.

PyTorch example

Show code
python
import os
import torch
import torch.nn as nn
import torch.distributed as dist
from torch.distributed.device_mesh import init_device_mesh
from torch.distributed.fsdp import fully_shard, MixedPrecisionPolicy

"""
Example of training a Transformer-like model with FSDP (PyTorch's fully_shard)
Example run (4 GPUs on one machine): torchrun --nproc_per_node=4 train_fsdp.py
"""

dist.init_process_group(backend='nccl')
rank = dist.get_rank()
local_rank = int(os.environ['LOCAL_RANK'])
torch.cuda.set_device(local_rank)
mesh = init_device_mesh('cuda', (dist.get_world_size(),))  # shard weights across all GPUs


class Block(nn.Module):
  def __init__(self, dim=2048):
    super().__init__()
    self.norm = nn.LayerNorm(dim)
    self.ff = nn.Sequential(nn.Linear(dim, 4 * dim), nn.GELU(), nn.Linear(4 * dim, dim))

  def forward(self, x):
    return x + self.ff(self.norm(x))


class Model(nn.Module):
  def __init__(self, dim=2048, n_blocks=24, n_classes=10):
    super().__init__()
    self.blocks = nn.ModuleList([Block(dim) for _ in range(n_blocks)])
    self.head = nn.Linear(dim, n_classes)

  def forward(self, x):
    for block in self.blocks:
      x = block(x)
    return self.head(x)


model = Model().cuda()

# compute in BF16, sum gradients (Reduce-Scatter) in FP32
mp_policy = MixedPrecisionPolicy(param_dtype=torch.bfloat16, reduce_dtype=torch.float32)

# 1. Apply fully_shard to each block, making one block one unit
#    reshard_after_forward=True: discard gathered weights after the forward pass and gather them again before the backward pass (less memory)
for block in model.blocks:
  fully_shard(block, mesh=mesh, reshard_after_forward=True, mp_policy=mp_policy)
# 2. Finally apply it to the whole model (the remaining weights, such as the output layer, become the outermost unit)
fully_shard(model, mesh=mesh, mp_policy=mp_policy)

# 3. Create the optimizer after applying fully_shard (so that it receives the sharded weights)
#    Each GPU's Adam state covers only its own 1/F of the weights
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4)

for step in range(10):
  model.train()
  x = torch.randn(8, 2048, device='cuda')    # this GPU's share of the mini-batch (same as data parallelism)
  y = torch.randint(0, 10, (8,), device='cuda')
  loss = nn.functional.cross_entropy(model(x), y)
  loss.backward()          # during backward, gather weights per unit and Reduce-Scatter the gradients
  optimizer.step()         # update only this GPU's 1/F of the weights
  optimizer.zero_grad()
  if rank == 0:
    print(f"step {step}: loss {loss.item():.4f}")

dist.destroy_process_group()

FAQ

Q. How should I choose between FSDP and DDP?
A.

If the model's weights, gradients, and optimizer states fit on one GPU, use DDP. It has less communication and trains fastest. Use FSDP when they do not fit. In the original paper, FSDP and DDP were about equally fast on small models (611M and 2.28B parameters). FSDP can still train at sizes where DDP runs out of memory.

Q. How is FSDP different from ZeRO?
A.

The idea is the same; FSDP takes ZeRO as its starting point and redesigns it inside PyTorch. The full sharding strategy corresponds to ZeRO's stage that shards the weights as well (Pos+g+pP_{os+g+p}, Stage 3). FSDP works with PyTorch features alone and lets you choose the unit granularity, the range of GPUs to shard across (hybrid), whether to discard weights after the forward pass, and so on.

Q. What granularity should units have?
A.

For a Transformer, the basic choice is to make each block one unit. Peak memory is determined by the largest unit, so finer units reduce memory. However, more units mean more communications, each smaller and less efficient. In the original paper's measurements, total communication time rose sharply when the number of elements sent per All-Gather fell below 33 million.

References

  1. Zhao, Y., Gu, A., Varma, R., Luo, L., Huang, C.-C., Xu, M., Wright, L., Shojanazeri, H., Ott, M., Shleifer, S., Desmaison, A., Balioglu, C., Damania, P., Nguyen, B., Chauhan, G., Hao, Y., Mathews, A., & Li, S. (2023). PyTorch FSDP: Experiences on Scaling Fully Sharded Data Parallel. Proceedings of the VLDB Endowment, 16(12), 3848–3860.
  2. PyTorch Documentation, "FullyShardedDataParallel."
  3. PyTorch Documentation, "torch.distributed.fsdp.fully_shard."