AI State of the Art
SOTA/Training: Modern Training Techniques/36 min
Section 91

ZeRO: Stage 1, 2, 3 (DeepSpeed)

Listen as a podcast →

The problem: every card stores the same thing N times

Imagine training a model on 64 graphics processors, Graphics Processing Units, almost always shortened to GPU. In classic data parallelism, DDP, for Distributed Data Parallel, PyTorch's standard method, covered in Data Parallelism every GPU holds a complete copy of the model: the parameters, the gradients, and the optimizer states. GPU 0 stores everything. GPU 1 stores exactly the same thing. So does GPU 2. Sixty-four identical copies.

That is pure waste. The useful information exists once, but it occupies 64 times its size. It is as if 64 students each photocopied an entire encyclopedia when each of them needs one chapter.

ZeRO (Zero Redundancy Optimizer) asks the obvious question: why not split the load? GPU 0 keeps one sixty-fourth of the states, GPU 1 another sixty-fourth, and so on. When a GPU needs a complete piece of information, it temporarily gathers it from the others, uses it, then throws it away.

ZeRO: Memory Optimizations Toward Training Trillion Parameter Models (Rajbhandari et al., 2019)

The memory arithmetic of training

This section is the course's reference for everything to do with training memory. Other pages point here rather than redo the calculation. It only takes one multiplication.

The four line items, and why only one of them moves

Training a model fills the graphics card's memory (its VRAM, Video Random Access Memory) with four line items, and no more:

  1. The weights. The model's learned values. These are what you read to make a prediction.
  2. The gradients. One number per weight, computed on the backward pass, saying which way to nudge that weight.
  3. The optimizer states. The bookkeeping the optimizer maintains on each weight from one step to the next. See Modern optimizers.
  4. The activations. The intermediate results computed on the forward pass and kept because the backward pass will need them.

The decisive distinction is what each item is counted per: the first three are counted per parameter, the fourth per position in the text.

A model has the same number of weights whether you show it one word or a million. So weights, gradients and optimizer states have a fixed size: it depends on the model and nothing else. Activations, by contrast, are the trace each token leaves as it passes through each layer. Double the batch size and you double the number of traces. Double the sequence length and you double it again. That, and only that, is why activation memory is the one you can act on by changing a training setting, and why the other three demand that you change method.

Bytes per parameter

You only need to know how many bytes each item spends per parameter, in today's standard configuration: 16-bit arithmetic (see Mixed precision) and the AdamW optimizer.

Line itemBytes per parameterWhere the number comes from
Weights, in BF16216 bits ÷ 8 bits per byte = 2 bytes
Gradients, in BF162one gradient per weight, same format
AdamW states8AdamW keeps two running averages per parameter, each in 32 bits: 2×4=82 \times 4 = 8
Fixed subtotal12
Activationsvariabledepends on batch size and sequence length

The 8 bytes on the third row is the number that surprises everyone, and it is the one to remember. AdamW does not settle for the current gradient: for every single parameter it stores an average of past gradients and an average of their squares. Two numbers, kept at full precision so they do not drift across tens of thousands of steps, hence 4 bytes each. What these two memories actually do is explained in Modern optimizers; the same count is the basis of Fine-tuning.

The 28 GB trap

A common mistake is to count 4 bytes per parameter for the optimizer, as if it kept only one average. For a 7-billion-parameter model that yields 28 GB where 56 are needed. AdamW keeps two: the momentum and the average of the squares. This is the heaviest item in training, four times bigger than the weights themselves.

The canonical example: 7 billion parameters

Write Φ\Phi for the number of parameters in the model. The whole calculation is "bytes per parameter × Φ\Phi".

Line itemCalculationMemory
BF16 weights2×7×1092 \times 7 \times 10^914 GB
BF16 gradients2×7×1092 \times 7 \times 10^914 GB
AdamW states8×7×1098 \times 7 \times 10^956 GB
Total before the first activation12×7×10912 \times 7 \times 10^984 GB

84 GB before a single activation has been stored. A common datacentre card tops out at 80 GB. A model routinely called "small" therefore already does not fit on one card, and it has not yet seen a single token. This explains two things at once: why training needs so many machines, and why ZeRO partitions precisely these three items, in this order.

A 70-billion model? Multiply by ten: 840 GB, eleven cards just to park the states.

Activations, the fourth item

For that same 7-billion model, with a 4096-token sequence and a batch of 1, activations weigh on the order of 10 to 30 GB depending on how attention is implemented, the calculation is spelled out in Gradient checkpointing, which also explains how you trade that memory for extra compute. It is the same order of magnitude used in Fine-tuning.

