AI Logic

Distributed Training and Memory Saving

Data Parallelism

Updated๏ผš

How data parallelism works. Left: the flow in which a minibatch is split across N GPUs, the gradients computed by each GPU's model replica are averaged with All-Reduce, and then the weights are updated. Right: a numerical example of All-Reduce averaging the gradients of 3 GPUs

Background and overview

Data parallelism is a training method that places a replica of the same model on each of several GPUs, splits the minibatch so each computes its part separately, averages the resulting gradients, and then updates every replica in the same way. Among the methods for speeding up training with multiple GPUs or machines, it is the most basic and the most widely used.

In deep learning, the more data there is and the larger the batch size used per step, the longer training takes on a single GPU. With data parallelism, for example, 256 examples can be split into 64 per GPU across 4 GPUs and computed simultaneously, dividing the computation of one training step by the number of devices.

The idea is similar to splitting the grading of a test among four people. If the answer sheets are split into four piles, each person computes the average score of their pile, and the four averages are then averaged, the result equals the average obtained when one person grades every sheet. In data parallelism, this "average score" corresponds to the gradient.

Data parallelism averages the gradients using a collective communication called All-Reduce. In All-Reduce, every participant contributes data of the same size, and every participant receives the sum (or average). PyTorch's DistributedDataParallel (DDP) is a representative implementation of data parallelism based on this mechanism, and Li et al. described its design in a 2020 paper. This article mainly follows that paper.

Theory

One training step of data parallelism goes as follows (left of the figure above).

  1. Before training starts, set the model weights on all GPUs to the same values.
    • DDP sends the weights of one process to all the other processes (broadcast).
  2. Split the minibatch (BB examples) across the NN GPUs, each receiving B/NB/N examples.
  3. Each GPU runs the forward pass and backpropagation on its share of the data and computes a gradient gk\boldsymbol{g}_k.
  4. All-Reduce computes the average of the gradients from all GPUs, and every GPU receives the same averaged gradient.
  5. Each GPU updates its weights with its own optimizer. Because everyone uses the same gradient, the updated weights are also identical.

In equations, with Bk\mathcal{B}_k the set of data assigned to GPU kk,

gk=NBโˆ‘iโˆˆBkโˆ‡ฮธโ„“i,g=1Nโˆ‘k=1Ngk=1Bโˆ‘i=1Bโˆ‡ฮธโ„“i\boldsymbol{g}_k = \frac{N}{B} \sum_{i \in \mathcal{B}_k} \nabla_{\boldsymbol{\theta}} \ell_i, \qquad \boldsymbol{g} = \frac{1}{N} \sum_{k=1}^{N} \boldsymbol{g}_k = \frac{1}{B} \sum_{i=1}^{B} \nabla_{\boldsymbol{\theta}} \ell_i

Here, โ„“i\ell_i is the loss of the ii-th example and ฮธ\boldsymbol{\theta} is the model weights. As the right-hand equation shows, the average g\boldsymbol{g} of the GPUs' gradients matches the gradient computed for all BB examples on one device.

Data parallelism is designed to be mathematically equivalent to training with a large batch on one device. This makes it possible to add devices with almost no changes to the model or training code. In DDP, simply wrapping a single-device model in DistributedDataParallel is enough; gradient averaging happens automatically during the backward pass.

An alternative is to average the weights after each replica has updated them (parameter averaging). Li et al. explain that DDP chose gradient averaging because, with optimizers that use past gradients such as momentum, parameter averaging is not equivalent to single-device training and the optimizer states on each GPU gradually drift apart, and because it makes overlapping computation and communication harder.

Techniques for faster communication

In data parallelism, speed is usually determined by communication. Li et al.'s evaluation also reports that communication takes more than half of the backward pass time, and that the fraction grows with model size. DDP reduces communication wait time with the following techniques.

TechniqueMechanismPurpose
Gradient bucketingGroup several small gradients (25MB per bucket by default) into one All-ReduceSending data in bulk is faster than sending small pieces many times
Overlapping computation and communicationDuring the backward pass, start All-Reduce as soon as a bucket's gradients are ready, without waiting for the remaining layersRun backward computation and communication at the same time
Skipping synchronization (no_sync)For several iterations, only accumulate gradients locally, then average them all at once on the last oneReduce the number of communications. Also usable for gradient accumulation

In the paper's evaluation, overlapping computation and communication made training 38.0% faster for ResNet50 and 35.2% faster for BERT when using NCCL as the communication library.

Bucket size is a trade-off between communication efficiency and waiting time. Larger buckets make each communication more efficient but increase the wait until a bucket is ready. The paper reports that, when configured properly, DDP achieved near-linear scaling on 256 GPUs.

All-Reduce is implemented with communication libraries such as NCCL, Gloo, and MPI. In ring All-Reduce, GPUs are connected in a ring and exchange data piece by piece with their neighbors. With this scheme, the communication volume per device is about twice the gradient size and barely grows as devices are added.

Practical notes and differences from other parallelism

