AI State of the Art
SOTA/Training: Modern Training Techniques/32 min
Section 93

Megatron-LM: Massive Training at NVIDIA

Listen as a podcast →

The problem: at some point, splitting the batch stops being enough

A 7-billion-parameter model already occupies 84 GB before the first activation, the arithmetic is laid out in ZeRO. At 175 billion you are around 2,100 GB for the model states alone. No amount of batch splitting fixes that: you have to split the model itself.

There are three ways to do it, and Megatron-LM, NVIDIA's distributed training framework, is the software that combines all three.

Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism (Shoeybi et al., 2019) Efficient Large-Scale Language Model Training on GPU Clusters Using Megatron-LM (Narayanan et al., 2021)

The three splits, and what each one communicates

Every parallelism scheme reduces to two questions: what does it split, and what must it then send, and when. Here are the three answers side by side.

ParallelismWhat it splitsWhat travels, and whenVolume
DP, Data Parallelismthe batch: each card sees different examplesone gradient all-reduce, once per training step, at the end of the backward passthe size of the model
PP, Pipeline Parallelismthe layer: cards divide the layers in sequencethe activations at a single boundary, sent from one card to the nextone slice of activations, point to point
TP, Tensor Parallelismthe weight tensor: one single matrix is cut across cardsan all-reduce of partial results, in the middle of every block, at every layeractivations, four times per layer

The contrast between the first row and the last is the whole subject of this page. These collective operations (all-reduce, all-gather, reduce-scatter) are explained in detail in FSDP; they are provided by NCCL (NVIDIA Collective Communications Library).

Tensor parallelism: cutting a matrix in half

This is Megatron's own split, and the most demanding one. Take the feed-forward network of a transformer block. It chains two matrix multiplications (GEMMs, GEneral Matrix Multiply) separated by a non-linearity:

Y=GeLU(XA)⋅BY = \text{GeLU}(X A) \cdot B

where XX is the input activation (computed on the text at hand), and AA and BB are two learned weight matrices, frozen once training is over. We want AA and BB spread across two cards.

Why the naive split costs two communications

Cut AA into two blocks of rows. Each card then computes part of the sum that makes up XAXA: neither of them holds the result, and their two partial results must be added to obtain XAXA. But GeLU is applied elementwise to XAXA, and it cannot be applied to a partial sum, since GeLU(a+b)≠GeLU(a)+GeLU(b)\text{GeLU}(a+b) \neq \text{GeLU}(a) + \text{GeLU}(b). So you must communicate before GeLU. Then, after the second matrix, communicate again. Two exchanges per block.

Megatron's trick: a single communication

Cut AA into columns instead: A=[A1,A2]A = [A_1, A_2]. Card 1 computes XA1XA_1, card 2 computes XA2XA_2. These are no longer partial sums but complete columns of the result. Each card can therefore apply GeLU on its own, exchanging nothing.

Then cut BB into rows: B=[B1;B2]B = [B_1 ; B_2]. Card 1 holds exactly the columns of GeLU(XA)\text{GeLU}(XA) that must meet the rows B1B_1. It computes GeLU(XA1)B1\text{GeLU}(XA_1) B_1, its neighbour computes GeLU(XA2)B2\text{GeLU}(XA_2) B_2, and the answer we want is the sum of the two. A single all-reduce, at the block's output.

Y=GeLU(XA1)B1⏟card 1+GeLU(XA2)B2⏟card 2Y = \underbrace{\text{GeLU}(XA_1)B_1}_{\text{card 1}} + \underbrace{\text{GeLU}(XA_2)B_2}_{\text{card 2}}

