29 minute read

“Scaling from one GPU to thousands.”

TL;DR

Modern AI models are too large for a single GPU, requiring distributed training across hundreds or thousands of devices. This article covers data parallelism with Ring All-Reduce, pipeline and tensor parallelism from Megatron-LM, ZeRO/FSDP for memory-efficient sharding, mixed precision training, gradient checkpointing, FlashAttention, and production concerns like fault tolerance, cost optimization, and debugging. These patterns directly support resource partitioning and the infrastructure behind LLM serving.

A team of draft horses in harness pulling the same heavy load together

1. The Need for Scale

Modern Deep Learning models are massive.

  • GPT-3: 175 Billion parameters.
  • PaLM: 540 Billion parameters.
  • Training Data: Trillions of tokens.

A single NVIDIA A100 GPU (80GB VRAM) cannot hold these models, let alone train them in a reasonable time. To train these models, we must distribute the computation across hundreds or thousands of GPUs.

2. Taxonomy of Parallelism

There are three main dimensions of parallelism in Deep Learning:

  1. Data Parallelism: Split the data across devices. Replicate the model.
  2. Model Parallelism: Split the model across devices. Replicate the data (or split it).
    • Pipeline Parallelism: Split layers across devices (Inter-layer).
    • Tensor Parallelism: Split individual operations (matrices) across devices (Intra-layer).
  3. 3D Parallelism: Combining all the above.

3. Data Parallelism (DP)

This is the simplest and most common form.

Mechanism:

  1. Copy the entire model to every GPU (Worker).
  2. Split the global batch into mini-batches. Assign one mini-batch to each GPU.
  3. Forward Pass: Each GPU computes predictions and loss for its mini-batch.
  4. Backward Pass: Each GPU computes gradients w.r.t. its local data.
  5. Synchronization: Gradients are aggregated (averaged) across all GPUs.
  6. Update: All GPUs update their model weights with the averaged gradients.

3.1. Parameter Server (PS) Architecture

  • Workers: Compute gradients.
  • Parameter Servers: Store global weights.
  • Flow: Workers pull weights -> Compute gradients -> Push gradients to PS -> PS updates weights.
  • Bottleneck: Network bandwidth at the PS.

3.2. Ring All-Reduce

Used in DistributedDataParallel (DDP) (PyTorch) and Horovod.

  • No central server.
  • GPUs are arranged in a logical ring.
  • Each GPU sends data to its neighbor and receives from the other neighbor.
  • Scatter-Reduce: Chunk gradients and reduce them as they pass around the ring.
  • All-Gather: Gather the reduced chunks back to all GPUs.
  • Bandwidth Optimal: Data sent per GPU stays roughly constant (about twice the gradient size) as GPUs are added.

4. Model Parallelism (MP)

When the model doesn’t fit in one GPU’s memory.

4.1. Pipeline Parallelism (PP)

Split the model layers into stages.

  • GPU 1: Layers 1-10
  • GPU 2: Layers 11-20
  • …
  • Naive Approach: GPU 2 waits for GPU 1. Huge “bubble” (idle time).
  • GPipe / PipeDream: Split the mini-batch into micro-batches. Pipeline the execution of micro-batches to fill the bubbles.

4.2. Tensor Parallelism (TP)

Split the tensors (matrices) themselves.

  • Example: Matrix Multiplication Y = XA.
  • Split A into columns A_1, A_2.
  • GPU 1 computes Y_1 = X A_1.
  • GPU 2 computes Y_2 = X A_2.
  • Concatenate Y = [Y_1, Y_2].
  • Requires high-bandwidth interconnect (NVLink) because synchronization happens per layer. Used in Megatron-LM.

5. ZeRO (Zero Redundancy Optimizer)

Standard Data Parallelism replicates the Optimizer States, Gradients, and Parameters on every GPU. This is wasteful.

ZeRO-DP (DeepSpeed):

  • ZeRO-1: Shard Optimizer States. (4x memory reduction).
  • ZeRO-2: Shard Gradients. (8x memory reduction).
  • ZeRO-3: Shard Parameters. (Memory usage scales linearly with number of GPUs).

With ZeRO-3, parameters are fetched on-demand just before the forward/backward pass of a layer and released immediately after. With enough GPUs, this makes trillion-parameter training feasible without each GPU holding the full model.

6. System Design: Designing a Training Cluster

Scenario: Build a cluster to train a 100B parameter model.

6.1. Hardware

  • Compute: NVIDIA H100 or A100 GPUs.
  • Interconnect:
    • Intra-node: NVLink / NVSwitch (900 GB/s per H100, 600 GB/s per A100). Needed for Tensor Parallelism.
    • Inter-node: InfiniBand or RoCE (RDMA over Converged Ethernet) (400 Gbps). Crucial for Data/Pipeline Parallelism.
  • Storage: High-performance parallel file system (Lustre, GPUDirect Storage) to feed data at line rate.

6.2. Network Topology

  • Rail-optimized: All GPU-0s across nodes communicate, all GPU-1s communicate, etc.
  • Non-Blocking Fat Tree: Ensures full bisection bandwidth.

6.3. Fault Tolerance

  • Checkpointing: Save model state frequently to S3/HDFS.
  • Elastic Training: If a node fails, the job should pause, reconfigure (remove bad node), and resume from the last checkpoint automatically (e.g., PyTorch Elastic / TorchRun).
  • Checkpoint interval: Checkpointing too often wastes time writing state; too rarely loses work on every failure. Young’s classic approximation gives the interval that minimizes total waste, where C is the time to write one checkpoint and M is the mean time between failures for the whole job:
\[\tau_{\text{opt}} \approx \sqrt{2 C M}\]

For example, if a checkpoint takes 2 minutes and the cluster sees a failure every 8 hours on average, the interval is about √(2 × 2 × 480) ≈ 44 minutes. Asynchronous checkpointing (writing from a copy in host memory while training continues) shrinks C and lets you checkpoint more often.

7. Communication Primitives (NCCL)

Understanding the underlying collective operations is key.

  • Broadcast: One sends to all.
  • Scatter: One splits data and sends parts to all.
  • Gather: All send to one.
  • All-Gather: Everyone gathers data from everyone.
  • Reduce: Aggregate data to one (Sum, Min, Max).
  • All-Reduce: Aggregate data and distribute result to all. (The workhorse of DP).

8. Deep Dive: Gradient Accumulation

If you can’t fit a large enough batch size for convergence (e.g., batch size 32) even with parallelism:

  • Run forward/backward for batch size 1.
  • Don’t update weights.
  • Accumulate gradients.
  • Repeat 32 times.
  • Update weights.
  • Simulates a larger batch size at the cost of compute time (no extra memory).

9. Case Study: Training GPT-3

  • Architecture: Transformer Decoder.
  • Parallelism:
    • Tensor Parallelism: Within each node (8 GPUs).
    • Pipeline Parallelism: Across nodes.
    • Data Parallelism: Across replicas of the pipeline.
  • Infrastructure: V100 GPUs on part of a high-bandwidth cluster provided by Microsoft, according to the GPT-3 paper.
  • Typical challenges at this scale: Stragglers (slow nodes), Silent Data Corruption (bit flips), Loss Spikes.

10. Deep Dive: Collective Communication (Ring All-Reduce)

The efficiency of Data Parallelism hinges on the All-Reduce operation. Goal: Every GPU starts with a gradient vector G_i. Every GPU ends with the sum of all the G_i.

Naive Approach:

  • All GPUs send their gradients to GPU 0 (Gather).
  • GPU 0 sums them.
  • GPU 0 sends the sum back to all GPUs (Broadcast).
  • Bottleneck: GPU 0’s bandwidth. Time scales linearly with N (number of GPUs).

Ring All-Reduce:

  • Topology: GPU 0 -> GPU 1 -> … -> GPU N-1 -> GPU 0.
  • Step 1: Scatter-Reduce:
    • Split the gradient vector into N chunks.
    • In each step, GPU i sends a chunk to GPU i+1 and receives a chunk from GPU i-1.
    • It adds the received chunk to its local chunk and passes it on.
    • After N-1 steps, each GPU holds a fully summed chunk of the gradient vector (different chunk for each GPU).
  • Step 2: All-Gather:
    • Each GPU sends its fully summed chunk to the next neighbor.
    • After N-1 steps, all GPUs have all the fully summed chunks.
  • Complexity:
    • Data transmitted per GPU, for a gradient of K bytes: \(2(N-1)\frac{K}{N} \approx 2K\).
    • Crucially: Nearly independent of N. Latency still grows with N (2(N-1) steps), which is why NCCL also uses tree algorithms at large scale.

11. Deep Dive: ZeRO (Zero Redundancy Optimizer) Details

Let’s break down the memory savings for a model with Ψ parameters. Using Mixed Precision (fp16/bf16) and Adam Optimizer.

Baseline (Standard DDP):

  • Parameters (fp16): 2Ψ bytes.
  • Gradients (fp16): 2Ψ bytes.
  • Optimizer States (fp32):
    • Master Weights: 4Ψ bytes.
    • Momentum: 4Ψ bytes.
    • Variance: 4Ψ bytes.
    • Total Opt States: 12Ψ bytes.
  • Total per GPU: 16Ψ bytes (activations come on top).

ZeRO-1 (Shard Optimizer States):

  • Partition the 12Ψ bytes of optimizer states across N GPUs.
  • Each GPU stores 12Ψ/N.
  • Total per GPU: 4Ψ + 12Ψ/N.
  • Savings: ~4x reduction.

ZeRO-2 (Shard Gradients):

  • Partition the 2Ψ bytes of gradients as well.
  • Each GPU stores (2Ψ + 12Ψ)/N.
  • Total per GPU: 2Ψ + 14Ψ/N.
  • Savings: ~8x reduction.

ZeRO-3 (Shard Parameters):

  • Partition the 2Ψ bytes of parameters too.
  • Total per GPU: 16Ψ/N.
  • Savings: Linear reduction with N.
  • Trade-off: Increased communication. Parameters must be all-gathered before each layer’s forward and backward pass and discarded immediately.
  • Worked example: A 7B-parameter model needs 16 × 7B = 112 GB for weights, gradients and Adam states, which does not fit on one 80 GB GPU. With ZeRO-3 across 8 GPUs that becomes 14 GB per GPU, leaving room for activations.

12. Deep Dive: Pipeline Parallelism (1F1B)

GPipe:

  • Split batch into M micro-batches.
  • Run all M forward passes.
  • Run all M backward passes.
  • Memory Issue: Need to store activations for all M micro-batches until the backward pass starts.

1F1B (One Forward One Backward) - PipeDream:

  • Schedule: Forward 1, Forward 2, …, Backward 1, Forward 3, Backward 2…
  • As soon as the first micro-batch finishes its forward pass at the last stage, it starts its backward pass.
  • This frees up activation memory much earlier.
  • Bubble: The idle time at the start and end of the pipeline.
    • With P pipeline stages and M micro-batches, the idle fraction is \(\frac{P-1}{M+P-1}\), which is about (P-1)/M when M ≫ P.
    • To minimize the bubble, use many more micro-batches than stages (M ≫ P). With 8 stages and 32 micro-batches the bubble is 7/39, about 18%.

13. Deep Dive: Tensor Parallelism (Megatron-LM)

How do we split a Transformer Layer across GPUs?

MLP Layer (A → GeLU → B):

  • Y = GeLU(X A).
  • Split A by columns (A_1, A_2).
  • Each GPU computes Y_i = GeLU(X A_i).
  • Next matrix B is split by rows (B_1, B_2).
  • Each GPU computes its partial product Y_i B_i, because Z = [Y_1, Y_2] · [B_1; B_2] = Y_1 B_1 + Y_2 B_2.
  • All-Reduce: Sum the results Y_1 B_1 + Y_2 B_2 across GPUs.
  • Benefit: Only one All-Reduce needed per MLP block.

Self-Attention Layer:

  • Split Query (Q), Key (K), Value (V) weight matrices by columns (split heads).
  • Each GPU computes attention for a subset of heads.
  • Output projection matrix O is split by rows.
  • All-Reduce: Sum the outputs of the projection.

14. Deep Dive: Network Topologies for AI Clusters

The physical wiring of the cluster determines the maximum possible bandwidth and latency.

1. Fat Tree (Clos Network):

  • Structure: A tree where links near the root have higher bandwidth (fatter) than links near the leaves.
  • Non-Blocking: Guarantees that any node can communicate with any other node at full line rate (if the switch capacity allows).
  • Pros: Predictable performance, easy to route.
  • Cons: Expensive (lots of switches and cables).

2. Torus / Mesh:

  • Structure: Grid-like connection. 2D Torus connects neighbors in X and Y (wrapping around). 3D Torus adds Z.
  • Pros: Cheaper (fewer switches, direct node-to-node links). Good for local communication (stencil patterns).
  • Cons: Higher latency for distant nodes (multi-hop).

3. Dragonfly:

  • Structure: Groups of routers fully connected within the group, and groups are fully connected to other groups.
  • Pros: Low diameter (max 3 hops for any pair), highly scalable.
  • Cons: Complex routing (needs adaptive routing to avoid congestion).

NVIDIA DGX SuperPOD: Reference designs use a rail-optimized, non-blocking fat tree with one InfiniBand NIC per GPU (200 Gb/s HDR on DGX A100 systems, 400 Gb/s NDR on DGX H100 systems).

15. Deep Dive: Framework Internals (PyTorch DDP)

How does DistributedDataParallel actually work?

1. Bucketing:

  • Gradients are small (e.g., bias vector). Sending millions of tiny packets kills performance (latency overhead).
  • DDP groups parameters into Buckets (e.g., 25MB).
  • It waits for all gradients in a bucket to be computed, then triggers one All-Reduce for the entire bucket.

2. Gradient Hooks:

  • DDP registers autograd hooks on every parameter.
  • When a gradient is ready, the hook fires.
  • The hook copies the gradient into the bucket buffer.

3. Overlap (Compute-Comm):

  • While the backward pass is computing gradients for layer L-1, the All-Reduce for layer L (already in bucket) is running asynchronously on the network card.
  • Goal: Hide communication time behind computation time.

16. Data pipeline: sharding and sequence packing

At thousands of GPUs, a slow input pipeline idles the whole cluster. Two habits matter most.

1. Shard the dataset and give every reader a disjoint slice. Store the corpus as many files (e.g., 10K-100K samples each, as WebDataset tars or TFRecords), assign shards round-robin to ranks, and split again across each rank’s DataLoader workers. Forgetting the second split is a common bug: every worker then streams the same shards and the model sees duplicated data.

from torch.utils.data import IterableDataset, get_worker_info

class ShardedDataset(IterableDataset):
    """Streams records from the shards assigned to this rank and loader worker."""

    def __init__(self, shard_paths: list[str], rank: int, world_size: int):
        super().__init__()
        self.shard_paths = shard_paths[rank::world_size]  # shards for this rank

    def __iter__(self):
        paths = self.shard_paths
        info = get_worker_info()
        if info is not None:  # split again across DataLoader workers
            paths = paths[info.id::info.num_workers]
        for path in paths:
            yield from self._read_shard(path)

    def _read_shard(self, path: str):
        # Read compressed records and yield token or audio sequences lazily
        raise NotImplementedError

2. Cut padding. Variable-length sequences padded to the batch maximum waste compute. Either bucket sequences by length so each batch pads only to its bucket size, or pack several sequences into one fixed-length block (with attention masks that stop them attending to each other).

def bucket_by_length(sequences, bucket_sizes):
    """Assign each sequence to the smallest bucket that fits it."""
    buckets = {b: [] for b in bucket_sizes}
    for seq in sequences:
        for b in bucket_sizes:
            if len(seq) <= b:
                buckets[b].append(seq)
                break
    return buckets

print({b: len(s) for b, s in bucket_by_length([[1] * n for n in (3, 60, 120, 500)], [64, 128, 512]).items()})
# {64: 2, 128: 1, 512: 1}

17. Case Study: LLaMA 2 Training Infrastructure

The Llama 2 paper (Touvron et al., 2023) is unusually specific about hardware:

  • Clusters: Meta’s Research Super Cluster (RSC) and internal production clusters, both with NVIDIA A100 GPUs.
  • Interconnect: RSC uses NVIDIA Quantum InfiniBand; the production cluster uses RoCE (RDMA over Converged Ethernet). Both have 200 Gbps endpoints.
  • Finding: RoCE, which is much cheaper, scaled almost as well as InfiniBand up to 2,000 GPUs for their workload.
  • Compute: About 1.72M A100 GPU-hours for the 70B model and 3.3M GPU-hours across the model family.
  • Optimizer settings: AdamW with gradient clipping at 1.0 and weight decay 0.1.

Training Stability:

  • Loss Spikes: Often caused by “bad” data or numerical instability (fp16 overflow).
  • Fix: Gradient clipping, AdamW, and skipping batches with NaN gradients. When spikes persist, the PaLM paper describes restarting from a checkpoint about 100 steps before the spike and skipping roughly 200 to 500 data batches.

18. Deep Dive: Asynchronous vs Synchronous SGD

Synchronous SGD (Standard):

  • Wait for ALL workers to finish.
  • Update = Average of all.
  • Pros: Mathematically equivalent to large-batch SGD. Converges well.
  • Cons: Straggler problem (fastest worker waits for slowest).

Asynchronous SGD (parameter server; Hogwild! is the shared-memory variant):

  • Workers push gradients to PS whenever they are done.
  • PS updates weights immediately.
  • Workers pull new weights.
  • Pros: No waiting. High hardware utilization.
  • Cons: Stale Gradients. A worker computes its gradient on the weights at step t, but by the time it pushes, the global weights are at step t+10. The gradient is “stale” and may point in the wrong direction.
  • Solution: Rarely used for large models now. Synchronous SGD, optionally with backup workers that let each step ignore the slowest few workers (Chen et al., 2016), is preferred.

19. Interview Questions

  1. Explain All-Reduce. How does Ring All-Reduce work? What is its complexity? (Each GPU sends 2(N-1)K/N bytes, about 2K.)
  2. Data Parallelism vs. Model Parallelism. When to use which?
  3. What is the “Stale Gradient” problem? In Asynchronous SGD, workers might compute gradients on old weights. How does Synchronous SGD fix this?
  4. How does ZeRO-3 work? How does it handle communication overhead? (Prefetching).
  5. Calculate Memory Footprint. For a model with P parameters, using Adam optimizer and mixed precision.
    • Parameters: 2P bytes (fp16).
    • Gradients: 2P bytes (fp16).
    • Optimizer States: 12P bytes (fp32 copy of params, momentum, variance).
    • Total: 16P bytes, before activations. For 1B params, ~16GB.

20. Deep Dive: Gradient Checkpointing (Activation Recomputation)

Problem: During backprop, we need activations from the forward pass. For a 100-layer model, storing all activations requires massive memory. Solution: Trade compute for memory.

Algorithm:

  1. Forward Pass: Only save activations at checkpoints (e.g., every 10 layers). Discard intermediate activations.
  2. Backward Pass: When we need activations for layer 15:
    • Re-run forward from checkpoint 10 to layer 15.
    • Compute gradients.
    • Discard the recomputed activations.

Memory Savings:

  • Without checkpointing: O(N) memory for N layers.
  • With a checkpoint every √N layers: O(√N) memory.
  • Cost: Roughly one extra forward pass per training step. Since the backward pass costs about twice the forward, that is about 33% more compute.

PyTorch Implementation:

import torch.nn as nn
from torch.utils.checkpoint import checkpoint

class MyModel(nn.Module):
    def __init__(self, layer1: nn.Module, layer2: nn.Module):
        super().__init__()
        self.layer1, self.layer2 = layer1, layer2

    def forward(self, x):
        # Recompute these blocks' activations during backward instead of storing them
        x = checkpoint(self.layer1, x, use_reentrant=False)
        x = checkpoint(self.layer2, x, use_reentrant=False)
        return x

21. Deep Dive: Mixed Precision Training (FP16/BF16)

Motivation: FP32 (32-bit floats) are slow and memory-hungry. FP16 (16-bit) uses half the memory and runs much faster on Tensor Cores. Challenge: FP16 has limited range (about 6 × 10⁻⁸ for the smallest subnormal up to 65,504). Gradients can underflow (become zero) or overflow.

Solution: Mixed Precision (NVIDIA Apex / PyTorch AMP):

  1. Master Weights: Keep FP32 copy of weights.
  2. Forward/Backward: Use FP16 for matrix multiplications (fast).
  3. Loss Scaling: Multiply loss by a large number (e.g., 1024) before backprop. This shifts gradients into FP16’s representable range.
  4. Unscale Gradients: Divide gradients by the scale factor before updating FP32 master weights.
  5. Update: Update FP32 weights, then copy to FP16 for next iteration.

BFloat16 (BF16):

  • Same exponent range as FP32 (8 bits), but only 7 bits for mantissa.
  • Advantage: No loss scaling needed. Easier to use.
  • Disadvantage: Fewer mantissa bits than FP16 (7 vs 10), so values are coarser.
  • Used in: Google TPUs, NVIDIA A100 and later, AMD MI200 and later.

22. Deep Dive: FlashAttention (Memory-Efficient Attention)

Standard Attention: O(N^2) memory for the attention matrix. For N=4096 tokens, this is about 16.8M elements (about 32 MB in FP16) per attention head, per sequence.

FlashAttention (Dao et al., 2022):

  • Idea: Never materialize the full N × N attention matrix.
  • Algorithm:
    1. Tile Q, K, V into blocks that fit in SRAM (on-chip cache).
    2. Compute attention for each block.
    3. Use online softmax (incremental computation) to avoid storing intermediate results in HBM (slow GPU memory).
  • Result: 2-4x speedup in the paper’s benchmarks, with memory linear in sequence length, which makes much longer contexts trainable.

Impact on Distributed Training:

  • Reduces activation memory, allowing larger batch sizes or longer sequences.
  • Standard in open LLM training stacks (the original LLaMA used the memory-efficient attention from xformers).

23. Deep Dive: FSDP (Fully Sharded Data Parallel)

PyTorch FSDP is PyTorch’s native ZeRO-3-style sharding. Newer releases also offer FSDP2 (fully_shard), which shards per parameter. Key Features:

  1. Auto-Wrapping: Automatically wraps model layers for sharding.
  2. CPU Offloading: Can offload parameters to CPU RAM when not in use, fitting larger models on fewer GPUs at a large speed cost.
  3. Mixed Precision: Native support for BF16.

Usage:

import functools

import torch
from torch.distributed.fsdp import FullyShardedDataParallel as FSDP, MixedPrecision
from torch.distributed.fsdp.wrap import transformer_auto_wrap_policy

# MyTransformer / MyTransformerBlock stand in for your model classes
wrap_policy = functools.partial(
    transformer_auto_wrap_policy, transformer_layer_cls={MyTransformerBlock}
)
bf16_policy = MixedPrecision(
    param_dtype=torch.bfloat16, reduce_dtype=torch.bfloat16, buffer_dtype=torch.bfloat16
)
model = FSDP(MyTransformer(), auto_wrap_policy=wrap_policy, mixed_precision=bf16_policy)

When to use FSDP vs DDP:

  • DDP: Model fits in one GPU. Simple, fast.
  • FSDP: Model doesn’t fit. Need memory efficiency.

24. Production Deployment: Monitoring & Observability

Training a model for weeks/months requires robust monitoring.

Metrics to Track:

  1. Loss Curves: Train/Val loss per step. Detect divergence early.
  2. Gradient Norms: Sudden spikes indicate instability.
  3. GPU Utilization: Should be >90%. If low, data loading is the bottleneck.
  4. Communication Time: Time spent in All-Reduce. Should be <10% of step time.
  5. Throughput: Tokens/second. Track degradation over time (memory leaks, stragglers).

Tools:

  • TensorBoard / Weights & Biases: Visualize metrics.
  • NVIDIA DCGM (Data Center GPU Manager): Monitor GPU health (temperature, power, ECC errors).
  • Prometheus + Grafana: Cluster-wide metrics.

Alerting:

  • Loss NaN: Immediate rollback.
  • GPU Failure: Auto-restart with elastic training.
  • Slow Node: Blacklist and redistribute work.

25. Production Deployment: Cost Optimization

Public estimates put a single GPT-3 training run in the millions of dollars at 2020 cloud prices. Before optimizing, estimate the bill.

Back-of-the-envelope example (illustrative prices): a 1B-parameter Transformer trained on 1T tokens on 128 A100s at an assumed $3 per GPU-hour.

  • Assume ~10,000 tokens/sec per GPU, so 1.28M tokens/sec in total.
  • 1T tokens ÷ 1.28M tokens/sec ≈ 781,000 s ≈ 9 days.
  • GPU cost per day: 128 × $3 × 24 h = $9,216, so the run costs about $83,000.
  • Sanity check: training takes about 6 FLOPs per parameter per token, so 6 × 10⁹ × 10¹² = 6 × 10²¹ FLOPs. Over 9 days on 128 GPUs that is about 19% of the A100’s 312 TFLOPS BF16 peak, a conservative utilization figure; better kernels and larger batches push it higher.

1. Spot Instances:

  • Use spot or preemptible capacity, which is much cheaper than on-demand (AWS advertises discounts of up to 90%).
  • Risk: Can be preempted.
  • Mitigation: Frequent checkpointing + elastic training.

2. Gradient Accumulation:

  • Simulate large batch size without needing more GPUs.
  • Example: 8 GPUs, batch size 4 per GPU, accumulate 8 steps = effective batch size 256.

3. Selective Precision:

  • Use FP16 for most layers, FP32 for sensitive layers (LayerNorm, Softmax).

4. Data Loading Optimization:

  • Prefetching: Load next batch while GPU is computing.
  • Compression: Store data in compressed format (Parquet, Arrow).
  • Sharding: Shard dataset across nodes to avoid network bottleneck.

26. Deep Dive: Bandwidth Analysis & Bottleneck Detection

Theoretical Peak Performance: For a model with P parameters and batch size B:

  • Compute: 2 × P × B FLOPs per forward pass (matrix multiplications).
  • Memory Bandwidth: 2 × P bytes to load weights (fp16).

Roofline Model:

  • Arithmetic Intensity (AI): FLOPs / Bytes.
  • For Transformers: AI ≈ 2PB / 2P = B (the batch size, in tokens).
  • A100 GPU:
    • Peak Compute: 312 TFLOPS (fp16).
    • Peak Bandwidth: about 2 TB/s.
    • Ridge Point: 312 × 10¹² FLOPs/s ÷ 2 × 10¹² bytes/s ≈ 156 FLOPs/byte.
  • If B is below roughly 156 tokens per weight load, we are memory-bound; above it, compute-bound. (Attention and KV cache traffic shift the real crossover, so measure.)

Implication:

  • Small batch sizes (B=1, inference) are memory-bound. Batch more requests, quantize weights, and cut memory traffic.
  • Large batch sizes (B=256, training) are compute-bound. Need to optimize kernels (FlashAttention).

27. Deep Dive: Debugging Distributed Training

Common Issues:

1. Hanging (Deadlock):

  • Symptom: Training freezes. No error message.
  • Cause: One GPU is waiting for All-Reduce, but another GPU crashed before reaching it.
  • Debug: Set NCCL_DEBUG=INFO. Check which GPU is stuck.
  • Fix: Add timeouts to collective operations.

2. Loss Divergence:

  • Symptom: Loss becomes NaN after a few steps.
  • Cause: Gradient explosion, bad data, or numerical instability.
  • Debug:
    • Log gradient norms per layer.
    • Check for NaN/Inf in activations.
    • Reduce learning rate.
  • Fix: Gradient clipping, mixed precision with loss scaling.

3. Slow Training:

  • Symptom: Throughput is 50% of expected.
  • Cause: Communication overhead, data loading bottleneck, or stragglers.
  • Debug:
    • Profile with torch.profiler or NVIDIA Nsight.
    • Check GPU utilization (nvidia-smi dmon).
    • Measure communication time vs compute time.
  • Fix:
    • Increase batch size (reduce communication frequency).
    • Use faster interconnect (InfiniBand).
    • Optimize data loading (more workers, prefetching).

28. Advanced Topic: Sequence Parallelism

For very long sequences (e.g., 100K tokens), activations along the sequence dimension stop fitting in memory. Sequence Parallelism (Megatron-LM, Korthikanti et al., 2022):

  • Tensor parallelism already splits attention and MLP work, but LayerNorm and dropout activations are still replicated on every GPU.
  • Sequence parallelism splits those regions along the sequence dimension, replacing each all-reduce with a reduce-scatter plus all-gather of the same total volume.

Context Parallelism / Ring Attention:

  • For the attention itself, split the sequence across GPUs and pass key/value blocks around a ring, so each GPU attends its query chunk to every key/value block.
  • Optimization: Overlap the key/value transfers with attention compute.

29. Advanced Topic: Expert Parallelism (MoE)

Mixture of Experts (MoE):

  • Replace the MLP layer with N expert MLPs.
  • A router (gating network) decides which expert(s) to use for each token.
  • Benefit: Increase model capacity without increasing compute (only 1-2 experts are active per token).

Expert Parallelism:

  • Place each expert on a different GPU.
  • Tokens are routed to the appropriate GPU.
  • Challenge: Load imbalance (some experts get more tokens).
  • Solution: Auxiliary loss to encourage balanced routing.

Example: Switch Transformer (Google, Fedus et al., 2021):

  • The largest variant, Switch-C, has about 1.6 trillion parameters.
  • 2,048 experts per MoE layer, with one expert active per token.
  • Trained with expert parallelism + data parallelism.

30. Summary & Best Practices

Choosing the Right Parallelism Strategy:

  • Model fits in 1 GPU: Use DDP (Data Parallelism).
  • Model fits in 1 node (8 GPUs): Use Tensor Parallelism (Megatron).
  • Model doesn’t fit in 1 node: Use Pipeline Parallelism + Tensor Parallelism.
  • Model is HUGE (>100B): Use 3D Parallelism (DP + TP + PP) or FSDP/ZeRO-3.

Optimization Checklist:

  1. ✅ Mixed Precision (BF16).
  2. ✅ Gradient Checkpointing.
  3. ✅ FlashAttention.
  4. ✅ Fused Kernels (AdamW, LayerNorm).
  5. ✅ Gradient Accumulation (if batch size is limited).
  6. ✅ Data Loading (prefetch, multiple workers).
  7. ✅ Profiling (find bottlenecks).

31. Common Pitfalls

  • OOM (Out of Memory): Not using gradient checkpointing (activation recomputation) or mixed precision.
  • Communication Overhead: Using Ethernet instead of InfiniBand for large models.
  • Uneven Load Balancing: In Pipeline Parallelism, if layers have different compute costs, some GPUs wait.
  • Batch Norm: Standard Batch Norm only sees the local batch. Need SyncBatchNorm to compute statistics across all GPUs.
  • Data Sharding: Not using a DistributedSampler (every worker sees the same data) or forgetting sampler.set_epoch(epoch) (the same shuffle every epoch).
  • Learning Rate Scaling: When increasing batch size from 256 to 2048, scale the LR proportionally with warmup (the linear scaling rule from Goyal et al., 2017, for SGD; Adam-style optimizers usually need retuning).

32. Real-World Deployment: Kubernetes for ML

Challenges:

  • GPUs are expensive. Need efficient scheduling.
  • Jobs can fail. Need auto-restart.
  • Multi-tenancy. Need isolation.

Kubeflow:

  • Kubernetes-native ML platform.
  • Components:
    • TFJob / PyTorchJob: Operators for distributed training.
    • Katib: Hyperparameter tuning.
    • KServe (formerly KFServing): Model serving.

Example PyTorchJob:

apiVersion: kubeflow.org/v1
kind: PyTorchJob
metadata:
  name: gpt-training
spec:
  pytorchReplicaSpecs:
    Master:
      replicas: 1
      template:
        spec:
          containers:
          - name: pytorch
            image: pytorch/pytorch:2.0.0-cuda11.7-cudnn8-runtime
            command: ["python", "train.py"]
            resources:
              limits:
                nvidia.com/gpu: 8
    Worker:
      replicas: 15
      template:
        spec:
          containers:
          - name: pytorch
            image: pytorch/pytorch:2.0.0-cuda11.7-cudnn8-runtime
            command: ["python", "train.py"]
            resources:
              limits:
                nvidia.com/gpu: 8

33. Conclusion

Distributed training is the backbone of modern AI. From GPT to Stable Diffusion, every large model relies on these techniques. Key Takeaways:

  • Start Simple: Use DDP for models that fit in one GPU.
  • Scale Gradually: Add Tensor/Pipeline Parallelism as needed.
  • Optimize Aggressively: Mixed precision, gradient checkpointing, FlashAttention are non-negotiable.
  • Monitor Everything: Loss, gradients, GPU utilization, communication time.
  • Expect Failures: Checkpointing and elastic training are essential.

The future of AI depends on our ability to train ever-larger models efficiently. Mastering distributed training is no longer optional, it’s a core skill for ML engineers.

FAQ

When should you use data parallelism vs model parallelism?

Use data parallelism (DDP) when the model fits on a single GPU, as it is the simplest and most efficient approach. When the model exceeds single-GPU memory, use tensor parallelism within a node (8 GPUs connected by NVLink) since it requires high-bandwidth interconnects. Use pipeline parallelism across nodes for very large models. For models over 100B parameters, use 3D parallelism (DP + TP + PP) or FSDP/ZeRO-3 which provides memory-efficient data parallelism by sharding parameters across GPUs.

How does ZeRO-3 reduce memory usage for large model training?

Standard data parallelism replicates all parameters, gradients, and optimizer states on every GPU, using 16 bytes per parameter with mixed precision and Adam. ZeRO-3 shards all three across N GPUs, reducing per-GPU memory to 16P/N bytes. Parameters are gathered via all-gather before each layer’s forward/backward pass and released immediately after, trading increased communication for linear memory scaling with the number of GPUs.

What is FlashAttention and why is it critical for LLM training?

Standard attention materializes the full N x N attention matrix in slow HBM memory. FlashAttention tiles Q, K, V into blocks that fit in fast on-chip SRAM and uses online softmax for incremental computation, never writing the full matrix to HBM. This provides 2-4x speedup, dramatically reduces activation memory, and enables training with 64K+ context lengths. It is standard in open LLM training stacks.

How do you handle GPU failures during multi-week training runs?

Use frequent checkpointing to distributed storage like S3 or HDFS, elastic training frameworks like TorchElastic that automatically reconfigure when nodes fail or are preempted, gradient norm monitoring to detect silent data corruption via loss spikes, and automatic rollback to previous checkpoints when corruption is detected. Kubernetes operators like PyTorchJob from Kubeflow handle pod scheduling and restart automatically. See resource partitioning for cluster-level fault tolerance patterns.