mcpField
T
training-llms-megatron

training-llms-megatron

github.com/orchestra-research开发14.1k959 次安装19 周前更新
代码仓库

关于 training-llms-megatron

Megatron-Core 是用于大规模 LLM 训练的框架,面向在 NVIDIA GPU 集群上训练模型的研究和工程团队。它提供张量、流水线、数据、上下文及专家并行配置,并支持预训练与微调工作流。

主要功能

  1. 01分布式 LLM 训练
  2. 02张量、流水线等并行策略
  3. 03MoE 专家并行
  4. 04FP8 与性能优化
  5. 05训练指标监控

适用场景

  1. 01在多 GPU 集群训练 LLaMA 模型
  2. 02配置 Mixtral 等 MoE 模型训练
  3. 03优化 H100 上的训练吞吐量

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/orchestra-research/ai-research-skills --skill training-llms-megatron

安装后在 Claude Code 中输入/training-llms-megatron确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/
benchmarks.md
parallelism-guide.md
production-examples.md
training-recipes.md

详细介绍

Megatron-Core - 大规模 LLM 训练

快速开始

Megatron-Core 通过先进的并行策略,在 H100 GPU 上以最高 47% 的模型 FLOP 利用率训练参数量为 2B 至 462B 的 LLM。

安装:

# Docker (recommended)
docker run --gpus all -it --rm nvcr.io/nvidia/pytorch:25.04-py3

# Or pip
pip install megatron-core

简单的分布式训练:

# Train with 2 GPUs using data parallelism
torchrun --nproc_per_node=2 examples/run_simple_mcore_train_loop.py

# Or LLaMA-3 8B training
./examples/llama/train_llama3_8b_fp8.sh

常见工作流

工作流 1:使用 3D 并行训练 LLaMA 风格模型

复制此检查清单:

LLaMA Training Setup:
- [ ] Step 1: Choose parallelism configuration
- [ ] Step 2: Configure training hyperparameters
- [ ] Step 3: Launch distributed training
- [ ] Step 4: Monitor performance metrics

步骤 1:选择并行配置

模型大小决定并行策略:

模型大小GPU 数量张量并行流水线并行数据并行上下文并行
7B81181
13B82141
70B644441
405B1288822

步骤 2:配置训练超参数

#!/bin/bash
# train_llama_70b.sh

GPUS_PER_NODE=8
NNODES=8  # 64 GPUs total
TP=4      # Tensor parallel
PP=4      # Pipeline parallel
CP=1      # Context parallel

# LLaMA 70B configuration
MODEL_SIZE=70  # Billion parameters
HIDDEN_SIZE=8192
NUM_LAYERS=80
NUM_HEADS=64
SEQ_LENGTH=4096

# Training hyperparameters
MICRO_BATCH=1
GLOBAL_BATCH=1024
LR=3e-4

torchrun \
  --nproc_per_node=$GPUS_PER_NODE \
  --nnodes=$NNODES \
  pretrain_gpt.py \
  --tensor-model-parallel-size $TP \
  --pipeline-model-parallel-size $PP \
  --context-parallel-size $CP \
  --sequence-parallel \
  --num-layers $NUM_LAYERS \
  --hidden-size $HIDDEN_SIZE \
  --num-attention-heads $NUM_HEADS \
  --seq-length $SEQ_LENGTH \
  --max-position-embeddings $SEQ_LENGTH \
  --micro-batch-size $MICRO_BATCH \
  --global-batch-size $GLOBAL_BATCH \
  --lr $LR \
  --train-iters 100000 \
  --lr-decay-style cosine \
  --lr-warmup-iters 2000 \
  --weight-decay 0.1 \
  --clip-grad 1.0 \
  --bf16 \
  --use-mcore-models \
  --transformer-impl transformer_engine \
  --data-path /path/to/data \
  --vocab-file /path/to/vocab.json \
  --merge-file /path/to/merges.txt

步骤 3:启动分布式训练

# Single node (8 GPUs)
bash train_llama_70b.sh

# Multi-node with SLURM
sbatch --nodes=8 --gpus-per-node=8 train_llama_70b.sh

步骤 4:监控性能指标

需要跟踪的关键指标:

Model FLOP Utilization (MFU): Target >40% on H100
Throughput: Tokens/sec/GPU
Memory usage: <80GB per GPU for 70B model
Loss: Should decrease steadily
工作流 2:配置混合专家(MoE)训练

适用于 Mixtral 等稀疏 MoE 模型。

MoE Training:
- [ ] Step 1: Configure expert parallelism
- [ ] Step 2: Set MoE hyperparameters
- [ ] Step 3: Launch training with EP

步骤 1:配置专家并行

# Mixtral 8x7B example
TENSOR_PARALLEL=2
PIPELINE_PARALLEL=1
EXPERT_PARALLEL=4  # Split 8 experts across 4 GPUs
DATA_PARALLEL=4

TOTAL_GPUS=$((TENSOR_PARALLEL * PIPELINE_PARALLEL * EXPERT_PARALLEL * DATA_PARALLEL))
# = 2 * 1 * 4 * 4 = 32 GPUs

步骤 2:设置 MoE 超参数