Figure from the Megatron-LM paper showing how matrices are split across two GPUs. Left, the MLP block: input X is duplicated on both GPUs by an operator f annotated identity, each GPU computes X times its half of the first matrix A, written A1 and A2 split column-wise, applies GeLU, then multiplies by its half of the second matrix B, written B1 and B2 stacked row-wise; an operator g annotated allreduce recombines the two partial results before dropout. Right, the self-attention block follows the same pattern, with attention heads divided between the two GPUs: Q, K and V are split into Q1 Q2, K1 K2, V1 V2, each GPU computes its own softmax and dropout independently, then an allreduce recombines the output.
The heart of the trick. The first matrix A is cut column-wise (A1, A2), so each card can apply GeLU to its own share without exchanging anything. The second matrix B is cut row-wise (B1, B2), so the two halves recombine as a plain addition. One all-reduce, marked in red, at each block's output instead of two.Source : Megatron-LM paper (Shoeybi et al., figure 3), via Yue Shui's blog

The attention block follows the same logic, with an even more natural split: attention heads are independent, so each card gets half of them. The weight matrices WQW_Q, WKW_K, WVW_V are cut column-wise head by head; each card computes its own QQ, KK, VV and its own softmax without asking anyone. The output projection matrix is cut row-wise, and an all-reduce recombines.

Counting the communications

The paper is explicit: the column-then-row split lets you run every multiplication in a transformer block with two all-reduces in the forward pass and two in the backward pass, that is four per layer per training step. One per block (attention and feed-forward) in each direction.

Where exactly? The paper introduces two conjugate operators:

  • gg, at each block's output: all-reduce in the forward pass, nothing in the backward. This is the one that sums the partial results.
  • ff, at each block's input: nothing in the forward pass, all-reduce in the backward. This is the one that recombines the gradient flowing back toward the input.
Why TP demands a very fast network and DP does not

It is not about volume, it is about where in the computation it sits.

The DP all-reduce carries gradients, whose size is the size of the model, and it happens once, at the end of the backward pass. You can fire it as soon as the first gradients are ready, while later layers are still computing: the communication slips underneath the computation and becomes nearly free in wall-clock time.

The TP all-reduce is in the middle of the computation. Nothing can proceed until it finishes, because the card needs the block's complete result to start the next block. It sits on the critical path, it cannot be hidden, and it happens four times per layer. On an 80-layer model that is 320 synchronised stops per training step. On top of that, what travels is activations: their size grows with batch size and sequence length, unlike gradients.

Hence the engineering rule: TP stays confined inside a single machine, on the NVLink connection between neighbouring cards (on the order of 900 gigabytes per second), and never crosses between machines, where InfiniBand tops out at 400 gigabits per second, that is 50 gigabytes per second, roughly eighteen times less, not twice as a careless reading of the two figures would suggest. Watch the unit: network links are advertised in bits per second, internal buses in bytes per second. See Scaling infrastructure.

TP is covered in depth in Tensor Parallelism, PP in Pipeline Parallelism.

3D parallelism: arranging cards in a grid

Megatron places every card at a coordinate in a three-dimensional grid:

identifier=(TP rank, PP rank, DP rank)\text{identifier} = (\text{TP rank},\ \text{PP rank},\ \text{DP rank})

Three numbers, one per kind of split. The total card count is the product of the three sizes. An illustrative configuration for 1,024 cards spread over 128 eight-card machines:

  • TP = 8: the eight cards of one machine divide every matrix, over the fast internal link.
  • PP = 16: sixteen machines in series divide the model's layers.
  • DP = 8: the complete pipeline, which therefore occupies 128 cards, is replicated eight times to process eight different batches.
  • Total: 8×16×8=1,0248 \times 16 \times 8 = 1{,}024.
3D parallelism diagram. Two stacked blocks, Data Parallel Rank 0 and Data Parallel Rank 1, each contain four pipeline stages in series (Pipeline Stage 0 to 3) which divide the network's layers: layers 0 to 7, 8 to 15, 16 to 23, 24 to 31. Within each stage, the groups of layers are themselves cut into four coloured slices labelled MP-0 to MP-3, corresponding to tensor parallelism. Horizontal arrows connect successive pipeline stages and vertical arrows labelled ZeRO connect the two data replicas.
All three dimensions at once. Top to bottom, the data replicas; left to right, the pipeline stages dividing the layers; and within each stage, the coloured slices that cut one single layer across several cards, which is tensor parallelism. Every card occupies exactly one cell of this grid.Source : DeepSpeed documentation (Microsoft)
Why three dimensions and not two?

