ML & Infrastructure

Distributed LLM Training 2026: FSDP, YaFSDP, DeepSpeed & Zero-3

So sánh toàn diện các framework distributed training hàng đầu. Chiến lược sharding, memory optimization, communication patterns — tất cả những gì ML engineer cần biết để train LLM hiệu quả năm 2026.

06/07/2026 25 phút đọc Võ Đào Huy Hoàng

1. Bối Cảnh — Vấn Đề Đơn Giản Nhưng Khó 🎯

Bạn muốn train một LLM 7B/70B/405B trên multi-GPU hoặc multi-node. Model không fit vào VRAM của 1 GPU. Bạn cần chia nhỏ model, shard optimizer states, overlap communication với computation — và làm tất cả đó đúng, nhanh, ổn định.

Năm 2026, có 3 player chính thống trị distributed training:

  • FSDP (PyTorch Native) — Fully Sharded Data Parallel, built-in, mature, production-ready
  • YaFSDP — Yet Another FSDP từ Yandex, optimize communication overlap, bucket-based all-gather
  • DeepSpeed Zero-3 — Microsoft, Zero Redundancy Optimizer, hybrid 3D parallelism, offload to CPU/NVMe
💡 Key Insight: Không có "silver bullet". Lựa chọn phụ thuộc vào: model size, hardware topology (NVLink/NVSwitch vs Ethernet), team expertise, ecosystem integration (Hugging Face Trainer, Lightning, vLLM, Megatron-LM).
70B+ Params cần distributed
3-5x Memory reduction với Zero-3
~40% Speedup YaFSDP vs FSDP
8-1024 GPUs typical cluster

2. Phân Loại Distributed Training 🧭

Trước khi deep-dive vào từng framework, cần hiểu rõ 5 loại parallelism cơ bản — mọi framework đều kết hợp chúng theo cách khác nhau:

📊
Data Parallel (DP)
+
🔧
Tensor Parallel (TP)
+
📦
Pipeline Parallel (PP)
+
📝
Sequence/Context Parallel

2.1 Data Parallelism (DP) — Baseline 📊

Replicate model trên mọi GPU, split batch theo data dimension. Mỗi GPU tính forward/backward độc lập, all-reduce gradients sau backward.

  • Pros: Đơn giản, scaling gần linear với batch size nhỏ
  • Cons: Model + optimizer + gradients phải fit VRAM từng GPU → giới hạn model size
  • Variants: DDP (DistributedDataParallel) — PyTorch standard, bucket-based gradient sync

2.2 Tensor Parallelism (TP) — Intra-Layer Sharding 🔧

Split weight matrices theo row/column dimension. Mỗi GPU cầm 1 shard của weight, all-reduce/all-gather trong forward/backward.

  • Megatron-LM style: Column parallel (linear1) + Row parallel (linear2) trong MLP/Attention
  • Pros: Giảm memory per GPU tuyến tính với TP degree
  • Cons: Cần high-bandwidth interconnect (NVLink/NVSwitch), communication overhead mỗi layer
  • Typical TP degree: 2-8 (trong 1 node)

2.3 Pipeline Parallelism (PP) — Inter-Layer Sharding 📦

Split model theo layer dimension. GPU 1 cầm layers 1-10, GPU 2 cầm layers 11-20... Micro-batches flow qua pipeline.

  • Pros: Memory per GPU = model_layers / PP_degree, communication chỉ ở boundary layers
  • Cons: Pipeline bubbles (idle time), load imbalance nếu layers không đều
  • Schedules: GPipe (sync), 1F1B (async), ZeroBubble (hybrid)
  • Typical PP degree: 2-8 (cross-node)

2.4 Sequence Parallelism (SP) — Activations Sharding 📝

Split activations theo sequence dimension. Quan trọng cho long-context training (32k-1M tokens).

  • Ring Attention / Ring Attention v2: Split K/V theo sequence, ring-all-reduce attention
  • Ulysses / Megatron-CP: All-to-all communication cho attention heads
  • Pros: Cho phép context length > VRAM limit, linear scaling với sequence length

