AI Logic

Distributed Training and Memory Saving

Tensor Parallelism (Megatron-LM)

Updated:

How tensor parallelism works. Left: the MLP block split across 2 GPUs, with weight A split by columns and B split by rows, summed at the end with All-Reduce. Right: the Self-Attention block, where the attention heads are divided among the GPUs and the output linear layer is split by rows and then summed

Background and overview

Tensor parallelism is a model-parallel method that splits the weight matrices of a single layer across multiple GPUs and has each GPU compute its share of the matrix multiplication. Megatron-LM is a design of this approach tailored to the Transformer; by adding only a small amount of communication inside each layer, it makes it possible to train large language models that do not fit on one GPU.

In data parallelism, every GPU holds the whole model, so it cannot be used unless the model fits in one GPU's memory. A method that splits the model itself is therefore needed. There are two ways to split: pipeline parallelism, which cuts the sequence of layers and assigns the pieces to GPUs, and tensor parallelism, which splits the matrices inside a single layer.

In their 2019 paper "Megatron-LM," Shoeybi et al. showed how to parallelize the two blocks of the Transformer (multi-head attention and the MLP) with only two All-Reduces in the forward pass and two in the backward pass per layer. No new compiler or library is required; it can be implemented by adding communication at a few places in an existing PyTorch Transformer implementation. With this method they trained an 8.3B-parameter GPT-2-style model and a 3.9B-parameter BERT-style model.

As an analogy, it is like splitting the computation of a large table by columns among several people. Each person computes only their assigned columns, and at the end they bring their results together and add them up.

Theory

One Transformer layer consists of a Self-Attention block and a two-layer MLP block. Megatron-LM splits each block as follows (figure above; Figure 3 of the paper). The explanation assumes 2 GPUs.

MLP block

  1. Pass the same input XX to all GPUs (ff in the figure).
  2. Split the first weight AA by columns, A=[A1,A2]A = [A_1, A_2]. GPU ii computes Yi=GeLU(XAi)Y_i = \mathrm{GeLU}(XA_i).
  3. Split the second weight BB by rows, and GPU ii computes YiBiY_i B_i.
  4. Sum the YiBiY_i B_i from each GPU with All-Reduce (gg in the figure). The sum equals YBYB computed without splitting.
  5. Apply Dropout to the summed output and pass it on.

There is a reason for splitting the first weight by columns. If it were split by rows, with X=[X1,X2]X = [X_1, X_2] and A=[A1A2]A = \begin{bmatrix} A_1 \\ A_2 \end{bmatrix}, then XA=X1A1+X2A2XA = X_1A_1 + X_2A_2, and a sum would be needed before the GELU. Since GELU is nonlinear,

GeLU(X1A1+X2A2)≠GeLU(X1A1)+GeLU(X2A2)\mathrm{GeLU}(X_1A_1 + X_2A_2) \neq \mathrm{GeLU}(X_1A_1) + \mathrm{GeLU}(X_2A_2)

so synchronization between GPUs would be required here. Splitting by columns gives, as in Eq. (3) of the paper,

[Y1,Y2]=[GeLU(XA1), GeLU(XA2)][Y_1, Y_2] = [\mathrm{GeLU}(XA_1),\ \mathrm{GeLU}(XA_2)]

so everything up to the GELU can be computed without communication. Multiplying each output YiY_i directly by the row-split BiB_i gives YB=Y1B1+Y2B2YB = Y_1B_1 + Y_2B_2, so only one communication at the end of the block is needed.

Self-Attention block

  1. Pass the same input XX to all GPUs (ff).
  2. Split the Query, Key, and Value weights by columns, dividing the attention heads among the GPUs. The heads can be computed independently of each other, so no communication is needed here either.
  3. Multiply the attention output by the row-split output linear layer.
  4. Sum the results of each GPU with All-Reduce (gg) and apply Dropout.

ff and gg are paired operations. ff passes its input through unchanged in the forward pass and All-Reduces the gradient in the backward pass. gg All-Reduces in the forward pass and passes the gradient through unchanged in the backward pass. The paper shows that ff can be written in a few lines as a PyTorch autograd.Function (see the implementation example below).

The key point of Megatron-LM is to pair a column-split layer with a row-split layer. The output of the column-split layer can be fed, still split across GPUs, into the next row-split layer, so no communication is needed between the two matrix multiplications. In this way, all the matrix multiplications in one Transformer layer can be parallelized with two All-Reduces in the forward pass and two in the backward pass.

Techniques for reducing communication

The design of Megatron-LM aims to reduce communication between GPUs and keep the GPUs busy with computation. To that end, in addition to the two blocks above, it uses the following techniques.

