AI State of the Art
SOTA/Training: Modern Training Techniques/31 min
Section 87

Data Parallelism (DP) and Distributed Data Parallel (DDP)

Listen as a podcast →

What this method splits, and what it must communicate

You understand a parallelism strategy by answering two questions, and only two: what does it split across machines, and what must it then send around, and when. Here are both answers for data parallelism (DP) before any explanation.

What it splits: the batch. The batch is the bundle of training examples processed together before the weights are corrected once. On 8 graphics cards, each one gets an eighth of the examples. And that is all that is split. The model itself is not split at all: every card keeps a complete copy, weights, gradients, and the optimizer's bookkeeping.

What it must communicate: the sum of the gradients, once, at the end of the backward pass. Each card saw different examples, so it computed different gradients. For the eight copies of the model to remain identical after the update, all eight cards must apply exactly the same correction. So the eight sets of gradients are added up and the total is handed back to everyone. That operation is an all-reduce, and it happens once per training step.

These two answers govern everything else, including where the method runs out.

Data parallelism saves you not one byte of memory

This is the consequence everyone forgets. Since every card keeps the model in full, adding cards in DP lightens nobody's memory. A card that could not hold the model on its own will not hold it any better with fifty neighbours. What DP buys is time: the same examples are processed eight times faster. Nothing else.

That is why DP is always combined with something else as soon as the model grows, ZeRO or FSDP for memory, tensor parallelism or pipeline parallelism to split the model itself.

The idea, in one picture

Copy the whole model onto each graphics card (the GPU, or Graphics Processing Unit), give each one a different slice of the batch, and add up the gradients at the end. Each card sees different examples, but they all apply the same correction and therefore stay at the same point.

It is like eight students each reading a different chapter of the same book and then pooling their notes. In the end everyone understands the same thing, but the reading took an eighth of the time.

Diagram titled Data Parallelism. On the left, the caption Split batch to train models on more data in parallel. On the right, two stacked rectangles each containing the same small neural network: the first receives an image of the digit 5 and is labelled Model copy on GPU 1, the second receives an image of the digit 3 and is labelled Model copy on GPU 2.
The whole principle in one picture: the same model is copied identically onto every GPU, and it is the batch that gets split. GPU 1 works on the digit 5, GPU 2 on the digit 3, and the two copies will stay in sync through the gradient exchange.Source : Sebastian Raschka, Optimizing Memory Usage for Training LLMs in PyTorch

The old implementation, no longer worth using

PyTorch's first interface, nn.DataParallel, ran everything inside a single Python program with one "master" card:

  1. The master scatters the data to cards 1, 2, 3...
  2. Each card runs its own forward and backward pass locally.
  3. The master gathers the outputs and reduces the gradients.

Two structural flaws. First, a single Python program cannot genuinely drive eight cards at once, because of the GIL (Global Interpreter Lock), the mechanism that prevents two Python threads from making progress simultaneously. Second, all the traffic funnels through the master card, which becomes a bottleneck and uses more memory than the rest.

Forget nn.DataParallel

This interface has been abandoned. The memory imbalance and the master-card bottleneck make it clearly slower than the DDP described below, even for a quick two-card experiment. There is no situation today where you would prefer it.

DDP: one independent program per card

DDP (Distributed Data Parallel) is the standard implementation. It launches one independent Python program per card. No global lock, no master: each program is self-contained and talks directly to its neighbours.

  • Program 0 on card 0
  • Program 1 on card 1
  • ...
  • Program 7 on card 7

Each program runs its forward and backward pass on its own data, then the all-reduce adds up everyone's gradients. After that synchronization, every card holds exactly the same gradients and applies exactly the same update. The copies never drift apart.

Four-column diagram. A cylinder labelled Global Data splits into three batches, Data Batch 0, 1 and 2, in the Data Load column. Each batch goes to a distinct GPU in the Forward column, then in the Backward column. The three branches converge into a vertical green block labelled Gradients AllReduce, from which three arrows fan back out to the three GPUs in the Optimization column.
One full DDP iteration. Each GPU loads its own batch and runs its forward and backward entirely on its own. The single meeting point is the green block in the middle: the gradient all-reduce. After it, every GPU applies exactly the same weight update.Source : Chishiki-AI, Multi-node Distributed Training with PyTorch

The all-reduce, and how a ring performs it

All-reduce means "reduce for everyone": one quantity held by all the cards is summed, and each card walks away with the complete total. This operation and its two cousins (reduce-scatter and all-gather) are spelled out in FSDP. They are provided by NCCL (NVIDIA Collective Communications Library), the software layer that carries them out on NVIDIA hardware.

The naive way to do an all-reduce would be for every card to send its gradients to every other card; traffic would explode with the card count. The algorithm used in practice is the ring all-reduce, in which each card only ever talks to its neighbour:

  1. The gradients are cut into as many chunks as there are cards.
  2. Reduce-scatter: the chunks travel around the ring; at each hop, each card adds the chunk it received to its own. After a full lap, each card holds the total for one chunk.
  3. All-gather: the totalled chunks make a second lap, without addition this time, so that everyone ends up with everything.
