MODULE 33: FULLY SHARDED DATA PARALLEL (FSDP) & ZeRO REDUNDANCY

Eliminate per-GPU model state redundancy when training multi-billion parameter LLMs and Foundation Models in PyTorch. Master ZeRO Stages 1, 2, and 3, FSDP ShardingStrategies (FULL_SHARD, SHARD_GRAD_OP, HYBRID_SHARD), Transformer auto-wrap policies, MixedPrecision policies, Activation Checkpointing, CPU Offloading, FSDP.summon_full_params, and Distributed State Dict saving.

🧩 Real-World Context: Breaking the Single-GPU Memory Wall for 7B–70B+ Parameter Models

Standard DistributedDataParallel (DDP) replicates the entire model parameters, gradients, and FP32 Adam optimizer states across every GPU. For a 7-Billion parameter LLM in mixed precision (2 bytes/param FP16 weights + 2 bytes/param FP16 gradients + 12 bytes/param FP32 Adam master weights, momentum, and variance = 16 bytes/param), DDP consumes 112 GB per GPU before even allocating activations—immediately crashing 80 GB H100/A100 GPUs with CUDA Out Of Memory (OOM).

PyTorch FSDP (Fully Sharded Data Parallel) implements DeepSpeed's ZeRO (Zero Redundancy Optimizer) Stages 1, 2, and 3 natively in PyTorch: sharding optimizer states, gradients, and model weights across all N ranks, gathering full layer weights on-the-fly via AllGather right before each layer's forward/backward computation, and immediately freeing unsharded memory afterward.

1. Memory Footprint Math: DDP Replication vs. ZeRO-1, ZeRO-2 & FSDP FULL_SHARD (ZeRO-3)
Computing exact per-GPU static model-state VRAM for a 7B parameter Transformer across 8 GPUs (N = 8) under mixed-precision AdamW (2Ψ parameters + 2Ψ gradients + 12Ψ FP32 optimizer states = 16Ψ total bytes): comparing DDP (112 GB/GPU) against ZeRO-1 (52 GB), ZeRO-2 (38 GB), and FSDP ZeRO-3 (14 GB/GPU — an 8× memory reduction).
Python (zero_memory_footprint_calculator.py)
def compute_static_vram_gb(num_params_billions: float, num_gpus: int) -> dict[str, float]:
    psi_gb = num_params_billions  # 1B params * 1 byte = 1 GB (10^9 bytes)
    p_bytes = 2.0 * psi_gb        # FP16 / BF16 Parameters (2 bytes/param)
    g_bytes = 2.0 * psi_gb        # FP16 / BF16 Gradients  (2 bytes/param)
    o_bytes = 12.0 * psi_gb       # FP32 Master + Momentum + Variance (12 bytes/param)

    return {
        "DDP (Replicated)": round(p_bytes + g_bytes + o_bytes, 2),
        "ZeRO-1 (Shard Optim)": round(p_bytes + g_bytes + (o_bytes / num_gpus), 2),
        "ZeRO-2 (SHARD_GRAD_OP)": round(p_bytes + ((g_bytes + o_bytes) / num_gpus), 2),
        "ZeRO-3 (FSDP FULL_SHARD)": round((p_bytes + g_bytes + o_bytes) / num_gpus, 2),
    }

vram_table = compute_static_vram_gb(num_params_billions=7.0, num_gpus=8)
for strategy, gb_per_gpu in vram_table.items():
    status = "OOM on 80GB A100!" if gb_per_gpu > 80.0 else "Fits 80GB A100"
    print(f"{strategy:<26} -> {gb_per_gpu:>6.2f} GB / GPU | {status}")