torchrun \
  --nproc_per_node=8 \
  pretrain_gpt.py \
  --tensor-model-parallel-size 2 \
  --pipeline-model-parallel-size 1 \
  --expert-model-parallel-size 4 \
  --num-experts 8 \
  --moe-router-topk 2 \
  --moe-router-load-balancing-type aux_loss \
  --moe-aux-loss-coeff 0.01 \
  --hidden-size 4096 \
  --num-layers 32 \
  --num-attention-heads 32 \
  --seq-length 4096 \
  --max-position-embeddings 4096 \
  --bf16 \
  --use-mcore-models \
  --transformer-impl transformer_engine \
  --data-path /path/to/data \
  --vocab-file /path/to/vocab.json \
  --merge-file /path/to/merges.txt

步骤 3:使用 EP 启动训练

专家并行会将不同专家分布到各个 GPU 上,在保持模型容量的同时减少内存占用。

Memory without EP: 8 experts × 7B = 56GB per GPU
Memory with EP=4: 2 experts × 7B = 14GB per GPU
Savings: 75% memory reduction
工作流 3:优化以实现最大吞吐量

在 H100 上达到 47% MFU。

Performance Optimization:
- [ ] Step 1: Enable Flash Attention
- [ ] Step 2: Use FP8 precision (H100)
- [ ] Step 3: Optimize micro-batch size
- [ ] Step 4: Tune parallelism degrees

步骤 1:启用优化

--use-mcore-models  # Use Megatron Core models
--transformer-impl transformer_engine  # Use Transformer Engine
--sequence-parallel  # Reduce activation memory (use with TP)

步骤 2:使用 FP8 精度(仅限 H100)

--fp8-hybrid  # FP8 mixed precision training
# Transformer Engine handles FP8 automatically

结果:在 H100 上,相较于 BF16 可提速 1.5-2 倍。

步骤 3:优化微批次大小

找到适合内存的最大微批次:

# Start with 1, increase until OOM
for MBS in 1 2 4 8; do
  echo "Testing micro-batch-size=$MBS"
  torchrun ... --micro-batch-size $MBS
done

典型值:

  • 7B 模型:4-8
  • 70B 模型:1-2
  • 405B 模型:1

步骤 4:调整并行度

经验法则:

Tensor Parallel: Use ≤8 (limited by NVLink within node)
Pipeline Parallel: Use for >70B models
Context Parallel: Use for sequences >8K tokens
Data Parallel: Fill remaining GPUs

128 张 H100 上运行 405B 模型的示例:

TP=8 (1 node)
PP=8 (across nodes)
CP=2 (long sequences)
DP=1
Total = 8 × 8 × 2 × 1 = 128 GPUs

何时使用及替代方案

适合使用 Megatron-Core 的情况:

  • 训练参数量 >10B 的模型
  • 需要最高效率(目标 >40% MFU)
  • 使用 NVIDIA GPU(A100、H100)
  • 大规模生产训练
  • 希望精细控制并行策略

适合使用的替代方案:

  • PyTorch FSDP:模型 <70B、API 更简单、PyTorch 原生支持
  • DeepSpeed:设置更简单,适用于 <100B 的模型
  • HuggingFace Accelerate:适合原型开发,工作流更简单
  • LitGPT:适合教学,采用单文件实现

常见问题

问题:GPU 利用率低(<30% MFU)

原因:

  1. 微批次过小
  2. 并行开销过大
  3. 未使用 Flash Attention

解决方法:

# Increase micro-batch
--micro-batch-size 4  # Was 1

# Enable optimizations
--use-flash-attn
--sequence-parallel

# Reduce TP if >8
--tensor-model-parallel-size 4  # Was 16

问题:内存不足

通过以下方式减少内存占用:

--tensor-model-parallel-size 2  # Split model across GPUs
--recompute-granularity full  # Gradient checkpointing
--recompute-method block  # Checkpoint transformer blocks
--recompute-num-layers 1  # Checkpoint every layer

或者使用 CPU/NVMe 卸载:

--cpu-optimizer  # Offload optimizer to CPU
--cpu-optimizer-type ADAM  # CPU Adam variant

问题:训练速度低于预期

请检查:

  1. 网络瓶颈:确保已启用 InfiniBand/NVLink
  2. 流水线气泡:使用交错流水线调度
    --num-layers-per-virtual-pipeline-stage 2
    
  3. 数据加载:使用快速数据加载器
    --dataloader-type cyclic
    

问题:损失发散

稳定训练:

--lr-warmup-iters 2000  # Longer warmup
--clip-grad 1.0  # Gradient clipping
--init-method-std 0.006  # Smaller init
--attention-dropout 0.0  # No dropout in attention
--hidden-dropout 0.0  # No dropout in FFN

进阶主题

并行策略:参阅 references/parallelism-guide.md,了解 TP/PP/DP/CP/EP 的详细对比、性能分析以及各自的适用场景。

性能基准:参阅 references/benchmarks.md,了解不同模型大小和 GPU 配置下的 MFU 数据。

生产配置:参阅 references/production-examples.md,了解 LLaMA 3 405B、Nemotron-4 340B 和 DeepSeek-V3 671B 的实际配置。

训练配方:参阅 references/training-recipes.md,了解 GPT/LLaMA/Mixtral 架构的完整超参数配置。

硬件要求

  • GPU:NVIDIA Ampere+(A100、H100、B200)
    • Turing 也能运行,但速度较慢
    • FP8 需要 Hopper/Ada/Blackwell
  • 网络:多节点环境需要 InfiniBand 或 400Gb+ 以太网
  • 每个 GPU 的内存:
    • 7B 模型:40GB+
    • 70B 模型:80GB(TP=4)
    • 405B 模型:80GB(TP=8,PP=8)
  • 存储:检查点需要高速 NVMe(70B+ 模型需 1TB+)

资源

评论

支持 Markdown