Diagram of ring reduce-scatter. Five GPUs numbered 0 to 4 are stacked vertically, each with an array of five cells named a, b, c, d, e carrying the GPU index. Grey arrows step diagonally from one GPU to the next, and a black arrow loops from the bottom back to the top to close the ring. On each row one cell already holds a partial sum, for example a1 plus a0 on GPU 1 or b2 plus b1 on GPU 2.
One step of the reduce-scatter. Gradients are cut into as many chunks as there are GPUs, and each GPU sends just one chunk to its right-hand neighbour, which adds it to its own. Nobody talks to everybody: each GPU only ever talks to its neighbour, which is why the volume exchanged is almost independent of the number of GPUs.Source : Andrew Gibiansky, Bringing HPC Techniques to Deep Learning

The volume each card sends is then:

V=2⋅P−1P⋅MV = 2 \cdot \frac{P - 1}{P} \cdot M

where PP is the number of cards and MM the total size of the gradients in bytes, that is, 2 bytes per model parameter in BF16 (see ZeRO for that accounting). The factor of 2 comes from the two laps described above: one for the reduce-scatter, one for the all-gather. The (P−1)/P(P-1)/P factor comes from the fact that a card need not send itself its own chunk: out of PP chunks, it circulates P−1P-1.

In one sentence: each card sends a little less than twice the size of the gradients, no matter how many cards there are.

Why the ring scales

The (P−1)/P(P-1)/P term is 0.875 at 8 cards and 0.99 at 100 cards: it tends to 1 and will never exceed it. The volume sent per card is therefore capped at 2M2M, whether the cluster has eight cards or a thousand. That is precisely the property that makes data parallelism usable at scale, and precisely what the star topology of nn.DataParallel lacked.

Why this exchange is nearly free

Here is the decisive argument of the page, the one that explains why data parallelism can cross the slow network between machines while tensor parallelism cannot.

It is not a question of volume. It is a question of where the exchange sits inside the computation. The DP all-reduce happens at the end of the backward pass, on gradients that nothing else in the current step depends on. So you can start it early and let it run underneath the computation: as soon as the last layer's gradients are ready, their all-reduce begins in the background while the backward pass keeps working its way toward the first layers. By the time the backward pass ends, most of the traffic has already gone through.

An exchange tucked underneath computation that was going to happen anyway costs almost nothing in wall-clock time. An exchange that halts the computation while it waits for an answer costs full price. That is the whole difference between DP and tensor parallelism, whose all-reduce lands in the middle of every layer and blocks what follows, the argument is developed in Megatron-LM.

PyTorch gets this overlap through hooks, small functions attached to each parameter and fired as soon as its gradient is ready. To avoid launching thousands of tiny transfers (each transfer carries a fixed start-up cost that would dominate) gradients are grouped into buckets of 25 megabytes by default: a bucket must fill up before its all-reduce is triggered.

DDP in practice

The settings that matter

SettingWhat it denotesCommon values
world_sizetotal number of programs, hence of cards8, 16, 64
rankunique identifier of a program across the whole cluster, from 0 to world_size - 10 to 63
local_rankidentifier of the card within its own machine0 to 7 on an 8-card machine
backendcommunication library usednccl on NVIDIA hardware
bucket_cap_mbsize of a gradient bucket before its all-reduce fires25 megabytes

The communication libraries

  • NCCL: built for NVIDIA cards, it exploits the fast NVLink connections inside a machine and InfiniBand between machines. The default choice.
  • Gloo: general-purpose, works on CPUs too. Slower, but handy while debugging.
  • MPI (Message Passing Interface), the long-standing standard of high-performance computing. Rarely used for deep learning.

Launching a run

torchrun --nproc_per_node=8 --nnodes=2 --node_rank=0 \
  --master_addr=host0 train.py

torchrun starts the programs and fills in the environment variables they need (RANK, LOCAL_RANK, WORLD_SIZE). It is the recommended route: hand-rolled launchers expose you to synchronization bugs that are painful to diagnose.

Adjusting the learning rate

With PP cards and a micro-batch of BB examples per card, the effective batch is P×BP \times B. A gradient averaged over more examples is smoother: it points more reliably in the right direction, but each step becomes timid relative to the number of examples it consumed. You compensate by raising the learning rate.

The usual rule is linear scaling:

lreffective=lrbase×Plr_{\text{effective}} = lr_{\text{base}} \times P

where lrlr is the learning rate (the length of the step the optimizer takes along the direction the gradient indicates) and PP the number of cards. Plainly: if you multiply by eight the number of examples seen before each correction, multiply the correction by eight too. With lr=0.001lr = 0.001 on one card, use lr=0.008lr = 0.008 on eight.

