Contents

Foundation Model Engineering

Manuscript updated (UTC) · Chapter source on GitHub · Cite this chapter (RIS)

On this page

7.2 ZeRO (Zero Redundancy Optimizer)

With eight GPUs, how many copies of an Adam optimizer do you need? In ordinary Distributed Data Parallel (DDP), each worker processes different examples, receives the same reduced gradients, and applies the same update to a complete copy of the weights. Adding workers can increase throughput while leaving the model-state memory required on each worker unchanged. ZeRO assigns ownership of those states to individual ranks (worker processes). [1]

1. The Anatomy of GPU Memory

For this example, each parameter needs two bytes for the training weight, two for its gradient, four for a master copy used by the optimizer, and eight for Adam’s two FP32 moments. The second moment tracks squared gradients. These are accounting choices: a different gradient dtype or an optimizer without a master copy changes the total. [1]

A model with Φ\Phi parameters therefore has 16Φ16\Phi bytes of model states, including 12Φ12\Phi bytes for the optimizer and its master weights. At 70 billion parameters, that is 1,120 GB on each ordinary DDP worker before activations. All memory figures here use decimal GB. Sequence length, saved activations, recomputation, communication buffers and allocator headroom enter a separate peak-memory estimate.

2. What does one worker own?

Follow weights 5 and 6 through four ranks

Number eight weights from 1 to 8. Split them into four equal shards. Rank 0 owns indices 1–2, rank 1 owns 3–4, rank 2 owns 5–6, and rank 3 owns 7–8 when a state is sharded. The cells below list the weight indices covered by each kind of persistent state on rank 2. P denotes training weights, G gradients, and O optimizer state including master weights. Watch the columns change one at a time. [1]

StagePGOBytes
DDP1–81–81–8128
ZeRO-11–81–85–656
ZeRO-21–85–65–644
ZeRO-35–65–65–632

For example, the ZeRO-2 row has eight two-byte weights, two two-byte gradients and two twelve-byte optimizer entries: 16+4+24=4416+4+24=44 bytes. During a collective, a rank can briefly hold buffers larger than the shard it owns.

Run the exchange on a CPU. The four-rank PyTorch script uses eight FP32 weights initialized to 1 through 8. Rank rr differentiates the quadratic loss (r+1)∑jwj2/2(r+1)\sum_j w_j^2/2. There is one equally weighted contribution per rank. Reduce-scatter sums the four gradient vectors and gives each worker its two entries. After division by four, rank 2 gets gradients 12.5 and 15. An SGD step with learning rate 0.1 changes its weights from 5 and 6 to 3.75 and 4.5. All-gather reconstructs the full update, which every worker checks against an unsharded step.

torchrun --standalone --nproc-per-node=4 zero_shards.py

This run uses Linux, CPU PyTorch 2.15.0 and the Gloo backend. It demonstrates the two collectives with actual gradients. The memory table uses mixed precision and Adam, so its byte counts are calculated rather than measured from this script. [4]

Stage 1: Optimizer State Partitioning (PosP_{os})

With NN data-parallel ranks, each owns 1/N1/N of the optimizer state and updates the corresponding weights. Each still stores complete weight and gradient tensors. Persistent model-state memory per rank is 4Φ+12Φ/N4\Phi+12\Phi/N bytes.

Stage 2: Gradient Partitioning (Pos+gP_{os+g})

As gradients become available, the workers can reduce a bucket and send the summed entries to their owners. Each owner retains only its gradient shard and uses it for the optimizer step. The model-state estimate falls to 2Φ+14Φ/N2\Phi+14\Phi/N. Stages 1 and 2 can match DDP’s idealized communication volume. Bucket sizes and the overlap of communication with computation still affect elapsed time. [1]

Stage 3: Parameter Partitioning (Pos+g+pP_{os+g+p})

The weights also have owners. To compute a layer, each rank gathers the weights it needs. Retaining them for backward or releasing them and gathering them again trades memory for communication. The persistent state is 16Φ/N16\Phi/N bytes per rank. The paper’s simplified schedule estimates about 1.5 times DDP’s communication volume. Actual traffic depends on group size, prefetch and retention policy. [1]

3. What fits in an 80 GB budget?

The initial setting is 70 billion parameters on eight ranks. Even at stage 3, each GPU needs 140 GB for model states. Move to 16 ranks and the estimate drops to 70 GB. Under an 80 GB budget, that leaves 10 GB for everything else. A peak-memory measurement during a real step tells you whether that is enough.

Model-state memory per GPU

Each GPU runs one data-parallel rank. For each parameter, this example counts 2 bytes for an FP16 or BF16 weight, 2 for its gradient and 12 for the FP32 master weight and two Adam moments.

DDP
1120.0 GB
ZeRO-1
385.0 GB
ZeRO-2
262.5 GB
ZeRO-3
140.0 GB
80 GB budget

4. Beyond GPU Limits: ZeRO-Offload & ZeRO-Infinity

When adding GPUs is impractical, moving state to another memory tier gives you another option. ZeRO-Offload moves optimizer state and computation to the CPU. Overlapping the CPU update and PCIe transfers with GPU work can reduce stalls. Delaying an update by a step also changes the training algorithm. [2]

ZeRO-Infinity also uses host memory and NVMe storage, fetching tensors when the computation needs them. A run can have ample storage capacity and still stall if transfers cannot finish before the next layer needs its weights. [3]


