VerifiedarXiv:1909.0805334 min
Training · Systems

Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism

A transformer too big for one GPU trains anyway if each layer’s matrix multiplies are split across several GPUs.

Megatron-LM cuts the two weight matrices of each attention and MLP block in complementary directions, so the GPUs exchange data twice per layer in the forward pass and twice in the backward pass. With that change to an ordinary PyTorch model, NVIDIA trained an 8.3-billion-parameter GPT-2 on 512 GPUs.

Explaining the paperMegatron-LM: Training Multi-Billion Parameter Language Models Using Model ParallelismShoeybi, Patwary, Puri, LeGresley, Casper, Catanzaro · NVIDIA · 2019 · arXiv:1909.08053 ↗

In 2019 the largest GPU memory available was the 32 GB of an NVIDIA V100, and the training state of a language model with a few billion parameters no longer fit in it.

Megatron-LM is a paper about that one engineering problem. Adding GPUs the usual way does not reduce what each GPU has to hold, so the authors split the individual matrix multiplies inside every transformer layer across a small group of GPUs. The paper calls this intra-layer model parallelism; the field now calls it tensor parallelism. It needs no new compiler and no rewrite of the model, only a few communication calls added to a PyTorch transformer.

Every one of those calls is an all-reduce: each GPU in the group contributes a tensor of the same shape, and every GPU receives the elementwise sum. The design work is in placing the sums so there are as few as possible. The page follows the paper in order: the memory arithmetic that forces a split; the two ways to cut one matrix multiply, and why only one lets the nonlinearity run without communication; how pairing the two cuts gives a block with one all-reduce in each direction; the embedding and the loss; how the 512 GPUs are grouped; two changes that let the deep models converge; and the measured scaling and accuracy.

Why an 8.3-billion-parameter model does not fit on one GPU

Training with Adam in mixed precision keeps five numbers per parameter in memory for the whole run: the half-precision weight (2 bytes) and its gradient (2 bytes), a full-precision master copy of the weight that the optimizer updates (4 bytes), and Adam’s running averages of the gradient and of its square (4 bytes each). That is 16 bytes per parameter. The paper itself only says that optimizers like Adam need extra memory per parameter; the 16-byte accounting is standard practice, written out in the ZeRO paper.

For the 8.3-billion-parameter model that comes to 8.3 billion × 16 bytes ≈ 133 GB, four times a V100’s 32 GB. The optimizer’s share alone, the master copy and the two averages at 12 bytes per parameter, is about 100 GB. The 1.2B model needs about 19 GB and fits, which matches the paper’s statement that its 1.2B configuration trains on one GPU. Activations, the intermediate values the forward pass keeps for the backward pass, are separate and come on top. They can be traded for compute: activation checkpointing keeps only some of them and recomputes the rest during the backward pass, and the paper checkpoints after every transformer layer. The 16 bytes per parameter cannot be traded that way, since the weights, gradients and optimizer state are all used at every step.

Data parallelism, the default way to use more GPUs, gives every GPU a full copy of the model and a different slice of the batch, then averages the gradients. Every copy still needs all 133 GB, so more GPUs make training faster without making the model fit. The paper states the limitation directly: with data parallelism, the model must fit entirely on one worker. Getting under 32 GB requires each GPU to hold a fraction of the model. In Figure 1 the left bar is the whole model’s training state on one GPU and the right bar is one GPU’s share when the model is split tt ways. Drag the model size past 2 billion parameters.

Figure 1 · the memory wall
8.3B
The left bar is the training state of the whole model at 16 bytes per parameter on one 32 GB GPU; it crosses the line at about 2 billion parameters. The right bar is one GPU’s share with the model split tt ways, where tt is the smallest power of two that brings the share under 32 GB. At the paper’s sizes that rule reproduces its choices: 1.2B on 1 GPU, 2.5B on 2, 4.2B on 4, 8.3B on 8.

A model can be divided in two directions. Pipeline parallelism, as in GPipe, puts whole layers on different GPUs and passes activations from one to the next like stations on an assembly line. Each GPU sits idle while the batch’s first micro-batch reaches it and again after its last one leaves; these idle stretches are called pipeline bubbles. Intra-layer parallelism keeps every layer on every GPU of a group and splits each layer’s weight matrices, so all the GPUs work on the same layer at the same moment. Mesh-TensorFlow had already expressed intra-layer splits through its own language and a compiler that inserts the communication. Megatron writes the transformer-specific split by hand in PyTorch, and the paper describes it as orthogonal and complementary to pipelining: the two can be combined.

How tensor parallelism splits one matrix multiply

The MLP in each transformer layer starts with a matrix multiply (a GEMM, in GPU terminology) followed by GeLU, an activation function applied to each entry separately that multiplies an entry xx by Φ(x)\Phi(x), the standard normal CDF:

Y=GeLU(XA)Y = \text{GeLU}(XA)
(1)

XX has one row per token, b⋅sb \cdot s rows for a batch of bb sequences of ss tokens, and hh columns, the hidden size. AA is h×4hh \times 4h. To share this work between two GPUs, AA can be cut in half along its rows or along its columns.

Cut by rows. GPU 0 then holds the top rows of AA, which multiply only the left columns of XX, so XX is cut by columns to match:

X=[X1, X2],A=[A1A2]  ⟹  XA=X1A1+X2A2X = [X_1,\, X_2],\quad A = \begin{bmatrix} A_1 \\ A_2 \end{bmatrix} \;\Longrightarrow\; XA = X_1 A_1 + X_2 A_2X=[X1, X2],A=[A1A2]  ⟹  XA=X1A1+X2A2\begin{gathered} X = [X_1,\, X_2],\quad A = \begin{bmatrix} A_1 \\ A_2 \end{bmatrix} \\ \;\Longrightarrow\; XA = X_1 A_1 + X_2 A_2 \end{gathered}
(2)

Each GPU now holds a partial product with the full output shape, and the true product is their sum. GeLU is nonlinear, so it cannot be applied to the two pieces and the results added afterwards:

GeLU(X1A1+X2A2)  ≠  GeLU(X1A1)+GeLU(X2A2)\text{GeLU}(X_1 A_1 + X_2 A_2) \;\neq\; \text{GeLU}(X_1 A_1) + \text{GeLU}(X_2 A_2)GeLU(X1A1+X2A2)  ≠  GeLU(X1A1)+GeLU(X2A2)\begin{aligned} &\text{GeLU}(X_1 A_1 + X_2 A_2) \\ &\;\neq\; \text{GeLU}(X_1 A_1) + \text{GeLU}(X_2 A_2) \end{aligned}

Take one output entry where GPU 0’s partial is 1 and GPU 1’s is −1. Applying GeLU to each and adding gives 0.841 − 0.159 = 0.683, while the correct value is GeLU(0) = 0. With rows cut, the GPUs have to all-reduce the partial products before GeLU can run.

Cut by columns. XX stays whole on both GPUs, and each GPU computes complete output columns:

A=[A1, A2]  ⟹  [Y1, Y2]=[GeLU(XA1), GeLU(XA2)]A = [A_1,\, A_2] \;\Longrightarrow\; [Y_1,\, Y_2] = \big[\text{GeLU}(XA_1),\ \text{GeLU}(XA_2)\big]A=[A1, A2]  ⟹  [Y1, Y2]=[GeLU(XA1), GeLU(XA2)]\begin{gathered} A = [A_1,\, A_2] \;\Longrightarrow\; \\ [Y_1,\, Y_2] = \big[\text{GeLU}(XA_1),\ \text{GeLU}(XA_2)\big] \end{gathered}
(3)

Output column jj depends only on column jj of AA, so GPU 0’s columns are final after its own multiply, and GeLU applies to them with no communication. The output stays split: Y1Y_1 on GPU 0, Y2Y_2 on GPU 1. The paper uses this cut for the first GEMM because it removes a synchronization point. Toggle the two cuts in Figure 2 and watch where the all-reduce appears.

Figure 2 · column split vs row split
The GEMM of (1) followed by GeLU, on two GPUs. With AA split by columns, each GPU applies GeLU to its own output columns and nothing is sent. With AA split by rows, each GPU holds a partial sum, and an all-reduce has to add them before GeLU.

The MLP block: column split, then row split

After the column-parallel first GEMM, the GeLU output YY is divided by columns: with tt GPUs, GPU kk holds a bs×4h/tb s \times 4h/t slice YkY_k. The MLP’s second GEMM multiplies by BB, which is 4h×h4h \times h, to return to width hh. Cutting BB by rows into B1,…,BtB_1, \dots, B_t matches the slices already in place, by the same identity as (2) with YY in the role of XX:

Z=GeLU(XA) B=∑k=1tGeLU(XAk) BkZ = \text{GeLU}(XA)\,B = \sum_{k=1}^{t} \text{GeLU}(XA_k)\,B_k

GPU kk computes its term from data it already holds. Each term is a full-shape bs×hb s \times h partial output, and one all-reduce adds the tt terms; the paper places it right before the dropout that follows the MLP. Nothing crosses between GPUs between the two GEMMs, so the MLP costs one all-reduce in the forward pass. Splitting the second GEMM by columns too would need the full YY on every GPU first, an all-gather of bs⋅4hb s \cdot 4h values, four times the size of the all-reduce it replaces. As code, for GPU kk:

# MLP forward on GPU k of t (h = hidden size, A: h x 4h, B: 4h x h)
x   = f(x)                     # x: (b*s, h), same on every GPU
y_k = gelu(x @ A[:, cols_k])   # (b*s, 4h/t)  column-parallel, no communication
z_k = y_k @ B[cols_k, :]       # (b*s, h)     row-parallel: a partial sum
z   = g(z_k) + bias_B          # all-reduce, then add the bias once
z   = dropout(z) + x           # duplicated on every GPU

The bias of the first GEMM is split with its columns, so each GPU adds its own slice. The bias of the second GEMM is added once, after the all-reduce; added before it, the sum would contain it tt times. The official code does this in its row-parallel linear layer.

Figure 3 runs the MLP on numbers small enough to read: hidden size 4, one token, random 4×44 \times 4 matrices AA and BB. In the column-then-row mode each GPU prints its slice of xAxA, the GeLU of that slice, and its partial output; the all-reduced sum matches the unsplit result to within float rounding at every tt. The row-first mode prints the partial pre-activations instead, and how far the sum of their GeLUs lands from the GeLU of their sum.

Figure 3 · the split MLP, checked on numbers
A toy MLP, GeLU(xA) B\text{GeLU}(xA)\,B, with hidden size 4, split across tt GPUs. Column, then row is Megatron’s order: the partial outputs sum to the unsplit result. Row first, no sync applies GeLU to each partial and shows the gap. Press “new numbers” for new weights; t=1t = 1 is the unsplit baseline.

The f and g operators: four all-reduces per layer

The all-reduce after the second GEMM handles the forward pass. In the backward pass, gradients flow the other way. XX entered the block as a full copy on every GPU, and each GPU’s first GEMM used it, so each GPU can compute only its own share of the gradient with respect to XX, the part that flows back through its columns of AA. The true gradient is the sum of the shares:

∂L∂X=∑k=1t∂L∂(XAk) Ak⊤\frac{\partial L}{\partial X} = \sum_{k=1}^{t} \frac{\partial L}{\partial (XA_k)}\, A_k^{\top}

That sum is an all-reduce at the block’s input, in the backward pass. The gradient arriving at the block’s output is already identical on every GPU, because everything after the block (dropout, the residual add, the next layer norm) runs on identical copies, so the forward all-reduce needs no backward counterpart. The paper names the two operators:

They are conjugates, the same all-reduce in opposite passes, and both follow from the chain rule: a tensor copied to tt GPUs in the forward pass has its tt gradients summed in the backward pass, and for a sum in the forward pass, the gradient of each term in the backward pass equals the incoming gradient. Each is a short PyTorch autograd function:

# f and g run the SAME all-reduce, on opposite passes (paper, Code 1).
# Official code: copy_to_ / reduce_from_model_parallel_region (mpu/mappings.py).
class f(torch.autograd.Function):        # at the block input
    def forward(ctx, x):     return x                        # identity
    def backward(ctx, grad): all_reduce(grad); return grad   # sum

class g(torch.autograd.Function):        # at the block output
    def forward(ctx, x):     all_reduce(x); return x         # sum
    def backward(ctx, grad): return grad                     # identity

Self-attention has the same two-GEMM shape. Its first GEMM projects XX to queries, keys and values for every head, and heads are independent: head 3 computes its attention scores and weighted sum from its own query, key and value columns only. So the Q, K and V projections are split by columns along head boundaries, and each GPU receives whole heads, never part of one. With 24 heads and t=8t = 8, each GPU runs 3 heads from start to finish, including the softmax, which runs over sequence positions, a dimension that is not split. The output projection, which mixes the heads back to width hh, is split by rows, takes each GPU’s head outputs directly, and ends in its own gg.

Per transformer layer that makes two all-reduces in the forward pass (gg after attention, gg after the MLP) and two in the backward pass (an ff before each), four in total, whatever tt is. Figure 4 draws one lane per GPU for the trained 8.3B model (hidden size 3072, MLP width 12288, 24 heads) with each GPU’s shard printed in its lane. Switch between the forward and backward passes to see which operator sums, and drag tt down to 1, where neither operator has anything to do.

Figure 4 · the f and g operators
t = 8
One block of the 8.3B model split tt ways, one lane per GPU. Forward: the tt partial outputs meet at g and are summed, while f only copies the input. Backward: the partial input gradients meet at f, while g only copies the gradient. The footer shows what shrinks with tt and what does not.

The same shapes as a listing:

# 8.3B GPT-2 (Table 2): h = 3072, MLP width 4h = 12288, 24 heads of dim 128.
# Split t = 8 ways. Per GPU:
MLP   A    3072 x 12288 -> column split -> 3072 x 1536   (GeLU stays local)
      B   12288 x 3072  -> row split    -> 1536 x 3072   then g: all-reduce