2.5 Context Parallelism (CP) — Long Context Specialist 📝

Variant của SP tối ưu cho attention. DeepSpeed-Ulysses, Megatron-CP, xFormers-ring.

  • CP degree thường = TP degree hoặc SP degree
  • Quan trọng cho LLM 128k-1M context (Llama-3.1, Nemotron-3, Qwen2.5)
⚠️ 3D Parallelism = DP × TP × PP: Real-world training kết hợp cả 3. Ví dụ: 70B model trên 128 GPUs → DP=16, TP=4, PP=2. Mỗi GPU cầm 1/4 tensor × 1/2 layers × 1/16 data batch.

3. FSDP — Fully Sharded Data Parallel 🏗️

FSDP là PyTorch native solution (torch.distributed.fsdp). Idea cốt lõi: shard mọi thứ — model parameters, optimizer states, gradients — across data parallel group. Chỉ gather khi cần compute.

3.1 Kiến Trúc FSDP & Sharding Strategies 🏗️

FSDP Memory Model (per GPU):

┌─────────────────────────────────────────────────────────────────┐
│                      FULL MODEL (7B params)                     │
│  Param: 14GB  |  Optim: 56GB (AdamW: 4x)  |  Grad: 14GB        │
│  Total: ~84GB per GPU (IMPOSSIBLE on single GPU)               │
└─────────────────────────────────────────────────────────────────┘
                              ↓ FSDP Sharding (DP=8)
┌─────────────────────────────────────────────────────────────────┐
│                      SHARDED PER GPU (DP rank)                  │
│  Param Shard: 1.75GB  |  Optim Shard: 7GB  |  Grad Shard: 1.75GB │
│  + Activation: ~6GB  |  Peak: ~16.5GB  ✅ FITS A100 40GB       │
└─────────────────────────────────────────────────────────────────┘

3 Sharding Strategies chính:

Strategy Shard What Communication Best For
FULL_SHARD Params + Optim + Gradients All-gather params before fwd/bwd; reduce-scatter grads Max memory saving, large models
SHARD_GRAD_OP Optim + Gradients (params replicated) Reduce-scatter grads; all-gather optim Medium models, less comm overhead
NO_SHARD (DP) Nothing (replicate all) All-reduce gradients only Small models, debug, baseline
HYBRID_SHARD FULL_SHARD intra-node, NO_SHARD inter-node Intra-node: all-gather; Inter-node: all-reduce Multi-node, slow interconnect
# FSDP Setup (PyTorch 2.3+)
from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
from torch.distributed.fsdp import ShardingStrategy, CPUOffload
from torch.distributed.fsdp.wrap import transformer_auto_wrap_policy
import functools

# Auto-wrap policy cho transformer layers
auto_wrap_policy = functools.partial(
    transformer_auto_wrap_policy,
    transformer_layer_cls={LlamaDecoderLayer}  # hoặc GPTNeoXLayer, etc.
)

# FSDP config
fsdp_config = {
    "sharding_strategy": ShardingStrategy.FULL_SHARD,
    "cpu_offload": CPUOffload(offload_params=False),  # True để offload params to CPU
    "auto_wrap_policy": auto_wrap_policy,
    "backward_prefetch": BackwardPrefetch.BACKWARD_PRE,  # Prefetch next layer params
    "forward_prefetch": True,
    "use_orig_params": True,  # Cho phép optimizer hoạt động trên original params
    "sync_module_states": True,
    "param_init_fn": None,
}

model = FSDP(model, **fsdp_config)
optimizer = torch.optim.AdamW(model.parameters(), lr=2e-5, foreach=True)  # foreach=True quan trọng cho perf

3.2 FSDP vs DDP: Memory & Communication 📊