5. Engineering Implementation: Initialization Is Part of the Memory Plan

Limitation: this compact DeepSpeed sketch illustrates initialization and causal loss semantics. It omits a real Transformer, padding masks, mixed-precision policy, validation, and production checkpoint orchestration; it is not production-grade.

ZeRO-3 cannot rescue memory already exhausted while constructing the full model. Instantiate large parameters inside deepspeed.zero.Init (or use an equivalent FSDP/meta-device initialization path) so weights are partitioned as they are created.

import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.distributed as dist
import deepspeed
from torch.utils.data import Dataset

class SimpleLLM(nn.Module):
    def __init__(self, vocab_size=32_000, d_model=4_096):
        super().__init__()
        self.embed = nn.Embedding(vocab_size, d_model)
        self.layers = nn.Sequential(*[
            nn.Linear(d_model, d_model, bias=False) for _ in range(24)
        ])
        self.lm_head = nn.Linear(d_model, vocab_size, bias=False)

    def forward(self, token_ids):
        return self.lm_head(self.layers(self.embed(token_ids)))

class TokenDataset(Dataset):
    def __len__(self): return 1_000
    def __getitem__(self, index):
        generator = torch.Generator().manual_seed(index)
        return torch.randint(0, 32_000, (513,), generator=generator)

def train():
    deepspeed.init_distributed()
    with deepspeed.zero.Init(config_dict_or_path="ds_config.json"):
        model = SimpleLLM(vocab_size=32_000, d_model=4_096)

    engine, _, loader, _ = deepspeed.initialize(
        model=model,
        model_parameters=model.parameters(),
        training_data=TokenDataset(),
        config="ds_config.json",
    )

    for tokens in loader:
        tokens = tokens.to(engine.device)
        inputs, targets = tokens[:, :-1], tokens[:, 1:]  # causal shift
        logits = engine(inputs)
        loss = F.cross_entropy(logits.float().flatten(0, 1), targets.flatten())
        engine.backward(loss)
        engine.step()
        if dist.get_rank() == 0:
            print(float(loss))
        break  # All ranks stop together after this demonstration step.

The resolved global batch must equal microbatch × accumulation × data-parallel degree. Budget peak all-gathered parameter groups, activations, temporary buffers, fragmentation, and communication overlap in addition to persistent sharded states. Before scale-up, compare one-node and multi-node memory peaks and step time.

A resumable checkpoint includes sharded model and optimizer, scheduler, scaler/FP8 state, global tokens, RNG and sampler/data cursor, plus model/data/tokenizer/code/config hashes. Test restore with the deployed DeepSpeed version and launcher; a weights-only save is not an exact continuation.

The sketch predicts 512 next-token targets from each 513-token random sample and stops after one microbatch. If the accumulation factor exceeds one, that call to engine.step() may precede the first weight update. To compare two stages on real data, hold example IDs, sequence length, learning rate, precision and accumulation fixed. Record validation loss per target, gradient norm, throughput, peak memory and time waiting on collectives. Stop before scaling if loss becomes nonfinite or a checkpoint resumed at the same data position cannot reproduce the next update.

The Engineering Trade-off

Compare stage 2 and stage 3 at the same sequence length and batch size. Record peak device memory and step time. If stage 3 frees memory but spends longer waiting for parameter gathers, you have measured the cost of that memory saving.

Summary

Choose a stage by accounting for what each rank owns between operations and what it must gather during a step. Section 7.3 combines this partitioning with tensor and pipeline parallelism.

Quizzes

Quiz 1: Does equal idealized communication volume imply equal runtime? No. Reduce-Scatter plus All-Gather can have the same idealized byte volume as DDP All-Reduce, but startup, bucket size, ordering, memory copies and overlap can differ.

Quiz 2: If ZeRO-3 partitions the parameters, how does a GPU compute the forward pass for a specific transformer layer if it only holds a fraction of that layer’s weights? It gathers the required weight shards before computing the layer. Releasing them after forward saves memory. Retaining them until backward can avoid a second gather.

Quiz 3: You are training a 10B parameter model using ZeRO-Offload. You notice that GPU utilization (MFU) has dropped significantly, and the GPU is frequently idle. What is the most likely system bottleneck? The PCIe bandwidth or the CPU compute speed. ZeRO-Offload moves the optimizer step to the CPU. If the CPU is too slow at computing the Adam updates, or if the PCIe bus is too slow to transfer the updated weights back to the GPU in time for the next forward pass, the GPU will stall and wait for the CPU, drastically lowering utilization.

Quiz 4: What optimizer-related state is counted in this section’s 16-byte example? Four bytes of FP32 master weights plus eight bytes for two FP32 moments give 12 bytes per parameter. This is an implementation-specific accounting example; Adam does not inherently require a separate FP32 master copy in every setup.


References

  1. Rajbhandari, S., et al. (2020). ZeRO: Memory Optimizations Toward Training Trillion Parameter Models. SC20. arXiv:1910.02054.
  2. Ren, J., et al. (2021). ZeRO-Offload: Democratizing Billion-Scale Model Training. USENIX ATC. arXiv:2101.06840.
  3. Rajbhandari, S., et al. (2021). ZeRO-Infinity: Breaking the GPU Memory Wall for Extreme Scale Deep Learning. SC21. arXiv:2104.07857.
  4. PyTorch. Distributed communication package, reduce_scatter_tensor and all_gather_into_tensor.