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.
| Dimension | What is divided | Typical placement |
|---|---|---|
| Tensor parallelism | Weight matrices inside each layer | Within one node, 2 to 8 GPUs |
| Pipeline parallelism | Consecutive groups of layers | Across nodes |
| Data parallelism | Training batch; full model replicas | Across the whole cluster |
| Sequence parallelism | Activations along the sequence axis | Paired with tensor parallelism |
| Context parallelism | Very long input sequences | For contexts of 32k tokens and more |
| Expert parallelism | Experts of a mixture-of-experts layer | Across GPUs holding different experts |
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.
| Technique | Benefit | Cost |
|---|---|---|
| Interleaved 1F1B schedule | Smaller pipeline bubble | More point-to-point messages |
| Full activation recomputation | Large activation memory savings | About one third more compute |
| Selective recomputation | Most savings for attention memory | Small compute overhead |
| Distributed optimizer | Optimizer state split across ranks | Extra gather and scatter steps |
| FP8 with Transformer Engine | Higher throughput on recent GPUs | Needs careful scaling and validation |
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 compared with related frameworks
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.
| Tool | Primary focus | Relation to Megatron-LM |
|---|---|---|
| DeepSpeed | ZeRO sharding and training efficiency | Often combined as Megatron-DeepSpeed |
| PyTorch FSDP | Fully sharded data parallelism | Simpler setup, less layer-level splitting |
| NVIDIA NeMo | End-to-end model development | Uses Megatron-Core as its training backend |
| Hugging Face Accelerate | Easy multi-GPU scripts | Can wrap Megatron-LM as a plugin |
| JAX with XLA | Compiler-driven sharding | Alternative approach outside PyTorch |
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.
| Situation | Recommended setting | Reason |
|---|---|---|
| Model fits on one GPU | Data parallelism only | No partitioning overhead |
| Model fits in one node | Tensor parallelism up to 8 | NVLink bandwidth handles all-reduce |
| Model exceeds one node | Add pipeline parallelism | Point-to-point traffic suits slower links |
| Very long sequences | Enable context parallelism | Splits attention memory along tokens |
| Mixture-of-experts model | Enable expert parallelism | Places experts on separate devices |
- 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.