资讯动态

用 OpenScholar 改造版 torchtune 微调 LLM:从 tune CLI、YAML 配置到多卡训练配方

发布时间:2026/10/13 12:31:13 来源:尧图企业网站定制
人工智能RAGNLP微调模型推理服务【免费下载链接】OpenScholarThis repository includes the official implementation of OpenScholar: Synthesizing Scientific Literature with Retrieval-augmented LMs.项目地址https://gitcode.com/gh_mirrors/op/OpenScholar点击查看免费下载本文以 OpenScholar 仓库中 training/README.md 这份为 OpenScholar 定制的 torchtune 训练文档为主体完整梳理该训练代码库的安装、tune命令行体系、模型下载、LoRA/QLoRA/全量微调等配方的启动方式与配置修改方法并结合仓库内 CLI 源码、配方注册表与 OpenScholar 实际使用的 YAML 配置说明 OpenScholar-8B 是如何基于这套改造版 torchtune 训练出来的。一、training 目录是什么为 OpenScholar 定制的 torchtune仓库根目录 README.md 在Repository Organizations一节中明确说明src/是 OpenScholar 推理主代码training/ 是使用处理后的数据训练 Llama 3.1 8B 的训练代码我们对早期版本的torchtune做了修改retriever/是检索retrieval代码。也就是说training/ 目录整体是一份torchtune 的 vendored内嵌副本并针对 OpenScholar 的训练需求做了修改。training/README.md 的标题即为 torchtune (Modified for OpenScholar)其内容就是 torchtune 的标准 README介绍、安装、快速上手、设计原则等而 OpenScholar 对这份 README 几乎没有增删说明团队直接沿用了 torchtune 的用法只在实际训练时改动了配置与数据接入。版本信息以 training/version.txt 为准当前值为0.2.1属于 torchtune 的 alpha 阶段版本因此文中的功能范围支持的模型、配方、CLI 子命令都应以本仓库实际代码为准而不是 torchtune 上游后续版本的能力。README 开头的 NOTE 同时给出了两条时间线事实torchtune 在 2024 年 7 月更新了 Llama3.1 的权重llama3_1/下的 8B 与 70B 配置支持 LoRA、QLoRA 与全量微调三种方式QLoRA 405B 的支持即将添加。核心能力与生态集成README 将 torchtune 定位为PyTorch 原生的 LLM 编写、微调与实验库提供的核心能力包括使用可组合、模块化构件实现的流行 LLM 原生 PyTorch 实现面向流行微调技术LoRA、QLoRA易用且可 hack 的训练配方——没有 Trainer、没有训练框架只有 PyTorch用 YAML 配置训练、评测、量化或推理配方内置多种流行数据集格式与 prompt 模板。与之集成的生态组件在源码中均有对应落点生态组件在本仓库的落点Hugging Face Hub 权重下载training/torchtune/_cli/download.pyEleutherAI 评测框架training/recipes/eleuther_eval.pyHugging Face Datasets 数据加载training/torchtune/datasets/_instruct.pyPyTorch FSDP 分布式训练training/recipes/full_finetune_distributed.py、training/recipes/lora_finetune_distributed.pytorchao 低精度与训练后量化training/recipes/quantize.pybitsandbytes 低显存优化器training/recipes/configs/llama2/7B_full_low_memory.yaml二、支持的模型与微调配方总览支持的模型README 中的模型支持表链接均指向本仓库对应目录如下ModelSizes模型实现 / 配置Llama3.18B, 70Btorchtune/models/llama3_1/、recipes/configs/llama3_1/Llama38B, 70Btorchtune/models/llama3/、recipes/configs/llama3/Llama27B, 13B, 70Btorchtune/models/llama2/、recipes/configs/llama2/Code-Llama27B, 13B, 70Btorchtune/models/code_llama2/、recipes/configs/code_llama2/Mistral7Btorchtune/models/mistral/、recipes/configs/mistral/Gemma2B, 7Btorchtune/models/gemma/、recipes/configs/gemma/Phi3Minitorchtune/models/phi3/、recipes/configs/phi3/Qwen20.5B, 1.5B, 7Btorchtune/models/qwen2/、recipes/configs/qwen2/对 OpenScholar 而言重点自然是Llama3.1 8B根 README 的Training一节说明OpenScholar-8B 是用 13k 条指令微调数据OS_Train_Data在 8*A100 上使用修改版 torchtune 训练的。微调配方recipes矩阵README 给出的配方矩阵为训练方式微调方法代码 / 示例配置分布式训练1~8 GPUFulltraining/recipes/full_finetune_distributed.py、llama3/8B_full.yaml分布式训练1~8 GPULoRAtraining/recipes/lora_finetune_distributed.py、llama3/8B_lora.yaml单卡 / 低显存1 GPUFulltraining/recipes/full_finetune_single_device.py、llama3/8B_full_single_device.yaml单卡 / 低显存1 GPULoRA QLoRAtraining/recipes/lora_finetune_single_device.py、llama3/8B_lora_single_device.yaml单卡1 GPUDPOtraining/recipes/lora_dpo_single_device.py、llama2/7B_lora_dpo_single_device.yaml单卡1 GPURLHF with PPOtraining/recipes/ppo_full_finetune_single_device.py、mistral/7B_full_ppo_low_memory.yaml从 training/torchtune/_recipe_registry.py 的注册表看除上表外CLI 还登记了lora_dpo_distributed、lora_finetune_fsdp2dev 实验配方、generate推理生成、eleuther_eval评测、quantize量化与qat_distributed量化感知训练等配方每个配方都带有supports_distributed标志——这正是tune run判断是否允许 torchrun 参数的依据见下文。README 同时给出了一组 Llama2-7B / 70B 的峰值显存与训练速度参考数据适用前提Batch Size47B 序列长度 2048、70B 序列长度 4096硬件方法模型单卡峰值显存 (GB)训练速度 (tokens/sec)1 x RTX 4090QLoRALlama2-7B12.331551 x RTX 4090LoRALlama2-7B21.325822 x RTX 4090LoRALlama2-7B16.227681 x RTX 4090Full fine-tune*Llama2-7B24.17024 x RTX 4090Full fine-tuneLlama2-7B24.113888 x A100LoRALlama2-70B26.433848 x A100Full fine-tune*Llama2-70B70.42032* 使用 bitsandbytes 的 PagedAdamWQLoRA 行使用 torch compile。单卡配方暴露了分布式版本没有的若干显存优化bitsandbytes 低精度优化器、把 optimizer step 与 backward 融合以减少梯度显存示例见 llama2/7B_full_low_memory.yaml。该配置中可以看到两处关键项optimizer: bitsandbytes.optim.PagedAdamW与optimizer_in_bwd: True。对显存紧张的环境README 建议以单卡配置作为起点。三、Llama3 / Llama3.1 微调命令速查README 说明Llama3 8B 与 70B 支持单卡上的 LoRA、QLoRA、全量微调8B 支持多设备 LoRA 与全量微调70B 支持多设备 LoRA。并特别提示Llama3 与 Llama3.1 的 LoRA/QLoRA 配置默认使用 instruct 微调版模型因为 base 8B/70B 模型中并非所有特殊 token 的 embedding 都已初始化。初始实验中Llama3-8B 的 QLoRA 单卡峰值分配显存约 9GBLoRA 单卡约 19GB。单卡# LoRA 8B tune run lora_finetune_single_device --config llama3_1/8B_lora_single_device # QLoRA 8B tune run lora_finetune_single_device --config llama3_1/8B_qlora_single_device # Full 8B tune run full_finetune_single_device --config llama3_1/8B_full_single_device多卡# Full 8B tune run --nproc_per_node 4 full_finetune_distributed --config llama3_1/8B_full # LoRA 8B tune run --nproc_per_node 2 lora_finetune_distributed --config llama3_1/8B_lora # LoRA 70B先下载 70B 权重 tune download meta-llama/Meta-Llama-3.1-70b --hf-token --output-dir /tmp/Meta-Llama-3.1-70b --ignore-patterns original/consolidated* tune run --nproc_per_node 8 lora_finetune_distributed --config llama3_1/70B_lora.yamlREADME 特别指出 70B 的下载命令与 8B 略有差异70B 使用 HuggingFacesafetensors格式加载模型所以下载命令需要显式传入--ignore-patterns original/consolidated*跳过非 safetensors 的旧式权重文件避免重复下载。完整配置清单见 training/recipes/configs/llama3/ 与 training/recipes/configs/llama3_1/。OpenScholar 实战视角查看 training/recipes/configs/llama3_1/8B_full.yaml 会发现它与 torchtune 上游默认配置的差异——dataset组件被换成了torchtune.datasets.chat_datasetsource指向 OpenScholar 内部处理好的指令数据目录chat_format: torchtune.data.Llama3ChatFormat、max_seq_len: 8096优化器为普通torch.optim.AdamWlr2e-5、epochs: 3并开启enable_activation_checkpointing与memory_efficient_fsdp_wrap。这说明 OpenScholar 训练时走的就是修改本地配置的路线把 13k 条科学文献指令数据接入chat_dataset多轮对话格式其余训练管线完全复用 torchtune 分布式全量微调配方。四、安装README 的安装步骤为Step 1安装 PyTorch。torchtune 在最新稳定版 PyTorch 及预览 nightly 版本上测试若要微调多模态 LLM 还需 torchvision# 安装 PyTorch 稳定版 pip install torch torchvision # 安装 nightly 以获得最新特性 pip install --pre torch torchvision --index-url https://download.pytorch.org/whl/nightly/cu121Step 2安装 torchtune。稳定版发布于 PyPIpip install torchtune验证安装tune --help预期输出usage: tune [-h] {ls,cp,download,run,validate} ... Welcome to the torchtune CLI! options: -h, --help show this help message and exit ...{ls,cp,download,run,validate}这 5 个子命令与 training/torchtune/_cli/tune.py 中注册的子解析器一一对应Download、List、Copy、Run、Validate且不带子命令时默认打印帮助set_defaults(funclambda args: self._parser.print_help())。tune命令本身由 training/pyproject.toml 的[project.scripts]段声明为tune torchtune._cli.tune:main。在 OpenScholar 仓库中的使用方式由于训练代码是 vendored 副本实际训练时应以training/目录为工作目录安装其本地包pip install -e training或直接在该目录下运行使tune指向本仓库的torchtune与recipes这样才能使用其中被 OpenScholar 修改过的配方与配置直接pip install torchtune装的是上游版本不包含 OpenScholar 的改动。五、Get Started下载模型、运行配方、修改配置1. 下载模型先按官方 meta-llama 仓库的说明确认你有权访问 Llama 权重然后tune download meta-llama/Meta-Llama-3-8B \ --output-dir /tmp/Meta-Llama-3-8B \ --hf-token HF_TOKEN提示设置环境变量HF_TOKEN或直接传--hf-token来验证访问权限token 可在 Hugging Face 个人账户的 token 设置页获取。结合 training/torchtune/_cli/download.py 的源码可以补充几个 README 未展开的细节--output-dir缺省值为/tmp/model_name见 _download_cmd--ignore-patterns默认值是*.safetensors即普通下载默认跳过 safetensors 分片以避免重复权重而 70B 场景则相反需要下载 safetensors、跳过original/consolidated*——这正是 README 强调 70B 命令不同的原因底层调用 Hugging Face Hub 的snapshot_download遇到 gated 仓库如 Llama 系列但没有有效 token 时会报GatedRepoError并给出明确提示。2. 运行微调配方README 以 Llama2-7B 为例给出两条命令原文示例# 单卡 LoRA tune run lora_finetune_single_device --config llama2/7B_lora_single_device # 两卡分布式 LoRA/Full tune run --nproc_per_node 2 full_finetune_distributed --config llama2/7B_full提示torchrun 的参数如--nproc_per_node必须放在 recipe 名称之前此后的 CLI 参数只用于覆盖配置不影响分布式训练。tune run的行为在 training/torchtune/_cli/run.py 中有完整实现关键机制值得了解配方解析_get_recipe先按名称在 _recipe_registry.py 注册表中查找找不到就当作本地文件路径直接运行——所以你也可以tune run my_custom_recipe.py --config xxx.yaml跑自己的配方配置解析_get_config把llama2/7B_lora_single_device这样的短名解析成recipes/configs/llama2/7B_lora_single_device.yaml的完整路径分布式判定_is_distributed_args通过比较sys.argv总长与 recipe 参数长来判断是否带了 torchrun 参数若带了而配方的supports_distributedFalse如单卡配方直接报错 does not support distributed training。分布式路径调用torch.distributed.run即 torchrun单卡路径则用runpy.run_path直接执行 recipe 脚本见 _run_distributed / _run_single_device这些分支在 training/tests/torchtune/_cli/test_run.py 中有对应测试用例例如对单卡配方传--nproc_per_node必须以 does not support distributed training 报错。另外注意一个容易踩坑的点training/recipes/init.py 会在import recipes时直接raise ModuleNotFoundError——recipes/不是一个可 import 的 Python 包配方只能通过tune run以脚本方式运行而不能在代码里当模块引用。3. 修改配置CLI Override 与本地副本README 给出两种修改配置的方式。方式一命令行覆盖Config Overridestune run lora_finetune_single_device \ --config llama2/7B_lora_single_device \ batch_size8 \ enable_activation_checkpointingTrue \ max_steps_per_epoch128底层机制是parse装饰器training/torchtune/config/_parse.py 中parse用TuneRecipeArgumentParser解析出 YAML 参数与 CLI 参数再由_merge_yaml_and_cli_args合并成最终的DictConfig——CLI 上的keyvalue覆盖对应 YAML 字段支持点路径如checkpointer.checkpoint_dir...。方式二复制本地副本tune cptune cp llama2/7B_full ./my_custom_config.yaml # Copied to ./7B_full.yaml tune run full_finetune_distributed --config ./my_custom_config.yamlcp子命令的实现见 training/torchtune/_cli/cp.py它同样按注册表定位源文件recipe 或 config支持-n/--no-clobber目标已存在时不覆盖与--make-parents自动创建父目录两个选项。4. 读懂一个 YAML_component_与instantiate配置的核心语法是_component_字段它指定要实例化的 Python 对象点路径同级其他字段作为构造参数。以 llama3_1/8B_lora_single_device.yaml 为例# Model Arguments model: _component_: torchtune.models.llama3_1.lora_llama3_1_8b lora_attn_modules: [q_proj, v_proj] apply_lora_to_mlp: False apply_lora_to_output: False lora_rank: 8 lora_alpha: 16 # Tokenizer tokenizer: _component_: torchtune.models.llama3.llama3_tokenizer path: /tmp/Meta-Llama-3.1-8B-Instruct/original/tokenizer.model # Dataset dataset: _component_: torchtune.datasets.alpaca_cleaned_dataset # Optimizer optimizer: _component_: torch.optim.AdamW weight_decay: 0.01 lr: 3e-4 lr_scheduler: _component_: torchtune.modules.get_cosine_schedule_with_warmup num_warmup_steps: 100recipe 内部通过config.instantiate(cfg.dataset)之类的调用完成实例化见 training/torchtune/config/_instantiate.py。该配置其余值得注意的字段checkpointerFullModelHFCheckpointer列出 4 个 safetensors 分片、gradient_accumulation_steps: 64单卡用小 batch 2 累积 64 等效扩大批大小、dtype: bf16、enable_activation_checkpointing: True以及默认禁用的 profiler 段enabled: False。_component_用法的完整说明可参考仓库内自带的配置深度文档 training/docs/source/deep_dives/configs.rst。分布式 LoRA 配置 llama3_1/8B_lora.yaml 与之对比主要差异是gradient_accumulation_steps: 32配合--nproc_per_node 2总批大小 batch_size × GPU 数 × 累积步数以及enable_activation_checkpointing: False。六、配方内部分布式 LoRA 训练都做了什么README 提到没有训练框架、显式展开训练逻辑这一点在 training/recipes/lora_finetune_distributed.py 的类文档中体现得最充分LoRAFinetuneRecipeDistributed支持的特性包括FSDP仅支持 PyTorch FSDP不支持 DDP也不支持 CPU 训练Activation Checkpointing由enable_activation_checkpointing控制以重计算换显存精度支持 fp32 与 bf16由dtype控制bf16 下激活、梯度与优化器状态均为 bfloat16fp16 与混合精度当前不支持recipe 会对dtypefp16直接ValueError见 lora_finetune_distributed.py梯度累积Total Batch Size batch_size × number of GPUs × gradient_accumulation_stepsCheckpointing每个 epoch 结束与训练结束时保存 adapter 权重与合并后的完整权重优化器状态与 recipe 状态seed、已跑 epoch 数等仅用于resume_from_checkpoint断点续训不支持 epoch 中途检查点日志支持 Terminal、Disk、WandB、TensorBoard。七、设计原则README 的 Design Principles 部分概括了 torchtune 的三条设计哲学也解释了为什么这套代码对 OpenScholar 这类拿来自改的场景友好Native PyTorch虽然集成了 Hugging Face Datasets、EleutherAI 评测等外部生态但所有核心功能都是 PyTorch 写的Simplicity and Extensibility组合优于继承、不引入训练框架显式展开训练逻辑便于定制、宁可代码重复也不要不必要的抽象、模块化构件优于单体组件Correctness不提供第一个功能但已提供的功能都有充分测试——组件级数值一致性单测、模型级检查点数值一致性测试、以及标准基准上的 recipe 级性能一致性集成测试。仓库内 training/tests/ 目录tests/torchtune/与tests/recipes/即是对应的测试体系。八、许可与致谢torchtune 部分以 BSD 3-Clause 协议发布见 training/LICENSE使用第三方模型时仍需遵守相应模型的服务条款。致谢部分列出了 Llama2 原始实现、EleutherAI / Hugging Face / Weights Biases 等合作方以及 gpt-fast、llama recipes、bitsandbytes、axolotl、lit-gpt、HF TRL 等生态项目对 torchtune 设计的影响社区贡献部分则点名了 PPO/RLHF、Qwen2、Gemma 2B、DPO 等功能的贡献者。九、小结在 OpenScholar 中如何落地把 training/README.md 当作通用 torchtune 使用手册再叠加根 README 与仓库源码中的 OpenScholar 改动可以得出该仓库训练 OpenScholar-8B 的实际路径以 training/ 下的改造版 torchtunev0.2.1为训练框架tune download拉取 Llama 3.1 8B 权重safetensors 分片 tokenizer将 13k 条科学文献指令数据接入torchtune.datasets.chat_datasetLlama3ChatFormat、max_seq_len: 8096如 llama3_1/8B_full.yaml 所示在 8×A100 上用tune run --nproc_per_node 8 full_finetune_distributed --config llama3_1/8B_fullbf16、AdamW lr2e-5、3 epochs、激活检查点 显存高效 FSDP wrap完成全量微调训练产物即根 README 中推理时使用的OpenScholar/Llama-3.1_OpenScholar-8B权重推理侧由 src/ 与run.py的 RAG 管线消费。若要在自己的环境复现或改造这一流程只需围绕tune download / tune run / tune cp三个子命令与对应 YAML 中_component_字段的替换展开即可配方行为均可在 training/recipes/ 与 training/torchtune/ 中找到源码级依据。赞分享人工智能RAGNLP微调模型推理服务【免费下载链接】OpenScholarThis repository includes the official implementation of OpenScholar: Synthesizing Scientific Literature with Retrieval-augmented LMs.项目地址https://gitcode.com/gh_mirrors/op/OpenScholar点击查看免费下载相关推荐PaddleClas 模型微调Finetune实战指南从数据准备到配置修改与多卡训练PaddleClas 模型微调Finetune实战指南从数据准备到配置修改与多卡训练 本指南面向已在 Linux 上完成 PaddleClas 环境配置并人工智能深度学习计算机视觉watermark.js vs 传统后端水印前端解决方案的优势与适用场景watermark.js vs 传统后端水印前端解决方案的优势与适用场景 在数字内容保护领域水印技术一直扮演着重要角色。watermark.js作为一款专为基于 DeepSpeed 的 Qwen-7B-Chat 全量微调实战从环境配置到多卡训练基于 DeepSpeed 的 Qwen 7B Chat 全量微调实战从环境配置到多卡训练 导读 本文基于开源仓库《开源大模型食用指南》中的 06 Qwen 7教程大模型本地部署微调创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

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

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

免费获取报价 →
↑