AI Logic

Distributed Training and Memory Saving

Pipeline Parallelism (GPipe)

Updated:

The GPipe pipeline. Top: a timeline of model parallelism without micro-batches, where only one of the four GPUs works at a time and idle time is long. Bottom: a timeline of GPipe, which splits the mini-batch into four micro-batches, runs the forward passes staggered, then runs the backward passes, and finally updates all at once. The idle time (bubble) becomes shorter

Background and overview

GPipe is a pipeline-parallel method that splits a model's sequence of layers into several stages placed on different GPUs, and further divides each mini-batch into smaller micro-batches that flow through in order like an assembly line. It can train large models that do not fit on one GPU across multiple GPUs while keeping GPU idle time down.

If the model is simply cut along its sequence of layers and distributed across GPUs, GPU 2 waits until GPU 1 finishes, and in the backward pass GPU 1 in turn waits for the GPUs above it. Only one GPU works at any moment, so adding more GPUs does not make it faster (top of the figure above).

In a 2019 paper (NeurIPS), Huang et al. split the mini-batch into MM micro-batches and fed them through in sequence, so that different GPUs can compute different micro-batches at the same time (bottom of the figure above). Because the gradients are accumulated over the whole mini-batch before updating, the updates are the same as training on a single device, regardless of the number of stages. With this method they trained a 557M-parameter AmoebaNet and a 128-layer, 6B-parameter multilingual translation Transformer.

As an analogy, consider an assembly line in which washing, drying, and folding are each handled by one person. If all the laundry goes through as one big pile, the person drying can do nothing until all the washing is done. If it is split into small baskets passed along one after another, all three can work at the same time.

Theory

One training step of GPipe proceeds as follows (Section 2.2 and Figure 2c of the paper).

  1. Split an LL-layer model into KK groups of consecutive layers (stages), and place stage kk on GPU kk. Split so that the computational cost of the stages is balanced.
  2. Divide a mini-batch of size NN into MM micro-batches of equal size.
  3. Forward pass: send the micro-batches one at a time through stage 1 onward. When GPU kk finishes computing micro-batch mm, it sends the output to GPU k+1k+1 and immediately starts computing the next micro-batch m+1m+1.
  4. Backward pass: after the forward passes of all micro-batches are complete, propagate the per-micro-batch gradients backward starting from the last stage. The gradients are computed using the same weights as in the forward pass.
  5. Sum the gradients of the MM micro-batches and update the weights on all GPUs simultaneously at the end of the mini-batch.

While the micro-batches are starting to flow until all stages are busy, and again while they are draining, some GPUs are doing nothing. This idle time is called the bubble. With KK stages and MM micro-batches, the fraction of one step taken up by the bubble is approximately

K−1M+K−1\frac{K-1}{M+K-1}

(Section 2.3 of the paper). In the example in the figure (K=M=4K = M = 4), each GPU is idle for 3 out of 7 time slots. The larger MM is, the smaller this fraction becomes. The paper reports that the bubble was almost negligible when M≥4KM \geq 4K.

GPipe is a synchronous method. Every micro-batch is computed with the same weights and the update is done all at once at the end of the mini-batch, so the gradients are the same as in training without a pipeline. Since changing the number of stages does not change the training result, you can add more devices without retuning hyperparameters.

Techniques for reducing memory and communication

Beyond pipelining, GPipe also reduces activation memory by combining it with gradient checkpointing (which the paper calls re-materialization).

  • In the forward pass, each GPU saves only the outputs at the stage boundaries.
  • In the backward pass, GPU kk recomputes the stage's forward pass FkF_k from the saved input to rebuild the activations inside the stage.

With this, the peak activation memory becomes

O ⁣(N+LK×NM)O\!\left(N + \frac{L}{K} \times \frac{N}{M}\right)

Here NN is for saving the boundary outputs, and LK×NM\frac{L}{K} \times \frac{N}{M} is for recomputing one stage (L/KL/K layers) on one micro-batch (N/MN/M examples). This is much smaller than the O(N×L)O(N \times L) required without checkpointing or stage partitioning. The paper notes that the recomputation for the backward pass can start early without waiting for the gradients of the preceding layers, which also helps fill the bubble.