PartHow it is splitPurpose
MLPFirst weight by columns, second weight by rowsEliminates communication between the two matrix multiplications
Self-AttentionHeads divided among GPUs, output linear layer split by rowsComputes the heads without communication
Input embeddingSplit along the vocabulary dimensionSplits the large vocabulary (tens of thousands) × hidden matrix
Output embedding and lossSplit along the vocabulary dimension, with each GPU computing up to the cross-entropyCommunicates only the loss (batch × sequence length) instead of the logits (batch × sequence length × vocabulary)
Layer Normalization, Dropout, residual connectionsNot split; all GPUs perform the same computationEliminates communication for distributing results

For the output embedding, gathering the logits for each GPU's share of the vocabulary to every GPU would mean sending batch size × sequence length × vocabulary size values. GPT-2's vocabulary is 50,257, so this is a very large amount. The paper reduced the amount sent by a factor of the vocabulary size by having each GPU proceed all the way through the loss computation before communicating.

For the weight update, too, each GPU handles only the weights it holds. Split weights exist only on their own GPU, and unsplit weights (such as Layer Normalization) have the same values on all GPUs, so there is no need to exchange updated weights.

Tensor parallelism can be combined with data parallelism. In the paper, GPUs within the same server (e.g., 8 GPUs) form a tensor-parallel group, and GPUs at the same position in each group form a data-parallel group. The 8.3B-parameter model used 8-way tensor parallelism × 64-way data parallelism = 512 GPUs.

Experimental results

The paper's experiments were run on up to 512 V100 GPUs (32GB). GPUs within the same server are connected at 300GB/s, and servers at 100GB/s. All models were trained with mixed precision training, using gradient checkpointing at every Transformer layer.

Efficiency as the number of GPUs grows: efficiency when the model is scaled up with the number of GPUs, relative to a 1.2B-parameter model that fits on one GPU (39 TFLOPS on one GPU, 30% of peak) (Table 1 and Figure 5 of the paper).

ParametersTensor-parallel GPUsEfficiencyTensor parallel × 64-way data parallel GPUsEfficiency
1.2B1100%6496%
2.5B295%12883%
4.2B482%25679%
8.3B877%51274%

With 512 GPUs, an overall throughput of 15.1 PFLOPS was sustained (the abstract gives the efficiency relative to the baseline as 76%).

Accuracy of large models: the 8.3B-parameter GPT-2-style model, evaluated without training on the target task (zero-shot), reached a WikiText103 perplexity of 10.81 (the previous best was 15.79) and a LAMBADA accuracy of 66.51% (previously 63.24%). The 3.9B-parameter BERT-style model reached 89.5% on the RACE reading-comprehension test (90.9% with an ensemble of 5 models), and both exceeded the previous best results.

When BERT-style models were scaled up, training with the original architecture became unstable. The paper shows that swapping the order of Layer Normalization and the residual connection (applying Layer Normalization to the input of each block) allows BERT models larger than BERT-Large (336M parameters) to be trained stably.

Practical considerations

Tensor parallelism performs All-Reduces at every layer, so it depends heavily on the speed of communication between GPUs. In the paper, tensor-parallel groups are formed from GPUs within the same server (connected at 300GB/s), and data parallelism is used across servers. Adding GPUs makes the computation per GPU smaller and increases the share of communication, so efficiency also drops (77% at 8 GPUs in the table above).

  • Choose a split count that divides the number of heads and the hidden size. Since the heads are divided among GPUs, the number of heads must be divisible by the tensor-parallel size. The paper also increases the vocabulary size from 50,257 to 51,200 so that each GPU's share is a multiple of 128.
  • Be careful with random numbers. Dropout appears both in parts that are not split and perform the same computation, such as before the residual connection, and in parts split per GPU, such as inside Self-Attention. Appendix B of the paper explains using the same random seed on all GPUs in the former case to get the same mask, and different random numbers per GPU in the latter.
  • Combine with other forms of parallelism. Tensor parallelism splits the inside of a single layer. For models with many layers, combine it with pipeline parallelism; when using many GPUs, combine it with data parallelism. The paper also notes that tensor parallelism is orthogonal to pipeline parallelism and can be combined with it.

Comparison with other forms of parallelism

Methods for splitting a large model across multiple GPUs differ in what they split, as follows.

MethodWhat is splitWhen communication happensIdle timeBest suited for
Tensor parallelism (Megatron-LM)Matrices within a single layerEvery layer (two All-Reduces forward and two backward per layer)Almost noneLarge individual layers; among GPUs with fast links
Pipeline parallelism (GPipe)Sequence of layersActivations and gradients sent at stage boundariesWaiting between stages (the bubble)Many layers; can span servers
ZeRO / FSDPWeights, gradients, and optimizer states (computation is data parallel)Weights gathered before computing each layerAlmost noneWhen only memory, not computation, should be split
Data parallelismData (mini-batches)Gradients averaged in the backward passNoneWhen the model fits on one GPU
  • Tensor parallelism suits cases where the matrices of a single layer are large and GPUs connected by fast links are available within the same server.
  • For models with many layers, or when splitting a model across servers, combine it with pipeline parallelism, which needs less communication.
  • If you do not want to rewrite the model code, ZeRO/FSDP are easier to adopt. Tensor parallelism requires deciding how to split each layer.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.distributed as dist

