1. Project Overview & Quickstart (PaddlePaddle/PaddleFormers)
File: README.md
最新更新 | 特性 | 安装 | 快速体验 | 社区交流
PaddleFormers
📝简介
PaddleFormers 是基于百度深度学习框架 PaddlePaddle 搭建的 Transformers 库,旨在为 PaddlePaddle 生态提供与 Hugging Face Transformers 项目对等的模型接口与功能体验,支持大语言模型(LLM)与视觉语言模型(VLM)的训练能力。PaddleFormers 充分发挥 PaddlePaddle 在高性能训练方面的内置优势,全面支持包括张量并行、流水线并行和专家并行在内的主流大模型分布式训练策略,以及自动混合精度等加速技术,在 DeepSeek-V4、GLM-4.5-Air 等重点模型上,训练性能明显超越 Megatron-LM ,实现了高效的预训练与后训练性能。
结合业界主流优化方法与飞桨在业务实践中积累的高效特性,PaddleFormers 致力于打造高性能、低资源占用的训练体验,帮助用户高效便捷地完成大模型训练,而无需关注底层复杂的优化细节。
🆕最新更新
[!IMPORTANT]
PaddleFormers v1.2 发布 — 业界率先实现对 DeepSeek-V4 大规模分布式训练的全面支持! 查看训练实践 →
- 2026.06.19 - PaddleFormers v1.2 正式发布!这个版本我们支持了 DeepSeek-V4 系列模型128K 以上的长文训练。DeepSeek-V4 作为业界领先的开源 MoE 模型,其全新的 CSA+HCA 混合注意力、mHC 残差连接、Muon 优化器等架构创新对训练框架提出了极高要求。我们从训练策略、模型结构到通信算子进行了全栈适配:支持 Document Mask、Packing 数据流 以及 CP(上下文并行)等高效训练策略,新增 FlashMLA 高性能注意力算子、高度融合的高性能 FP8 MoE 模块、DeepEP/HybridEP 专家并行通信库、TileLang 融合算子以及 MoE Auto-Subbatch 显存动态负载均衡能力,实现了 DeepSeek-V4 模型的高效预训练、中训练和 SFT 训练能力。此外,本版本也对 DeepSeek-V3.2 和 Qwen3.5 系列模型训练进行了支持。
- 2026.03.31 - PaddleFormers v1.1 正式发布!在这个版本中我们支持了 GLM-4.5 系列模型的单步与多步 MTP 训练能力。依托 MTP 架构优势,开发者可显著提升推理效率;同时针对 MTP 模块训练场景,我们新增主干网络冻结开关,灵活满足各类模型精细化调优需求。此外,我们对视觉理解类模型进行了深度优化,Qwen3-VL 30B-A3B 模型性能相比上个版本提升48%,领先 Megatron-LM 6%。
- 2026.01.21 - PaddleFomers v1.0版本发布啦!我们提供了针对 LLM 和 VLM 等模型的训练能力,针对 DeepSeek-V3模型和 GLM-4.5-Air 等重点模型,我们实现了极致性能优化(训练性能明显超越 Megatron-LM )。针对 PaddleOCR-VL,我们在昆仑芯 P800、天数天垓150等国产计算芯片上进行了适配,更好的满足国内用户需求。
✨特性
- 丰富的模型支持: PaddleFormers 实现了对于 100+ 主流的大语言模型和视觉语言模型的训练能力支持,涵盖了 DeepSeek-V3、GLM-4.5系列、Qwen2和 Qwen3系列、Qwen3-VL 等前沿模型。同时提供了对 ERNIE-4.5、ERNIE-4.5-VL、PaddleOCR-VL 等文心系列模型完备的训练能力。
- 高性能组网实现: 实现了 FP8低精度训练与高性能算子优化、通信计算重叠优化、精细化存算均衡等策略,大幅提升大模型训练的计算、通信和存储效率。在 DeepSeek-V3、GLM-4.5-Air 等模型上,训练性能明显超越 Megatron-LM。
- 全流程能力支持: PaddleFormers 实现了从预训练到后训练的全流程训练能力支持,其中后训练支持 CPT / SFT / SFT-LoRA / DPO / DPO-LoRA 等主流能力,帮助用户高效、便捷地完成大模型的迭代与优化。PaddleFormers 还实现了对 Safetensors 格式的 全面支持 ,训练完成的模型,其存储格式与 Hugging Face 上托管的权重格式一致,可以在任意支持该格式的框架或工具中使用(如 FastDeploy / vLLM / SGLang 等)。
- 完备的训练能力支持: PaddleFormers 实现了对于 Function Call 、 Thinking 等大模型前沿能力的训练支持,并通过 Data Packing 、 Padding Free 等数据流技术显著优化训练性能。
- 国产芯片深度适配: 支持昆仑芯 P800、天数天垓150、沐曦 C550等国产计算平台,基于128卡昆仑芯 P800支持 DeepSeek V3的 SFT,成为最少国产算力资源后训练方案。
📋模型列表
| 模型类型 | 模型系列 | 模型名称 | Chat Template |
|---|---|---|---|
| LLM | DeepSeekv3 | deepseek-ai/DeepSeek-V3-Base、deepseek-ai/DeepSeek-V3、deepseek-ai/DeepSeek-V3-0324 | deepseek3 |
| DeepSeekv3.2 | deepseek-ai/DeepSeek-V3.2 | deepseek3 | |
| DeepSeekv4 | deepseek-ai/DeepSeek-V4-Pro、deepseek-ai/DeepSeek-V4-Flash | deepseek3 | |
| 🏛️ERNIE-4.5 | baidu/ERNIE-4.5-0.3B-Base-PT、baidu/ERNIE-4.5-0.3B-PT、baidu/ERNIE-4.5-21B-A3B-Base-PT、baidu/ERNIE-4.5-21B-A3B-PT、baidu/ERNIE-4.5-300B-A47B-Base-PT、baidu/ERNIE-4.5-300B-A47B-PT、baidu/ERNIE-4.5-21B-A3B-Thinking | ernie、ernie_nothink | |
| gemma3 | google/gemma-3-270m、google/gemma-3-270m-it、google/gemma-3-1b-pt、google/gemma-3-1b-it、google/gemma-3-4b-pt、google/gemma-3-4b-it、google/gemma-3-12b-pt、google/gemma-3-12b-it、google/gemma-3-27b-pt、google/gemma-3-27b-it | gemma | |
| GLM-4.5 | zai-org/GLM-4.5-Air-Base、zai-org/GLM-4.5-Air、zai-org/GLM-4.5-Base、zai-org/GLM-4.5 | glm4_moe | |
| gpt-oss | openai/gpt-oss-20b、openai/gpt-oss-120b | gpt | |
| Granite | ibm-granite/granite-3.2-2b-base、ibm-granite/granite-3.2-2b-instruct、ibm-granite/granite-3.2-8b-base、ibm-granite/granite-3.2-8b-instruct | granite | |
| Llama-3 | meta-llama/Meta-Llama-3-8B、meta-llama/Meta-Llama-3-8B-Instruct、meta-llama/Meta-Llama-3-70B、meta-llama/Meta-Llama-3-70B-Instruct、meta-llama/Llama-3.1-8B、meta-llama/Llama-3.1-8B-Instruct、meta-llama/Llama-3.1-70B、meta-llama/Llama-3.1-70B-Instruct、meta-llama/Llama-3.1-405B、meta-llama/Llama-3.1-405B-Instruct、meta-llama/Llama-3.2-1B、meta-llama/Llama-3.2-1B-Instruct、meta-llama/Llama-3.2-3B、meta-llama/Llama-3.2-3B-Instruct、meta-llama/Llama-3.3-70B-Instruct | llama3 | |
| OLMo2 | allenai/OLMo-2-0425-1B、allenai/OLMo-2-0425-1B-SFT、allenai/OLMo-2-0425-1B-DPO、allenai/OLMo-2-0425-1B-Instruct、allenai/OLMo-2-1124-7B、allenai/OLMo-2-1124-7B-SFT、allenai/OLMo-2-1124-7B-DPO、allenai/OLMo-2-1124-7B-Instruct、allenai/OLMo-2-1124-13B、allenai/OLMo-2-1124-13B-SFT、allenai/OLMo-2-1124-13B-DPO、allenai/OLMo-2-1124-13B-Instruct、allenai/OLMo-2-0325-32B、allenai/OLMo-2-0325-32B-SFT、allenai/OLMo-2-0325-32B-DPO、allenai/OLMo-2-0325-32B-Instruct | jinja | |
| phi-4 | microsoft/phi-4 | phi4 | |
| Qwen2 | Qwen/Qwen2-0.5B、Qwen/Qwen2-0.5B-Instruct、Qwen/Qwen2-1.5B、Qwen/Qwen2-1.5B-Instruct、Qwen/Qwen2-7B、Qwen/Qwen2-7B-Instruct、Qwen/Qwen2-57B-A14B、Qwen/Qwen2-57B-A14B-Instruct、Qwen/Qwen2-72B、Qwen/Qwen2-0.5B-Instruct | qwen | |
| Qwen3 | Qwen/Qwen3-0.6B-Base、Qwen/Qwen3-0.6B、Qwen/Qwen3-1.7B-Base、Qwen/Qwen3-1.7B、Qwen/Qwen3-4B-Base、Qwen/Qwen3-4B、Qwen/Qwen3-4B-Instruct-2507、Qwen/Qwen3-4B-Thinking-2507、Qwen/Qwen3-8B-Base、Qwen/Qwen3-8B、Qwen/Qwen3-14B-Base、Qwen/Qwen3-14B、Qwen/Qwen3-32B、Qwen/Qwen3-30B-A3B-Base、Qwen/Qwen3-30B-A3B、Qwen/Qwen3-30B-A3B-Instruct-2507、Qwen/Qwen3-30B-A3B-Thinking-2507、Qwen/Qwen3-235B-A22B、Qwen/Qwen3-235B-A22B-Instruct-2507、Qwen/Qwen3-235B-A22B-Thinking-2507 | qwen3、qwen3_nothink | |
| Qwen3-Next | Qwen/Qwen3-Next-80B-A3B-Instruct、Qwen/Qwen3-Next-80B-A3B-Thinking | qwen3、qwen3_nothink | |
| Qwen3.5 | Qwen/Qwen3.5-MoE | qwen3_5、qwen3_5_nothink | |
| VLM | 🏛️ERNIE-4.5-VL | baidu/ERNIE-4.5-VL-28B-A3B-Base-PT、baidu/ERNIE-4.5-VL-28B-A3B-PT、baidu/ERNIE-4.5-VL-424B-A47B-Base-PT、baidu/ERNIE-4.5-VL-424B-A47B-PT、baidu/ERNIE-4.5-VL-28B-A3B-Thinking | ernie_vl、ernie_vl_nothink |
| 🏛️PaddleOCR-VL | PaddlePaddle/PaddleOCR-VL | paddleocr_vl | |
| Qwen2.5-VL | Qwen/Qwen2.5-VL-3B-Instruct、Qwen/Qwen2.5-VL-7B-Instruct、Qwen/Qwen2.5-VL-32B-Instruct、Qwen/Qwen2.5-VL-72B-Instruct | qwen2_vl | |
| Qwen3-VL | Qwen/Qwen3-VL-2B-Instruct、Qwen/Qwen3-VL-2B-Thinking、Qwen/Qwen3-VL-4B-Instruct、Qwen/Qwen3-VL-4B-Thinking、Qwen/Qwen3-VL-8B-Instruct、Qwen/Qwen3-VL-8B-Thinking、Qwen/Qwen3-VL-32B-Instruct、Qwen/Qwen3-VL-32B-Thinking、Qwen/Qwen3-VL-30B-A3B-Instruct、Qwen/Qwen3-VL-30B-A3B-Thinking、Qwen/Qwen3-VL-235B-A22B-Instruct、Qwen/Qwen3-VL-235B-A22B-Thinking | qwen3_vl、qwen3_vl_nothink |
- 更多关于模型训练能力的支持细节,请参考:PaddleFormers 模型能力矩阵
- 带有🏛️标签的模型是 PaddleFormers 官方维护的模型
💾安装
环境依赖
- python ≥ 3.12
- CUDA ≥ 13.0
- PaddleFleet ≥ 0.3(仅为 GPU 训练功能依赖)
安装依赖(GPU)
基于 Docker 容器的方式(推荐)
为了避免本地环境存在较多冲突,我们建议使用 PaddleFormers 的预置镜像来准备环境,容器中已经拉取了 PaddleFormers 仓库并完成了安装:
shell# 以cuda12.6为例 docker run --gpus all --name paddleformers-work -v $(pwd):/work \ -w=/work --shm-size=512G --network=host -it \ ccr-2vdh3abv-pub.cnc.bj.baidubce.com/paddlepaddle/paddle:3.3.0-gpu-cuda12.6-cudnn9.5 /bin/bash # cuda12.9镜像:ccr-2vdh3abv-pub.cnc.bj.baidubce.com/paddlepaddle/paddle:3.3.0-gpu-cuda12.9-cudnn9.9 # cuda13.0镜像:ccr-2vdh3abv-pub.cnc.bj.baidubce.com/paddlepaddle/paddle:3.3.0-gpu-cuda13.0-cudnn9.13
基于 pip/源码的安装方式
我们推荐使用
conda/venv/uv等虚拟环境工具管理 python 环境。shell# conda conda create -n paddleformers-work python=3.10 #支持python3.10~3.13 conda activate paddleformers-work # venv python -m venv .paddleformers-work source .paddleformers-work/bin/activate # uv uv venv .paddleformers-work source .paddleformers-work/bin/activate
安装方案一: 拉取源码安装
shell# Install development version git clone https://github.com/PaddlePaddle/PaddleFormers.git cd PaddleFormers # cuda12.6 python -m pip install -e '.[paddlefleet]' --extra-index-url https://www.paddlepaddle.org.cn/packages/nightly/cu126/ --extra-index-url https://www.paddlepaddle.org.cn/packages/stable/cu126/ # cuda12.9 # python -m pip install -e '.[paddlefleet]' --extra-index-url https://www.paddlepaddle.org.cn/packages/nightly/cu129/ --extra-index-url https://www.paddlepaddle.org.cn/packages/stable/cu129/ # cuda13.0 # python -m pip install -e '.[paddlefleet]' --extra-index-url https://www.paddlepaddle.org.cn/packages/nightly/cu130/ --extra-index-url https://www.paddlepaddle.org.cn/packages/stable/cu130/
安装方案二: 如果您不想拉取源码,可以基于下面的命令安装 PaddleFormers 和 PaddleFleet。
shell# Install via pip # cuda12.6 python -m pip install "paddleformers[paddlefleet]" --extra-index-url https://www.paddlepaddle.org.cn/packages/stable/cu126/ # cuda12.9 # python -m pip install "paddleformers[paddlefleet]" --extra-index-url https://www.paddlepaddle.org.cn/packages/stable/cu129/ # cuda13.0 # python -m pip install "paddleformers[paddlefleet]" --extra-index-url https://www.paddlepaddle.org.cn/packages/stable/cu130/
安装方案三: 如果您只需使用 tokenizer 或者 processor,可以通过以下命令安装,这种情况下不会安装训练相关的依赖,安装速度更加快。
shellpython -m pip install paddleformers
安装依赖(XPU & ILUVATAR-GPU & Metax GPU)
⚡快速体验
PaddleFormers 在 API 设计上与 Hugging Face Transformers 保持了高度一致,使用示例如下:
使用 tokenizer
from paddleformers.transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B-Base")
print(tokenizer.encode("中华人民共和国"))
# 中华人民共和国将会被编码为两个token:
# [105492, 104773]文本生成
from paddleformers.transformers import AutoTokenizer, AutoModelForCausalLM
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B-Base")
model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-0.6B-Base", dtype="bfloat16").eval()
input_features = tokenizer("请给我一段大模型的简短介绍:", return_tensors="pd")
outputs = model.generate(**input_features, max_new_tokens=256)
output_ids = outputs[0].tolist()[0]
print(tokenizer.decode(output_ids, skip_special_tokens=True))模型训练
paddleformers-cli train ./examples/config/sft/full.yaml📊数据处理
🚀模型训练 & 部署
- PaddleFormers 命令行工具
- 训练参数配置说明
- 基于 PaddleFormers 进行模型预训练/后预训练
- 基于 PaddleFormers 进行指令微调(SFT & LoRA)
- 基于 PaddleFormers 进行偏好对齐(DPO & LoRA)
- 基于 FastDeploy / vLLM 部署模型
💻多硬件使用
🔍最佳实践
- 基于 DeepSeekv3的高效预训练
- 基于 ERNIE-4.5的高效预训练
- 训练一个偏好 Emoji 输出的对齐模型
- 训练一个支持思考能力的模型
- 训练一个支持 Function Call 能力的模型
- 基于 PaddleOCR-VL 微调实现孟加拉语识别能力
- 训练一个支持 Grounding 的模型
➕其他
💬社区相关
贡献代码
- 欢迎社区用户为 PaddleFormers 贡献代码,详情请参考 贡献指南。
和我们交流
- 微信扫描二维码并填写问卷,即可加入交流群与众多社区开发者以及官方团队深度交流.
🙏致谢
我们借鉴了 Hugging Face 的Transformers🤗关于预训练模型使用的优秀设计,在此对 Hugging Face 作者及其开源社区表示感谢。
📜许可证
PaddleFormers 遵循Apache-2.0开源协议。
File: docs/zh/chat_template_guide.md
1. 背景说明
大语言模型依托对话交互能力,能够输出符合人类语境的智能回复。而这一能力需依托 **Chat Template **结构化标注角色与上下文,定义多轮对话数据如何被转换为模型可训练的 token 序列,从而确保交互逻辑精准。
**Chat Template ** 规定了:
不同角色(如
system / user / assistant)的拼接方式特殊 token(如 BOS / EOS / role token)的插入规则
哪些 token 参与 loss 计算(label / mask 规则)
2. 使用说明
PaddleFormers 内置了常用模型的默认 Chat Template,普通用户无需额外开发,在训练配置中指定使用即可,如 qwen3:
template_backend: custom
template: qwen3值得注意的是,哪怕是同一系列的模型,在不同训练任务(如 思考模型和非思考模型)对 label 和 mask 的策略也存在差异,务必确保为对应的模型设置正确的 Chat Template,使用不匹配的 Chat Template 可能导致:
训练不收敛或效果明显下降
对话边界学习错误
推理阶段输出异常
在模型列表中,我们给出了不同模型训练时所需使用的 Template,在训练时请按照表格所建议的 Template 进行设置。
3. 自定义新的 Template
在以下情况中,您可能想要使用自己定义的 Chat Template:
希望自定义对话格式或特殊 token 规则
新增或接入框架尚未内置的新模型
需要调整 label / mask 行为(如特殊 EOS、packing 场景)
在这些情况下,您需要显式注册 Chat Template,以确保模型输入格式与训练目标一致。
对于未注册的情况,框架将使用对应模型的默认模板。
3.1. 注册方法
在 paddleformers/datasets/template/template.py 文件中实现模型 chat template 的注册,如:
register_template(
name="glm4_moe",
format_user=StringFormatter(slots=["<|user|>\n{{content}}<|assistant|>\n"]),
format_assistant=StringFormatter(slots=["\n{{content}}"]),
format_system=StringFormatter(slots=["[gMASK]<sop><|system|>\n{{content}}"]),
format_function=FunctionFormatter(slots=["{{content}}"], tool_format="glm4_moe"),
format_observation=StringFormatter(slots=["<|observation|>\n{{content}}<|assistant|>"]),
format_tools=ToolFormatter(tool_format="glm4_moe"),
format_prefix=EmptyFormatter(slots=["[gMASK]<sop>"]),
suffix=["<|user|>"],
thought_words=("", ""),
template_class=ReasoningTemplate,
)3.2. 参数说明
| 参数名 | 解释 |
|---|---|
name |
template 的名字,也就是训练的时候需要指定的 template 参数 |
format_user |
对 role 为 user 的 content 进行 format,{{content}}表示塞入实际的 content,其他为拼接的 token |
format_assistant |
对 role 为 assistant 的 content 进行 format |
format_system |
对 role 为 system 的 content 进行 format |
format_function |
对 role 为 function(申请工具调用)的 content 进行 format |
format_observation |
对 role 为 observation(工具返回信息)的 content 进行 format |
format_tools |
对 tools 信息进行 format |
format_prefix |
在格式化后最开头固定添加的内容 |
default_system |
默认的 system 信息,如果数据里面没有 role 为 system 的,就用这个 |
chat_sep |
历史轮对话末尾加的字符串 |
suffix |
默认为 eos token,在多轮对话的最后面添加 |
efficient_eos |
suffix 是否有效,即是否在最后拼接 suffix token |
auto_add_bos |
设置为 true 的时候,如果 bos 没添加,会自动添加上 |
thought_words |
数据里面的思考标志是什么,比如 |
enable_thinking |
否的话,会把思考信息删掉(当 template_class 选 ReasoningTemplate 时候生效) |
mm_plugin |
使用什么插件来处理多模信息 |
grounding_plugin |
使用什么插件来处理 grounding 任务的 target 信息 |
template_class |
template 类,可以选 Template 或 ReasoningTemplate,ReasoningTemplate 一般是思考模型会用的,会根据 enable_thinking 决定是否删除思考信息 |
3.3. 多模态处理(注册 mm_plugin)
多模模型需要实现自己的多模数据处理方法,包括图片处理、视频处理、音频处理、获取处理后的 tokens 数量来填充占位符
具体实现方式可以参考 Qwen2VLPlugin 类
3.3.1. 多模数据下载(选做)
在基类 MMPluginMixin 中,PaddleFormers 已经为大家实现了最基本的数据下载函数:
_regularize_images:负责图片数据下载_regularize_videos:负责视频数据下载和抽帧_regularize_videos:负责音频数据下载(暂未实现)
若大家有定制化的数据下载需求,只需重写对应的处理函数即可
3.3.2. 多模数据预处理(选做)
在基类 MMPluginMixin 中,PaddleFormers 已经为大家实现了最基本的多模数据预处理函数:_get_mm_inputs
在 _get_mm_inputs 中,PaddleFormers 会调用多模 processor 来处理对应模态的数据,并返回处理结果
若大家有定制化的数据预处理需求,只需重写 _get_mm_inputs 函数即可
3.3.3. 多模 token 拼接(必做)
PaddleFormers 需要重写 process_messages 函数来实现 template 中多模 token 的拼接逻辑。
在模型的 template 中,各个模态的数据会有各自的占位符,图片数据通常使用占位符 `` ,视频数据通常使用占位符 <video> ,音频数据通常使用占位符 <audio> 。在 process_messages 函数中,PaddleFormers 需要将每个占位符替换为对应数量的多模 token。
以 Qwen2VLPlugin 中对图片 token 的处理为例:
# ... 省略前序处理逻辑
for message in messages: # 遍历messages中的每一轮对话
content = message["content"] # 获取每轮对话的内容
while IMAGE_PLACEHOLDER in content: # 当对话内容中存在图片占位符时
image_seqlen = (
image_grid_thw[num_image_tokens].prod().item() // merge_length if self.expand_mm_tokens else 1
) # 根据image_grid_thw计算图片token的个数
content = content.replace(
IMAGE_PLACEHOLDER,
f"{self.vision_bos_token}{self.image_token * image_seqlen}{self.vision_eos_token}",
1,
) # 将图片占位符替换为对应的多模special tokens
num_image_tokens += 1
# ... 省略后续处理逻辑3.3.4. mm_plugin 注册
类实现后在下面注册:
PLUGINS = {
"base": BasePlugin,
"qwen2_vl": Qwen2VLPlugin,
"qwen3_vl": Qwen3VLPlugin,
"glm4v": GLM4VPlugin,
}3.3.5. template 注册
mm_plugin 注册完后,还需要在 template 中注册:
register_template(
name="qwen2_vl",
...
mm_plugin=get_mm_plugin(name="qwen2_vl", image_token="<|image_pad|>", video_token="<|video_pad|>"),
)其中,name需要填入在PLUGINS中注册的key名,image_token、video_token、audio_token为模型各模态的 special token。
3.4 示例
如果模型的 chat template 为:
<s>user prompt here
<model>model response here</s>
user prompt here
<model>model response here</s>对应的 register_template 为:
register_template(
name="custom",
format_user=StringFormatter(slots=["{{content}}\n<model>"]),
format_assistant=StringFormatter(slots=["{{content}}"]),
format_prefix=EmptyFormatter("<s>"),
chat_sep="</s>\n",
suffix="</s>",
)3.5 查看 Template 处理效果
在进行 sft 训练的时候,打开 FLAGS_enable_dataset_debug,即可打印 decode 之后的 input_ids 和 label,如:
查看打印的 input 和 labels 是否符合预期来确认 template 实现是否正确
4. 推理使用说明
训练阶段自定义注册的 template 必须与推理阶段保持一致,确保相同输入在两阶段生成完全一致的 token。否则将导致训练与推理输入不一致,影响模型实际推理表现。
具体方法:您可以使用 huggingface 提供的 https://huggingface.co/spaces/huggingfacejs/chat-template-playground 测试该模型 template 对数据渲染后的结果,与打开 FLAGS_enable_dataset_debug 后打印的训练数据进行对比,如果不一致,需要调整自定义的 template 或 plugin。
File: docs/zh/cli_usage.md
1. 命令行界面
1.1. 概述
PaddleFormers CLI(Command Line Interface)提供了基于终端的程序交互,通过配置文件来管理各类参数,高效灵活地执行模型训练、推理和评估任务。
1.2. 快速入门
安装
参考README 文档进行 paddleformers 安装
验证安装:
paddleformers-cli help预期输出:
------------------------------------------------------------
| Usage: |
| paddleformers-cli train : model finetuning |
| paddleformers-cli export : model export |
| paddleformers-cli help: show helping info |
------------------------------------------------------------AI 计算卡配置
默认情况下,CLI 中使用所有可用的 AI 计算卡。
如果您想指定特定的计算卡,请在运行 CLI 之前设置对应的环境变量。
对于英伟达 GPU 或者天数智芯计算卡,通过以下环境变量进行设置:
# Single GPU / Iluvatar GPU
export CUDA_VISIBLE_DEVICES=0
# Multi GPUs / Iluvatar GPUs
export CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7对于昆仑芯计算卡,通过以下环境变量进行设置:
# Single XPU
export XPU_VISIBLE_DEVICES=0
# Multi XPUs
export XPU_VISIBLE_DEVICES=0,1,2,3,4,5,6,71.3. CLI 具体用法
以下环节使用 Qwen/Qwen3-0.6B-Base 模型进行演示
1.3.1. 模型预训练
# Example 1: PT-Full using online dataset
paddleformers-cli train examples/config/pt/full.yaml
# Example 2: PT-Full using offline dataset
paddleformers-cli train examples/config/pt/full_offline_data.yaml1.3.2. SFT 和 LoRA 微调
# Example 1: SFT
paddleformers-cli train examples/config/sft/lora.yaml
# Example 2: SFT-Full
paddleformers-cli train examples/config/sft/full.yaml1.3.3. DPO 和 LoRA 微调
# Example 1: 8K seq length, DPO
paddleformers-cli train examples/config/dpo/full.yaml
# Example 2: 8K seq length, DPO-LoRA
paddleformers-cli train examples/config/dpo/lora.yaml1.3.4. 模型导出
paddleformers-cli export examples/config/run_export.yaml1.3.5. 多节点训练
方式一
NNODES={num_nodes} MASTER_ADDR={your_master_addr} MASTER_PORT={your_master_port} RANK={rank} CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 paddleformers-cli train examples/config/sft_full.yaml方式二 (mpirun)
先写一个脚本,例如scripts/train_96_gpus.sh,内容为:
NNODES={num_nodes} MASTER_ADDR={your_master_addr} MASTER_PORT={your_master_port} RANK={rank} CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 paddleformers-cli train examples/config/sft_full.yaml然后:
mpirun bash scripts/train_96_gpus.sh1.4. 参数传递
paddleformers-cli 支持在输入命令中传入参数用于覆盖配置文件中的内容,具体的用法如下:
paddleformers-cli train examples/config/sft/lora.yaml key1=value key2=value2
# 示例 修改模型名称和LoRA配置
paddleformers-cli train examples/config/sft/lora.yaml model_name_or_path=./models/Qwen3-0.6B lora_rank=8File: docs/zh/custom_datasets_format_zh.md
当前文件格式支持
当前支持 json、jsonl、parquet 三种格式,需保证文件名后缀和文件内容保持一致
新增文件格式支持
在 paddleformers/datasets/reader/io.py 里面实现各种类型文件的读取函数,例如 parquet 文件:
def load_parquet(file_path):
try:
table = pq.read_table(file_path)
df = table.to_pandas()
return df
except Exception:
raise ValueError(f"file {file_path} load failed")然后在 paddleformers/datasets/reader/file_reader.py 中BaseReader 的self.loader_map 中进行注册:
self.loader_map = {
".json": load_json,
".jsonl": load_json,
".txt": load_txt,
".csv": load_csv,
".parquet": load_parquet,
}当前数据格式支持
当前支持 erniekit 和messages 两种格式的数据
新增数据格式支持
在 paddleformers/datasets/reader/convertor.py 里面实现各种格式的转换函数,统一转换成 messages 格式,例如 erniekit 格式转 messages 格式:
def erniekit_convertor(item):
# erniekit dpo data
if "src" in item and "tgt" in item and "response" in item:
res = convert_dpo_txt_data(item)
# erniekit sft data
elif "src" in item and "tgt" in item:
res = convert_txt_data(item)
# erniekit pretraining data
elif "text" in item:
res = convert_pretraining_data(item)
# erniekit multi modal data
else:
res = convert_mm_data(item)
return res然后在 paddleformers/datasets/reader/file_reader.py 中BaseReader 的self.convertor_map 中进行注册:
self.convertor_map = {
"erniekit": erniekit_convertor,
"messages": messages_convertor,
}File: docs/zh/data_processing_guide.md
1. 数据流基础参数说明
1.1. 参数说明
- 参数
| 参数名 | 参数说明 |
|---|---|
| train_dataset_path | 训练数据集路径:允许指定多个路径,通过,分隔不同的数据集。 |
| eval_dataset_path | 验证数据集路径:允许指定多个路径,通过,分隔不同的数据集。 |
| train_dataset_type | 训练数据集格式,可选数据集格式为 erniekit / messages |
| eval_dataset_type | 验证数据集格式,可选数据集格式为 erniekit / messages |
| dataset_type | 数据集类型,离线预训练数据流为pretrain,离线 SFT 数据流为offline,在线数据流当前默认为iterable |
| skip_warmup | 是否跳过 mmap 文件的预热过程,默认为 True |
- 示例:
# single-source
train_dataset_type: "erniekit"
train_dataset_path: "./examples/data/sft-train.jsonl"
# multi-source
train_dataset_type: "erniekit,erniekit"
train_dataset_path: "./examples/data/sft-train1.jsonl,./examples/data/sft-train2.jsonl"2. 多源数据集混合策略
2.1. 参数说明
- 参数
| 参数名 | 参数说明 |
|---|---|
| train_dataset_prob | 指定用于多源训练数据集混合概率 |
| eval_dataset_prob | 指定用于多源评估数据集混合概率 |
| mix_strategy | 指定多源数据集的混合策略 |
- 示例
# single-source
train_dataset_type: "erniekit"
train_dataset_path: "./examples/data/sft-train.jsonl"
train_dataset_prob: "1.0"
# multi-source
train_dataset_type: "erniekit,erniekit"
train_dataset_path: "./examples/data/sft-train1.jsonl,./examples/data/sft-train2.jsonl"
train_dataset_prob: "0.8,0.2"
mix_strategy: "concat"2.2. 混合策略
在很多情况下,开发者可能有多个源的数据需要进行训练。在训练时,通过不同的策略进行混合使用。
PaddleFormers 目前支持四种数多源数据集拼接策略:random, concat, interleave_under, interleave_over
| 多源数据集拼接策略 | 适用场景 | 限制 | 描述 |
|---|---|---|---|
random |
数据集极大,需要严格的数据配比 | 最大步数 > 0 | 在random模式,基于输入的数据配比,构建一个固定大小(num_samples_each_epoch)的样本池,data loader 从该样本池中随机获取数据。 |
concat |
需要训练数据集中的所有数据 | 无 | 在concat模式下,不使用输入的数据配比,而是多个数据集直接合并。数据集的大小等于输入多源数据集的总大小。当 max_steps = -1 时,设置num_train_epochs允许完整遍历输入数据集num_train_epochs回合。 |
interleave_under |
当小数据集很重要但样本有限时 | 无 | interleave表示根据数据比例对多个数据集进行交叉拼接。interleave_under表示欠采样,这意味着一旦其中一个数据集耗尽,采样就会停止。 |
interleave_over |
当小数据集很重要但样本有限时 | 无 | interleave表示根据数据比例对多个数据集进行交叉拼接。interleave_over表示过采样,意味着只有在所有数据集耗尽后才停止采样。 |
- 注意:
num_samples_each_epoch只适用于random数据采样策略。
3. 数据拼接策略
在大模型(LLM / 多模态模型)训练过程中,序列长度不一致 是一个天然且普遍存在的问题。不同样本在 token 数、模态数量(文本、图像、视频)上差异极大,如果不对数据进行合理组织,会导致 严重的计算和显存浪费 ,成为训练效率和规模扩展的核心瓶颈。因此,我们引入 packing、padding-free 等数据拼接策略 解决该问题。
3.1. 参数说明
- 参数
| 参数名 | 参数说明 | 默认值 |
|---|---|---|
| packing | 是否使用 packing 策略进行数据拼接 | false |
| greedy_intokens | 在 packing 为 true 的时候,是否使用贪心 packing 策略 | true |
| truncate_packing | 在 packing 为 true 的时候,是否使用 truncate packing 策略进行拼接(仅限于在线预训练数据流) | true |
| padding_free | 将一个 batch 中的数据进行展平而避免数据 padding,packing=true/false 都可行 | false |
| use_global_causal_attn | 打开的时候为 Causal Attention,关闭的时候为 Causal Document Attention | false |
- 示例
packing: true
greedy_intokens: true
truncate_packing: false
padding_free: false
use_global_causal_attn: false3.2. 数据 packing 策略
packing 是一种优化批处理的技术,将多个短输入序列输入大语言模型(LLM)之前,先将它们合并成一个更长的序列,这能减少填充开销,并提高硬件利用率(例如,提升 GPU/TPU 的效率)。
The greedy intokens strategy 是一种token级别的优化方法,在批量处理过程中,以贪婪的方式优先填满可用的 token budget(例如,最大序列长度)。该策略确保模型在约束条件下生成尽可能多的token,最大程度减少容量浪费。
- 参数说明:
| packing | greedy_intokens | Packing Strategy |
|---|---|---|
| false | any | 不开packing |
| true | false | 开packing,但不使用贪心策略 |
| true | true | 开packing,同时使用贪心策略 |
- 补充:在线预训练数据流中另外支持了
truncate_packing的策略,支持将数据进行截断,有效降低 padding token,truncate_packing和packing设置为True即可使用,具体如下图所示:
3.3. Padding Free
padding_free 将一个 batch 中的数据进行展平而避免数据 padding,从而降低显存占用并加快训练(同一 batch 的不同序列之间依旧是不可见的)。默认为 False。
相较于packing,padding_free不需要额外的预处理时间,但packing的训练速度更快且显存占用更稳定。
3.4. Attention Mask
数据流默认会传入一个因果的 Attention Mask,在 packing 情况下,
当
use_global_causal_attn为 true 的时候,对应下图所示的Causal Attention,一个Sequence内的不同 sample 是可见的当
use_global_causal_attn为 false 的时候,对应下图所示的Causal Document Attention,一个Sequence内的不同 sample 是不可见的
4. 离线数据流使用
相比在线数据流,离线数据流将分词、裁剪、packing 等复杂数据处理前移,在训练阶段仅做顺序读取与计算,显著降低 CPU 开销,提升训练稳定性和可复现性,更适合大规模分布式训练。
当前 PaddleFormers 仅支持预训练数据使用离线数据流
4.1. 离线数据流制作
离线数据流制作方法如下:
下载一个文本数据集,例如 https://modelscope.cn/datasets/BazingaLyn/mini_pretrain_dataset
格式需为 jsonl,每行格式例如 BazingaLyn/mini_pretrain_dataset/pretrain_hq_v7.jsonl:
{"text": "番茄炒蛋\n材料:\n鸡蛋3个、番茄1个、油、盐、糖、水淀粉\n做法:..."}
{"text": "请描述一下如何正确规划个人理财。正确规划个人理财需要以下几个步骤..."}
{"text": "请输入一段描述有关海洋保护的情景对话。Person A: 哇,这个海滩真..."}
{"text": "鉴别两种不同类型的葡萄酒。鉴别葡萄酒的方法因其类型和品种而异,下..."}运行examples/tools/create_pretraining_data.py,生成数据将会保存在当前目录下的./pretrain_data.bin和./pretrain_data.idx
python -u examples/tools/create_pretraining_data.py \
--model_name_or_path "/path/to/your/Qwen3-0.6B-base" \
--data_format "JSON" \
--input_path "/path/to/your/BazingaLyn/mini_pretrain_dataset/pretrain_hq_v7.jsonl" \
--append_eos \
--output_prefix "./pretrain_data" \
--workers 1 \
--log_interval 10000 \
--data_impl "mmap"- 参数说明
| 参数名 | 类型 | 说明 |
|---|---|---|
--model_name_or_path |
string | 模型路径 |
--data_format |
string | 支持的文件格式,当前只支持 JSON |
--input_path |
string | 输入的 json 文件的路径 |
--append_eos |
store_true | 是否在每条数据的结尾添加 eos token |
--output_prefix |
str | 输出文件的前缀 |
--workers |
int | 运行的进程数 |
--log_interval |
int | 打印日志间隔 |
--data_impl |
str | 制作的数据集类型,默认为 mmap,也可以选择 lazy |
4.2. 参数说明
- 参数
| 参数名 | 参数说明 |
|---|---|
| input_dir | 指定数据集的前缀,例如:数据集 data-1-part0.bin 需要设置为 input_dir: "1.0 ./data-1-part0",1.0 为数据配比 |
| split | split 字段为 train/eval 的分配比例,如:split: "998,2", 其中 train 为训练集,eval 为评估集 |
| dataset_type | dataset_type 指定为 pretrain,例如:dataset_type: "pretrain" |
- 示例
dataset_type: "pretrain"
input_dir: "1.0 ./data/pre-training/demo_data/data-1-part0"
split: "998,2"File: docs/zh/dataset_format.md
1. 文件格式说明
当前 PaddleFormers 的预训练、后训练数据流支持 jsonl 、 json 等格式的数据,训练时需确保文件名后缀和文件内容格式保持一致。
1.1. 新增文件格式支持
如果您有格外的文件格式需要支持,可以在 paddleformers/datasets/reader/io.py 里面实现各种类型文件的读取函数,返回的数据格式为 List(Dict)
例如读取 json 文件:
def load_json(file_path):
try:
with open(file_path, "r", encoding="utf-8") as f:
return json.load(f)
except FileNotFoundError:
raise FileNotFoundError(f"file {file_path} not exists")
except json.JSONDecodeError:
pass # fallback to JSONL然后在 paddleformers/datasets/reader/file_reader.py 中 BaseReader 的 self.loader_map 中进行注册:
self.loader_map = {
".json": load_json,
".jsonl": load_json,
".txt": load_txt,
".csv": load_csv,
".parquet": load_parquet,
}2. 数据格式说明
PaddleFormers 支持业界常用的不同的数据集格式,通常情况下,我们推荐使用 messages 格式,该格式下数据的表示较为直观且功能齐全。
2.1. 预训练/后预训练数据格式
2.1.1. 在线数据流
messages 格式(点击展开/收起)
使用
messages格式需要在train(/eval)_dataset_type处指定为messagesmessages 格式:每条数据都是一个字典,包含以下字段:
messages:List(Dict)样例数据:
json{"messages": [{"role": "assistant", "content": "一个需要连续输入值的分类问题的示例是房屋价格预测。房屋的价格通常基于诸如平方英尺、位置、卧室和浴室数量以及像后院或车库等功能这样的因素定价。为了准确预测房屋价格,这些标准必须作为连续输入值输入到分类模型中。"}]} ...
erniekit 格式(点击展开/收起)
使用
erniekit格式需要在train(/eval)_dataset_type处指定为erniekiterniekit 格式:每条数据都是一个字典,包含以下字段:
text:str, List(str)样例数据:
json{"text": ["一个需要连续输入值的分类问题的示例是房屋价格预测。房屋的价格通常基于诸如平方英尺、位置、卧室和浴室数量以及像后院或车库等功能这样的因素定价。为了准确预测房屋价格,这些标准必须作为连续输入值输入到分类模型中。"]} ...
为了方便测试,我们也提供了 demo 数据集可以直接使用:
# messages格式
wget https://paddleformers.bj.bcebos.com/datasets/release/v1.0/pt_online_data_messages.tar.gz
mkdir -p data/pt && tar -xf pt_online_data_messages.tar.gz -C data/pt/
# erniekit格式
wget https://paddleformers.bj.bcebos.com/datasets/release/v1.0/pt_online_data_erniekit.tar.gz
mkdir -p data/pt && tar -xf pt_online_data_erniekit.tar.gz -C data/pt/2.1.2. 离线数据流
我们也可以选择使用离线的比特预训练数据流,更节省内存。
为了方便测试,我们也提供了 离线预训练 demo 数据集 可以直接使用:
wget https://paddleformers.bj.bcebos.com/datasets/pretrain_offline_data.tar.gz
mkdir -p data/pre-training && tar -xf pretrain_offline_data.tar.gz -C data/pre-training/您也可以制作自己的离线数据流,离线数据流制作方法如下:
下载一个文本数据集,例如 https://modelscope.cn/datasets/BazingaLyn/mini_pretrain_dataset
格式需为 jsonl,每行格式例如 BazingaLyn/mini_pretrain_dataset/pretrain_hq_v7.jsonl:
{"text": "番茄炒蛋\n材料:\n鸡蛋3个、番茄1个、油、盐、糖、水淀粉\n做法:..."}
{"text": "请描述一下如何正确规划个人理财。正确规划个人理财需要以下几个步骤..."}
{"text": "请输入一段描述有关海洋保护的情景对话。Person A: 哇,这个海滩真..."}
{"text": "鉴别两种不同类型的葡萄酒。鉴别葡萄酒的方法因其类型和品种而异,下..."}运行examples/tools/create_pretraining_data.py,生成数据将会保存在当前目录下的./pretrain_data.bin和./pretrain_data.idx
python -u examples/tools/create_pretraining_data.py \
--model_name_or_path "/path/to/your/Qwen3-0.6B-base" \
--data_format "JSON" \
--input_path "/path/to/your/BazingaLyn/mini_pretrain_dataset/pretrain_hq_v7.jsonl" \
--append_eos \
--output_prefix "./pretrain_data" \
--workers 1 \
--log_interval 10000 \
--data_impl "mmap"- 参数说明
| 参数名 | 类型 | 说明 |
|---|---|---|
--model_name_or_path |
string | 模型路径 |
--data_format |
string | 支持的文件格式,当前只支持 JSON |
--input_path |
string | 输入的 json 文件的路径 |
--append_eos |
store_true | 是否在每条数据的结尾添加 eos token |
--output_prefix |
str | 输出文件的前缀 |
--workers |
int | 运行的进程数 |
--log_interval |
int | 打印日志间隔 |
--data_impl |
str | 制作的数据集类型,默认为 mmap,也可以选择 lazy |
2.2. 指令微调(SFT)数据格式
2.2.1. 在线数据流
messages 格式(点击展开/收起)
使用
messages格式需要在train(/eval)_dataset_type处指定为messagesSFT 数据流中,每条数据都是一个字典,包含以下字段:
messages:List(Dict), 每个字典包含role、content、tool_calls(optional)三种 key。
role的值可以选择system,user,assistant,tool/tool_response/observation(optional)或tool_call/tool_call/function(optional)。content为具体的对话内容。tool_calls(optional)为申请工具调用。
tools(optional):List(Dict), 表示工具信息。
label(optional): Training flag (1=参与训练, 0=不参与训练)Notes:
- 每个训练样本均为 JSON 格式,多个样本以换行符分隔
样例数据:
text
/* Detailed source-code truncated for AI context efficiency. */python\ndef twoSum(nums, target):\n num_map = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in num_map:\n return [num_map[complement], i]\n num_map[num] = i\n\n\n### Explanation\n- Initialization: The dictionary num_map will track each number encountered and its index.\n- Iteration: For each number num at index i:\n - Compute complement = target - num.\n - If complement is in num_map, return [num_map[complement], i] since these two numbers sum to the target.\n - Otherwise, store num with its index in num_map for future checks.\n- Efficiency: This approach runs in O(n) time, where n is the number of elements, as each dictionary operation (insertion and lookup) is O(1) on average. The space complexity is O(n) to store the dictionary.\n"}
text] }]
text用于 function call 训练的 demo 数据: ```json [ { "messages": [ {"role": "user", "content": "I'm feeling a bit down. Can you tell me a joke to cheer me up?"}, {"role": "assistant", "content": "Okay, let me try to figure out how to approach this. The user is feeling down and asks for a joke to cheer up. I need to connect this request to the appropriate function call. Looking at the available tools, there's a function called get_random_joke which is designed exactly for this purpose. Since the user's main need is to feel better, providing a joke makes sense. The function doesn't require any parameters, so it's straightforward to call it without any additional arguments.\n", "tool_calls": [{"type": "function", "function": {"name": "get_random_joke", "arguments": {}}}]}, {"role": "tool", "content": [{"joke": "Why don't scientists trust atoms? Because they make up everything!"}]}, {"role": "assistant", "content": "Sure, here's a joke for you: \"Why don't scientists trust atoms? Because they make up everything!\" I hope that brings a smile to your face."} ], "tools": [ {"type": "function", "function": {"name": "get_random_joke", "description": "Get a random joke", "parameters": {"type": "object", "properties": {}, "required": []}}}, {"type": "function", "function": {"name": "generate_random_number", "description": "Generate a random number within a specified range", "parameters": {"type": "object", "properties": {"min": {"type": "number", "description": "The minimum value of the range"}, "max": {"type": "number", "description": "The maximum value of the range"}}, "required": ["min", "max"]}}} ] } ]为了方便测试,我们也提供了
messages格式的function call数据集可以直接使用:shellwget https://paddleformers.bj.bcebos.com/datasets/release/v1.0/sft_function_call_data.tar.gz mkdir -p data/sft && tar -zxf sft_function_call_data.tar.gz -C data/sft/
erniekit 格式(点击展开/收起)
使用
erniekit格式需要在train(/eval)_dataset_type处指定为erniekitSFT 数据流中,每条数据都是一个字典,包含以下字段:
src:str, List(str), 模型的输入指令(instruction)、提示(prompt),模型应该执行的任务。tgt:str, List(str), 模型的输出。system(optional): 系统配置label(optional): Training flag (1=参与训练, 0=不参与训练)is_system(optional): 标志 src 的第一条数据是否是 systemNotes:
src和tgt为支持多轮对话的列表(List)对象- 每个训练样本均为 JSON 格式,多个样本以换行符分隔
样例数据:
json{ "system": "你是一个生活小助理", "src": [ "我们如何在日常生活中减少用水?", "还有别的建议吗?" ], "tgt": [ "1. 使用节水装置,如节水淋浴喷头和水龙头。", "2. 使用水箱或水桶收集家庭废水,例如洗碗和洗浴。 \n3. 在社区中提高节水意识。 \n4. 检查水管和灌溉系统的漏水情况,并及时修复它们。 \n5. 洗澡时间缩短,使用低流量淋浴头节约用水。 \n6. 收集雨水,用于园艺或其他非饮用目的。 \n7. 刷牙或擦手时关掉水龙头。 \n8. 减少浇水草坪的时间。 \n9. 尽可能多地重复使用灰水(来自洗衣机、浴室水槽和淋浴的水)。 \n10. 只购买能源效率高的洗碗机和洗衣机。" ], "label": [0, 1], }
为了方便测试,我们也提供了 tatsu-lab/alpaca demo 数据集可以直接使用:
# messages格式
wget https://paddleformers.bj.bcebos.com/datasets/release/v1.0/sft_online_data_messages.tar.gz
mkdir -p data/sft && tar -xf sft_online_data_messages.tar.gz -C data/sft/
# erniekit格式
wget https://paddleformers.bj.bcebos.com/datasets/release/v1.0/sft_online_data_erniekit.tar.gz
mkdir -p data/sft && tar -xf sft_online_data_erniekit.tar.gz -C data/sft/2.2.2. 离线比特数据流
离线数据流需要按下面脚本生成离线比特数据流:
CUDA_VISIBLE_DEVICES=0 paddleformers-cli train examples/config/sft/full.yaml make_offline_data=true- 制作离线数据集时,建议使用真实训练的 yaml 配置文件,另外需要注意以下参数:
| 参数名 | 类型 | 说明 |
|---|---|---|
dataset_output_dir |
string | 制作的离线数据集输出目录 |
dataset_num_proc |
int | 多进程数量,建议设置为8或16 |
训练的时候需要指定dataset_type为offline,input_dir为数据集路径,例如:
# 流式数据流dataloader_shuffle不生效,非流式生效,如果要保持一致建议设置dataloader_shuffle=false
paddleformers-cli train examples/config/sft/full.yaml \
input_dir="dataset_output" \
dataset_type=offline \
dataloader_shuffle=false可以使用examples/tools/merge.py脚本合并多个离线数据集, 使用方法:
python examples/tools/merge.py --input_dirs /path/B,/path/A --split train --output mergeinput_dirs 参数是用逗号分隔的多个目录,例如:/path/B,/path/A,代表合并的顺序split 参数代表输入的目录的 split,例如:train,代表合并训练集,eval 代表合并验证集output 参数代表输出合并产出的目录,例如:merge,代表输出目录名为 merge
2.3. 直接偏好优化(DPO)数据格式
messages 格式(点击展开/收起)
使用
messages格式需要在train(/eval)_dataset_type处指定为messagesDPO 数据流中,每条数据都是一个字典,包含以下字段:
messages:List(dict), 对话历史列表, 包含role("user"或"assistant") 和content(str) 字段。chosen_response:List(dict), 偏好(chosen)的系统回复, 包含role("assistant") 和content(str) 等字段,根据是否调用工具可能包含工具调用信息 (tool_calls)。rejected_response:List(dict), 非偏好(rejected)的系统回复, 包含role("assistant") 和content(str) 等字段。tools:List(dict), 对话中可能用到的工具(函数)的定义列表。样例数据:
text
/* Detailed source-code truncated for AI context efficiency. */
> 为了方便测试,我们也提供了 function call DPO 数据集可以直接使用:
>
> ```shell
> # messages格式
> wget https://paddleformers.bj.bcebos.com/datasets/release/v1.0/dpo_function_call_data.tar.gz
> mkdir -p data/dpo && tar -xf dpo_function_call_data.tar.gz -C data/dpo/
> ```
>
------
**erniekit 格式(点击展开/收起)**
------
>
> 使用 `erniekit` 格式需要在 `train(/eval)_dataset_type` 处指定为 `erniekit`
>
> DPO 数据流中,每条数据都是一个字典,包含以下字段:
>
> * `system(optional)`: 系统配置
> * `src` : `str, List(str)`, 用户对话内容
> * `tgt` : `str, List(str)`, 系统回复内容(比 src 少一个)
> * `response` : `str, List(str)`, 包含 chosen 和 rejected 回复。
> * `sort` : `List(int)`, sort 值用于区分 response 中 chosen 和 rejected(sort 值小的是 rejected,sort 值大的是 chosen)。
> * `is_system(optional)` : 标志 src 的第一条数据是否是 system
>
> Notes:
>
> * 每个训练样本均为 JSON 格式,多个样本以换行符分隔
>
> 样例数据:
>
> ```json
> {
> "system": "你是一个生活小助理",
> "src": [
> "你好。",
> "哪一个富含蛋白质,床还是墙?"
> ],
> "tgt": ["你好呀,我是你的生活小助理。"],
> "response": [
> [
> "床和墙都不是蛋白质的来源,因为它们都是无生命的物体。蛋白质通常存在于肉类、奶制品、豆类和坚果等食物中。"
> ],
> [
> "对不起,我无法回答那个问题。请提供更具体的信息,让我知道你需要什么帮助。"
> ]
> ],
> "sort": [
> 1,
> 0
> ]
> }
> ...
> ```
>
------
为了方便测试,我们也提供了偏好数据集可以直接使用:
```shell
# messages格式
wget https://paddleformers.bj.bcebos.com/datasets/release/v1.0/dpo_online_data_messages.tar.gz
mkdir -p data/dpo && tar -xf dpo_online_data_messages.tar.gz -C data/dpo/
# erniekit格式
wget https://paddleformers.bj.bcebos.com/datasets/release/v1.0/dpo_online_data_erniekit.tar.gz
mkdir -p data/dpo && tar -xf dpo_online_data_erniekit.tar.gz -C data/dpo/2.4. 多模态指令微调(SFT)数据格式
messages 格式(点击展开/收起)
使用
messages格式需要在train(/eval)_dataset_type处指定为messages多模态 messages 格式需要在纯文本 messages 格式的基础上加上
images、videos、audios几个 key,用于传入多模态资源的url或者path,同时在messages中插入``、<video>、<audio>标签来表述插入多模态数据的位置:纯文本:
json{"messages": [{"role": "assistant", "content": "预训练的文本在这里"}]}加入图片:
json{"messages": [{"role": "assistant", "content": "是一只小狗,是一只小猫"}], "images": ["/xxx/x.jpg", "/xxx/x.png"]}加入音频:
json{"messages": [{"role": "assistant", "content": "<audio>描述了今天天气真不错"}], "audios": ["/xxx/x.wav"]}加入图片与视频:
json{"messages": [{"role": "assistant", "content": "是一个大象,<video>是一只狮子在跑步"}], "images": ["/xxx/x.jpg"], "videos": ["/xxx/x.mp4"]}
erniekit 格式(点击展开/收起)
使用
erniekit格式需要在train(/eval)_dataset_type处指定为erniekitSFT 数据流中,每条数据都是一个字典,包含以下字段:
text_info: 纯文本的列表,每个元素包含一个text和一个tag
text: 来自使用者的问题或系统回复的文字内容tag: 遮挡标签 (no_mask=包含在训练中,mask=排除)
image_info: 图像组成的列表,每个元素包含一个image_url和一个matched_text_index
image_url: 线上下载图像的网址或本地存取图像的路径matched_text_index:text_info中匹配文字的索引
- 预设值:
matched_text_index=0表示图像与第一个文字匹配,并将其放置在第一个文字之前
is_system(optional): 系统标志 (1=系统配置 0=无系统配置)
- 系统配置 = 如果
is_system=1,则为text_info[0]注意:
- 通过将
image_info替换为video_info来支持视频数据- 请确保
mask和no_mask在text_info中交替出现这是一个 SFT VL 数据集的多图像示例:
json{ "image_info": [ {"matched_text_index": 0, "image_url": "./DoclingMatix/218/0.png"}, {"matched_text_index": 0, "image_url": "./DoclingMatix/218/1.png"} ], "text_info": [ {"text": "What is the purpose of the resolution discussed in the text?", "tag": "mask"}, {"text": "The purpose of the resolution is to approve the redevelopment contract of the Philadelphia Redevelopment Authority for the redevelopment and urban renewal of a portion of the Haddington Urban Renewal Area, Unit Nos. 2 and 3, and to authorize the Redevelopment Authority to execute the redevelopment contract with Danielle M. Carson-Varns.", "tag": "no_mask"}, {"text": "Who introduced Resolution No. 160204 to the City Council?", "tag": "mask"}, {"text": "Councilmember Blackwell introduced Resolution No. 160204 to the City Council.", "tag": "no_mask"}, ... ] }这是一个 SFT VL 数据集的单视频示例:
json{ "video_info": [ {"matched_text_index": 0, "image_url": "./NExTVideo/1027/4789497818.mp4"} ], "text_info": [ {"text": "how does the man sit on the grass?\nA. kneel\nB. one leg in the air\nC. sitting on bicycle seat\nD. legs spread out\nE. squatting down\n Answer with the option's letter from the given choices directly.", "tag": "mask"}, {"text": "D", "tag": "no_mask"} ] }这是一个 SFT VL 数据集的系统配置示例:
json{ "is_system": 1, "text_info": [ {"text": "Your role as ...", "tag": "mask"}, {"text": "好的", "tag": "no_mask"}, {"text": "What is written...", "tag": "mask"}, {"text": "So I've got...", "tag": "no_mask"}, ... ] "image_info": [...] }
为了方便测试,我们也提供了用于快速训练的 demo 数据:
# messages格式
wget https://paddleformers.bj.bcebos.com/datasets/release/v1.0/sft_vl_data_messages.tar.gz
mkdir -p data/sft-vl && tar -xf sft_vl_data_messages.tar.gz -C data/sft-vl
# erniekit格式
wget https://paddleformers.bj.bcebos.com/datasets/release/v1.0/sft_vl_data_erniekit.tar.gz
mkdir -p data/sft-vl && tar -xf sft_vl_data_erniekit.tar.gz -C data/sft-vl2.5. 多模态直接偏好优化(DPO)数据格式
messages 格式(点击展开/收起)
使用
messages格式需要在train(/eval)_dataset_type处指定为messages多模态 DPO 数据流在纯文本 DPO 格式的基础上扩展支持多模态输入,内容中可以包含 ``,
<video>,<audio>标签来引用多模态资源。包含以下字段:
messages:List(dict), 对话历史列表, 包含role("user"或"assistant") 和content(str) 字段。chosen_response:List(dict), 偏好(chosen)的系统回复, 包含role("assistant") 和content(str) 等字段。rejected_response:List(dict), 非偏好(rejected)的系统回复, 包含role("assistant") 和content(str) 等字段。images:List(str), 图像资源的本地路径或在线 URL 列表videos:List(str), 视频资源的本地路径或在线 URL 列表audios:List(str), 音频资源的本地路径或在线 URL 列表样例数据(包含图像的多模态 DPO):
json{ "messages": [ { "role": "system", "content": "你是一个多模态AI助手,可以理解和描述图像内容。" }, { "role": "user", "content": "请描述一下中的场景" } ], "chosen_response": [{ "role": "assistant", "content": "这张图片展示了一个阳光明媚的公园场景,有绿树、草坪和散步的人们。" }], "rejected_response": [{ "role": "assistant", "content": "图片里有些东西,但我不太确定具体是什么。" }] "images": ["/path/to/image.jpg"], }样例数据(包含图像和视频的多模态 DPO):
json{ "messages": [ { "role": "user", "content": "中的动物和<video>中的动物有什么不同?" } ], "chosen_response": [{ "role": "assistant", "content": "图片中的是一只静态的猫,而视频展示的是一只正在奔跑的狗,它们在物种和行为上都有显著差异。" }], "rejected_response": [{ "role": "assistant", "content": "它们都是动物,没什么不同。" }] "images": ["/path/to/animal1.jpg"], "videos": ["/path/to/animal2.mp4"], }
为了方便测试,我们也提供了用于快速训练的 demo 数据:
# messages格式
wget https://paddleformers.bj.bcebos.com/datasets/release/v1.0/dpo_vl_data_messages.tar.gz
mkdir -p data/dpo-vl && tar -xf dpo_vl_data_messages.tar.gz -C data/dpo-vl2.6. 新增数据格式支持
PaddleFormers 支持多种不同的数据格式处理,我们通过将其他数据格式转换为 messages 格式来实现该功能
如果您有其他需要支持的数据格式,可以在 paddleformers/datasets/reader/convertor.py 里面实现对应格式的转换函数,统一转换成 messages 格式。
例如 erniekit 格式转 messages 格式:
def erniekit_convertor(item):
# erniekit dpo data
if "src" in item and "tgt" in item and "response" in item:
res = convert_dpo_txt_data(item)
# erniekit sft data
elif "src" in item and "tgt" in item:
res = convert_txt_data(item)
# erniekit pretraining data
elif "text" in item:
res = convert_pretraining_data(item)
# erniekit multi modal data
else:
res = convert_mm_data(item)
return res然后在 paddleformers/datasets/reader/file_reader.py 中 BaseReader 的 self.convertor_map 中进行注册:
self.convertor_map = {
"erniekit": erniekit_convertor,
"messages": messages_convertor,
}注册完成后在训练的时候指定 train/eval_dataset_type 为 erniekit / messages 即可使用
File: docs/zh/deployment_guide.md
1. 引言
当模型训练完成,用于推理时,需要基于高效的推理引擎进行部署,以满足 低时延 / 高吞吐 等需求。基于 PaddleFormers 训练完成的模型可以直接使用 vLLM 和 FastDeploy 等工具推理。本文档介绍如何使用 vLLM 和 FastDeploy 部署大语言模型,实现高性能、低延迟的在线推理服务。
2. vLLM 使用指南
vLLM 是一个快速且易于使用的大语言模型推理部署库。有以下优点:
- 显著提升吞吐和显存效率
- 通过 PagedAttention 高效管理 key 和 value 内存占用
- 支持连续批处理(continuous batching)
2.1. 环境准备
2.1.1 环境要求
请参考 vllm 安装文档 中的环境要求
2.1.2 依赖安装
| Mandatory | Minimum | Recommend |
|---|---|---|
| vllm | 0.13.0 | 0.13.0 |
pip install vllm>=0.13.0更多安装方式请参考 vllm 安装文档
2.2. 启动服务
当使用 PaddleFormers 训练完成模型后,模型权重会保存于训练配置中的 output_dir 中,请将该目录作为 --model 指定的路径。(LoRA 训练需要指定为模型合并参数后保存的路径)
python -m vllm.entrypoints.openai.api_server \
--model {模型保存地址} \
--port 8180 \
--trust-remote-code \
--max-model-len 4096 \
--max-num-seqs 32 \
--served-model-name {自定义名称}2.3. 发起服务请求
通过如下命令发起服务请求。其中 model 需要传入启动服务时设置的名称 {served-model-name}
curl http://localhost:8180/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "{served-model-name}",
"messages": [
{"role": "user", "content": "把李白的静夜思改写为现代诗"}
]
}'vLLM 服务接口兼容 OpenAI 协议,可以通过如下 Python 代码发起服务请求。
from openai import OpenAI
openai_api_key = "EMPTY"
openai_api_base = "http://localhost:8180/v1"
client = OpenAI(
api_key=openai_api_key,
base_url=openai_api_base,
)
chat_response = client.chat.completions.create(
model="{served-model-name}",
messages=[
{"role": "system", "content": "I'm a helpful AI assistant."},
{"role": "user", "content": "把李白的静夜思改写为现代诗"},
],
)
print("Chat response:", chat_response)3. FastDeploy 使用指南
FastDeploy 是基于飞桨(PaddlePaddle)的大语言模型与视觉语言模型推理部署工具包。有以下优点:
- 负载均衡式 PD 分解:工业级解决方案,支持上下文缓存与动态实例角色切换,在保障 SLO 达标和吞吐量的同时优化资源利用率
- 统一 KV 缓存传输:轻量级高性能传输库,支持智能 NVLink/RDMA 选择
- OpenAI API 协议兼容:服务化部署支持 OpenAI 协议调用
- 全量化格式支持:W8A16、W8A8、W4A16、W4A8、W2A16、FP8等
- 丰富的加速策略:推测解码、多令牌预测(MTP)及分块预填充
- 多硬件支持:NVIDIA GPU、昆仑芯 XPU、海光 DCU、天数智芯 GPU、燧原 GCU、沐曦 GPU、英特尔 Gaudi 等
3.1. 环境准备
3.1.1. 环境要求
请参考 FastDeploy 安装文档 的环境要求
3.1.2. 依赖安装
| Mandatory | Minimum | Recommend |
|---|---|---|
| FastDeploy | 2.3.2 | 2.4.0 |
为避免环境配置问题并简化安装流程,推荐使用官方镜像创建容器使用
docker pull ccr-2vdh3abv-pub.cnc.bj.baidubce.com/paddlepaddle/fastdeploy-cuda-12.6:2.3.2更多安装方式请参考 FastDeploy 安装文档
3.2. 启动服务
当使用 PaddleFormers 训练完成模型后,模型权重会保存于训练配置中的 output_dir 中,请将该目录作为 --model 指定的路径。(LoRA 训练需要指定为模型合并参数后保存的路径)
python -m fastdeploy.entrypoints.openai.api_server \
--model {模型保存地址} \
--port 8180 \
--metrics-port 8181 \
--engine-worker-queue-port 8182 \
--max-model-len 4096 \
--max-num-seqs 323.2. 发起服务请求
执行启动服务指令后,当终端打印如下信息,说明服务已经启动成功。
api_server.py[line:91] Launching metrics service at http://0.0.0.0:8181/metrics
api_server.py[line:94] Launching chat completion service at http://0.0.0.0:8180/v1/chat/completions
api_server.py[line:97] Launching completion service at http://0.0.0.0:8180/v1/completions
INFO: Started server process [13909]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://0.0.0.0:8180 (Press CTRL+C to quit)FastDeploy 提供服务探活接口,用以判断服务的启动状态,执行如下命令返回 HTTP/1.1 200 OK 即表示服务启动成功。
curl -i http://0.0.0.0:8180/health通过如下命令发起服务请求。
curl -X POST "http://0.0.0.0:8180/v1/chat/completions" \
-H "Content-Type: application/json" \
-d '{
"messages": [
{"role": "user", "content": "把李白的静夜思改写为现代诗"}
]
}'FastDeploy 服务接口兼容 OpenAI 协议,可以通过如下 Python 代码发起服务请求。
import openai
host = "0.0.0.0"
port = "8180"
client = openai.Client(base_url=f"http://{host}:{port}/v1", api_key="null")
response = client.chat.completions.create(
model="null",
messages=[
{"role": "system", "content": "I'm a helpful AI assistant."},
{"role": "user", "content": "把李白的静夜思改写为现代诗"},
],
stream=True,
)
for chunk in response:
if chunk.choices[0].delta:
print(chunk.choices[0].delta.content, end='')
print('\n')File: docs/zh/dpo_and_lora_guide.md
1. 背景说明
大模型的训练流程通常包含四个关键阶段:
- 预训练(Pre-training):通过海量无标注数据进行预训练,学习语言能力和世界知识,构建通用基座;
- 后预训练(Post-Pre-training):通过注入特定领域知识以增强专业性,构建领域基座模型;
- 有监督微调(SFT):利用高质量指令数据进行微调,模型具备对话与任务处理能力;
- 偏好对齐(DPO/RLHF):采用偏好优化(DPO/RLHF)技术,基于成对的优劣反馈数据对模型进行价值观对齐,从而输出符合人类预期的最终版本。(本文讲解 DPO)
本文旨在说明如何基于 PaddleFormers 进行模型的偏好对齐。
2. 数据准备
为了方便演示,我们提供一个 demo 数据,执行下载并解压。如果想要使用自己的数据进行训练,请参考数据集格式说明进行数据的准备。
wget https://paddleformers.bj.bcebos.com/datasets/release/v1.0/dpo_online_data_messages.tar.gz
mkdir -p data/dpo && tar -xf dpo_online_data_messages.tar.gz -C data/dpo/demo 数据格式: messages 格式,每条数据都是一个字典。如下字段:
messages:对话内容,最后一轮为用户指令。chosen_response:对应用户指令的回复的 优势答案 。rejected_response:对应用户指令的回复的 劣势答案 。role:角色,user 为用户 Query,assistant 为模型的回复。content:文本内容。
{
"messages": [
{
"role": "user",
"content": "What kind of blankets does a elepahant like to eat?"
}
],
"chosen_response": [
{
"role": "assistant",
"content": "Elephants are herbivores and their diet consists mainly of leaves, fruits, bark, and roots. They do not eat blankets."
}
],
"rejected_response": [
{
"role": "assistant",
"content": "Elephants are herbivores and prefer to eat leaves, grass, bark and fruits of woody plants and tree species. They also eat small animals, roots, stems and some artificial fodders like hay. They often prefer to eat three or four times a day, and generally take only a few bites from an area before moving onto another part of the food source."
}
]
}3. 训练
DPO 支持全量训练和 LoRA 训练:
全量 DPO 更新全部参数,适合数据算力充足、追求极致效果的场景。
LoRA 仅训练低秩矩阵,适配资源受限、需快速迁移的任务。
3.1. 超参数配置
训练配置推荐使用 yaml 格式文件,如下示例:
全量训练配置
### data
train_dataset_type: messages
eval_dataset_type: messages
train_dataset_path: ./data/dpo/train_messages.jsonl
train_dataset_prob: "1.0"
eval_dataset_path: ./data/dpo/eval_messages.jsonl
eval_dataset_prob: "1.0"
max_seq_len: 8192
packing: true
mix_strategy: concat
### model
model_name_or_path: baidu/ERNIE-4.5-0.3B-PT
_attn_implementation: flashmask
### finetuning
# base
stage: DPO
fine_tuning: full
seed: 23
do_train: true
do_eval: true
per_device_eval_batch_size: 1
per_device_train_batch_size: 1
num_train_epochs: 1
max_steps: -1
eval_steps: 100
evaluation_strategy: steps
save_steps: 100
save_strategy: steps
logging_steps: 1
gradient_accumulation_steps: 4
logging_dir: ./vdl_log
output_dir: ./checkpoints/ernie45-dpo-full
disable_tqdm: true
eval_accumulation_steps: 16
model_with_dpo_criterion: true
# train
warmup_steps: 20
learning_rate: 1.0e-6
# performance
tensor_model_parallel_size: 1
pipeline_model_parallel_size: 1
sharding: stage2
recompute_granularity: full
recompute_method: uniform
recompute_num_layers: 1
bf16: true
fp16_opt_level: O2
save_checkpoint_format: flex_checkpoint
load_checkpoint_format: flex_checkpointlora 训练配置
### data
train_dataset_type: messages
eval_dataset_type: messages
train_dataset_path: ./data/dpo/train_messages.jsonl
train_dataset_prob: "1.0"
eval_dataset_path: ./data/dpo/eval_messages.jsonl
eval_dataset_prob: "1.0"
max_seq_len: 8192
packing: true
mix_strategy: concat
### model
model_name_or_path: baidu/ERNIE-4.5-0.3B-PT
_attn_implementation: flashmask
lora: true
lora_rank: 8
### finetuning
# base
stage: DPO
fine_tuning: lora
seed: 23
do_train: true
do_eval: true
per_device_eval_batch_size: 1
per_device_train_batch_size: 1
num_train_epochs: 1
max_steps: -1
eval_steps: 100
evaluation_strategy: steps
save_steps: 100
save_strategy: steps
logging_steps: 1
gradient_accumulation_steps: 4
logging_dir: ./vdl_log
output_dir: ./checkpoints/ernie45-dpo-lora
disable_tqdm: true
eval_accumulation_steps: 16
model_with_dpo_criterion: true
# train
warmup_steps: 20
learning_rate: 1.0e-5
# performance
tensor_model_parallel_size: 1
pipeline_model_parallel_size: 1
sharding: stage2
recompute_granularity: full
recompute_method: uniform
recompute_num_layers: 1
bf16: true
fp16_opt_level: O2
save_checkpoint_format: flex_checkpoint
load_checkpoint_format: flex_checkpoint配置说明(详见[训练参数配置说明](./training_arguments.md))
train(eval)_dataset_type :由于 demo 数据类型是 messages 格式,配置为messages
packing & mix_strategy:数据处理策略,详见数据流参数说明
model_name_or_path:模型本地路径或 HuggingFace 仓库对应的名称,如baidu/ERNIE-4.5-0.3B-PT,推荐使用 SFT 后的模型
_attn_implementation:模型 Attention Mask 实现方式,推荐使用 flashmask,是一种针对 FlashAttention 的一种核心优化技术。
lora:Bool 类型,是否 lora 训练,默认False。
lora_rank:开启 lora 训练时设置,一般设置8即可,如果需要适配更复杂训练任务,可适当提高(如16、32等)。
stage:与训练类型相关,设置DPO
fine_tuning:full表示全量训练,lora仅训练 LoRA 参数
max_steps:设置-1表示训练到最大 step 停止,也可指定设置最大步数
load_checkpoint_format:加载模型格式方式,推荐flex_checkpoint
save_checkpoint_format:保存模型格式方式,推荐flex_checkpoint
model_with_dpo_criterion:默认关闭,组网中包含 dpo criterion 时需要开启,否则关闭,如 ernie45需要开启。
3.2. 启动训练
全量训练
CUDA_VISIBLE_DEVICES=0 paddleformers-cli train dpo_full.yamlCUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 paddleformers-cli train dpo_full.yamllora 训练
CUDA_VISIBLE_DEVICES=0 paddleformers-cli train dpo_lora.yamlCUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 paddleformers-cli train dpo_lora.yaml4. 参数合并
针对 lora 训练后模型,需要将 LoRA 参数合并到主模型才能用于推理部署使用,为此我们提供了 LoRA 参数合并功能。
配置
合参配置使用 yaml 格式文件,如下示例:
fine_tuning: LoRA
model_name_or_path: baidu/ERNIE-4.5-0.3B-PT
download_hub: huggingface
output_dir: ./checkpoints/ernie45-dpo-loramodel_name_or_path:主模型的本地路径或 HuggingFace 仓库对应的名称,如baidu/ERNIE-4.5-0.3B-PT
download_hub:仓库源,本地路径无需设置;如果model_name_or_path是远程仓库模型,需要同时指定对应的仓库源,可设置huggingface、aistudio、modelscope。
output_dir:lora 训练后参数的保存路径,与上述 lora 训练配置的output_dir保持一致即可。
5. 推理部署
同基于 PaddleFormers 进行指令微调(SFT & LoRA)
File: docs/zh/how_to_download_model.md
1. PaddleFormers 自动下载
当使用 PaddleFormers 训练时,无论是使用 API 接口,还是通过命令行工具中的配置文件,在指定了正确的repo_id/model_id后,都会自动下载模型文件到本地并缓存。
配置文件
model_name_or_path: Qwen/Qwen3-0.6B-BaseAPI 使用
from paddleformers.transformers import AutoTokenizer, AutoModelForCausalLM
# 将会自动下载Qwen3-0.6B-Base的tokenizer物料
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B-Base")
# 将会自动下载Qwen3-0.6B-Base的模型物料
model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-0.6B-Base", dtype="bfloat16", convert_from_hf=True).eval()考虑到不同用户网络连接的问题,PaddleFormers 支持以下三种下载源:
使用自动下载时,默认从 HuggingFace 下载,用户可以通过配置环境变量 DOWNLOAD_SOURCE 修改下载源,可取值为 "aistudio", "modelscope", "huggingface"。例如:
export DOWNLOAD_SOURCE=aistudio # "aistudio", "modelscope" or "huggingface"2. 手动下载
如果网络不稳定,自动下载可能会失败,您可以选择手动下载模型保存到本地文件夹中,在配置文件或者 API 中指定对应的路径即可
配置文件
model_name_or_path: {模型保存路径}API 使用
from paddleformers.transformers import AutoTokenizer, AutoModelForCausalLM
tokenizer = AutoTokenizer.from_pretrained("{模型保存路径}")
model = AutoModelForCausalLM.from_pretrained("{模型保存路径}", dtype="bfloat16", convert_from_hf=True).eval()2.1. HuggingFace
使用命令行工具下载
# 首先请先安装huggingface_hub库
python -m pip install huggingface_hub
# 下载整个repo到指定目录
# 填写要下载的模型repo_id,在local_dir后指定下载路径,以下示例为下载到当前文件夹
hf download {repo_id} --local-dir ./
# 下载单个文件到指定目录(以下载README.md为例)
hf download {repo_id} README.md --local-dir ./更多下载方式请参考 HuggingFace 模型下载
2.2. AIStudio
使用命令行工具下载
注意:在 AIstudio 上,repo_id 前缀可能因模型发布者不同,和 HuggingFace 有所差异,在加载或引用模型时,请务必使用完整的、准确的 repo_id,以确保正确访问目标模型。您可以在模型详情页或分享链接中找到该标识符。
# 首先请先安装aistudio-sdk库
python -m pip install --upgrade aistudio-sdk
# 下载整个repo到指定目录
# 填写要下载的模型repo_id,在local_dir后指定下载路径,以下示例为下载到当前文件夹
aistudio download --model {repo_id} --local_dir ./
# 下载单个文件到指定目录(以下载README.md为例)
aistudio download README.md --model {repo_id} --local_dir ./更多下载方式请参考 AIStudio 模型下载
2.3. ModelScope
使用命令行工具下载
注意:在 ModelScope 上,repo_id 前缀可能因模型发布者不同,和 HuggingFace 有所差异,在加载或引用模型时,请务必使用完整的、准确的 repo_id,以确保正确访问目标模型。您可以在模型详情页或分享链接中找到该标识符。
# 首先请先安装modelscope库
python -m pip install modelscope
# 下载整个repo到指定目录
# 填写要下载的模型repo_id,在local_dir后指定下载路径,以下示例为下载到当前文件夹
modelscope download --model {repo_id} --local_dir ./
# 下载单个文件到指定目录(以下载README.md为例)
modelscope download --model {repo_id} README.md --local_dir ./更多下载方式请参考 ModelScope 模型下载
2. Official Technical Reference & Guides (PaddlePaddle/docs)
PaddlePaddle docs
Source files for contents presented at PaddlePaddle documentation.
Note: English version API docs are generally docstrings in PaddlePaddle/Paddle, documents for other PaddlePaddle projects are being managed in their respective ways.
Codebase structure
- docs: PaddlePaddle 2.0 & above docs source file.
- docs/api: PaddlePaddle API docs.
- docs/guides: PaddlePaddle guides docs.
- docs/tutorial: PaddlePaddle tutorial docs.
- ci_scripts: docs CI scripts.
How to build
- pre-requirements
- docker
- Instructions
- step1: clone docstext
git clone https://github.com/PaddlePaddle/docs - step2: build docstext
cd docs mkdir output bash docs-build.sh -f absolute_path_docs - step3: preview docs
The output of docs will be generated in docs/output.
- step1: clone docs
How to contribute
PaddlePaddle welcomes documentation contributions, please see CONTRIBUTING.md for details.