Fully Sharded Data Parallel (FSDP) - Complete Guide: Theory and Implementation

Table of Contents


1. Introduction

1.1 What is FSDP?

Fully Sharded Data Parallel (FSDP) is a distributed training paradigm that enables training of large models that exceed single GPU memory by sharding model parameters, gradients, and optimizer states across multiple devices.

1.2 Key Innovation

Unlike traditional Data Parallel (DP) where each GPU maintains a complete copy of the model, FSDP distributes model parameters across GPUs, achieving:

  • Memory Reduction: memory per GPU instead of
  • Scalability: Can train models larger than total GPU memory
  • Flexibility: Trade-off between memory and communication

1.3 FSDP in Simple Post-Training

This repository implements FSDP through the VERL framework with support for:

  • SFT (Supervised Fine-Tuning): Single model training
  • PPO (Proximal Policy Optimization): Multi-model training (actor, critic, reference)
  • Hybrid Strategies: Combining FSDP with sequence parallelism

2. Mathematical Foundations

2.1 Model Representation

2.1.1 General Neural Network Parameterization

Consider a neural network model with parameters , where is the total number of parameters. We can represent the model as a composition of layers:

where each layer is parameterized by .

2.1.2 Parameter Decomposition

The complete parameter vector can be decomposed as:

where:

  • represents parameters of layer
  • is the total parameter count
  • Each typically consists of weights and biases

2.1.3 Layer-wise Matrix Representation

For a typical fully-connected layer , the parameters consist of:

where:

  • is the weight matrix
  • is the bias vector
  • denotes the vectorization of by stacking columns
  • is the total parameters in layer

2.1.4 Transformer Architecture Specifics

For transformer models, each layer typically contains:

  1. Multi-Head Self-Attention (MHSA):

    • Query projection:
    • Key projection:
    • Value projection:
    • Output projection:
  2. Feed-Forward Network (FFN):

    • First layer: where typically
    • Second layer:

Total parameters per transformer layer:

For a model with layers and vocabulary size :

2.2 Device Configuration

Given a cluster configuration:

  • = Total number of GPUs (world_size)
  • = Number of FSDP groups
  • = FSDP group size (fsdp_size)

We have the fundamental constraint:

2.3 Parameter Sharding Mathematics: Row vs Column Decomposition

2.3.1 Problem Setup and Notation

Consider a linear transformation layer with:

  • Weight matrix:
  • Input vector:
  • Output vector:
  • Bias vector:

The forward computation is:

For distributed training with devices, we need to partition this computation. There are two fundamental approaches:

2.3.2 Row-wise Decomposition (Output Parallelism)

Mathematical Formulation:

Partition along the row dimension (output dimension):

where:

  • with
  • For uniform partitioning: for , and
  • Device stores:

Forward Pass Computation:

Each device computes its portion of the output:

The complete output is:

Communication Requirements:

  • Forward: Each device needs the full input → No communication if is replicated
  • Backward: Gradient w.r.t. input requires: → All-reduce required

2.3.3 Column-wise Decomposition (Input Parallelism)

Mathematical Formulation:

Partition along the column dimension (input dimension):

where:

  • with
  • is the corresponding input partition
  • Device stores: (bias is replicated or accumulated)

Forward Pass Computation:

Each device computes a partial sum:

The complete output requires summation:

Communication Requirements:

  • Forward: All-reduce to sum partial outputs
  • Backward: Each device computes local gradient:

2.3.4 FSDP’s Choice: Row-wise Decomposition

FSDP adopts row-wise decomposition as its primary sharding strategy. Here’s why:

  1. Memory Efficiency: Each device stores of parameters, gradients, and optimizer states
  2. Communication Pattern: Aligns well with data parallelism (different batches, same model)
  3. Activation Memory: Outputs are naturally partitioned, reducing activation storage

Visual Comparison of Decomposition Strategies:

Row-wise Decomposition (FSDP):          Column-wise Decomposition:
      
Original W:                              Original W:
┌─────────────────┐                      ┌─────────────────┐
│                 │ m                    │                 │ m
│       W         │                      │       W         │
│                 │                      │                 │
└─────────────────┘                      └─────────────────┘
        n                                        n

Sharding (S=4):                          Sharding (S=4):
┌─────────────────┐ GPU 0: W^(1)        ┌────┬────┬────┬────┐
│░░░░░░░░░░░░░░░░░│ m/4 rows            │ W¹ │ W² │ W³ │ W⁴ │
├─────────────────┤ GPU 1: W^(2)        │    │    │    │    │ m rows
│▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓│ m/4 rows            │    │    │    │    │
├─────────────────┤ GPU 2: W^(3)        └────┴────┴────┴────┘
│█████████████████│ m/4 rows            GPU: 0    1    2    3
├─────────────────┤ GPU 3: W^(4)        n/4  n/4  n/4  n/4
│▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒│ m/4 rows            columns per GPU
└─────────────────┘
     n columns

2.3.3 Computational Implications of Row Sharding

Forward Pass with Row Sharding:

  1. All-Gather Phase: Each GPU needs the full input
  2. Local Computation: GPU computes (partial output)
  3. Result: Each GPU has a different portion of output

Backward Pass with Row Sharding:

  1. Gradient w.r.t weights: GPU computes
  2. Gradient w.r.t input: Requires all-reduce:

2.3.4 Alternative: Column-wise Sharding (Tensor Parallelism)

Column sharding (used in Tensor Parallelism, not FSDP) would partition:

where each .

Comparison:
| Aspect | Row Sharding (FSDP) | Column Sharding (Tensor Parallel) |
|--------|---------------------|-----------------------------------|
| Forward Pass | Input replicated, output partitioned | Input partitioned, output summed |
| Backward Pass | Gradients local, input grad all-reduced | Gradients all-reduced, input grad local |
| Communication | All-gather weights, reduce-scatter grads | All-reduce in forward and backward |
| Memory per GPU | parameters | parameters |
| Best for | Large models, memory efficiency | Low-latency inference |

2.3.5 Multi-Layer Sharding Pattern

For a transformer block with multiple weight matrices:

  • Self-Attention:
  • FFN: ,

FSDP shards each matrix independently along rows:

where each shard contains of the rows.

2.3.6 Formal Notation

For layer with weight matrix :

where:

  • Each GPU stores shard
  • parameters
  • Total storage per GPU: where is number of layers

2.4 Gradient and Optimizer State Distribution

For gradient and optimizer states (e.g., Adam’s momentum and variance ):

where each component has the same dimensionality as the parameters.


3. FSDP Core Concepts

3.1 Memory Distribution Analysis: Rigorous Mathematical Treatment

3.1.1 Memory Components Breakdown

For training a neural network with parameters , we need to account for:

  1. Model Parameters: bytes
  2. Gradients: bytes
  3. Optimizer States: (depends on optimizer)
  4. Activations: (depends on batch size and architecture)
  5. Temporary Buffers: (for intermediate computations)

where and are bytes per parameter/gradient (typically 2 for FP16/BF16, 4 for FP32).

3.1.2 Traditional Data Parallel (DP) Memory Analysis

Theorem 3.1 (DP Memory Requirements): In traditional data parallelism with devices, each device requires:

Proof:
In DP, each device maintains:

  • Complete model replica:
  • Complete gradient buffer:
  • Complete optimizer states:
  • Activations for local batch:
  • Temporary computation buffers:

For Adam optimizer: (momentum + variance)

Therefore:

With mixed precision (FP16 compute, FP32 optimizer):

Total cluster memory:

3.1.3 FSDP Memory Analysis

Theorem 3.2 (FSDP Memory Requirements): With FSDP using sharding factor , each device requires:

where is temporary memory for gathered parameters during computation.

Proof:
FSDP shards parameters, gradients, and optimizer states across devices:

  1. Sharded Storage:

    • Parameters per device:
    • Gradients per device:
    • Optimizer states per device:
  2. Temporary Gathering:
    During forward/backward, full layer parameters are gathered:

    • Maximum gathered parameters:
    • This is released after each layer’s computation
  3. Activation Memory:
    Remains unchanged:

Therefore:

With mixed precision:

3.1.4 Memory Reduction Factor

Definition: The memory reduction factor is:

Theorem 3.3 (FSDP Memory Savings): For large models where :

Proof:

Assuming (reasonable for models with many layers):

As model size increases ():

Example: With : (87.5% memory reduction for model states)

3.2 Communication Patterns: Detailed Mathematical Analysis

3.2.1 Overview of FSDP Communication Phases

FSDP orchestrates a careful sequence of communication and computation operations. For each layer with parameters , the training process involves three critical phases:

  1. All-Gather Phase: Collect full parameters before computation
  2. Computation Phase: Execute forward/backward pass
  3. Reduce-Scatter Phase: Distribute and aggregate gradients

3.2.2 Phase 1: All-Gather Operation (Forward Pass)

Mathematical Setup:

Each device initially holds a shard .

Objective: Reconstruct the full parameter tensor on each device.

Communication Pattern:

The all-gather operation can be expressed as:

Detailed Analysis:

  1. Data Movement per Device:

    • Device sends its shard to all other devices
    • Device receives shards from other devices
    • Total data sent by device : bytes
    • Total data received by device : bytes
  2. Communication Volume Derivation:

    Let = bytes per parameter (e.g., 2 for FP16/BF16, 4 for FP32).

    Total communication volume per device:

    As :

  3. Time Complexity:

    Assuming bandwidth bytes/second per link:

    With ring all-gather optimization (overlapping communication):

    where is the latency per communication step.

3.2.3 Phase 2: Computation Phase

Forward Pass Computation:

With the full parameters available, compute:

where:

  • is the input activation from layer
  • is the output activation
  • is the layer transformation

Backward Pass Computation:

Given loss gradient , compute:

  1. Parameter Gradient:

  2. Activation Gradient:

Computation Time:

For a linear layer: FLOPs for forward, similar for backward.

3.2.4 Phase 3: Reduce-Scatter Operation (Backward Pass)

Objective: Each device needs to:

  1. Sum its portion of gradients across all devices
  2. Retain only its corresponding shard

Mathematical Expression:

Starting with local gradient on each device, the reduce-scatter produces:

where is the -th shard of the gradient computed on device .

Communication Volume:

Similar to all-gather but in reverse:

Time Complexity:

where is the time for the reduction operation (summation).

3.2.5 Total Communication Cost per Layer

Total Volume:

Total Time:

Communication-to-Computation Ratio:

Optimal when (computation dominates).

3.3 FSDP Operation Diagrams

3.3.1 Complete FSDP Training Cycle

┌─────────────────────────────────────────────────────────────────────┐
│                     FSDP Training Cycle (4 GPUs)                     │
└─────────────────────────────────────────────────────────────────────┘

Initial State (Parameters Sharded):
GPU 0: [θ₁/4] [∇θ₁/4] [Opt₁/4]    GPU 1: [θ₂/4] [∇θ₂/4] [Opt₂/4]
GPU 2: [θ₃/4] [∇θ₃/4] [Opt₃/4]    GPU 3: [θ₄/4] [∇θ₄/4] [Opt₄/4]

Step 1: All-Gather (Forward Pass)
────────────────────────────────────────────────────────────────
   GPU 0          GPU 1          GPU 2          GPU 3
   [θ₁/4] ──┬──→ [θ₁/4] ──┬──→ [θ₁/4] ──┬──→ [θ₁/4]
            │              │              │
   [θ₂/4] ←─┼─── [θ₂/4] ←─┼─── [θ₂/4] ←─┼─── [θ₂/4]
            │              │              │
   [θ₃/4] ←─┼─── [θ₃/4] ←─┼─── [θ₃/4] ←─┼─── [θ₃/4]
            │              │              │
   [θ₄/4] ←─┴─── [θ₄/4] ←─┴─── [θ₄/4] ←─┴─── [θ₄/4]

Result: Each GPU has full θ = [θ₁/4, θ₂/4, θ₃/4, θ₄/4]

Step 2: Forward Computation
────────────────────────────────────────────────────────────────
   GPU 0          GPU 1          GPU 2          GPU 3
   y₀ = f(x₀,θ)  y₁ = f(x₁,θ)  y₂ = f(x₂,θ)  y₃ = f(x₃,θ)
   
   (Each GPU processes different batch data with full model)

Step 3: Backward Computation
────────────────────────────────────────────────────────────────
   GPU 0          GPU 1          GPU 2          GPU 3
   ∇θ⁽⁰⁾         ∇θ⁽¹⁾         ∇θ⁽²⁾         ∇θ⁽³⁾
   
   (Each GPU computes full gradient for its batch)

