Megatron-LM README

The project's README from github.com/NVIDIA/Megatron-LM. As one markdown file: README.md.

Megatron-LM and Megatron Core

GPU-optimized library for training transformer models at scale

Documentation version license

About

This repository contains two components: Megatron-LM and Megatron Core.

Megatron-LM is a reference example that includes Megatron Core plus pre-configured training scripts, ideal for research teams, learning distributed training, and quick experimentation.

Megatron Core is a composable library with GPU-optimized building blocks for custom training frameworks. It provides transformer building blocks, advanced parallelism strategies (TP, PP, DP, EP, and CP), mixed precision support (FP16, BF16, FP8, and FP4), and model architectures, ideal for framework developers and ML engineers building custom training pipelines.

Megatron Bridge provides bidirectional Hugging Face ↔ Megatron checkpoint conversion with production-ready recipes.

Getting Started

Install from PyPI:

uv pip install megatron-core

Or clone and install from source:

git clone https://github.com/NVIDIA/Megatron-LM.git
cd Megatron-LM
uv pip install -e .

Note: Building from source can use a lot of memory. If the build runs out of memory, limit parallel compilation jobs by setting MAX_JOBS (for example, MAX_JOBS=4 uv pip install -e .).

For NVIDIA GPU Cloud (NGC) container setup and all installation options, review the Installation Guide.

Latest News

Previous News

Project Structure

Megatron-LM/
├── megatron/
│   ├── core/                    # Megatron Core (kernels, parallelism, building blocks)
│   │   ├── models/              # Transformer models
│   │   ├── transformer/         # Transformer building blocks
│   │   ├── tensor_parallel/     # Tensor parallelism
│   │   ├── pipeline_parallel/   # Pipeline parallelism
│   │   ├── distributed/         # Distributed training (FSDP, DDP)
│   │   ├── optimizer/           # Optimizers
│   │   ├── datasets/            # Dataset loaders
│   │   ├── inference/           # Inference engines and server
│   │   └── export/              # Model export (example: TensorRT-LLM)
│   ├── training/                # Training scripts
│   ├── legacy/                  # Legacy components
│   ├── post_training/           # Post-training (quantization, distillation, pruning, etc.)
│   └── rl/                      # Reinforcement learning (including RLHF)
├── examples/                    # Ready-to-use training examples
├── tools/                       # Utility tools
├── tests/                       # Comprehensive test suite
└── docs/                        # Documentation

Performance Benchmarking

For the latest performance benchmarking results, refer to NVIDIA Megatron Bridge Performance Summary.

The codebase efficiently trains models from 2B to 462B parameters across thousands of GPUs, achieving up to 47% Model FLOP Utilization (MFU) on H100 clusters.

Model table

Benchmark Configuration:

  • Vocabulary size: 131,072 tokens
  • Sequence length: 4,096 tokens
  • Model scaling: Varied hidden size, attention heads, and layers to achieve target parameter counts
  • Communication optimizations: Fine-grained overlapping with DP (--overlap-grad-reduce, --overlap-param-gather), TP (--tp-comm-overlap), and PP (enabled by default)

Key Results:

  • 6,144 H100 GPUs: Successfully benchmarked 462B parameter model training.
  • Superlinear scaling: MFU increases from 41% to 47–48% with model size.
  • End-to-end measurement: Throughputs include all operations (data loading, optimizer steps, communication, and logging).
  • Production ready: Full training pipeline with checkpointing and fault tolerance.
  • Note: Performance results measured without training to convergence

Weak Scaling Results

The weak scaled results show superlinear scaling (MFU increases from 41% for the smallest model considered to 47–48% for the largest models); this is because larger GEMMs have higher arithmetic intensity and are consequently more efficient to execute.

Weak scaling

Strong Scaling Results

This test strong scales the standard GPT-3 model (slightly more than 175 billion parameters due to larger vocabulary size) from 96 H100 GPUs to 4,608 GPUs, using the same batch size of 1,152 sequences throughout. Communication becomes more exposed at larger scale, leading to a reduction in MFU from 47% to 42%.

Strong scaling

Roadmaps

Resources

Getting Help

  • 📖 Documentation - Official guides and API reference
  • 🐛 Issues - Bug reports and feature requests

Contributing

