GPU Training: Parallelism, Precision, and Data Loading
Difficulty: Senior Level | Companies: Google, Meta, Netflix, Uber, Stripe
Prerequisites
- !PyTorch training loops and autograd
- !What CUDA devices and memory are
- !Basic understanding of batch training
What You'll Learn
- 1Diagnose whether compute, memory, or input is the real bottleneck
- 2Set up DistributedDataParallel with correct sampling
- 3Use mixed precision safely with gradient scaling and clipping
- 4Benchmark throughput in a way that supports real decisions
Where GPU time actually goes
An idle GPU is a rental you keep paying for, and in practice the device sits idle far more than teams expect. The three usual culprits are input starvation â the data loader cannot feed the next batch fast enough â host-to-device transfer happening serially instead of overlapped with compute â and synchronization points that force every rank to wait for the slowest one. Each presents differently: input starvation shows GPU utilization hovering well below capacity with low memory use; transfer overhead shows as long gaps between steps; stragglers show as sawtooth utilization across ranks that should be identical.
The discipline that fixes all three is measurement before optimization. Log step time broken into data wait, forward, backward, and optimizer segments, alongside GPU utilization and memory, and only then change something. Teams that skip this routinely buy larger clusters to compensate for a single-threaded CSV reader, multiplying their bill while the actual bottleneck stays exactly where it was. A ten-minute profile usually identifies which of the three you have, and the fix differs completely for each.
Choosing a parallelism strategy
Data parallelism replicates the model on every device and splits the batch, which scales cleanly while the model fits in one device's memory. Model parallelism splits the weights themselves and is only worth the communication overhead when the model will not fit. Pipeline parallelism staggers layers across devices to keep them busy, at the cost of bubbles where devices wait. Most teams never need anything beyond data parallelism plus gradient accumulation â reach for the others only when memory, not time, is the constraint.
| Strategy | Scales | Communication cost | Complexity | When to use |
|---|---|---|---|---|
| Data parallel (DDP) | Well, near-linear | Gradients each step | Low | Model fits on one device |
| Gradient accumulation | Not parallel; simulates batch | None | Very low | Batch larger than memory |
| Model parallel | Poorly alone | Activations between devices | High | Model exceeds one device |
| Pipeline parallel | Moderately | Stage handoffs, bubble time | High | Deep, layer-partitionable models |
| Tensor parallel | Well at very large scale | Per-layer all-reduce | Very high | Very wide layers inside a device group |
One warning about expectations: doubling devices rarely doubles throughput. Communication, stragglers, and fixed per-step costs impose a ceiling, and a scaling efficiency above 85% per doubling is genuinely good. If your second GPU delivers 60% of the first, profile communication before buying the third.
Distributed training done correctly
DistributedDataParallel is easy to start and easy to get subtly wrong. Three details decide whether results are correct: every rank must see a different shard of data, the sampler must be re-seeded each epoch so shuffling differs across epochs but stays deterministic, and only rank zero should write logs and checkpoints. Miss the first and ranks train on identical batches, silently halving your effective batch; miss the second and resuming a run produces a different data order than the original.
# ddp_training.py
import os
import time
from dataclasses import dataclass
import torch
import torch.distributed as dist
import torch.nn as nn
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.data import DataLoader, DistributedSampler
from torch.utils.data.dataset import TensorDataset
@dataclass
class TrainConfig:
epochs: int = 4
batch_size: int = 128
lr: float = 1e-3
log_rank0_only: bool = True
def setup(rank: int, world_size: int) -> None:
os.environ.setdefault("MASTER_ADDR", "127.0.0.1")
os.environ.setdefault("MASTER_PORT", "29517")
dist.init_process_group(backend="nccl", rank=rank, world_size=world_size)
torch.cuda.set_device(rank)
def cleanup() -> None:
dist.destroy_process_group()
class Net(nn.Module):
def __init__(self, in_dim: int = 64, classes: int = 10):
super().__init__()
self.body = nn.Sequential(
nn.Linear(in_dim, 256), nn.ReLU(),
nn.Linear(256, 256), nn.ReLU(),
nn.Linear(256, classes),
)
def forward(self, x):
return self.body(x)
def train(rank: int, world_size: int, cfg: TrainConfig) -> None:
setup(rank, world_size)
torch.manual_seed(42 + rank)
X = torch.randn(20_000, 64)
y = torch.randint(0, 10, (20_000,))
dataset = TensorDataset(X, y)
sampler = DistributedSampler(
dataset, num_replicas=world_size, rank=rank, shuffle=True, drop_last=True
)
loader = DataLoader(
dataset,
batch_size=cfg.batch_size,
sampler=sampler,
num_workers=4,
pin_memory=True,
persistent_workers=True,
prefetch_factor=4,
)
model = Net().to(rank)
model = DDP(model, device_ids=[rank])
optimizer = torch.optim.AdamW(model.parameters(), lr=cfg.lr)
criterion = nn.CrossEntropyLoss()
for epoch in range(cfg.epochs):
sampler.set_epoch(epoch)
model.train()
running, seen = 0.0, 0
started = time.perf_counter()
for xb, yb in loader:
xb = xb.to(rank, non_blocking=True)
yb = yb.to(rank, non_blocking=True)
optimizer.zero_grad(set_to_none=True)
loss = criterion(model(xb), yb)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
optimizer.step()
running += loss.item() * yb.size(0)
seen += yb.size(0)
if rank == 0:
elapsed = time.perf_counter() - started
print(
f"epoch {epoch} loss={running / seen:.4f} "
f"samples_per_sec={seen / elapsed:.0f} world_size={world_size}"
)
if rank == 0:
torch.save(model.module.state_dict(), "model.pt")
cleanup()
if __name__ == "__main__":
world = int(os.environ.get("WORLD_SIZE", "1"))
train(rank=int(os.environ.get("RANK", 0)), world_size=world, cfg=TrainConfig())
set_to_none=True on the optimizer zeroing is a small but real win â it avoids writing zeros into gradient storage each step â and non_blocking=True combined with pinned memory lets the transfer overlap the next compute. Neither is a silver bullet, but both are free once the pattern is in place.
Mixed precision without NaN blowups
Automatic mixed precision runs eligible operations in 16-bit, roughly doubling throughput on modern hardware and halving memory, which often lets you raise the batch size as well. The risk is numerical: small gradients underflow to zero and the loss can explode. GradScaler exists precisely to manage this â it multiplies the loss before backward to keep small gradients representable, then skips the optimizer step if the scaled gradients overflow, adjusting the scale dynamically.
# mixed_precision.py
import time
from dataclasses import dataclass
from typing import Dict
import torch
import torch.nn as nn
from torch.cuda.amp import GradScaler, autocast
@dataclass
class AmpConfig:
enabled: bool = True
init_scale: float = 65536.0
growth_interval: int = 2000
max_grad_norm: float = 1.0
class AmpTrainer:
def __init__(self, model: nn.Module, device: torch.device, cfg: AmpConfig = AmpConfig()):
self.model = model.to(device)
self.device = device
self.cfg = cfg
self.scaler = GradScaler(
enabled=cfg.enabled,
init_scale=cfg.init_scale,
growth_interval=cfg.growth_interval,
)
self.skipped_steps = 0
def step(self, xb: torch.Tensor, yb: torch.Tensor,
criterion: nn.Module, optimizer: torch.optim.Optimizer) -> Dict[str, float]:
xb, yb = xb.to(self.device, non_blocking=True), yb.to(self.device, non_blocking=True)
optimizer.zero_grad(set_to_none=True)
with autocast(enabled=self.cfg.enabled):
logits = self.model(xb)
loss = criterion(logits, yb)
self.scaler.scale(loss).backward()
if self.cfg.max_grad_norm:
self.scaler.unscale_(optimizer)
grad_norm = torch.nn.utils.clip_grad_norm_(
self.model.parameters(), self.cfg.max_grad_norm
)
else:
grad_norm = torch.tensor(0.0)
before = self.scaler.get_scale()
self.scaler.step(optimizer)
self.scaler.update()
if self.scaler.get_scale() < before:
self.skipped_steps += 1
return {"loss": float(loss.detach()), "grad_norm": float(grad_norm),
"scale": float(self.scaler.get_scale())}
def benchmark(self, loader, criterion, optimizer, steps: int = 50) -> Dict[str, float]:
self.model.train()
started = time.perf_counter()
for i, (xb, yb) in enumerate(loader):
if i >= steps:
break
self.step(xb, yb, criterion, optimizer)
elapsed = time.perf_counter() - started
return {
"steps_per_sec": steps / elapsed,
"ms_per_step": elapsed / steps * 1000,
"skipped_steps": self.skipped_steps,
}
model = nn.Sequential(nn.Linear(64, 256), nn.ReLU(), nn.Linear(256, 10))
trainer = AmpTrainer(model, torch.device("cuda" if torch.cuda.is_available() else "cpu"))
print("amp ready, skipped:", trainer.skipped_steps)
Watch skipped_steps. Occasional skips are normal while the scaler finds its level; a counter that climbs steadily means you should lower the initial scale or add gradient clipping, because each skip stalls progress for that step. If loss goes to NaN during a run, the first suspects are the learning rate, an unclipped gradient spike, and inputs whose scale changed after preprocessing.
The data loader is usually the bottleneck
Model and optimizer are fast; getting bytes to the device is not. Four settings matter: num_workers high enough that prefetching keeps ahead of compute, pin_memory=True so host-to-device copies use the fast path, persistent_workers=True to avoid re-forking every epoch, and a prefetch_factor that keeps a few batches queued per worker. Beyond a point, more workers compete for CPU and memory bandwidth and throughput stops improving â find that plateau empirically rather than setting the number to the core count by reflex.
For very large datasets, consider format and access pattern before adding workers. Columnar formats with contiguous row groups beat row-oriented files for random access, and an IterableDataset that streams sharded files avoids the index-build cost entirely. Whatever you choose, keep an eye on the ratio of data-wait time to total step time; when wait exceeds roughly a fifth of the step, no amount of kernel optimization will rescue your throughput.
Measuring throughput honestly
Comparisons only mean something when the measurement is fixed: same batch size, same sequence or input lengths, same number of warm-up steps discarded, same precision mode, and step time reported as a distribution rather than a single average. A benchmark that includes the first fifty steps will show you compilation and cache warm-up, not steady state; a benchmark on synthetic uniform inputs will hide the tail caused by the longest sequences in your real data.
Record the effective batch size alongside every number. Doubling devices while halving per-device batch keeps the global batch constant but changes gradient noise and convergence, so a "2Ã faster" claim that also changed the effective batch is not a controlled comparison. The honest report includes throughput, memory high-water mark, precision mode, world size, and the dataset shape â five fields that let a colleague reproduce the number instead of trusting it.
đĄProfile before you scale
Common Mistakes
Forgetting sampler.set_epoch each epoch
Fix: Call it every epoch so ranks reshuffle differently, or all ranks repeat the same shard order.
Logging and checkpointing from every rank
Fix: Restrict writes to rank zero and broadcast or share configuration instead.
Raising num_workers without measuring
Fix: Sweep worker counts and stop at the throughput plateau; extra workers then just compete for CPU.
Claiming speedups from uncontrolled benchmarks
Fix: Hold batch size, data shape, precision, and warm-up constant, and report the distribution of step times.
Best Practices
- Break step time into data, transfer, forward, backward, and optimizer segments
- Use pinned memory with non-blocking transfers to overlap input with compute
- Combine AMP with gradient clipping and watch the skip counter
- Checkpoint optimizer state as well as weights so resumes continue cleanly
- Record world size and effective batch with every throughput claim
Interview Questions
Q1: Data parallelism or model parallelism â how do you decide?
Whether the model fits on one device. If it does, data parallelism scales far better; model and pipeline parallelism are memory-driven choices with real communication costs.
Q2: Why does mixed precision need a gradient scaler?
16-bit underflows small gradients; scaling before backward keeps them representable, and steps with overflow are skipped while the scale adjusts.
Q3: Why is training throughput not linear in GPU count?
Gradient all-reduce, stragglers, and fixed per-step overheads grow with world size, so efficiency per doubling typically lands around 80 to 90 percent.
Q4: How do you know the data loader is the bottleneck?
GPU utilization sits well below capacity with memory headroom, and instrumented data-wait time dominates the step breakdown.
Key Takeaways
- Profile the step before buying more devices â input starvation is the common cause
- DDP correctness depends on sharded sampling, per-epoch reseeding, and rank-zero writes
- AMP plus scaler plus clipping gives most of the speedup with controlled risk
- Workers, pinned memory, and prefetch must be tuned to a measured plateau
- Controlled benchmarks with reported context are the only comparisons worth acting on