Output:
DDP (Replicated)           -> 112.00 GB / GPU | OOM on 80GB A100!
ZeRO-1 (Shard Optim)       ->  52.00 GB / GPU | Fits 80GB A100
ZeRO-2 (SHARD_GRAD_OP)     ->  38.00 GB / GPU | Fits 80GB A100
ZeRO-3 (FSDP FULL_SHARD)   ->  14.00 GB / GPU | Fits 80GB A100
2. FSDP FULL_SHARD (ZeRO-3) AllGather & ReduceScatter Execution Lifecycle
Tracing how FullyShardedDataParallel(model, sharding_strategy=ShardingStrategy.FULL_SHARD) executes a Transformer layer across 4 GPUs: each rank holds 1/4 of the weights at rest, invokes AllGather to reconstruct full weights for forward/backward matmuls, immediately frees unsharded weights, and runs ReduceScatter to average and partition gradients back to 1/4 shards.
Python (fsdp_full_shard_lifecycle.py)
import torch
import torch.nn as nn
from torch.distributed.fsdp import FullyShardedDataParallel as FSDP, ShardingStrategy

# Inside torchrun worker (e.g., 4 GPUs):
# model = TransformerDecoder(...).to(local_rank)
# fsdp_model = FSDP(
#     model,
#     sharding_strategy=ShardingStrategy.FULL_SHARD,  # ZeRO-3: shards Params + Grads + Optim
#     device_id=torch.cuda.current_device(),
#     limit_all_gathers=True,  # Prevents CPU thread from queueing excessive AllGathers (avoids OOM)
# )

# Simulate 1,024-element layer weight sharded across 4 FSDP ranks
full_params = 1024
world_size = 4
at_rest_shard = full_params // world_size
peak_unsharded = full_params

print(f"At-Rest Parameter Shard per GPU : {at_rest_shard} params (25% memory)")
print(f"Transient Forward AllGather Peak: {peak_unsharded} params -> Freed immediately post-layer")
print(f"Backward Gradient Sync          : ReduceScatter -> {at_rest_shard} gradient shard per GPU")
Output:
At-Rest Parameter Shard per GPU : 256 params (25% memory)
Transient Forward AllGather Peak: 1024 params -> Freed immediately post-layer
Backward Gradient Sync          : ReduceScatter -> 256 gradient shard per GPU
3. Transformer Layer Auto-Wrap Policy (transformer_auto_wrap_policy)
Wrapping an entire 32-layer LLM inside a single top-level FSDP unit would force AllGather of all 7B parameters simultaneously—defeating memory savings. Using functools.partial(transformer_auto_wrap_policy, transformer_layer_cls={TransformerBlock}) wraps each individual decoder block into its own FSDP unit so only one layer is unsharded at any instant.
Python (fsdp_transformer_auto_wrap.py)
import functools
import torch.nn as nn
from torch.distributed.fsdp.wrap import transformer_auto_wrap_policy

class LlamaDecoderBlock(nn.Module):
    def __init__(self, d_model: int = 4096):
        super().__init__()
        self.attn = nn.Linear(d_model, d_model, bias=False)
        self.mlp = nn.Linear(d_model, d_model * 4, bias=False)

    def forward(self, x):
        return self.mlp(self.attn(x))

# Auto-wrap policy wraps every LlamaDecoderBlock as an independent FSDP communication unit
auto_wrap_policy = functools.partial(
    transformer_auto_wrap_policy,
    transformer_layer_cls={LlamaDecoderBlock},
)

num_layers = 32
params_per_block_m = (4096 * 4096 + 4096 * 16384) / 1e6
print(f"Auto-Wrap Unit Class      : {LlamaDecoderBlock.__name__} ({num_layers} independent FSDP units)")
print(f"Peak Transient Unsharded  : 1 Block ({params_per_block_m:.2f}M params) vs. All 32 Blocks ({params_per_block_m * num_layers:.2f}M)")
Output:
Auto-Wrap Unit Class      : LlamaDecoderBlock (32 independent FSDP units)
Peak Transient Unsharded  : 1 Block (83.89M params) vs. All 32 Blocks (2684.35M)
4. Size-Based Auto-Wrap Policy (size_based_auto_wrap_policy) for Multimodal / Vision Backbones
For heterogeneous Vision-Language Models (VLMs) or ConvNeXt + Diffusion U-Nets that lack a single uniform Transformer block class, configuring functools.partial(size_based_auto_wrap_policy, min_num_params=20_000_000) automatically shards any submodule exceeding 20M parameters while grouping smaller layers cleanly.
Python (fsdp_size_based_auto_wrap.py)
import functools
import torch.nn as nn
from torch.distributed.fsdp.wrap import size_based_auto_wrap_policy