Keep the order of magnitude and above all the dependency: at batch 8, this item is multiplied by 8. It is the only one of the four whose size you control with a setting, and the only one ZeRO does not partition, for activations you need other tools (sequence parallelism, activation recomputation).

The master copy: why some counts say 16 bytes, not 12

The table above counts 12 bytes per parameter. The ZeRO paper counts 16. Both are right, and here is the difference, because it accounts for nearly every contradiction you will read on the subject.

Under mixed precision you actually keep two versions of the weights: a 16-bit working copy for the forward and backward passes, and a 32-bit master copy on which the optimizer applies its updates. Without that master copy, the tiny corrections the optimizer adds to the weights round down to zero and training stalls, the mechanism is detailed in Mixed precision.

The master copy costs 4 more bytes per parameter:

2⏟16-bit weights+4⏟32-bit master copy+2⏟gradients+8⏟AdamW=16 bytes per parameter\underbrace{2}_{\text{16-bit weights}} + \underbrace{4}_{\text{32-bit master copy}} + \underbrace{2}_{\text{gradients}} + \underbrace{8}_{\text{AdamW}} = 16 \text{ bytes per parameter}

That is 16×7×109=11216 \times 7 \times 10^9 = 112 GB for our 7-billion model. This is the famous "16Φ16\Phi" of the ZeRO paper, and it is the figure we will use in the stage formulas below so that they line up with the paper.

Which to use? Twelve bytes per parameter is the short version, enough to size a job in your head. Sixteen is the full version, master copy included. The two numbers do not contradict each other: they count the same setup with or without one row. What you must never do is count the master copy and forget one of AdamW's two moments.

The redundancy, in numbers

Back to the point. With 64 GPUs in DDP the total cost is 64×16Φ=1024Φ64 \times 16\Phi = 1024\Phi bytes, while the unique information weighs only 16Φ16\Phi. The wasted fraction is 63/6463/64, that is 98.4% of memory spent on useless copies.

A concrete example: a 7-billion model

16Φ=16×7×109=11216\Phi = 16 \times 7 \times 10^9 = 112 GB per GPU in DDP. Across 64 GPUs, 7.2 TB in total for 112 GB of unique information. ZeRO stage 3 brings that down to 112/64=1.75112 / 64 = 1.75 GB per GPU, activations excluded, since ZeRO does not partition them and they add on top.

The three collective operations, explained

ZeRO's stages differ by the exchanges they require. Those exchanges have names worth understanding once and for all. They come from NCCL, the NVIDIA Collective Communications Library, the software layer that carries them out on NVIDIA cards.

Picture each GPU holding a four-line ledger.

  • All-reduce. Every GPU ends up with the sum of all four lines from all the ledgers, in all four lines. Everyone leaves with the complete, identical result.
  • Reduce-scatter. The same addition, but each GPU receives only one line of the result: GPU 0 keeps the sum of the line-1 entries, GPU 1 the sum of the line-2 entries, and so on. Same addition work, four times less data brought home.
  • All-gather. The reverse: each GPU starts with one line and leaves with all four, with no addition at all. This is how a complete tensor is rebuilt from its shards.

The relationship that governs everything: an all-reduce is exactly a reduce-scatter followed by an all-gather. That is why some ZeRO stages cost nothing in communication, they merely cut in two an operation DDP was already performing.

The three stages: from cautious to radical

In the formulas below, Φ\Phi is the number of parameters and PP the number of GPUs. Every term divided by PP is a partitioned item; every undivided term is an item still replicated identically on each card.

Stage 1: partition the optimizer states

Stage 1 goes after the biggest chunk: AdamW's two moments plus the 32-bit master copy, that is the 12Φ12\Phi bytes. Each GPU keeps only its 1/P1/P share.

Memory per GPU=2Φ+2Φ+12ΦP\text{Memory per GPU} = 2\Phi + 2\Phi + \frac{12\Phi}{P}

In one sentence: the working weights and the gradients stay whole on every card, only the optimizer's bookkeeping is split.

With P=64P = 64: 2+2+12/64=4.19Φ2 + 2 + 12/64 = 4.19\Phi bytes, against 16Φ16\Phi in DDP. Roughly a 3.8x reduction. Communication: strictly the same as DDP, no overhead at all.

Why no overhead? Because each GPU only needs to update the slice of weights whose states it holds. So it does a reduce-scatter of the gradients instead of an all-reduce, updates its slice, then an all-gather of the updated weights. Reduce-scatter plus all-gather equals all-reduce: identical volume.

Stage 1: the free win

This is the recommended starting point. Almost 4x the memory for not one extra byte of communication. If your model does not fit under DDP, turn on stage 1 before anything else.

Stage 2: partition the gradients too

