Training at real scale: multiple GPUs
In stage 06 you trained a model on your CPU. In 06.4, on your GPU. Now the leap you cannot make at home, but can understand: when the model does not fit on a single card.
This document explains the mechanism. There is no code because you would need the hardware — but by the end you will be able to read a real training configuration and understand what is going on.
The problem, in numbers
A 70-billion-parameter model, training with AdamW in fp32:
weights 70,000 M × 4 bytes = 280 GB
gradients 70,000 M × 4 bytes = 280 GB
Adam's m momentum 70,000 M × 4 bytes = 280 GB
Adam's v variance 70,000 M × 4 bytes = 280 GB
-------
1,120 GB
An H100 has 80 GB. You need at least 14 just to hold the state, and that is not counting the activations, which are usually more than people expect.
You compute it yourself in
etapas/06_transformer/02_anatomia.py, section 4.
There are four ways to split it up, and in practice all four get combined.
1. Data parallelism (DP) — the simplest
Each GPU has a complete copy of the model and processes a different batch.
GPU 0: full model ← batch A → gradients A ─┐
GPU 1: full model ← batch B → gradients B ─┼─► average ─► everyone
GPU 2: full model ← batch C → gradients C ─┤ (all-reduce)
GPU 3: full model ← batch D → gradients D ─┘
After each step the gradients are averaged across all GPUs with an operation called all-reduce, and everyone applies the same update. That way all the copies stay identical.
Why it works: the gradient of a large batch is the mean of the gradients of its parts. Mathematically, 4 GPUs at batch 8 each are exactly equivalent to 1 GPU at batch 32.
What it solves: speed. What it does NOT solve: memory. If the model does not fit on one GPU, DP does not help: each one still needs the whole model.
The hidden cost: you have to communicate the entire gradients (280 GB for a 70B) on every step. With slow interconnects, you spend more time communicating than computing. That is why NVLink and InfiniBand exist.
2. ZeRO / FSDP — splitting the state
The key observation: if every GPU has an identical copy of the weights, the gradient and Adam's state, you are storing the same thing N times.
ZeRO (Zero Redundancy Optimizer) splits it, in three cumulative stages:
| Stage | What it splits | Memory per GPU (70B, 64 GPUs) |
|---|---|---|
| — | nothing | 1,120 GB |
| ZeRO-1 | optimizer state | 297 GB |
| ZeRO-2 | + gradients | 288 GB |
| ZeRO-3 / FSDP | + the weights themselves | 17.5 GB |
How ZeRO-3 works (which is what PyTorch calls FSDP):
- Each GPU stores only 1/N of the weights.
- When it is time to compute layer 5, all the GPUs exchange the pieces of that layer (all-gather), compute it, and throw away what was not theirs.
- Same on the way back.
In other words: you trade memory for communication. You reconstruct each layer right when you need it and discard it afterwards.
The intuition: instead of every worker having the complete toolkit, there is one toolkit shared out and passed around as needed. It takes up far less room and you lose time passing it along.
3. Tensor parallelism (TP) — splitting the matrices
For when a single layer does not fit on one GPU.
A linear layer Y = X · W with W of 8192×32768 gets split by columns:
GPU 0: W[:, 0:8192] → Y0 = X · W0
GPU 1: W[:, 8192:16384] → Y1 = X · W1
GPU 2: W[:, 16384:24576] → Y2 = X · W2
GPU 3: W[:, 24576:32768] → Y3 = X · W3
Y = concatenate(Y0, Y1, Y2, Y3)
In attention it is even more natural: each GPU keeps some of the heads. The heads are already independent by design.
Look at your
AtencionCausal.forward: the reshape to(B, T, 3, H, dh)separates the heads explicitly. Splitting theHdimension across GPUs is immediate.
The cost: you have to communicate inside each layer, several times per pass. It is very frequent communication and very latency-sensitive, so tensor parallelism is only used within a single node (8 GPUs joined by NVLink). Across nodes it is unworkable.
4. Pipeline parallelism (PP) — splitting the layers
Layers 1-20 on GPU 0, 21-40 on GPU 1, and so on.
The problem is obvious: while GPU 0 works, the others wait.
Naive: GPU0 ████░░░░░░░░
GPU1 ░░░░████░░░░
GPU2 ░░░░░░░░████ ← 66% of the time idle (the "bubble")
The solution: split the batch into microbatches and overlap them, like an assembly line.
Pipelined: GPU0 ████████░░
GPU1 ░░████████
GPU2 ░░░░██████ ← the bubble shrinks a lot
It is exactly the same principle as instruction pipelining in a processor.
The cost: you only have to communicate the activations at the boundary between stages. That is little communication, so PP does work across nodes.
5. How they combine: 4D parallelism
In a real training run all of them are used at once, each in the dimension where it is cheap:
WITHIN a node (8 GPUs, very fast NVLink) → TENSOR parallelism
BETWEEN nodes in a group → PIPELINE parallelism
BETWEEN groups → DATA parallelism
And on top of all of it → ZeRO for the state
A plausible example with 1,024 GPUs:
TP = 8 (within each node)
PP = 8 (8 nodes per model replica)
DP = 16 (16 replicas in parallel)
8 × 8 × 16 = 1,024
Choosing that configuration is an optimization problem in itself, and every large model publishes its own in its technical report.
6. The other tricks, the ones that save the run
Gradient checkpointing
Do not store the intermediate activations: recompute them on the backward pass.
- Saves an enormous amount of memory (from O(layers) to O(√layers) with the usual strategy)
- Costs ~30% more compute
- It almost always pays off, because memory is the scarce thing
Your
mininndoes not have it, and that is why one step at batch 16 and context 192 runs to around 7 GB. It is the concrete reason this technique exists.
Mixed precision
Compute in bf16 and keep a master copy of the weights in fp32.
Why bf16 and not fp16: bf16 has the same exponent bits as fp32, so it has the same range and does not overflow. fp16 has more precision but less range, and it overflows on the gradients, which forces you to use loss scaling and complicates everything.
Gradient accumulation
If you want an effective batch of 4 million tokens but only 100,000 fit:
for i in 1..40:
compute the loss of a microbatch
perdida.backward() # the gradients ACCUMULATE
optimizador.step() # a single step, with the gradient of all 40
This works precisely because of the behaviour that forces you to call
zero_grad()on every step: autograd accumulates gradients. What was a hazard in stage 03 is the tool here.
Checkpoints
With 1,000 GPUs, something fails every few hours. You have to save every ~20 minutes, and save the optimizer state too (Adam's m and v). If you save only the weights, on resume Adam starts from scratch and the loss takes a visible jump.
7. What really happens in a three-month training run
The technical reports for OPT-175B (Meta) and BLOOM are required reading, because they tell you what the clean papers do not:
- Constant hardware failures. GPUs hanging, nodes going down, memory with errors.
- Loss spikes. The loss shoots up for no apparent reason. Sometimes it recovers on its own; sometimes you have to go back to the last checkpoint and skip that batch of data.
- People on shift 24/7 watching graphs.
- Nothing can be repeated. You do not relaunch a 50-million-euro run because you had a better idea halfway through.
- Silent divergences. Training carries on, the loss goes down, and the resulting model is worse than expected. Finding that out takes weeks.
8. And even so, it is the same loop
All of the above is systems engineering. The maths does not change one comma:
logits = modelo(x)
perdida = cross_entropy(logits, y)
perdida.backward()
optimizador.step()
That loop, which you wrote in etapas/06_transformer/01_entrenar.py, is literally the same one running on 25,000 GPUs for three months. What changes is where the numbers are and how they move between chips.
And that, however small it sounds, is the difference between a weekend project and a billion-euro infrastructure.
To go deeper
| Topic | Where |
|---|---|
| ZeRO | Rajbhandari et al., ZeRO: Memory Optimizations Toward Training Trillion Parameter Models (2019) |
| Megatron (TP) | Shoeybi et al., Megatron-LM (2019) |
| GPipe (PP) | Huang et al., GPipe (2018) |
| How it is really done | the technical reports for OPT-175B, BLOOM and LLaMA 3 |
| In PyTorch | torch.distributed, FSDP, and the DeepSpeed library |
Back to the index: 00-mapa.md