Communication consists only of sending the activations and gradients at stage boundaries to neighboring GPUs. As a result, near-linear speedup with the number of devices can be achieved even when the GPUs are not connected by fast links. For models that use batch normalization, the statistics during training are computed per micro-batch, while the moving averages used for evaluation are tracked over the whole mini-batch.

Experimental results

Speed as the number of devices grows: training throughput for different numbers of stages KK and micro-batches MM (normalized so that K=2K = 2, M=1M = 1 is 1) on TPUs (Table 2 of the paper).

ModelMMK=2K = 2K=4K = 4K=8K = 8
AmoebaNet111.131.38
AmoebaNet41.071.261.72
AmoebaNet321.211.843.48
Transformer111.071.3
Transformer41.73.24.8
Transformer321.83.46.3
  • With M=1M = 1 (no micro-batches), adding devices barely helps, because only one device works at any moment.
  • The Transformer's per-layer computation is uniform, so it sped up nearly linearly with the number of devices. AmoebaNet has uneven per-layer computation, so it scaled sublinearly.
  • Even on P100 GPUs without fast interconnects (NVLink), going from 2 to 8 stages with M=32M = 32 gave 2.7× for AmoebaNet and 3.3× for the Transformer (Table 3).

Model size that can be trained: on TPUv3 with 16GB per device, a Transformer of up to 83.9B parameters (128 stages), 298× the size trainable on one device, could be trained; on accelerators with 8GB per device, an AmoebaNet of up to 1.8B parameters (8 stages), 25× larger, could be trained (Table 1). Even on a single device, gradient checkpointing and micro-batches reduced AmoebaNet's activation memory from 6.26GB to 3.46GB, raising the trainable size from 82M to 318M parameters.

Accuracy: a 557M-parameter AmoebaNet-B (4 stages, 480×480 input) achieved 84.4% top-1 accuracy on ImageNet. In multilingual translation, a single 128-layer, 6B-parameter Transformer trained on 103 languages outperformed 350M-parameter models trained separately per language on 100 language pairs.

Practical considerations

With too few micro-batches MM, GPUs sit idle in the bubble. In the paper's results, the bubble was almost negligible when MM was at least 4 times the number of stages KK. However, increasing MM makes the micro-batches smaller, which can lower the efficiency of each computation, so choose it together with the overall batch size.

  • Balance the computational cost of the stages. The speed of the pipeline is determined by the slowest stage. The paper's method partitions the layers based on per-layer cost estimates so that the differences between stages are small. AmoebaNet, with its uneven per-layer cost, did not speed up linearly with the number of devices.
  • Activation memory grows with the number of micro-batches. Before the backward pass starts, the stage-boundary outputs of all micro-batches must be held. Combine with gradient checkpointing to reduce this. A schedule that starts the backward pass early to reduce this memory is the 1F1B schedule of PipeDream.
  • Batch normalization uses per-micro-batch statistics. Be careful, because the statistics become unstable if micro-batches are too small.
  • Combine with other forms of parallelism. The paper notes that GPipe can be combined with data parallelism to scale to even more devices.

Comparison with other forms of parallelism

Even within pipeline parallelism, methods differ in their schedules and in how they handle weights.

MethodWhat is splitScheduleWeight updatesIdle time
Plain model parallelismSequence of layersRun one mini-batch through in orderSynchronousVery large (only one device works at a time)
GPipeSequence of layersAll forward passes, then all backward passesSynchronous (all at once at the end of the mini-batch)Bubble of K−1M+K−1\frac{K-1}{M+K-1}
PipeDreamSequence of layersAlternate one forward and one backward pass (1F1B)Asynchronous (keeps multiple weight versions)Almost none in steady state
Tensor parallelism (Megatron-LM)Matrices within a single layerAll GPUs compute the same layer simultaneouslySynchronousAlmost none (communication per layer)
  • When the training result should match that of a single device, the synchronous GPipe is easy to work with.
  • To further reduce the bubble and activation memory, consider PipeDream's 1F1B schedule.
  • A common setup for training large models is to combine both: tensor parallelism when individual layers are large, and pipeline parallelism when there are many layers.