Attn  QKV  3072 x 9216  -> column split -> 3072 x 1152   = 3 of the 24 heads
      out  3072 x 3072  -> row split    ->  384 x 3072   then g: all-reduce

The weights shrink with tt; the all-reduces do not. Each gg sums partial outputs of the full bs×hb s \times h shape. In the paper’s 8.3B run each model copy processes 8 sequences of 1024 tokens per step, so one all-reduce adds 8 × 1024 × 3072 = 25.2 million values, about 50 MB at two bytes each. A bandwidth-optimal all-reduce, such as the ring algorithm, has each GPU send and receive about 2(t−1)/t2(t-1)/t times the tensor size, 1.75 times at t=8t = 8. Each GPU’s matmul work, meanwhile, falls as 1/t1/t, so splitting a fixed model more ways raises the fraction of time spent communicating. The paper keeps every tensor-parallel group inside one server, where the GPUs are connected by NVSwitch at 300 GB/s; servers are linked at 100 GB/s.

Everything else in the layer is duplicated. Layer norm, dropout and the residual adds act on the full activation that every GPU holds after gg, and the paper computes them on every GPU rather than once with a broadcast. Each GPU keeps its own copy of the layer-norm parameters and updates only its own weight shards, so no parameter values are exchanged within the group. Duplicated dropout must drop the same entries on every GPU, or the copies of the residual stream would drift apart, so its random generator gets the same seed on every GPU. Dropout inside the split region, on each GPU’s own attention heads, should differ between GPUs, so it uses a second generator seeded differently per GPU (the code adds the GPU’s rank within the group to the seed).

Splitting the embedding and the cross-entropy loss

Outside the layers are the input embedding, which maps token ids to vectors, and the output layer, which maps each final vector to a score, a logit, for every token in the vocabulary. GPT-2 ties the two to one weight matrix EE of size h×vh \times v, with a vocabulary of vv = 50,257 tokens. Megatron splits EE along the vocabulary, so each GPU holds the vectors of a contiguous range of token ids.

On the input side, each GPU looks up the tokens that fall in its range and writes zeros for the rest. Every token belongs to exactly one range, so an all-reduce (a gg) of these bs×hb s \times h results gives every GPU the full embedding.

On the output side, the parallel GEMM [XE1,…,XEt][XE_1, \dots, XE_t] leaves each GPU with the logits for its own range. Gathering them in one place to compute the loss would move b×s×vb \times s \times v values: for 8,192 tokens and the padded vv = 51,200, that is 419 million values per step. The loss needs far less. For a token with target jj and logits zz, cross-entropy is

ℓ=−log⁡ezj∑i=1vezi=log⁡∑i=1vezi−m − (zj−m)\ell = -\log \frac{e^{z_j}}{\sum_{i=1}^{v} e^{z_i}} = \log \sum_{i=1}^{v} e^{z_i - m} \,-\, (z_j - m)ℓ=−log⁡ezj∑i=1vezi=log⁡∑i=1vezi−m − (zj−m)\begin{aligned} \ell &= -\log \frac{e^{z_j}}{\sum_{i=1}^{v} e^{z_i}} \\ &= \log \sum_{i=1}^{v} e^{z_i - m} \,-\, (z_j - m) \end{aligned}

where mm is the largest logit, subtracted so the exponentials cannot overflow. If GPU kk owns the vocabulary range VkV_k, its local maximum is mkm_k and its local sum of exponentials is SkS_k, and the loss regroups exactly:

Sk=∑i∈Vkezi−m,m=max⁡kmk,S=∑k=1tSk,ℓ=log⁡S−(zj−m)S_k = \sum_{i \in V_k} e^{z_i - m}, \qquad m = \max_{k} m_k, \qquad S = \sum_{k=1}^{t} S_k, \qquad \ell = \log S - (z_j - m)Sk=∑i∈Vkezi−m,m=max⁡kmk,S=∑k=1tSk,ℓ=log⁡S−(zj−m)\begin{gathered} S_k = \sum_{i \in V_k} e^{z_i - m}, \qquad m = \max_{k} m_k, \\ S = \sum_{k=1}^{t} S_k, \qquad \ell = \log S - (z_j - m) \end{gathered}

Each quantity is one number per token, built from one number per GPU. The official code computes the loss with three all-reduces of b×sb \times s values each: a MAX for mm, a SUM for the target logit (the GPU whose range contains jj contributes zj−mz_j - m, the others contribute 0), and a SUM for SS. Every GPU then holds the exact loss for every token, since the max and the sums were only regrouped. The backward pass of the loss needs no communication, because the gradient with respect to the logits, the softmax minus one at the target, uses only mm, SS and each GPU’s own logits. The paper summarizes the saving as reducing the communicated dimension from b×s×vb \times s \times v to b×sb \times s; counting the three reductions, the fused loss sends v/3v/3 fewer values, about 17,000 times fewer at vv = 51,200. Step through the three all-reduces for one token in Figure 5.