The order of the three is not arbitrary: it follows the ranking of the links, fastest to slowest.

TP is the chattiest and least hideable, so it gets the best link: the eight cards inside one machine. PP only exchanges the activations at one boundary between two stages, from one card to exactly one other (a point-to-point send, not a collective) so it tolerates the inter-machine link. DP is the least demanding, one exchange per step that can be hidden, so it gets whatever is left.

Without PP, each replica would have to fit on a single eight-card machine, and a 175-billion-parameter model would not fit. PP is what lets you spread a model over several machines without ever pushing a TP all-reduce onto the slow network.

The optimisations that matter

Sequence parallelism, alongside TP

TP splits the matrices but leaves untouched the operations that are not matrix multiplications: normalisations and dropout. Those are therefore replicated identically across the cards of a TP group, and their activations occupy the same memory on each. Pure redundancy.

Sequence parallelism splits them along sequence length: for those operations, each card in the TP group handles only a slice of tokens. The communication cost is zero, and this is the remarkable part: the TP all-reduces are replaced by a reduce-scatter plus an all-gather, which carry exactly the same volume, since an all-reduce is precisely those two operations back to back. You remove a memory redundancy without paying a single byte of network. See Sequence Parallelism.

Selective activation recomputation

Rather than recomputing every activation in every layer, Megatron targets the ones that cost the most memory per unit of computation saved: the attention matrix and its softmax, whose size grows with the square of sequence length. Everything else is kept.

Reducing Activation Recomputation in Large Transformer Models (Korthikanti et al., 2022)
What the paper measures

The authors combine sequence parallelism with selective recomputation and report activation memory divided by 5 while cutting recomputation's time overhead by more than 90% relative to full recomputation. On a 530-billion-parameter model trained on 2,240 A100 cards they measure a Model FLOPs Utilization of 54.2%, against 42.1% with full recomputation, a 29% faster run.

Diagram comparing two activation-recomputation policies. Top, block method with 3 layers: a sequence of Transformer blocks, each containing LayerNorm, multi-head attention, LayerNorm and MLP; the first three blocks are green (recomputed during backpropagation) and the fourth is purple (fully saved during the forward). Bottom, uniform method with 2 layers: all blocks are green, and red triangles marking saved activations appear every two blocks instead of every block.
Two ways to dial recomputation in Megatron. In green, what will be recomputed during the backward pass; in purple, what stays in memory; the red triangles mark the save points. The more green, the less memory you use and the more you recompute, that is the dial you set layer by layer.Source : NVIDIA NeMo Megatron-Bridge documentation

The full mechanism is explained in Activation recomputation.

Pipeline scheduling

PP has a structural flaw: while card 1 computes layer 1, the others wait their turn. That is the pipeline bubble, wasted compute time. Megatron offers several schedules to shrink it:

  • 1F1B, one forward one backward: each card alternates, which frees a micro-batch's activations as soon as its backward runs and therefore caps memory.
  • Interleaved 1F1B: instead of giving a card one contiguous chunk of layers, you give it several non-contiguous chunks. There are more stages to fill, so the relative bubble shrinks, at the cost of more exchanges. The paper puts the throughput gain at more than 10%, with a comparable memory footprint.

Overlapping communication and computation

The goal is the same everywhere: never leave a card stalled on the network. The DP all-reduce is launched while the backward pass continues; PP weights are prefetched during the current layer's computation. What cannot be hidden, as we saw, is the TP all-reduce.

Numerical precisions

