AI Logic

Distributed Training and Memory Saving

Pipeline Parallelism (PipeDream)

Updated:

How PipeDream works. Left: a 1F1B schedule with 4 stages, in which 4 minibatches are injected at startup and each GPU then alternates forward and backward passes. Right: the weight-stashing procedure for minibatch 5 on GPU 1, in which the weight version used in the forward pass is stashed, the gradient is computed with that version in the backward pass, and it is applied to the latest weights

Background and overview

PipeDream is a pipeline-parallel method that splits the sequence of a model's layers into stages placed on GPUs and keeps the pipeline flowing without stopping by having each GPU alternate one forward pass and one backward pass (1F1B). To use the same weights in the forward and backward passes, it combines this with "weight stashing," which keeps older versions of the weights.

In data parallelism, the All-Reduce communication of gradients for all weights becomes heavier as the number of GPUs grows. In the paper's measurements with 32 GPUs, up to 90% of the time was spent waiting on communication, depending on the model. With pipeline parallelism, each GPU only needs to send the activations and gradients at the stage boundary to one neighboring GPU.

However, deep learning training is a round trip, "a forward pass followed by a backward pass that traverses the same layers in reverse," so it does not work like an ordinary assembly line. If the pipeline is drained before each update after a fixed number of inputs, as in GPipe, GPUs sit idle (a bubble) every time.

In their 2019 paper (SOSP), Narayanan et al. proposed a schedule in which the pipeline is never drained and each GPU repeatedly alternates forward and backward passes, together with weight stashing to still obtain correct gradients. They report that time to reach target accuracy was up to 5.3x shorter than with data parallelism.

An analogy is the kitchen of a conveyor-belt sushi restaurant. The person shaping sushi and the person plating it finish earlier orders while taking new ones, so nobody's hands are idle and the flow continues.

Theory

PipeDream's training flow is as follows (left of the figure above; Section 3.2 and Figure 4 of the paper).

  1. Split the sequence of the model's layers into stages and place each stage on a GPU. Let KK be the number of stages.
  2. Startup: Inject into the input stage just enough minibatches to fill the pipeline. For a configuration with stages in a single line, this is KK (NOAM in the paper).
  3. As soon as the last stage finishes the forward pass of a minibatch, it runs the backward pass of that minibatch.
  4. Steady state: Each stage alternates, one at a time, the forward pass of one minibatch and the backward pass of an earlier minibatch (1F1B).
  5. Each stage updates its own weights every time it finishes one backward pass.

In the steady state, every GPU is always running either a forward or a backward pass. Because the pipeline never needs to be drained, a GPipe-style bubble occurs only at startup.

The problem here is the mismatch of weight versions. On GPU 1 in the figure, the forward pass of minibatch 5 runs after the update from minibatch 1, but its backward pass runs after the updates from minibatches 2, 3, and 4. Computing the gradient with weights different from those of the forward pass does not give the correct gradient.

PipeDream therefore uses weight stashing (right of the figure above; Section 3.3 of the paper).

  1. The forward pass uses the latest weights at that moment and stashes that version.
  2. The backward pass computes the gradient with the same stashed version of the weights.
  3. The computed gradient is applied to the latest weights at that moment.
  4. The old version is discarded once it has been used.

With nn stages and wl(t)\boldsymbol{w}_l^{(t)} denoting the weights of stage ll after processing tt minibatches, the update with weight stashing is, in the paper's notation,

w(t+1)=w(t)−ν⋅∇f ⁣(w1(t−n+1),w2(t−n+2),…,wn(t))\boldsymbol{w}^{(t+1)} = \boldsymbol{w}^{(t)} - \nu \cdot \nabla f\!\left(\boldsymbol{w}_1^{(t-n+1)}, \boldsymbol{w}_2^{(t-n+2)}, \dots, \boldsymbol{w}_n^{(t)}\right)

where ff is the loss and ν\nu is the learning rate. The gradient of the first stage is computed with weights from n−1n-1 steps earlier, and that of the last stage with the latest weights. The paper points out that without weight stashing, this update is not the gradient of the loss with respect to any set of weights.

Stage partitioning and memory

In addition to 1F1B and weight stashing, PipeDream has a mechanism that automatically decides how to partition the stages. Since pipeline speed is determined by the slowest stage, it is important to balance the compute time of the stages.