Figure 5 · fused parallel cross-entropy
51K
Top: one token’s 16 logits on 4 GPUs, target outlined. The three steps are the three all-reduces of the fused loss; at step 3 the fused loss is printed above the loss computed from gathered logits. Bottom: values sent for 8,192 tokens, gathering the logits (b⋅s⋅vb \cdot s \cdot v) against the fused loss (3⋅b⋅s3 \cdot b \cdot s), on a log scale. Drag the vocabulary.

The vocabulary is padded from 50,257 to 51,200, which is divisible by 128 × 8 = 1024, so at t=8t = 8 each GPU holds 6,400 tokens, a multiple of 128. The paper pads for efficient logit GEMMs, and it holds the hidden size per attention head fixed at 96 across its scaling study for the same reason, consistent GEMM sizes.

Adding data parallelism: how 512 GPUs are grouped

Tensor parallelism makes the model fit; data parallelism adds throughput on top. The 8.3B run uses both: 8-way tensor parallelism within each model copy and 64 copies, 512 V100s in 32 DGX-2H servers of 16 GPUs each. Appendix B of the paper gives the grouping. A model-parallel group is 8 GPUs inside one server, and GPUs 1 to 8 hold one copy of the model. The GPUs at the same position in every copy form a data-parallel group, for example GPUs 1, 9, 17, …, 505. They hold the same weight shard, process different sequences, and after the backward pass all-reduce that shard’s gradients. There are 8 such groups of 64 GPUs, and their 8 gradient all-reduces run at the same time.

With t=8t = 8, each GPU’s shard is about an eighth of the 8.3 billion weights, so each data-parallel all-reduce sums about a billion gradient values across 64 GPUs once per step. The activation all-reduces of ff and gg are smaller (25.2 million values each) and far more frequent, and they stay on the NVSwitch links inside a server; the data-parallel groups span servers. In Figure 6, click any GPU to see its two groups, and drag tt to regroup the same 512 GPUs.

Figure 6 · model-parallel and data-parallel groups
t = 8
32 servers of 16 GPUs, numbered as in the paper’s Figure 8. The selected GPU’s model-parallel group is tt consecutive GPUs in one server holding one copy of the model; its data-parallel group is every GPU holding the same shard. At t=1t = 1 nothing is split and all 512 GPUs form one data-parallel group, which only works for a model that fits on one GPU.

Making deep models converge: layer norm placement and residual scaling

Fitting a model does not make it train well. Lan et al., in the ALBERT paper, had found that growing BERT past BERT-Large (336M parameters) made it worse: their 1.3B BERT-xlarge scored below BERT-Large. Megatron reports that changing the order of layer normalization and the residual connection removes this degradation.

post-LN: xℓ+1=LN(xℓ+F(xℓ))pre-LN: xℓ+1=xℓ+F(LN(xℓ))\text{post-LN: } x_{\ell+1} = \text{LN}\big(x_\ell + F(x_\ell)\big) \qquad \text{pre-LN: } x_{\ell+1} = x_\ell + F\big(\text{LN}(x_\ell)\big)post-LN: xℓ+1=LN(xℓ+F(xℓ))pre-LN: xℓ+1=xℓ+F(LN(xℓ))\begin{gathered} \text{post-LN: } x_{\ell+1} = \text{LN}\big(x_\ell + F(x_\ell)\big) \\ \text{pre-LN: } x_{\ell+1} = x_\ell + F\big(\text{LN}(x_\ell)\big) \end{gathered}

Here FF is a sublayer, attention or the MLP. The original BERT block, post-LN, normalizes after the residual add, so the residual stream itself is renormalized after every sublayer. The rearranged block, pre-LN, normalizes only the sublayer’s input, and the path from one block to the next is a plain addition. The official code also adds a final layer norm after the last block, before the output head, so the change is more than moving one line. Unrolling the pre-LN additions over LL sublayers gives

xL=x0+∑ℓ=0L−1F(LN(xℓ))x_L = x_0 + \sum_{\ell=0}^{L-1} F\big(\text{LN}(x_\ell)\big)

so the gradient with respect to any earlier xℓx_\ell contains an identity term carried straight back from the top, while in post-LN every layer norm on the stream sits on that path and rescales the gradient passing through it.

The names post-LN and pre-LN, and the gradient analysis, come from Xiong et al., published in 2020 after Megatron. They prove that at initialization post-LN’s gradients near the output layer are large, which is why post-LN needs a learning-rate warm-up, and that pre-LN’s are well-behaved. Megatron claims only to be the first to report that the change enables larger BERT models. In its experiments the rearranged model trains without the instabilities of the original and reaches a lower training loss, and accuracy on every downstream task improves monotonically from 336M to 1.3B to 3.9B parameters.

