All courses

Data parallelism

Replicate the model on every GPU, give each a different shard of the batch, and all-reduce the gradients before the step. Explain why this keeps training mathematically identical to one large batch.

Builds on: The LLM training loop, Collective ops: all-reduce, all-gather, reduce-scatter

▶ Watch this lesson Start the whole course

What the animation says

One run, eight GPUs

Your model fits on one GPU. But each training step should use a batch of 1024 sequences, and one GPU is too slow. You have eight GPUs. The goal is strict: the exact step one huge GPU would take. Same gradient, same parameters, after every step. Not just something close. So give every GPU a full copy of the model, and a different slice of the batch: 128 sequences each. Each GPU runs forward and backward on its own slice, all at the same time.

Four tokens, two GPUs

Shrink it so we can follow the numbers. Four tokens, with per-token gradients two, four, minus one, and three. One big GPU averages all four: eight over four, which is two. That's the target. Now split them. GPU one gets two and four; its own mean is three. GPU two gets minus one and three; its mean is one. An all-reduce adds up the GPUs' results and hands every GPU the sum: four. But the target is two. What turns this four into two?

Why it's exact

Divide by the number of GPUs: four over two is two. Exactly the full-batch gradient. The reason: with equal shards, the batch loss is just the average of the shard losses. And the gradient of an average is the average of the gradients. Each GPU gets its piece by ordinary backprop. Every copy starts with the same weights and applies the same averaged gradient. So the copies stay identical, up to tiny rounding. Only one kind of thing crosses between the GPUs each step. Tap it.

The trap: unequal shards

Now a trap. Same four tokens, but split unevenly: three on GPU one, one on GPU two. In real runs this happens with padding. Shards end up with different numbers of real tokens. GPU one's mean is five thirds. GPU two's mean is three. If we average those two means, do we still get the full-batch two?

The fix: divide by tokens

Averaging the means gives seven thirds, not two. The single token on GPU two weighs as much as three. The fix: each GPU sends the sum of its per-token gradients, plus its token count. All-reduce both. Five plus three is eight. Three plus one is four tokens. Eight over four: two again. With equal shards, this is the same as averaging the means and dividing by the number of GPUs.

Check it in code

Let's check it in code. This function is the gradient of a mean squared error over whatever rows it gets. This line is the one big GPU: the gradient over all eight rows at once. These lines split the rows into two equal shards, and each simulated GPU computes its own gradient. Then sum and divide by the GPU count. The check prints True. The price: every GPU holds the whole model. And each step, each GPU sends about twice the gradient's size, whatever the batch size.

8 GPUs, one training run

Your model fits on one GPU, but you want each step to use 1024 sequences, and one GPU takes too long to process that many. You have 8 GPUs. How do you split the work so that the result is **exactly** the run one huge GPU would produce? You want the same gradient and the same parameters after every step, not just something close.

A mean of gradients is a gradient of a mean

Give every GPU a full copy of the model, and give each a different slice of the batch. Each GPU runs forward and backward on its own slice. Think of 8 accountants, each totalling one stack of receipts. Combining their totals gives exactly the grand total. The same holds here. The batch loss is an average over tokens, and the gradient of a sum is the sum of the gradients. So if every slice has the same number of tokens, averaging the 8 slice-gradients with an all-reduce gives exactly the full-batch gradient.

Why the split is exact

Split the $B$ sequences into $G$ shards, one per GPU, each with the same number of target tokens (for example $B/G$ full-length sequences with no padding). Let $\mathcal{L}_g$ be the mean loss over shard $g$'s tokens. Because each shard holds an equal share of the tokens, $$\mathcal{L}=\tfrac1G\sum_{g=1}^{G}\mathcal{L}_g \;\Rightarrow\; \nabla_\theta\mathcal{L}=\tfrac1G\sum_{g}\nabla_\theta\mathcal{L}_g$$ GPU $g$ computes $\nabla_\theta\mathcal{L}_g$ by backprop on its shard. An all-reduce sums these, and each GPU divides by $G$. Every copy started with the same $\theta$ and applies the same update with the same gradient, so all copies stay identical without ever sending weights. The only difference from one big GPU is tiny rounding from adding numbers in a different order.

Four tokens, two GPUs

Suppose the per-token gradients are $2, 4, -1, 3$. The full-batch mean is $8/4=2$. GPU 1 gets $\{2,4\}$, so its local mean is $3$. GPU 2 gets $\{-1,3\}$, so its local mean is $1$. The all-reduce sum is $3+1=4$, and $4/G=4/2=2$. That matches the full batch. The trap is unequal shards. If GPU 1 held $\{2,4,-1\}$ (mean $5/3$) and GPU 2 held $\{3\}$, then $(5/3+3)/2=7/3\neq2$. This happens in practice when padding leaves shards with different numbers of real tokens. In that case, all-reduce the summed per-token gradients and divide by the total token count: $(5+3)/4=2$.

Simulate it in numpy

This simulates 4 GPUs on a toy squared-error model. Each simulated GPU computes the gradient of its shard's mean loss. The averaged result matches the full-batch gradient.
import numpy as np
rng = np.random.default_rng(0)
X, y, w = rng.normal(size=(8, 3)), rng.normal(size=8), rng.normal(size=3)
def grad(Xs, ys, w):  # gradient of mean squared error
    return 2 * Xs.T @ (Xs @ w - ys) / len(ys)
full = grad(X, y, w)                          # one big GPU
G = 4
shards = zip(np.split(X, G), np.split(y, G))  # equal shards
local = [grad(Xs, ys, w) for Xs, ys in shards]  # each GPU
allreduced = sum(local) / G                   # all-reduce sum, then / G
print(np.allclose(full, allreduced))          # True

Remember

Data parallelism means the same model on every GPU and a different shard of the batch on each. Before the optimizer step, all-reduce the gradients. In general, sum each shard's per-token gradient sums and divide by the total token count. With equal shards, this is the same as averaging the shard means (divide by $G$). Because the gradient of an average equals the average of gradients, this is one large-batch step, up to rounding. The cost is that every GPU holds the whole model. With a ring all-reduce (reduce-scatter then all-gather), each GPU also sends about $2(G-1)/G\approx2$ times the gradient size per step, whatever the batch size.

On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.