Stage 2 adds the gradients to the list. During the backward pass they are reduce-scattered as they are produced, and each GPU keeps only its partition. A gradient it is not responsible for is dropped as soon as it has been sent.

Memory per GPU=2Φ+2ΦP+12ΦP\text{Memory per GPU} = 2\Phi + \frac{2\Phi}{P} + \frac{12\Phi}{P}

With P=64P = 64: 2+2/64+12/64=2.22Φ2 + 2/64 + 12/64 = 2.22\Phi bytes, roughly 7x less than DDP. Communication: still the same as DDP.

This is the best compromise for most situations: seven times less memory without a penny of extra communication. When in doubt, take stage 2.

Stage 3: partition the parameters themselves

Stage 3 takes the logic all the way: even the weights are partitioned. Each GPU stores only a 1/P1/P fraction of the model. Before each layer, that layer's complete parameters are gathered with an all-gather, used, then freed.

Memory per GPU=16ΦP\text{Memory per GPU} = \frac{16\Phi}{P}

With P=64P = 64: 0.25Φ0.25\Phi bytes per GPU, a 64x reduction, everything divided by the number of cards, with no exception.

This time the price is real. The weights have to be gathered on the forward pass and on the backward pass, whereas DDP never gathered them at all. The paper puts the overhead at 1.5 times DDP's communication volume.

The price of stage 3

Stage 3 is unbeatable on memory, but the saving is paid for in network traffic. It earns its place when the model will not fit even under stage 2, and it demands a fast interconnect: on a slow network the weight all-gathers become the limiting factor and the cards sit waiting.

Comparing the stages

StageWhat is splitWhat travels, and whenMemory per GPUVolume exchanged
DDPnothing (only the batch)all-reduce of the gradients, once at the end of the backward pass16Φ16\Phi1x (baseline)
ZeRO-1optimizer statesreduce-scatter of the gradients at the end of the backward pass, all-gather of the weights after the update≈4Φ\approx 4\Phi (at P=64P=64)1x
ZeRO-2+ gradientssame two operations, but the reduce-scatter happens layer by layer during the backward pass≈2Φ\approx 2\Phi (at P=64P=64)1x
ZeRO-3+ weightsadditionally: an all-gather of the weights before every layer, on the forward and on the backward pass16Φ/P16\Phi / P1.5x

Two ways to read this table. First, what gets split moves one notch down each row: the batch, then the bookkeeping, then the gradients, then the weights. Second, the moment of communication shifts: DDP exchanges once per training step, stage 3 exchanges once per layer per pass. It is that shift, more than the volume, that makes stage 3 sensitive to network quality.

The memory column depends on PP; the values shown are for 64 GPUs, as in the calculations above.

What the paper measures

The authors report training models of over 100 billion parameters on 400 GPUs with super-linear speedup (more GPUs means less memory per card, hence larger local batches, hence better efficiency) at a throughput of 15 petaFLOP per second. They also report training a 13-billion-parameter model without any model parallelism, which was the practical barrier ZeRO set out to remove.

ZeRO-Offload and ZeRO-Infinity: spilling to the processor and the disk

ZeRO-Offload

What if you went further still? ZeRO-Offload moves the optimizer states and the parameter update to the memory of the central processor (the CPU, Central Processing Unit), while the GPU concentrates on the forward and backward passes. The GPU memory freed up goes to activations.

ZeRO-Offload: Democratizing Billion-Scale Model Training (Ren et al., 2021)

The trick: the AdamW update is a simple operation the CPU can carry out while the GPU is already computing the next forward pass. That is how the transfer latency gets hidden.

What the paper measures

The authors report training a model of over 13 billion parameters on a single card, against 1.4 billion at most with PyTorch alone, and 40 TFLOP per second on one V100 for that 10-billion model, against 30 for the 1.4-billion model without offload.

Two stacked diagrams. On top, ZeRO-Offload data placement: for each GPU in a node, a blue parameter bar and a small orange gradient bar stay in GPU memory, while CPU memory holds an orange gradient bar and a large green optimizer-states bar, one partition per data-parallel process. Below, the timeline of one training step: the computation stream shows forward and backward on GPU, then parameter update on CPU, then forward and backward on GPU again for the next step; underneath, the swapping stream shows a GPU-to-CPU gradient transfer during the backward pass and a CPU-to-GPU parameter transfer during the update.
On top, who keeps what: the big green bars (optimizer states) have migrated from GPU to CPU memory, leaving only the current parameters and gradients on the GPU. Below, why this does not wreck performance: the transfers (the yellow and orange bands at the bottom) are tucked underneath computation that is already running, and the AdamW update happens on the CPU while the GPU waits for almost nothing.Source : ZeRO-Offload paper (Ren et al.), via the Microsoft Research DeepSpeed blog