Figure 7 · where the layer norm sits
The original post-LN block normalizes the sum, so a layer norm sits on the residual stream and rescales it after every sublayer. The rearranged pre-LN block normalizes only the sublayer’s input and leaves the skip connection a plain addition.

The second change is in the initialization. All weights start from a normal distribution with standard deviation 0.02, and the layers that write into the residual stream (the output projection of attention and the second GEMM of the MLP) are scaled down further by 1/2N1/\sqrt{2N}, where NN is the number of transformer layers:

σout=0.022N\sigma_{\text{out}} = \frac{0.02}{\sqrt{2N}}

Each layer adds two contributions to the residual stream, so after NN layers the stream is the input plus 2N2N terms. If the terms are roughly independent their variances add, and the added variance grows like 2N2N; dividing each term’s standard deviation by 2N\sqrt{2N} cancels that growth. For the 72-layer 8.3B model, 2N2N = 144, so the output projections start at 0.02 / 12 ≈ 0.0017. GPT-2 writes the same scale as 1/N1/\sqrt{N} with NN counting residual layers, two per transformer layer, which is the same number.

The rest of the recipe is standard for the time. The optimizer is Adam with decoupled weight decay 0.01, global gradient-norm clipping at 1.0, dropout 0.1, and mixed precision with dynamic loss scaling. The GPT-2 models train on 1024-token sequences at a batch size of 512 for 300,000 iterations, with a learning rate of 1.5e-4 warmed up over 3,000 iterations and cosine-decayed to 1e-5. The BERT models use the original 30,522-token vocabulary, a batch of 1024, a learning rate of 1e-4 warmed up over 10,000 iterations and decayed linearly over 2 million, and ALBERT’s sentence-order prediction in place of next-sentence prediction, with the whole-word n-gram masking of Joshi et al. (2019). All of it trains on a 174 GB deduplicated corpus built from Wikipedia, CC-Stories, RealNews and OpenWebText, plus BooksCorpus for BERT only, since it overlaps the LAMBADA test.

How well it scales

The scaling study uses weak scaling: the model grows with the number of GPUs, which matches the goal of training models that did not fit before. Its four GPT-2 configurations keep 96 hidden units per head: 1.2B on 1 GPU (hidden 1536, 16 heads, 40 layers), 2.5B on 2 (1920, 20, 54), 4.2B on 4 (2304, 24, 64) and 8.3B on 8 (3072, 32, 72). The baseline is the 1.2B model on one V100, which sustains 39 TeraFLOPs, 30% of the GPU’s theoretical peak. The paper calls it a strong baseline because the 39 TeraFLOPs are measured over the whole training process, not only the matrix multiplies.

Three efficiency numbers come out of the study, each against a different baseline. With tensor parallelism alone, the 8.3B model on 8 GPUs keeps 77% of linear scaling: the 8 GPUs together sustain 77% of 8 times the baseline’s FLOP rate. Adding 64-way data parallelism to reach 512 GPUs, at a global batch of 512, keeps 74%; the drop comes from the extra gradient communication. And the whole 512-GPU run sustains 15.1 PetaFLOPs, which is 76% of 512 × 39 TeraFLOPs = 19.97 PetaFLOPs.

Figure 8 has two more views. In strong scaling the model stays fixed at 1.2B and the GPUs are added only for speed, with a fixed batch of 8: speedups of 1.64, 2.34 and 2.98 on 2, 4 and 8 GPUs, against an ideal of 2, 4 and 8. The paper attributes the falloff to the shrinking per-GPU computation, as memory bandwidth and communication begin to dominate, the effect described in the f and g section. The attention-heads view holds the 8.3B model and 8-way split fixed and varies the heads: 16, 24 and 32 heads give 82%, 80% and 77%, because more heads means smaller GEMMs inside self-attention and more softmax elements. The trained 8.3B model uses 24 heads, the 80% setting; the 77% headline is the 32-head scaling configuration.

Figure 8 · scaling efficiency
Weak scaling: 77% of linear with 8-way tensor parallelism, 74% across 512 GPUs with data parallelism added. Strong scaling: on a fixed 1.2B model the speedup falls below the ideal diagonal as GPUs are added. Attention heads: more heads, lower efficiency. All values are from the paper’s tables.

Results: an 8.3B GPT-2 and a 3.9B BERT

The trained GPT-2 models are 355M (24 layers, hidden 1024, 16 heads), 2.5B (54, 1920, 20) and 8.3B (72, 3072, 24), on 64, 128 and 512 GPUs, at 0.86, 2.27 and 2.10 days per epoch. One epoch of the corpus is 68,507 iterations, so at its rate the 8.3B model's 300,000 iterations take about nine days. Its validation perplexity on a held-out part of the training corpus reaches 9.27.

Zero-shot, the 8.3B model reaches a WikiText103 test perplexity of 10.81, against a prior best of 15.79, and 66.51% accuracy on LAMBADA, which asks the model to predict the last word of a passage, against a prior 63.24%. Perplexity is the exponential of the average per-token loss, and lower means the model assigns more probability to the held-out text. WikiText103 is scored per word, so the paper sums the loss over its own subword tokens and divides by the number of original word-level tokens ToT_o:

PPL=exp⁡(−1To∑t=1Tlog⁡P(t∣0:t−1))\text{PPL} = \exp\Big(-\frac{1}{T_o}\sum_{t=1}^{T} \log P(t \mid 0{:}t-1)\Big)
(4)

The smaller models follow the same trend: 355M scores 19.31 and 45.18%, 2.5B scores 12.76 and 61.73%. To check for leakage, the paper measures the share of test 8-grams that also appear in its training data: at most 10.8% for WikiText103 and 1.4% for LAMBADA.

The rearranged BERT models are 336M (24 layers, hidden 1024, 16 heads), 1.3B (24, 2048, 32) and 3.9B (48, 2560, 40), with 64 hidden units per head. On RACE, a reading-comprehension test, the 3.9B model scores 89.5% as a single model and 90.9% as a five-model ensemble, past the ALBERT ensemble’s 89.4%. On the development sets it reaches 91.4 on MNLI (natural-language inference), 92.7 on QQP (duplicate-question detection), 95.5/90.0 (F1 / exact match) on SQuAD 1.1 and 91.2/88.5 on SQuAD 2.0 (question answering), each above the 1.3B and 336M models. Switch between the metrics in Figure 9.

Figure 9 · accuracy against model size
Quality against model size, with the prior state of the art as a dashed line. GPT-2 WikiText103 perplexity falls to 10.81 and LAMBADA accuracy rises to 66.51%; BERT RACE accuracy reaches 89.5% single and 90.9% ensemble. Teal bars beat the prior best.

Turing-NLG, a 17B model from Microsoft, was trained with tensor slicing on the Megatron-LM framework. GPT-3 used model parallelism within each matrix multiply together with parallelism across layers, and cites this paper. Megatron-Turing NLG, at 530B, combined Megatron’s tensor slicing with DeepSpeed’s pipeline and data parallelism into 3D parallelism. The direct follow-up from the same group, Reducing Activation Recomputation (2022), adds sequence parallelism and selective recomputation on top of tensor parallelism to cut the activation memory this paper left to checkpointing.

Provenance Verified against primary literatureHow we verify
Vaswani et al. (2017)The transformer layer: self-attention with independent heads, then a two-GEMM MLP. Megatron splits both.
Shazeer et al. (2018), Mesh-TensorFlowIntra-layer splitting of tensor computations through a dedicated language and compiler. Megatron writes the transformer-specific split by hand in native PyTorch.
Huang et al. (2018), GPipePipeline (across-layer) model parallelism, which suffers pipeline bubbles. The paper calls its own method orthogonal and complementary to it.
Chen et al. (2016)Activation checkpointing. Megatron checkpoints after every transformer layer.
Micikevicius et al. (2017); NVIDIA (2018)Mixed-precision training with an fp32 master copy; dynamic loss scaling. Used as is.
Radford et al. (2019), GPT-2The model family, and the residual-layer init scale 1/sqrt(N) with N residual layers, which equals Megatron's 1/sqrt(2N) with N transformer layers.
Lan et al. (2019), ALBERTReported that BERT degrades past BERT-Large (336M). Megatron's BERT training recipe largely follows it (sentence-order prediction).
Xiong et al. (2020)Named the two orderings post-LN and pre-LN and analyzed their gradients at initialization. Published after Megatron; Megatron does not cite it.
Rajbhandari et al. (2019), ZeROWrites out the 16 bytes per parameter of mixed-precision Adam that this page uses. The Megatron paper is only qualitative about optimizer memory.
Official code, NVIDIA/Megatron-LM v1.0mpu/mappings.py:79-100 (f and g); mpu/layers.py:124-137 (masked embedding lookup, then all-reduce) and :328-332 (row-parallel bias added after the all-reduce); mpu/cross_entropy.py:31-76 (three all-reduces: MAX, then two SUMs); mpu/random.py:165-167 (per-rank dropout seed = seed + 2718 + rank); model/transformer.py:372-373 (final layer norm); model/utils.py:33-35 (std / sqrt(2 * num_layers)).
caveatTwo scope notes. (1) The paper reports 77%, 74% and 76% scaling efficiency, and they are three different sustained measurements, not one number rounded and not a peak-versus-sustained comparison: 77% is 8-way tensor parallelism alone on the 32-head 8.3B configuration, 74% is the combined 512-GPU run (8-way model times 64-way data), and 76% is 15.1 PetaFLOPs divided by 512 times the 39 TeraFLOPs of the single-GPU baseline. (2) The paper says the fused cross-entropy "reduces the dimension to b × s" by "communicating scalar losses instead of logits". The official v1.0 code communicates three per-token scalars (the max logit, the target logit, the sum of exponentials) in three all-reduces of b × s values each, so the saving over gathering the logits is a factor of v/3 (about 17,000 at v = 51,200), not v. The loss is exact either way.

