One GPU Trains; Many GPUs Coordinate
Distributed training is not "the same code, more GPUs." Each parallelism strategy splits a different thing â data, individual weight matrices, or model stages â and each introduces a communication pattern that can erase your speedup if you choose it without measuring.
- Pick between data, tensor, pipeline, and sharded parallelism from model size relative to GPU memory
- Read a throughput table in tokens per second per GPU and spot communication bottlenecks
- Structure checkpointing and mixed precision so long runs survive hardware failures
Training Infrastructure: Parallelism Strategies for LLMs
What You'll Learn
- 1Explain what each parallelism strategy splits and what communication it requires
- 2Launch a data-parallel training loop with proper sampling and gradient synchronization
- 3Choose a tensor, pipeline, or sharded configuration from a model's memory footprint
- 4Apply mixed precision and checkpointing to make multi-day runs practical
What Breaks When You Scale Past One GPU
A single modern GPU holds 80 GB of high-bandwidth memory and delivers teraflops of compute, which is enough to fine-tune a 7B model with adapters but not enough to pre-train it. The moment a training state â parameters, gradients, optimizer moments, activations â no longer fits on one card, you enter the world of distributed training, and the failure modes change character.
The first enemy is the interconnect. GPUs inside one server talk over NVLink at hundreds of gigabytes per second; across servers you get InfiniBand or, worse, ordinary Ethernet. Algorithms that look fine on a diagram crawl when every step requires a global synchronization over a slow link. The second enemy is stragglers: in lockstep training, the slowest rank sets the pace for everyone. The third is silent numerical divergence â ranks that drift apart because someone forgot to seed or synchronize a buffer â which surfaces days later as a perplexity curve that refuses to improve.
Good infrastructure design attacks all three: it minimizes cross-node traffic, keeps every rank busy, and makes state checkpoints routine rather than heroic.
Data Parallelism: The Default Starting Point
Data parallelism replicates the full model on every GPU and gives each rank a different slice of the batch. After backpropagation, ranks reduce their gradients with an all-reduce so every replica updates identically. It is the simplest strategy to implement and the first one you should reach for while the model still fits in one card's memory.
The details that make or break a data-parallel run are rarely in the model code. The sampler must shard the dataset by rank so workers never duplicate examples, and the epoch loop should call its set-epoch method so shuffling differs across restarts. Launching is typically done with a single-node launcher that spawns one process per GPU.
import torch
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.data import DataLoader, DistributedSampler
class DataParallelTrainer:
def __init__(self, model, rank, world_size):
self.rank = rank
self.world_size = world_size
dist.init_process_group("nccl", rank=rank, world_size=world_size)
torch.cuda.set_device(rank)
self.model = DDP(model.to(rank), device_ids=[rank])
def make_loader(self, dataset, batch_size):
sampler = DistributedSampler(dataset, num_replicas=self.world_size,
rank=self.rank, shuffle=True)
return DataLoader(dataset, batch_size=batch_size, sampler=sampler)
def train_epoch(self, loader, optimizer, criterion):
self.model.train()
total = 0.0
for data, target in loader:
data, target = data.to(self.rank), target.to(self.rank)
optimizer.zero_grad(set_to_none=True)
loss = criterion(self.model(data), target)
loss.backward()
optimizer.step()
total += loss.item()
return total / len(loader)
def close(self):
dist.destroy_process_group()
# Launch with: torchrun --standalone --nproc_per_node=4 train.py
Pure data parallelism stops working when the replicated model plus optimizer state outgrows a single card. At that point you add a second axis of splitting.
Choosing a Parallelism Strategy
Each strategy splits a different resource, and production runs usually combine them. Use the table to map your constraint to a starting configuration:
| Strategy | What is split | Communication pattern | Best when | Main cost |
|---|---|---|---|---|
| Data parallel (DDP) | Batch across replicas | All-reduce gradients each step | Model fits on one GPU | Memory duplicates per GPU |
| Fully sharded (FSDP) | Parameters, grads, optimizer states | All-gather per layer, reduce-scatter | Model is near or over single-GPU capacity | Extra gather traffic per layer |
| Tensor parallel | Individual weight matrices and attention heads | All-reduce inside each layer | Very wide layers that cannot shard otherwise | Latency-sensitive per-layer syncs |
| Pipeline parallel | Contiguous model stages across GPUs | Point-to-point activation sends | Very deep models | Pipeline bubble time |
| Expert parallel (MoE) | Experts across ranks | All-to-all token routing | Mixture-of-experts layers | Load imbalance between experts |
A practical rule: start with FSDP across every GPU in a node before paying the complexity cost of tensor and pipeline parallelism, because FSDP requires no model-code surgery beyond wrapping layers and keeps the programming model simple.
Tensor Parallelism Inside Attention and MLP Blocks
Tensor parallelism splits single operations across GPUs. In a transformer, the natural seams are the attention heads and the two matrices of the MLP down-projection. Each rank owns a slice of the weight matrix, computes a partial result, and an all-reduce recombines the outputs so every rank holds the full activation.
The performance characteristic that governs tensor parallelism is that every layer triggers two synchronizations on the forward pass and two on the backward pass. Those collectives are latency-bound, so tensor parallel groups are almost always kept inside one server where NVLink keeps the round trip short. Stretching a tensor-parallel group across nodes is the classic way to turn a fast model into a slow one.
import torch.distributed as dist
class ColumnParallelLinear:
"""Splits the output dimension of a linear layer across ranks."""
def __init__(self, weight, world_size, rank):
self.world_size = world_size
self.rank = rank
rows = weight.shape[0] // world_size
self.local = weight[rank * rows:(rank + 1) * rows].contiguous()
def forward(self, x):
partial = torch.matmul(x, self.local.transpose(0, 1))
dist.all_reduce(partial, op=dist.ReduceOp.SUM)
return partial
class HeadParallelAttention:
"""Assigns a disjoint group of attention heads to each rank."""
def __init__(self, num_heads, world_size, rank):
assert num_heads % world_size == 0
self.heads_per_rank = num_heads // world_size
self.rank = rank
def slice_heads(self, q, k, v):
d = q.shape[-1] // (self.heads_per_rank * self.world_size)
start = self.rank * self.heads_per_rank * d
end = start + self.heads_per_rank * d
return q[..., start:end], k[..., start:end], v[..., start:end]
The divisibility assertion in the head-slicing class hides a real operational constraint: tensor parallelism requires layer dimensions that divide evenly by your group size, which constrains model architecture choices long before training starts.
Pipeline Parallelism and the Bubble Problem
Pipeline parallelism assigns contiguous blocks of layers to different GPUs. The first stage receives embeddings and produces activations that flow forward to the next stage. The complication is that while stage two computes, stage one sits idle unless you split the batch into micro-batches and interleave them.
That idle fraction is the pipeline bubble: with p stages and m micro-batches, a naive schedule leaves roughly p minus one of every m plus p minus one slots empty. GPipe-style schedules maximize throughput by ramping all micro-batches forward before pulling gradients back; 1F1B schedules trade a little memory for earlier gradient computation by alternating forward and backward passes as soon as dependencies allow. In both cases the practical lever is the same â increase the number of micro-batches to shrink the bubble, until activation memory or communication overhead pushes back.
import torch
class PipelineStage:
def __init__(self, layers, stage_id):
self.layers = layers
self.stage_id = stage_id
def forward(self, x):
for layer in self.layers:
x = layer(x)
return x
def gpipe_microbatches(batch, num_micro, stage_count):
chunks = torch.chunk(batch, num_micro, dim=0)
schedule = []
total_steps = num_micro + stage_count - 1
for step in range(total_steps):
for stage in range(stage_count):
fwd = step - stage
bwd = step - stage - stage_count + 1
if 0 <= fwd < num_micro:
schedule.append(("fwd", stage, fwd))
if 0 <= bwd < num_micro:
schedule.append(("bwd", stage, bwd))
return schedule
# schedule = gpipe_microbatches(batch, num_micro=8, stage_count=4)
Treat the scheduler output as a contract: every stage must execute exactly the ops in order, or activations silently misalign across the pipeline.
Mixed Precision, Checkpointing, and Efficiency Metrics
Almost every large-model training run uses bf16 or fp16 for the forward and backward compute, with fp32 master weights and a gradient scaler where loss scaling is required. Mixed precision roughly halves memory traffic and, on tensor cores, can double throughput. The failure mode to watch is underflow in fp16 without scaling; bf16 avoids the issue by keeping fp32's exponent range, which is why it became the default for large-model pre-training.
Checkpointing trades compute for memory by recomputing activations during the backward pass instead of storing them, enabling larger batches or deeper models at the cost of roughly 20â30 percent extra compute. Gradient accumulation lets you simulate large global batch sizes while keeping per-step activations small.
The metric that tells you whether the whole stack is working is model FLOPs utilization: achieved FLOPs divided by the hardware's peak. Well-run large-model training reaches 35â50 percent; a configuration that keeps GPUs idle on collectives or bubbles will land far below, and no amount of extra hardware fixes a utilization problem â only a configuration change does.
Common Mistakes
Scaling to many nodes before confirming single-node efficiency
Fix: Maximize tokens per second per GPU on one node first; multipliers carry existing inefficiencies
Using tensor parallelism across machines for convenience
Fix: Keep tensor-parallel groups within a node; use FSDP or pipeline parallelism for cross-node scaling
Checkpointing only from rank zero with no redundancy
Fix: Write checkpoints from all ranks to fault-tolerant storage and test resume from the middle of a run
Judging a run by loss curve shape alone
Fix: Track model FLOPs utilization and tokens per second per GPU every run
Best Practices
- Wrap models in FSDP before reaching for hand-tuned tensor or pipeline splits
- Use bf16 mixed precision with fp32 master weights as the default numeric configuration
- Set gradient accumulation to hit your target global batch size without OOM errors
- Log throughput and utilization alongside loss so regressions surface within hours, not weeks
Interview Questions
Q1: What is the pipeline bubble, and how do you shrink it?
The bubble is the idle time on pipeline stages while micro-batches ramp up and wind down. Its size scales with stage count relative to micro-batch count, so increasing the number of micro-batches reduces the fraction of idle time, at the cost of more activation memory and communication messages.
Q2: When do you choose FSDP over plain data parallelism?
When model parameters plus gradients plus optimizer states approach or exceed single-GPU memory. FSDP shards those across ranks and all-gathers them per layer, trading extra communication for the ability to train models several times larger than one card can hold.
Q3: Why keep tensor parallel groups inside a single server?
Tensor parallelism synchronizes twice per layer in each direction. Those collectives are latency-sensitive, and cross-node links add milliseconds per sync that compound across hundreds of layers. NVLink keeps the round trip short enough for the strategy to pay off.
Key Takeaways
- Data parallelism replicates the model and splits the batch; FSDP shards weights, gradients, and optimizer states to fit larger models
- Tensor parallelism splits matrices and attention heads with per-layer all-reduce; pipeline parallelism splits stages and must manage the bubble
- Mixed precision with bf16 and fp32 master weights is the default numeric recipe for large-model training
- Checkpoint every rank to durable storage and verify resume paths before long runs
- Model FLOPs utilization, not just loss, tells you whether the distributed configuration is healthy