Metric DDP FSDP FULL_SHARD FSDP HYBRID_SHARD
Model Memory/GPUFull1/DP1/DP_intra_node
Optimizer Memory/GPUFull1/DP1/DP_intra_node
Gradient Memory/GPUFull1/DP1/DP_intra_node
Comm Volume (params)02 × model_size × (DP-1)/DPIntra-node only
Comm Volume (grads)model_size × (DP-1)/DPmodel_size × (DP-1)/DPInter-node only
Activation MemoryFullFullFull
Max Model SizeVRAMVRAM × DPVRAM × DP_intra_node
PyTorch Native
✅ FSDP Advantages: Native PyTorch (no extra deps), composable với activation checkpointing, works với torch.compile, hỗ trợ mixed precision (bf16/fp8), flexible sharding strategies, mature ecosystem (HF Trainer, Lightning, Accelerate).

4. YaFSDP — Yet Another FSDP ⚡

YaFSDP (Yandex) là drop-in replacement cho FSDP với focus vào communication-computation overlapbucket-based all-gather. Released 2024, production-ready tại Yandex cho training 100B+ models.

4.1 Innovations: Buckets, Overlap, All-Gather 🔬

FSDP vs YaFSDP Communication Pattern:

FSDP (Sequential):
┌─────────────────────────────────────────────────────────────┐
│ Layer 1: [All-Gather Params] → [Forward] → [All-Gather]... │
│ Layer 2: [All-Gather Params] → [Forward] → [All-Gather]... │
│ Layer 3: [All-Gather Params] → [Forward] → [All-Gather]... │
│ ...                                                         │
│ Idle GPU time giữa all-gather và compute                    │
└─────────────────────────────────────────────────────────────┘

YaFSDP (Pipelined + Buckets):
┌─────────────────────────────────────────────────────────────┐
│ Bucket 1 (Layers 1-4):  [All-Gather] → [Forward]            │
│ Bucket 2 (Layers 5-8):           [All-Gather] → [Forward]   │
│ Bucket 3 (Layers 9-12):                 [All-Gather] → ...  │
│                                                         │
│ Overlap: All-Gather(Bucket N+1) || Forward(Bucket N)       │
│ Pre-fetch: Next bucket params trước khi cần                │
└─────────────────────────────────────────────────────────────┘

Key Innovations:

  • Bucket-based sharding: Group layers vào buckets, all-gather per bucket thay vì per-layer → giảm kernel launches, better NIC utilization
  • Communication-computation overlap: Double buffering — prefetch bucket N+1 trong khi compute bucket N
  • Hierarchical all-gather: Intra-node NVLink all-gather → inter-node NCCL all-gather, tận dụng bandwidth hierarchy
  • Optimizer state sharding: Tương tự FSDP nhưng overlap reduce-scatter với backward
  • FP8 support: Native FP8 training (H100/H200), quantization-aware communication
# YaFSDP Setup (pip install yafsdp)
from yafsdp import YaFSDP

# Config tương tự FSDP nhưng có thêm overlap params
yafsdp_config = {
    "sharding_strategy": "full_shard",
    "bucket_size": 100_000_000,  # ~100M params per bucket
    "overlap_comm_compute": True,
    "prefetch_buckets": 2,  # Prefetch N buckets ahead
    "hierarchical_allgather": True,
    "fp8": True,  # H100+ only
    "use_orig_params": True,
}

model = YaFSDP(model, **yafsdp_config)

4.2 Benchmarks: YaFSDP vs FSDP 📈

Config Model GPUs FSDP (TFLOPS/GPU) YaFSDP (TFLOPS/GPU) Speedup
A100 80GB × 8Llama-2 70B8142198+39%
A100 80GB × 64Llama-2 70B64135185+37%
H100 80GB × 8Llama-3 70B8298415+39%
H100 80GB × 128Llama-3 405B128267378+41%
A100 40GB × 8Llama-2 13B8156189+21%
📊 Source: Yandex YaFSDP benchmarks 2024-2025. Speedup cao nhất ở large model + large DP (communication-bound regime). Trên small model/small DP, speedup ~15-20% do compute-bound.
⚠️ Caveats: YaFSDP cần tune bucket_size cho từng model/hardware. Bucket quá nhỏ → overhead nhiều kernel launches; quá lớn → giảm overlap. Default 100M params hoạt động tốt cho hầu hết transformer models.

