AI Logic

Distributed Training and Memory Saving

ZeRO

Updated:

How ZeRO partitions memory. Top: bars of the weights, gradients, and optimizer state per GPU at four stages, namely ordinary data parallelism, P_os which partitions the optimizer state, P_os+g which also partitions gradients, and P_os+g+p which also partitions weights, with the memory per GPU for 7.5 billion parameters on 64 GPUs (120GB, 31.4GB, 16.6GB, 1.9GB). Bottom: the communication in one training step of P_os+g (Reduce-Scatter of gradients, update of owned weights, All-Gather of weights)

Background and overview

ZeRO (Zero Redundancy Optimizer) is a method that greatly reduces memory per GPU by partitioning across GPUs the weights, gradients, and optimizer state that each GPU redundantly holds in data parallelism. Computation stays as in data parallelism, and it makes it possible to train large models that do not fit on one GPU without rewriting the model code.

In data parallelism, every GPU holds one full set of the same model's weights, gradients, and optimizer state. Training on 64 GPUs means 64 copies of the same thing. According to the paper, on 32GB GPUs, ordinary data parallelism could train only up to 1.4 billion parameters. Meanwhile, methods that split the model, such as tensor parallelism, can reduce memory but require communication for every layer, so they slow down sharply across servers. In the paper's measurements, training a 40-billion-parameter model with Megatron-LM across two servers (DGX-2) achieved about 5 TFLOPS per GPU (less than 5% of peak).

In their 2020 paper (SC20), Rajbhandari et al. proposed ZeRO, which removes this redundancy while keeping the compute and communication efficiency of data parallelism. By increasing what is partitioned in three stages, it can reduce memory per GPU by up to a factor of the number of GPUs.

An analogy: instead of every member of a 64-person team carrying their own copy of the same thick dictionary, they split the dictionary by pages and show each other the pages they need whenever necessary.

Theory

First, the breakdown of training memory. Following Section 3.1 of the paper, let Ψ\Psi be the number of parameters, and consider using Adam with mixed precision training.

What is heldFormatSize (bytes)
WeightsFP162Ψ2\Psi
GradientsFP162Ψ2\Psi
Optimizer state (FP32 copy of weights, momentum, variance)FP324Ψ+4Ψ+4Ψ=KΨ4\Psi + 4\Psi + 4\Psi = K\Psi (K=12K = 12)

The total is (2+2+K)Ψ=16Ψ(2 + 2 + K)\Psi = 16\Psi bytes. For the 1.5-billion-parameter GPT-2, the FP16 weights are 3GB, yet training needs at least 24GB. The largest part is the optimizer state. Together these are called the "model states."

The data-parallel part of ZeRO (ZeRO-DP) partitions the model states in three stages (figure above; let NdN_d be the data-parallel degree).

  1. PosP_{os}: partition the optimizer state. The optimizer state is split into NdN_d equal parts; GPU ii holds only the ii-th part and updates only the weights of that part. At the end of the step, All-Gather makes the updated weights consistent on all GPUs.
  2. Pos+gP_{os+g}: also partition gradients. GPU ii only needs the gradients of the part it updates. Each time gradients are computed in the backward pass, they are summed only on the owning GPU (Reduce-Scatter), and the other GPUs discard them.
  3. Pos+g+pP_{os+g+p}: also partition weights. Each GPU holds only the weights of its own part. Weights of other parts are received from the owning GPU just before computing that part in the forward and backward passes, and discarded after use.

Memory per GPU follows the formulas in Figure 1 of the paper.

(2+2+K)Ψ⏟data parallel  →  2Ψ+2Ψ+KΨNd⏟Pos  →  2Ψ+(2+K)ΨNd⏟Pos+g  →  (2+2+K)ΨNd⏟Pos+g+p\underbrace{(2 + 2 + K)\Psi}_{\text{data parallel}} \;\to\; \underbrace{2\Psi + 2\Psi + \frac{K\Psi}{N_d}}_{P_{os}} \;\to\; \underbrace{2\Psi + \frac{(2 + K)\Psi}{N_d}}_{P_{os+g}} \;\to\; \underbrace{\frac{(2 + 2 + K)\Psi}{N_d}}_{P_{os+g+p}}

When NdN_d is large, PosP_{os} becomes about 4Ψ4\Psi (one quarter), Pos+gP_{os+g} about 2Ψ2\Psi (one eighth), and Pos+g+pP_{os+g+p} one NdN_d-th. In the paper's example (Ψ=7.5\Psi = 7.5 billion, Nd=64N_d = 64), the 120GB of ordinary data parallelism drops to 31.4GB, 16.6GB, and 1.9GB.