When using data parallelism, keep the following in mind.

  • The global batch size grows. With 64 examples per device on 8 devices, the global batch size is 512. Goyal et al. combined the "linear scaling rule," which multiplies the learning rate by kk when the batch size is multiplied by kk, with warmup, which gradually raises the learning rate at the start of training, and report training ResNet-50 with a batch of 8,192 on 256 GPUs in about one hour without loss of accuracy. For even larger batches, optimizers such as LARS and LAMB are also used.
  • The whole model must fit on each GPU. Every GPU holds its own copy of the weights, gradients, and optimizer states, which wastes memory. For large models that do not fit on one device, combine it with ZeRO or FSDP, which partition these across GPUs, or with GPipe (pipeline parallelism) or Megatron-LM (tensor parallelism), which split the model itself.
  • Batch normalization statistics are computed within each GPU. By default, the mean and variance of batch normalization are computed only from the B/NB/N examples on each GPU. DDP keeps values such as running averages consistent by broadcasting them from one process, but to compute the training statistics across all GPUs, use SyncBatchNorm.
  • Keep the data partitioning consistent. To prevent GPUs from reading the same examples, PyTorch uses DistributedSampler, and set_epoch is called every epoch to change the shuffle.

Adding devices in data parallelism does not reduce the communication volume of each training step. With a large model and slow communication between GPUs (such as across machines), adding devices may not speed up training. Tune the bucket size and how often synchronization is skipped while measuring throughput.

The differences from other forms of parallelism are as follows.

MethodWhat is splitWhat each GPU holdsWhen it fits
Data parallelismData (the minibatch)The whole modelWhen the model fits on one device. The simplest
ZeRO / FSDPData, plus weights, gradients, and optimizer statesPart of the model (gathered when needed)When the model barely fails to fit on one device
Pipeline parallelismLayers (the model split by depth)Some of the layersVery large models with many layers
Tensor parallelismMatrices within a layerPart of each matrixWhen a single layer is too large

PyTorch example

Show code
python
import os
import torch
import torch.nn as nn
import torch.optim as optim
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.data import DataLoader
from torch.utils.data.distributed import DistributedSampler
from torchvision import datasets, transforms

'''
Image classification task using MNIST data (data parallelism)
Example run (4 GPUs on one machine): torchrun --nproc_per_node=4 train_ddp.py
'''

# Hyperparameters
batch_size = 64       # batch size per GPU (64 ร— number of GPUs in total)
epochs = 5            # number of epochs
learning_rate = 1e-3  # learning rate

# Get this process's rank from the environment variables set by torchrun
dist.init_process_group(backend='nccl' if torch.cuda.is_available() else 'gloo')
rank = dist.get_rank()
local_rank = int(os.environ['LOCAL_RANK'])
if torch.cuda.is_available():
  torch.cuda.set_device(local_rank)
  device = torch.device('cuda', local_rank)
else:
  device = torch.device('cpu')

# Dataset and loader (DistributedSampler makes each GPU read different data)
transform = transforms.Compose([
  transforms.ToTensor(),
  transforms.Normalize((0.1307,), (0.3081,))
])
if rank == 0:
  datasets.MNIST(root='./data', train=True, download=True)  # download in only one process
dist.barrier()
train_dataset = datasets.MNIST(root='./data', train=True, download=False, transform=transform)
sampler = DistributedSampler(train_dataset, shuffle=True)
train_loader = DataLoader(train_dataset, batch_size=batch_size, sampler=sampler)

# Model (place the same model on each GPU and wrap it in DDP)
model = nn.Sequential(
  nn.Flatten(),
  nn.Linear(28 * 28, 256), nn.ReLU(),
  nn.Linear(256, 10)
).to(device)
model = DDP(model, device_ids=[local_rank] if torch.cuda.is_available() else None)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)

# Training loop (almost the same as on one device; gradients are averaged automatically inside loss.backward())
for epoch in range(epochs):
  sampler.set_epoch(epoch)  # change the shuffle every epoch
  model.train()
  for images, labels in train_loader:
    images, labels = images.to(device), labels.to(device)
    optimizer.zero_grad()
    loss = criterion(model(images), labels)
    loss.backward()
    optimizer.step()
  if rank == 0:
    print(f"epoch {epoch + 1}: loss {loss.item():.4f}")

# Save in only one process (the weights are the same on every GPU)
if rank == 0:
  torch.save(model.module.state_dict(), 'mnist_ddp.pt')
dist.destroy_process_group()

FAQ

Q. What is the difference between DataParallel and DistributedDataParallel?
A.

DataParallel uses multiple threads within a single process and parallelizes only across the GPUs of one machine. DistributedDataParallel (DDP) launches a separate process per GPU and can also scale across multiple machines. PyTorch recommends using DDP.

Q. Should the learning rate change when adding GPUs?
A.

If devices are added without changing the per-device batch size, the global batch size grows, so the learning rate should be revisited. Goyal et al. propose multiplying the learning rate by k when the batch size is multiplied by k, and adding warmup at the start of training. However, for very large batches, this rule alone may not work well.

Q. Can data parallelism be used when the model does not fit on one GPU?
A.

Plain data parallelism cannot be used, because each GPU holds the whole model. Combine it with ZeRO or FSDP, which partition weights, gradients, and optimizer states across GPUs, or with pipeline or tensor parallelism, which split the model's layers or matrices.

References

  1. Li, S., Zhao, Y., Varma, R., Salpekar, O., Noordhuis, P., Li, T., Paszke, A., Smith, J., Vaughan, B., Damania, P., & Chintala, S. (2020). PyTorch Distributed: Experiences on Accelerating Data Parallel Training. Proceedings of the VLDB Endowment, 13(12), 3005โ€“3018.
  2. Goyal, P., Dollรกr, P., Girshick, R., Noordhuis, P., Wesolowski, L., Kyrola, A., Tulloch, A., Jia, Y., & He, K. (2017). Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour. arXiv:1706.02677.