Megatron-LM

Also known as: Megatron-Core

On this page 7

Megatron-LM is an open-source framework from NVIDIA for training very large transformer language models across hundreds or thousands of GPUs, best known for introducing tensor model parallelism for transformer layers. Among AI frameworks & tools, it occupies the specialized niche of large-scale pretraining, where a single model is too big to fit in the memory of one accelerator and must be split across many devices.

The project consists of two parts: a set of reference training scripts and examples, and Megatron-Core, a composable library of GPU-optimized building blocks that other software builds on. In practice, the name refers to both the original research codebase and the parallelism techniques it made standard in artificial intelligence research and industry.

How Megatron-LM splits a model across GPUs

Megatron-LM trains models that exceed single-device memory by combining several forms of parallelism at once. The core idea, published in 2019, is to partition the weight matrices of each transformer layer across GPUs, so that every device holds only a slice of the attention and feed-forward parameters and computes its part of each matrix multiplication.

In the feed-forward block, the first linear layer is split by columns and the second by rows, which means the GPUs need only one all-reduce operation in the forward pass and one in the backward pass per block. Attention heads are divided among devices in the same way. This design keeps communication low, but it requires a fast interconnect such as NVLink, so tensor parallelism is normally confined to the GPUs inside one server.

The parallelism dimensions that Megatron-LM supports are summarized in the following table, together with what each one divides and where it is typically applied.

DimensionWhat is dividedTypical placement
Tensor parallelismWeight matrices inside each layerWithin one node, 2 to 8 GPUs
Pipeline parallelismConsecutive groups of layersAcross nodes
Data parallelismTraining batch; full model replicasAcross the whole cluster
Sequence parallelismActivations along the sequence axisPaired with tensor parallelism
Context parallelismVery long input sequencesFor contexts of 32k tokens and more
Expert parallelismExperts of a mixture-of-experts layerAcross GPUs holding different experts
Parallelism dimensions in Megatron-LM

Pipeline scheduling and memory techniques

Pipeline parallelism assigns blocks of layers to different stages and streams micro-batches through them. A naive schedule leaves GPUs idle while the pipeline fills and drains; this idle time is called the pipeline bubble. Megatron-LM uses a one-forward-one-backward (1F1B) schedule and an interleaved schedule, in which each GPU holds several smaller, non-adjacent layer chunks, to shrink the bubble at the cost of extra communication.

Memory, not compute, is often the binding constraint. The framework therefore offers activation recomputation, which discards intermediate results and recomputes them during the backward pass, and a distributed optimizer that shards optimizer states across data-parallel ranks in a manner similar to ZeRO stage 1. Selective recomputation recomputes only the memory-heavy but cheap attention operations, which recovers most of the memory savings with a modest compute overhead.

The main techniques and their trade-offs are listed below.

TechniqueBenefitCost
Interleaved 1F1B scheduleSmaller pipeline bubbleMore point-to-point messages
Full activation recomputationLarge activation memory savingsAbout one third more compute
Selective recomputationMost savings for attention memorySmall compute overhead
Distributed optimizerOptimizer state split across ranksExtra gather and scatter steps
FP8 with Transformer EngineHigher throughput on recent GPUsNeeds careful scaling and validation
Memory and efficiency techniques

Mixed precision is standard: training usually runs in BF16, with FP8 available on Hopper and newer GPUs through the Transformer Engine library. Throughput is commonly reported as model FLOPs utilization (MFU), and well-tuned large runs typically reach roughly 40 to 55 percent of peak, depending on model size, sequence length and network topology.

Megatron-LM is a low-level training engine, not a general-purpose deep learning library. It runs on top of PyTorch, depends on NCCL for collective communication and is frequently combined with or compared to other distributed training tools, as the table shows.

ToolPrimary focusRelation to Megatron-LM
DeepSpeedZeRO sharding and training efficiencyOften combined as Megatron-DeepSpeed
PyTorch FSDPFully sharded data parallelismSimpler setup, less layer-level splitting
NVIDIA NeMoEnd-to-end model developmentUses Megatron-Core as its training backend
Hugging Face AccelerateEasy multi-GPU scriptsCan wrap Megatron-LM as a plugin
JAX with XLACompiler-driven shardingAlternative approach outside PyTorch
Position among distributed training tools

The essential difference is that Megatron-LM gives explicit, hand-optimized control over model partitioning, whereas sharded data-parallel approaches keep the model logically whole and shard parameters only for storage. For models beyond roughly tens of billions of parameters, the combination of tensor, pipeline and data parallelism, often called 3D parallelism, remains the most widely used recipe.

Configuring a Megatron-LM training run

A run is defined largely through command-line arguments that set the model architecture, the parallel layout and the data pipeline. The product of tensor, pipeline and context parallel sizes must divide the total number of GPUs, and the remaining factor becomes the data-parallel size. Training data is tokenized in advance into an indexed binary format that the framework reads with memory mapping.

Choosing the layout is the decisive step for performance. The following decision table reflects common practice.

SituationRecommended settingReason
Model fits on one GPUData parallelism onlyNo partitioning overhead
Model fits in one nodeTensor parallelism up to 8NVLink bandwidth handles all-reduce
Model exceeds one nodeAdd pipeline parallelismPoint-to-point traffic suits slower links
Very long sequencesEnable context parallelismSplits attention memory along tokens
Mixture-of-experts modelEnable expert parallelismPlaces experts on separate devices
Choosing a parallel layout
  • Keep tensor parallelism inside a node; crossing nodes usually collapses throughput.
  • Use a global batch size large enough to fill the pipeline with many micro-batches.
  • Save checkpoints in the distributed checkpoint format, which allows resuming with a different parallel layout.

Limitations and common mistakes

Megatron-LM has a steep learning curve. It assumes familiarity with distributed systems, cluster schedulers such as Slurm and NVIDIA hardware, and its best performance depends on NVIDIA GPUs and high-bandwidth networking such as InfiniBand. Support for other accelerators exists only through separate forks or community efforts and is not equivalent.

Typical errors include mismatched parallel sizes that do not divide the GPU count, too few micro-batches that leave a large pipeline bubble, and converting checkpoints to other formats without verifying numerical equivalence. Another misconception is that the framework is meant for fine-tuning small models; for that task, lighter tools such as Hugging Face TRL or PyTorch Lightning are usually more practical.

A plain-language summary

Some AI models are so large that no single computer chip can hold them. Megatron-LM is software that cuts such a model into pieces and spreads them across many chips. Each chip does its share of the work. The chips then exchange results many times per second.

Think of a very large book being copied by a team. One person cannot hold the whole book. So each person gets some pages, and some people work on halves of the same page. A careful plan keeps everyone busy and in sync. Megatron-LM is that plan for training large language models.

An example from practice

A research team at a national computing center wants to pretrain a 70-billion-parameter language model for several European languages. The model in BF16 needs far more memory than a single 80 GB GPU offers, and the cluster provides 512 GPUs in 64 nodes of eight GPUs each, connected by InfiniBand.

The engineers choose tensor parallelism of 8 within each node, pipeline parallelism of 4 across nodes and a resulting data-parallel size of 16. They enable the distributed optimizer, selective recomputation and the interleaved schedule, and they tokenize about two trillion tokens into the indexed binary format in advance.

After tuning the micro-batch count to reduce the pipeline bubble, the run sustains about 45 percent model FLOPs utilization. Training completes within the allocated compute budget, and the team converts the final distributed checkpoint to a common format for evaluation and release.