ZeRO-Infinity

The boldest extension: using the CPU and the NVMe disk (Non-Volatile Memory express, the standard for fast solid-state drives) as overflow memory. Idle parameters and states sleep on disk, come back up to the CPU on demand, then to the GPU just before use.

ZeRO-Infinity: Breaking the GPU Memory Wall for Extreme Scale Deep Learning (Rajbhandari et al., 2021)
ZeRO-Infinity diagram. On the left, a Model States box details layer 0: parameters P0, gradients G0 and optimizer states A0. On the right, four GPUs numbered 0 to 3; above them a Network band carrying the AllGather operation on P0 and the ReduceScatter operation on G0, connected to the GPUs by arrows annotated one times the data volume. Below the GPUs, two large purple boxes labelled Slow Memory (CPU + NVMe) hold the parameter, gradient and optimizer-state shards for each GPU, connected to the GPUs by arrows annotated one over DP times the data volume.
Memory becomes a three-storey pyramid. The big purple boxes at the bottom are CPU and disk: that is where the parameters, gradients and optimizer states you do not need right now are sleeping. The GPUs in the middle only ever receive one shard at a time (bottom arrows), and pass it around through the network at the top. The trick the arrow annotations reveal: each GPU pulls only a one-over-DP fraction from its own disk, so reads happen in parallel across the whole machine.Source : ZeRO-Infinity paper (Rajbhandari et al.), via Ilyee Blog
What the paper measures

The authors claim they can fit models of tens and even hundreds of trillions of parameters for training, and sustain over 25 petaFLOP per second on 512 V100 GPUs, that is 40% of peak throughput. The trade-off is not in the title: the further down the memory pyramid you go, the more the transfers weigh, and on a single GPU training becomes very slow.

Horizontal bar chart titled Max model size (B), giving the largest trainable model size for seven techniques: Data parallel 1.4 billion, ZeRO 2 10 billion, ZeRO Offload 13 billion, ZeRO 3 20 billion, 3D Parallelism 20 billion, ZeRO-Inf-CPU 70 billion, ZeRO-Inf-NVMe 1000 billion.
The ranking, as measured by the authors on a single machine. The first five bars look so alike you can barely tell them apart: partitioning memory across GPUs buys you roughly a factor of ten and no more, because you are still capped by total GPU memory. The last bar is different in kind: once you accept writing to disk, the ceiling moves from 20 to 1000 billion parameters, a factor of 50. The trade-off, invisible on this chart, is speed.Source : ZeRO-Infinity paper (Rajbhandari et al., 2021, figure 1), via ar5iv

ZeRO and FSDP: two implementations, one idea

ZeRO (Microsoft, in the DeepSpeed library) and FSDP (Fully Sharded Data Parallel, from Meta, built into PyTorch) realise the same concept: partition model states across GPUs to remove redundancy. FSDP is covered in detail in FSDP. The differences are matters of implementation and ecosystem:

AspectZeRO-3 (DeepSpeed)FSDP (PyTorch)
Natureexternal librarybuilt into PyTorch
ConfigurationJSON filePython interface
Spilling to CPU and diskmore complete (ZeRO-Infinity)more limited
Composing with the rest of PyTorchthrough the librarynative

For a new project, FSDP is generally the default: native to PyTorch, easier to compose with the rest of the ecosystem. DeepSpeed keeps the edge when you need spilling to disk, or in toolchains that already integrate it.

The historical perspective

ZeRO marked a break when it was published in 2020: it showed that large models could be trained without model parallelism, that is, without splitting weight matrices or layers, which previously demanded rare expertise and a rewrite of the model. Today ZeRO-3 and FSDP are functionally close, and the choice comes down mostly to the ecosystem you already have.

Summary

ZeRO solves a simple problem: the memory redundancy of classic data parallelism. By partitioning the optimizer states (stage 1), then the gradients (stage 2), then the weights (stage 3), it makes trainable models that are too big for one card's memory. Stage 2 is the right default: about seven times less memory, with no extra communication. Stage 3 divides everything by the number of cards, at the price of one and a half times the network traffic.

And the lesson that outlives ZeRO: on a 7-billion-parameter model, 84 GB are gone before the first activation, 56 of them for AdamW's bookkeeping alone. All of distributed training follows from that count.

Check your understanding0 / 5

1. For a 7-billion-parameter model, how much do the AdamW optimizer states weigh, and why?

2. Of the four memory items in training, which one depends on batch size and sequence length?

3. Why do ZeRO stages 1 and 2 cost not one byte of communication more than DDP?

4. Which ZeRO stage does the page recommend as the default, and why?

5. This page counts 12 bytes per parameter, while the ZeRO paper counts 16. Who is right?