5. DeepSpeed Zero-3 & Hybrid Engine 🚀

DeepSpeed (Microsoft) là framework mature nhất cho large-scale training. Zero Redundancy Optimizer (ZeRO) là core innovation — partition optimizer states, gradients, params across data parallel group.

5.1 Zero Stages: 1 → 2 → 3 → Offload 📊

Stage Shards Memory/GPU (70B, AdamW) Comm Pattern Use Case
ZeRO-1 Optimizer states ~28GB (params+grads full, optim 1/DP) All-gather optim before step Medium models, easy migration from DDP
ZeRO-2 Optim + Gradients ~14GB (params full, optim+grads 1/DP) Reduce-scatter grads; all-gather optim Large models, good balance
ZeRO-3 Params + Optim + Gradients ~4GB (all sharded 1/DP) All-gather params fwd/bwd; reduce-scatter grads Max model size, memory-constrained
ZeRO-3 + Offload All + CPU/NVMe offload ~1-2GB GPU (rest on CPU/NVMe) Async copy to/from CPU/NVMe Extreme memory saving, slower
# DeepSpeed Zero-3 Config (ds_config.json)
{
  "train_batch_size": 512,
  "train_micro_batch_size_per_gpu": 2,
  "gradient_accumulation_steps": 32,
  
  "zero_optimization": {
    "stage": 3,
    "overlap_comm": true,
    "contiguous_gradients": true,
    "reduce_bucket_size": 5e7,
    "stage3_prefetch_bucket_size": 5e7,
    "stage3_param_persistence_threshold": 1e5,
    "stage3_max_live_parameters": 1e9,
    "stage3_max_reuse_distance": 1e9,
    "stage3_gather_16bit_weights_on_model_save": true,
    
    # Offload to CPU (optional)
    "offload_param": {
      "device": "cpu",
      "pin_memory": true
    },
    "offload_optimizer": {
      "device": "cpu",
      "pin_memory": true
    }
  },
  
  "fp16": {
    "enabled": false
  },
  "bf16": {
    "enabled": true
  },
  
  "gradient_clipping": 1.0,
  "prescale_gradients": false,
  "wall_clock_breakdown": false
}

5.2 3D Parallelism & Hybrid Engine 🌐

DeepSpeed mạnh nhất ở hybrid 3D parallelism — kết hợp DP + TP + PP seamless. Megatron-LM style TP + PP với ZeRO DP.

🔄
Data Parallel (ZeRO-3)
×
🔧
Tensor Parallel (Megatron)
×
📦
Pipeline Parallel (1F1B)
# DeepSpeed 3D Parallelism Config
{
  "zero_optimization": {
    "stage": 3
  },
  
  "tensor_parallel": {
    "enabled": true,
    "tp_size": 4,
    "tp_mode": "megatron"
  },
  
  "pipeline": {
    "enabled": true,
    "pp_size": 2,
    "schedule": "1f1b",
    "micro_batches": 4
  },
  
  # Total GPUs = dp_size × tp_size × pp_size
  # Example: 128 GPUs = 16 × 4 × 2
}
✅ DeepSpeed Advantages: Mature 3D parallelism, excellent Megatron-LM integration, ZeRO-Inference cho serving, DeepSpeed-MoE cho mixture-of-experts, DeepSpeed-Chat cho RLHF, auto-tuning (DeepSpeed-Autotuning), Hugging Face Trainer integration first-class, production-proven tại Microsoft, NVIDIA, Meta.

6. So Sánh Toàn Diện — Chọn Gì? ⚖️

6.1 Decision Matrix 🎯