Questions you might still have

?

Is tensor parallelism the same as pipeline parallelism?
No. Pipeline parallelism puts whole layers on different GPUs and passes activations down the line, which leaves some GPUs idle at the start and end of each batch (pipeline bubbles). Tensor parallelism, this paper, keeps every layer on every GPU of a group and splits the weight matrices inside it. The two compose: Megatron-Turing NLG (530B) used Megatron tensor slicing with DeepSpeed pipeline and data parallelism.

?

Why not split both GEMMs of the MLP by columns?
The second GEMM would then need the full GeLU output on every GPU, so the t column slices of width 4h/t would first have to be all-gathered (b·s·4h values, four times the size of the all-reduce Megatron uses), and its output would again be split by columns. Column then row is the only order with no communication between the two GEMMs and a single all-reduce after them.

?

Does fusing the loss into the output GEMM change the answer?
No. Cross-entropy needs the largest logit, the target logit and the sum of exponentials, and each of those is a max or a sum over the vocabulary that can be taken per GPU and then combined with one all-reduce. The official code does exactly three such all-reduces of one number per token. The backward pass needs no communication at all, because the gradient with respect to the logits is the softmax minus one at the target.

?

Why does each all-reduce stay the same size as t grows?
g sums partial outputs that each have the full b·s × h shape, because each GPU's row-parallel GEMM produces a contribution to every output entry. Only the weights are divided by t. With 8 sequences of 1024 tokens at h = 3072 that is 25.2 million values per all-reduce at every t, while each GPU's matmul work falls as 1/t, so communication takes a growing share of the time.

?

Why do more attention heads lower the efficiency?
At a fixed hidden size, more heads means a smaller dimension per head, so the per-head GEMMs inside self-attention get smaller and the softmax has more elements. On the 8.3B model with 8-way splitting the paper measures 82%, 80% and 77% of linear scaling at 16, 24 and 32 heads.

?

Can a 7B model be trained with data parallelism alone?
Not on 32 GB GPUs with mixed-precision Adam: 7 billion parameters at 16 bytes each is 112 GB per copy, and every data-parallel copy holds all of it. Splitting the model (tensor or pipeline parallelism) or sharding the optimizer state across data-parallel GPUs, as ZeRO does, is required.

?

Did Megatron invent tensor parallelism?
It made the transformer version practical. Mesh-TensorFlow could already express intra-layer splits, through a compiler. The residual init scale came from GPT-2, activation checkpointing from Chen et al., mixed precision from Micikevicius et al. Megatron's contribution is the column-then-row arrangement for attention and the MLP, the vocabulary-parallel embedding and loss, all written as a few communication calls in PyTorch. The paper calls it intra-layer model parallelism; tensor parallelism is the later name.

Footnotes & further reading

  1. The paper: Shoeybi, Patwary, Puri, LeGresley, Casper, Catanzaro, Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism (NVIDIA, 2019). Official code: NVIDIA/Megatron-LM at v1.0.
  2. The transformer the splits operate on: Vaswani et al., Attention Is All You Need (2017).
  3. Earlier model parallelism: Shazeer et al., Mesh-TensorFlow (2018), and the pipeline approach, Huang et al., GPipe (2018).
  4. The memory levers: Chen et al., activation checkpointing (2016); Micikevicius et al., mixed-precision training (2017); the 16-bytes-per-parameter accounting in Rajbhandari et al., ZeRO (2019).
  5. The ring all-reduce and its 2(t−1)/t2(t-1)/t traffic per GPU: Patarasuk and Yuan, Bandwidth optimal all-reduce algorithms for clusters of workstations (2009).
  6. Layer-norm placement: Ba et al., Layer Normalization (2016); Xiong et al., On Layer Normalization in the Transformer Architecture (2020); and the BERT degradation result, Lan et al., ALBERT (2019).
  7. Where it went next: BERT and GPT-3; Megatron-Turing NLG 530B (2022); and Korthikanti et al., Reducing Activation Recomputation in Large Transformer Models (2022).