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 ParallelismIn 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 ways. Drag the model size past 2 billion parameters.
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 by , the standard normal CDF:
has one row per token, rows for a batch of sequences of tokens, and columns, the hidden size. is . To share this work between two GPUs, can be cut in half along its rows or along its columns.
Cut by rows. GPU 0 then holds the top rows of , which multiply only the left columns of , so is cut by columns to match:
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:
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. stays whole on both GPUs, and each GPU computes complete output columns:
Output column depends only on column of , so GPU 0’s columns are final after its own multiply, and GeLU applies to them with no communication. The output stays split: on GPU 0, 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.
The MLP block: column split, then row split
After the column-parallel first GEMM, the GeLU output is divided by columns: with GPUs, GPU holds a slice . The MLP’s second GEMM multiplies by , which is , to return to width . Cutting by rows into matches the slices already in place, by the same identity as (2) with in the role of :
GPU computes its term from data it already holds. Each term is a full-shape partial output, and one all-reduce adds the 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 on every GPU first, an all-gather of values, four times the size of the all-reduce it replaces. As code, for GPU :
# 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 GPUThe 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 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 matrices and . In the column-then-row mode each GPU prints its slice of , the GeLU of that slice, and its partial output; the all-reduced sum matches the unsplit result to within float rounding at every . 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.
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. 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 , the part that flows back through its columns of . The true gradient is the sum of the shares:
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:
- , at the block input: identity in the forward pass, all-reduce in the backward pass.
- , at the block output: all-reduce in the forward pass, identity in the backward pass.
They are conjugates, the same all-reduce in opposite passes, and both follow from the chain rule: a tensor copied to GPUs in the forward pass has its 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 # identitySelf-attention has the same two-GEMM shape. Its first GEMM projects 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 , 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 , is split by rows, takes each GPU’s head outputs directly, and ends in its own .
Per transformer layer that makes two all-reduces in the forward pass ( after attention, after the MLP) and two in the backward pass (an before each), four in total, whatever 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 down to 1, where neither operator has anything to do.
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-reduceThe weights shrink with ; the all-reduces do not. Each sums partial outputs of the full 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 times the tensor size, 1.75 times at . Each GPU’s matmul work, meanwhile, falls as , 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 , 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 of size , with a vocabulary of = 50,257 tokens. Megatron splits 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 ) of these results gives every GPU the full embedding.
On the output side, the parallel GEMM leaves each GPU with the logits for its own range. Gathering them in one place to compute the loss would move values: for 8,192 tokens and the padded = 51,200, that is 419 million values per step. The loss needs far less. For a token with target and logits , cross-entropy is
where is the largest logit, subtracted so the exponentials cannot overflow. If GPU owns the vocabulary range , its local maximum is and its local sum of exponentials is , and the loss regroups exactly:
Each quantity is one number per token, built from one number per GPU. The official code computes the loss with three all-reduces of values each: a MAX for , a SUM for the target logit (the GPU whose range contains contributes , the others contribute 0), and a SUM for . 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 , and each GPU’s own logits. The paper summarizes the saving as reducing the communicated dimension from to ; counting the three reductions, the fused loss sends fewer values, about 17,000 times fewer at = 51,200. Step through the three all-reduces for one token in Figure 5.
The vocabulary is padded from 50,257 to 51,200, which is divisible by 128 × 8 = 1024, so at 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 , 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 and 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 to regroup the same 512 GPUs.
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.
Here 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 sublayers gives
so the gradient with respect to any earlier 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.
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 , where is the number of transformer layers:
Each layer adds two contributions to the residual stream, so after layers the stream is the input plus terms. If the terms are roughly independent their variances add, and the added variance grows like ; dividing each term’s standard deviation by cancels that growth. For the 72-layer 8.3B model, = 144, so the output projections start at 0.02 / 12 ≈ 0.0017. GPT-2 writes the same scale as with 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.
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 :
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.
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.
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
- 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.
- The transformer the splits operate on: Vaswani et al., Attention Is All You Need (2017).
- Earlier model parallelism: Shazeer et al., Mesh-TensorFlow (2018), and the pipeline approach, Huang et al., GPipe (2018).
- 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).
- The ring all-reduce and its traffic per GPU: Patarasuk and Yuan, Bandwidth optimal all-reduce algorithms for clusters of workstations (2009).
- 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).
- 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).
How could this explainer be improved? Found an error, or something unclear? I read every message.