Model Optimization and Distributed Training Parallelism Strategies
Machine LearningModel answerLast updated
Explain key techniques for reducing training and inference cost, then compare how tensor parallelism and pipeline parallelism split work across GPUs.
Model Optimization and Distributed Training Parallelism Strategies
Modern deep learning models — particularly large language models — routinely hit hardware limits during both training and serving. Engineers working on these systems need to understand not just what each optimization does, but why it helps, which bottleneck it addresses, and what it costs.
Part 1: Optimization techniques
Walk through the major categories of optimization used in training and inference:
- Quantization — what bit-width choices exist, when they help and when they don't, and what can go wrong
- Pruning and sparsity — the difference between unstructured and structured approaches, and what hardware support looks like
- Knowledge distillation — how a student learns from a teacher, and the practical cost of the approach
- Kernel and operator fusion — why combining ops matters, and what FlashAttention is actually doing
- Memory optimizations for training — activation checkpointing, ZeRO/FSDP sharding, gradient accumulation
- Inference-specific techniques — KV caching, continuous batching, speculative decoding
For each, explain the goal, the mechanism, and the trade-offs.
Part 2: Tensor parallelism vs. pipeline parallelism
Compare the two main model parallelism strategies:
- How each one partitions the model
- What communication it requires and when that communication happens
- Whether it reduces latency, increases throughput, or both
- What hardware topology suits each
- Where performance degrades and why
A strong answer ties each technique back to a specific bottleneck (memory capacity, memory bandwidth, compute, communication) rather than treating them as interchangeable options.
Hints
Hint 1
Start by classifying each optimization by the bottleneck it targets — memory capacity, memory bandwidth, or compute — before explaining the mechanism. LLM decode and LLM prefill are bottlenecked differently, which affects which optimizations actually help each phase.
Hint 2
For tensor parallelism, trace one transformer MLP block through the forward pass: where does each GPU hold a slice of the weight matrix, where does local compute happen, and exactly when does the all-reduce fire? Then ask whether that all-reduce can be hidden behind compute, and what happens to efficiency as you increase the number of GPUs.
Hint 3
Pipeline parallelism replaces per-layer collectives with point-to-point sends between stage boundaries — think about why that matters for cross-node bandwidth, and then explain what the pipeline bubble is and why micro-batches are the mitigation.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Framing: always start from the bottleneck
The roofline model divides workloads into compute-bound (arithmetic intensity is high, the GPU's FLOP/s is the limit) and memory-bandwidth-bound (arithmetic intensity is low, HBM bandwidth is the limit). Large matrix multiplications in training and in LLM prefill are compute-bound. LLM autoregressive decode with small batches is bandwidth-bound — every weight is loaded from HBM for a handful of multiply-accumulate operations. Elementwise ops like LayerNorm, GELU, and softmax are almost always bandwidth-bound. This framing determines which optimization actually moves the needle.
Optimization techniques
Quantization
The goal is to represent values in fewer bytes, which reduces both memory footprint and HBM traffic, and enables faster low-precision tensor core operations.
- FP16/BF16 mixed precision is standard for training. FP16 requires explicit loss scaling to avoid underflow; BF16 has a wider exponent range and usually does not.
- FP8 training (Hopper and later, via Transformer Engine with per-tensor scaling) pushes further with minimal accuracy loss.
- INT8/INT4 weight-only quantization (GPTQ, AWQ) targets inference. Weights are stored compressed and dequantized before the matrix multiply, so they help bandwidth-bound decode but not compute-bound prefill.
- SmoothQuant migrates activation outliers into the weight matrix so W8A8 activation quantization becomes viable.
Trade-offs: outlier channels cause accuracy drops. Post-training quantization is cheap but loses more accuracy at very low bit-widths; quantization-aware training recovers it at the cost of a full training run.
Pruning and sparsity
Unstructured pruning can reach 90%+ sparsity on paper but gives little GPU speedup because irregular memory access patterns prevent efficient tensor core utilization. Structured pruning (removing entire heads, channels, or layers) yields real throughput gains at the cost of more accuracy degradation and typically requires fine-tuning. NVIDIA's 2:4 semi-structured sparsity — keeping 2 nonzeros per group of 4 — is the practical middle ground: Ampere and later can roughly double sparse matmul throughput with this pattern.
Knowledge distillation
A smaller student model minimizes a weighted combination of the hard cross-entropy loss and a KL divergence against the teacher's softened output distribution (temperature T > 1 smooths the logits). Variants also match intermediate hidden states. The cost is a full training run plus teacher inference. The benefit: every subsequent inference call is cheaper, and the student often outperforms a from-scratch model of the same size.
Kernel fusion and FlashAttention
Fusing kernels keeps intermediate results in registers or shared memory instead of writing them to HBM and reading them back. A fused bias+GELU replaces two kernel launches and two HBM round-trips with one. FlashAttention is the most impactful example: it tiles Q, K, and V, computes softmax in an online streaming fashion, and never materializes the full N×N attention score matrix in HBM. Memory usage drops from O(N²) to O(N) and HBM traffic falls dramatically for long sequences.
CUDA Graphs serialize a sequence of kernel launches into a single GPU submission, removing CPU-side launch overhead — this matters for small-batch inference where launch latency is a meaningful fraction of total time.
Training memory optimizations
Activation checkpointing discards intermediate activations during the forward pass and recomputes them during backward, saving roughly proportional to the number of checkpointed layers at the cost of ~30% extra compute. ZeRO and PyTorch FSDP shard optimizer states, gradients, and parameters across data-parallel ranks — Adam in mixed precision costs ~16 bytes per parameter, so sharding across 64 GPUs cuts per-GPU overhead to a small fraction. The trade-off is additional all-gather and reduce-scatter collectives.
Inference optimizations
KV caching avoids recomputing key/value projections for past tokens. PagedAttention manages the KV cache in non-contiguous pages to reduce fragmentation. Continuous batching (in-flight batching) keeps GPU utilization high as requests arrive mid-batch. Speculative decoding uses a small draft model to propose several tokens, then verifies them in one forward pass of the large model — latency drops significantly for bandwidth-bound decode.
Tensor parallelism (TP)
TP splits individual weight matrices within a layer across GPUs (Megatron-LM style).
For an MLP: the first linear is column-parallel — each of t GPUs holds 1/t of the output columns, so GELUs execute locally with no communication. The second linear is row-parallel, producing partial output sums. A single all-reduce synchronizes the partial sums and produces the correct full output. Attention is analogous: heads are partitioned across GPUs, and the output projection is row-parallel with one all-reduce.
Communication pattern: ~2 all-reduces per transformer layer in the forward pass, ~2 in the backward pass. Each moves an activation tensor of size roughly batch × sequence × hidden. The all-reduce sits on the critical path and is difficult to fully overlap with compute. Sequence parallelism replaces each all-reduce with a reduce-scatter plus all-gather, keeping total volume the same but also sharding LayerNorm/dropout activations along the sequence axis, which saves activation memory.
When to use: when a single layer's weights or activations don't fit on one device, or when you need lower per-token latency (all GPUs contribute to every token). Keep TP within an NVLink/NVSwitch domain — typically t ≤ 8. Crossing InfiniBand for all-reduces destroys efficiency because the communication-to-compute ratio grows as per-GPU GEMMs shrink and tensor core utilization drops.
Common mistakes: ignoring divisibility constraints (hidden size and head count must divide evenly by t), and scaling TP beyond the NVLink domain.
Pipeline parallelism (PP)
PP assigns contiguous groups of layers to separate GPU stages. A batch is divided into m micro-batches that flow through stage 0 → stage 1 → ... → stage p−1 in sequence.
Communication pattern: point-to-point sends of boundary activations (forward pass) and their gradients (backward pass), approximately batch × sequence × hidden per micro-batch per stage boundary. No collectives, and volume per communication event is much smaller than TP's all-reduces. This makes PP well-suited to cross-node communication over InfiniBand.
Pipeline bubble: in the simplest 1F1B schedule, GPUs are idle while the first micro-batch fills the pipeline and while it drains. Bubble fraction is approximately (p−1)/m. Increasing m amortizes the bubble; interleaved schedules (1F1B with interleaving) reduce it further by assigning non-contiguous stage chunks to each GPU.
When to use: distributing a model across nodes where bandwidth is limited to InfiniBand speeds, or when total parameter count simply requires more GPUs than fit in one NVLink domain.
Common mistakes: setting m too small (large bubble ratio), unbalanced stage partitioning creating a throughput bottleneck at the slowest stage, and forgetting that activation memory for all in-flight micro-batches accumulates across stages.
Choosing between TP and PP
In practice they are combined. TP runs within an NVLink domain for low-latency intra-node communication; PP runs across nodes where only InfiniBand is available. Data parallelism (with ZeRO sharding) runs across replicas. A typical large-scale training job uses 3D parallelism: TP × PP × DP. The sizing decision comes down to whether your bottleneck is per-layer memory (favor TP), cross-node scale (favor PP), or aggregate throughput with enough memory per node (favor DP).