PyTorch example

Show code
python
import os
import torch
import torch.nn as nn
import torch.distributed as dist
from torch.distributed.pipelining import PipelineStage, ScheduleGPipe

"""
GPipe pipeline parallelism (PyTorch's torch.distributed.pipelining)
Example run (4 GPUs on one machine): torchrun --nproc_per_node=4 train_gpipe.py
"""

dist.init_process_group(backend='nccl' if torch.cuda.is_available() else 'gloo')
rank = dist.get_rank()
world_size = dist.get_world_size()      # number of stages K (one stage per GPU)
local_rank = int(os.environ['LOCAL_RANK'])
device = torch.device('cuda', local_rank) if torch.cuda.is_available() else torch.device('cpu')

batch_size = 64     # mini-batch size N
n_microbatches = 16  # number of micro-batches M (the bubble is small when M >= 4K)
dim, n_layers = 1024, 16

# 1. Split the L-layer model into K stages and build only this GPU's stage (equal numbers of layers)
layers_per_stage = n_layers // world_size
stage_module = nn.Sequential(*[
  nn.Sequential(nn.Linear(dim, dim), nn.ReLU()) for _ in range(layers_per_stage)
])
if rank == world_size - 1:
  stage_module.append(nn.Linear(dim, 10))  # put the output layer in the last stage
stage_module.to(device)

stage = PipelineStage(stage_module, rank, world_size, device)

# 2. GPipe schedule: run all forward passes, then all backward passes
def loss_fn(output, target):
  return nn.functional.cross_entropy(output, target)

schedule = ScheduleGPipe(stage, n_microbatches=n_microbatches, loss_fn=loss_fn)
optimizer = torch.optim.Adam(stage_module.parameters(), lr=1e-3)

for step in range(10):
  stage_module.train()
  optimizer.zero_grad()
  x = torch.randn(batch_size, dim, device=device)
  y = torch.randint(0, 10, (batch_size,), device=device)
  if rank == 0:
    schedule.step(x)                       # first stage: split the mini-batch into M and feed them in
  elif rank == world_size - 1:
    losses = []
    schedule.step(target=y, losses=losses)  # last stage: receive the loss of each micro-batch
    print(f"step {step}: loss {torch.stack(losses).mean().item():.4f}")
  else:
    schedule.step()                        # middle stages: receive, compute, and send to the next
  # 3. The gradients of the M micro-batches have accumulated, so update once at the end of the mini-batch (synchronous)
  optimizer.step()

dist.destroy_process_group()

FAQ

Q. How many micro-batches should I use?
A.

A rule of thumb is at least 4 times the number of stages KK. In the original paper, the bubble was almost negligible with M≥4KM \geq 4K. The bubble fraction is approximately K−1M+K−1\frac{K-1}{M+K-1}, so it shrinks as MM grows. However, micro-batches that are too small lower the efficiency of each computation and make batch normalization statistics unstable.

Q. Does training with GPipe give different results from training on a single device?
A.

The gradients are the same. GPipe computes all micro-batches with the same weights, sums the gradients, and updates only once at the end of the mini-batch. The one difference is that batch normalization statistics are computed per micro-batch.

Q. How is GPipe different from PipeDream?
A.

GPipe is synchronous: it runs all forward passes, then all backward passes, and updates all at once at the end of the mini-batch. The result matches that of a single device, but a bubble remains. PipeDream alternates one forward and one backward pass (1F1B) and updates the weights per micro-batch. Idle time almost disappears, but it must keep multiple weight versions and the updates become asynchronous.

References

  1. Huang, Y., Cheng, Y., Bapna, A., Firat, O., Chen, M. X., Chen, D., Lee, H., Ngiam, J., Le, Q. V., Wu, Y., & Chen, Z. (2019). GPipe: Efficient Training of Giant Neural Networks using Pipeline Parallelism. NeurIPS 2019. arXiv:1811.06965.
  2. PyTorch Documentation, "Pipeline Parallelism - torch.distributed.pipelining."