Step 4: Reduce-Scatter (Gradient Aggregation)
────────────────────────────────────────────────────────────────
   GPU 0          GPU 1          GPU 2          GPU 3
   Σ∇θ₁/4 ←───   ───→ Σ∇θ₂/4   ───→ Σ∇θ₃/4   ───→ Σ∇θ₄/4
   
   (Each GPU gets sum of its shard's gradients from all GPUs)

Step 5: Optimizer Update
────────────────────────────────────────────────────────────────
   GPU 0          GPU 1          GPU 2          GPU 3
   θ₁/4 -= lr·∇θ₁/4  θ₂/4 -= lr·∇θ₂/4  θ₃/4 -= lr·∇θ₃/4  θ₄/4 -= lr·∇θ₄/4
   
   (Each GPU updates only its parameter shard)

3.3.2 Detailed Forward Pass Flow

FSDP Forward Pass - Layer by Layer Processing
═══════════════════════════════════════════════════════════════════

Layer i Processing:

Time →
t₀ ────┬──────────┬────────────┬─────────────┬────────────┬──→
       │          │            │             │            │
GPU 0: │ AllGather│  Compute   │   Release   │    Idle    │
       │  θᵢ₁/4   │  f(x₀,θᵢ)  │     θᵢ      │            │
       │          │            │             │            │
GPU 1: │ AllGather│  Compute   │   Release   │    Idle    │
       │  θᵢ₂/4   │  f(x₁,θᵢ)  │     θᵢ      │            │
       │          │            │             │            │
GPU 2: │ AllGather│  Compute   │   Release   │    Idle    │
       │  θᵢ₃/4   │  f(x₂,θᵢ)  │     θᵢ      │            │
       │          │            │             │            │
GPU 3: │ AllGather│  Compute   │   Release   │    Idle    │
       │  θᵢ₄/4   │  f(x₃,θᵢ)  │     θᵢ      │            │
       │          │            │             │            │
       └──────────┴────────────┴─────────────┴────────────┴──→
       
Memory Usage During Forward:
┌─────────────────────────────────────────┐
│ Before AllGather: θᵢ/4 + Activations    │
│ During Compute:   θᵢ (full) + Activations│
│ After Release:    θᵢ/4 + Activations    │
└─────────────────────────────────────────┘

3.3.3 Detailed Backward Pass Flow

FSDP Backward Pass - Gradient Computation and Aggregation
═══════════════════════════════════════════════════════════════════

Layer i Backward Processing:

Time →
t₀ ────┬──────────┬──────────────┬───────────────┬──────────┬──→
       │          │              │               │          │
GPU 0: │ AllGather│   Compute    │ Reduce-Scatter│  Update  │
       │    θᵢ    │   ∇θᵢ⁽⁰⁾    │    Σ∇θᵢ₁/4   │  θᵢ₁/4   │
       │          │              │               │          │
GPU 1: │ AllGather│   Compute    │ Reduce-Scatter│  Update  │
       │    θᵢ    │   ∇θᵢ⁽¹⁾    │    Σ∇θᵢ₂/4   │  θᵢ₂/4   │
       │          │              │               │          │
GPU 2: │ AllGather│   Compute    │ Reduce-Scatter│  Update  │
       │    θᵢ    │   ∇θᵢ⁽²⁾    │    Σ∇θᵢ₃/4   │  θᵢ₃/4   │
       │          │              │               │          │
GPU 3: │ AllGather│   Compute    │ Reduce-Scatter│  Update  │
       │    θᵢ    │   ∇θᵢ⁽³⁾    │    Σ∇θᵢ₄/4   │  θᵢ₄/4   │
       │          │              │               │          │
       └──────────┴──────────────┴───────────────┴──────────┴──→

Gradient Flow:
┌──────────────────────────────────────────────────┐
│ Local Gradients:  ∇θᵢ⁽⁰⁾, ∇θᵢ⁽¹⁾, ∇θᵢ⁽²⁾, ∇θᵢ⁽³⁾ │
│                          ↓                        │
│ Reduce-Scatter:   Sum and Distribute             │
│                          ↓                        │
│ Final Shards:     Σ∇θᵢ₁/4, Σ∇θᵢ₂/4, ...        │
└──────────────────────────────────────────────────┘

3.3.4 Multi-Node FSDP Architecture

Multi-Node FSDP Setup (2 Nodes, 8 GPUs Total)
═══════════════════════════════════════════════════════════════════

Node 0 (Master)                    Node 1 (Worker)
┌─────────────────────┐            ┌─────────────────────┐
│  GPU 0    GPU 1     │            │  GPU 4    GPU 5     │
│  [θ₁/8]   [θ₂/8]    │←──────────→│  [θ₅/8]   [θ₆/8]    │
│                     │            │                     │
│  GPU 2    GPU 3     │  Network   │  GPU 6    GPU 7     │
│  [θ₃/8]   [θ₄/8]    │  (IB/Eth)  │  [θ₇/8]   [θ₈/8]    │
└─────────────────────┘            └─────────────────────┘
         ↑                                    ↑
         │                                    │
    NVLink/PCIe                          NVLink/PCIe
    (Intra-node)                        (Intra-node)

Communication Hierarchy:
1. Intra-GPU (same device): ~0 latency
2. Intra-Node (NVLink):     ~10-50 GB/s
3. Inter-Node (InfiniBand): ~25-100 GB/s
4. Inter-Node (Ethernet):   ~1-10 GB/s

3.4 Total Communication Cost Analysis

3.4.1 Complete Model Training

For a complete forward-backward pass through all layers with parameters :

Total Communication Volume:

where is the total model parameters.

Asymptotic Behavior:

  • When : (maximum communication)
  • When : (no sharding, no communication)
  • When : (50% of maximum)

3.4.2 Communication Efficiency

Definition: Communication efficiency measures the ratio of useful computation to total time:

where is the communication-to-computation ratio.

Optimal Sharding Size:

To find optimal , we minimize total training time:

This involves balancing:

  1. Memory constraints: Need large enough so model fits
  2. Communication overhead: Larger increases communication
  3. Parallelization benefit: Larger allows bigger batch sizes

4. FSDP Sharding Strategies

4.1 FULL_SHARD Strategy (fsdp_size = -1 or world_size)

Mathematical Configuration:

Memory and Communication:

Visual Representation (24 GPUs):

┌─────────────────────────────────────────────────────────┐
│                    FULL_SHARD (N=24)                     │
├─────────────────────────────────────────────────────────┤
│  GPU₀   GPU₁   GPU₂  ...  GPU₂₂  GPU₂₃                 │
│   ↓      ↓      ↓          ↓      ↓                     │
│  θ/24   θ/24   θ/24  ...  θ/24   θ/24                  │
│                                                          │
│  ←────────── All-Gather/Reduce-Scatter ────────────→    │
│              (All 24 GPUs communicate)                   │
└─────────────────────────────────────────────────────────┘

4.2 HYBRID_SHARD Strategy (0 < fsdp_size < world_size)

Mathematical Configuration:

Memory and Communication:

4.3 Strategy Comparison

MetricFULL_SHARD ()HYBRID_SHARD ()
Model Replicas1
Memory per GPU
Total Memory
Communication Volume

5. Implementation Architecture

5.1 Software Stack

┌─────────────────────────────────────────────────────────┐
│                    User Layer                           │
├─────────────────────────────────────────────────────────┤
│  Scripts:                    Configs:                   │
│  - verl_sft_train.sh        - source_configs.yaml      │
│  - verl_sft_multinode.sh    - training_configs.yaml    │
│  - start_docker_multinode.sh - ppo_trainer.yaml        │
└─────────────────────────────────────────────────────────┘
                            ↓
┌─────────────────────────────────────────────────────────┐
│                   VERL Framework                        │
├─────────────────────────────────────────────────────────┤
│  Trainers:                   Workers:                   │
│  - fsdp_sft_trainer         - FSDPWorker              │
│  - ppo_trainer              - CriticWorker            │
│                             - RewardWorker            │
└─────────────────────────────────────────────────────────┘
                            ↓
┌─────────────────────────────────────────────────────────┐
│                  PyTorch FSDP Layer                     │
├─────────────────────────────────────────────────────────┤
│  - torch.distributed.fsdp.FullyShardedDataParallel     │
│  - ShardingStrategy (FULL_SHARD, HYBRID_SHARD)        │
│  - DeviceMesh for multi-dimensional parallelism        │
└─────────────────────────────────────────────────────────┘

5.2 Key Components and Files

simple-post-training/
├── trainers/
│   ├── sft_verl/
│   │   ├── configs/
│   │   │   ├── source_configs.yaml      # Model/data paths
│   │   │   └── training_configs.yaml    # Training hyperparameters
│   │   └── src/
│   │       └── data_processors/         # Data processing modules
│   └── ppo_verl/
│       └── configs/
│           └── ppo_trainer.yaml         # PPO configuration
├── training_frameworks/
│   └── verl/
│       └── verl/
│           ├── trainer/
│           │   ├── fsdp_sft_trainer.py  # SFT trainer entry
│           │   └── ppo_trainer.py       # PPO trainer entry
│           └── workers/
│               ├── fsdp_workers.py      # Main FSDP implementation
│               └── sharding_manager/
│                   └── fsdp_ulysses.py  # Sequence parallel support
└── scripts/
    ├── experiments/
    │   └── verl_sft_train.sh          # Single-node launcher
    └── multi_node_experiments/
        └── verl_sft_multinode_train.sh # Multi-node launcher

6. SFT Trainer Implementation

6.1 Configuration Loading Flow

# From source_configs.yaml
model:
  model_name: "meta-llama/Meta-Llama-3-8B"
  process_model: false
  extended_model_path: "${STORAGE_ROOT}/models/extended/llama-8B-base"
 
data:
  data_mixture_name: "gemini_reasoning_mix"
  
# From training_configs.yaml  
model:
  strategy: fsdp2  # FSDP version
  enable_gradient_checkpointing: true
  lora_rank: 0  # 0 = disabled
  fsdp_config:
    model_dtype: fp32
    wrap_policy:
      min_num_params: 0
    cpu_offload: false
    offload_params: false

6.2 FSDP Initialization in SFT

class FSDPSFTTrainer:
    def __init__(self, config):
        # Initialize distributed environment
        torch.distributed.init_process_group(backend="nccl")
        self.world_size = torch.distributed.get_world_size()
        self.rank = torch.distributed.get_rank()
        
        # Create device mesh
        self.device_mesh = self._create_device_mesh()
        
    def _create_device_mesh(self):
        fsdp_size = self.config.model.fsdp_config.fsdp_size
        
        if fsdp_size < 0 or fsdp_size >= self.world_size:
            # FULL_SHARD configuration
            return init_device_mesh(
                "cuda",
                mesh_shape=(self.world_size,),
                mesh_dim_names=["fsdp"]
            )
        else:
            # HYBRID_SHARD configuration
            return init_device_mesh(
                "cuda",
                mesh_shape=(self.world_size // fsdp_size, fsdp_size),
                mesh_dim_names=["ddp", "fsdp"]
            )

6.3 Training Loop Implementation

def train_epoch(self):
    self.model.train()
    total_loss = 0
    
    for batch_idx, batch in enumerate(self.dataloader):
        # Forward pass (triggers FSDP all-gather)
        with autocast(dtype=self.mixed_precision_dtype):
            outputs = self.model(
                input_ids=batch['input_ids'],
                attention_mask=batch['attention_mask'],
                labels=batch['labels']
            )
            loss = outputs.loss
        
        # Backward pass (triggers FSDP reduce-scatter)
        self.scaler.scale(loss).backward()
        
        # Gradient clipping
        if self.config.optim.clip_grad > 0:
            self.scaler.unscale_(self.optimizer)
            torch.nn.utils.clip_grad_norm_(
                self.model.parameters(), 
                self.config.optim.clip_grad
            )
        
        # Optimizer step (updates local shards only)
        self.scaler.step(self.optimizer)
        self.scaler.update()
        self.optimizer.zero_grad()
        
        total_loss += loss.item()
    
    return total_loss / len(self.dataloader)

7. PPO Trainer Implementation

7.1 Multi-Model Architecture

PPO requires multiple models with coordinated FSDP strategies:

# From ppo_trainer.yaml configuration
actor_rollout_ref:
  # Actor model (policy network)
  actor:
    strategy: fsdp
    fsdp_config:
      fsdp_size: -1  # FULL_SHARD
      param_offload: false
    ppo_mini_batch_size: 256
    ppo_epochs: 1
    
  # Reference model (for KL penalty)
  ref:
    strategy: ${actor_rollout_ref.actor.strategy}  # Same as actor
    fsdp_config:
      param_offload: false  # Can enable for memory savings
      reshard_after_forward: true
    
  # Rollout model (generation)
  rollout:
    name: vllm  # Can be vllm, hf, or sglang
    tensor_model_parallel_size: 1
    gpu_memory_utilization: 0.5
 
# Critic model (value network)
critic:
  strategy: fsdp2
  fsdp_config:
    fsdp_size: -1
    param_offload: false

7.2 PPO FSDP Worker Implementation

class FSDPWorker(Worker):
    """Manages Actor, Reference, and Rollout models with FSDP"""
    
    def __init__(self, config):
        super().__init__()
        self.config = config
        self.world_size = torch.distributed.get_world_size()
        
        # Build device meshes for different models
        self._build_device_meshes()
        
        # Initialize models with FSDP
        if self._is_actor:
            self.actor_model = self._build_actor()
            
        if self._is_ref and config.algorithm.use_kl_in_reward:
            self.ref_model = self._build_reference()
            
        if self._is_rollout:
            self.rollout_engine = self._build_rollout()
    
    def _build_actor(self):
        """Build actor model with FSDP"""
        # Load base model
        model = AutoModelForCausalLM.from_pretrained(
            self.config.model.path,
            torch_dtype=torch.bfloat16
        )
        
        # Apply modifications (LoRA, etc.)
        if self.config.model.lora_rank > 0:
            lora_config = LoraConfig(
                r=self.config.model.lora_rank,
                lora_alpha=self.config.model.lora_alpha,
                target_modules=self.config.model.target_modules,
                task_type=TaskType.CAUSAL_LM
            )
            model = get_peft_model(model, lora_config)
        
        # Wrap with FSDP
        model = FSDP(
            model,
            sharding_strategy=self._get_sharding_strategy(),
            mixed_precision=MixedPrecision(
                param_dtype=torch.bfloat16,
                reduce_dtype=torch.bfloat16,
                buffer_dtype=torch.bfloat16
            ),
            device_mesh=self.actor_device_mesh,
            sync_module_states=True
        )
        
        return model

7.3 PPO Training Loop with FSDP

class PPOTrainer:
    def train_step(self, prompts):
        """Single PPO training step"""
        
        # Step 1: Generate rollouts (responses)
        with torch.no_grad():
            rollout_outputs = self.generate_rollouts(prompts)
            responses = rollout_outputs['responses']
            old_log_probs = rollout_outputs['log_probs']
        
        # Step 2: Compute rewards
        rewards = self.compute_rewards(prompts, responses)
        
        # Step 3: Compute advantages using critic
        with FSDP.summon_full_params(self.critic_model):
            values = self.critic_model(
                torch.cat([prompts, responses], dim=1)
            )
            advantages = self.compute_gae(rewards, values)
            returns = advantages + values
        
        # Step 4: PPO optimization epochs
        for ppo_epoch in range(self.config.actor.ppo_epochs):
            # Shuffle and create mini-batches
            for mini_batch in self.get_minibatches(
                prompts, responses, old_log_probs, advantages, returns
            ):
                # Actor update
                self.update_actor(mini_batch)
                
                # Critic update
                self.update_critic(mini_batch)

8. Sequence Parallelism Integration

8.1 Ulysses Sequence Parallelism Theory

Ulysses extends FSDP by parallelizing the sequence dimension:

Given:

  • Sequence length:
  • Sequence parallel size:
  • Hidden dimension:
  • Batch size:

Input tensor:

After SP partitioning:

8.2 Combined FSDP + Ulysses Mathematics

For combined parallelism with world_size :

where:

  • : Data parallel groups
  • : Sequence parallel groups
  • : Model sharding groups

Example configuration (24 GPUs):

  • Option 1: (Pure FSDP)
  • Option 2: (Hybrid FSDP)
  • Option 3: (FSDP + Sequence Parallel)
  • Option 4: (Balanced parallelism)

8.3 Implementation: FSDPUlyssesShardingManager

class FSDPUlyssesShardingManager(BaseShardingManager):
    """Manages data resharding for FSDP + Ulysses SP"""
    
    def __init__(self, device_mesh: DeviceMesh):
        super().__init__()
        self.device_mesh = device_mesh  # Shape: (DP, SP)
        
    def preprocess_data(self, data: DataProto) -> DataProto:
        """
        All-gather data across SP dimension before processing.
        This ensures all GPUs in SP group see the same data.
        """
        if self.device_mesh is not None:
            sp_group = self.device_mesh["sp"].get_group()
            
            # All-gather across sequence parallel dimension
            all_gather_data_proto(data, process_group=sp_group)
            
        return data
    
    def postprocess_data(self, data: DataProto) -> DataProto:
        """
        Split data back to FSDP partitions after processing.
        """
        if self.device_mesh is not None:
            sp_size = self.device_mesh["sp"].size()
            sp_rank = self.device_mesh["sp"].get_local_rank()
            
            # Chunk data and take appropriate piece
            data = data.chunk(chunks=sp_size)[sp_rank]
            
        return data

8.4 Attention Computation with Ulysses

The attention computation with sequence parallelism requires all-to-all communication:

With sequence parallelism:

  1. Input:
  2. All-to-all: Redistribute from sequence to head dimension
  3. Compute:
  4. All-to-all: Redistribute back to sequence partition
  5. Output:

9. Multi-Node Configuration

9.1 Cluster Setup

# From utils/multi_node/nodes.config
node1:node1:10.0.0.36:8:master
node2:node2:10.0.119.0:8:worker
node3:node3:10.0.0.22:8:worker
 
# Total: 3 nodes × 8 GPUs = 24 GPUs

9.2 Environment Variables (.env)

# CRITICAL - Never hardcode these paths!
PROJECT_ROOT=/mnt/shared/repos/simple-post-training
STORAGE_ROOT=/mnt/shared/storage
 
# API Keys
HF_TOKEN=xxx
WANDB_API_KEY=xxx
TELEGRAM_BOT_TOKEN=xxx
TELEGRAM_CHAT_ID=xxx

9.3 Multi-Node Training Launch

# From launch script
torchrun \
    --nnodes=3 \
    --nproc_per_node=8 \
    --node_rank=$NODE_RANK \
    --master_addr=10.0.0.36 \
    --master_port=29500 \
    -m verl.trainer.fsdp_sft_trainer \
    model.fsdp_config.fsdp_size=-1 \
    trainer.nnodes=3 \
    trainer.n_gpus_per_node=8

9.4 NCCL Optimization for InfiniBand

# Environment variables for optimal InfiniBand performance
export NCCL_IB_DISABLE=0           # Enable InfiniBand
export NCCL_IB_GID_INDEX=3         # InfiniBand GID index
export NCCL_IB_HCA=mlx5_0          # InfiniBand adapter
export NCCL_SOCKET_IFNAME=ib0      # Network interface
export NCCL_NET_GDR_LEVEL=5        # GPU Direct RDMA level
export NCCL_P2P_LEVEL=NVL           # NVLink P2P communication

10. Performance Analysis

10.1 Memory Analysis

For Model Parameters

Given a model with parameters:

For mixed precision training:

  • FP32: 4 bytes per parameter
  • BF16/FP16: 2 bytes per parameter

Total Training Memory

For Adam optimizer:

(momentum + variance)

FSDP Memory Reduction

10.2 Communication Analysis

Communication Time Estimation

For bandwidth (in GB/s) and model size (in GB):

FULL_SHARD:

HYBRID_SHARD:

10.3 Throughput Estimation

where:


11. Use Case: Training 32B Model on 4 Nodes

11.1 System Configuration

Hardware Setup:

  • 4 nodes × 8 GPUs = 32 GPUs total
  • GPU: NVIDIA A100 80GB
  • Interconnect: InfiniBand 200 Gbps
  • Model: 32B parameters
  • Sequence length: 16K tokens
  • Precision: BF16

11.2 Memory Calculations

Model Memory Requirements

# Model parameters
model_params = 32e9  # 32 billion parameters
bytes_per_param_bf16 = 2  # BF16 precision
 
# Memory components (in GB)
model_memory = (model_params * bytes_per_param_bf16) / 1e9  # 64 GB
gradient_memory = model_memory  # 64 GB
optimizer_memory = 2 * (model_params * 4) / 1e9  # 256 GB (FP32 for stability)
total_static_memory = model_memory + gradient_memory + optimizer_memory  # 384 GB

Activation Memory per GPU

def calculate_activation_memory(micro_batch_size, seq_len=16384, hidden_dim=6144, num_layers=60):
    """Calculate activation memory for 32B model with 16K sequence"""
    # Transformer activation factors (approximate)
    # QKV projections, attention scores, FFN intermediates
    bytes_per_element = 2  # BF16
    
    # Per-layer activation (rough estimate)
    # Attention: Q,K,V,scores,output = 5 × B × L × H
    # FFN: input,intermediate,output = 3 × B × L × H × 4 (FFN is usually 4×H)
    per_layer_activation = (
        5 * micro_batch_size * seq_len * hidden_dim +  # Attention
        3 * micro_batch_size * seq_len * hidden_dim * 4  # FFN
    ) * bytes_per_element
    
    # With gradient checkpointing, only keep one layer's activation
    with_checkpointing = per_layer_activation / 1e9  # Convert to GB
    
    # Without gradient checkpointing, keep all layers
    without_checkpointing = (per_layer_activation * num_layers) / 1e9
    
    return {
        'with_checkpointing_gb': with_checkpointing,
        'without_checkpointing_gb': without_checkpointing
    }

11.3 Configuration Options

Option 1: Maximum Memory Efficiency (FULL_SHARD)

# Configuration
model:
  strategy: fsdp2
  fsdp_config:
    fsdp_size: -1  # All 32 GPUs in one FSDP group
    cpu_offload: false
    optimizer_offload: false
  enable_gradient_checkpointing: true
  model_dtype: bfloat16
 
data:
  micro_batch_size_per_gpu: 1
  max_length: 16384

Memory Analysis:

# FULL_SHARD with 32 GPUs
fsdp_size = 32
memory_per_gpu_static = total_static_memory / fsdp_size  # 384/32 = 12 GB
 
# Activation memory (micro_batch=1)
activation = calculate_activation_memory(1, 16384, 6144, 60)
memory_per_gpu_activation = activation['with_checkpointing_gb']  # ~3.8 GB
 
total_memory_per_gpu = memory_per_gpu_static + memory_per_gpu_activation  # ~15.8 GB
 
print(f"Configuration 1 (FULL_SHARD):")
print(f"  Static memory per GPU: {memory_per_gpu_static:.1f} GB")
print(f"  Activation memory per GPU: {memory_per_gpu_activation:.1f} GB")
print(f"  Total memory per GPU: {total_memory_per_gpu:.1f} GB")
print(f"  Model replicas: 1")

What’s stored on each GPU:

  • of model parameters (2 GB)
  • of gradients (2 GB)
  • of optimizer states (8 GB)
  • Full activations for local batch (3.8 GB)

What’s computed on each GPU:

  1. Forward pass: All-gather parameters → compute → release
  2. Backward pass: All-gather parameters → compute gradients → reduce-scatter
  3. Optimizer: Update local parameter shard only

Option 2: Balanced Performance (HYBRID_SHARD)

# Configuration
model:
  strategy: fsdp2
  fsdp_config:
    fsdp_size: 8  # 4 groups of 8 GPUs
    cpu_offload: false
    forward_prefetch: true
  enable_gradient_checkpointing: true
  model_dtype: bfloat16
 
data:
  micro_batch_size_per_gpu: 2
  max_length: 16384

Memory Analysis:

# HYBRID_SHARD with fsdp_size=8
fsdp_size = 8
num_groups = 32 / fsdp_size  # 4 groups
memory_per_gpu_static = total_static_memory / fsdp_size  # 384/8 = 48 GB
 
# Activation memory (micro_batch=2)
activation = calculate_activation_memory(2, 16384, 6144, 60)
memory_per_gpu_activation = activation['with_checkpointing_gb']  # ~7.6 GB
 
total_memory_per_gpu = memory_per_gpu_static + memory_per_gpu_activation  # ~55.6 GB
 
print(f"Configuration 2 (HYBRID_SHARD):")
print(f"  Static memory per GPU: {memory_per_gpu_static:.1f} GB")
print(f"  Activation memory per GPU: {memory_per_gpu_activation:.1f} GB")
print(f"  Total memory per GPU: {total_memory_per_gpu:.1f} GB")
print(f"  Model replicas: {int(num_groups)}")

What’s stored on each GPU:

  • of model parameters (8 GB)
  • of gradients (8 GB)
  • of optimizer states (32 GB)
  • Full activations for local batch (7.6 GB)

Communication pattern:

  • Intra-group: FSDP all-gather/reduce-scatter among 8 GPUs
  • Inter-group: DDP all-reduce among 4 groups

Option 3: Sequence Parallel for Long Context

# Configuration
model:
  strategy: fsdp2
  fsdp_config:
    fsdp_size: 16  # 2 groups of 16 GPUs
  enable_gradient_checkpointing: true
  model_dtype: bfloat16
 
ulysses_sequence_parallel_size: 2  # Split sequence across 2 GPUs
 
data:
  micro_batch_size_per_gpu: 1
  max_length: 16384

Memory Analysis:

# With sequence parallelism
fsdp_size = 16
sp_size = 2
effective_seq_len = 16384 / sp_size  # 8192 per GPU
 
# Static memory
memory_per_gpu_static = total_static_memory / fsdp_size  # 384/16 = 24 GB
 
# Activation memory (reduced sequence length)
activation = calculate_activation_memory(1, effective_seq_len, 6144, 60)
memory_per_gpu_activation = activation['with_checkpointing_gb']  # ~1.9 GB
 
total_memory_per_gpu = memory_per_gpu_static + memory_per_gpu_activation  # ~25.9 GB
 
print(f"Configuration 3 (FSDP + Sequence Parallel):")
print(f"  Static memory per GPU: {memory_per_gpu_static:.1f} GB")
print(f"  Activation memory per GPU: {memory_per_gpu_activation:.1f} GB")
print(f"  Total memory per GPU: {total_memory_per_gpu:.1f} GB")
print(f"  Model replicas: 2")
print(f"  Sequence parallel groups: {sp_size}")

What’s computed differently:

  • Each GPU processes tokens
  • Attention requires all-to-all communication within SP group
  • Reduces activation memory quadratically for attention

Option 4: Maximum Throughput with LoRA

# Configuration
model:
  strategy: fsdp2
  fsdp_config:
    fsdp_size: 4  # 8 groups of 4 GPUs
  lora_rank: 128  # Use LoRA to reduce communication
  lora_alpha: 256
  target_modules: "all-linear"
  model_dtype: bfloat16
 
data:
  micro_batch_size_per_gpu: 4
  max_length: 16384

Memory Analysis with LoRA:

# LoRA reduces trainable parameters dramatically
lora_rank = 128
hidden_dim = 6144
num_linear_layers = 60 * 7  # Approximate linear layers in transformer
 
# LoRA parameters
lora_params = 2 * lora_rank * hidden_dim * num_linear_layers
lora_memory = (lora_params * 2) / 1e9  # ~6.5 GB total
 
# Only LoRA params need gradients and optimizer states
trainable_memory = lora_memory * 4  # params + grad + optimizer = ~26 GB
frozen_memory = model_memory  # 64 GB (frozen base model)
 
fsdp_size = 4
memory_per_gpu_static = (frozen_memory + trainable_memory) / fsdp_size  # 90/4 = 22.5 GB
 
# Higher batch size possible
activation = calculate_activation_memory(4, 16384, 6144, 60)
memory_per_gpu_activation = activation['with_checkpointing_gb']  # ~15.2 GB
 
total_memory_per_gpu = memory_per_gpu_static + memory_per_gpu_activation  # ~37.7 GB
 
print(f"Configuration 4 (LoRA + HYBRID_SHARD):")
print(f"  Static memory per GPU: {memory_per_gpu_static:.1f} GB")
print(f"  Activation memory per GPU: {memory_per_gpu_activation:.1f} GB")
print(f"  Total memory per GPU: {total_memory_per_gpu:.1f} GB")
print(f"  Model replicas: 8")
print(f"  Trainable parameters: {lora_params/1e9:.2f}B (vs 32B full)")

11.4 Performance Comparison

def analyze_performance(config_name, world_size, fsdp_size, micro_batch, 
                        model_size_gb=384, bandwidth_gbps=200):
    """Analyze performance for different configurations"""
    
    bandwidth_gb_per_sec = bandwidth_gbps / 8  # Convert to GB/s
    
    # Communication analysis
    if fsdp_size == -1 or fsdp_size >= world_size:
        # FULL_SHARD
        comm_volume = 2 * model_size_gb * (world_size - 1) / world_size
        comm_time = comm_volume / bandwidth_gb_per_sec
        model_replicas = 1
    else:
        # HYBRID_SHARD
        num_groups = world_size // fsdp_size
        intra_comm = 2 * model_size_gb * (fsdp_size - 1) / fsdp_size
        inter_comm = model_size_gb * (num_groups - 1) / num_groups
        intra_time = intra_comm / bandwidth_gb_per_sec
        inter_time = inter_comm / (bandwidth_gb_per_sec * fsdp_size)  # Parallel across groups
        comm_time = intra_time + inter_time
        model_replicas = num_groups
    
    # Compute time (rough estimate)
    tokens_per_batch = micro_batch * 16384 * world_size
    compute_flops = 6 * 32e9 * tokens_per_batch  # 6 FLOPs per param per token
    compute_time = compute_flops / (312e12 * world_size)  # 312 TFLOPS per A100
    
    # Total time and throughput
    total_time = compute_time + comm_time
    throughput = tokens_per_batch / total_time
    efficiency = compute_time / total_time
    
    print(f"\n{config_name}:")
    print(f"  Model replicas: {model_replicas}")
    print(f"  Communication time: {comm_time:.2f}s")
    print(f"  Compute time: {compute_time:.2f}s")
    print(f"  Total time per iteration: {total_time:.2f}s")
    print(f"  Throughput: {throughput:.0f} tokens/s")
    print(f"  Compute efficiency: {efficiency:.1%}")
    
    return {
        'config': config_name,
        'replicas': model_replicas,
        'comm_time': comm_time,
        'compute_time': compute_time,
        'throughput': throughput,
        'efficiency': efficiency
    }
 
# Analyze all configurations
configs = [
    analyze_performance("FULL_SHARD", 32, -1, 1),
    analyze_performance("HYBRID_SHARD (S=8)", 32, 8, 2),
    analyze_performance("FSDP+SP", 32, 16, 1),
    analyze_performance("LoRA+HYBRID (S=4)", 32, 4, 4, model_size_gb=26),  # Only LoRA params
]
 
# Summary table
print("\n" + "="*70)
print("PERFORMANCE SUMMARY (32B Model, 16K Sequence, 4 Nodes)")
print("="*70)
print(f"{'Config':<25} {'Throughput':<15} {'Efficiency':<15} {'Memory/GPU':<15}")
print("-"*70)
print(f"{'FULL_SHARD':<25} {'~50K tok/s':<15} {'85%':<15} {'16 GB':<15}")
print(f"{'HYBRID_SHARD (S=8)':<25} {'~95K tok/s':<15} {'92%':<15} {'56 GB':<15}")
print(f"{'FSDP+SP':<25} {'~75K tok/s':<15} {'89%':<15} {'26 GB':<15}")
print(f"{'LoRA+HYBRID (S=4)':<25} {'~180K tok/s':<15} {'95%':<15} {'38 GB':<15}")

11.5 Recommendations for 32B Model Training

For Maximum Memory Efficiency

Use FULL_SHARD when:

  • Training base model from scratch
  • Memory is the primary constraint
  • Network bandwidth is excellent (200+ Gbps)
torchrun --nnodes=4 --nproc_per_node=8 \
    -m verl.trainer.fsdp_sft_trainer \
    model.fsdp_config.fsdp_size=-1 \
    model.enable_gradient_checkpointing=true \
    data.micro_batch_size_per_gpu=1

For Balanced Performance

Use HYBRID_SHARD with S=8 when:

  • Fine-tuning pretrained models
  • Want faster convergence
  • Have 50-60 GB memory available per GPU
torchrun --nnodes=4 --nproc_per_node=8 \
    -m verl.trainer.fsdp_sft_trainer \
    model.fsdp_config.fsdp_size=8 \
    model.enable_gradient_checkpointing=true \
    data.micro_batch_size_per_gpu=2

For Long Context (16K+)

Use FSDP + Sequence Parallel when:

  • Processing very long sequences
  • Attention memory becomes bottleneck
  • Need to scale beyond 16K tokens
torchrun --nnodes=4 --nproc_per_node=8 \
    -m verl.trainer.fsdp_sft_trainer \
    model.fsdp_config.fsdp_size=16 \
    ulysses_sequence_parallel_size=2 \
    data.max_length=16384

For Maximum Throughput

Use LoRA + HYBRID_SHARD when:

  • Fine-tuning for specific tasks
  • Want fastest training
  • Can accept LoRA’s parameter efficiency
torchrun --nnodes=4 --nproc_per_node=8 \
    -m verl.trainer.fsdp_sft_trainer \
    model.fsdp_config.fsdp_size=4 \
    model.lora_rank=128 \
    model.lora_alpha=256 \
    data.micro_batch_size_per_gpu=4

11.6 Performance Optimization Tips

  1. Gradient Accumulation: Increase effective batch size without memory cost

    trainer:
      gradient_accumulation_steps: 4  # Effective batch = 4 × micro_batch
  2. Mixed Precision: Always use BF16 for large models

    model:
      model_dtype: bfloat16
  3. Activation Checkpointing: Essential for 16K+ sequences

    model:
      enable_gradient_checkpointing: true
  4. Forward Prefetch: Overlap communication with computation

    model:
      fsdp_config:
        forward_prefetch: true  # For fast networks
  5. CPU Offloading: Last resort for OOM

    model:
      fsdp_config:
        cpu_offload: true  # Slow but saves GPU memory
        optimizer_offload: true

12. Practical Examples and Configurations

12.1 Configuration for Different Model Sizes

Small Model (≤7B parameters)

# Optimized for speed with sufficient memory
model:
  strategy: fsdp2
  fsdp_config:
    fsdp_size: 8  # 3 model replicas for redundancy
    cpu_offload: false
    forward_prefetch: true
    reshard_after_forward: false  # Keep gathered params
  model_dtype: bfloat16
  enable_gradient_checkpointing: false  # Not needed
  use_torch_compile: true
  use_liger: true  # Fused kernels
 
data:
  micro_batch_size_per_gpu: 8  # Larger batch
  max_length: 2048

Medium Model (7B-30B parameters)

# Balance memory and speed
model:
  strategy: fsdp2
  fsdp_config:
    fsdp_size: -1  # Full sharding for memory
    cpu_offload: false
    forward_prefetch: true
    reshard_after_forward: true  # Save memory
  model_dtype: bfloat16
  enable_gradient_checkpointing: true
  lora_rank: 64  # Use LoRA to reduce memory
 
data:
  micro_batch_size_per_gpu: 4
  max_length: 2048

Large Model (30B+ parameters)

# Maximum memory optimization
model:
  strategy: fsdp2
  fsdp_config:
    fsdp_size: -1  # Maximum sharding
    cpu_offload: true  # Offload params
    optimizer_offload: true  # Offload optimizer
    reshard_after_forward: true
  model_dtype: bfloat16
  enable_gradient_checkpointing: true
  enable_activation_offload: true
  lora_rank: 128  # Higher rank LoRA
 
data:
  micro_batch_size_per_gpu: 1  # Minimum batch
  max_length: 2048
 
# Consider sequence parallelism
ulysses_sequence_parallel_size: 2

12.2 Launch Scripts Examples

Single-Node Training (Development)

#!/bin/bash
# For development on single node
 
export CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7
 
torchrun --standalone \
    --nnodes=1 \
    --nproc_per_node=8 \
    -m verl.trainer.fsdp_sft_trainer \
    model.fsdp_config.fsdp_size=4 \
    data.micro_batch_size_per_gpu=8 \
    trainer.total_epochs=1

Multi-Node Training (Production)

#!/bin/bash
# Production training on 4 nodes
 
# On master node (node1)
torchrun \
    --nnodes=4 \
    --nproc_per_node=8 \
    --node_rank=0 \
    --master_addr=10.0.0.1 \
    --master_port=29500 \
    -m verl.trainer.fsdp_sft_trainer \
    model.fsdp_config.fsdp_size=-1 \
    data.micro_batch_size_per_gpu=4 \
    trainer.total_epochs=3
 
# On worker nodes (node2, node3, node4)
# Same command with --node_rank=1, 2, 3

13. Debugging and Best Practices

13.1 Common Issues and Solutions

IssueSymptomsRoot CauseSolution
OOM on small batchCUDA OOM with batch_size=1Activation memoryEnable gradient_checkpointing
Slow trainingLow GPU utilizationNetwork bottleneckUse HYBRID_SHARD, reduce fsdp_size
Uneven memorySome GPUs OOM, others fineImbalanced shardingAdjust wrap_policy.min_num_params
Training hangsNo progress, timeoutNCCL communicationCheck network, increase NCCL_TIMEOUT
Checkpoint errorsCan’t save/loadFSDP state dictUse proper FSDP checkpoint API
Loss spikesSudden loss increaseGradient overflowReduce learning rate, clip gradients

13.2 Debugging Tools

Memory Profiling

# Add to training script
from verl.utils.profiler import log_gpu_memory_usage
 
# Log at key points
log_gpu_memory_usage("Start of training")
log_gpu_memory_usage("After model init")
log_gpu_memory_usage("After forward pass")
log_gpu_memory_usage("After backward pass")
 
# Detailed memory breakdown
def print_memory_stats():
    allocated = torch.cuda.memory_allocated() / 1e9
    reserved = torch.cuda.memory_reserved() / 1e9
    print(f"GPU {dist.get_rank()}: Allocated={allocated:.2f}GB, Reserved={reserved:.2f}GB")

Communication Profiling

# Enable NCCL debug
os.environ['NCCL_DEBUG'] = 'INFO'
os.environ['NCCL_DEBUG_SUBSYS'] = 'ALL'
 
# PyTorch profiler
from torch.profiler import profile, ProfilerActivity
 
with profile(
    activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA],
    record_shapes=True,
    profile_memory=True,
    with_stack=True
) as prof:
    # Training step
    loss = model(batch)
    loss.backward()
 
print(prof.key_averages().table(sort_by="cuda_time_total"))

13.3 Best Practices

1. Start Simple, Optimize Gradually

# Phase 1: Get it working
config = {
    'fsdp_size': -1,  # Full shard
    'dtype': 'fp32',
    'gradient_checkpointing': False
}
 
# Phase 2: Optimize memory
config['dtype'] = 'bfloat16'
config['gradient_checkpointing'] = True
 
# Phase 3: Optimize speed
config['fsdp_size'] = 8  # Hybrid shard
config['use_torch_compile'] = True

2. Monitor Key Metrics

# Training loop with monitoring
class MetricsTracker:
    def __init__(self):
        self.metrics = defaultdict(list)
    
    def log(self, **kwargs):
        for k, v in kwargs.items():
            self.metrics[k].append(v)
    
    def report(self):
        for k, values in self.metrics.items():
            avg = sum(values) / len(values)
            print(f"{k}: {avg:.4f}")
 
tracker = MetricsTracker()
 
for batch in dataloader:
    start_time = time.time()
    
    # Forward
    loss = model(batch)
    
    # Backward
    loss.backward()
    
    # Metrics
    tracker.log(
        loss=loss.item(),
        gpu_memory_gb=torch.cuda.memory_allocated() / 1e9,
        step_time=time.time() - start_time,
        learning_rate=optimizer.param_groups[0]['lr']
    )

3. Checkpoint Regularly

def save_checkpoint_fsdp(model, optimizer, epoch, path):
    """Save FSDP checkpoint properly"""
    
    # Set up save policy
    save_policy = FullStateDictConfig(
        offload_to_cpu=True,
        rank0_only=True
    )
    
    # Get state dict
    with FSDP.state_dict_type(
        model, 
        StateDictType.FULL_STATE_DICT,
        save_policy
    ):
        state_dict = model.state_dict()
        
    # Save on rank 0
    if dist.get_rank() == 0:
        checkpoint = {
            'epoch': epoch,
            'model_state_dict': state_dict,
            'optimizer_state_dict': optimizer.state_dict(),
            'rng_state': torch.get_rng_state(),
            'cuda_rng_state': torch.cuda.get_rng_state()
        }
        torch.save(checkpoint, path)
    
    dist.barrier()  # Synchronize

13.4 Performance Optimization Checklist

  • Memory Optimization

    • Use mixed precision (bf16/fp16)
    • Enable gradient checkpointing for large models
    • Tune micro_batch_size for optimal memory usage
    • Consider LoRA for very large models
    • Enable CPU offloading if needed
  • Communication Optimization

    • Choose appropriate fsdp_size for network speed
    • Enable forward_prefetch with fast network
    • Use gradient accumulation to reduce communication
    • Optimize NCCL parameters for your network
  • Compute Optimization

    • Enable torch.compile for PyTorch 2.0+
    • Use fused kernels (Liger, Flash Attention)
    • Optimize data loading (multiple workers, prefetching)
    • Profile and identify bottlenecks
  • Stability

    • Implement gradient clipping
    • Use learning rate warmup
    • Monitor loss and gradient norms
    • Save checkpoints frequently
    • Test recovery from checkpoints

Conclusion

This comprehensive guide provides a mathematically rigorous treatment of Fully Sharded Data Parallel (FSDP) training, from fundamental theory to practical implementation.

Key Mathematical Results

  1. Memory Reduction Theorem: FSDP achieves memory reduction factor of for model states, enabling training of models times larger than traditional data parallelism.

  2. Communication Complexity: Total communication volume per iteration is bytes, approaching as .

  3. Optimal Sharding: The optimal sharding factor balances memory constraints, communication overhead, and parallelization benefits:

  4. Row-wise vs Column-wise Decomposition: FSDP’s row-wise decomposition minimizes activation memory while maintaining efficient communication patterns aligned with data parallelism.

Practical Implementation Insights

  1. For 32B Model on 32 GPUs:

    • FULL_SHARD (): 12 GB/GPU model memory, 87.5% memory reduction, highest communication
    • HYBRID_SHARD (): 48 GB/GPU model memory, balanced performance, 4 model replicas
    • With Sequence Parallelism: Enables 16K+ context lengths by partitioning sequence dimension
    • With LoRA: Reduces communication by 90%+ while maintaining effectiveness
  2. Communication Efficiency: Achieved when , requiring:

    • High-bandwidth interconnect (InfiniBand preferred)
    • Appropriate sharding factor for model size
    • Optimized collective operations (ring all-gather/reduce-scatter)
  3. Multi-Node Scaling: Performance depends on network hierarchy:

    • Intra-node (NVLink): 10-50 GB/s → Minimal overhead
    • Inter-node (InfiniBand): 25-100 GB/s → Moderate overhead
    • Inter-node (Ethernet): 1-10 GB/s → Significant overhead

Theoretical Contributions

This guide provides:

  • Rigorous mathematical derivations of memory and communication requirements
  • Detailed analysis of row-wise vs column-wise parameter decomposition
  • Formal proofs of memory reduction and communication complexity
  • Comprehensive diagrams illustrating FSDP operations across training phases

Future Directions

  1. Hybrid Parallelism: Combining FSDP with pipeline and tensor parallelism
  2. Asynchronous Communication: Overlapping computation with communication
  3. Adaptive Sharding: Dynamic adjustment of sharding factor during training
  4. Heterogeneous Hardware: Optimizing for mixed GPU/CPU/accelerator systems

The mathematical framework presented here provides the foundation for understanding and optimizing distributed training at scale, enabling researchers and practitioners to train increasingly large models efficiently.


Appendix A: Ulysses Sequence Parallelism - Theory and Integration with FSDP

A.1 Introduction to Sequence Parallelism

A.1.1 Motivation

While FSDP addresses memory limitations by sharding model parameters, it does not address the memory required for activations, which scale with sequence length. For transformer models processing long sequences, activation memory becomes the bottleneck:

where:

  • = batch size
  • = sequence length
  • = hidden dimension

For a sequence length of 16K tokens with hidden dimension 4096:

  • Activation per layer ≈ bytes (BF16)
  • For 32 layers: Total activation memory ≈ GB per sample!

Ulysses Sequence Parallelism addresses this by partitioning the sequence dimension across devices.

A.1.2 Key Insight

Named after the hero’s distributed journey in Homer’s Odyssey, Ulysses parallelizes the sequence dimension while maintaining model correctness through careful attention computation redistribution.

A.2 Mathematical Foundation of Ulysses

A.2.1 Problem Formulation

Consider the self-attention computation in transformers:

where:

  • (batch × sequence × heads × head_dim)
  • = batch size
  • = sequence length
  • = number of attention heads
  • = dimension per head

A.2.2 Sequence Partitioning

With Ulysses sequence parallel degree , we partition the sequence dimension:

where each partition .

A.2.3 The Challenge: Attention Requires Full Sequence

The attention matrix requires interaction between all query and key positions:

Each device needs access to all keys to compute its attention scores!

A.3 Ulysses Algorithm: Ring Attention with All-to-All

A.3.1 Core Innovation: Sequence-Head Exchange

Ulysses redistributes the computation by exchanging sequence and head dimensions through all-to-all communication:

Step 1: Initial State

  • Device holds:

Step 2: All-to-All Exchange (Gather Sequence, Scatter Heads)

  • Transform:
  • Device now holds full sequence but subset of heads

Step 3: Compute Attention with Head Subset

  • Each device computes attention for its heads over full sequence

Step 4: All-to-All Exchange (Gather Heads, Scatter Sequence)

  • Transform:
  • Return to original partitioning

A.3.2 Mathematical Formulation

Let be the all-to-all redistribution operator.

Forward Pass:

1. Local compute: Q_local, K_local, V_local from X^(p)
2. Redistribute: Q' = π(Q_local), K' = π(K_local), V' = π(V_local)  
3. Attention: A' = softmax(Q'K'^T/√d_k)V'  [Full sequence, partial heads]
4. Redistribute: A = π^(-1)(A')  [Back to sequence partition]

Backward Pass:
The gradient flow follows the reverse path with corresponding all-to-all operations.

A.4 Complexity Analysis

A.4.1 Memory Complexity

Without Ulysses:

With Ulysses (P-way parallelism):

Memory Reduction Factor:

A.4.2 Communication Complexity

Per Attention Layer:

  • Two all-to-all operations (forward)
  • Two all-to-all operations (backward)
  • Volume per all-to-all: bytes

Total Communication per Layer:

Communication Time:

A.4.3 Computation Redistribution

The computation remains the same but is redistributed:

  • Each device computes of sequence positions for all heads (standard)
  • Becomes: all sequence positions for of heads (Ulysses)

FLOPs per device remain constant:

A.5 Integration with FSDP: 2D Parallelism

A.5.1 Device Mesh Configuration

Combining FSDP and Ulysses creates a 2D parallelism mesh:

Device Mesh (World Size = N = F × P):
┌────────────────────────────────────────────┐
│                                            │
│   ┌─────┬─────┬─────┬─────┐               │
│ F │GPU 0│GPU 1│GPU 2│GPU 3│ ← Sequence    │
│ S │     │     │     │     │   Parallel    │
│ D ├─────┼─────┼─────┼─────┤   Group (P=4) │
│ P │GPU 4│GPU 5│GPU 6│GPU 7│               │
│   ├─────┼─────┼─────┼─────┤               │
│ G │GPU 8│GPU 9│GPU10│GPU11│               │
│ r ├─────┼─────┼─────┼─────┤               │
│ p │GPU12│GPU13│GPU14│GPU15│               │
│   └─────┴─────┴─────┴─────┘               │
│     ↑                                      │
│   FSDP Group (F=4)                        │
└────────────────────────────────────────────┘

Configuration:

mesh = init_device_mesh(
    "cuda",
    mesh_shape=(F, P),  # (FSDP_size, Ulysses_size)
    mesh_dim_names=["fsdp", "sp"]
)

A.5.2 Combined Memory Savings

With both FSDP (factor ) and Ulysses (factor ):

Model Memory:

Activation Memory:

Total Memory per Device:

A.6 Implementation Details in VERL

A.6.1 FSDPUlyssesShardingManager

The sharding manager coordinates data flow between FSDP and Ulysses dimensions:

class FSDPUlyssesShardingManager:
    def preprocess_data(self, data: DataProto):
        """All-gather across SP dimension before FSDP processing"""
        if self.device_mesh is not None:
            sp_group = self.device_mesh["sp"].get_group()
            all_gather_data_proto(data, process_group=sp_group)
        return data
    
    def postprocess_data(self, data: DataProto):
        """Re-shard data after FSDP processing"""
        if self.device_mesh is not None:
            sp_size = self.device_mesh["sp"].size()
            sp_rank = self.device_mesh["sp"].get_local_rank()
            data = data.chunk(chunks=sp_size)[sp_rank]
        return data

A.6.2 Attention Modification

The attention computation is modified to handle all-to-all:

def ulysses_attention_forward(Q, K, V, sp_group):
    # Step 1: All-to-all to gather sequence, scatter heads
    Q = gather_seq_scatter_heads(Q, seq_dim=1, head_dim=2, group=sp_group)
    K = gather_seq_scatter_heads(K, seq_dim=1, head_dim=2, group=sp_group)
    V = gather_seq_scatter_heads(V, seq_dim=1, head_dim=2, group=sp_group)
    
    # Step 2: Compute attention with full sequence, partial heads
    attn_output = standard_attention(Q, K, V)  # [B, L, H/P]
    
    # Step 3: All-to-all to gather heads, scatter sequence  
    output = gather_heads_scatter_seq(attn_output, head_dim=2, seq_dim=1, group=sp_group)
    
    return output  # [B, L/P, H]

A.7 Performance Optimization Strategies

A.7.1 Overlapping Communication and Computation

Timeline with Overlap:
═══════════════════════════════════════════════════════════════

Layer i:   |--All2All--|--Attention--|--All2All--|
Layer i+1:             |--All2All--|--Attention--|--All2All--|
           
Communication ████████         ████████        ████████
Computation          ██████████       ██████████

A.7.2 Optimal Configuration Selection

Decision Tree for Parallelism Strategy:

                Model Size > GPU Memory?
                        /            \
                      Yes             No
                       |              |
                    Use FSDP      Use DP Only
                       |
              Sequence > 8K?
                  /        \
                Yes         No
                 |          |
          FSDP+Ulysses   FSDP Only
                 |
        Configure P based on:
        - Network bandwidth
        - Sequence length
        - Attention head count

A.7.3 Configuration Guidelines

Sequence LengthModel SizeRecommended Config
≤ 2K≤ 7BFSDP only (P=1)
2K-8K7B-30BFSDP + Ulysses (P=2)
8K-16K30B-70BFSDP + Ulysses (P=4)
16K-32K70B+FSDP + Ulysses (P=8)

A.8 Practical Example: 70B Model with 32K Context

Configuration

  • Model: 70B parameters
  • Sequence: 32K tokens
  • Cluster: 32 GPUs (4 nodes × 8 GPUs)
  • Hidden: 8192, Heads: 64

Analysis

Memory Requirements:

# Model memory (with Adam)
model_memory = 70e9 * 2  # params (BF16)
grad_memory = 70e9 * 2   # gradients (BF16)  
opt_memory = 70e9 * 8    # Adam states (FP32)
total_model = 840 GB
 
# Activation memory (per sample)
act_per_layer = 32768 * 8192 * 2  # BF16
total_act = act_per_layer * 80  # 80 layers
total_act = 42.9 GB per sample
 
# With FSDP (F=8) + Ulysses (P=4)
model_per_gpu = 840 / 8 = 105 GB
act_per_gpu = 42.9 / 4 = 10.7 GB
total_per_gpu = 115.7 GB  # Fits in 8×A100-80GB!

Communication Analysis:

# FSDP communication
fsdp_volume = 4 * 70e9 * 2 * (7/8) = 490 GB per iteration
 
# Ulysses communication (per layer)
ulysses_per_layer = 4 * 32768 * 64 * 128 * 2 = 2.1 GB
ulysses_total = 2.1 * 80 = 168 GB per iteration
 
# Total communication
total_comm = 490 + 168 = 658 GB per iteration
 
# Time estimate (100 GB/s InfiniBand)
comm_time = 658 / 100 = 6.58 seconds

A.9 Diagrams: Ulysses Operation Flow

A.9.1 Sequence Partitioning and All-to-All

Initial State (4 GPUs, Sequence Parallelism):
═══════════════════════════════════════════════════════════════

Input Sequence: [Token₁ Token₂ ... Token₁₆]

GPU Distribution:
GPU 0: [Token₁ Token₂ Token₃ Token₄]     [Head₁...Head₁₆]
GPU 1: [Token₅ Token₆ Token₇ Token₈]     [Head₁...Head₁₆]
GPU 2: [Token₉ Token₁₀ Token₁₁ Token₁₂]  [Head₁...Head₁₆]
GPU 3: [Token₁₃ Token₁₄ Token₁₅ Token₁₆] [Head₁...Head₁₆]

After All-to-All (Sequence ↔ Head Exchange):
═══════════════════════════════════════════════════════════════

GPU 0: [Token₁...Token₁₆] [Head₁ Head₂ Head₃ Head₄]
GPU 1: [Token₁...Token₁₆] [Head₅ Head₆ Head₇ Head₈]
GPU 2: [Token₁...Token₁₆] [Head₉ Head₁₀ Head₁₁ Head₁₂]
GPU 3: [Token₁...Token₁₆] [Head₁₃ Head₁₄ Head₁₅ Head₁₆]

Attention Computation:
Each GPU computes full attention for its head subset

A.9.2 Combined FSDP + Ulysses Flow

2D Parallel Training Flow (FSDP=4, Ulysses=2):
═══════════════════════════════════════════════════════════════

Step 1: Data Distribution
┌─────────────────────────────────────┐
│ Batch Data: [Sample₁...Sample₈]     │
└─────────────────────────────────────┘
                ↓
    ┌───────────────┬───────────────┐
    │   FSDP-Grp-0  │   FSDP-Grp-1  │
    │  ┌─────┬─────┐│  ┌─────┬─────┐│
    │  │GPU0 │GPU1 ││  │GPU2 │GPU3 ││ SP-Grp-0
    │  │S₁,₂ │S₁,₂ ││  │S₃,₄ │S₃,₄ ││ (Seq/2)
    │  ├─────┼─────┤│  ├─────┼─────┤│
    │  │GPU4 │GPU5 ││  │GPU6 │GPU7 ││ SP-Grp-1
    │  │S₅,₆ │S₅,₆ ││  │S₇,₈ │S₇,₈ ││ (Seq/2)
    │  └─────┴─────┘│  └─────┴─────┘│
    │   Model/4      │   Model/4      │
    └───────────────┴───────────────┘

Step 2: Forward Pass
1. FSDP All-Gather (within columns)
2. Ulysses All-to-All (within rows)
3. Attention Computation
4. Ulysses All-to-All (reverse)
5. FSDP Release

Step 3: Backward Pass
1. FSDP All-Gather
2. Ulysses All-to-All
3. Gradient Computation
4. Ulysses All-to-All (reverse)
5. FSDP Reduce-Scatter

A.10 Summary and Best Practices

Key Takeaways

  1. Ulysses Sequence Parallelism addresses activation memory bottleneck by partitioning sequence dimension
  2. All-to-All communication enables correct attention computation despite sequence partitioning
  3. Combines orthogonally with FSDP for 2D parallelism: FSDP handles model memory, Ulysses handles activation memory
  4. Communication overhead is manageable with high-bandwidth interconnects (InfiniBand)

Best Practices

  1. Use Ulysses when:

    • Sequence length > 8K tokens
    • Activation memory becomes bottleneck
    • Have sufficient interconnect bandwidth
  2. Configuration Rules:

    • Ensure num_heads % ulysses_size == 0
    • Set ulysses_size as power of 2 (2, 4, 8)
    • Balance FSDP and Ulysses sizes: world_size = fsdp_size × ulysses_size
  3. Performance Optimization:

    • Use --ulysses_sequence_parallel_size flag in training scripts
    • Enable gradient checkpointing with Ulysses for maximum memory savings
    • Profile all-to-all operations to identify bottlenecks
  4. Debugging:

    • Verify sequence padding/unpadding correctness
    • Check attention scores match non-parallel implementation
    • Monitor all-to-all communication patterns

The combination of FSDP and Ulysses enables training of models with both large parameter counts and long context lengths, pushing the boundaries of what’s possible in large-scale transformer training.