At every stage, the computation is the same as ordinary data parallelism. Each GPU runs the forward and backward passes on its share of the minibatch using the full model's weights. The only change is who holds the model states, and where, while they are not used for computation. That is why it can be used without rewriting the model code.

Why communication volume does not increase

Even with partitioned memory, communication volume barely increases. Chapter 7 of the paper explains it as follows.

The All-Reduce of ordinary data parallelism is implemented in two stages, Reduce-Scatter (sum and give each GPU a different part) and All-Gather (collect each GPU's part on all GPUs), each sending Ψ\Psi of data, for 2Ψ2\Psi in total.

MethodCommunication per stepVolume
Ordinary data parallelismAll-Reduce of gradients2Ψ2\Psi
PosP_{os}, Pos+gP_{os+g}Reduce-Scatter of gradients + All-Gather of updated weightsΨ+Ψ=2Ψ\Psi + \Psi = 2\Psi (same)
Pos+g+pP_{os+g+p}Gather weights before the forward pass + gather again before the backward pass + Reduce-Scatter of gradientsΨ+Ψ+Ψ=3Ψ\Psi + \Psi + \Psi = 3\Psi (1.5x)

Pos+gP_{os+g} simply splits the All-Reduce in two and inserts "update only the part I own" between them, so the volume does not change. Pos+g+pP_{os+g+p} needs two weight-gathering communications, for the forward and backward passes, so it is 1.5x, but memory drops by a factor of the number of GPUs.

Memory for activations and more (ZeRO-R): Besides the model states, activations, temporary buffers, and memory fragmentation also use memory. The paper collectively calls ZeRO-R the methods of partitioning activation checkpoints that each GPU redundantly holds when combined with tensor parallelism (PaP_a), offloading them to CPU memory if needed, fixing buffer sizes, and preventing fragmentation. For activations, gradient checkpointing is also used.

Experimental results

The paper's implementation (ZeRO-100B) implements Pos+gP_{os+g} and ZeRO-R in PyTorch (Pos+g+pP_{os+g+p} is not included in this evaluation). It was evaluated on 400 V100 GPUs.

ComparisonResult
Trainable model sizeUp to 170 billion parameters on 400 GPUs; more than 8x Megatron-LM alone
Speed (8 billion to 100 billion parameters)15 PFLOPS aggregate on average (over 30% of peak); up to 10x over Megatron-LM alone
Size trainable without tensor parallelism13 billion parameters on 128 GPUs, over 40 TFLOPS per GPU. Ordinary data parallelism goes only up to 1.4 billion parameters, at under 20 TFLOPS
Scaling up the GPU countFor a 60-billion-parameter model, going from 64 to 400 GPUs gave a speedup exceeding the GPU ratio

As the basis of comparison, ZeRO keeps tensor parallelism within a single server, whereas Megatron-LM alone needs tensor parallelism across servers beyond 40 billion parameters. The paper states that the main cause of the gap is that communication bandwidth drops from 300GB/s to 12.5GB/s per link across servers.

The speedup exceeding the GPU ratio arises because the more GPUs there are, the smaller the model states per GPU, which allows a larger batch per GPU and higher compute efficiency.

This implementation was also used to train Turing-NLG, a 17-billion-parameter language model.

Practical considerations

What ZeRO reduces is the model states (weights, gradients, optimizer state). ZeRO-DP does not reduce activation memory. When batches or sequences are large and activations dominate memory, combine it with methods such as gradient checkpointing. The paper also estimates that a 100-billion-parameter GPT-style model needs about 60GB of activations at batch size 32 even with gradient checkpointing.

  • Choose the stage by balancing memory and communication. PosP_{os} and Pos+gP_{os+g} do not change communication volume, so they are the stages to try first. Use Pos+g+pP_{os+g+p} when memory is still insufficient. Communication becomes 1.5x, so it can be slower where GPU-to-GPU communication is slow.
  • More GPUs means less memory. The reduction is proportional to NdN_d, so the effect is small with few GPUs. Plug the GPU count into the formulas in the figure above to estimate whether the model states fit.
  • It can be combined with tensor parallelism. The paper states that with tensor-parallel degree NmN_m, memory per GPU can be reduced by up to a factor of Nd×NmN_d \times N_m. For example, it shows a configuration that fits a 1-trillion-parameter model on 1,024 GPUs with 16-way tensor parallelism within a server and 64-way data parallelism across servers.
  • Using it in PyTorch. PyTorch has ZeroRedundancyOptimizer, equivalent to PosP_{os}, which partitions the optimizer state. To also partition gradients and weights, use FSDP (PyTorch's Fully Sharded Data Parallel) or DeepSpeed by the paper's authors.

Comparison with other methods

This compares methods for reducing the memory of large models from the same viewpoints.

MethodWhat is partitionedComputationCommunication (relative to data parallelism)Model rewriting
Data parallelismData onlyWhole model on each GPU1xNot needed
ZeRO PosP_{os}, Pos+gP_{os+g}Optimizer state, gradientsSame as data parallelism1xNot needed
ZeRO Pos+g+pP_{os+g+p}, FSDPAll model states, including weightsSame as data parallelism (weights gathered just before computation)1.5xNot needed (wrapping units must be chosen)
Tensor parallelism (Megatron-LM)Matrices within a layerEach GPU computes part of a matrixCommunication per layer (slow across servers)Needed per layer
Pipeline parallelism (GPipe)Sequence of layersEach GPU computes some layersOnly activations at boundariesStage partitioning must be decided
  • If the model barely fails to fit on one GPU, start with PosP_{os} and Pos+gP_{os+g}, which do not increase communication.
  • Even a model that is far too large for one GPU can fit with Pos+g+pP_{os+g+p} (FSDP in PyTorch) given enough GPUs.
  • When a single layer is large or the model is very large, combine ZeRO with tensor and pipeline parallelism.

PyTorch example

Show code
python
import os
import torch
import torch.nn as nn
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.distributed.optim import ZeroRedundancyOptimizer

"""
Example of using ZeRO's P_os (partitioning the optimizer state) with PyTorch's ZeroRedundancyOptimizer
Example run (4 GPUs on one machine): torchrun --nproc_per_node=4 train_zero.py
"""

dist.init_process_group(backend='nccl' if torch.cuda.is_available() else 'gloo')
rank = dist.get_rank()
local_rank = int(os.environ['LOCAL_RANK'])
device = torch.device('cuda', local_rank) if torch.cuda.is_available() else torch.device('cpu')

model = nn.Sequential(*[nn.Sequential(nn.Linear(2048, 2048), nn.ReLU()) for _ in range(16)]).to(device)
model = DDP(model, device_ids=[local_rank] if torch.cuda.is_available() else None)  # Gradient averaging is ordinary data parallelism

# Just wrapping the optimizer partitions Adam's state (momentum and variance) across the GPUs
# Each GPU updates only the parameters it owns and broadcasts the updated weights to all
optimizer = ZeroRedundancyOptimizer(
  model.parameters(),
  optimizer_class=torch.optim.Adam,
  lr=1e-4,
)

for step in range(10):
  model.train()
  x = torch.randn(32, 2048, device=device)
  loss = model(x).pow(2).mean()
  optimizer.zero_grad()
  loss.backward()
  optimizer.step()
  if rank == 0:
    print(f"step {step}: loss {loss.item():.4f}")

# To save a checkpoint, gather the partitioned state onto one GPU first
optimizer.consolidate_state_dict(to=0)
if rank == 0:
  torch.save({'model': model.module.state_dict(), 'optimizer': optimizer.state_dict()}, 'ckpt.pt')

dist.destroy_process_group()

# To also partition gradients and weights (P_os+g, P_os+g+p), use PyTorch's FSDP or DeepSpeed

FAQ

Q. How should I choose among ZeRO's three stages?
A.

Start with the stages that do not change communication volume. PosP_{os}, which partitions the optimizer state, cuts memory to about one quarter, and Pos+gP_{os+g}, which also partitions gradients, to about one eighth. If that is still not enough, use Pos+g+pP_{os+g+p}, which also partitions weights. Memory drops by a factor of the number of GPUs, but communication volume becomes 1.5x.

Q. Should I use ZeRO or model parallelism (tensor parallelism)?
A.

If the only goal is to fit the model, ZeRO is easier. It reduces memory without rewriting the model code, used the same way as data parallelism. Tensor parallelism requires communication for every layer, so it slows down across servers. However, when activation memory needs to be reduced, or when data parallelism alone makes the global batch too large, combine it with tensor parallelism.

Q. Are ZeRO and FSDP the same thing?
A.

The idea is the same. FSDP is an implementation built into PyTorch of the method corresponding to ZeRO's Pos+g+pP_{os+g+p} (partitioning all of the weights, gradients, and optimizer state). A setting that partitions only gradients and optimizer state (corresponding to Pos+gP_{os+g}) is also available.

References

  1. Rajbhandari, S., Rasley, J., Ruwase, O., & He, Y. (2020). ZeRO: Memory Optimizations Toward Training Trillion Parameter Models. SC20: International Conference for High Performance Computing, Networking, Storage and Analysis. arXiv:1910.02054.
  2. PyTorch Documentation, "Distributed Optimizers - ZeroRedundancyOptimizer."