Criteria FSDP YaFSDP DeepSpeed Zero-3
Ease of Adoption★★★★★ Native PyTorch★★★★☆ Pip install, API similar★★★☆☆ Config JSON, more complex
Memory Efficiency★★★★☆ FULL_SHARD★★★★☆ Same + overlap★★★★★ ZeRO-3 + offload
Communication Overlap★★★☆☆ Backward prefetch★★★★★ Bucket pipeline★★★★☆ Overlap comm
3D Parallelism (DP+TP+PP)★★★☆☆ Manual compose★★☆☆☆ Limited★★★★★ Native hybrid
Long Context (SP/CP)★★★☆☆ Manual★★★☆☆ Manual★★★★★ Ulysses/CP built-in
MoE Support★★★☆☆ Basic★★☆☆☆ Limited★★★★★ DeepSpeed-MoE
FP8 Training (H100)★★★★☆ torch.compile★★★★★ Native★★★★☆ Via TransformerEngine
Ecosystem (HF, Lightning)★★★★★ First-class★★★★☆ Good★★★★★ First-class
Debugging/Profiling★★★★★ PyTorch tools★★★★☆ Custom tools★★★☆☆ DS reporting
Production Maturity★★★★★ Meta, HF, etc.★★★★☆ Yandex★★★★★ Microsoft, NVIDIA

6.2 Khuyến Nghị Theo Workload 🎯

🏆 Single Node (≤8 GPUs), Model ≤70B, Team PyTorch-native: FSDP — simplest, native, best debugging, HF Trainer integration seamless.
🏆 Single/Multi-Node, Model 70B-405B, NVLink/NVSwitch, Want Max Throughput: YaFSDP — best communication overlap, 30-40% faster than FSDP at scale, FP8 native.
🏆 Multi-Node (>8 GPUs), Need 3D Parallelism, MoE, Long Context, RLHF Pipeline: DeepSpeed Zero-3 — only framework with native hybrid DP+TP+PP, MoE, CP/Ulysses, offload, mature RLHF stack.
🏆 Memory-Constrained (Consumer GPUs, 24-48GB), Model >70B: DeepSpeed ZeRO-3 + CPU Offload — can train 70B on 8×RTX 3090/4090.
🏆 Quick Experimentation, Debugging, Education: FSDP — PyTorch native, minimal config, works with torch.compile, easy to inspect.

7. Best Practices 2026 📋

7.1 Communication Optimization 📡

  • NCCL Tuning: Set NCCL_ALGO=RING cho small messages, TREE cho large. NCCL_PROTO=LL (low latency) cho small, LL128 cho large.
  • Topology Awareness: Sử dụng NCCL_TOPO_FILE hoặc torch.distributed.init_device_mesh để map ranks đúng NVLink domain.
  • Bucket Sizing: FSDP/YaFSDP bucket ~50-200M params. DeepSpeed reduce_bucket_size ~50M. Tune theo model size.
  • Overlap Strategy: Enable backward_prefetch=BACKWARD_PRE (FSDP), overlap_comm=true (DeepSpeed), overlap_comm_compute=true (YaFSDP).
  • Gradient Accumulation: Large effective batch = small micro-batch × grad_accum. Reduces comm frequency. Typical: 32-128 steps.
# NCCL Env Vars cho optimal perf
export NCCL_ALGO=RING,TREE
export NCCL_PROTO=LL,LL128
export NCCL_MIN_NCHANNELS=4
export NCCL_MAX_NCHANNELS=16
export NCCL_BUFFSIZE=8388608  # 8MB buffer
export NCCL_NTHREADS=4
export NCCL_NSOCKS_PERTHREAD=4
export CUDA_DEVICE_MAX_CONNECTIONS=1  # Quan trọng cho overlap

# Cho multi-node Ethernet (non-NVLink)
export NCCL_IB_DISABLE=0
export NCCL_IB_GID_INDEX=3
export NCCL_IB_TC=106
export NCCL_IB_SL=5
export NCCL_IB_TIMEOUT=22

7.2 Memory Optimization Checklist 💾

