Key takeaways
- One GPU can neither hold the job nor finish it in time: training a 7-billion-parameter model takes 112 GB of memory before activations, and one GPU would need over 20 years. Parallel training spreads the memory and the compute across many GPUs.
- Everything rests on collective operations: broadcast, reduce, all-reduce, all-gather and reduce-scatter. Remember all-reduce = reduce-scatter + all-gather; with the ring algorithm, the time depends almost entirely on the amount of data and the bandwidth.
- When you split a matrix multiplication, check whether the contracting dimension is split. If it isn't, there's no communication; if it is, you only get partial sums and need an all-reduce.
- Data parallelism (DP) splits the batch; ZeRO / FSDP goes on to shard the optimizer state, the gradients and the parameters, cutting out the redundant memory.
- Model parallelism: pipeline parallelism (PP) splits by layer and uses micro-batches to fill in the bubbles; tensor parallelism (TP) splits by columns, then by rows, so each MLP or attention block needs just one all-reduce.
Is one GPU enough?
First, memory
Say you want to train a model with 7 billion parameters, about the size of the smallest Llama 2, and you have one very good GPU with 80 GB of memory. Is that enough?
Back in episode 10 we saw that during training, every parameter drags several other numbers along with it. With last episode's mixed precision:
| Item |
Bytes/param |
| BF16 weight |
2 |
| BF16 gradient |
2 |
| FP32 master weight |
4 |
| Adam first moment |
4 |
| Adam second moment |
4 |
| Total |
16 |
7 billion × 16 bytes = 112 GB. Before we've even counted the activations, that's more than all 80 GB on the card.
Then, time
The compute needed for training is roughly 6× parameters × training tokens. The 7-billion version of Llama 2 was trained on 2 trillion tokens:
6×(7×109)×(2×1012)=8.4×1022 FLOPs
A single A100 peaks at 312 trillion operations per second (312×1012), and in practice you get to use about 40% of that. Work it out and it would take a full 21 years. That's not just a guess: the Llama 2 paper reports about 184,000 GPU hours for the 7-billion-parameter model, which also works out to about 21 years.
But spread the work evenly over 1000 GPUs and it takes only about 8 days. That's what parallel training is all about: spreading both the memory and the compute across lots of GPUs.
Ideally, doubling the GPUs doubles the throughput (FLOPs per second). That's called strong scaling. But GPUs have to swap data with each other, and that communication drags things down. So this episode is about two things: how to split the work, and how to communicate.
What to split: data, memory, model
At heart, every kind of parallelism comes down to splitting something up:
- Split the data: data parallelism (DP). Hand the samples in a batch out to different GPUs, let every GPU run the whole model (full forward and backward pass), and combine the gradients at the end.
- Split the memory: ZeRO / FSDP. In data parallelism, every GPU stores a lot of the exact same stuff. Split that duplicated state up and share it out.
- Split the model: model parallelism. Split up the computation of a single forward pass across GPUs. You can split by layers, which is pipeline parallelism (PP), or cut a single matrix into pieces, which is tensor parallelism (TP).
Intuition: Data parallelism is having too much homework: you bring in a few friends, everyone does a part, and you compare answers at the end. Model parallelism is one problem that's too big for one person, so several people team up on that same problem. DP scales throughput; TP and PP shrink the model memory on each GPU; SP (sequence parallelism) shrinks the activation memory.
What people call 5D parallelism is DP (split the data), TP (split weight matrices), PP (split layers), SP (sequence parallelism, split the sequence length) and EP (expert parallelism, spread the experts of a mixture-of-experts model across GPUs). This episode covers the first three, plus ZeRO.
However you split things, GPUs have to exchange data, so let's start at the very bottom, with the communication operations themselves.
Five basic communication patterns
Every parallel method is built on a handful of standard communication operations called collectives. Let's watch them on four GPUs, each holding a chunk of data split into four small pieces:
| GPU |
Data |
| GPU 0 |
1, 2, 0, 3 |
| GPU 1 |
2, 0, 1, 1 |
| GPU 2 |
3, 1, 2, 0 |
| GPU 3 |
0, 4, 1, 2 |
- Broadcast (one to all): one GPU copies the same data to every other GPU. For example, at the start of training, GPU 0 sends its freshly initialized weights to everyone.
- Reduce: every GPU has different data; we add it all up position by position, and the result lands on just one GPU. The first piece is 1+2+3+0=6, and the full sum is [6,7,4,6].
- All-reduce: again we take the sum, but this time every GPU needs the final result. The most direct way is to reduce onto one GPU, then broadcast the result back out.
- All-gather: at first, each GPU has only its own little piece. Once the gather is done, every GPU has the complete set.
- Reduce-scatter: every GPU has a full set of data that hasn't been added up yet. After summing, the result is cut into four pieces, and each GPU keeps only the piece it's responsible for.
Intuition: The output of reduce-scatter is exactly what all-gather starts from. Chain the two together and you get an all-reduce:
all-reduce=reduce-scatter+all-gather. We'll lean on this relationship again and again.
Ring all-reduce
Gathering everything onto one GPU has a problem: GPU 0 has to receive data from every other GPU. The more GPUs you add, the busier it gets, while the others just sit there waiting.
A better way is ring all-reduce. Connect the GPUs into a ring, so each GPU only ever talks to its two neighbors: it receives from the one before it and sends to the one after it.
- Phase one: reduce-scatter. At each step, every GPU sends one of its pieces to the next GPU, which adds it to its own piece in the same position; in the next step, the piece that was just added to gets passed along and added to again. After three steps, every GPU has one piece that holds the full sum over all four GPUs (GPU 0's first piece is 6, for example). This phase does every addition, with no redundant copying, and the half-summed pieces can be thrown away.
- Phase two: all-gather. Around the same ring, each GPU passes its complete piece to the next GPU, which simply stores it, with no adding. This phase does all the copying and none of the arithmetic. After three steps, all four GPUs hold 6,7,4,6.
Now count the traffic. With four GPUs, at each step every GPU sends just a quarter of the data, and the two phases take six steps, so each GPU sends only 1.5 times the size of the array. With N GPUs:
per stepN1×steps2(N−1)=2⋅NN−1 arrays
| GPUs N |
Ring: each sends |
Gather: GPU 0 |
| 2 |
1.00 |
2 |
| 4 |
1.50 |
6 |
| 8 |
1.75 |
14 |
| 64 |
1.97 |
126 |
| 1024 |
2.00 |
2046 |
(Units: one full copy of the array.) The more GPUs you add, the closer the ring number gets to 2, so it barely changes. When you gather onto one GPU, its load grows in direct proportion to the number of GPUs.
Intuition: For a large enough array, the time an all-reduce takes depends mainly on how big the array is and how fast the links are, and hardly at all on how many GPUs take part. The same goes for all-gather and reduce-scatter, which each take half of that.
Sharding notation: who holds which piece
To describe who holds which piece of a matrix, we need some notation.
- Arrange the GPUs in a grid, called a mesh. Say, four GPUs in a 2×2 grid: the horizontal direction is the X axis and the vertical direction is the Y axis.
- For a matrix A, the direction along its rows is called I and along its columns J.
| Notation |
Meaning |
| A[IX,J] |
rows split along X; copied along Y |
| A[IX,JY] |
rows along X, columns along Y: one block per GPU |
| A[IXY,J] |
rows cut into four, one part per GPU |
| A[I,J] |
every GPU holds a full copy |
| A[I,J]{UX} |
not yet reduced along X (partial sums) |
IX means GPUs with different X coordinates get different blocks of rows. A mesh axis that doesn't appear means the data is copied along it: in A[IX,J], Y is missing, so the two GPUs stacked in the same column hold exactly the same data.
{UX} means every GPU holds a matrix of the full shape, but it's only a partial sum: you have to add up the copies along X to get the real value, A=A(X=0)+A(X=1).
With this notation, the three collectives can be written precisely:
AllGatherYReduceScatterY,JAllReduceY: A[I,JY]→A[I,J]: A[I,J]{UY}→A[I,JY]: A[I,J]{UY}→A[I,J]
- All-gather drops a subscript: columns that were split along Y get stitched back together.
- Reduce-scatter adds up the unreduced data and at the same time adds a subscript: the result is split along Y and shared out.
- All-reduce simply drops the not-yet-reduced mark {UY}: every GPU gets the complete sum.
Forward and backward come in pairs
In backpropagation, these operations come in pairs. Remember the rule from episode 3: if a value gets copied to several places in the forward pass, then on the way back, the gradients flowing in from all those places get added up (gradients sum at branches).
- The backward of all-gather is reduce-scatter. All-gather copies each piece to every GPU, where it feeds different downstream computations. On the way back, the gradients from all the GPUs are summed and sent to the GPU the piece came from. That's a reduce-scatter. (Fan out forward → sum backward.)
- The backward of reduce-scatter is all-gather. A sum passes the same gradient, unchanged, back to each of its terms. Reduce-scatter sums in the forward pass, so its backward broadcasts each piece's gradient back to all its contributors: an all-gather. (Sum forward → fan out backward.)
Put the two together, and the backward pass of an all-reduce is just another all-reduce.
How to split a matrix multiplication
The single most important operation in parallel computing is matrix multiplication. A small example:
(1324)(5768)=(19432250)
The 19 in C's top-left corner is 1×5+2×7. The sum runs over A's columns and B's rows; the dimension that gets summed away like this is called the contracting dimension.
- Split A by rows: one GPU gets the first row, the other the second, and both have a full copy of B. Each GPU computes one row of C on its own, with no communication at all.
- Split the contracting dimension: one GPU gets A's first column and B's first row, the other gets the second column and second row. Each GPU ends up with a matrix of the full shape, but it's only a partial sum:
(13)(56)=(515618),(24)(78)=(14281632)
It takes 5+14 to make 19. We have to add the two GPUs' results together, and that's exactly an all-reduce.
Intuition: Matrix multiplication has a nice property: write the matrices in blocks, and the product can be written as block matrix multiplies. That's the foundation of distributed matmul. The whole trick is to check whether the contracting dimension has been split.
Four cases of distributed matrix multiplication
Case 1: neither matrix has its contracting dimension split. Each GPU multiplies its own two blocks and gets one block of C, with no communication at all, and the output comes out already sharded the way we want:
A[IX,J]⋅B[J,KY]→C[IX,KY]
Case 2: only one matrix has its contracting dimension split. Say A's columns are split along X and B is whole. First all-gather A to make it whole, then multiply:
AllGatherX: A[I,JX]→A[I,J] A[I,J]⋅B[J,K]→C[I,K]
Case 3: both matrices have their contracting dimension split along the same axis. Each GPU can multiply, but all it gets is a partial sum. A final all-reduce adds them up, leaving every GPU with the same fully summed result:
A[I,JX]⋅B[JX,K]→C[I,K]{UX}AllReduceX: C[I,K]{UX}→C[I,K]
Case 4: both matrices have a non-contracting dimension split along the same axis, as in A[IX,J]⋅B[J,KX]. GPU 0 has the top half of A and the left half of B, so it can only compute C's top-left block; the top-right block needs the right half of B, which is on the other GPU. A single mesh axis can't split both dimensions of the output at once, so we first all-gather one of the inputs (say B), which takes us back to case 1.
Keep these four cases in mind. Tensor parallelism, as we'll see, is really just about picking the split that needs the least communication.
Data parallelism (DDP)
How it works
Say a batch has 32 samples and we have four GPUs. Each GPU gets 8 of them, which is called a micro-batch.
- Every GPU holds a complete copy of the model and runs the forward pass on its own micro-batch.
- It runs the backward pass and computes the gradients for all parameters. Since the data differ, the four GPUs get different gradients (say 0.8,0.4,1.2,0.0).
- An all-reduce gives every GPU the averaged gradient.
- Each GPU uses that same gradient to update all of its parameters: W←W−ηgˉ.
Why an average in step 3? The loss for the whole batch is the average of the four losses, and taking a derivative is linear, so the overall gradient is just the average of the four gradients:
L∇L=41(L0+L1+L2+L3)=41(g0+g1+g2+g3)=41(0.8+0.4+1.2+0.0)=0.6
That's exactly an all-reduce: sum, then divide by four. In step 4 everyone does exactly the same computation, so the four copies of the model always stay in sync.
Key points
This is DDP, distributed data parallel:
- Communication only happens during the backward pass, and the last layers' gradients can start sending as soon as they're ready, overlapping with the backward computation of the earlier layers. Most of the communication hides behind compute.
- As long as your model fits on one GPU, start with DDP. Adding GPUs lets you use a bigger batch, and throughput goes up with it.
But there's an obvious waste: the four GPUs store four identical copies of the weights, the gradients and the optimizer state.
ZeRO: split up the duplicated memory
Remember the tally from the start: 16 bytes per parameter, 12 of them optimizer state (the FP32 master weight plus Adam's two moments). In data parallelism, every GPU stores a full copy of all of it.
The idea behind ZeRO is simple: if everyone stores exactly the same thing, split it up. With M GPUs, each keeps just M1 of it, and each keeps a different share.
- Stage 1 (ZeRO-1): shard the optimizer state. Each GPU keeps only M1 of the Adam state and only updates the matching parameters. The procedure changes too: instead of an all-reduce, the gradients go through a reduce-scatter, so each GPU receives only the summed gradient for its own share. After updating its share of the parameters, it sends the new values to everyone with an all-gather. A reduce-scatter plus an all-gather is exactly one all-reduce, so the communication is the same as before, yet we save a big chunk of memory. It's a free win.
- Stage 2 (ZeRO-2): shard the gradients too. During the backward pass, each layer's gradients are reduce-scattered the moment they're computed; each GPU keeps only its own share and frees the rest right away. The communication still doesn't change.
- Stage 3 (ZeRO-3): shard the parameters too. This is FSDP (fully sharded data parallel) in PyTorch: each GPU stores only M1 of the parameters.
Writing Ψ for the parameter count, memory per GPU (without activations) steps down like this:
| Scheme |
Memory per GPU |
| DDP |
(2+2+12)Ψ |
| ZeRO-1 |
(2+2+M12)Ψ |
| ZeRO-2 |
(2+M14)Ψ |
| ZeRO-3 |
M16Ψ |
Plug in 7 billion parameters and 8 GPUs. Plain DDP needs 112 GB per GPU. ZeRO-1 already brings that down to 38.5 GB, which fits on an 80 GB card; ZeRO-2 needs 26.3 GB; ZeRO-3 just 14 GB. The more GPUs you have, the more you save.
The cost of FSDP, and the limits of data parallelism
What stage 3 costs
Each GPU stores only M1 of every layer's parameters, so before each layer runs, its parameters have to be all-gathered into a full copy, which is thrown away right after use. In the backward pass the parameters have to be gathered all over again, and the forward all-gather pairs up with a reduce-scatter of the gradients: as soon as a layer's gradients are done, they're split up and each GPU keeps only its share. Note that although FSDP stores the parameters sharded, every GPU still computes the full forward pass; the parameters are just assembled right before they're needed.
According to the ZeRO paper's analysis, stages 1 and 2 communicate exactly as much as ordinary data parallelism, while stage 3 adds one more all-gather of the parameters, about 1.5 times as much. What you get in return: you can train models that simply don't fit on one GPU.
Two ceilings for data parallelism
- You can't have more GPUs than samples in a batch (it needs M<B). And the batch can't grow forever: past the critical batch size, making it bigger buys you very little.
- Even with stage 3, the activations on each GPU don't shrink at all, because every GPU still runs the full forward pass. With bigger models and longer sequences, data parallelism alone isn't enough.
That's when we split up the computation of a single forward pass itself: model parallelism. There are two ways to do it: by layers, or by matrices.
Pipeline parallelism and bubbles
The naive way: everyone takes turns waiting
Pipeline parallelism divides the model's layers into stages, one per GPU. With four stages, GPU 0 computes the first 8 layers, hands its intermediate results (the activations) to GPU 1, and so on down the line.
The most naive approach sends the whole batch through in one go. Draw a timeline, with time running left to right and one row per GPU: the forward pass moves down from GPU to GPU, then the backward pass walks back up (it costs about twice the compute of the forward). At any moment only one GPU is working while the other three wait. These gaps are called pipeline bubbles. With four GPUs, utilization is only one quarter, so naive model parallelism doesn't improve throughput at all.
Micro-batches: an assembly line
The fix is to cut the batch into several micro-batches. As soon as GPU 0 finishes the first one, it passes it to GPU 1 and immediately starts on the second, just like an assembly line in a factory. Once all the forward passes are done, the backward passes run in turn. This schedule is called GPipe.
The bubbles are still there, but now they're just two triangles, one at the start and one at the end. The fraction of time lost to bubbles is
bubble fraction=m+p−1p−1
where p is the number of pipeline stages and m the number of micro-batches. With p=4 and m=4, bubbles take 3/7≈43% of the time; raise m to 8 and that drops to 3/11≈27%. The more micro-batches, the smaller the bubbles.
In code, you put each part of the model on a different GPU, then set chunks=8 to cut each batch into 8 micro-batches (this is an interface from an older version of PyTorch, shown for illustration):
from torch.distributed.pipeline.sync import Pipe
model = nn.Sequential(
nn.Linear(512, 512).to('cuda:0'),
nn.ReLU().to('cuda:0'),
nn.Linear(512, 512).to('cuda:1'),
nn.ReLU().to('cuda:1'),
)
model = Pipe(model, chunks=8) # splits batch into 8 micro-batches
output = model(x)
Schedules: GPipe vs 1F1B
GPipe has a drawback: the backward passes don't start until every forward pass is done, so GPU 0 has to hold the activations of all 8 micro-batches at once. That's a lot of activation memory.
Another common schedule is 1F1B, short for one forward, one backward. After a few warm-up steps, each GPU alternates: a forward, then a backward, then a forward again. As soon as a backward pass finishes, that micro-batch's activations can be freed. The two schedules take exactly the same total time, with exactly the same bubbles, but with 1F1B, GPU 0 never holds more than 4 sets of activations, which is exactly the number of pipeline stages.
Going further, interleaved schedules give each GPU several non-adjacent chunks of layers. That shrinks the bubbles even more, at the cost of more communication.
Intuition: Pipeline parallelism only sends activations between neighboring stages, so there isn't much communication. That's why it's often used across machines.
Tensor parallelism: splitting the MLP
Column parallel and row parallel
The other way to split goes further: cut up individual weight matrices. That's tensor parallelism. Start with one linear layer, Y=XW:
- Column parallel: cut W into two halves by columns, one per GPU, and each GPU computes half of Y's columns by itself. That's case 1: no communication, and the output comes out sharded.
- Row parallel: cut W by rows instead. Then X has to be split by columns too, each GPU only gets a partial sum, and it takes an all-reduce to get Y. That's case 3.
A tiny example
The MLP in a Transformer multiplies by Wup, applies an activation function, then multiplies by Wdown. Take x=(1,2):
Wup=(10011−111),Wdown=10210111
On one GPU: xWup=(1,2,−1,3), ReLU turns the negative number into zero to give (1,2,0,3), and multiplying by Wdown gives (4,5).
The tensor-parallel split: Wup by columns, Wdown by rows. GPU 0 takes the first two columns of Wup and the first two rows of Wdown; GPU 1 takes the rest.
- GPU 0: x times its two columns gives (1,2), which ReLU leaves unchanged; times the first two rows of Wdown gives (1,2).
- GPU 1: it gets (−1,3), which ReLU turns into (0,3); times the last two rows gives (3,3).
Add up the two GPUs' results: 1+3=4 and 2+3=5, exactly the right answer. No communication along the way, just one all-reduce at the very end.
Why it works
Split h into two blocks by columns and Wdown into two blocks by rows. Then the product breaks into a sum of two terms, each living entirely on one GPU:
y=hWdown=(h0h1)(W0W1)=h0W0+h1W1=y0+y1
The key is the activation function in the middle. It works element by element, and each GPU holds complete columns, so each one can apply it directly. If we split Wup by rows instead, each GPU would hold only partial sums, and
ReLU(2+(−3))=0=ReLU(2)+ReLU(−3)=2
so we'd have to communicate before the activation. Any other choice of split forces a collective in the middle; "columns, then rows" needs just one all-reduce.
SwiGLU works the same way:
(SiLU(xWgate)⊙xWup)Wdown
Wgate and Wup are both split by columns; after the element-wise product the result is still sharded along F, the MLP's hidden dimension; finally Wdown is split by rows, with one all-reduce at the end.
Tensor parallelism: attention and its cost
Splitting attention by heads
Attention splits even more naturally. In multi-head attention, each head is computed independently, so we can hand the heads out to different GPUs, say four of eight heads each:
- Each GPU computes Q, K and V only for its own heads, which amounts to splitting the QKV projection by columns.
- The attention itself is computed entirely locally, with no communication.
- The output projection WO is split by rows, giving partial sums, with one all-reduce at the end.
The communication cost
What about the backward pass? The input x was copied to every GPU on the way forward, so on the way back, the gradients for x from each GPU have to be added up: another all-reduce. So every Transformer layer needs two all-reduces forward and two more backward. They happen in every single layer, right on the critical path of the computation, which is why tensor parallelism usually stays among the GPUs inside a single machine, where the links are fastest.
The code
Column parallelism is just a linear layer whose output dimension is divided by N; row parallelism divides the input dimension by N instead and does one all-reduce after the multiply. Chain them and you have a tensor-parallel MLP:
class ColumnParallelLinear(nn.Module):
def __init__(self, in_features, out_features, world_size, rank):
super().__init__()
self.linear = nn.Linear(in_features, out_features // world_size,
bias=False, device=f"cuda:{rank}")
def forward(self, x):
return self.linear(x)
class RowParallelLinear(nn.Module):
def __init__(self, in_features, out_features, world_size, rank):
super().__init__()
self.linear = nn.Linear(in_features // world_size, out_features,
bias=False, device=f"cuda:{rank}")
def forward(self, x):
# each GPU computes partial result
partial = self.linear(x)
# All-reduce to sum partial results across GPUs
dist.all_reduce(partial, op=dist.ReduceOp.SUM)
return partial
class TensorParallelMLP(nn.Module):
"""column parallel -> activation -> row parallel requires only one all-reduce"""
def __init__(self, d_model, d_ff, world_size, rank):
super().__init__()
self.fc1 = ColumnParallelLinear(d_model, d_ff, world_size, rank)
self.fc2 = RowParallelLinear(d_ff, d_model, world_size, rank)
def forward(self, x):
x = self.fc1(x)
x = nn.functional.silu(x)
return self.fc2(x) # (batch, seq, d_model), all-reduced
Watch out: Tensor parallelism can also be combined with FSDP: sharding the batch dimension B shrinks the all-gathers, and sharding the FFN dimension F cuts down FSDP's communication overhead.
Putting it together
Real large-scale training usually combines several of these: tensor parallelism inside each machine, pipeline parallelism between machines, and data parallelism wrapped around the whole thing. For example, 2 data-parallel replicas × 4 pipeline stages × 4-GPU tensor parallelism per machine. Add sequence parallelism and expert parallelism, and you get what people call 5D parallelism.
Recap
- One GPU can't hold the job or finish it: training 7 billion parameters takes 112 GB (16 bytes per parameter), and one GPU would need 21 years.
- Collectives are the foundation: all-reduce = reduce-scatter (all the adding) + all-gather (all the copying). With a ring, each GPU sends 2(N−1)/N arrays, so the time depends almost only on data size and bandwidth. All-gather and reduce-scatter are each other's backward; all-reduce's backward is another all-reduce.
- To split a matmul, check the contracting dimension: unsplit means no communication; split on one side means all-gather first; split on both sides gives partial sums and needs an all-reduce.
- DDP splits the batch and all-reduces gradients in the backward pass. ZeRO shards optimizer state, gradients and parameters in turn; stages 1 and 2 cost no extra communication, stage 3 (FSDP) about 1.5 times. DP is limited by M<B and the critical batch size, and never shrinks activation memory.
- Pipelines split by layer, with bubble fraction m+p−1p−1; 1F1B saves activation memory, and pipelines suit links between machines. Tensor parallelism splits columns then rows, attention by heads, one all-reduce per block, and suits GPUs within one machine.
Next time we move on to post-training, starting with a basic idea from reinforcement learning: policy gradients.