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-reduce or reduce-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

  1. 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, 60 layers, a 4h feed-forward network (MLP), and a 32,000-token tied vocabulary. Each layer holds roughly 12 * h^2 ≈ 805M parameters (4 * h^2 across attention's Q, K, V, O matrices plus 8 * h^2 across the MLP's up and down matrices). Across 60 layers plus 32,000 * 8192 ≈ 0.26B embedding 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 GB GPUs, inference needs at least 2 GPUs for weights alone, and training needs at least 10 GPUs 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).
  2. Tensor parallelism: split matrices inside every layer

    Tensor parallelism (TP) partitions each individual layer's weight matrices across t GPUs so all t GPUs compute on the exact same tokens simultaneously. Consider Megatron-LM's standard split of a two-layer MLP Y = GeLU(X @ A) @ B across t = 2 GPUs:

    • Column-parallel first layer (A = [A_0 | A_1]): Slicing A vertically gives each GPU 4h / t columns. Because GeLU acts element-wise on each feature independently, GeLU(X @ A_i) requires zero communication!
    • Row-parallel second layer (B stacked horizontally as [B_0 ; B_1]): GPU i multiplies its local GeLU(X @ A_i) slice by B_i, producing a partial full-width [tokens, h] matrix.
    • One all-reduce at the end: An all-reduce is a collective operation that sums matching tensors across all t GPUs and leaves the identical total Y = Y_0 + Y_1 on 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 GPUs
    

    Multi-head attention splits the exact same way across heads: Q, K, V projections are column-parallel so each GPU owns num_heads / t heads (requiring num_heads to be divisible by t), softmax attention runs completely locally per head, and the output projection O is row-parallel followed by one all-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 large 4h / 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 each all-reduce with a reduce-scatter plus all-gather of identical total byte volume.

  3. Tensor-parallel communication cost and interconnect limits

    Every transformer block executes 2 all-reduces in the forward pass (one after attention, one after the MLP) and 2 all-reduces in 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 = 8192 model with t = 8 GPUs, bf16 activations (2 bytes), and a micro-batch of 4,096 tokens (2 sequences of length 2,048). Assume 400 TFLOP/s sustained compute per GPU, 300 GB/s unidirectional send bandwidth per GPU inside one server (e.g., high-speed NVLink), and 25 GB/s unidirectional across servers (one 200 Gb/s network 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 ms is manageable (and partially overlappable with tiled matmul kernels). Across servers, 9.4 ms is 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 with tokens. Pushing t larger also shrinks h^2 / t while keeping 2 * (t - 1) / t near 2, which is why TP is almost always confined within a single high-bandwidth server (or NVLink rack domain).

  4. Pipeline parallelism: split the layer stack into stages

    Pipeline parallelism (PP) partitions the vertical stack of layers into p contiguous stages, placing one stage per GPU (or per server). With 60 layers and p = 6, Stage 0 holds layers 0..9, Stage 1 holds layers 10..19, and so on through Stage 5 (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 ms
    

    Spending 2.7 ms on a slow cross-server network link after 165 ms of local math is tiny (< 2% overhead!). However, pure PP introduces three challenges of its own: 1. Sequential dependency (idle bubbles): Stage i + 1 cannot compute forward on a batch until Stage i finishes it. 2. Stage balance: Stage 0 (input embeddings) and Stage p - 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 = 6 leaves 10 layers (~8.05B params * 16 B = ~129 GB) per stage, still exceeding one 80 GB GPU unless combined with TP or sharded optimizer states.

  5. Pipeline bubbles, micro-batches, and 1F1B scheduling

    If we push one whole batch through p = 4 stages, 3 out of 4 GPUs sit idle at every moment (75% wasted time!). To keep stages busy, we slice each batch into m micro-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 = 4 GPipe 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 = 7 slots on every stage: m = 4 busy slots and p - 1 = 3 idle 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.094
    

    Notice in GPipe above that Stage 0 must hold forward activations for all m micro-batches until slot 11. A 1F1B (One-Forward-One-Backward) schedule starts running B0 as soon as F0 finishes Stage p - 1, alternating one forward and one backward so at most p micro-batches' activations are live on Stage 0 (same bubble fraction, p / m of the activation memory!). Interleaved 1F1B assigns v non-contiguous layer chunks per device (e.g., GPU 0 holds layers 0..4 and 30..34 when m is a multiple of p), cutting the bubble by v at the cost of v times as many point-to-point transfers.

  6. 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.

  7. 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 GB of bf16 weights from GPU HBM memory!

    Assume each GPU has 3 TB/s of HBM memory bandwidth and ~10 microseconds per 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 t GPUs stream weight shards simultaneously for the same token. At batch 1, each [1, 8192] activation is just 16 KB, making all-reduce latency-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.
  8. When and how to combine them (3D parallelism)

    Neither method scales arbitrarily on its own: TP hits a wall as soon as t crosses onto slower inter-server networks, while scaling PP to huge p demands huge m >> p to 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 = 8 across 8 NVLink GPUs) to divide single-layer memory and utilize fast local collectives. - Pipeline parallelism across servers (PP = 3 across 3 servers = 24 GPUs per model replica) so only rare point-to-point boundary tensors cross slower inter-server links. In our 778 GB training example, 778 GB / 24 ≈ 32.4 GB of weights, gradients, and Adam state sit on each 80 GB GPU, leaving nearly 48 GB for 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 TP inside one server that fits weights + KV cache and meets per-token latency targets; add PP across 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, V heads so activation functions/attention need zero communication, paired with row-parallel horizontal slices on the second MLP and O matrices). PP splits the vertical stack of layers into p contiguous stages across devices.
  • Communication pattern: TP runs 2 forward and 2 backward all-reduces per layer (4 per step, or equivalent reduce-scatter + all-gather under 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 as O(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 t GPUs busy simultaneously on the same tokens. PP suffers a bubble fraction (p - 1) / (m + p - 1) requiring m >> p micro-batches, and uses a 1F1B (One-Forward-One-Backward) schedule to cap peak stored micro-batch activations at p instead of m.
  • 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 ms vs. ~32.4 ms at TP = 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 TP inside each fast server with PP across 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 + 1 must wait for Stage i, 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 4 all-reduces per layer per step (2 forward + 2 backward), rising to 6 if full activation recomputation re-runs the forward pass during backpropagation.
  • Running PP with m close to p: Setting m = p leaves (p - 1) / (2p - 1) ≈ 50% of GPU cycles idle in pipeline bubbles.
  • Ignoring attention head divisibility and GQA in TP: num_query_heads must be divisible by t, and under grouped-query attention (GQA) if num_kv_heads < t, KV heads must be replicated across TP ranks rather than shrinking the KV cache by t.
  • Reaching for TP/PP when ZeRO / FSDP suffices: If single-layer weights easily fit on one GPU and only the 16 B/param Adam 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 i sits idle until Stages 0..i-1 finish 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, executing m micro-batches takes m + p - 1 time slots per phase, leaving p - 1 idle 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 - 1 slots regardless of how many micro-batches stream through in between, splitting a batch into m micro-batches amortizes that fixed overhead so the idle fraction drops to (p - 1) / (m + p - 1) (for p = 4, dropping from 75% at m = 1 to 15.8% at m = 16 and 4.5% at m = 64). Accumulating gradients across the m micro-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 at p) 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 4 blocking all-reduces of full [tokens, h] activation tensors inside every layer (240 collectives per step for a 60-layer model). As t grows, ring all-reduce volume per GPU stays near 2 * activation_bytes while per-GPU compute shrinks as 1 / t, so crossing from 300 GB/s intra-server NVLink (~0.8 ms forward comm per layer) to 25 GB/s cross-server networking (~9.4 ms vs. 2.1 ms compute) 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 t GPUs that read and multiply simultaneously on the same token (cutting weight-read time by ~t), while its [batch, h] all-reduces are 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 below p, 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

Similar questions

More Mistral AI interview questions

All 17 Mistral AI questions →