Megatron stacks three levels, following the logic in mixed precision: BF16 for the forward and backward passes, FP32 for the master copy of the weights and for gradient accumulation (without which the optimizer's minuscule corrections round to zero), and FP8 on cards that support it, which doubles the theoretical throughput of matrix multiplications, see FP8.

What the papers measure

The metric used is MFU, Model FLOPs Utilization: the fraction of the card's theoretically available floating-point operations that actually goes into moving the model forward. An MFU of 50% does not mean half the machine is asleep: the other 50% goes into network communication, the pipeline bubble, operations that are not matrix multiplications (normalisations, activations) and memory-bandwidth limits.

What is measuredReported resultSource
8.3 billion parameters on 512 cards15.1 petaFLOP per second, 76% scaling efficiency against a single card sustaining 39 teraFLOP per second, which is 30% of its peak2019 paper
1 trillion parameters on 3,072 A100 cards502 petaFLOP per second, that is 52% of theoretical peak per card2021 paper
530 billion parameters on 2,240 A100 cards54.2% MFU with selective recomputation, against 42.1% with full recomputation2022 paper

The second figure checks out with one division in front of you: 502,000/3,072≈163502{,}000 / 3{,}072 \approx 163 teraFLOP per second per card, against the 312 teraFLOP per second BF16 peak of an A100, which is indeed 52%. That the efficiency stays above half across three thousand cards is the real result of that paper.

The MFU percentage trap

Two MFU figures are only comparable at identical hardware, model size and sequence length. The denominator is the card's theoretical peak, which more than tripled between A100 and H100: the same absolute throughput therefore yields a three-times-lower MFU on the newer card. Distrust any MFU table that does not say which card was used.

Ecosystem

NeMo

NeMo is NVIDIA's convenience layer on top of Megatron-LM: declarative configuration in YAML files (YAML Ain't Markup Language, a human-readable configuration text format) instead of Python code, ready-made recipes for language models, multimodal models and ASR (Automatic Speech Recognition), and integration with NVIDIA's deployment tooling.

Models trained with Megatron-LM

BLOOM (BigScience), 176 billion parameters, was trained with Megatron-DeepSpeed, a merger of the two frameworks pairing Megatron's tensor and pipeline parallelism with DeepSpeed's memory partitioning. Megatron-LM is otherwise the reference codebase for distributed-training research, and many non-public industrial models build on it.

Comparison with the alternatives

FrameworkDeveloperMain strength
Megatron-LMNVIDIAheavily optimised tensor and pipeline parallelism on NVIDIA hardware
DeepSpeedMicrosoftZeRO, offload to CPU and disk, flexibility
FSDPMeta / PyTorchnative PyTorch integration, simplicity
ColossalAIHPC-AIseveral execution backends, accessible configuration
When to choose Megatron-LM?

The dividing line is card count. Below a hundred or so, a model fits with memory partitioning alone, and FSDP or DeepSpeed are enough, simpler to configure, better documented. Above that, once cutting the matrices and spreading the layers over several machines becomes unavoidable, Megatron-LM is the reference choice: it is the only one whose three splits have been measured at that scale by their own authors. The price is markedly more complex configuration.

Summary

Megatron-LM answers the question "what do we split?" with "all three at once". The batch (DP), the layer (PP) and the weight tensor (TP), arranged in a three-dimensional grid whose ordering follows the links from fastest to slowest. The thing to retain is how tensor parallelism behaves: cutting one matrix across cards forces an all-reduce in the middle of every block, at every layer, in both directions, four per layer per step. That exchange sits on the critical path, it cannot be hidden under computation, and that is why TP never leaves the inside of a single machine, unlike data parallelism whose one all-reduce per step slides underneath the backward pass.

Check your understanding0 / 5

1. To spread the feed-forward network Y = GeLU(XA) · B over two cards, Megatron cuts the first matrix A into columns rather than rows. Why?

2. Tensor parallelism demands the NVLink link inside a machine, while data parallelism tolerates the much slower inter-machine network. The main reason?

3. In Megatron's 3D grid, why does TP get the cards inside one machine, while DP is pushed onto the slowest link?

4. A table reports 45 percent MFU for a run on H100s and 52 percent for another on A100s. Can you conclude the second run is better optimised?

5. A team is training a 13-billion-parameter model on 64 cards. Is Megatron-LM the choice the page recommends?