🧠 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:

  1. Keep the sharded parameters (can’t delete yet)
  2. Receive parameters from other GPUs
  3. 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:

ScenarioExampleWhy It Works
Model fits after gathering70B model, 80GB GPU, 4 GPUs70B params = 280GB, fits in 80GB during gather
High-speed interconnectNVLink (600GB/s)Communication overhead minimal
Multiple nodes available16 GPUs across 2 nodesCan shard across more devices

❌ FSDP Fails When:

ScenarioExampleWhy It Fails
Model too large175B model, 80GB GPU700GB > 80GB even with gathering
Slow interconnectEthernet (10GB/s)Communication dominates computation
Single GPU70B model, 1 GPUNo 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:

  1. Pipeline Parallelism: Split model by layers across GPUs
  2. Tensor Parallelism: Split individual layers across GPUs
  3. CPU Offloading: Store parameters in CPU RAM (very slow)
  4. Model Compression: Quantization, pruning, distillation
  5. 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     # βœ… Correct

Q3: β€œ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?”

AspectDDPFSDP
MemoryFull model per GPU1/N model per GPU
CommunicationGradients onlyParameters + Gradients
Use CaseModel fits in GPUModel 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

  1. FSDP trades memory for communication - you save memory by sharding but pay in network traffic

  2. The all-gather creates a memory peak - this is the fundamental limitation

  3. FSDP alone isn’t always enough - for truly massive models, combine with pipeline/tensor parallelism

  4. Network speed matters - slow interconnect can make FSDP slower than running on fewer, bigger GPUs

  5. 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.