Technique Memory Savings Trade-off Framework Support
Activation Checkpointing30-50% activation mem+15-25% computeAll (selective layers)
ZeRO-3 / FULL_SHARD4-8× params+optim+comm overheadDS / FSDP / YaFSDP
CPU Offload (params/optim)Near-zero GPU mem2-5× slowerDS (best), FSDP (limited)
NVMe OffloadInfinite (disk-backed)10-50× slowerDeepSpeed only
FP8 / BF16 Training2× vs FP32Minimal (H100+)All (YaFSDP native)
Gradient AccumulationNo direct savingLarger effective batchAll
Flash Attention 2/3O(L²) → O(L) activationRequires Hopper+All
Sequence/Context ParallelActivation ÷ SP_degree+commDS (best), others manual
torch.compile + inductorKernel fusionCompile timeFSDP best, DS limited
# Activation Checkpointing Pattern (FSDP/YaFSDP/DS)
from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import (
    checkpoint_wrapper, CheckpointImpl, apply_activation_checkpointing
)

# Checkpoint every N transformer layers
non_reentrant_wrapper = lambda module: checkpoint_wrapper(
    module, checkpoint_impl=CheckpointImpl.NO_REENTRANT
)

apply_activation_checkpointing(
    model,
    checkpoint_wrapper_fn=non_reentrant_wrapper,
    check_fn=lambda m: isinstance(m, LlamaDecoderLayer)  # hoặc layer class tương ứng
)

7.3 Monitoring & Debugging 🔍

  • PyTorch Profiler: torch.profiler.profile với schedule=torch.profiler.schedule(wait=1, warmup=1, active=3), trace NCCL kernels.
  • NCCL Debug: NCCL_DEBUG=INFO hoặc VERSION để xem ring/tree selection, bus bandwidth.
  • DeepSpeed Report: deepspeed --report generates HTML report với memory/comm breakdown.
  • Memory Snapshot: torch.cuda.memory._dump_snapshot() + torch.cuda.memory._load_snapshot() visualize bằng memory_viz.
  • TensorBoard: Log MFU (Model FLOPs Utilization), throughput, memory, loss curves.
  • Key Metrics: MFU > 40% (good), > 50% (excellent). Comm/Compute ratio < 0.3. Memory fragmentation < 10%.
# MFU Calculation
def calculate_mfu(model_params, batch_size, seq_len, gpus, step_time, dtype="bf16"):
    # 6 × params × batch × seq (forward + backward)
    flops_per_token = 6 * model_params
    tokens_per_step = batch_size * seq_len * gpus
    total_flops = flops_per_token * tokens_per_step
    
    # GPU peak FLOPS (BF16 Tensor Core)
    gpu_peak_flops = {"a100": 312e12, "h100": 989e12, "h200": 989e12}[gpu_type.lower()]
    
    theoretical = gpu_peak_flops * gpus * step_time
    mfu = total_flops / theoretical
    return mfu

# Target: MFU > 0.4 (40%)

8. Kết Luận & Lộ Trình 🎓

Năm 2026, distributed LLM training đã chín muồi với 3 framework chính:

FSDP PyTorch Native Choice
YaFSDP Throughput King
DeepSpeed Feature Complete

Lộ trình học suggested:

  1. Tuần 1-2: FSDP basics — single node, FULL_SHARD, HF Trainer integration
  2. Tuần 3-4: YaFSDP — bucket tuning, overlap analysis, FP8 trên H100
  3. Tuần 5-6: DeepSpeed Zero-3 — config JSON, 3D parallelism, offload strategies
  4. Tuần 7-8: Advanced — SP/CP cho long context, MoE training, RLHF pipeline
  5. Ongoing: Profiling, MFU optimization, kernel fusion, new hardware (Blackwell, Rubin)
🚀 Final Recommendation: Đừng chỉ học 1 framework. Hiểu cơ chế sharding, communication patterns, memory hierarchy — thì bạn dễ migrate giữa FSDP/YaFSDP/DeepSpeed. Core concepts (ZeRO, TP, PP, SP, overlap, bucketing) là transferable. Framework chỉ là implementation detail.

Happy training! 🎯 Train smart, scale fast, debug less.

📚 References & Further Reading: