π§ FSDP: The Conceptual Guide
TL;DR: FSDP lets you train models larger than GPU memory by sharding them across devices. The catch? During computation, each GPU still needs to fit the full model temporarily.
π― The Core Problem
You have a 70B parameter model that needs 280GB of memory.
Your GPU has 80GB.
How do you train it?
π‘ The FSDP Solution
The Key Insight
Instead of each GPU holding a complete copy of the model, each GPU holds only a shard (piece) of it. When needed, GPUs temporarily reconstruct the full model through communication.
The Three-Step Dance
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Step 1: SHARD β
β Each GPU holds 1/N of the model β
β β
β GPU 0: [Layer 0-3] πΎ 70GB β
β GPU 1: [Layer 4-7] πΎ 70GB β
β GPU 2: [Layer 8-11] πΎ 70GB β
β GPU 3: [Layer 12-15] πΎ 70GB β
β β
β Total: 280GB model β Each GPU: 70GB β
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Step 2: GATHER (When Computing) β
β Temporarily reconstruct full layer β
β β
β Computing Layer 0: β
β All GPUs: "Hey, send me your piece of Layer 0!" β
β GPU 0-3: [Full Layer 0] πΎ 280GB (TEMPORARY!) β
β β
β β οΈ CRITICAL: Each GPU needs 280GB during this step! β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Step 3: COMPUTE & DISCARD β
β Do the math, then throw away the gathered pieces β
β β
β GPU 0: compute(Layer 0) β keep only gradients β
β GPU 1: compute(Layer 0) β keep only gradients β
β GPU 2: compute(Layer 0) β keep only gradients β
β GPU 3: compute(Layer 0) β keep only gradients β
β β
β Back to 70GB per GPU β
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
π¨ The Critical Limitation
The Model Size Ceiling
Question: βWhat if my model is so large that even one layer doesnβt fit after gathering?β
Answer: Youβre stuck. FSDP has a hard limit:
Where compression factor β 3-4x (from mixed precision, activation checkpointing, etc.)
Why This Happens
During the all-gather operation, FSDP must:
- Keep the sharded parameters (canβt delete yet)
- Receive parameters from other GPUs
- Construct the full layer
This creates a memory peak:
peak_memory = shard_size + full_layer_size
= model_size/N + model_size
= model_size Γ (1 + 1/N)For large N, this approaches the full model size!
π’ The Math Behind FSDP
Memory Reduction Formula
For a model with parameters :
- Without FSDP: Each GPU stores parameters
- With FSDP: Each GPU stores parameters
- Memory Reduction:
Communication Cost
All-Gather (Forward Pass):
- Volume:
- Time: where = bandwidth
Reduce-Scatter (Backward Pass):
- Volume: Same as all-gather
- Time: Same complexity
Total Training Time
π When FSDP Works vs. Fails
β FSDP Works When:
| Scenario | Example | Why It Works |
|---|---|---|
| Model fits after gathering | 70B model, 80GB GPU, 4 GPUs | 70B params = 280GB, fits in 80GB during gather |
| High-speed interconnect | NVLink (600GB/s) | Communication overhead minimal |
| Multiple nodes available | 16 GPUs across 2 nodes | Can shard across more devices |
β FSDP Fails When:
| Scenario | Example | Why It Fails |
|---|---|---|
| Model too large | 175B model, 80GB GPU | 700GB > 80GB even with gathering |
| Slow interconnect | Ethernet (10GB/s) | Communication dominates computation |
| Single GPU | 70B model, 1 GPU | No sharding possible |
π¨ Visual: FSDP in Action
Forward Pass Timeline
Time β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
t=0 Shard 0 active
[β β‘β‘β‘] GPU0 computes with its shard
[β‘β‘β‘β‘] GPU1 idle
[β‘β‘β‘β‘] GPU2 idle
[β‘β‘β‘β‘] GPU3 idle
t=1 All-gather for Layer 0
[β β β β ] GPU0 gathers
[β β β β ] GPU1 gathers
[β β β β ] GPU2 gathers
[β β β β ] GPU3 gathers
πΎ Peak memory! Each GPU has full layer
t=2 Compute Layer 0
[ββββ] All GPUs compute in parallel
t=3 Discard gathered params
[β β‘β‘β‘] GPU0 back to shard only
[β‘β β‘β‘] GPU1 back to shard only
[β‘β‘β β‘] GPU2 back to shard only
[β‘β‘β‘β ] GPU3 back to shard only
πΎ Memory returns to normal
t=4 Move to Layer 1...
(Repeat process)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
π€ Frequently Asked Questions
Q1: βMy 500B model doesnβt fit even with FSDP. What now?β
Options:
- Pipeline Parallelism: Split model by layers across GPUs
- Tensor Parallelism: Split individual layers across GPUs
- CPU Offloading: Store parameters in CPU RAM (very slow)
- Model Compression: Quantization, pruning, distillation
- Get Bigger GPUs: Sometimes the only solution
Q2: βWhy not just keep everything sharded all the time?β
Answer: Matrix multiplication requires full matrices:
# This doesn't work:
shard_output = shard_input @ shard_weight # β Wrong dimensions!
# You need:
full_output = full_input @ full_weight # β
CorrectQ3: βHow do I choose the sharding factor N?β
Formula:
N = ceil(model_memory / (gpu_memory Γ safety_factor))Where safety_factor β 0.5-0.7 (for gradients, activations, overhead)
Q4: βWhatβs the difference between FSDP and DDP?β
| Aspect | DDP | FSDP |
|---|---|---|
| Memory | Full model per GPU | 1/N model per GPU |
| Communication | Gradients only | Parameters + Gradients |
| Use Case | Model fits in GPU | Model too large for GPU |
π§ͺ Baby FSDP: A Minimal Implementation
Hereβs FSDP in 100 lines to build intuition:
import torch
import torch.distributed as dist
from typing import List
class BabyFSDP:
"""
A minimal FSDP implementation for educational purposes.
Real FSDP has many optimizations we skip here.
"""
def __init__(self, model: torch.nn.Module, world_size: int, rank: int):
self.model = model
self.world_size = world_size
self.rank = rank
# Shard parameters
self.param_shards = self._shard_parameters()
def _shard_parameters(self) -> List[torch.Tensor]:
"""Divide parameters across GPUs"""
all_params = []
for param in self.model.parameters():
# Flatten parameter
flat = param.data.view(-1)
# Calculate shard size
shard_size = len(flat) // self.world_size
# Extract this GPU's shard
start = self.rank * shard_size
end = start + shard_size if self.rank < self.world_size - 1 else len(flat)
shard = flat[start:end].clone()
# Store shard and forget full parameter
all_params.append(shard)
param.data = None # Free memory!
return all_params
def all_gather_params(self, layer_idx: int) -> torch.Tensor:
"""Reconstruct full layer from shards"""
# Get this GPU's shard
my_shard = self.param_shards[layer_idx]
# Prepare buffer for all shards
gathered = [torch.empty_like(my_shard) for _ in range(self.world_size)]
# All-gather operation
dist.all_gather(gathered, my_shard)
# Concatenate to form full parameter
full_param = torch.cat(gathered)
return full_param
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""Forward pass with on-the-fly parameter gathering"""
for layer_idx, layer in enumerate(self.model.layers):
# Step 1: Gather full parameters for this layer
full_params = self.all_gather_params(layer_idx)
# Step 2: Temporarily assign to layer
with torch.no_grad():
# This is simplified - real FSDP handles this more elegantly
layer.weight.data = full_params.view(layer.weight.shape)
# Step 3: Compute
x = layer(x)
# Step 4: Discard gathered parameters
layer.weight.data = None # Free memory immediately!
return x
def backward(self, loss: torch.Tensor):
"""Backward pass with gradient reduce-scatter"""
loss.backward()
for layer_idx, layer in enumerate(self.model.layers):
# Get local gradient shard
grad = layer.weight.grad.view(-1)
grad_shard = self._extract_shard(grad, self.rank)
# Reduce-scatter: sum gradients and distribute shards
output = torch.zeros_like(grad_shard)
dist.reduce_scatter(output, list(grad.chunk(self.world_size)))
# Store reduced gradient shard
self.grad_shards[layer_idx] = output
# Free full gradient
layer.weight.grad = None
# Usage example:
def train_with_baby_fsdp():
# Initialize distributed training
dist.init_process_group("nccl")
rank = dist.get_rank()
world_size = dist.get_world_size()
# Create model and wrap with BabyFSDP
model = create_large_model() # Your 70B model
fsdp_model = BabyFSDP(model, world_size, rank)
# Training loop
for batch in dataloader:
# Forward pass (handles gathering)
output = fsdp_model.forward(batch)
# Compute loss
loss = compute_loss(output, targets)
# Backward pass (handles reduce-scatter)
fsdp_model.backward(loss)
# Optimizer step on sharded parameters
update_sharded_params(fsdp_model.param_shards, fsdp_model.grad_shards)π Key Takeaways
-
FSDP trades memory for communication - you save memory by sharding but pay in network traffic
-
The all-gather creates a memory peak - this is the fundamental limitation
-
FSDP alone isnβt always enough - for truly massive models, combine with pipeline/tensor parallelism
-
Network speed matters - slow interconnect can make FSDP slower than running on fewer, bigger GPUs
-
Itβs not magic - FSDP canβt break the laws of physics. If your model needs X GB during computation, you need X GB available
π Whatβs Next?
- For Larger Models: Learn about pipeline parallelism (splits by layers) and tensor parallelism (splits within layers)
- For Faster Training: Explore activation checkpointing, mixed precision, and gradient accumulation
- For Production: Consider frameworks like DeepSpeed, FairScale, or PyTorch native FSDP
Remember: FSDP is powerful, but itβs not a silver bullet. Understanding its limitations is as important as understanding its capabilities.