Distributed training: DP, TP, PP, FSDP
Split training across GPUs by data (replicate model, split batch), by state (FSDP/ZeRO shard weights, gradients, optimizer), inside layers (tensor) or across layers (pipeline). Mixed-precision Adam needs ~16 bytes per parameter.
Analogy: A restaurant kitchen: data parallel is identical stations cooking different orders; FSDP splits one pantry across stations; tensor parallel is four cooks plating one dish; pipeline is an assembly line, one step per cook.
How it works
- A 7B model needs ~112 GB of state before activations: more than an 80 GB H100.
- DDP scales throughput but saves no memory; ZeRO-3/FSDP shards state to ~16 × params / N per GPU.
- Tensor parallelism communicates inside every layer, so it needs NVLink and stays within one node.
- Pipeline parallelism spreads layers across nodes with light traffic, but GPUs idle in fill-and-drain bubbles.
- For fine-tuning, one-node FSDP or LoRA covers most cases.
Check yourself
Answer to mark it learned; your answers aren't scored.
A 2-node training job (8 H100s per node) uses tensor parallelism of degree 16, spanning both nodes over InfiniBand. Profiling shows GPUs mostly idle, waiting on communication. Best fix?
Go deeper
Full explanation
When training outgrows one GPU's memory or speed, you split the work. Start from the memory math: mixed-precision Adam keeps ~16 bytes per parameter (2 for bf16 weights, 2 for gradients, 12 for the fp32 master copy and two Adam moments) before activations. A 7B model needs ~112 GB: more than an 80 GB H100.
- Data parallelism (DDP): every GPU holds a full replica and a different slice of the batch; gradients are all-reduced each step. Scales throughput, saves no memory.
- FSDP / ZeRO: still data parallel, but shards state across N GPUs: ZeRO-1 the optimizer states, ZeRO-2 also gradients, ZeRO-3/FSDP also parameters, all-gathered layer by layer just in time. Per-GPU state drops to ~16 × params / N for ~1.5× DDP's communication.
- Tensor parallelism (TP): splits each matrix multiply inside a layer across GPUs (Megatron-LM). It communicates inside every layer, so it needs NVLink and stays within a node.
- Pipeline parallelism (PP): places consecutive layers on different GPUs and streams micro-batches through. Light communication, but GPUs idle in pipeline bubbles while each step fills and drains.
3D parallelism combines them: TP inside a node, PP across nodes, DP/FSDP across replicas; Mixture of Experts (MoE) and long-context runs add expert and context parallelism. Activation checkpointing trades ~33% more compute for far less activation memory. For fine-tuning, one-node FSDP or LoRA & QLoRA covers most cases.
Code Memory math + FSDP2 on one 8-GPU node
# Launch: torchrun --nproc_per_node=8 train.py
import torch, torch.distributed as dist
from torch.distributed.fsdp import fully_shard, MixedPrecisionPolicy # FSDP2, PyTorch >= 2.6
from transformers import AutoModelForCausalLM
MODEL = "meta-llama/Llama-3.1-8B" # any decoder model
def state_gb(params: float, shards: int = 1) -> float:
# bf16 weight + bf16 grad (4 B) + fp32 master, Adam m and v (12 B); no activations
return 16 * params / shards / 1e9
print(state_gb(7e9), state_gb(7e9, shards=8)) # 112.0 GB total, 14.0 GB per GPU
dist.init_process_group("nccl")
torch.cuda.set_device(dist.get_rank() % torch.cuda.device_count())
model = AutoModelForCausalLM.from_pretrained(MODEL, torch_dtype=torch.float32) # master copy
mp = MixedPrecisionPolicy(param_dtype=torch.bfloat16, reduce_dtype=torch.float32)
for block in model.model.layers: # one FSDP unit per transformer block, so
fully_shard(block, mp_policy=mp) # only ~one block is unsharded at a time
fully_shard(model, mp_policy=mp)
opt = torch.optim.AdamW(model.parameters(), lr=1e-5) # states exist only for the local shard
for batch in loader: # DistributedSampler: a different slice per rank
loss = model(**batch).loss # forward: all-gather each block's params, then free
loss.backward() # backward: re-gather, then reduce-scatter gradients
opt.step() # each rank updates only its 1/8 of the weights
opt.zero_grad()Real example
Full fine-tuning Llama 3.1 8B: 8B × 16 bytes ≈ 128 GB of state, so plain DDP on 80 GB H100s fails even at batch size 1. FSDP on one 8-GPU node puts ~16 GB of state on each GPU, leaving ~60 GB for activations; with activation checkpointing, 8k-token sequences fit. A 70B full fine-tune is ~1.1 TB of state: FSDP over 4 nodes (32 GPUs) gives ~35 GB each. If the 70B job only adapts style, QLoRA is the cheaper answer: the QLoRA paper fine-tuned a 65B model on a single 48 GB GPU.
Trade-offs +3 · −4
+ You gain
- DDP is nearly free to adopt: one wrapper and near-linear throughput scaling while the batch still converges.
- FSDP/ZeRO fits models N× larger than one GPU's memory with little code change.
- TP, PP and DP compose to thousands of GPUs: Llama 3 405B trained on up to 16K H100s.
− You pay
- Communication becomes the bottleneck: TP needs NVLink, FSDP at scale needs fast inter-node links.
- Pipeline bubbles waste GPU time unless micro-batches far outnumber stages.
- 3D configs are hard to tune and debug: hangs, stragglers and checkpoint resharding are real operational work.
- Global batch grows with DP degree; past a point, bigger batches stop helping convergence.
Use it when
Full fine-tuning or pretraining when ~16 bytes × params plus activations exceeds one GPU, or one GPU is too slow. Default to FSDP; add TP/PP only at tens of billions of parameters on hundreds of GPUs.
Avoid it when
When LoRA or QLoRA on one GPU meets the quality bar, or when you're only serving: sharding for inference is a different problem (Self-hosted serving stack).
Numbers to know 5
- Mixed-precision Adam ≈ 16 bytes/param before activations: 7B ≈ 112 GB, 70B ≈ 1.1 TB.
- ZeRO-3/FSDP: per-GPU state ≈ 16 × params / N, at ~1.5× DDP's communication volume.
- Pipeline bubble ≈ (p−1)/(m+p−1) of step time: 4 stages, 16 micro-batches → ~16% idle.
- H100 NVLink ~900 GB/s per GPU vs ~100 GB/s for a 400 Gb/s InfiniBand link (both bidirectional, ~9×): TP stays inside the node.
- Llama 3 405B: 4D parallelism (TP, CP, PP, FSDP) on up to 16K H100s at ~38–43% MFU.
Common pitfalls 4
- Forgetting activations: 16 bytes/param is only the state; long sequences can need more memory than the weights.
- Running TP across nodes over InfiniBand: per-layer all-reduces on a slow link stall every step.
- Too few micro-batches per pipeline step, so bubbles eat a large share of GPU time.
- Saving full checkpoints by gathering on rank 0: slow and OOM-prone; use sharded checkpoints.
Interview questions 3
Answer out loud first, then reveal.
How much GPU memory does a full fine-tune of a 7B model need, and how would you fit it?Show answer
I start with ~16 bytes per parameter for mixed-precision Adam: 2 for bf16 weights, 2 for gradients, 12 for the fp32 master copy and two Adam moments. That's ~112 GB before activations, so it doesn't fit one 80 GB H100, and DDP doesn't help because it replicates everything. I'd use FSDP or ZeRO-3 on one 8-GPU node: ~14 GB of state per GPU, the rest for activations, plus activation checkpointing for long sequences. But first I'd ask whether LoRA on one GPU reaches the quality bar for a fraction of the cost.
When do you need tensor or pipeline parallelism instead of just FSDP?Show answer
FSDP all-gathers every layer's weights on every step, so its traffic grows with model size and crosses node boundaries; and pure data parallelism needs at least one sample per GPU, so at thousands of GPUs the global batch gets too large to converge well. At tens of billions of parameters on hundreds of GPUs, I add TP inside each node, where NVLink makes per-layer all-reduces affordable, and PP across nodes, which only passes activations at stage boundaries. The price is pipeline bubbles, so I use many micro-batches and an interleaved schedule, with FSDP as the outer dimension.
What's the difference between ZeRO stages 1, 2 and 3?Show answer
What gets sharded across the N data-parallel ranks. Stage 1 shards optimizer states, the biggest piece at 12 of the 16 bytes per parameter, so memory drops to ~4 + 12/N bytes per parameter at the same communication as DDP. Stage 2 also shards gradients: ~2 + 14/N, still the same communication. Stage 3, equivalent to FSDP, shards parameters too: 16/N, but it must all-gather weights for every forward and backward, about 1.5× DDP's traffic. I pick the lowest stage that fits.