# Wrap any submodule containing >= 20,000,000 parameters into its own FSDP sharding unit
size_wrap_policy = functools.partial(
    size_based_auto_wrap_policy,
    min_num_params=20_000_000,
)

# Inspect candidate VLM modules against the 20M threshold
vlm_blocks = {
    "patch_embed (Conv2d)": 1_200_000,
    "vision_stage_3 (ViT-H)": 48_500_000,
    "cross_attn_projector": 26_200_000,
    "lm_head (Vocab 128K)": 524_288_000,
}

for name, num_p in vlm_blocks.items():
    wrapped = num_p >= 20_000_000
    print(f"{name:<24} | Params: {num_p:>11,} | FSDP Auto-Wrapped: {wrapped}")
Output:
patch_embed (Conv2d)     | Params:   1,200,000 | FSDP Auto-Wrapped: False
vision_stage_3 (ViT-H)   | Params:  48,500,000 | FSDP Auto-Wrapped: True
cross_attn_projector     | Params:  26,200,000 | FSDP Auto-Wrapped: True
lm_head (Vocab 128K)     | Params: 524,288,000 | FSDP Auto-Wrapped: True
5. FSDP MixedPrecision Policy (BF16 Compute, BF16 Reduce, FP32 Master Shards)
Configuring MixedPrecision(param_dtype=torch.bfloat16, reduce_dtype=torch.bfloat16, buffer_dtype=torch.bfloat16) in FSDP: weights are cast to BF16 during forward/backward AllGather and ReduceScatter to halve NVLink/InfiniBand communication volume, while FSDP retains full FP32 master parameter shards for numerically stable AdamW updates.
Python (fsdp_mixed_precision_policy.py)
import torch
from torch.distributed.fsdp import MixedPrecision

# Production BF16 policy for Ampere (A100) and Hopper (H100) GPU clusters
bf16_policy = MixedPrecision(
    param_dtype=torch.bfloat16,   # Casts sharded weights to BF16 before AllGather
    reduce_dtype=torch.bfloat16,  # Performs ReduceScatter gradient averaging in BF16 (2x bandwidth!)
    buffer_dtype=torch.bfloat16,  # Casts RoPE / Causal Mask buffers to BF16
)

# High-precision gradient reduction variant for sensitive RLHF / DPO fine-tuning
bf16_fp32_reduce_policy = MixedPrecision(
    param_dtype=torch.bfloat16,
    reduce_dtype=torch.float32,   # Accumulates cross-GPU gradients in FP32 to prevent underflow
    buffer_dtype=torch.bfloat16,
)

print("Standard LLM Pretrain Policy :", bf16_policy)
print("RLHF / DPO Precision Policy  :", bf16_fp32_reduce_policy)
Output:
Standard LLM Pretrain Policy : MixedPrecision(param_dtype=torch.bfloat16, reduce_dtype=torch.bfloat16, buffer_dtype=torch.bfloat16, cast_forward_inputs=True, cast_root_forward_inputs=True)
RLHF / DPO Precision Policy  : MixedPrecision(param_dtype=torch.bfloat16, reduce_dtype=torch.float32, buffer_dtype=torch.bfloat16, cast_forward_inputs=True, cast_root_forward_inputs=True)
6. Non-Reentrant Activation Checkpointing + FSDP for 32K Long-Context Training
Even after ZeRO-3 eliminates weight redundancy, 32K-token self-attention activation tensors can consume 60+ GB per GPU. Applying apply_activation_checkpointing with CheckpointImpl.NO_REENTRANT discards intermediate activations during forward and recomputes them during backward—cutting activation VRAM by ~70%.
Python (fsdp_activation_checkpointing.py)
import functools
import torch.nn as nn
from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import (
    checkpoint_wrapper,
    CheckpointImpl,
    apply_activation_checkpointing,
)