PhaseWhat it does
ProfilingRuns 1,000 minibatches on a single GPU and measures each layer's forward and backward time, output size, and weight size
PartitioningUses dynamic programming to split layers into stages so that the time of the slowest stage is minimized. It also accounts for differences in communication speed (within and across servers)
ReplicationReplicates compute-heavy stages across multiple GPUs as data parallelism (e.g., "15-1" for VGG-16, with 15 GPUs for the convolutional stage and 1 for the fully connected stage)

When a stage is replicated, GPUs are assigned in round-robin order by minibatch ID so that the forward and backward passes of the same minibatch run on the same GPU (1F1B-RR). This is because the backward pass needs the weights and activations used in the forward pass.

Weight stashing increases memory, but it stays at about the same level as data parallelism. When split into nn stages, each GPU holds 1/n1/n of the whole model's weights and activations. Since at most nn minibatches are in flight, holding nn versions of weights and activations totals about the same as each GPU holding the whole model in data parallelism.

Version mismatch across stages remains. Weight stashing only aligns the forward and backward weights within one stage. Each stage uses a different weight version; an option called "vertical sync," which makes all stages use the same version, is available but not used by default. The paper states that the default behavior has properties between single-GPU minibatch SGD and synchronous data parallelism.

Experimental results

The paper compared time to reach target accuracy against data parallelism (synchronous All-Reduce) (Table 1 of the paper). The GPUs were V100s (Cluster-A: 4 per server, PCIe, 10 Gbps between servers; Cluster-B: 8 per server, NVLink, 25 Gbps).

TaskModelTargetConfiguration (servers × GPUs)Stage configurationSpeedup over data parallelism
Image classificationVGG-16top-1 68%4×4 (A)15-15.28x
Image classificationVGG-16top-1 68%2×8 (B)15-12.46x
Image classificationResNet-50top-1 75.9%4×4 (A)16 (data parallel)1x
TranslationGNMT-16BLEU 21.82×8 (B)Straight3.14x
Language modelAWD LMPerplexity 981×4 (A)Straight4.25x
  • Where it beats data parallelism: Models with layers that have large weights and small outputs (the fully connected layers of VGG-16, an LSTM language model) saw large speedups. For AWD LM, communication volume was 88% lower than with data parallelism.
  • Where data parallelism was chosen: ResNet-50 consists of convolutional layers with small weights and large outputs, so a pipeline increases communication. PipeDream's partitioner chose data parallelism (one stage replicated across 16 GPUs).
  • Training progress: In most settings, the number of epochs to reach target accuracy was about the same as with data parallelism; the speedup came from shorter time per epoch.

