Model, Pipeline and Tensor Parallelism
Data parallelism assumes that one device can hold the whole model, its gradients and its optimiser state. For large models that assumption fails first: the model does not fit, however small the batch. The answer is to split the model instead of the data. There are two directions to cut. Pipeline parallelism cuts between layers (device 0 runs the first layers, device 1 the next ones). Tensor parallelism cuts inside a layer (each device holds part of every weight matrix). A third family, sharded data parallelism (ZeRO, FSDP), keeps data parallelism but stores each parameter on only one device.
How much memory does training need?
Inference needs the weights. Training needs much more: the gradients, the optimiser state, and the activations saved for the backward pass. With Adam in mixed precision (fp16 or bf16 compute, fp32 master copy) the usual count is 16 bytes per parameter before activations.
# Memory to train a model with Adam in mixed precision (bytes per parameter)
per_param = {"fp16 weights": 2, "fp16 gradients": 2, "fp32 master weights": 4,
"Adam first moment (fp32)": 4, "Adam second moment (fp32)": 4}
total = sum(per_param.values())
for k, v in per_param.items():
print(f"{k:26s} {v:2d} bytes")
print(f"{'total':26s} {total:2d} bytes per parameter (activations not included)")
gpu = 80 # GB on one large GPU
for name, n in [("BERT-base", 110e6), ("1.3B", 1.3e9), ("7B", 7e9), ("70B", 70e9)]:
gb = n * total / 1e9
print(f"{name:9s} {gb:7.1f} GB -> {'fits' if gb <= gpu else 'does not fit'} on one {gpu} GB GPU; "
f"sharded over 8 GPUs: {gb / 8:6.1f} GB each")fp16 weights 2 bytes
fp16 gradients 2 bytes
fp32 master weights 4 bytes
Adam first moment (fp32) 4 bytes
Adam second moment (fp32) 4 bytes
total 16 bytes per parameter (activations not included)
BERT-base 1.8 GB -> fits on one 80 GB GPU; sharded over 8 GPUs: 0.2 GB each
1.3B 20.8 GB -> fits on one 80 GB GPU; sharded over 8 GPUs: 2.6 GB each
7B 112.0 GB -> does not fit on one 80 GB GPU; sharded over 8 GPUs: 14.0 GB each
70B 1120.0 GB -> does not fit on one 80 GB GPU; sharded over 8 GPUs: 140.0 GB each
A 7-billion-parameter model needs 112 GB for its weights, gradients and Adam state alone, more than the 80 GB of the largest common accelerators, before a single activation is stored. Plain data parallelism cannot help, since every replica would need the full 112 GB. Divided over 8 devices it is 14 GB each, which fits: some form of splitting the model is required, and which one depends on the interconnect and the architecture. (Counting parameters and FLOPs layer by layer is done in parameter and FLOP counting; mixed precision is its own lesson.)
Three ways to split
| Splits | Each device holds | Communicates | Needs | |
|---|---|---|---|---|
| Data parallel | the batch | the whole model | gradients, once per step (all-reduce) | the model fits on one device |
| Pipeline parallel | the layers, into stages | of the layers | activations between neighbouring stages | micro-batches to keep the stages busy |
| Tensor parallel | each weight matrix | of every layer | activations inside every block (all-reduce) | a very fast link (same machine) |
| Sharded data parallel (ZeRO, FSDP) | parameters, gradients, optimiser state | of the state, the full layer briefly while it runs | parameters gathered before each layer, gradients reduce-scattered | more traffic than plain data parallel |
Tensor parallelism: splitting a matrix multiply
A linear layer computes . A weight matrix can be split two ways, and each needs different communication:
The trick of Megatron-LM is to pair them in a transformer's MLP block . Split by columns: device computes , a slice of the hidden units, with no communication, because the activation acts on each hidden unit separately. Split by rows to match: device computes the partial output , and one all-reduce adds the partials. Two matrix multiplies, one all-reduce in the forward pass (and one in the backward pass). The same pattern splits attention by heads.
import numpy as np
rng = np.random.default_rng(0)
X = rng.normal(size=(4, 6)) # 4 tokens (or examples), 6 features
A = rng.normal(size=(6, 8)) # first layer 6 -> 8
B = rng.normal(size=(8, 6)) # second layer 8 -> 6
relu = lambda z: np.maximum(z, 0)
Y_one = relu(X @ A) @ B # one device does everything
# column-parallel: split A by columns, each device computes half of the hidden units
A0, A1 = np.hsplit(A, 2) # each 6 x 4
H0, H1 = relu(X @ A0), relu(X @ A1) # no communication needed: ReLU acts per unit
print("hidden part on device 0:", H0.shape, "| device 1:", H1.shape)
# row-parallel: split B by rows to match; each device gets a partial output
B0, B1 = np.vsplit(B, 2) # each 4 x 6
P0, P1 = H0 @ B0, H1 @ B1 # partial sums, each 4 x 6
Y_tp = P0 + P1 # one all-reduce (sum) of a 4 x 6 activation
print("partial output of device 0 alone equals the answer:", np.allclose(P0, Y_one))
print("after the all-reduce:", np.allclose(Y_tp, Y_one))
print("weights per device:", A0.size + B0.size, "of", A.size + B.size)
# the wrong split: rows of A would need the full sum BEFORE the non-linearity
A0r, A1r = np.vsplit(A, 2) # each 3 x 8, X split by columns to match
Z_wrong = relu(X[:, :3] @ A0r) + relu(X[:, 3:] @ A1r)
print("splitting A by rows and applying ReLU to partial sums is correct:",
np.allclose(Z_wrong, relu(X @ A)))hidden part on device 0: (4, 4) | device 1: (4, 4)
partial output of device 0 alone equals the answer: False
after the all-reduce: True
weights per device: 48 of 96
splitting A by rows and applying ReLU to partial sums is correct: False
Device 0's partial output alone is wrong; after the all-reduce (here P0 + P1) the block's output equals the one-device result, and each device stores 48 of the 96 weights. The last line shows why the order matters: splitting by rows would give partial sums of , and the ReLU of a partial sum is not a partial sum of the ReLU, so that split would need an all-reduce before the activation, one more communication per layer.
The cost is that the all-reduce sits in the middle of every block, on the critical path of every forward and backward pass. That is why tensor parallelism is used inside one machine, over NVLink-class links (degree 2 to 8), and almost never across machines.
Pipeline parallelism and the bubble
Pipeline parallelism gives each of devices a contiguous stage of layers. Done naively, one batch flows through device 0, then device 1, and so on: while one device computes, the other wait, and devices are no faster than one (they only provide the memory). GPipe splits the mini-batch into micro-batches: as soon as stage 0 has finished micro-batch 0 and passed its activations on, it starts on micro-batch 1. After all forward passes, the backward passes run through the pipeline in the opposite direction, gradients are accumulated over the micro-batches, and the optimiser steps once (the update is the same as for the whole mini-batch, as with gradient accumulation).
The idle time at the start and end of each phase is the pipeline bubble. With forward and backward times and per micro-batch and stage, one step takes , of which each device works :
The simulation builds the schedule above as text and measures the idle share for several and :
def gpipe(p, m):
"""GPipe schedule: all m forward micro-batches, then all m backward ones (backward = 2 time units).
Returns one row of cells per device: 'F3' = forward of micro-batch 3, 'B3' = backward, '..' = idle."""
grid = [[] for _ in range(p)]
t_fwd = p + m - 1 # forward phase length in time units
for d in range(p):
row = [".."] * (t_fwd + 2 * (p + m - 1))
for k in range(m):
row[d + k] = f"F{k}" # device d runs micro-batch k at time d + k
start = t_fwd + 2 * ((p - 1 - d) + k) # backward runs from the last device to the first
row[start] = row[start + 1] = f"B{m - 1 - k}" # last micro-batch first
grid[d] = row
return grid
p, m = 4, 4
for d, row in enumerate(gpipe(p, m)):
print(f"device {d}: " + " ".join(row))
busy = 3 * m # each device: m forwards (1) + m backwards (2)
total = 3 * (p + m - 1)
print(f"each device is busy {busy} of {total} time units: bubble = {1 - busy / total:.3f}")
print()
print(" p m bubble (p-1)/(m+p-1)")
for p in [4, 8]:
for m in [1, 4, 8, 16, 32]:
grid = gpipe(p, m)
idle = sum(c == ".." for c in grid[0]) / len(grid[0])
print(f"{p:2d} {m:3d} {idle:.3f} formula {(p - 1) / (m + p - 1):.3f}")device 0: F0 F1 F2 F3 .. .. .. .. .. .. .. .. .. B3 B3 B2 B2 B1 B1 B0 B0
device 1: .. F0 F1 F2 F3 .. .. .. .. .. .. B3 B3 B2 B2 B1 B1 B0 B0 .. ..
device 2: .. .. F0 F1 F2 F3 .. .. .. B3 B3 B2 B2 B1 B1 B0 B0 .. .. .. ..
device 3: .. .. .. F0 F1 F2 F3 B3 B3 B2 B2 B1 B1 B0 B0 .. .. .. .. .. ..
each device is busy 12 of 21 time units: bubble = 0.429
p m bubble (p-1)/(m+p-1)
4 1 0.750 formula 0.750
4 4 0.429 formula 0.429
4 8 0.273 formula 0.273
4 16 0.158 formula 0.158
4 32 0.086 formula 0.086
8 1 0.875 formula 0.875
8 4 0.636 formula 0.636
8 8 0.467 formula 0.467
8 16 0.304 formula 0.304
8 32 0.179 formula 0.179
With 4 stages and 4 micro-batches the devices are idle 0.429 of the time (the 9 empty cells out of 21 in each row). The bubble shrinks as grows: 32 micro-batches bring it to 0.086 for 4 stages, while 8 stages need even more micro-batches for the same efficiency (0.179 at ). More micro-batches have a price, though: in GPipe each stage keeps the activations of all micro-batches until their backward pass. The 1F1B schedule (one forward, one backward, used by PipeDream and Megatron) starts the backward pass of a micro-batch as soon as it reaches the last stage, which keeps at most micro-batches in flight and the bubble the same. Activation checkpointing (recompute activations during backward instead of storing them) trades about a third more compute for much less memory and is used with all of these.
With PyTorch: a tensor-parallel MLP on two processes
The same column-then-row split with real processes: each rank keeps its slice of the two Linear layers, and the row-parallel layer all-reduces its partial output.
import os
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
from torch import nn
class ColumnParallelLinear(nn.Module):
"""Holds out_features / world_size output columns of a Linear layer."""
def __init__(self, full: nn.Linear, rank, world):
super().__init__()
rows = full.out_features // world
self.weight = nn.Parameter(full.weight[rank * rows:(rank + 1) * rows].detach().clone())
self.bias = nn.Parameter(full.bias[rank * rows:(rank + 1) * rows].detach().clone())
def forward(self, x):
return x @ self.weight.T + self.bias # this rank's slice of the hidden units
class RowParallelLinear(nn.Module):
"""Holds in_features / world_size input rows; sums the partial outputs with all-reduce."""
def __init__(self, full: nn.Linear, rank, world):
super().__init__()
cols = full.in_features // world
self.weight = nn.Parameter(full.weight[:, rank * cols:(rank + 1) * cols].detach().clone())
self.bias = nn.Parameter(full.bias.detach().clone()) if rank == 0 else None # add the bias once
def forward(self, h):
y = h @ self.weight.T
if self.bias is not None:
y = y + self.bias
dist.all_reduce(y) # forward communication: one all-reduce
return y
def worker(rank, world):
os.environ.update(MASTER_ADDR="127.0.0.1", MASTER_PORT="29502", GLOO_SOCKET_IFNAME="lo")
dist.init_process_group("gloo", rank=rank, world_size=world)
torch.manual_seed(0)
fc1, fc2 = nn.Linear(16, 64), nn.Linear(64, 16) # the full MLP block, same on both ranks
x = torch.randn(8, 16)
y_full = fc2(torch.relu(fc1(x))) # reference: one device
tp = nn.Sequential(ColumnParallelLinear(fc1, rank, world), nn.ReLU(), RowParallelLinear(fc2, rank, world))
with torch.no_grad():
y_tp = tp(x)
n_local = sum(p.numel() for p in tp.parameters())
sizes = [None] * world
dist.all_gather_object(sizes, n_local)
if rank == 0:
print("full block parameters:", sum(p.numel() for p in [*fc1.parameters(), *fc2.parameters()]))
print("parameters per rank :", sizes)
print("output shape:", tuple(y_tp.shape), "| equal to the one-device output:",
torch.allclose(y_tp, y_full, atol=1e-6))
dist.destroy_process_group()
if __name__ == "__main__":
mp.spawn(worker, args=(2,), nprocs=2)full block parameters: 2128
parameters per rank : [1072, 1056]
output shape: (8, 16) | equal to the one-device output: True
Rank 0 holds 1072 parameters and rank 1 holds 1056 of the block's 2128; the difference is the second layer's bias, which only rank 0 adds so it is not counted twice after the all-reduce. The output equals the single-device MLP. Production code does not write these classes by hand: PyTorch has torch.distributed.tensor.parallel (ColwiseParallel, RowwiseParallel) and torch.distributed.pipelining for pipeline stages, and Megatron-LM and DeepSpeed implement all three kinds of parallelism for transformers. Running them needs several GPUs; the logic is what you just ran.
Sharding instead of splitting: ZeRO and FSDP
Data parallelism stores identical copies of the weights, gradients and Adam state, which is wasteful. ZeRO (DeepSpeed) and PyTorch's FSDP (Fully Sharded Data Parallel) keep the data-parallel algorithm but store each piece of the state on one rank only:
- Stage 1 shards the optimiser state (12 of the 16 bytes per parameter in the count above).
- Stage 2 also shards the gradients: a reduce-scatter instead of an all-reduce leaves each rank with the summed gradient for its own shard.
- Stage 3 (FSDP's "full shard") also shards the weights. Before a layer runs, an all-gather assembles its weights from all ranks; afterwards they are freed.
With full sharding the 7B model's 112 GB spread over 8 devices is 14 GB per device, the sum computed in the first example, and the program still looks like data parallelism: every rank runs the whole model on its own shard of the batch. The price is roughly 1.5 times the communication of plain data parallelism. For models up to tens of billions of parameters, FSDP alone is often enough; beyond that, it is combined with the other kinds.
Putting them together: 3-D parallelism
The largest models combine all three, matched to the hardware: tensor parallelism inside a machine (8 GPUs on NVLink), pipeline parallelism across a few machines (only activations of stage boundaries travel), and data parallelism (often sharded) across groups of those. With degrees , and , the job uses devices; for example 8 x 4 x 32 = 1024 GPUs. The choice is an engineering trade-off between memory, communication volume and bubble time, and it is the reason large training runs are planned with a cost model before a single step runs.
Pitfalls
- Reaching for model parallelism too early. If the model fits on one device with a smaller batch, data parallelism (plus gradient accumulation, mixed precision and activation checkpointing) is simpler and usually faster. Try FSDP before writing pipeline stages.
- Tensor parallelism across slow links. Its all-reduce runs inside every block; over Ethernet the devices spend most of their time waiting.
- Too few micro-batches. With the bubble is 50 % or more; the stages mostly wait.
- Unbalanced stages. The pipeline runs at the pace of its slowest stage. Split by measured time, not by layer count (embedding and output layers are often much heavier).
- Forgetting the activations. The 16 bytes per parameter exclude activations, which grow with batch size and sequence length and are often the larger part.
- Counting a bias twice. In a row-parallel layer, only one rank adds the bias (or the bias is added after the all-reduce).
Practice
- How many bytes of weights, gradients and Adam state does a 13-billion-parameter model need with the 16-bytes-per-parameter count? On how many 80 GB devices does it fit with full sharding, ignoring activations?
- A pipeline has 8 stages. How many micro-batches are needed to bring the bubble below 10 %?
- In a column-parallel layer followed by a ReLU and a row-parallel layer, why is there no communication between the first layer and the ReLU?
- You have 2 machines with 8 GPUs each, connected by 10 Gbit Ethernet, and a model that needs about 4 GPUs' memory. Which parallelism goes where?
Answers
- GB. 3 devices would hold 69.3 GB each, which fits under 80 GB but leaves little for activations; in practice 4 or 8.
- means , so .
- The column split gives each device complete hidden units (all of their inputs were summed on that device), and ReLU acts on each hidden unit separately, so each device can apply it to its own slice.
- Tensor (or FSDP) parallelism of degree 4 inside each machine, over the fast local links, and data parallelism across the groups: 4 groups of 4 GPUs, 2 per machine. Only the gradient all-reduce crosses the slow Ethernet, once per step, and it can overlap with backward.
Test yourself
A model does not fit in one device's memory even with batch size 1. Which approach does not help on its own?
- Pipeline parallelism
- Tensor parallelism
- Plain data parallelism
- Fully sharded data parallelism (FSDP)
In a Megatron-style MLP block split over two devices, how are and split?
- Both by rows
- by columns, by rows, one all-reduce at the end
- by rows, by columns
- Neither: each device holds a full copy
What is the pipeline bubble fraction for stages and micro-batches?
- 0
Why is tensor parallelism usually kept inside one machine?
- It needs the same random seed
- It communicates inside every layer, on the critical path, so it needs very fast links
- It only works on CPUs
- It cannot be combined with data parallelism