"""
Minimal implementation of the MLP block with tensor parallelism (Megatron-LM)
Follows Figure 3(a) and Code 1 of the paper. Run with one process per GPU, e.g. torchrun --nproc_per_node=2
"""

class CopyToParallel(torch.autograd.Function):
  """f: identity in the forward pass, All-Reduce the gradient in the backward pass (Code 1 of the paper)"""
  @staticmethod
  def forward(ctx, x):
    return x

  @staticmethod
  def backward(ctx, grad):
    grad = grad.clone()
    dist.all_reduce(grad)
    return grad


class ReduceFromParallel(torch.autograd.Function):
  """g: All-Reduce in the forward pass, identity in the backward pass"""
  @staticmethod
  def forward(ctx, x):
    x = x.clone()
    dist.all_reduce(x)
    return x

  @staticmethod
  def backward(ctx, grad):
    return grad


class ParallelMLP(nn.Module):
  """Y = GeLU(X A), Z = Dropout(Y B). Split A by columns and B by rows into world_size parts"""
  def __init__(self, hidden, ffn, dropout=0.1):
    super().__init__()
    world_size = dist.get_world_size()
    assert ffn % world_size == 0
    self.ffn_local = ffn // world_size
    # Each GPU holds only part of A's columns (hidden × ffn/N) and part of B's rows (ffn/N × hidden)
    self.A = nn.Linear(hidden, self.ffn_local)            # column-split A_i (the bias is split too)
    self.B = nn.Linear(self.ffn_local, hidden, bias=False)  # row-split B_i
    self.B_bias = nn.Parameter(torch.zeros(hidden))       # B's bias is added only once, after the sum
    self.dropout = nn.Dropout(dropout)

  def forward(self, x):
    x = CopyToParallel.apply(x)          # f
    y = F.gelu(self.A(x))                # GeLU(X A_i): computed without communication
    z = self.B(y)                        # Y_i B_i
    z = ReduceFromParallel.apply(z)      # g: sum Y_i B_i over all GPUs
    return self.dropout(z + self.B_bias)


if __name__ == '__main__':
  dist.init_process_group(backend='nccl' if torch.cuda.is_available() else 'gloo')
  rank = dist.get_rank()
  torch.manual_seed(0)                   # the input is the same on all GPUs
  x = torch.randn(4, 16, 1024)           # (batch, sequence length, hidden)
  torch.manual_seed(1 + rank)            # initialize the split weights differently on each GPU
  mlp = ParallelMLP(hidden=1024, ffn=4096)
  mlp.train()
  out = mlp(x)
  out.sum().backward()
  if rank == 0:
    print(out.shape)                     # torch.Size([4, 16, 1024]): the same output on all GPUs
  dist.destroy_process_group()

# Using PyTorch's built-in support (DTensor tensor parallelism):
# from torch.distributed.device_mesh import init_device_mesh
# from torch.distributed.tensor.parallel import parallelize_module, ColwiseParallel, RowwiseParallel
# tp_mesh = init_device_mesh('cuda', (2,))
# model = parallelize_module(model, tp_mesh, {'w1': ColwiseParallel(), 'w2': RowwiseParallel()})

FAQ

Q. How is tensor parallelism different from pipeline parallelism?
A.

Tensor parallelism splits the matrices inside a single layer, and all GPUs compute the same layer at the same time. Pipeline parallelism cuts the sequence of layers and assigns the pieces to GPUs, passing data along in order. Tensor parallelism needs communication at every layer, so it is used among GPUs with fast links; pipeline parallelism needs little communication, so it can also span servers. Large models combine both.

Q. Why is the first weight split by columns and the second by rows?
A.

Splitting the first by columns lets each GPU compute up to the GELU without communication. Splitting it by rows would require a sum before the GELU. The output remains split across the GPUs, so if the second weight is split by rows, it can be multiplied directly and summed only once at the end. This brings the communication of the MLP block down to one All-Reduce in the forward pass and one in the backward pass.

Q. How many GPUs can tensor parallelism scale to?
A.

The paper scaled up to 8 GPUs (the GPUs within one server), with 77% efficiency. The more GPUs, the smaller the computation per GPU and the larger the share of per-layer All-Reduces. To use more GPUs than that, combine it with data parallelism or pipeline parallelism. The paper's largest configuration was 8-way tensor parallelism × 64-way data parallelism = 512 GPUs.

References

  1. Shoeybi, M., Patwary, M., Puri, R., LeGresley, P., Casper, J., & Catanzaro, B. (2019). Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism. arXiv:1909.08053.
  2. PyTorch Documentation, "Tensor Parallelism - torch.distributed.tensor.parallel."