llama-factory llm模型微调框架
LlamaFactory 是一个功能强大、易于使用的大语言模型微调框架。
LlamaFactory 是一个 “一站式”的大模型微调工具包。它基于 PyTorch 和 Hugging Face 生态系统构建,提供了统一的接口和丰富的优化策略,极大地简化了从准备数据到训练模型、再到评估部署的整个微调流程。
LlamaFactory 优点:
-
极其简便易用
-
Web UI 界面:提供了类似 ChatGPT 的图形化界面,你可以通过点击和填写表单来完成模型训练,几乎不需要写代码。
-
命令行接口:对于高级用户,也提供了完善的 CLI 工具,方便集成到自动化流程中。
-
统一配置:通过一个 YAML 或 JSON 配置文件,就能管理所有训练参数、数据路径和模型设置。
-
-
广泛的模型支持
-
支持几乎所有主流的开源大模型家族,包括:
-
LLaMA & LLaMA-2
-
Mistral & Mixtral
-
Qwen(通义千问)
-
Baichuan(百川)
-
ChatGLM
-
Gemma
-
Phi
-
... 以及更多。
-
-
-
高效的训练技术
-
LoRA / QLoRA:核心支持。QLoRA 允许你在单张消费级显卡(如 RTX 3090/4090)上微调大型模型(如 70B),极大地降低了硬件门槛。
-
梯度检查点、混合精度训练:进一步优化显存和训练速度。
-
FSDP:支持多卡分布式训练,充分利用硬件资源。
-
-
丰富的训练方法
-
监督微调:最常用的方法,用于指令遵循、对话等任务。
-
奖励模型训练:为 RLHF 流程准备。
-
PPO 训练:实现强化学习微调。
-
DPO 训练:一种更高效、稳定的直接偏好优化方法。
-
-
强大的数据处理能力
-
支持多种数据格式(JSON, JSONL, CSV等)。
-
内置了对话、指令、文本补全等多种数据模板。
-
可以轻松地将你自己的数据转换成模型可接受的格式。
-
llama-factory参数详解:https://www.cnblogs.com/pass-ion/p/19263097
SFT/DPO/KTO/PPO 对比
| 方法 | 全称 | 核心思路 | 训练范式 | 优势 | 劣势 | 适用场景 |
|---|---|---|---|---|---|---|
| SFT | Supervised Fine-Tuning | 监督微调:用人工标注的 “指令 - 最优回答” 对模型进行有监督训练 | 单阶段监督学习 | 简单易实现、收敛快、数据成本低 | 依赖高质量标注、易产生幻觉 | 基础对齐(模型学会 “听话”) |
| DPO | Direct Preference Optimization | 直接偏好优化:用 “指令 + 多个回答 + 偏好标签” 训练,直接优化偏好排序,无需奖励模型 | 无奖励模型的强化学习 | 训练稳定、无需 RLHF 的奖励建模 | 仅优化两两偏好、依赖高质量对比数据 | 偏好对齐(模型学会 “选更好的”) |
| KTO | Kullback-Leibler Divergence Regularized Optimization | 基于 KL 散度正则的偏好优化:平衡 “偏好对齐” 和 “原模型能力保留”,支持单样本偏好 | 轻量强化学习 | 数据要求低、保留模型原生能力 | 对齐强度弱于 DPO/PPO | 低数据量场景、轻量化对齐 |
| PPO | Proximal Policy Optimization | 近端策略优化:通过 “奖励模型打分 + 策略迭代” 优化模型输出,RLHF 的核心 | 完整 RLHF 流程 | 对齐效果最好、灵活度高 | 训练复杂、易不稳定、成本高 | 高精度对齐(如产品级模型) |
关键补充说明:
- SFT 是基础:所有后续对齐方法(DPO/KTO/PPO)都需要先做 SFT,让模型具备基础的指令遵循能力;
- DPO 替代 RLHF 的核心环节:传统 RLHF 包含 SFT→RM(奖励模型)→PPO 三步,DPO 直接跳过 RM 训练,用对比数据直接优化策略,大幅降低训练成本;
- KTO 是 DPO 的轻量化版本:DPO 要求 “一对对比样本”(好 / 坏回答),KTO 支持 “单样本 + 偏好标签”(如直接标注某回答的偏好分数),数据收集更灵活;
- PPO 是最强但最复杂的:PPO 能动态优化模型输出(每轮生成→打分→更新),但需要训练奖励模型,且易出现 “模式崩溃”(模型只输出少数高分回答)。
sft/PPO监督微调训练集示例:
[ { "instruction": "国际经济与贸易专业的就业前景是怎样的?", "input": "", "output": "国际经济与贸易专业的就业前景较为广阔。随着全球经济一体化的深入发展,国际贸易交流不断增加,对专业人才的需求也日益增长。毕业生可以在跨国公司、国际贸易企业、金融机构以及政府部门等领域找到就业机会。此外,随着国家对外贸易政策的不断调整与改善,国际经济与贸易专业的就业前景也将更加乐观。综合来看,国际经济与贸易专业具有较高的就业率和就业质量,为毕业生提供了良好的职业发展空间。", "history": [ [ "从事国际经济与贸易专业的人可以有哪些工作机会?", "国际经济与贸易专业拥有广泛的就业领域。毕业生可以在进出口公司、物流公司、保险公司、银行中介类货代以及报关员、报检员等职位工作。此外,他们还可以在政府机构如外贸局、外汇局、商检局、海关等部门从事涉外经济贸易的实际业务、管理、调研和宣传策划工作。国际经济与贸易专业还培养了高素质的复合型涉外经贸人才,使他们具备从事国际经贸工作的能力和竞争力。" ] ] }, { "instruction": "列出三种创造性的解决问题的技巧。", "input": "", "output": "1. 头脑风暴: 这种技巧旨在通过鼓励尽可能多的想法来产生新颖的解决方案。与团队成员合作,不管想法多么离奇都应该提出来。最终,团队成员可以一起筛选想法,找到可行的解决方案。\n2. 逆向思维: 这种技巧要求您从问题的根源入手,从结局反推回去。基于这种思想,您可以回顾失败的原因,找到问题的根本所在,并找到更好的解决方案。\n3. 生命周期思考: 这种技巧倡导从全局的角度思考问题。它要求您考虑问题的各个环节,从问题的产生,发展到最终的解决方案。每一个阶段都需要考虑,确保解决方案是全面和持久的。", "history": [] }, { "instruction": "多元化是否更好", "input": "", "output": "多元化更好。\n\n通过多元化,不同的观点、文化、价值观和经验可以在一个社会中得到广泛的表达和交流。多元化可以促进创新和进步,因为它鼓励不同的思维方式和方法的交流和融合。不同的人才和智慧可以相互启发和补充,从而推动社会的发展。\n\n多元化还可以提供更多的选择和机会。在一个多元化的社会中,人们可以自由选择自己感兴趣的事业、教育、生活方式等。这种多样性可以促进个人的发展和幸福感,同时也为社会的进步和繁荣创造更多的机会。\n\n此外,多元化还有助于促进社会的稳定和和谐。在一个多元化的社会中,人们可以更好地理解和尊重彼此的差异,增进相互之间的理解和合作。这有助于减少冲突和分裂,促进社会的和谐和稳定。\n\n总的来说,多元化可以带来更多的创新、选择和机会,同时也有助于社会的稳定和和谐。因此,多元化是更好的选择。", "history": [] }, { "instruction": "了解凤凰国际在外汇市场的发展后,我想知道凤凰国际在哪些方面具有竞争优势?", "input": "", "output": "凤凰国际在外汇市场具有以下竞争优势。首先,凤凰国际拥有丰富的外汇交易经验和专业知识,在外汇市场具有较高的声誉和影响力。其次,凤凰国际提供多种外汇交易产品和服务,满足不同投资者的需求。凤凰国际还采用先进的交易技术和工具,提供稳定、快速的交易执行和高效的客户服务。此外,凤凰国际注重风险管理和合规控制,保护客户的利益和资金安全。通过这些优势,凤凰国际能够在激烈的市场竞争中脱颖而出,吸引更多的投资者选择与之合作。", "history": [ [ "近期有关上海理财博览会的报道称,凤凰国际正在推动外汇新潮流,请问凤凰国际是如何推动外汇市场的发展的? ", "凤凰国际作为一家专业的金融服务机构,通过其在外汇市场的专业知识和丰富经验,致力于推动外汇市场的发展。首先,凤凰国际为投资者提供了丰富的外汇交易产品和服务,包括多种货币对的交易,以满足不同投资者的需求。其次,凤凰国际积极推动外汇市场的创新,引入了先进的交易技术和工具,为投资者提供更便捷、高效的交易体验。此外,凤凰国际还定期举办理财博览会等活动,以促进外汇市场的知识传播和交流,提高投资者的交易技能和风险意识。通过这些举措,凤凰国际积极参与推动外汇市场的发展,为投资者创造更多的投资机会和价值。" ], [ "凤凰国际在推动外汇市场发展的过程中,有没有遇到过哪些挑战?该如何应对这些挑战?", "在推动外汇市场发展的过程中,凤凰国际也面临一些挑战。首先,外汇市场的竞争激烈,凤凰国际需要与其他金融机构竞争,提供更好的产品和服务,吸引更多的投资者。其次,外汇市场的监管和法规也是一个挑战,凤凰国际需要遵循相关法规,确保交易的合规性和安全性。另外,外汇市场的波动性较大,凤凰国际需要有效的风险管理措施,保护客户的资金安全。为了应对这些挑战,凤凰国际注重技术创新和研发投入,提升交易平台的性能和用户体验,同时加强风险管理和合规控制,确保客户的利益和安全。此外,凤凰国际还注重培养专业团队,提供专业化的咨询和服务,以满足客户不断增长的需求。通过这些举措,凤凰国际能够应对挑战,推动外汇市场的稳定发展。" ], [ "近期有关上海理财博览会的报道称,凤凰国际正在推动外汇新潮流,请问凤凰国际是如何推动外汇市场的发展的? ", "凤凰国际作为一家专业的金融服务机构,通过其在外汇市场的专业知识和丰富经验,致力于推动外汇市场的发展。首先,凤凰国际为投资者提供了丰富的外汇交易产品和服务,包括多种货币对的交易,以满足不同投资者的需求。其次,凤凰国际积极推动外汇市场的创新,引入了先进的交易技术和工具,为投资者提供更便捷、高效的交易体验。此外,凤凰国际还定期举办理财博览会等活动,以促进外汇市场的知识传播和交流,提高投资者的交易技能和风险意识。通过这些举措,凤凰国际积极参与推动外汇市场的发展,为投资者创造更多的投资机会和价值。" ], [ "凤凰国际在推动外汇市场发展的过程中,有没有遇到过哪些挑战?该如何应对这些挑战?", "在推动外汇市场发展的过程中,凤凰国际也面临一些挑战。首先,外汇市场的竞争激烈,凤凰国际需要与其他金融机构竞争,提供更好的产品和服务,吸引更多的投资者。其次,外汇市场的监管和法规也是一个挑战,凤凰国际需要遵循相关法规,确保交易的合规性和安全性。另外,外汇市场的波动性较大,凤凰国际需要有效的风险管理措施,保护客户的资金安全。为了应对这些挑战,凤凰国际注重技术创新和研发投入,提升交易平台的性能和用户体验,同时加强风险管理和合规控制,确保客户的利益和安全。此外,凤凰国际还注重培养专业团队,提供专业化的咨询和服务,以满足客户不断增长的需求。通过这些举措,凤凰国际能够应对挑战,推动外汇市场的稳定发展。" ], [ "凤凰国际作为金融服务机构,如何保护客户的资金安全?", "凤凰国际非常重视客户的资金安全,采取了多种措施来保护客户的资金。首先,凤凰国际与知名的银行和支付机构合作,建立了安全可靠的资金结算通道。客户的资金会被存放在独立的专门账户中,并且与凤凰国际的运营资金进行了严格的隔离管理。其次,凤凰国际采用了先进的加密技术,确保客户的交易和资金信息在传输过程中的安全性。同时,凤凰国际还定期进行安全审计和风险评估,保证系统的安全性和稳定性。此外,凤凰国际还严格遵守相关的法规和监管要求,对客户的身份信息进行认证和保护,防止资金洗钱和其他非法活动。通过这些措施,凤凰国际确保客户的资金安全,为客户提供可靠的交易环境。" ] ] } ]
rm训练集(奖励模型)示例:
绝对分值格式:
[ { "instruction": "解释什么是机器学习", "response": "机器学习是人工智能的一个分支,它使计算机系统能够从数据中学习和改进,而无需明确编程。通过算法分析数据、识别模式并做出预测或决策。", "score": 4.8 }, { "instruction": "如何泡一杯好茶?", "response": "首先选择优质茶叶,烧开水至适当温度(绿茶80°C,红茶95°C),预热茶具,按比例放入茶叶,注水后根据茶类控制浸泡时间,最后享用。", "score": 4.5 }, { "instruction": "Python中如何读取CSV文件?", "response": "可以使用pandas库:import pandas as pd; df = pd.read_csv('file.csv')。或者使用csv模块:import csv; with open('file.csv') as f: reader = csv.reader(f)。", "score": 4.9 } ]
训练逻辑:模型输入 instruction + response,输出一个标量分数,损失函数为「预测分数 - 真实分数」的均方误差(MSE),让模型学会给优质回答打高分。
对比成对格式:
[ { "instruction": "如何缓解胃痛?", "input": "胃疼有什么快速缓解的方法?", "chosen": "可以尝试喝温水、避免油腻食物,如果持续疼痛建议就医。", "rejected": "忍着就行了。" }, { "instruction": "什么是失眠?", "input": "失眠有哪些表现?", "chosen": "失眠通常指难以入睡或保持睡眠,导致白天疲劳。", "rejected": "失眠就是不想睡。" }, { "instruction": "如何预防骨质疏松?", "input": "骨质疏松该怎么预防?", "chosen": "建议摄入足够钙和维生素D,并进行适度负重运动。", "rejected": "骨质疏松无法预防。" } ]
训练逻辑:模型分别计算 chosen 和 rejected 的分数,损失函数要求「chosen 分数 - rejected 分数 > 阈值」,只需学会 “谁更好”,无需精确分数;
DPO训练集示例:
[ { "instruction": "如何缓解胃痛?", "input": "胃疼有什么快速缓解的方法?", "chosen": "可以尝试喝温水、避免油腻食物,如果持续疼痛建议就医。", "rejected": "忍着就行了。" }, { "instruction": "什么是失眠?", "input": "失眠有哪些表现?", "chosen": "失眠通常指难以入睡或保持睡眠,导致白天疲劳。", "rejected": "失眠就是不想睡。" }, { "instruction": "如何预防骨质疏松?", "input": "骨质疏松该怎么预防?", "chosen": "建议摄入足够钙和维生素D,并进行适度负重运动。", "rejected": "骨质疏松无法预防。" } ]
KTO 数据集示例:
[ { "messages": [ { "content": "The Federal Trade Commission is going after spyware, bits of computer code that install themselves on the computers of Internet users to track or disrupt their online activities.\nQ: Which is the best summary of this article?\nPick your answer from:\n(A). World\n(B). Sports\n(C). Business\n(D). Science/Tech\nI think the answer is", "role": "user" }, { "content": "Ooh ooh ah ah! *giggle* Let me think... Ooh ooh ah ah! *giggle* The best summary of this article is... *drumroll*... D! Science/Tech! Yay! *confetti* The Federal Trade Commission is talking about spyware, which is like a little computer bug that can watch what you do on your computer without you knowing. It's like a secret agent, but not a nice one! *gasp* The FTC wants to stop the spyware from doing its thing, so they're going after it! *cheer* Woohoo!", "role": "assistant" } ], "label": true }, { "messages": [ { "content": "Compare and contrast the roles of the hippocampus and the prefrontal cortex in the human brain, discussing their involvement in memory processing and decision making.", "role": "user" }, { "content": "The human brain is a highly complex organ, responsible for a myriad of cognitive functions, including memory processing and decision making. Two critical regions implicated in these processes are the hippocampus and the prefrontal cortex. While both structures play significant roles in these cognitive domains, they each contribute distinct functions that work in concert to facilitate our ability to navigate the world and make informed choices.\n\nThe hippocampus, located within the medial temporal lobe, is predominantly associated with the formation, consolidation, and retrieval of memories. Specifically, it plays a crucial role in episodic memory, which encompasses the storage and recollection of autobiographical events, as well as spatial memory, which pertains to the encoding and retrieval of spatial information. The hippocampus is vital for the formation of new memories and the integration of these memories into existing knowledge structures. It has been demonstrated that damage to the hippocampus can result in anterograde amnesia, a condition characterized by an inability to form new memories, while leaving previously consolidated memories intact.\n\nIn contrast, the prefrontal cortex, situated in the anterior portion of the frontal lobes, is primarily involved in executive functions, which include higher-order cognitive processes such as decision making, planning, reasoning, and inhibitory control. The prefrontal cortex is responsible for integrating information from various sources, evaluating potential outcomes, and selecting the most advantageous course of action. It is also implicated in working memory, which refers to the temporary storage and manipulation of information necessary for complex cognitive tasks. Damage to the prefrontal cortex can result in deficits in decision making, impulsivity, and poor judgment.\n\nWhile the hippocampus and prefrontal cortex have distinct roles, they are interconnected and work synergistically to facilitate memory processing and decision making. The hippocampus provides the prefrontal cortex with contextual information and episodic memories that inform decision-making processes. Conversely, the prefrontal cortex can modulate the hippocampus's activity during memory encoding and retrieval, influencing the salience and organization of memories. This dynamic interplay between the two regions enables individuals to adapt their decision-making strategies based on past experiences and contextual information.\n\nIn summary, the hippocampus and prefrontal cortex are integral to memory processing and decision making, albeit with distinct contributions. The hippocampus is primarily implicated in the formation, consolidation, and retrieval of episodic and spatial memories, while the prefrontal cortex is responsible for executive functions, including decision making, planning, and working memory. The interplay between these two regions allows for the integration of past experiences and contextual information in guiding informed decision making and shaping our behavior.", "role": "assistant" } ], "label": true }, { "messages": [ { "content": "How would you identify potential customers for a new product?", "role": "user" }, { "content": "To identify potential customers for a new product, the following steps can be taken:\n\n1. Analyze the target market: The first step in identifying potential customers is to analyze the target market for the new product. This includes researching the characteristics, needs, and behaviors of the consumers that the product is aimed at.\n\n2. Create a buyer persona: A buyer persona is a detailed description of the ideal customer for the product. It includes information on demographics, interests, behavior, pain points, and motivations. Creating a buyer persona will help narrow down the target audience and focus marketing efforts.\n\n3. Use online analytics tools: Online analytics tools such as Google Analytics can provide insights into the behavior and interests of website visitors. This data can be used to identify potential customers by analyzing their behavior on the site and the types of content they engage with.\n\n4. Monitor social media: Social media platforms are a great source of information on potential customers. By monitoring conversations and mentions of the product or related topics, businesses can identify potential customers and engage with them.\n\n5. Conduct surveys and focus groups: Getting direct feedback from potential customers can be extremely valuable. Surveys and focus groups can provide insights into customer needs and interests, and can help businesses identify potential customers and tailor their marketing efforts accordingly.\n\nIn summary, identifying potential customers for a new product requires careful analysis of the target market, the creation of a buyer persona, the use of analytics tools, social media monitoring, and direct feedback from consumers. All these steps combined will provide the best chance of finding and reaching potential customers for the new product.", "role": "assistant" } ], "label": false } ]
PPO训练流程
步骤 1:初始化基础模型
- 以SFT 微调后的模型为初始策略(Policy),保证模型已有基础的指令遵循能力;
- 同时初始化一个 “旧策略模型”(Old Policy),用于计算策略更新的概率比值(rt(θ)),每轮更新后同步新旧策略。
步骤 2:模型生成回答(Rollout 阶段)
- 输入一批 SFT 格式的指令(
instruction + input),让当前策略模型生成回答; - 记录生成过程中的每一步 token 的对数概率(log_probs),用于后续计算策略梯度;
- 生成的回答会被截断 / 补齐到固定长度,保证批量训练的效率。
步骤 3:奖励模型打分(Reward 计算)
- 将 “指令 + 生成的回答” 输入奖励模型(RM),得到原始奖励分数;
- 为了稳定训练,会对奖励分数做两项处理:
- 基线修正:减去批次内奖励分数的均值,得到相对优势(避免所有回答都是高分 / 低分导致梯度消失);
- KL 散度惩罚:加上 −β × KL(pnew∣∣pold),限制模型偏离原始能力(β 通常取 0.05),防止 “模式崩溃”。
- 最终用于训练的奖励 = 原始 RM 分数 - 批次均值 + KL 惩罚。
步骤 4:PPO 策略更新(Optimization 阶段)
- 计算优势函数(Advantage):
- 采用 GAE(Generalized Advantage Estimation)方法,融合即时奖励和未来奖励,计算每个 token 的优势值 A^t;
- 优势函数衡量 “当前 token 的选择比平均水平好多少”,是 PPO 损失的核心输入。
- 计算裁剪的 PPO 损失:
- 计算新策略与旧策略的概率比值 rt(θ)=pold(token∣context) / pnew(token∣context);
- 对 rt(θ) 进行裁剪(限制在 [0.8, 1.2] 之间),避免更新幅度过大;
- 损失函数取 “原始损失” 和 “裁剪后损失” 的最小值,保证更新的保守性;
- 同时加入价值函数(Value Function)损失(预测奖励分数的 MSE),辅助稳定训练。
步骤 5:迭代与收敛
- 每轮更新后,用新策略覆盖旧策略(或软更新,如 Polyak 平均);
- 重复 “生成→打分→更新” 流程,直到奖励分数不再提升或达到预设迭代次数。

浙公网安备 33010602011771号