Compared with the GPipe approach (implemented by the paper's authors with the same stage partitioning), when training GNMT-16 on 16 GPUs, GPipe's throughput was 35-71% lower than PipeDream's. The paper attributes this mainly to how often GPipe drains the pipeline.

Practical considerations

PipeDream's default update is asynchronous. Each stage updates with gradients computed on a slightly stale weight version, so the result is not exactly the same as training on a single GPU or with data parallelism. In the paper's experiments it reaches target accuracy, but if training results need to match the single-GPU case, choose a synchronous method such as GPipe.

  • Weight versions require memory. A version of the weights and activations is kept for each in-flight minibatch. Increasing the pipeline depth (the number of minibatches in flight) raises speed but also memory. In the paper's GNMT-8 experiment, depths of 4 (NOAM) and 7 were the fastest.
  • Some models are poorly suited. With many layers that have small weights and large outputs, such as convolutional layers, the activations sent at stage boundaries become larger, and data parallelism needs less communication.
  • PyTorch's Schedule1F1B is synchronous. Schedule1F1B in PyTorch's torch.distributed.pipelining runs the microbatches of one split minibatch in 1F1B order and updates all at once after they all finish. The order is the same as PipeDream, but it does not use weight stashing, and the update is synchronous like GPipe.

Comparison with other parallelism methods

This compares other pipeline-parallel methods and data parallelism from the same viewpoints.

MethodScheduleUpdateIdle timeExtra memory
PipeDream1F1B (alternating forward and backward)Asynchronous (weight stashing)Only at startupVersions of weights and activations for each in-flight minibatch
GPipeAll forward passes, then all backward passesSynchronous (all at once at the end of the minibatch)A bubble every time, K−1M+K−1\frac{K-1}{M+K-1}Activations of all microbatches (reduced with gradient checkpointing)
Data parallelismEach GPU computes the whole modelSynchronous (All-Reduce)None (but waits on communication)Each GPU holds the whole model
Tensor parallelism (Megatron-LM)All GPUs compute the same layer simultaneouslySynchronousNone (communication per layer)Almost none
  • When communication between servers is slow and the model has large weights, a low-communication pipeline-parallel method such as PipeDream has the advantage.
  • When training results need to match the single-GPU case, choose GPipe or a method that updates synchronously in 1F1B order (such as PyTorch's Schedule1F1B).
  • For convolutional models with small weights and large activations, data parallelism can be faster.

PyTorch example

Show code
python
import copy
import torch
import torch.nn as nn
from torch.func import functional_call

"""
Minimal example of PipeDream's weight stashing (takes out a single stage and runs it in one process)
Stashes the weight version used in the forward pass, computes the gradient with that version in the backward pass, and applies it to the latest weights
"""

torch.manual_seed(0)
dim = 32


class StashingStage:
  def __init__(self, module, lr=0.01):
    self.module = module
    self.optimizer = torch.optim.SGD(module.parameters(), lr=lr)
    self.stash = {}  # minibatch ID -> (weight version used in the forward pass, output)

  def forward(self, mb_id, x):
    # 1. Copy and stash the latest weights at this moment, and run the forward pass with that version
    version = {name: p.detach().clone().requires_grad_(True)
               for name, p in self.module.named_parameters()}
    out = functional_call(self.module, version, (x,))
    self.stash[mb_id] = (version, out)
    return out.detach()

  def backward(self, mb_id, grad_out):
    # 2. Compute the gradient with the same stashed version (the forward computation graph was built with that version)
    version, out = self.stash.pop(mb_id)   # 4. Discard the version once it is used
    out.backward(grad_out)
    # 3. Apply the computed gradient to the latest weights
    for name, p in self.module.named_parameters():
      p.grad = version[name].grad
    self.optimizer.step()
    self.optimizer.zero_grad()


stage = StashingStage(nn.Sequential(nn.Linear(dim, dim), nn.ReLU(), nn.Linear(dim, dim)))
batches = {i: torch.randn(8, dim) for i in range(1, 10)}

# 1F1B order for stage 1 (the first of 4 stages): inject 4 at startup, then alternate backward and forward
order = [('F', 1), ('F', 2), ('F', 3), ('F', 4),
         ('B', 1), ('F', 5), ('B', 2), ('F', 6), ('B', 3), ('F', 7), ('B', 4), ('F', 8), ('B', 5)]
for op, mb in order:
  if op == 'F':
    stage.forward(mb, batches[mb])
  else:
    # Normally this gradient comes from the next stage; random values are used here as an example
    stage.backward(mb, torch.randn(8, dim))

# The forward pass of minibatch 5 used the weights after the B1 update, and its backward pass ran after the B2-B4 updates,
# but the gradient is computed with the stashed "weights after the B1 update"
print(len(stage.stash))  # Only the versions of the in-flight minibatches (6, 7, 8) remain -> 3

FAQ

Q. What is 1F1B?
A.

It is a schedule that alternates "one forward pass (1 Forward) and one backward pass (1 Backward)." After the pipeline is filled at startup, each GPU alternates the forward pass of one minibatch and the backward pass of an earlier minibatch. This keeps every GPU always computing something without draining the pipeline.

Q. What happens without weight stashing?
A.

The forward and backward passes use different weight versions, so the computed gradient is incorrect. The paper points out that the resulting update is not the gradient of the loss with respect to any set of weights, and training may fail to converge. Weight stashing keeps the version used in the forward pass until the backward pass, making the gradient within one stage correct.

Q. Should I use PipeDream or GPipe?
A.

If training results need to match the single-GPU case, synchronous GPipe (or a method that updates synchronously in 1F1B order) is easier to work with. When communication is slow and speed is the priority even at the cost of slightly stale weights, PipeDream is a good fit. In the original paper, with the same stage partitioning, GPipe's throughput was 35-71% lower than PipeDream's.

References

  1. Narayanan, D., Harlap, A., Phanishayee, A., Seshadri, V., Devanur, N. R., Ganger, G. R., Gibbons, P. B., & Zaharia, M. (2019). PipeDream: Generalized Pipeline Parallelism for DNN Training. Proceedings of the 27th ACM Symposium on Operating Systems Principles (SOSP '19).
  2. Harlap, A., Narayanan, D., Phanishayee, A., Seshadri, V., Devanur, N., Ganger, G., & Gibbons, P. (2018). PipeDream: Fast and Efficient Pipeline Parallel DNN Training. arXiv:1806.03377.
  3. PyTorch Documentation, "Pipeline Parallelism - torch.distributed.pipelining."