class DecoderLayer(nn.Module):
    def __init__(self):
        super().__init__()
        self.proj = nn.Linear(1024, 1024)

    def forward(self, x):
        return self.proj(x)

# Non-reentrant wrapper is mandatory for clean compatibility with FSDP backward hooks
non_reentrant_wrapper = functools.partial(
    checkpoint_wrapper,
    checkpoint_impl=CheckpointImpl.NO_REENTRANT,
)

model = nn.Sequential(*[DecoderLayer() for _ in range(24)])
apply_activation_checkpointing(
    model,
    checkpoint_wrapper_fn=non_reentrant_wrapper,
    check_fn=lambda submodule: isinstance(submodule, DecoderLayer),
)

wrapped_count = sum(1 for m in model.modules() if "CheckpointWrapper" in type(m).__name__)
print(f"Checkpointed Decoder Layers: {wrapped_count}/24 | Activation Memory Saved: ~70% (+25% compute trade-off)")
Output:
Checkpointed Decoder Layers: 24/24 | Activation Memory Saved: ~70% (+25% compute trade-off)
7. HYBRID_SHARD (ZeRO-3 Intra-Node NVLink + DDP Inter-Node InfiniBand)
When scaling a 13B LLM across 8 multi-GPU nodes (64 GPUs total), running FULL_SHARD across all 64 GPUs pushes heavy AllGather/ReduceScatter traffic over slower inter-node InfiniBand links. ShardingStrategy.HYBRID_SHARD shards parameters across the 8 fast NVLink GPUs inside each node while replicating across nodes via standard DDP All-Reduce.
Python (fsdp_hybrid_shard_topology.py)
from torch.distributed.fsdp import ShardingStrategy

strategies = {
    "FULL_SHARD (ZeRO-3)": "Shards Params+Grads+Optim across ALL 64 GPUs (Max memory savings, inter-node AllGather)",
    "SHARD_GRAD_OP (ZeRO-2)": "Shards Grads+Optim across 64 GPUs; keeps Params unsharded during forward",
    "HYBRID_SHARD (2D Mesh)": "ZeRO-3 inside 8-GPU NVLink Node + DDP All-Reduce across 8 InfiniBand Nodes",
}

for name, desc in strategies.items():
    print(f"{name:<24} -> {desc}")
Output:
FULL_SHARD (ZeRO-3)      -> Shards Params+Grads+Optim across ALL 64 GPUs (Max memory savings, inter-node AllGather)
SHARD_GRAD_OP (ZeRO-2)   -> Shards Grads+Optim across 64 GPUs; keeps Params unsharded during forward
HYBRID_SHARD (2D Mesh)   -> ZeRO-3 inside 8-GPU NVLink Node + DDP All-Reduce across 8 InfiniBand Nodes
8. Meta-Device Initialization & sync_module_states=True for 70B Model Loading
Instantiating a 70B parameter model simultaneously across 8 processes on a single node requires 8 × 140 GB = 1.12 TB of host CPU RAM—crashing the server before FSDP even starts. Initializing the architecture on torch.device("meta") (0 bytes RAM), loading weights onto Rank 0 only, and passing sync_module_states=True broadcasts shards cleanly during FSDP wrapping.
Python (fsdp_meta_device_init.py)
import torch
import torch.nn as nn

# Zero-memory skeleton instantiation on "meta" device (0 bytes allocated!)
with torch.device("meta"):
    huge_model = nn.Sequential(
        nn.Linear(8192, 32768, bias=False),
        nn.SiLU(),
        nn.Linear(32768, 8192, bias=False),
    )

total_params = sum(p.numel() for p in huge_model.parameters())
meta_bytes = sum(p.numel() * p.element_size() for p in huge_model.parameters() if p.device.type != "meta")

# Production FSDP call:
# fsdp_model = FSDP(huge_model, sync_module_states=True, param_init_fn=lambda m: m.to_empty(device=torch.cuda.current_device()))
print(f"Model Parameter Count : {total_params:,} ({total_params / 1e6:.2f}M)")
print(f"Meta Device Storage   : {huge_model[0].weight.device} | Physical Bytes Allocated: {meta_bytes} bytes")
Output:
Model Parameter Count : 536,870,912 (536.87M)
Meta Device Storage   : meta | Physical Bytes Allocated: 0 bytes
9. Gradient Clipping (fsdp_model.clip_grad_norm_) & Sharded Optimizer State
Standard torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) produces incorrect global L2 norms under FSDP because each GPU only owns 1/N of the sharded gradients. Calling FSDP's dedicated method fsdp_model.clip_grad_norm_(max_norm=1.0) performs a distributed norm reduction across all sharded ranks before rescaling gradients identically.
Python (fsdp_sharded_grad_clipping.py)
import torch

# Simulate 4 FSDP GPU shards holding disjoint subsets of layer gradients
shard_grads = [
    torch.tensor([0.6, 0.8]),   # Rank 0 shard L2^2 = 1.00
    torch.tensor([1.0, 0.0]),   # Rank 1 shard L2^2 = 1.00
    torch.tensor([0.0, 1.0]),   # Rank 2 shard L2^2 = 1.00
    torch.tensor([0.6, 0.8]),   # Rank 3 shard L2^2 = 1.00
]

# fsdp_model.clip_grad_norm_(max_norm=1.0) computes true global L2 norm across all shards
global_norm = torch.sqrt(sum((g.norm() ** 2) for g in shard_grads))
max_norm = 1.0
clip_coef = min(1.0, max_norm / (global_norm.item() + 1e-6))
clipped_rank0 = shard_grads[0] * clip_coef

print(f"Naive Rank-0 Local Norm : {shard_grads[0].norm().item():.4f} (Wrong! Misses 75% of model)")
print(f"FSDP Global L2 Norm     : {global_norm.item():.4f} | Clip Scale: {clip_coef:.4f} | Clipped R0: {clipped_rank0.tolist()}")
Output:
Naive Rank-0 Local Norm : 1.0000 (Wrong! Misses 75% of model)
FSDP Global L2 Norm     : 2.0000 | Clip Scale: 0.5000 | Clipped R0: [0.30000001192092896, 0.4000000059604645]
10. CPU Offloading & Distributed Checkpointing (SHARDED_STATE_DICT vs. FULL_STATE_DICT)
Handling extreme model sizes on workstation GPUs with CPUOffload(offload_params=True) (pinning sharded weights and Adam states in host DDR5 RAM), and saving production checkpoints safely via FSDP.state_dict_type(model, StateDictType.SHARDED_STATE_DICT) so each GPU writes its local shard in parallel without Rank-0 host RAM OOM.
Python (fsdp_cpu_offload_and_checkpointing.py)
from torch.distributed.fsdp import (
    CPUOffload,
    StateDictType,
    FullStateDictConfig,
    ShardedStateDictConfig,
)

# 1. Offload sharded parameters & optimizer states to host CPU RAM when GPU VRAM is scarce
cpu_offload_cfg = CPUOffload(offload_params=True)

# 2. Export single consolidated state_dict on Rank 0 (for HuggingFace / vLLM inference export)
full_ckpt_cfg = FullStateDictConfig(offload_to_cpu=True, rank0_only=True)

# 3. Parallel distributed checkpointing (every rank saves its 1/N shard concurrently -> 8x faster!)
sharded_ckpt_cfg = ShardedStateDictConfig(offload_to_cpu=True)

print("CPU Offload Config      :", cpu_offload_cfg)
print("Inference Export Config :", full_ckpt_cfg)
print("Fast Parallel Ckpt Cfg  :", sharded_ckpt_cfg)
Output:
CPU Offload Config      : CPUOffload(offload_params=True)
Inference Export Config : FullStateDictConfig(offload_to_cpu=True, rank0_only=True)
Fast Parallel Ckpt Cfg  : ShardedStateDictConfig(offload_to_cpu=True, _use_dtensor=False)