Distributed & Efficient Training
After this lesson, you will be able to:
- Choose the right parallelism strategy (data parallel, pipeline parallel, tensor parallel, or sharded) based on whether your bottleneck is compute, memory, or communication
- Use Fully Sharded Data Parallel (FSDP) and DeepSpeed ZeRO to fit a 100B parameter model on hardware where DDP would OOM in seconds
- Apply gradient checkpointing, mixed precision (fp16/bf16), and gradient accumulation to halve memory usage with predictable compute tradeoffs
- Profile a distributed training run with PyTorch Profiler to distinguish a compute-bound bottleneck from a comm-bound one, and pick the right intervention for each
Before you start
Don't worry if "distributed training" sounds like a separate field — once you understand the three flavors of parallelism (data, model, pipeline) and the memory math behind ZeRO, it all clicks. The vocabulary looks daunting but the ideas are simple.
#The Capacity Wall
#Three Parallelism Strategies
The distributed-training literature compresses to three orthogonal techniques. Real systems combine them.
#Data Parallelism: Replicate the Model, Split the Batch
The line above says the global gradient is the plain average of the per-GPU gradients. Here is why that is exactly the gradient of one big batch, and what it costs to compute that average.
Averaging needs an all-reduce, and its cost decides whether data parallelism scales. The ring all-reduce used by NCCL and Horovod has a clean cost.
PyTorch has two classes for this, and one is a trap
nn.DataParallel(DP): one Python process spawns threads — Python's GIL bottlenecks everything. Don't use it.nn.parallel.DistributedDataParallel(DDP): one process per GPU, no GIL contention, ~95% scaling efficiency. Use this.
DDP works great until the model itself doesn't fit in one GPU. Then you need sharding.
#Pipeline Parallelism: Split Layers Across GPUs
Put the first 6 transformer layers on GPU 0, layers 7-12 on GPU 1, and so on. Forward pass: GPU 0 finishes layers 1-6 on a micro-batch, hands its activations to GPU 1, then immediately starts layers 1-6 on the next micro-batch. The "bubble" — the time GPUs sit idle waiting for the pipeline to fill — is the cost.
#Tensor Parallelism: Split a Single Layer Across GPUs
#ZeRO and FSDP: Shard Everything
ZeRO has three stages, each saving more memory at the cost of more communication:
Decision rubric
- Model fits in single GPU + you want speed → DDP
- Model barely fits, optimizer state is the killer → ZeRO-1
- Optimizer + gradients won't fit → ZeRO-2
- Even parameters don't fit → ZeRO-3 / FSDP (or DeepSpeed ZeRO-3)
- Model is so big a single layer doesn't fit → add tensor parallelism on top
You have a 13-billion-parameter model and 8 NVIDIA A100 80GB GPUs (~640GB total). You want to fine-tune with AdamW. Which strategy?
#Calculate the memory budget yourself
The "16 bytes per parameter" rule is the load-bearing arithmetic of every distributed-training decision. Let's open the hood and write it down precisely, because every "will this fit?" question reduces to one inequality. The accounting (Rajbhandari et al. 2019, "ZeRO: Memory Optimizations Toward Training Trillion Parameter Models") tracks four buffers per parameter during vanilla mixed-precision training with AdamW:
- Parameters (fp16/bf16). What the forward pass reads: 2 bytes
- Gradients (fp16/bf16). What backward writes: 2 bytes
- AdamW optimizer state. First moment
mand second momentv, both kept in fp32 for numerical stability (4 + 4 = 8 bytes) plus a fp32 master copy of the parameters used for the actual weight update (4 bytes). Total: 12 bytes
Activations are the second budget. The Megatron memory paper (Korthikanti et al. 2022, "Reducing Activation Recomputation in Large Transformer Models") gives the peak activation memory per transformer layer as approximately:
bytes_per_layer ≈ batch · seq_len · hidden · (34 + 5 · num_heads · seq_len / hidden)34·b·s·h term covers the LayerNorm outputs, QKV projections, attention output, MLP intermediate, and dropout masks. The 5·b·s·h · (num_heads·s/h) term is the attention-score matrix — quadratic in seq_len, which is why long-context training is so brutal.Where do the 34 and the 5 come from? You can count them tensor by tensor. Here is the count, which follows the one in the Megatron memory paper.
Sharding redistributes the 16 bytes:
| Strategy | Per-GPU memory (params/grad/optim) |
|---|---|
| DDP | 16 · N_params (everything replicated) |
| ZeRO-1 | (2 + 2 + 12/G) · N_params (optim state sharded) |
| ZeRO-2 | (2 + 2/G + 12/G) · N_params (optim + grads sharded) |
| ZeRO-3 / FSDP | (2 + 2 + 12)/G · N_params = 16·N_params / G (everything sharded) |
| Tensor parallel (TP=G) | weights and activations along feature dim divided by G |
Here is where the 16 bytes and each stage formula come from. The derivation uses N for the number of parameters and k for the number of GPUs, as in the formulas above.
Move the parameter count, the GPU count, the GPU memory and the ZeRO stage, and watch stage 1 shard the optimizer state, stage 2 also the gradients and stage 3 also the weights, so per-GPU memory falls from 16N to 16N/K (activations are not included).
N_params, G, batch_size, seq_len, hidden_size, num_layers, num_heads, and re-run.You have a 70B-parameter model and eight 80GB H100 GPUs. You want vanilla AdamW + bf16 mixed precision. Does plain DDP fit on this hardware?
The math here is unforgiving and exactly what you should reach for every time someone asks "will this run on N GPUs?". Numbers, not vibes.
3 · 7/8 · 140 GB = 367 GB of traffic per GPU per step. On 600 GB/s NVLink this is about 0.6 s of pure comm; on 100 Gb/s Ethernet (12.5 GB/s) it is about 30 seconds. Pick your interconnect before you pick your sharding strategy.#Memory Tricks That Stack on Top
#Mixed Precision Recap
GradScaler. bf16 has the same exponent range as fp32 but lower mantissa precision; the modern default for transformers because no scaler is needed.from torch.cuda.amp import autocast, GradScaler
scaler = GradScaler()
for batch in loader:
with autocast(dtype=torch.bfloat16): # or fp16 with scaler
out = model(batch)
loss = criterion(out, target)
scaler.scale(loss).backward() # for fp16; bf16 doesn't need scaling
scaler.step(optimizer)
scaler.update()#Gradient Checkpointing
Two short derivations explain the numbers in the checkpointing trade. First the compute cost of training, then the memory and the extra compute of checkpointing.
#Gradient Accumulation
Need an effective batch size of 256 but your GPU only fits batch 16? Run 16 micro-batches, accumulating gradients without stepping the optimizer, then step once.
optimizer.zero_grad()
for i in range(accum_steps):
loss = model(batch[i]) / accum_steps
loss.backward()
optimizer.step() # one step per (accum_steps × micro_batch) effective batch#Profiling: Find the Real Bottleneck
Interactive Lab
Watch loss curves, GPU utilization, and gradient norms update in real time — the same view you'd see when monitoring a real distributed training run.
You can't optimize what you can't measure. PyTorch Profiler classifies time spent into compute, memory, and communication.
This code needs PyTorch, and in places a GPU, so it cannot run on this page. Copy it to Google Colab to run it.
# Copy to Colab: needs torch, so it cannot run on this page.
# Distributed training skeleton: DDP + bf16 + gradient checkpointing + profiler
import torch
import torch.distributed as dist
import torch.nn as nn
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.checkpoint import checkpoint
from torch.cuda.amp import autocast
from torch.profiler import profile, ProfilerActivity, schedule
# Setup distributed (run with: torchrun --nproc_per_node=8 train.py)
dist.init_process_group(backend="nccl")
local_rank = int(os.environ["LOCAL_RANK"])
torch.cuda.set_device(local_rank)
class TransformerBlock(nn.Module):
def __init__(self, d):
super().__init__()
self.attn = nn.MultiheadAttention(d, 8, batch_first=True)
self.ffn = nn.Sequential(nn.Linear(d, 4*d), nn.GELU(), nn.Linear(4*d, d))
self.ln1, self.ln2 = nn.LayerNorm(d), nn.LayerNorm(d)
def forward(self, x):
x = x + self.attn(self.ln1(x), self.ln1(x), self.ln1(x))[0]
x = x + self.ffn(self.ln2(x))
return x
class GPTLike(nn.Module):
def __init__(self, n_layer=24, d=1024, vocab=50000):
super().__init__()
self.embed = nn.Embedding(vocab, d)
self.blocks = nn.ModuleList([TransformerBlock(d) for _ in range(n_layer)])
self.head = nn.Linear(d, vocab)
def forward(self, ids):
x = self.embed(ids)
for blk in self.blocks:
x = checkpoint(blk, x) # gradient checkpointing
return self.head(x)
model = GPTLike().cuda()
model = DDP(model, device_ids=[local_rank])
optimizer = torch.optim.AdamW(model.parameters(), lr=3e-4, weight_decay=0.1)
# Profile a few training steps
prof_schedule = schedule(wait=1, warmup=1, active=3, repeat=1)
with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA], schedule=prof_schedule) as prof:
for step in range(10):
ids = torch.randint(0, 50000, (8, 1024)).cuda()
with autocast(dtype=torch.bfloat16):
out = model(ids)
loss = out.sum()
loss.backward()
optimizer.step()
optimizer.zero_grad()
prof.step()
if local_rank == 0:
print(prof.key_averages().table(sort_by="cuda_time_total", row_limit=10))
dist.destroy_process_group()Notes for going further:
# Real-world version uses FSDP instead of DDP for memory savings:
# from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
# from torch.distributed.fsdp.wrap import transformer_auto_wrap_policy
# wrap_policy = functools.partial(transformer_auto_wrap_policy,
# transformer_layer_cls={TransformerBlock})
# model = FSDP(model, auto_wrap_policy=wrap_policy,
# mixed_precision=MixedPrecision(param_dtype=torch.bfloat16))
# # FSDP shards parameters across all GPUs in the data-parallel group;
# # each GPU only holds 1/N of the model at any time except during forward/backward of a wrapped blockWhat to check: Verify the model trains without OOM on a single 80GB GPU at this size; tensor parallel would be needed if the model itself didn't fit.
#Key Takeaways
- Three orthogonal parallelism strategies (data, pipeline, tensor) solve different walls. Data parallel scales compute, pipeline parallel splits layers, tensor parallel splits within a layer. Real systems combine all three for trillion-parameter models.
- DDP duplicates everything; FSDP shards everything. DDP is fine until your optimizer state alone exceeds GPU memory. FSDP / ZeRO-3 shards parameters, gradients, and optimizer state across data-parallel workers, dropping per-GPU memory by Nx for N GPUs.
- Mixed precision is free 2x speedup if you use bf16. Bf16 has the dynamic range of fp32 with half the bits; fp16 needs
GradScalerto avoid underflow but is faster on older hardware. - Gradient checkpointing trades ~30% compute for 10x activation-memory savings. Mandatory above 7B parameters, optional below. The single most useful trick for fitting larger models on the same hardware.
- Profile before optimizing. PyTorch Profiler tells you whether you're compute-bound (use bigger model or smaller batch), memory-bound (add checkpointing or shard with FSDP), or comm-bound (faster fabric or fewer all-reduces).
#Quick Check
You have 8 GPUs and a 70B-parameter model. The model itself doesn't fit on a single GPU. What strategy?