Tensor Parallelism vs. Pipeline Parallelism for Large Transformers
Medium · Machine Learning · Software Engineer · Technical Screen
Prompt
Compare tensor parallelism (TP) and pipeline parallelism (PP) when training or serving a transformer model whose footprint exceeds a single accelerator. Detail how each strategy slices the model, what data transfers it introduces on the network, and how you decide whether to use one or combine both.
Because no fixed parameter count, cluster interconnect, or latency SLA is given, state what hardware and workload factors you would clarify first (such as whether weights, optimizer states, or activations cause the out-of-memory error, intra-node vs. inter-node link speeds, batch size, and sequence length). Contrast training throughput against autoregressive token generation without treating either strategy as universally faster.
Scope & Expectations
- Memory diagnosis and partitioning: Separate weight, optimizer-state, and activation bottlenecks, then show how TP splits matrices within each transformer block while PP divides layers into sequential stages.
- Communication vs. hardware topology: Contrast TP's per-layer collective synchronizations (
all-reduceorreduce-scatter/all-gather) against PP's stage-boundary point-to-point transfers, explaining how link bandwidth and latency govern each. - Scheduling, bubbles, and inference latency: Explain pipeline idle bubbles, micro-batching schedules, and why compute-bound training/prefill behaves very differently from memory-bandwidth-bound autoregressive decoding.
- Hybrid 3D layouts: Describe when and how production clusters compose intra-node TP, inter-node PP, and data parallelism.
Step-by-step walkthrough
Diagnose why the model does not fit on one GPU
Before picking a parallelism strategy, clarify which memory component overflows a single GPU, what interconnect links the GPUs, and whether the workload is high-throughput training or low-latency serving.
Use a concrete running example: a dense decoder-only transformer with hidden width
h = 8192,60layers, a4hfeed-forward network (MLP), and a32,000-token tied vocabulary. Each layer holds roughly12 * h^2 ≈ 805Mparameters (4 * h^2across attention'sQ, K, V, Omatrices plus8 * h^2across the MLP's up and down matrices). Across60layers plus32,000 * 8192 ≈ 0.26Bembedding parameters, the model has 48.6B parameters:Inference weights (bf16, 2 bytes/param): 48.6e9 * 2 B ≈ 97.2 GB (plus KV cache) Training states (mixed-precision Adam, 16 B): 48.6e9 * 16 B ≈ 778.0 GB (plus activations) 16 B/param = bf16 weights (2) + bf16 grads (2) + fp32 master weights (4) + Adam m (4) + Adam v (4)On
80 GBGPUs, inference needs at least2GPUs for weights alone, and training needs at least10GPUs before counting activations:- If only optimizer states and gradients overflow: Data parallelism runs separate input batches across GPU replicas; pairing it with ZeRO / FSDP (Fully Sharded Data Parallel, which shards optimizer states, gradients, and optionally weights across data-parallel GPUs and gathers each layer just in time) can fit training without splitting layer math at all.
- If training activations overflow: Activation recomputation (gradient checkpointing — discarding intermediate layer activations during the forward pass and recomputing them during backward at ~33% extra FLOPs) and smaller micro-batches are the first tools.
- If weights themselves (or a single layer's activations) exceed one GPU, or serving latency requires parallel weight reads: We split the model itself via tensor parallelism (splitting matrices inside every layer) or pipeline parallelism (splitting the stack of layers across stages).
Tensor parallelism: split matrices inside every layer
Tensor parallelism (TP) partitions each individual layer's weight matrices across
tGPUs so alltGPUs compute on the exact same tokens simultaneously. Consider Megatron-LM's standard split of a two-layer MLPY = GeLU(X @ A) @ Bacrosst = 2GPUs:- Column-parallel first layer (
A = [A_0 | A_1]): SlicingAvertically gives each GPU4h / tcolumns. BecauseGeLUacts element-wise on each feature independently,GeLU(X @ A_i)requires zero communication! - Row-parallel second layer (
Bstacked horizontally as[B_0 ; B_1]): GPUimultiplies its localGeLU(X @ A_i)slice byB_i, producing a partial full-width[tokens, h]matrix. - One
all-reduceat the end: An all-reduce is a collective operation that sums matching tensors across alltGPUs and leaves the identical totalY = Y_0 + Y_1on every GPU.
Input X [tokens, h] (replicated on GPU 0 and GPU 1) | | v v X @ A_0 [tokens, 2h] X @ A_1 [tokens, 2h] (A split by columns) | | GeLU(.) GeLU(.) (element-wise: no comm!) | | (.) @ B_0 [tokens, h] (.) @ B_1 [tokens, h] (B split by rows) \ / +-----> All-Reduce (sum) <-------+ | Output Y = Y_0 + Y_1 [tokens, h] on both GPUsMulti-head attention splits the exact same way across heads:
Q, K, Vprojections are column-parallel so each GPU ownsnum_heads / theads (requiringnum_headsto be divisible byt), softmax attention runs completely locally per head, and the output projectionOis row-parallel followed by oneall-reduce.import numpy as np rng = np.random.default_rng(0) tokens, h, t = 4, 8, 2 x = rng.standard_normal((tokens, h)) A = rng.standard_normal((h, 4 * h)) B = rng.standard_normal((4 * h, h)) def gelu(z): return 0.5 * z * (1.0 + np.tanh(0.7978845608 * (z + 0.044715 * (z ** 3)))) full_output = gelu(x @ A) @ B # Split A by columns (axis=1) and B by matching rows (axis=0) across t = 2 devices A_shards = np.split(A, t, axis=1) B_shards = np.split(B, t, axis=0) partial_outputs = [gelu(x @ A_shards[i]) @ B_shards[i] for i in range(t)] tp_output = sum(partial_outputs) # simulates the all-reduce sum across devices assert np.allclose(full_output, tp_output)Notice what TP divides by
t: weights, gradients, optimizer states, and large4h/ per-head intermediate activations. Layer inputs/outputs ([tokens, h]) and norms (LayerNorm/RMSNorm) stay replicated unless paired with sequence parallelism — splitting those residual and norm tensors along the token axis and replacing eachall-reducewith areduce-scatterplusall-gatherof identical total byte volume.- Column-parallel first layer (
Tensor-parallel communication cost and interconnect limits
Every transformer block executes 2
all-reducesin the forward pass (one after attention, one after the MLP) and 2all-reducesin the backward pass — 4 collectives per layer per training step, directly on the critical path because the next sublayer cannot start until the sum finishes.Check the numbers on our
h = 8192model witht = 8GPUs,bf16activations (2bytes), and a micro-batch of4,096tokens (2sequences of length2,048). Assume400 TFLOP/ssustained compute per GPU,300 GB/sunidirectional send bandwidth per GPU inside one server (e.g., high-speed NVLink), and25 GB/sunidirectional across servers (one200 Gb/snetwork card per GPU):Activation tensor [4096, 8192] in bf16: 4096 * 8192 * 2 B = 67.1 MB Bytes sent per GPU in 1 ring all-reduce: 2 * ((t - 1) / t) * 67.1 MB = 117.4 MB Forward bytes sent per layer (2 all-reduces): 2 * 117.4 MB = 234.9 MB Forward compute per layer per GPU: (24 * 4096 * 8192^2 / 8) FLOP = 0.825 TFLOP (attention score matmuls at seq_len 2048 add ~0.034 TFLOP, ~4%) -> ~2.1 ms at 400 TFLOP/s Forward communication time per layer: 234.9 MB / 300 GB/s ≈ 0.8 ms (intra-server) 234.9 MB / 25 GB/s ≈ 9.4 ms (inter-server!)Inside one fast server,
0.8 msis manageable (and partially overlappable with tiled matmul kernels). Across servers,9.4 msis 4.5x slower than the math itself! Increasing batch size never fixes this ratio because both bytes (O(tokens * h)) and per-GPU compute (O(tokens * h^2 / t)) scale linearly withtokens. Pushingtlarger also shrinksh^2 / twhile keeping2 * (t - 1) / tnear2, which is why TP is almost always confined within a single high-bandwidth server (or NVLink rack domain).Pipeline parallelism: split the layer stack into stages
Pipeline parallelism (PP) partitions the vertical stack of layers into
pcontiguous stages, placing one stage per GPU (or per server). With60layers andp = 6, Stage0holds layers0..9, Stage1holds layers10..19, and so on through Stage5(50..59).Inside a stage, every layer is complete, so zero collectives occur. Communication uses point-to-point send/receive — transferring a single
[tokens, h]activation tensor across each stage boundary in the forward pass and one[tokens, h]gradient tensor back in the backward pass:10-layer stage forward compute (1 GPU): 10 * 24 * 4096 * 8192^2 ≈ 66.0 TFLOP -> ~165 ms at 400 TFLOP/s 1 boundary point-to-point send: 67.1 MB / 25 GB/s ≈ 2.7 msSpending
2.7 mson a slow cross-server network link after165 msof local math is tiny (< 2% overhead!). However, pure PP introduces three challenges of its own: 1. Sequential dependency (idle bubbles): Stagei + 1cannot compute forward on a batch until Stageifinishes it. 2. Stage balance: Stage0(input embeddings) and Stagep - 1(final norm + vocabulary head + loss) have extra work and memory unless layer counts are tuned. 3. Capacity per stage: In our 48.6B training example,p = 6leaves10layers (~8.05Bparams *16 B=~129 GB) per stage, still exceeding one80 GBGPU unless combined with TP or sharded optimizer states.Pipeline bubbles, micro-batches, and 1F1B scheduling
If we push one whole batch through
p = 4stages,3out of4GPUs sit idle at every moment (75%wasted time!). To keep stages busy, we slice each batch intommicro-batches (accumulating their gradients before one optimizer step) and stream them back-to-back.Even with micro-batches, later stages wait during startup (warm-up) and earlier stages wait at the end (drain). That idle fraction of wall-clock time is the pipeline bubble. Here is a
p = 4,m = 4GPipe schedule (F0..F3= forward micro-batches,B0..B3= backward,.= idle bubble slot):Time -> 1 2 3 4 5 6 7 | 8 9 10 11 12 13 14 Stage 0: F0 F1 F2 F3 . . . | . . . B3 B2 B1 B0 Stage 1: . F0 F1 F2 F3 . . | . . B3 B2 B1 B0 . Stage 2: . . F0 F1 F2 F3 . | . B3 B2 B1 B0 . . Stage 3: . . . F0 F1 F2 F3 | B3 B2 B1 B0 . . .Each phase takes
m + p - 1 = 7slots on every stage:m = 4busy slots andp - 1 = 3idle bubble slots, giving bubble fraction(p - 1) / (m + p - 1):def bubble_fraction(stages: int, micro_batches: int, chunks_per_device: int = 1) -> float: # Interleaved 1F1B (chunks_per_device = v > 1) requires micro_batches % stages == 0 idle_equivalent = (stages - 1) / chunks_per_device return idle_equivalent / (micro_batches + idle_equivalent) # p = 4 stages: m = 1 -> 0.750, m = 4 -> 0.429, m = 16 -> 0.158, m = 64 -> 0.045 assert [round(bubble_fraction(4, m), 3) for m in (1, 4, 16, 64)] == [0.75, 0.429, 0.158, 0.045] # p = 6, m = 24: 0.172 standard, dropping to 0.094 with v = 2 interleaved layer chunks assert round(bubble_fraction(6, 24, chunks_per_device=2), 3) == 0.094Notice in GPipe above that Stage
0must hold forward activations for allmmicro-batches until slot11. A 1F1B (One-Forward-One-Backward) schedule starts runningB0as soon asF0finishes Stagep - 1, alternating one forward and one backward so at mostpmicro-batches' activations are live on Stage0(same bubble fraction,p / mof the activation memory!). Interleaved 1F1B assignsvnon-contiguous layer chunks per device (e.g., GPU 0 holds layers0..4and30..34whenmis a multiple ofp), cutting the bubble byvat the cost ofvtimes as many point-to-point transfers.Compare memory footprints side by side
Memory component Tensor Parallelism (degree t) Pipeline Parallelism (degree p) Weights, grads, Adam Divided by t inside every layer Divided by p (fewer layers per stage) Training activations 4h MLP & head tensors divided by t; Stores only local layers, multiplied by [tokens, h] divided too if using in-flight micro-batches (m in GPipe, sequence parallelism capped at p on Stage 0 in 1F1B) Inference KV cache Split across t by KV heads (if Each stage stores KV cache only for its KV heads < t under grouped-query own slice of layers attention, KV heads are replicated)Here the KV cache stores past tokens' attention key and value vectors during generation so each new token avoids recomputing earlier positions.
How autoregressive inference flips the bottleneck
LLM serving has two distinct phases: prefill processes all prompt tokens in parallel (compute-bound, behaving like a forward training pass), whereas autoregressive decode generates output one token at a time per sequence. At small batch sizes, decode does very little arithmetic per byte of weights and is strictly bottlenecked by reading all
97.2 GBofbf16weights from GPU HBM memory!Assume each GPU has
3 TB/sof HBM memory bandwidth and~10 microsecondsper small local collective:Hypothetical 1-GPU weight read time: 97.2 GB / 3 TB/s = 32.4 ms per generated token TP = 4 (1 server): all 4 GPUs read 1/4 of weights in parallel -> 8.1 ms + 2 * 60 = 120 tiny (16 KB) all-reduces -> ~1.2 ms Total single-request decode latency ≈ 9.3 ms / token (~3.5x faster!) PP = 4 (stages): each GPU reads 1/4 of weights (8.1 ms), BUT Stage 1 waits for Stage 0, Stage 2 waits for Stage 1, Stage 3 waits for Stage 2: Total single-request decode latency ≈ 32.4 ms / token + 3 network hops- TP directly slashes single-token latency because all
tGPUs stream weight shards simultaneously for the same token. At batch1, each[1, 8192]activation is just16 KB, makingall-reducelatency-bound rather than bandwidth-bound — another reason TP belongs on low-latency NVLink inside one node. - PP does NOT reduce single-request decode latency. It fits models larger than one node and scales throughput only when enough concurrent user batches (
>= p) stay in flight to keep every stage occupied.
- TP directly slashes single-token latency because all
When and how to combine them (3D parallelism)
Neither method scales arbitrarily on its own: TP hits a wall as soon as
tcrosses onto slower inter-server networks, while scaling PP to hugepdemands hugem >> pto suppress bubbles (inflating global batch size or starving per-GPU matrix sizes).Production clusters combine both into 3D parallelism: - Tensor parallelism inside each server (
TP = 8across 8 NVLink GPUs) to divide single-layer memory and utilize fast local collectives. - Pipeline parallelism across servers (PP = 3across 3 servers =24GPUs per model replica) so only rare point-to-point boundary tensors cross slower inter-server links. In our778 GBtraining example,778 GB / 24 ≈ 32.4 GBof weights, gradients, and Adam state sit on each80 GBGPU, leaving nearly48 GBfor activations! - Data parallelism (with ZeRO-1 optimizer sharding) across replicas on top (DP = N) to scale training throughput to hundreds or thousands of GPUs.For serving, start with the smallest
TPinside one server that fits weights + KV cache and meets per-token latency targets; addPPacross servers only when a single server's aggregate GPU memory cannot hold the model, and rely on continuous batching of concurrent requests to hide the pipeline bubble.
Intuition & how it works
Imagine a team of four bakers making a 60-layer wedding cake that is too big for one counter. Tensor parallelism (TP) puts all four bakers side by side at the same table working on every single layer together: each mixes one-quarter of a layer's batter in parallel, and then they combine bowls (all-reduce, a collective sum across all devices) before starting the next layer. Pipeline parallelism (PP) sets up a four-station assembly line: Baker 0 makes layers 1–15 and hands the pan (point-to-point send, a direct transfer to one neighbor) to Baker 1 for layers 16–30, and so on.
Neither split works everywhere by itself. Spreading TP across separate servers connected by slower network cables stalls every single transformer layer waiting for four heavy group synchronizations per training step. Conversely, running a PP assembly line on one cake at a time leaves p - 1 out of p stations sitting completely idle waiting for their turn — wasted time called the pipeline bubble.
Concrete numbers on a 48.6B transformer (h = 8192, 60 layers, 97.2 GB bf16 weights) show why both exist. On one forward layer of 4,096 tokens across TP = 8 GPUs (~2.1 ms of math at 400 TFLOP/s), two all-reduces move 235 MB per GPU: inside one 300 GB/s NVLink server that takes just 0.8 ms, whereas across 25 GB/s server links it takes 9.4 ms — 4.5x slower than the math! Meanwhile, splitting 60 layers into PP = 4 stages with m = 1 batch wastes (4 - 1) / (1 + 4 - 1) = 75% of time idle, but slicing the batch into m = 16 micro-batches (small slices streamed back-to-back) shrinks the bubble to 3 / 19 ≈ 15.8% and crosses the 25 GB/s inter-server link only once every 15 layers (2.7 ms vs. 247 ms of math).
Key points
- What is partitioned: TP splits weight matrices inside every layer (column-parallel vertical slices on the first MLP matrix and
Q, K, Vheads so activation functions/attention need zero communication, paired with row-parallel horizontal slices on the second MLP andOmatrices). PP splits the vertical stack of layers intopcontiguous stages across devices. - Communication pattern: TP runs
2forward and2backwardall-reducesper layer (4per step, or equivalentreduce-scatter+all-gatherunder sequence parallelism, which also shards LayerNorm and residual activations along the token axis) directly on the critical path. PP sends one[tokens, h]activation tensor forward and one gradient tensor backward per stage boundary per micro-batch. - Hardware topology match: Because TP's communication per token scales as
O(h)while per-GPU compute drops asO(h^2 / t), TP requires fast local interconnects inside a server (e.g., NVLink). PP communicates once per multi-layer stage and overlaps well with micro-batch compute, tolerating slower cross-server Ethernet or InfiniBand links. - Utilization and activation memory: TP keeps all
tGPUs busy simultaneously on the same tokens. PP suffers a bubble fraction(p - 1) / (m + p - 1)requiringm >> pmicro-batches, and uses a 1F1B (One-Forward-One-Backward) schedule to cap peak stored micro-batch activations atpinstead ofm. - Training vs. inference: Prefill (parallel prompt processing) is compute-bound like training, whereas small-batch autoregressive decode (generating one token at a time) is bottlenecked by streaming weights from GPU memory (
97.2 GB+ the KV cache of past attention keys and values). TP divides weight reads in parallel to cut per-token latency (~9.3 msvs.~32.4 msatTP = 4), while PP runs stages sequentially per request and only boosts throughput when many concurrent batches fill the pipeline. - When to combine (3D parallelism): Combine
TPinside each fast server withPPacross servers when a model exceeds one server's memory, then layer data parallelism (often with ZeRO / FSDP optimizer/weight sharding and activation recomputation) on top to scale total throughput.
Common mistakes
- Claiming TP or PP is universally faster: Which wins depends on intra- vs. inter-node bandwidth, micro-batch count, sequence length, and whether you optimize training throughput or single-request decode latency.
- Saying PP lowers single-request decode latency: For a single sequence, Stage
i + 1must wait for Stagei, so end-to-end token latency stays equal to (or slightly above) single-device weight-read time; PP only increases multi-request throughput. - Counting only forward collectives in TP: Training requires
4all-reducesper layer per step (2forward +2backward), rising to6if full activation recomputation re-runs the forward pass during backpropagation. - Running PP with
mclose top: Settingm = pleaves(p - 1) / (2p - 1) ≈ 50%of GPU cycles idle in pipeline bubbles. - Ignoring attention head divisibility and GQA in TP:
num_query_headsmust be divisible byt, and under grouped-query attention (GQA) ifnum_kv_heads < t, KV heads must be replicated across TP ranks rather than shrinking the KV cache byt. - Reaching for TP/PP when ZeRO / FSDP suffices: If single-layer weights easily fit on one GPU and only the
16 B/paramAdam states overflow during training, sharding optimizer states across data-parallel ranks avoids pipeline bubbles and intra-layer collectives altogether.
Follow-up questions
- Why do idle bubbles appear in pipeline-parallel execution? Sequential data dependencies between stages cause them: in the forward pass Stage
isits idle until Stages0..i-1finish the first micro-batch (warm-up), and in the backward pass early stages wait for later stages to propagate gradients back (drain). With balanced stages, executingmmicro-batches takesm + p - 1time slots per phase, leavingp - 1idle bubble slots per device (and unbalanced stages, such as heavy embedding or vocabulary layers, add extra stalls paced by the slowest stage). - How does splitting a batch into micro-batches shrink idle pipeline time, and at what cost? Because warm-up and drain waste a fixed
p - 1slots regardless of how many micro-batches stream through in between, splitting a batch intommicro-batches amortizes that fixed overhead so the idle fraction drops to(p - 1) / (m + p - 1)(forp = 4, dropping from75%atm = 1to15.8%atm = 16and4.5%atm = 64). Accumulating gradients across themmicro-batches keeps the mathematical weight update identical to one full batch, trading off against higher activation memory (mitigated by 1F1B scheduling, which caps in-flight micro-batches atp) or smaller, less compute-efficient per-micro-batch matrices when global batch size is fixed. - Why is tensor parallelism usually restricted to high-bandwidth intra-node links rather than cross-node networks? TP executes
4blockingall-reducesof full[tokens, h]activation tensors inside every layer (240collectives per step for a 60-layer model). Astgrows, ringall-reducevolume per GPU stays near2 * activation_byteswhile per-GPU compute shrinks as1 / t, so crossing from300 GB/sintra-server NVLink (~0.8 msforward comm per layer) to25 GB/scross-server networking (~9.4 msvs.2.1 mscompute) makes GPUs spend most of their time stalled on network transfers. - How does single-stream or small-batch autoregressive decoding change the trade-off between tensor and pipeline parallelism? Small-batch autoregressive decode is memory-bandwidth bound on reading model weights once per generated token rather than compute-bound. TP splits weight matrices across
tGPUs that read and multiply simultaneously on the same token (cutting weight-read time by~t), while its[batch, h]all-reducesare tiny (tens of kilobytes) and dominated by per-message latency — best served on fast intra-server links. PP executes stages one after another for each token, yielding zero single-request latency speedup and leaving stages idle whenever concurrent active requests drop belowp, so serving setups apply intra-server TP first and add cross-server PP only if weights plus KV cache cannot fit inside one node.
Follow-up questions
- Why do idle bubbles appear in pipeline-parallel execution?
- How does splitting a batch into micro-batches shrink idle pipeline time, and at what cost?
- Why is tensor parallelism usually restricted to high-bandwidth intra-node links rather than cross-node networks?
- How does single-stream or small-batch autoregressive decoding change the trade-off between tensor and pipeline parallelism?
Similar questions
- Rapid-Fire Production LLM Inference and Evaluation
- Reward-Model RLHF vs. Direct Preference Optimization (DPO)
- LayerNorm vs. RMSNorm in Transformer Architectures
- Adam vs. AdamW: Adaptive Moments and Decoupled Decay
- Sparse Mixture-of-Experts Routing and Distributed Expert Parallelism
- Diffusion Generative Models: Noise Corruption, Training, and Reverse Sampling
More Mistral AI interview questions
- LayerNorm vs. RMSNorm in Transformer Architectures Medium
- Reward-Model RLHF vs. Direct Preference Optimization (DPO) Medium
- Spare GPU Scheduling Under Cluster-Switch Budgets Hard Pro
- Multi-Stage PDF-to-Markdown Inference Pipeline Hard Pro
- Adam vs. AdamW: Adaptive Moments and Decoupled Decay Medium Pro
- Sparse Mixture-of-Experts Routing and Distributed Expert Parallelism Medium Pro
- Diffusion Generative Models: Noise Corruption, Training, and Reverse Sampling Medium Pro
- Diagnosing and Fixing GPU Starvation in Training Data Loaders Medium Pro
- Rapid-Fire Production LLM Inference and Evaluation Medium Pro
- Design a Mistral-Powered Internal Engineering RAG Agent Medium Pro