资讯动态

Megatron-LLM快速上手:手把手微调LLaMa 2 7B的完整实战教程(含500M tokens代码数据)

发布时间:2026/8/22 14:30:29 来源:尧图企业网站定制
Megatron-LLM快速上手手把手微调LLaMa 2 7B的完整实战教程含500M tokens代码数据【免费下载链接】Megatron-LLMdistributed trainer for LLMs项目地址: https://gitcode.com/gh_mirrors/me/Megatron-LLMMegatron-LLM 是一个专为大语言模型LLM打造的开源分布式训练框架支持 LLaMa、LLaMa 2、Code Llama、Falcon 和 Mistral 等主流架构的预训练、微调与指令微调。本篇 Megatron-LLM 微调教程将手把手带你用 500M tokens 的代码数据完成LLaMa 2 7B 微调的完整流程从环境安装、数据预处理、权重转换到启动训练和最终部署发布全程约 6 个步骤即可跑通。 为什么选择 Megatron-LLM 微调 LLaMa 2对于新手来说直接用 Hugging Face 微调 7B 模型常常卡在显存瓶颈上。Megatron-LLM 的核心优势在于三路并行继承自 Megatron 的张量并行TP、流水线并行PP与数据并行DP单卡放不下也能多卡训架构支持全面原生支持 LLaMa 2 / Code Llama / Falcon / Mistral 的特殊结构如 RoPE 旋转位置编码、RMS LayerNorm、SwiGLU 激活参见 megatron/model/llama_model.py训练友好支持 FlashAttention 2、BF16/FP16、选择性激活重计算并提供 WandB 日志集成双向权重转换一键在 Hugging Face 格式与 Megatron 检查点之间互转weights_conversion/。️ 第一步环境安装与硬件要求⚠️ 硬件门槛参考来自官方 FAQ 实测LLaMa 2 7B 微调最低需要 2×80GB 显存TP2, PP1更大规模可参考 LLaMa 2 70B 需要 32×80GBTP8, PP4。更多细节见 docs/guide/faq.md。安装步骤非常直接# 1. 克隆仓库 git clone https://gitcode.com/gh_mirrors/me/Megatron-LLM.git cd Megatron-LLM # 2. 启动 NVIDIA PyTorch 容器推荐省去依赖折腾 sudo docker run --gpus all -it --rm --shm-size128gb \ -v /path/to/Megatron-LLM/:/mpt/Megatron-LLM \ nvcr.io/nvidia/pytorch:23.07-py3 # 3. 安装依赖并编译数据加载辅助库 pip install -r requirements.txt cd megatron/data make cd ../../完整入门文档见 docs/guide/getting_started.md。 第二步下载 LLaMa 2 7B 权重并转换为 Megatron 格式向 Meta 申请 LLaMa 2 权重访问权限并申请 Hugging Face 上meta-llama/Llama-2-7b-hf模型的访问创建 Hugging Face Token 并执行huggingface-cli login完成登录运行官方转换脚本把权重转成 Megatron 检查点python weights_conversion/hf_to_megatron.py llama2 --size7 \ --out/path/to/megatron/weights/ --cache-dir/path/to/llama-2-7b/转换逻辑位于 weights_conversion/hf_to_megatron.py支持从 Meta 官方权重或 Hugging Face 权重两种来源自动识别加载。 第三步准备 500M tokens 代码数据并预处理本教程使用 StarCoder 数据集中的Julia 语言子集约 500M tokens作为微调语料任何符合.jsonl格式每行一个含text键的 JSON 对象的语料都可以替换使用。from datasets import load_dataset import json dataset load_dataset(bigcode/starcoderdata, data_dirjulia, splittrain, cache_dir/path/to/cache/) with open(/path/to/raw.jsonl, w) as f: for doc in dataset: f.write(json.dumps({id: doc[id], text: doc[content]}) \n)接着用 tools/preprocess_data.py 把原始数据 tokenize 成二进制索引文件训练时读取速度更快python tools/preprocess_data.py --input/path/to/raw.jsonl \ --output_prefix/path/to/tokenized/starcoder \ --tokenizer_typeSentencePieceTokenizer \ --vocab_file/path/to/tokenizer.model \ --chunk_size32 --workers16 --no_new_tokens 小提示官方教程用序列长度 1024 来加速训练LLaMa 2 官方序列长度为 4096可按需调整。 第四步模型分片Sharding准备并行训练要使用张量并行需要先用 tools/checkpoint_util.py 把转换好的单份权重切分成多份python tools/checkpoint_util.py \ --target_tensor_parallel_size 2 \ --target_pipeline_parallel_size 1 \ --load_dir /path/to/megatron/weights/ \ --save_dir /path/to/sharded/weights/ \ --model_type llama2 --true_vocab_size 32000 --bf16如果你有 4 张及以上 GPU可以把--target_tensor_parallel_size设为 4 进一步提速。 第五步启动微调训练finetune.py 参数详解一切就绪用torchrun启动 finetune.py 微调入口COMMON_ARGS--hidden_dropout 0.0 --attention_dropout 0.0 --no_bias_gelu_fusion LLAMA_ARGS--use_rms_norm --glu_activation swiglu --no_tie_embed_logits --no_new_tokens --layernorm_epsilon 1e-5 DISTRIBUTED_ARGS--nproc_per_node 2 --nnodes 1 --node_rank 0 --master_addr localhost --master_port 8000 torchrun $DISTRIBUTED_ARGS finetune.py \ --tensor_model_parallel_size 2 --pipeline_model_parallel_size 1 \ --load /path/to/sharded/weights/ --save /path/to/sharded/weights/ \ --data_path /path/to/tokenized/starcoder_text_document \ --model_name llama2 --tokenizer_type SentencePieceTokenizer \ --vocab_file/path/to/megatron/weights/tokenizer.model \ --bf16 --use_flash_attn \ --micro_batch_size 1 --global_batch_size 1000 \ --sequence_parallel --recompute_granularity selective --use_checkpoint_args \ --train_iters 500 --lr_decay_style cosine --lr_warmup_iters 50 --lr 3e-4 --min_lr 1e-6 \ $COMMON_ARGS $LLAMA_ARGS训练量估算全局 batch size 为 1000、语料约 500M tokens 时跑 500 个迭代约等于1 个完整 epoch在 8×80GB A100 集群上大约需要 20 小时。多机训练只需修改DISTRIBUTED_ARGS中的nnodes/node_rank/master_addr推荐超参数可参考 examples/finetune.sh。✅可选校验训练前建议运行 verify_correctness.py它会同时跑官方 LLaMa 2 实现与 Megatron 实现对比输出 logits——32 位精度下平均绝对误差应 0.0116 位精度下 0.1确保权重转换无误。 第六步训练后权重合并与部署发布训练完成后分片权重需要合并回单份模型再转回 Hugging Face 格式即可无缝部署# 1. 合并分片权重 python tools/checkpoint_util.py \ --target_tensor_parallel_size 1 --target_pipeline_parallel_size 1 \ --load_dir /path/to/sharded/weights/ \ --save_dir /path/to/unsharded/weights/ \ --model_type llama2 --true_vocab_size 32000 --bf16 # 2. 转换为 Hugging Face 格式 python weights_conversion/megatron_to_hf.py \ --input_dir/path/to/unsharded/weights/ --output_dir/path/to/hf/weights/转换脚本 weights_conversion/megatron_to_hf.py 会同时转换 tokenizer之后即可用transformers.pipeline(text-generation, ...)直接加载你的微调模型进行推理。 常见问题TP/PP 如何设置新手最常纠结的就是并行策略官方 FAQ 给出了清晰的经验法则能不用模型并行就不用优先堆数据并行单卡装得下、micro batch 够大时 TP/PP 都设 1单机优先张量并行跨节点时 PP 尽量小、保证 micro batch ≥ 5GPU 数量公式GPUs DP × TP × PP数据并行度会由框架自动推算。更多细节如多节点启动、添加特殊 token见 docs/guide/faq.md。 总结与下一步本教程带你完整走通了 Megatron-LLM 微调 LLaMa 2 7B 的六步流程环境安装 → 权重转换 → 数据预处理500M tokens→ 模型分片 → 分布式微调 → 合并部署。接下来你可以继续探索指令微调Instruct Tuning让模型学会遵循指令见 docs/guide/instruction_tuning.md更大规模训练示例examples/parallelize.sh核心并行实现megatron/core/tensor_parallel/。 完成这次实战你就已经掌握了用商品级硬件微调 7B 级开源大模型的全部关键技能【免费下载链接】Megatron-LLMdistributed trainer for LLMs项目地址: https://gitcode.com/gh_mirrors/me/Megatron-LLM创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价