📚 FSDP: Complete Theoretical Guide
A mathematically rigorous guide to Fully Sharded Data Parallel training
Table of Contents
Core Theory
Advanced Topics
Appendices
1. Mathematical Foundations
1.1 Model Representation
Consider a neural network with parameters :
For transformers with layers, hidden dimension , and vocabulary :
1.2 Sharding Function
Define the sharding function :
where is the shard on device .
1.3 Memory States
Each device maintains three memory states:
With FSDP:
- (sharded parameters)
- (sharded gradients)
- (Adam states)
Memory reduction factor:
2. Sharding Strategies
2.1 Row-wise Decomposition (FSDP Choice)
For weight matrix , partition by rows:
where
Forward Pass:
- Input: (replicated)
- Compute: (local computation)
- Output:
Backward Pass:
- Input: (partitioned as )
- Compute: (local computation)
- Reduce: (all-reduce required)
Complexity:
- Computation: per device
- Communication: for all-reduce
- Memory: per device
2.2 Column-wise Decomposition (Alternative)
Partition by columns:
where
Forward Pass:
- Input: (partitioned)
- Compute: (local computation)
- Reduce: (all-reduce required)
Complexity:
- Computation: per device
- Communication: for all-reduce
- Memory: per device
2.3 Comparison
| Aspect | Row-wise | Column-wise |
|---|---|---|
| Forward Comm | None | All-reduce () |
| Backward Comm | All-reduce () | None |
| Activation Memory | ||
| Best For |
FSDP chooses row-wise because:
- Transformers have square matrices ()
- Better compatibility with data parallelism
- Simpler gradient computation
3. Communication Patterns: Detailed Analysis
3.1 All-Gather Operation: Complete Derivation
3.1.1 Initial State
Consider 4 GPUs (2 nodes × 2 GPUs/node) with a model parameter (64MB in FP32):
Node 0: Node 1:
┌─────────────────────────┐ ┌─────────────────────────┐
│ GPU 0 GPU 1 │ │ GPU 2 GPU 3 │
│ W[0:1024,:] W[1024: │ │ W[2048: W[3072: │
│ 2048,:] │ │ 3072,:] 4096,:] │
│ (16MB) (16MB) │ │ (16MB) (16MB) │
└─────────────────────────┘ └─────────────────────────┘
↕ NVLink (600GB/s) ↕ NVLink (600GB/s)
↔ InfiniBand (100GB/s) ↔
3.1.2 All-Gather Algorithm Steps
Step 1: Intra-node Exchange (NVLink)
Each GPU exchanges with its node neighbor:
# GPU 0 sends W[0:1024,:] to GPU 1
# GPU 1 sends W[1024:2048,:] to GPU 0
# Similarly for Node 1Time:
After Step 1:
GPU 0: W[0:2048,:] (32MB)
GPU 1: W[0:2048,:] (32MB)
GPU 2: W[2048:4096,:] (32MB)
GPU 3: W[2048:4096,:] (32MB)
Step 2: Inter-node Exchange (InfiniBand)
Representatives from each node exchange:
# GPU 0 sends W[0:2048,:] to GPU 2
# GPU 2 sends W[2048:4096,:] to GPU 0Time:
Step 3: Final Intra-node Broadcast
# GPU 0 broadcasts W[2048:4096,:] to GPU 1
# GPU 2 broadcasts W[0:2048,:] to GPU 3Time:
Total Time:
3.1.3 Generalized Communication Volume
For GPUs with parameter size , each GPU must receive shards of size :
As :
This means every GPU receives almost the entire model regardless of sharding factor!
3.2 Reduce-Scatter: Detailed Gradient Aggregation
3.2.1 Problem Setup
After backward pass, each GPU has computed full gradients :
GPU i has: ∇W_i = ∂L/∂W computed on batch_i
Goal: Each GPU gets sum of its shard: Σⱼ ∇W_j[shard_i]
3.2.2 Reduce-Scatter Algorithm
Phase 1: Reduce (All GPUs sum their gradients)
Ring-reduce pattern for 4 GPUs:
Round 1: GPU 0 → GPU 1 → GPU 2 → GPU 3 → GPU 0
Send chunk 0, accumulate
Round 2: GPU 0 → GPU 1 → GPU 2 → GPU 3 → GPU 0
Send chunk 1, accumulate
Round 3: GPU 0 → GPU 1 → GPU 2 → GPU 3 → GPU 0
Send chunk 2, accumulate
After reduce, GPU 0 has:
Phase 2: Scatter (Distribute reduced shards)
Each GPU keeps only its designated shard and discards the rest.
3.2.3 Bandwidth-Optimal Implementation
Using recursive doubling for GPUs:
def reduce_scatter_recursive(grad, rank, size):
# Step k: Exchange with partner 2^k away
for k in range(log2(size)):
partner = rank ^ (1 << k)
# Split gradient in half
if rank < partner:
send_half = grad[len(grad)//2:]
recv_half = grad[:len(grad)//2]
else:
send_half = grad[:len(grad)//2]
recv_half = grad[len(grad)//2:]
# Exchange and reduce
send(send_half, partner)
received = recv(partner)
recv_half += received
# Keep only relevant half for next iteration
grad = recv_half if rank < partner else recv_half
return grad # Final shard, fully reducedTime complexity:
3.3 Communication Patterns in Multi-Node Settings
3.3.1 Hierarchical Communication Strategy
For 32 GPUs (4 nodes × 8 GPUs/node):
Level 1: Intra-GPU (PCIe) - 32 GB/s - Ignored
Level 2: Intra-node (NVLink) - 600 GB/s - 8 GPUs
Level 3: Inter-node (IB) - 100 GB/s - 4 nodes
Level 4: Cross-rack (Ethernet) - 10 GB/s - Multiple racks
Optimal Strategy: Minimize higher-level communication
-
Local Reduction First:
# Each node reduces locally local_sum = all_reduce_intra_node(grad) # Uses NVLink -
Cross-Node Communication:
# Node representatives communicate if is_node_leader: global_sum = all_reduce_inter_node(local_sum) # Uses IB -
Local Broadcast:
# Broadcast within node final = broadcast_intra_node(global_sum) # Uses NVLink
3.3.2 Communication Schedule Optimization
Problem: Minimize total communication time
Given bandwidth hierarchy: , , GB/s
Solution: Use tree-based algorithms respecting bandwidth tiers
def optimized_all_gather(data, topology):
# Stage 1: Gather within NVLink domain
for node in topology.nodes:
if node.has_nvlink:
node.local_gather() # 600 GB/s
# Stage 2: Gather across InfiniBand
for rack in topology.racks:
rack.ib_gather() # 100 GB/s
# Stage 3: Final ethernet exchange if needed
if topology.num_racks > 1:
topology.ethernet_gather() # 10 GB/s
return gathered_data4. Memory Analysis: Complete Forward and Backward Pass
4.1 Memory Components Breakdown
4.1.1 Parameter Memory
For a transformer model with layers, hidden dimension , and vocabulary size :
Embedding Layer:
- Token embeddings:
- Position embeddings:
- Memory: bytes
Per Transformer Layer:
- Attention:
- FFN: ,
- LayerNorm: (×2 per layer)
- Memory: bytes
Total Parameter Memory:
For Llama-70B (, , ):
4.1.2 Activation Memory
For batch size and sequence length :
Per Layer Activations (must be saved for backward):
- Layer input:
- Attention scores:
- Attention output:
- FFN intermediate:
- Layer output:
Memory per layer:
Total activation memory:
For , , , , :
4.2 Forward Pass: Step-by-Step Memory Evolution
Consider processing layer with FSDP on 4 GPUs:
Step 1: Initial State
GPU 0: W_ℓ[0:2048,:] (sharded params) = 0.7GB
Activations from layer ℓ-1 = 0.4GB
Total: 1.1GB
Step 2: All-Gather Parameters
# All GPUs gather full layer parameters
W_ℓ_full = all_gather(W_ℓ_shard) # 2.8GBGPU 0: W_ℓ[0:2048,:] (keep shard) = 0.7GB
W_ℓ_full (gathered) = 2.8GB ← PEAK!
Activations from layer ℓ-1 = 0.4GB
Total: 3.9GB
Step 3: Compute Forward
# Attention computation
Q = X @ W_Q # B×S×h
K = X @ W_K # B×S×h
V = X @ W_V # B×S×h
scores = (Q @ K.T) / sqrt(h) # B×n_h×S×S
attn = softmax(scores) @ V # B×S×h
Y_attn = attn @ W_O # B×S×h
# FFN computation
Z = gelu(Y_attn @ W_1) # B×S×4h
Y = Z @ W_2 # B×S×hGPU 0: W_ℓ[0:2048,:] (shard) = 0.7GB
W_ℓ_full (can free after compute) = 2.8GB
Input activations X_ℓ = 0.4GB
Attention intermediates = 0.8GB
FFN intermediates = 1.6GB
Output Y_ℓ = 0.4GB
Total: 6.7GB
Step 4: Free Gathered Parameters
del W_ℓ_full # Free memory immediatelyGPU 0: W_ℓ[0:2048,:] (shard) = 0.7GB
All activations for layer ℓ = 3.2GB
Total: 3.9GB
4.3 Backward Pass: Detailed Memory and Communication
Step 1: Gradient Computation
Starting from loss gradient :
# Backward through FFN
dZ = dY @ W_2.T # Need W_2 (gathered)
dW_2 = Z.T @ dY # Gradient for W_2
dY_attn = dZ * gelu'(·) @ W_1.T # Need W_1
dW_1 = Y_attn.T @ (dZ * gelu'(·))
# Backward through Attention
d_attn = dY_attn @ W_O.T # Need W_O
dW_O = attn.T @ dY_attn
# ... complex attention backward ...
dX = dQ @ W_Q.T + dK @ W_K.T + dV @ W_V.TMemory during gradient computation:
GPU 0: W_ℓ_full (re-gathered) = 2.8GB
Activations (saved from forward) = 3.2GB
Gradients dW_ℓ (full) = 2.8GB
Gradient flow dX = 0.4GB
Total: 9.2GB ← PEAK MEMORY!
Step 2: Reduce-Scatter Gradients
Each GPU has computed full gradients on its data batch. Now reduce and scatter:
# Each GPU has dW_ℓ computed on its batch
# Goal: GPU i gets Σⱼ dW_ℓ_j[shard_i]
dW_ℓ_shard = reduce_scatter(dW_ℓ_full)Communication pattern for 4 GPUs:
GPU 0: Send dW[2048:] to others (2.1GB out)
Receive Σ dW[0:2048] parts (2.1GB in)
Final: Σⱼ dW_j[0:2048] (0.7GB kept)
Step 3: Optimizer Update
With sharded gradients and parameters:
# Adam optimizer state (sharded)
m_ℓ = β₁ * m_ℓ + (1-β₁) * dW_ℓ_shard
v_ℓ = β₂ * v_ℓ + (1-β₂) * dW_ℓ_shard²
W_ℓ_shard -= lr * m_ℓ / (sqrt(v_ℓ) + ε)Memory for optimizer:
GPU 0: W_ℓ_shard = 0.7GB
dW_ℓ_shard = 0.7GB
m_ℓ (momentum, sharded) = 0.7GB
v_ℓ (variance, sharded) = 0.7GB
Total: 2.8GB
4.4 Peak Memory Analysis: The Critical Constraint
4.4.1 Memory Peak Points
Three critical peaks during training:
Peak 1: During All-Gather
Peak 2: During Forward Computation
Peak 3: During Backward Computation
Overall Peak:
4.4.2 The Fundamental Limitation
Theorem: FSDP cannot train a model larger than GPU memory allows for a single layer.
Proof: During all-gather for layer , GPU must hold:
- Sharded parameters from all layers:
- Full parameters for current layer:
- Activations from previous layers:
Minimum required memory:
Even as :
This sets a hard limit on model size regardless of sharding!
4.5 Memory Optimization Techniques
4.5.1 Activation Checkpointing
Trade compute for memory by recomputing activations:
def forward_with_checkpoint(x, layer):
# Don't save intermediate activations
y = checkpoint(layer, x) # Will recompute in backward
return yMemory savings: (optimal checkpointing)
5. Performance Analysis
5.1 Time per Iteration
where:
- (C = FLOPs, F = GPU FLOPs)
5.2 Scaling Efficiency
5.3 Break-even Point
FSDP is beneficial when:
6. Sequence Parallelism (Ulysses)
6.1 Sequence Partitioning
For sequence length and parallel degree :
6.2 Attention with All-to-All
The attention computation requires special handling:
- Partition sequence: Each device gets tokens
- All-to-all exchange: Redistribute for attention heads
- Compute attention: Local computation on exchanged data
- All-to-all exchange: Redistribute back to sequence
6.3 2D Parallelism: FSDP + Ulysses
6.3.1 Device Mesh Configuration
Consider a 2D mesh with groups for parameter sharding and groups for sequence parallelism:
Total devices:
6.3.2 Memory Distribution Derivation
Without any parallelism, each device stores:
- Model parameters:
- Activations for sequence:
- Total memory:
With FSDP only:
- Parameters are sharded:
- Full sequence remains:
- Memory per device:
With Sequence Parallelism only:
- Full parameters remain:
- Sequence is partitioned:
- Memory per device:
With 2D Parallelism (FSDP + Ulysses):
- Parameters sharded by FSDP:
- Sequence partitioned by SP:
- Memory per device:
6.3.3 Memory Reduction Factor
The memory reduction compared to single device:
If parameters and activations contribute equally to memory ():
Maximum reduction when :
6.3.4 Communication Pattern in 2D
The communication becomes hierarchical:
-
Within SP groups (row-wise): All-to-all for sequence exchange
- Volume: per device
- Frequency: Every attention layer
-
Within FSDP groups (column-wise): All-gather/reduce-scatter for parameters
- Volume: per device
- Frequency: Every layer forward/backward
-
Total communication per iteration:
where = number of attention layers, = total layers
7. PPO/RLHF Training with FSDP: Complete Analysis
7.1 Reinforcement Learning from Human Feedback (RLHF)
7.1.1 The Three-Phase RLHF Pipeline
Phase 1: Supervised Fine-Tuning (SFT)
# Standard supervised learning
θ_sft = argmin_θ E[(x,y)~D_sft][L_CE(π_θ(y|x), y)]Phase 2: Reward Model Training
# Learn human preferences
θ_R = argmin_θ E[(x,y_w,y_l)~D_pref][
-log(σ(R_θ(x,y_w) - R_θ(x,y_l)))
]Phase 3: PPO Optimization
# Optimize policy with reward signal
θ_π = argmax_θ E[R(x,y) - β·KL(π_θ||π_ref)]7.1.2 Memory Requirements per Phase
| Phase | Models Needed | Memory (70B) | Communication |
|---|---|---|---|
| SFT | Policy only | 280GB | Gradients only |
| Reward Training | Reward only | 280GB | Gradients only |
| PPO | Policy + Ref + Reward + Value | 1120GB | Complex inter-model |
7.2 PPO Algorithm: Detailed Mathematical Framework
7.2.1 Objective Function Derivation
The PPO objective maximizes expected reward while constraining policy changes:
where:
- is the probability ratio
- is the advantage estimate
- is the clipping parameter (typically 0.2)
7.2.2 Advantage Estimation (GAE)
Generalized Advantage Estimation computes:
where is the TD residual.
Recursive formulation:
7.3 Four-Model System Architecture
7.3.1 Model Specifications
For a 70B parameter base model:
| Model | Parameters | Purpose | Memory (FP16) |
|---|---|---|---|
| Actor | 70B | Generate responses | 140GB |
| Critic | 70B + value head | Estimate returns | 140GB |
| Reference | 70B (frozen) | KL regularization | 140GB |
| Reward | 70B + reward head | Score responses | 140GB |
Total: 560GB for all models simultaneously!
7.3.2 FSDP Sharding Strategy
With 32 GPUs (4 nodes × 8 GPUs), each with 80GB memory:
# Device mesh for multi-model training
device_mesh = DeviceMesh(
"cuda",
mesh=[[0,1,2,3,4,5,6,7], # Node 0: Actor
[8,9,10,11,12,13,14,15], # Node 1: Critic
[16,17,18,19,20,21,22,23], # Node 2: Reference
[24,25,26,27,28,29,30,31]] # Node 3: Reward
)Memory per GPU:
- Without FSDP: 140GB (impossible!)
- With FSDP(8): 140GB/8 = 17.5GB ✓
7.4 PPO Forward Pass: Complete Data Flow
Step 1: Generate Responses (Actor)
# Input: prompts x ∈ R^{B×S_prompt}
# Actor generates completions
with actor_fsdp.summon_full_params():
logits = actor(x) # R^{B×S_response×V}
responses = sample(logits, temperature=T)Memory on Actor GPUs:
Sharded params: 17.5GB
Gathered params: 140GB (temporary)
Activations: ~10GB
Total peak: 167.5GB > 80GB ❌
Solution: Layer-by-layer gathering!
Step 2: Compute KL Penalty (Reference)
# Reference model evaluates actor's responses
with ref_fsdp.summon_full_params():
ref_logits = reference(concat(x, responses))
log_probs_ref = log_softmax(ref_logits)
# Compute KL divergence
kl_penalty = sum(π_θ * (log(π_θ) - log(π_ref)))Communication: Actor → Reference
- Data: Responses + logits
- Size: bytes
- Time: (inter-node)
Step 3: Score Responses (Reward)
# Reward model scores the generated responses
with reward_fsdp.summon_full_params():
rewards = reward_model(concat(x, responses))
# Shape: R^{B×1}Step 4: Estimate Values (Critic)
# Critic estimates value of states
with critic_fsdp.summon_full_params():
values = critic(concat(x, responses[:t]))
# Shape: R^{B×S_response}Step 5: Compute Advantages
# Using GAE with γ=0.99, λ=0.95
advantages = compute_gae(rewards, values, gamma, lam)
returns = advantages + values7.5 PPO Backward Pass: Gradient Flow
7.5.1 Actor Gradient Computation
The actor loss combines:
- Policy gradient loss
- Value function loss (if shared backbone)
- Entropy bonus
Gradient computation:
# Compute probability ratio
ratio = exp(log_probs - old_log_probs)
# Clipped surrogate loss
surr1 = ratio * advantages
surr2 = clip(ratio, 1-ε, 1+ε) * advantages
policy_loss = -min(surr1, surr2).mean()
# Backward pass
policy_loss.backward()
# Reduce-scatter gradients across FSDP group
grad_actor_shard = reduce_scatter(grad_actor_full)7.5.2 Critic Gradient Computation
Value function loss:
value_loss = 0.5 * (returns - values).pow(2).mean()
value_loss.backward()
grad_critic_shard = reduce_scatter(grad_critic_full)7.6 Memory Orchestration Timeline
7.6.1 Time-Multiplexed Execution
With limited GPU memory, models are loaded/unloaded dynamically:
Time GPU Memory State Operation
────────────────────────────────────────────────
t=0 [Actor: 140GB] Generate responses
t=1 [Free Actor → Load Ref] Transfer responses
t=2 [Reference: 140GB] Compute KL penalty
t=3 [Free Ref → Load Reward] Transfer KL values
t=4 [Reward: 140GB] Score responses
t=5 [Free Reward → Load Critic] Transfer rewards
t=6 [Critic: 140GB] Estimate values
t=7 [Keep Critic] Compute advantages
t=8 [Free Critic → Load Actor] Start backward
t=9 [Actor: 140GB] Actor.backward()
t=10 [Free Actor → Load Critic]
t=11 [Critic: 140GB] Critic.backward()
────────────────────────────────────────────────
7.6.2 Pipeline Parallelism Alternative
Split models across nodes in pipeline:
Node 0: Actor layers 0-20
Node 1: Actor layers 21-40 + Critic layers 0-20
Node 2: Critic layers 21-40 + Ref layers 0-20
Node 3: Ref layers 21-40 + Reward (full)
This enables concurrent execution but increases communication.
7.7 PPO vs Standard RLHF: Key Differences
7.7.1 Algorithm Comparison
| Aspect | PPO | Standard RLHF (REINFORCE) |
|---|---|---|
| Optimization | Clipped surrogate | Direct policy gradient |
| Sample Efficiency | High (reuse data) | Low (on-policy) |
| Stability | Stable (clipping) | Unstable (high variance) |
| Compute | 4-6 models | 3 models |
| Memory | ~560GB | ~420GB |
7.7.2 Mathematical Differences
REINFORCE Gradient:
PPO Gradient (with importance sampling):
Key advantage: PPO can reuse old samples via importance sampling!
7.8 Communication Patterns in Multi-Model PPO
7.8.1 Inter-Model Data Transfer
# Data flow between models
Actor → Reference: B × S × V × 2 bytes (logits)
Actor → Reward: B × S × 2 bytes (tokens)
Actor → Critic: B × S × 2 bytes (tokens)
Reward → Critic: B × 1 × 4 bytes (rewards)
Reference → Actor: B × S × 4 bytes (KL values)
Critic → Actor: B × S × 4 bytes (advantages)Total per iteration: ~ bytes
7.8.2 Optimized Communication Strategy
Broadcast-Reduce Pattern:
def optimized_ppo_comm(actor_output, device_mesh):
# Broadcast from actor node to all
if rank in actor_ranks:
broadcast(actor_output, root=actor_root)
# Each model processes independently
ref_output = reference_forward(actor_output)
reward_output = reward_forward(actor_output)
critic_output = critic_forward(actor_output)
# Reduce results back to actor
advantages = all_reduce([ref_output, reward_output, critic_output])
return advantages7.9 Scaling Analysis
7.9.1 Weak Scaling
Keep batch size per GPU constant, increase GPUs:
| GPUs | Model Size | Batch/GPU | Total Batch | Time/Step |
|---|---|---|---|---|
| 8 | 70B | 1 | 8 | 10s |
| 16 | 140B | 1 | 16 | 10.5s |
| 32 | 280B | 1 | 32 | 11s |
Near-linear scaling until communication dominates.
7.9.2 Strong Scaling
Fix total batch size, increase GPUs:
| GPUs | Batch/GPU | Compute Time | Comm Time | Total | Efficiency |
|---|---|---|---|---|---|
| 8 | 16 | 40s | 2s | 42s | 100% |
| 16 | 8 | 20s | 4s | 24s | 87.5% |
| 32 | 4 | 10s | 8s | 18s | 58.3% |
Efficiency drops as communication overhead increases.
7.10 Complete Worked Example: One PPO Iteration
7.10.1 Setup
- Model: Llama-70B (, , )
- Hardware: 32 A100 GPUs (4 nodes × 8 GPUs, 80GB each)
- Batch: , ,
- FSDP: Sharding factor = 8 per model
7.10.2 Memory Calculation per Model
Parameter Memory:
Base model: 70B × 2 bytes (FP16) = 140GB
Per GPU with FSDP(8): 140GB / 8 = 17.5GB
Activation Memory (per forward pass):
Per layer: B × S × h × 2 = 32 × 1024 × 8192 × 2 = 536MB
Total (80 layers): 536MB × 80 = 42.9GB
Per GPU: 42.9GB / 8 = 5.4GB
Peak Memory During All-Gather:
Sharded params: 17.5GB
Full layer params: 1.75GB (one layer)
Activations: 5.4GB
Buffer: 2GB
Total: 26.65GB < 80GB ✓
7.10.3 Forward Pass Timeline
t=0ms: Start Actor Forward
# Node 0 (GPUs 0-7): Actor model
for layer in range(80):
# All-gather layer params (1.75GB)
t_gather = 1.75GB / (600GB/s × 8) = 0.36ms
# Compute layer
FLOPs = 2 × B × S × (12 × h²)
= 2 × 32 × 1024 × 12 × 8192²
= 52.6 TFLOPs
t_compute = 52.6TF / (312TF/s × 8) = 21ms
# Free gathered params
t_free = 0.1ms
Total per layer: 21.46ms
Total actor forward: 80 × 21.46ms = 1717mst=1717ms: Actor → Reference Transfer
# Transfer logits from Node 0 to Node 2
Data size: B × S × V × 2 = 32 × 512 × 32000 × 2 = 1.05GB
Transfer time: 1.05GB / 100GB/s = 10.5mst=1728ms: Reference Forward
# Node 2 (GPUs 16-23): Reference model
# Similar to actor: 1717ms
End time: 3445mst=3445ms: Actor + Ref → Reward Transfer
# Transfer responses to Node 3
Data size: B × S × 2 = 32 × 512 × 2 = 32KB
Transfer time: negligiblet=3446ms: Reward Forward
# Node 3 (GPUs 24-31): Reward model
# Forward pass: 1717ms
# Final scalar output per sequence
End time: 5163mst=5163ms: All → Critic Transfer
# Aggregate data for critic
Data size: ~1GB
Transfer time: 10mst=5173ms: Critic Forward
# Node 1 (GPUs 8-15): Critic model
# Forward pass: 1717ms
End time: 6890mst=6890ms: Compute Advantages
# GAE computation (on CPU or single GPU)
for t in reversed(range(S)):
delta = rewards[t] + gamma × values[t+1] - values[t]
advantages[t] = delta + gamma × lambda × advantages[t+1]
Time: ~5ms7.10.4 Backward Pass Timeline
t=6895ms: Critic Backward
# Gradient computation per layer
for layer in reversed(range(80)):
# All-gather params: 0.36ms
# Compute gradients:
Backward FLOPs ≈ 2 × Forward FLOPs
t_grad = 42ms
# Reduce-scatter gradients
t_reduce = 1.75GB / (600GB/s × 8) = 0.36ms
Total per layer: 42.72ms
Total critic backward: 80 × 42.72ms = 3418ms
End time: 10313mst=10313ms: Actor Backward
# Similar to critic backward
Total: 3418ms
End time: 13731ms7.10.5 Optimizer Step
t=13731ms: Update Weights
# Each GPU updates its sharded parameters
for param_shard, grad_shard in zip(params, grads):
# Adam update (all local operations)
m = β1 × m + (1-β1) × grad_shard
v = β2 × v + (1-β2) × grad_shard²
param_shard -= lr × m / (sqrt(v) + ε)
Time per model: ~50ms
Total (parallel): 50msTotal Iteration Time: 13.78 seconds
7.10.6 Throughput Analysis
Tokens processed: B × (S_prompt + S_response) = 32 × 1024 = 32,768
Time: 13.78s
Throughput: 32,768 / 13.78 = 2,378 tokens/second
FLOPs utilized:
- Forward: 4 models × 52.6 TFLOPs × 80 layers = 16.8 PFLOPs
- Backward: 2 models × 105.2 TFLOPs × 80 layers = 16.8 PFLOPs
- Total: 33.6 PFLOPs
FLOP/s achieved: 33.6 PF / 13.78s = 2.44 PFLOP/s
Peak theoretical: 32 × 312 TFLOP/s = 9.98 PFLOP/s
Efficiency: 24.4%
7.10.7 Communication Breakdown
Intra-node (NVLink):
- All-gather: 80 layers × 1.75GB × 4 models = 560GB
- Reduce-scatter: 80 layers × 1.75GB × 2 models = 280GB
- Time: 840GB / (600GB/s × 8) = 175ms
Inter-node (InfiniBand):
- Model outputs: ~4GB
- Time: 4GB / 100GB/s = 40ms
Communication fraction: 215ms / 13780ms = 1.6%
7.11 Optimizations for Production
7.11.1 Gradient Accumulation
Simulate larger batches without memory increase:
accumulation_steps = 4
for step in range(accumulation_steps):
loss = compute_loss(batch[step]) / accumulation_steps
loss.backward() # Accumulate gradients
optimizer.step() # Single update
optimizer.zero_grad()Effective batch:
7.11.2 Mixed Precision Training
Use FP16 compute with FP32 master weights:
with autocast():
output = model(input) # FP16 compute
loss = criterion(output, target)
scaler.scale(loss).backward() # Scale gradients
scaler.step(optimizer) # Unscale before update
scaler.update()Memory savings: 50% for activations
Speed improvement: 2-3× on A100
7.11.3 Flash Attention
Replace standard attention with Flash Attention:
Standard: memory
Flash: memory
# Standard attention
scores = Q @ K.T / sqrt(d) # S×S matrix!
attn = softmax(scores) @ V
# Flash attention (fused kernel)
attn = flash_attn(Q, K, V) # No S×S materializedFor : Memory reduction from 16MB to 0.5MB per head!
8. 2D/3D Parallelism
8.1 Parallelism Hierarchy
8.2 Optimal Decomposition
For total GPUs:
- Minimize inter-node communication: GPUs per node
- Balance memory:
- Maximize batch:
8.3 Communication Hierarchy
- Intra-node (NVLink, 600GB/s): Tensor parallel
- Inter-node (InfiniBand, 100GB/s): FSDP/Pipeline
- Cross-rack (Ethernet, 10GB/s): Data parallel
Appendix A: Implementation Details
A.1 VERL Framework Architecture
The VERL framework implements FSDP through:
# Simplified architecture
class FSDPWorker:
def __init__(self, model_config):
self.device_mesh = create_device_mesh()
self.model = FSDP(
model,
device_mesh=self.device_mesh,
sharding_strategy=ShardingStrategy.FULL_SHARD
)
def train_step(self, batch):
# All-gather parameters
with self.model.summon_full_params():
output = self.model(batch)
# Compute loss
loss = compute_loss(output)
# Reduce-scatter gradients
loss.backward()
# Update sharded optimizer states
self.optimizer.step()A.2 Configuration Parameters
Key FSDP settings:
sharding_strategy: FULL_SHARD, SHARD_GRAD_OP, NO_SHARDcpu_offload: Move parameters to CPU when not in usemixed_precision: FP16/BF16 trainingactivation_checkpointing: Trade compute for memory
A.3 Multi-Node Setup
# Example 4-node configuration
fsdp_config:
sharding_strategy: FULL_SHARD
device_mesh:
shape: [4, 8] # 4 nodes × 8 GPUs
dim_names: ["fsdp", "dp"]
communication:
backend: nccl
timeout: 1800
optimization:
gradient_accumulation: 4
mixed_precision: bf16Appendix B: Code Examples
B.1 Basic FSDP Training Loop
import torch
from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
def train_with_fsdp(model, dataloader, num_epochs):
# Wrap model with FSDP
model = FSDP(
model,
sharding_strategy=ShardingStrategy.FULL_SHARD,
cpu_offload=CPUOffload(offload_params=True),
mixed_precision=MixedPrecision(
param_dtype=torch.bfloat16,
reduce_dtype=torch.bfloat16,
)
)
optimizer = torch.optim.AdamW(model.parameters())
for epoch in range(num_epochs):
for batch in dataloader:
# Forward pass (triggers all-gather)
output = model(batch['input'])
loss = F.cross_entropy(output, batch['target'])
# Backward pass (triggers reduce-scatter)
loss.backward()
# Optimizer step (on sharded params)
optimizer.step()
optimizer.zero_grad()B.2 Sequence Parallel Integration
from verl.utils.ulysses import (
set_ulysses_sequence_parallel_group,
ulysses_pad_and_slice_inputs
)
def forward_with_ulysses(input_ids, position_ids, sp_size):
# Pad and slice inputs for sequence parallelism
input_ids, position_ids, pad_size = ulysses_pad_and_slice_inputs(
input_ids, position_ids, sp_size
)
# Forward through model with SP
with ulysses_context(sp_group):
output = model(input_ids, position_ids)
# Gather outputs
output = gather_sequence_parallel_output(output)
# Remove padding
if pad_size > 0:
output = output[:, :-pad_size]
return outputAppendix C: Configuration Reference
C.1 Memory Estimation
def estimate_memory_requirements(
model_size_b: float, # Billions of parameters
batch_size: int,
seq_length: int,
num_gpus: int,
sharding_factor: int
) -> dict:
"""Estimate memory requirements for FSDP training"""
# Model memory (assuming fp32)
param_memory = model_size_b * 1e9 * 4 / 1e9 # GB
# Sharded memory per GPU
sharded_param = param_memory / sharding_factor
sharded_grad = sharded_param
sharded_optimizer = sharded_param * 2 # Adam
# Peak during all-gather
peak_param = param_memory # Full model
# Activations (rough estimate)
activation_memory = (
batch_size * seq_length * 8192 * 24 * 4 / 1e9
) # Assuming hidden_size=8192, 24 layers
return {
'sharded_total': sharded_param + sharded_grad + sharded_optimizer,
'peak_memory': max(peak_param, activation_memory),
'recommended_gpu_memory': peak_param * 1.5 # 50% safety margin
}C.2 Optimal Configuration Finder
def find_optimal_fsdp_config(
model_size_b: float,
gpu_memory_gb: int,
num_gpus: int,
interconnect_speed_gbps: int
) -> dict:
"""Find optimal FSDP configuration"""
# Minimum sharding factor for memory
min_sharding = math.ceil(
(model_size_b * 4) / (gpu_memory_gb * 0.5)
)
# Maximum useful sharding (communication bound)
max_sharding = min(
num_gpus,
int(interconnect_speed_gbps / 10) # Rule of thumb
)
# Optimal is usually in between
optimal_sharding = min(
max(min_sharding, num_gpus // 2),
max_sharding
)
return {
'sharding_factor': optimal_sharding,
'use_cpu_offload': min_sharding > num_gpus,
'gradient_checkpointing': model_size_b > 30,
'mixed_precision': True, # Always recommended
}References
This guide provides the theoretical foundation for FSDP. For implementation details, see the appendices and code examples.