Where the rule comes from

It was established and measured on image classification, with a batch of 8,192 examples on 256 cards, paired with a gradual warmup of the learning rate over the first epochs, without that warmup, the very first large step destabilizes training. The full learning-rate schedule is covered in LR scheduling.

Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour (Goyal et al., 2017)

Measuring efficiency, and reading it correctly

scaling efficiency=throughput on P cardsP×throughput on 1 card\text{scaling efficiency} = \frac{\text{throughput on } P \text{ cards}}{P \times \text{throughput on 1 card}}

where throughput is counted in examples processed per second. The numerator is what you get; the denominator is what you would get if the cards never spoke to each other. A ratio of 1 would mean communication is entirely free; you never quite get there, because some traffic always remains unhidden.

The neighbouring metric you meet in papers is MFU, Model FLOPs Utilization: the fraction of the floating-point operations per second theoretically available on the card that actually goes into moving the model forward. Careful, two MFU figures are only comparable on identical hardware, since the denominator is the card's theoretical peak, and that changes with every generation.

What actually determines efficiency

Two factors, and only two. The link: inside a machine, cards are wired together by NVLink and communication all but disappears underneath the computation; between machines you go over the network, more than an order of magnitude slower, and the room for hiding shrinks. The compute-to-communication ratio: the larger the micro-batch, the more computation there is to stack on top of the same volume of gradients, so the better the hiding. Conversely, a large model with a small micro-batch is the unfavourable case.

If the network becomes the limiting factor, the first remedy is gradient accumulation: run several micro-batches before triggering the all-reduce, which raises the amount of computation per exchange.

Check your bandwidth units

This is the most common misreading on the subject, and it corrupts every argument built on it. Network links are advertised in gigabits per second, internal buses in gigabytes per second, and a byte is eight bits.

LinkAdvertised rateIn gigabytes per second
NVLink 4, between cards in one machine900 GB/s900
InfiniBand NDR, between machines400 Gbit/s50

The ratio is roughly 18x, not 2x as a careless comparison of 900 and 400 would suggest. These interconnects are detailed in Scaling infrastructure.

The limit: memory, which does not budge

Back to the consequence announced at the top of the page. DDP replicates the whole model on every card. For a 7-billion-parameter model in mixed precision with the AdamW optimizer, the accounting established in ZeRO gives:

ItemBytes per parameterMemory at 7 billion
Weights in BF16214 GB
Gradients in BF16214 GB
AdamW states (two running averages in 32 bits)856 GB
Total before the first activation1284 GB

84 GB, on every card, before a single activation has been stored. A common datacenter card tops out at 80 GB: the model does not fit. And that figure is the same on one card as on a thousand, since DP only splits the batch.

AdamW costs 56 GB, not 28

The classic mistake is to count 4 bytes per parameter for the optimizer, as if it kept a single quantity per weight. AdamW keeps two (a running average of past gradients and a running average of their squares) each in 32 bits, so 8 bytes per parameter and 56 GB for a 7-billion model. It is the heaviest item in training, four times larger than the weights. The details are in ZeRO and in Modern optimizers.

What you have to add to DP

This is exactly the observation that produced ZeRO and FSDP. They keep the batch split but add a parameter split: each card holds only a slice of the weights, gradients and optimizer states, and temporarily gathers what it needs. The 84 GB is then divided by the number of cards.

What you wantWhat has to be splitWhere it is covered
go faster, the model fitting on one cardthe batchthis page
fit a model too large for one cardthe batch and the parameterZeRO, FSDP
fit a layer too large for one cardthe weight tensortensor parallelism
spread a model across several machinesthe layerpipeline parallelism
train on a very long contextthe sequencesequence parallelism

These splits compose: that is the three-dimensional parallelism described in Megatron-LM.

Summary

Data parallelism splits the batch and nothing else. Every card keeps a full copy of the model and processes its share of the examples; a single all-reduce at the end of the backward pass sums the gradients so that all copies apply the same correction. Because that exchange has no dependency inside the current step, you start it early and it runs underneath the backward pass: nearly free in wall-clock time, which is what lets DP work even between machines.

The price is the exact counterpart of that simplicity: memory is not saved at all. The 84 GB of a 7-billion model is duplicated on every card. DP is therefore the base building block (the first thing to try, the last thing to remove) but never sufficient on its own beyond a model that fits on one card.

Check your understanding0 / 5

1. A model does not fit in the memory of a single card. Does going from 8 to 64 cards in data parallelism solve the problem?

2. Why does a 7-billion-parameter model already occupy 84 GB per card before a single activation has been stored?

3. Why is DP's all-reduce nearly free in wall-clock time, even though it moves close to twice the size of the gradients?

4. NVLink is advertised at 900 GB/s, InfiniBand at 400 Gbit/s. What is the real ratio between the two?

5. In ring all-reduce, how does the volume each card sends evolve when you go from 8 to 1,000 cards?