# Distributed Training: Data, Tensor and Pipeline Parallelism

> Data parallelism splits the batch, tensor parallelism the matrices inside a layer, pipeline parallelism the stack of layers; ZeRO and FSDP shard optimizer state, gradients and parameters. Runnable checks verify gradient averaging, ring all-reduce traffic, the Megatron split and the bubble formula.

- URL: https://dmxsf.com/en/wiki/pretraining/distributed-training/
- [DMXSF](https://dmxsf.com/en/about/)
- Advanced
- Updated: 2026-11-27
- Tags: Distributed training, Pretraining

## After this page you will be able to

- Explain why large-model training rarely stays on one GPU or one machine.
- Say what data, tensor and pipeline parallelism each split, and how much communication each one costs.
- Place FSDP, ZeRO, Megatron-LM and DeepSpeed on the map.
- Verify three things in code: when data-parallel gradient averaging matches single-GPU training, why tensor parallelism splits the first matrix by columns and the second by rows, and how much time the pipeline bubble wastes.
- Given a new training job, decide whether to fix memory, bandwidth or scheduling first.

The goal is not the command-line flags of one framework but a map of parallelism strategies.

All experiments on this page ran on the CPU of an Apple M2 Max (PyTorch 2.10.0, the gloo backend for the multi-process runs). On a real cluster communication is far faster and the absolute numbers differ, but what the experiments check are **mathematical equivalences and communication formulas**, which do not depend on the hardware. The few numbers that involve bandwidth and compute are formula-based illustrations and are labelled as such.

## Why one GPU hits a ceiling quickly

Training consumes much more than the model weights. At least four things take memory and compute:

- the parameters
- the gradients
- the optimizer state
- the activations

With Adam, one copy of the parameters comes with several more copies of state, and longer sequences make the activations and the attention cost balloon. Two problems appear quickly:

1. The model simply does not fit.
2. Even if it barely fits, training is far too slow.

Distributed training exists to solve "does not fit" and "too slow" at the same time.

## A framework: what exactly are you splitting?

The easiest way to understand the strategies is to ask one question:

> Did I split the data, the model, or the execution over time?

Which gives:

- Data parallelism: every GPU holds the same model and processes different data.
- Tensor parallelism: the weight matrices of one layer are split across GPUs.
- Pipeline parallelism: different layers, or groups of layers, sit on different devices and are chained like an assembly line.

They do not exclude each other; real large-model training usually combines them.

Putting the three splits in one picture makes the difference easier to see:

*Figure: The most useful entry point to distributed training is not framework names but whether you are splitting the batch, the matrices, or the depth of the network.*

## Data parallelism: the easiest idea and the first one you meet

The intuition is simple:

- Every GPU holds the same copy of the model.
- A large batch is cut into smaller ones.
- Every GPU runs its own forward and backward pass.
- The gradients are synchronized and everyone applies the same update.

It is easy to reason about and barely touches the model code, so it is the usual starting point.

### What DDP does

`DistributedDataParallel` (DDP) classically takes care of gradient synchronization during the backward pass:

- each GPU first computes its own gradients,
- an `all-reduce` then aggregates them,
- so that all replicas stay identical.

The drawback is just as clear: the data is split but the model is replicated in full, so the memory pressure does not go away.

### Hands-on: what does "averaging" the gradients mean?

After the `all-reduce` sum, DDP divides by the number of GPUs, i.e. it **averages** the gradients of the GPUs (the PyTorch documentation says "the gradients between different nodes are averaged"). If every GPU's loss is a mean over an **equal** number of samples, the result is identical to the gradient of one GPU run over the whole batch. The trouble starts when the numbers of samples differ: a language-model loss is a mean over valid tokens, and the sequences on different GPUs differ in length, so the numbers of valid tokens differ.

The script below trains a tiny language model (vocabulary 50, an embedding and one linear layer) in 4 processes (gloo backend) and compares three ways of computing the gradient with the reference answer "one process, the whole batch, averaged over the global number of valid tokens". "Valid length" is the number of non-padding positions in a sequence; 8 sequences are divided over 4 processes, 2 each. Save it as `ddp_check.py` and run `python ddp_check.py`; no `torchrun` is needed:

```python
import os

import torch
import torch.distributed as dist
import torch.multiprocessing as mp
import torch.nn as nn
import torch.nn.functional as F

V, T, WORLD = 50, 16, 4  # vocabulary, sequence length, number of processes

def build():
    torch.manual_seed(0)
    return nn.Sequential(nn.Embedding(V, 8), nn.Linear(8, V))

def token_loss(model, ids, valid):
    """Sum of the loss over valid tokens, and the number of valid tokens."""
    logits = model(ids[:, :-1])
    ce = F.cross_entropy(logits.flatten(0, 1), ids[:, 1:].flatten(),
                         reduction="none")
    mask = valid[:, 1:].flatten()
    return (ce * mask).sum(), mask.sum()

def flat_grad(model):
    return torch.cat([p.grad.flatten() for p in model.parameters()])

def worker(rank, ids, valid, queue):
    os.environ.update(MASTER_ADDR="127.0.0.1", MASTER_PORT="29511")
    dist.init_process_group("gloo", rank=rank, world_size=WORLD)
    model = build()
    mine = slice(rank * 2, rank * 2 + 2)  # each process gets 2 sequences
    total, count = token_loss(model, ids[mine], valid[mine])

    # Way A: average locally, then average across ranks (DDP's default)
    (total / count).backward()
    for p in model.parameters():
        dist.all_reduce(p.grad)
        p.grad /= WORLD
    grad_a = flat_grad(model).clone()

    # Way B: only sum the gradients, divide by the global valid-token count
    model.zero_grad()
    total, count = token_loss(model, ids[mine], valid[mine])
    dist.all_reduce(count)
    (total / count).backward()
    for p in model.parameters():
        dist.all_reduce(p.grad)
    grad_b = flat_grad(model).clone()
    if rank == 0:
        queue.put((grad_a, grad_b))
    dist.destroy_process_group()

def run(lengths):
    torch.manual_seed(1)
    ids = torch.randint(0, V, (8, T))
    valid = (torch.arange(T)[None] < torch.tensor(lengths)[:, None]).float()
    model = build()  # one process, whole batch, global token mean: the truth
    total, count = token_loss(model, ids, valid)
    (total / count).backward()
    ref = flat_grad(model)

    model = build()  # accumulation: 4 micro-batches, each averaged, then / 4
    for k in range(WORLD):
        part = slice(k * 2, k * 2 + 2)
        total, count = token_loss(model, ids[part], valid[part])
        (total / count / WORLD).backward()
    acc = flat_grad(model)

    queue = mp.get_context("spawn").SimpleQueue()
    mp.spawn(worker, args=(ids, valid, queue), nprocs=WORLD)
    grad_a, grad_b = queue.get()
    rel = lambda g: ((g - ref).norm() / ref.norm()).item()
    print(f"valid lengths {lengths}")
    print(f"  A average of per-rank means     rel. error {rel(grad_a):.2e}")
    print(f"  B divide by global token count  rel. error {rel(grad_b):.2e}")
    print(f"  accumulation (mean per micro)   rel. error {rel(acc):.2e}")

if __name__ == "__main__":
    run([16] * 8)  # all sequences full length: A and B agree
    run([16, 14, 12, 12, 10, 8, 8, 4])  # uneven: A over-weights short ones
```

Output ("relative error" is the norm of the difference to the reference divided by the norm of the reference):

```text
valid lengths [16, 16, 16, 16, 16, 16, 16, 16]
  A average of per-rank means     rel. error 2.45e-07
  B divide by global token count  rel. error 2.45e-07
  accumulation (mean per micro)   rel. error 2.42e-07
valid lengths [16, 14, 12, 12, 10, 8, 8, 4]
  A average of per-rank means     rel. error 3.65e-01
  B divide by global token count  rel. error 1.60e-07
  accumulation (mean per micro)   rel. error 3.65e-01
```

1. **With equal lengths all three agree with the reference.** The difference is float32 rounding, of order $10^{-7}$.
2. **With uneven lengths, way A is off by 36.5%.** The four GPUs hold 28, 22, 16 and 10 valid prediction tokens, but way A gives each GPU a weight of 1/4: the 10 tokens on the fourth GPU deserve 13.2% of the weight and get 25%, about 1.9 times too much.
3. **Way B brings the error back to rounding level.** Sum the gradients and divide by the **global** number of valid tokens, and every token has the same weight.
4. **Gradient accumulation is the same math problem.** Processing micro-batches one after another in time or side by side in space averages the loss in the same way. So "global batch = per-GPU batch × GPUs × accumulation steps" only holds when every piece has the same number of samples.

What do frameworks do? The Hugging Face `Trainer` (transformers 5.3.0 in this page's environment) counts the valid tokens (`labels != -100`) of all micro-batches in a gradient-accumulation window before the window starts, sums them across devices when `average_tokens_across_devices` is on, and passes the result to the loss function as `num_items_in_batch`. That is way B. In a hand-written training loop you have to do the same explicitly.

### Ring all-reduce: why traffic does not grow with the number of GPUs

An `all-reduce` gives every GPU the sum of all GPUs' gradients. The naive approach sends everything to one GPU, sums, and broadcasts; that GPU's bandwidth becomes the bottleneck. **Ring all-reduce** connects the $n$ GPUs in a ring, cuts the gradient into $n$ chunks, and runs two phases of $n-1$ steps each:

- **reduce-scatter:** in every step each GPU sends one chunk to its right neighbour, which adds it to its own copy of that chunk. After $n-1$ steps every GPU holds exactly one chunk of the global sum.
- **all-gather:** another $n-1$ steps pass these summed chunks around the ring so that everyone ends up with the full result.

Every step moves only $1/n$ of the data, so each GPU sends $2(n-1)/n$ times the gradient size in total. The simulation below really moves data between $n$ "ranks" and counts the elements each one sends:

```python
import numpy as np

def ring_all_reduce(vectors):
    """Ring all-reduce: per-rank results and elements sent by each rank."""
    n = len(vectors)
    chunks = [np.array_split(v.copy(), n) for v in vectors]
    sent = [0] * n

    for step in range(n - 1):  # phase 1: reduce-scatter, add while passing
        for r in range(n):
            c = (r - step) % n  # the chunk sent to the right neighbour
            chunks[(r + 1) % n][c] += chunks[r][c]
            sent[r] += len(chunks[r][c])
    # now rank r holds the fully summed chunk number (r + 1) % n

    for step in range(n - 1):  # phase 2: all-gather, pass sums around
        for r in range(n):
            c = (r + 1 - step) % n
            chunks[(r + 1) % n][c] = chunks[r][c].copy()
            sent[r] += len(chunks[r][c])
    return [np.concatenate(ch) for ch in chunks], sent

rng = np.random.default_rng(0)
size = 1_000_000  # each rank holds a gradient of one million elements
for n in (2, 4, 8, 16):
    vectors = [rng.standard_normal(size) for _ in range(n)]
    out, sent = ring_all_reduce(vectors)
    ok = all(np.allclose(o, sum(vectors)) for o in out)
    print(f"n={n:2d} correct {ok}  sent per rank {sent[0] / size:.4f} x size"
          f"  formula 2(n-1)/n = {2 * (n - 1) / n:.4f}")
```

```text
n= 2 correct True  sent per rank 1.0000 x size  formula 2(n-1)/n = 1.0000
n= 4 correct True  sent per rank 1.5000 x size  formula 2(n-1)/n = 1.5000
n= 8 correct True  sent per rank 1.7500 x size  formula 2(n-1)/n = 1.7500
n=16 correct True  sent per rank 1.8750 x size  formula 2(n-1)/n = 1.8750
```

The result matches the formula and has three consequences:

1. **The bandwidth term barely grows with the number of GPUs.** What each GPU sends approaches $2S$ ($S$ is the gradient size in bytes) instead of growing linearly, which is what allows data parallelism to scale to thousands of GPUs.
2. **The latency term grows linearly.** There are $2(n-1)$ steps, and each step has a fixed start-up delay.
3. **all-reduce = reduce-scatter + all-gather.** That is why ZeRO-1 and ZeRO-2 communicate as much as plain data parallelism: they merely split these two steps apart and insert "update only my own shard of the parameters" in between.

Put the two terms together: with a start-up latency $\alpha$ per step and a link bandwidth $\beta$, one all-reduce takes about

$$
T \approx 2(n-1)\,\alpha + \frac{2(n-1)}{n}\cdot\frac{S}{\beta}.
$$

For large gradients the second term dominates; for small messages the first does. That is why communication libraries such as NCCL choose between ring, tree and other algorithms depending on message size and network topology. The full comparison of all-reduce implementations, multi-node topology and the all-to-all of MoE is in [Collective Communication](https://dmxsf.com/en/wiki/systems/collective-communication/).

### Why ZeRO and FSDP matter

As models grow, replicating all the weights becomes wasteful. The core idea of both ZeRO and FSDP is to spread the parameters, gradients and optimizer state across the GPUs instead of keeping a full copy everywhere.

Roughly:

- ZeRO-1: shard the optimizer state
- ZeRO-2: also shard the gradients
- ZeRO-3: also shard the parameters
- FSDP: manage parameters shard by shard, gathering and releasing them on demand

These methods are still in the "data-parallel family"; they simply manage memory more aggressively and more finely.

Do the memory savings cost communication? The ZeRO paper (Rajbhandari et al., 2020) analyses it as follows. Let $\Psi$ be the number of parameters. Plain data parallelism moves $2\Psi$ elements per GPU per step: one reduce-scatter and one all-gather, $\Psi$ each. ZeRO-1 and ZeRO-2 reduce-scatter the gradients, let each GPU update only its own shard of the parameters, and all-gather the updated parameters, so the total is still $2\Psi$, **the same as plain data parallelism**. In ZeRO-3 the parameters are sharded too: the forward pass has to gather every layer's parameters, the backward pass gathers them once more, and the gradients are reduce-scattered, for a total of $3\Psi$, **1.5 times plain data parallelism**.

### Hands-on: where does training memory go?

With mixed-precision AdamW (see [Optimizers and training stability](https://dmxsf.com/en/wiki/foundations/optimizers-and-training-stability/) for why it is set up this way), every parameter needs a BF16 weight (2 bytes), a BF16 gradient (2 bytes), and an FP32 master weight plus two moments (12 bytes together): 16 bytes in total, activations not included. For a 7B model that is on the order of 112 GB, which does not fit on an 80 GB GPU. ZeRO (Rajbhandari et al., 2020) shards these three kinds of state step by step across $N$ GPUs:

| Scheme | Model state per GPU |
| --- | --- |
| Plain data parallelism | $16\Psi$ |
| ZeRO-1 (shard optimizer state) | $4\Psi + 12\Psi/N$ |
| ZeRO-2 (also shard gradients) | $2\Psi + 14\Psi/N$ |
| ZeRO-3 (also shard parameters; full-shard FSDP is similar) | $16\Psi/N$ |

Drag the number of GPUs and the model size to see what each level saves.

Two conclusions worth checking:

1. **Take 7.5B parameters on 64 GPUs.** Plain data parallelism needs 111.8 GiB per GPU (the ZeRO paper's 120 GB; the paper uses $10^9$ bytes), and the three ZeRO levels need 29.2, 15.5 and 1.75 GiB (Table 1 of the paper: 31.4, 16.6 and 1.88 GB).
2. **Take 70B parameters and an 80 GiB GPU.** However many GPUs you add, ZeRO-1 and ZeRO-2 do not fit: the unsharded weights ($2\Psi$) and gradients ($2\Psi$) alone exceed one GPU. Only ZeRO-3 works, and it needs at least 14 GPUs to hold the model state, before activations. That is the numerical basis for "if the model does not fit, look at FSDP / ZeRO-3 first". How to account for the activation memory on top of the model state is covered in [The compute and memory ledger of training](https://dmxsf.com/en/wiki/pretraining/compute-and-memory/).

## Tensor parallelism: when one layer is too big, split its insides

When a single layer's matrices no longer fit on one GPU, or one GPU cannot deliver enough compute, data parallelism alone is not enough. That is when tensor parallelism comes in.

Tensor parallelism means: `split the linear algebra of one layer across several GPUs and compute it together`.

The two common ways are:

- split a weight matrix by columns
- split a weight matrix by rows

For a very large linear layer `Y = XW`, if `W` is too big, each GPU can hold a part of `W` and the partial results are then concatenated or summed.

### Benefits of tensor parallelism

- The capacity of a single layer is no longer limited by one GPU.
- Large matrix multiplications use more devices in parallel.
- It is essential for very large models; many models with tens or hundreds of billions of parameters depend on it.

### Costs of tensor parallelism

- Communication inside every layer is frequent and depends on fast interconnect.
- It is complex to implement and tightly coupled to the model code.
- If the bandwidth between GPUs is too low, communication can eat the theoretical speed-up.

So tensor parallelism is not "the earlier the better". It pays off when the model really approaches the limits of the hardware.

### Hands-on: why the Megatron split goes columns first, rows second

The MLP of a Transformer is $Y=\mathrm{GeLU}(XA)\,B$: $A$ expands the hidden size $h$ to $4h$ and $B$ projects it back to $h$. Megatron-LM (Shoeybi et al., 2019) splits $A$ **by columns** into $A_1,\dots,A_t$ and $B$ **by rows** into $B_1,\dots,B_t$. GPU $i$ takes $A_i$ and $B_i$, runs the whole MLP by itself, and the outputs of the GPUs are added at the end:

$$
Y=\sum_{i=1}^{t}\mathrm{GeLU}(XA_i)\,B_i .
$$

That needs a single `all-reduce` at the very end. If you split $A$ by rows instead, every GPU only gets a **partial sum** of $XA$, and GeLU is nonlinear: $\mathrm{GeLU}(a+b)\neq\mathrm{GeLU}(a)+\mathrm{GeLU}(b)$. The full $XA$ must be all-reduced before the activation, which adds a synchronization point in the middle. The code runs both ways:

```python
import torch
import torch.nn.functional as F

torch.manual_seed(0)
x = torch.randn(4, 16, 64, dtype=torch.float64)  # (batch, sequence, hidden)
W1 = torch.randn(64, 256, dtype=torch.float64) / 8
W2 = torch.randn(256, 64, dtype=torch.float64) / 16
ref = F.gelu(x @ W1) @ W2  # one-GPU MLP: expand, activate, project back

for t in (2, 4, 8):  # tensor-parallel degree
    # Megatron split: W1 by columns, W2 by rows; each GPU runs a full MLP
    parts = [F.gelu(x @ a) @ b
             for a, b in zip(W1.chunk(t, dim=1), W2.chunk(t, dim=0))]
    out = sum(parts)  # the only communication: one all-reduce(sum)
    print(f"t={t}: max error {(out - ref).abs().max():.1e}")

# Counter-example: split W1 by rows (input dim); each GPU gets a partial sum,
# but the activation function cannot be applied to partial sums
t = 4
xs, ws = x.chunk(t, dim=-1), W1.chunk(t, dim=0)
wrong = sum(F.gelu(xi @ wi) for xi, wi in zip(xs, ws)) @ W2
right = F.gelu(sum(xi @ wi for xi, wi in zip(xs, ws))) @ W2  # sum first
print(f"activate, then sum   max error {(wrong - ref).abs().max():.1e}")
print(f"sum, then activate   max error {(right - ref).abs().max():.1e}")
```

```text
t=2: max error 2.2e-15
t=4: max error 2.7e-15
t=8: max error 3.1e-15
activate, then sum   max error 1.2e+00
sum, then activate   max error 1.8e-15
```

1. **Columns first, rows second is exactly equivalent to one GPU.** With 2, 4 or 8 shards the error is only float64 rounding ($10^{-15}$), and the whole MLP needs just one all-reduce in the forward pass.
2. **"Activate, then sum" is wrong.** The error is 1.2, comparable to the size of the output. To use a row split you must sum before the activation, which costs an extra round of communication.
3. **Attention uses the same idea.** Split by attention heads: the $Q$, $K$ and $V$ projections are split by columns, every GPU computes its own heads independently, the output projection is split by rows, and again one all-reduce finishes the job.
4. **The communication bill.** The Megatron-LM paper states that a Transformer layer needs 2 all-reduces in the forward pass (one for attention, one for the MLP) and 2 in the backward pass, each carrying the activation of one micro-batch (shape $b\times s\times h$). This traffic is on the critical path and hard to overlap with compute, so tensor parallelism is normally confined to the fast interconnect inside one machine; the "communication" section below puts numbers on this.

The widget below repeats the experiment with the same shapes: first what each card holds and computes, then the outputs summed card by card against one GPU, and finally one intermediate channel to see why GeLU cannot be split.

## Pipeline parallelism: cut the layer stack into stages

The starting point is: if the model has many layers, put the first few on device A, the middle ones on device B and the last ones on device C.

Different micro-batches then flow through the stages like products through a factory line.

For example:

- GPU0 holds layers 1 to 12
- GPU1 holds layers 13 to 24
- GPU2 holds layers 25 to 36

While the first micro-batch moves on to GPU1, GPU0 can already start on the second.

### What pipeline parallelism solves

- No single device has to hold the whole network.
- Splitting by layers spreads the memory load naturally.
- It suits very deep networks.

### Its biggest pain point

The classic problem is the pipeline bubble: some stages sit idle because they are not being fed. With too few micro-batches or unevenly sized stages, device utilization falls.

So pipeline parallelism is not just "cutting the layers"; it is also about how evenly you cut.

### Hands-on: how micro-batches shrink the bubble

Let the pipeline have $p$ stages and a batch be cut into $m$ micro-batches. GPipe runs all forward passes first and then all backward passes: during the first $p-1$ forward steps and the last $p-1$ backward steps some stages always wait. The Megatron-LM paper gives the bubble time as a fraction of the ideal compute time:

$$
\frac{t_{\text{pb}}}{t_{\text{id}}} = \frac{p-1}{m},
$$

which corresponds to an idle share of $(p-1)/(m+p-1)$ of the total time. The widget below simulates the GPipe and 1F1B schedules from their dependencies and also counts how many micro-batches the first stage has to keep activations for.

1. **The bubble shrinks as long as $m$ is much larger than $p$.** With $p=4$, $m=4$ idles $3/7 \approx 42.9\%$ of the time and $m=32$ only $3/35 \approx 8.6\%$.
2. **GPipe and 1F1B have the same bubble; they differ in activation memory.** With $p=4$ and $m=8$ both idle $3/11 \approx 27.3\%$, but the first stage keeps activations for 8 micro-batches under GPipe and only 4 under 1F1B (never more than $p$).
3. **Interleaved schedules shrink the bubble further.** Each GPU owns $v$ non-contiguous chunks of layers, which reduces the bubble to $1/v$ at the price of $v$ times more communication.

You can check the formula with code too. The script below builds the GPipe timetable from the dependencies (each stage needs 1 time unit per forward step and 2 per backward step, and does one job at a time), measures how long each stage is idle, and compares it with $(p-1)/(m+p-1)$:

```python
def gpipe(p, m, t_fwd=1.0, t_bwd=2.0):
    """GPipe schedule: p stages, m micro-batches, all forward then all back."""
    free = [0.0] * p  # when each stage can start its next job
    fwd = [[0.0] * m for _ in range(p)]  # forward completion times
    bwd = [[0.0] * m for _ in range(p)]  # backward completion times
    for i in range(m):
        for s in range(p):
            ready = fwd[s - 1][i] if s else 0.0
            fwd[s][i] = free[s] = max(free[s], ready) + t_fwd
    for i in range(m):
        for s in reversed(range(p)):
            ready = bwd[s + 1][i] if s < p - 1 else fwd[s][i]
            bwd[s][i] = free[s] = max(free[s], ready) + t_bwd
    total = max(free)
    busy = m * (t_fwd + t_bwd)  # time each stage actually computes
    return total, 1 - busy / total

for p, m in [(4, 4), (4, 8), (4, 16), (4, 32), (8, 32)]:
    total, idle = gpipe(p, m)
    print(f"p={p} m={m:2d}  total {total:5.0f}  idle {idle:6.1%}"
          f"  formula (p-1)/(m+p-1) = {(p - 1) / (m + p - 1):6.1%}")
```

```text
p=4 m= 4  total    21  idle  42.9%  formula (p-1)/(m+p-1) =  42.9%
p=4 m= 8  total    33  idle  27.3%  formula (p-1)/(m+p-1) =  27.3%
p=4 m=16  total    57  idle  15.8%  formula (p-1)/(m+p-1) =  15.8%
p=4 m=32  total   105  idle   8.6%  formula (p-1)/(m+p-1) =   8.6%
p=8 m=32  total   117  idle  17.9%  formula (p-1)/(m+p-1) =  17.9%
```

The total time is exactly $(m+p-1)\times(t_{\text{fwd}}+t_{\text{bwd}})$: the forward and the backward phase each carry $p-1$ extra time units of filling and draining, while every stage has only $m$ micro-batches of work, so the idle share is $(p-1)/(m+p-1)$. The last two rows show one more thing: with the same $m=32$, going from 4 to 8 stages raises the idle share from 8.6% to 17.9%, so **the finer you cut, the more micro-batches you need**.

## How the three combine

Industrial training is rarely a choice of one; it is a three-dimensional combination. Think of it as:

- data parallelism scales sample throughput horizontally,
- tensor parallelism splits the big layers,
- pipeline parallelism splits the stack of layers.

That is what "3D parallelism" means in many frameworks.

A rough example:

- 2-way tensor parallelism inside every group of 2 GPUs,
- each such group forms one pipeline stage,
- and the pipelines are replicated 2-way for data parallelism.

It sounds complicated, but it simply splits along several dimensions at the same time.

## Which one first?

A practical framework:

### Case 1: the model fits but training is too slow

Start with data parallelism: it raises throughput most directly and costs the least engineering.

### Case 2: the model does not fit, but the layers are not enormous

Look at FSDP or ZeRO-3 first. They often squeeze out the memory without deep changes to the model code.

### Case 3: a single matrix is already too large

You need tensor parallelism, because the problem is no longer wasted replicas but the layer itself.

### Case 4: the model is very deep and splitting between layers is natural

Pipeline parallelism can help, but stage partitioning and micro-batch scheduling must be handled carefully.

Compressing these four cases into a "what to do first" diagram is closer to real engineering decisions:

*Figure: Many teams do not start with 3D parallelism: data parallelism or FSDP removes most of the problems, and tensor or pipeline parallelism comes in for the real bottleneck.*

## A common engineering path: FSDP or DeepSpeed first

If this is your first real distributed run, the usual route is not full 3D parallelism but one of these two:

1. `PyTorch FSDP + torchrun`
2. `DeepSpeed ZeRO + accelerate / the deepspeed launcher`

The former is closer to the PyTorch ecosystem; the latter has a lot of mature large-model experience behind it. A minimal `torchrun` launch looks roughly like this:

```bash
torchrun --nproc_per_node=4 train.py \
  --model_name Qwen/Qwen2.5-7B \
  --fsdp "full_shard auto_wrap" \
  --bf16 true \
  --gradient_checkpointing true
```

What the flags signal:

- `nproc_per_node=4` starts 4 processes on this machine, one per GPU
- `full_shard` shards the parameters and gradients
- `gradient_checkpointing` trades time for memory

It is not an optimal configuration, but it is enough to take you from one GPU to several.

## Why communication decides success or failure

Beginners often look only at the number of GPUs and ignore the traffic between them. In fact:

- data parallelism depends on gradient synchronization,
- tensor parallelism depends on exchanging intermediate results inside a layer,
- pipeline parallelism depends on passing activations between stages.

If the interconnect is weak, for example plain PCIe instead of a fast fabric such as NVLink or InfiniBand, "can be parallelized in theory" does not mean "is faster in practice".

A rule of thumb:

- Data parallelism is sensitive to communication but usually the easiest to accept.
- Tensor parallelism depends the most on high-bandwidth, low-latency links.
- Pipeline parallelism depends more on balanced stages and good scheduling.

### Hands-on: doing the communication arithmetic

Plugging the formulas above into one model turns these rules of thumb into numbers. The example is the shape of Llama 2 7B (6.738B parameters, 32 layers, hidden size 4096, sequence length 4096) in BF16. It answers three questions: how much data does each kind of parallelism move per step; how does tensor-parallel communication compare with its compute; and with a fixed global batch, can communication still be hidden as GPUs are added?

The bandwidths are the figures reported in the DeepSeek-V3 paper (about 160 GB/s for NVLink inside a node, about 50 GB/s for InfiniBand between nodes). The compute peak is the dense BF16 peak of the H100 SXM, 989 TFLOPs, with an MFU of 40%. **These numbers do not come from one machine; they are only for a feel of the orders of magnitude, not measurements.**

```python
PSI = 6.738e9  # parameters of Llama 2 7B
H, LAYERS, SEQ = 4096, 32, 4096  # hidden size, layers, sequence length
BF16, GB = 2, 1e9  # bytes per number
# Illustrative values: H100 dense BF16 peak, 40% MFU, and the two bandwidths
# reported in the DeepSeek-V3 paper
PEAK, MFU, NVLINK, IB = 989e12, 0.40, 160 * GB, 50 * GB

def ring(n, nbytes):
    """Bytes each GPU sends in a ring all-reduce."""
    return 2 * (n - 1) / n * nbytes

n = 64
grads = PSI * BF16  # total bytes of BF16 gradients
print(f"data parallel, n={n}")
print(f"  DDP / ZeRO-1/2  per GPU per step {ring(n, grads) / GB:5.1f} GB")
# ZeRO-3: all-gather in forward, all-gather again in backward, reduce-scatter
zero3 = 3 * (n - 1) / n * grads
print(f"  ZeRO-3 / FSDP   per GPU per step {zero3 / GB:5.1f} GB")

act = 1 * SEQ * H * BF16  # activation bytes of one layer, one sequence
print("tensor parallel, per micro-batch per GPU")
for t in (2, 4, 8):
    tp = LAYERS * 4 * ring(t, act)  # 2 all-reduces forward + 2 backward / layer
    compute = 6 * PSI * SEQ / t / (PEAK * MFU)  # same micro-batch, per GPU
    print(f"  t={t}  {tp / GB:4.1f} GB: NVLink {tp / NVLINK * 1e3:3.0f} ms, "
          f"IB {tp / IB * 1e3:3.0f} ms, compute {compute * 1e3:3.0f} ms")
print(f"pipeline parallel: {2 * act / 1e6:.1f} MB per micro-batch per boundary")

# Fixed global batch, more GPUs? (a model, not a measurement)
comm = ring(n, grads) / IB  # gradient sync time, nearly independent of n
glob = 4 * 2**20  # global batch of 4M tokens
print(f"\ngradient sync {comm:.2f} s; global batch {glob / 2**20:.0f}M tokens")
for gpus in (64, 128, 256, 512, 1024):
    compute = 6 * PSI * (glob / gpus) / (PEAK * MFU)  # per-GPU step compute
    exposed = max(0.0, comm - compute * 2 / 3)  # only backward (~2/3) hides it
    print(f"{gpus:5d} GPUs {glob // gpus:6d} tok  compute {compute:5.2f} s"
          f"  exposed {exposed:4.2f} s  eff. "
          f"{compute / (compute + exposed):5.1%}")
need = comm / (4 * PSI / (PEAK * MFU))  # tokens per GPU for backward to hide it
print(f"each GPU needs about {need:,.0f} tokens per step to hide the sync")
```

```text
data parallel, n=64
  DDP / ZeRO-1/2  per GPU per step  26.5 GB
  ZeRO-3 / FSDP   per GPU per step  39.8 GB
tensor parallel, per micro-batch per GPU
  t=2   4.3 GB: NVLink  27 ms, IB  86 ms, compute 209 ms
  t=4   6.4 GB: NVLink  40 ms, IB 129 ms, compute 105 ms
  t=8   7.5 GB: NVLink  47 ms, IB 150 ms, compute  52 ms
pipeline parallel: 67.1 MB per micro-batch per boundary

gradient sync 0.53 s; global batch 4M tokens
   64 GPUs  65536 tok  compute  6.70 s  exposed 0.00 s  eff. 100.0%
  128 GPUs  32768 tok  compute  3.35 s  exposed 0.00 s  eff. 100.0%
  256 GPUs  16384 tok  compute  1.67 s  exposed 0.00 s  eff. 100.0%
  512 GPUs   8192 tok  compute  0.84 s  exposed 0.00 s  eff. 100.0%
 1024 GPUs   4096 tok  compute  0.42 s  exposed 0.25 s  eff. 62.5%
each GPU needs about 7,788 tokens per step to hide the sync
```

1. **Data parallelism: one gradient exchange per step, almost independent of the number of GPUs.** On 64 GPUs each GPU sends 26.5 GB per step; ZeRO-3 gathers the parameters twice more and sends 39.8 GB, exactly 1.5 times as much, in line with the ZeRO paper's analysis.
2. **Tensor parallelism: communication is on the critical path and only suits fast interconnect.** With $t=8$ each GPU sends 7.5 GB per micro-batch, which takes 47 ms over NVLink, already as long as the 52 ms of compute; over InfiniBand it takes 150 ms, nearly three times the compute. The more you split, the less compute each GPU has while the traffic even grows slightly ($2(t-1)/t$ approaches 2), so the tensor-parallel degree is normally capped at the number of GPUs in one machine.
3. **The bigger the model, the better tensor parallelism pays off.** Per token and layer the communication is about $16\,\tfrac{t-1}{t}\,h$ bytes and the compute about $72\,h^2$ FLOPs (forward plus backward, attention scores ignored); their ratio is inversely proportional to the hidden size $h$, so doubling the hidden size halves the communication share.
4. **Pipeline parallelism passes one activation across each boundary between adjacent stages.** That is 67 MB per micro-batch (forward activations plus backward gradients), two orders of magnitude less than the 7.5 GB of tensor parallelism, so it tolerates inter-node InfiniBand much better.
5. **With a fixed global batch, adding GPUs makes the communication "show through".** Doubling the GPUs halves each GPU's compute time while the gradient sync stays at 0.53 s. Under these assumptions each GPU needs about 7,800 tokens per step for the backward pass to hide the gradient sync; with 1024 GPUs only 4096 tokens remain per GPU and scaling efficiency drops to 62.5%. The model assumes perfect overlap and no latency term, so real systems degrade earlier and more smoothly: it is an **upper bound**. The Llama 3 paper reports the same effect: with the global batch fixed at 16M tokens, going from 8K to 16K GPUs lowered MFU from 43% to 41% (see [The compute and memory ledger of training](https://dmxsf.com/en/wiki/pretraining/compute-and-memory/)).

## Why activation checkpointing shows up everywhere

Many multi-GPU launch commands also switch on `gradient checkpointing` or activation recomputation. The reason is simple:

- Distribution does not remove the activation cost.
- In long-sequence training the activations are often still the main memory pressure.

Activation checkpointing does not keep every intermediate result in the forward pass and recomputes parts of them in the backward pass. It does not conflict with any parallelism strategy and usually comes with them. The price is one extra forward pass per step, about a third more compute; how much it saves and whether it is worth it is worked out in [The compute and memory ledger of training](https://dmxsf.com/en/wiki/pretraining/compute-and-memory/) (for Llama 2 7B with 4096 tokens the activations drop from 18.75 GiB to 1.59 GiB).

### Checkpoint granularity and offload

The memory optimization lecture in [CMU ML Systems](https://mlsyscourse.org/schedule) puts two strategies on the timeline. Rematerialization reruns forward operations when backward needs the activations. Offload moves activations to host memory and fetches them when needed. Compare delays on the critical path. Recompute that runs in series adds its full duration. With prefetching, computation may overlap part of the transfers out and back.

Consider $L$ layers, segments of at most $s$ layers, and equal-sized activation slots. Saving the input to each segment uses $\lceil L/s\rceil$ slots. Recomputation during backward can use another $s$ temporary slots for one segment. Thus $\lceil L/s\rceil+s$ is a conservative peak bound in this model. The code sweeps several segment sizes with Python 3.14.3 on an Apple M2 Max.

```python
from math import ceil

layers = 36

def checkpoint_slots(segment):
    checkpoints = ceil(layers / segment)
    return checkpoints + segment

segments = (1, 3, 6, 9, 18, 36)
best = min(segments, key=checkpoint_slots)
assert best == 6 and checkpoint_slots(best) == 12
for segment in segments:
    print(f"segment {segment:2}: {checkpoint_slots(segment):2} slots")
```

```text
segment  1: 37 slots
segment  3: 15 slots
segment  6: 12 slots
segment  9: 13 slots
segment 18: 20 slots
segment 36: 37 slots
```

Short segments save many boundaries. Long segments need more temporary storage while recomputing. The continuous approximation $L/s+s$ is minimized near $\sqrt{L}$. Real layers have different activation sizes and recomputation costs. Tensor lifetime, communication buffers, and microbatch count also affect the peak. Compare activation memory, total memory, and step time separately, then inspect whether copies, communication, and recompute overlap.

## What to watch during training

Once you train on several GPUs, loss alone no longer tells you whether the system is healthy. Also watch:

- whether memory per GPU is balanced,
- whether GPU utilization stays low for long,
- how long the GPUs wait on communication,
- whether the step time jitters,
- whether gradient sync has become the bottleneck,
- whether OOMs or NCCL timeouts occur often.

Many stalled projects have nothing wrong with the model; one parallelism dimension is simply configured out of balance.

Lining up symptoms, bottlenecks and first actions helps you avoid the reflex of "add more GPUs" or "use heavier parallelism" every time multi-GPU training misbehaves:

| Symptom | Likely bottleneck | First thing to check |
| --- | --- | --- |
| Doubling the GPUs barely raises throughput | Usually not a lack of GPUs: gradient sync, data loading or the global batch design has become the new bottleneck | GPU utilization, communication wait, the DataLoader, and whether global batch and gradient accumulation are balanced |
| Still frequent OOMs on multiple GPUs | Activations or optimizer state are still too heavy, or a better sharding strategy is not in use yet | Try FSDP / ZeRO, gradient checkpointing and a shorter sequence before reaching for heavier tensor parallelism |
| NCCL timeouts or visibly jittery step times | A weak topology, too little inter-node bandwidth, or one rank that slows everyone down | The interconnect, per-rank timelines, NCCL logs and batch jitter; do not look at the average step time only |
| Pipeline idles, GPU utilization is uneven | Most likely uneven stages, too few micro-batches, or tensor parallelism would fit better than more stages | Tune stage balance and micro-batches first, then decide whether to change the parallel dimension |

The most common misjudgment in distributed training is treating "more GPUs" as the universal answer instead of first locating which parallel dimension the bottleneck is in.

## Common misconceptions

### 1. Thinking more GPUs always means linear speed-up

Once communication, I/O or scheduling becomes the bottleneck, adding GPUs may only add complexity instead of proportional gains.

### 2. Reaching for tensor parallelism as soon as the model does not fit

FSDP or ZeRO is often enough to solve the memory problem without introducing heavier changes to the model code.

### 3. Neglecting batch design

The global batch size in distributed training is usually `per_device_batch * world_size * grad_accumulation`. If these quantities are not thought through, stability and throughput can both suffer. There is also a subtler precondition: this product only holds when every piece has the same number of samples; with uneven sequence lengths you have to normalize by the global number of valid tokens, otherwise the short batches get too much weight (36.5% off in the experiment above).

### 4. Watching only the average throughput, not the tail

Some configurations have a good average speed but suffer from severe occasional jitter and costly recovery. Check stability before launch, not just the peak speed.

## Summary and exercises

**Key points:**

1. The three parallelisms split different things: data parallelism splits the batch, tensor parallelism the matrices inside a layer, pipeline parallelism the stack of layers. ZeRO and FSDP belong to the data-parallel family and shard optimizer state, gradients and parameters in turn, taking the per-GPU model state from $16\Psi$ down to $16\Psi/N$.
2. In data parallelism, averaging gradients is only equivalent to one large batch when every piece has the same number of samples. With unequal valid-token counts, sum the gradients and divide by the global number of valid tokens; gradient accumulation is the same problem.
3. A ring all-reduce sends $2(n-1)/n$ times the gradient size per GPU, which barely grows with the number of GPUs. It equals a reduce-scatter plus an all-gather, so ZeRO-1 and ZeRO-2 communicate as much as plain data parallelism and ZeRO-3 1.5 times as much.
4. Tensor parallelism has to split by columns first and rows second to bring the communication of MLP and attention down to 2 all-reduces per layer in the forward pass and 2 in the backward pass; this traffic is on the critical path and only suits fast intra-node links. Pipeline parallelism communicates little but needs enough micro-batches to push the bubble $(p-1)/(m+p-1)$ down.
5. With a fixed global batch, adding GPUs shortens the compute per GPU and exposes the communication, so scaling efficiency drops. Find out whether memory, bandwidth or bubbles are the bottleneck before choosing a parallelism.

### Quick self-check

**1. Four GPUs run data parallelism; each GPU averages the loss over its own valid tokens and the sequence lengths differ. How does DDP's default gradient averaging compare with single-GPU training on the whole batch?**

- [ ] Identical, because all-reduce is an exact sum
- [x] Every GPU gets a weight of 1/4, so GPUs with few valid tokens are over-weighted and the gradient is biased
- [ ] The gradient is always too large
- [ ] The bias only appears with FSDP

> All-reduce itself is exact; the bias comes from "average inside each GPU first, then average across GPUs". In this page's experiment, four GPUs with 28, 22, 16 and 10 valid tokens give a gradient that is off by 36.5% relative to the reference; summing the gradients and dividing by the global valid-token count brings the error back to $10^{-7}$.

**2. In a ring all-reduce over $n$ GPUs, each holding $S$ bytes of gradients, how much does each GPU send in total?**

- [ ] $(n-1)\,S$
- [ ] $S/n$
- [x] $2(n-1)S/n$, approaching $2S$ as $n$ grows
- [ ] $nS$

> The reduce-scatter and the all-gather take $n-1$ steps each, and each step sends $S/n$. That is why the bandwidth cost of gradient sync barely grows with the number of GPUs; what does grow is the number of steps (latency).

**3. Why does Megatron-LM split the first linear layer of the MLP by columns and the second by rows?**

- [x] With a column split each GPU gets a complete slice of the hidden units, GeLU can be applied locally, and the whole MLP needs only one final all-reduce
- [ ] A row split uses the least memory
- [ ] So that the outputs of the GPUs differ
- [ ] It is just a convention; row-then-column would make no difference

> Splitting the first layer by rows gives each GPU only a partial sum, and GeLU is nonlinear, so you cannot activate first and sum afterwards. In this page's code, "activate then sum" has an error of 1.2, while "sum first" is at rounding level but costs one more communication.

**4. A pipeline has 4 stages and a batch is cut into 16 micro-batches. Under the GPipe schedule, what share of the total time is idle?**

- [ ] 42.9%
- [x] 15.8%
- [ ] 8.6%
- [ ] 25%

> The idle share is $(p-1)/(m+p-1)=3/19\approx15.8\%$. 42.9% is the value for $m=4$ and 8.6% the value for $m=32$.

**5. Compared with plain data parallelism, how much communication does ZeRO-3 (full-shard FSDP) need per step?**

- [ ] The same
- [ ] Half, because each GPU handles only $1/N$ of the state
- [x] 1.5 times: the parameters are gathered once more in the forward pass and once in the backward pass
- [ ] Twice

> The ZeRO paper's analysis gives $2\Psi$ for plain data parallelism, the same $2\Psi$ for ZeRO-1 and ZeRO-2, and $3\Psi$ for ZeRO-3. In this page's example, a 7B model on 64 GPUs sends 26.5 GB versus 39.8 GB per GPU per step.

**6. A machine has 8 GPUs with 80 GiB each, and you want to train a 70B model with mixed-precision AdamW. Is ZeRO-3 / FSDP alone enough?**

- [ ] Yes, dividing the model state by 8 makes it fit
- [x] No: the model state is about 130 GiB per GPU, already above 80 GiB, and activations are not even counted
- [ ] Yes, with gradient checkpointing switched on
- [ ] Yes, if you use BF16

> The 16 bytes per parameter of model state add up to $16\times70\times10^9$ bytes; divided by 8 that is $1.4\times10^{11}$ bytes, about 130 GiB. Gradient checkpointing only saves activations, and BF16 is already counted in the 16 bytes. At least 14 GPUs are needed just for the model state, and in practice you combine it with tensor or pipeline parallelism or offload the state to CPU memory.

**Exercises:**

1. A 7B model (6.738B parameters) with BF16 gradients runs a ring all-reduce. How many GB does each GPU send per step with 8 GPUs and with 1024 GPUs?
2. A pipeline has 8 stages. How many micro-batches are needed to keep the GPipe idle share within 10%?
3. The loss curve of an 8-GPU data-parallel run jitters far more early on than when you reproduce it on one GPU; sequence lengths vary between 128 and 2048. What do you check first?
4. A model doubles its hidden size from 4096 to 8192 with the tensor-parallel degree unchanged. How does the ratio of tensor-parallel communication to compute change, and what does that mean for "should we use tensor parallelism"?

<details>
<summary>Reference answers</summary>

1. The gradients total $6.738\times10^9\times2=13.476$ GB. With 8 GPUs: $2\times7/8\times13.476\approx23.6$ GB; with 1024 GPUs: $2\times1023/1024\times13.476\approx26.9$ GB. The GPU count grows 128-fold while each GPU's traffic grows only about 14%.
2. We need $(p-1)/(m+p-1)\le0.1$, i.e. $7/(m+7)\le0.1$, so $m\ge63$. With many stages the number of micro-batches has to grow with them, which in turn requires a large enough global batch.
3. First the loss normalization: does each GPU divide by its own valid-token count and are the results then averaged (way A)? With large length differences the GPUs with few tokens are over-weighted, which makes the gradient noisier and biased. Switch to dividing by the global number of valid tokens, then check the padding ratio and whether the global batch and learning rate still match after the change in parallelism.
4. The communication per token and layer is about $16\,\tfrac{t-1}{t}\,h$ bytes and the compute about $72\,h^2$ FLOPs; the ratio is inversely proportional to $h$, so doubling the hidden size halves the communication share. Bigger models therefore suit tensor parallelism better, and on small models tensor parallelism easily lets communication swamp compute.

</details>

## Further reading

- For the whole training pipeline, continue with [The LLM training pipeline](https://dmxsf.com/en/wiki/pretraining/training-pipeline/).
- For why the training budget has to be planned together with scale, read [Scaling laws](https://dmxsf.com/en/wiki/pretraining/scaling-laws/) and the [breakdown](https://dmxsf.com/en/blog/scaling-laws-for-neural-language-models/) of the original paper by Kaplan et al., [Scaling Laws for Neural Language Models](https://arxiv.org/abs/2001.08361).
- For the memory and compute arithmetic of training, see [The compute and memory ledger of training](https://dmxsf.com/en/wiki/pretraining/compute-and-memory/); for how expert parallelism fits into this map, see [Mixture of Experts](https://dmxsf.com/en/wiki/architecture/mixture-of-experts/).
- For a real training system that pushes pipeline parallelism, cross-node expert parallelism and communication overlap to the limit, read the [DeepSeek-V3 technical report](https://arxiv.org/abs/2412.19437) (DualPipe, cross-node communication and FP8).
- Original papers: Rajbhandari et al., [ZeRO: Memory Optimizations Toward Training Trillion Parameter Models](https://arxiv.org/abs/1910.02054) ([paper breakdown](https://dmxsf.com/en/blog/zero-memory-optimizations-toward-training-trillion-parameter-models/)); Shoeybi et al., [Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism](https://arxiv.org/abs/1909.08053); Narayanan et al., [Efficient Large-Scale Language Model Training on GPU Clusters Using Megatron-LM](https://arxiv.org/abs/2104.04473) (the bubble formula and interleaved schedules); Huang et al., [GPipe](https://arxiv.org/abs/1811.06965).
- 4D parallelism on 16,384 H100s (the order of TP, CP, PP and FSDP), MFU and 54 days of failure statistics: see the [Llama 3 breakdown](https://dmxsf.com/en/blog/the-llama-3-herd-of-models/).

## Companion code

[Distributed training: gradients, ZeRO, tensor and pipeline parallelism](https://github.com/dmxsf/dmxsf/tree/main/labs/pretraining/distributed-training): Built and measured in a few processes on one machine: data-parallel gradient averaging, the ring all-reduce, data parallelism, ZeRO-1 and ZeRO-3 trained side by side (same weights, measured memory and communication), Megatron-style tensor parallelism, and pipeline schedules.

- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run pretraining/distributed-training`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/pretraining/distributed-training/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/pretraining/distributed-training/README.en.md)
- [`parallel.py`](https://github.com/dmxsf/dmxsf/blob/main/src/dmxsf/pretraining/parallel.py)
- [`distributed.py`](https://github.com/dmxsf/dmxsf/blob/main/src/dmxsf/pretraining/distributed.py)
- [Find this lab in the catalog](https://dmxsf.com/en/code/#distributed-training)

## FAQ

### What do data, tensor and pipeline parallelism each split?

Data parallelism splits the data: every GPU holds a full copy of the model, processes a different mini-batch, and the gradients are then synchronized. Tensor parallelism splits the matrices inside a layer: the linear algebra of one layer is spread over several GPUs. Pipeline parallelism splits the stack of layers: different groups of layers live on different devices and micro-batches flow through them like items on an assembly line.

### What problem do FSDP and ZeRO solve?

In plain data parallelism every GPU stores the full parameters, gradients and optimizer state, which wastes memory. ZeRO and FSDP shard that state across GPUs: ZeRO-1 shards the optimizer state, ZeRO-2 also the gradients, ZeRO-3 also the parameters; FSDP manages parameters in shards, gathering them when needed and releasing them afterwards. They are still part of the data-parallel family and are often the first step in practice.

### If the model does not fit, do I have to use tensor parallelism?

Not necessarily. FSDP or ZeRO often solve the memory problem on their own. Tensor parallelism communicates inside every layer, depends on fast interconnect and is entangled with the model code, so it pays off when a single layer's matrices approach the limits of one GPU. It is not something to reach for early.

### Why does adding GPUs not speed training up linearly?

As soon as communication, I/O or scheduling becomes the bottleneck, more GPUs stop paying off proportionally. A ring all-reduce sends almost the same amount of data per GPU no matter how many GPUs there are, while with a fixed global batch doubling the GPUs halves each GPU's compute time; once compute is too short to hide the gradient sync, scaling efficiency drops. Watch the global batch size (per-GPU batch times GPUs times accumulation steps), the communication cost and the long tail of step times, not just peak throughput.

### Why can data-parallel gradients differ from single-GPU large-batch training?

DDP averages the gradients of the GPUs. If each GPU averages its loss over its own valid tokens and the GPUs hold different numbers of valid tokens (uneven sequence lengths, different padding), the average of averages is not the global per-token average and the GPUs with few tokens get too much weight. In the experiment below, with valid lengths from 16 down to 4, the gradient is off by 36.5% relative to the single-process full batch; dividing by the global number of valid tokens brings the error down to 1.6e-07. Gradient accumulation has exactly the same issue.

### How does ring all-reduce traffic depend on the number of GPUs?

Each GPU sends 2(n−1)/n times the gradient size: 1× for n=2, 1.875× for n=16, approaching 2× however many GPUs there are, so the bandwidth term barely grows with n. The number of sequential steps, 2(n−1), does grow linearly, which is the latency term. A ring all-reduce is a reduce-scatter followed by an all-gather; ZeRO-1 and ZeRO-2 just split those two steps apart, so their traffic equals plain data parallelism, while ZeRO-3 gathers the parameters once more in the forward pass and once in the backward pass and costs 1.5×.