Contributions are welcome. Ways to contribute:

  • 🐛 Report bugs - Help improve reliability
  • 💡 Suggest features - Shape the future of Megatron Core
  • 📝 Improve docs - Make Megatron Core more accessible
  • 🔧 Submit PRs - Contribute code improvements

→ Contributing Guide

Citation

If you use Megatron in your research or project, use the following citation:

@article{megatron-lm,
  title={Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism},
  author={Shoeybi, Mohammad and Patwary, Mostofa and Puri, Raul and LeGresley, Patrick and Casper, Jared and Catanzaro, Bryan},
  journal={arXiv preprint arXiv:1909.08053},
  year={2019}
}

Megatron-LM (NVIDIA/Megatron-LM)

Searching Database…

Что это такое?Опенсорсный набор инструментов от NVIDIA для обучения больших трансформерных (LLM) моделей в масштабе. Он поставляется в виде Megatron-LM — готового решения с обучающими скриптами — и Megatron Core, библиотеки из оптимизированных под GPU модулей, из которых собирают обучение моделей на тысячах GPU.
Это одна библиотека или несколько компонентов?Два компонента в одном репозитории: Megatron-LM — готовый пример с заранее настроенными скриптами для обучения, а Megatron Core — модульная библиотека, из которой строят собственные обучающие фреймворки. Отдельная утилита, Megatron Bridge, конвертирует чекпоинты между форматами Hugging Face и Megatron.
Как его установить?Установите из PyPI либо склонируйте репозиторий и соберите из исходников. Сборка из исходников требовательна к памяти, поэтому если компиляции не хватает памяти, ограничьте число параллельных задач, например MAXJOBS=4 uv pip install -e . Остальные варианты описаны в контейнерах NGC от NVIDIA и в Installation Guide, а дальше вас ведёт гайд Your First Training Run.
Есть ли подводные камни с версиями или совместимостью?Поддержка Python 3.10 уходит: грядущий релиз 0.17.0 требует Python 3.12 или новее, так что зависимым проектам придётся поднять минимальную версию. Сборка из исходников также может исчерпать память на не самых мощных машинах.
Для кого это — для исследователей или разработчиков фреймворков?И для тех, и для других, в зависимости от компонента: исследовательские команды, которые осваивают распределённое обучение и запускают быстрые эксперименты, берут готовые скрипты Megatron-LM, а разработчики фреймворков и ML-инженеры, строящие собственные пайплайны обучения, используют модули Megatron Core.
Нужно ли железо NVIDIA или подойдёт любой GPU?Он собран и протестирован только вокруг GPU NVIDIA — опубликованные результаты получены на кластерах H100, до 6 144 GPU для модели с 462 млрд параметров. Самые крупные запуски предполагают многоузловой кластер, а не одну машину.
Какого размера модели на нём тестировали?В опубликованных бенчмарках обучают модели от 2 до 462 млрд параметров на кластерах до 6 144 GPU H100, достигая 47–48% Model FLOP Utilization на верхнем крае, причём в измеренную пропускную способность включены продакшен-возможности вроде чекпоинтов и отказоустойчивости.
Как он распределяет обучение на тысячи GPU?С помощью пяти стратегий параллелизма: тензорного, конвейерного, по данным, экспертного и контекстного (TP, PP, DP, EP, CP) в сочетании со смешанной точностью FP16, BF16, FP8 и FP4. Dynamic Context Parallelism даёт ускорение до 1.48x при обучении на последовательностях переменной длины.
Можно ли взять чекпоинты из Hugging Face?Да. Megatron Bridge конвертирует чекпоинты в обе стороны между форматами Hugging Face и Megatron и содержит готовые продакшен-рецепты для популярных моделей, включая рецепты конвертации, инференса и предобучения для DeepSeek-V4.
Какие свежие модели он поддерживает?Недавние релизы добавили начальную поддержку DeepSeek-V4, оптимизированные MoE-рецепты для DeepSeek-V3, Mixtral и Qwen3, гибридную архитектуру Falcon-H1 (трансформер + Mamba) с тернарной квантизацией BitNet, а также возможности GPT-OSS вроде масштабирования YaRN RoPE и attention sinks.
What are similar projects?TensorRT-LLM, halo, DMI, LittleBit, verl, Meshy, Intern-Decision, airllm
Creator
NVIDIA
Size
155.8 MB
Stars
18.2K
Age
7y
Commits · 90 Days