LLaMA-Factory 微调 DeepSeek-R1 模型实战指南
介绍使用 LLaMA-Factory 对 DeepSeek-R1 模型进行可视化的微调流程。内容包括环境搭建(Anaconda、CUDA)、数据集准备与预处理(聊天记录清洗、格式转换)、模型配置与训练参数设置、评估指标解读以及模型导出部署。通过 LoRA 技术实现高效微调,适用于个人风格化对话模型的构建。

介绍使用 LLaMA-Factory 对 DeepSeek-R1 模型进行可视化的微调流程。内容包括环境搭建(Anaconda、CUDA)、数据集准备与预处理(聊天记录清洗、格式转换)、模型配置与训练参数设置、评估指标解读以及模型导出部署。通过 LoRA 技术实现高效微调,适用于个人风格化对话模型的构建。

使用 LLaMA-Factory 进行模型微调具有多方面的好处。首先,它简化了大模型微调的过程,使得用户能够轻松进行模型的优化和改进。此外,LLaMA-Factory 支持多种训练方法,如全量调参、LoRA 等,以及不同的对齐方案,如 DPO、PPO 等。这为用户提供了灵活性,可以根据具体需求选择合适的微调策略。
LLaMA-Factory 还提供了一站式服务,从模型微调到量化处理,再到运行,整个过程一气呵成。此外,它支持多种流行的语言模型,如 LLaMA、BLOOM、Mistral、Baichuan 等,涵盖了广泛的应用场景。
在模型量化方面,LLaMA-Factory 能够有效地压缩模型规模,减少模型运行所需的计算量和存储空间,使得模型能够在性能稍弱的设备上也能流畅运行。这不仅提高了模型的可访问性,也降低了运行成本。
此外,LLaMA-Factory 的训练过程中记录的内容比较全面,除了同步输出 loss 曲线图以外,还自带 BLEU 等评测指标,这有助于用户更好地监控和评估模型的性能。
官方建议 Python 版本至少为 3.9,推荐 3.10。
pip install -r requirements.txt
pip install -e ".[torch,metrics]"
conda install pytorch torchvision torchaudio pytorch-cuda=11.8 -c nvidia
记得输入 y 继续安装。
如果要在 Windows 平台上开启量化 LoRA(QLoRA),需要安装预编译的 bitsandbytes 库。支持 CUDA 11.1 到 12.2,请根据您的 CUDA 版本情况选择适合的发布版本。
pip install https://github.com/jllllll/bitsandbytes-windows-webui/releases/download/wheels/bitsandbytes-0.41.2.post2-py3-none-win_amd64.whl
llamafactory-cli webui
interface.py 代码中的 share 参数。run_web_ui() 和 run_web_demo() 方法,将 share=gradio_share 修改为 share=True。使用数据导出工具进行聊天记录解析。例如可以使用 MemoTrace 或其他类似工具(如 finetune_dataset_maker)。
merge.py 的文件。import os
import json
# 设置目标文件夹路径
folder_path = r'D:\软件\留痕\data\聊天记录'
# 获取文件夹及其所有子文件夹中的所有 .json 文件
json_files = []
for root, dirs, files in os.walk(folder_path):
for file in files:
if file.endswith('.json'):
json_files.append(os.path.join(root, file))
# 合并所有 .json 文件
merged_data = []
for file in json_files:
with open(file, 'r', encoding='utf-8') as f:
try:
data = json.load(f)
merged_data.append(data)
except json.JSONDecodeError:
print(f"Error decoding {file}. Skipping.")
# 保存合并后的数据到一个新的 .json 文件
merged_file_path = os.path.join(folder_path, 'merged_data.json')
with open(merged_file_path, 'w', encoding='utf-8') as merged_file:
json.dump(merged_data, merged_file, indent=4, ensure_ascii=False)
print(f"合并后的文件已保存至:{merged_file_path}")
python merge.py。数据集预处理是机器学习和人工智能中不可或缺的环节。预处理能够提升数据质量,通过清洗噪声、去除重复和无关信息,以及标准化格式,为模型训练提供纯净且一致的输入。
Data_Preprocessing.py 的文件。import json
import re
# 读取 merged_data.json 文件
with open('merged_data.json', 'r', encoding='utf-8') as file:
data = json.load(file)
# 转换后的数据格式
converted_data = []
# 数据清洗:去除空消息,清除特殊字符,统一格式
def clean_data(dataset):
cleaned_data = []
for example in dataset:
messages = example['messages']
cleaned_messages = []
for message in messages:
# 去除内容为空的消息
if not message['content'].strip():
continue
# 清除多余的空格、换行符等
message['content'] = message['content'].replace("\n", " ").strip()
cleaned_messages.append(message)
if cleaned_messages:
cleaned_data.append({'messages': cleaned_messages})
return cleaned_data
# 脱敏处理:替换敏感信息
def replace_sensitive_info(text):
# 匹配手机号、邮箱等敏感信息
text = re.sub(r'\d{3}[-]?\d{4}[-]?\d{4}', '[PHONE_NUMBER]', text) # 替换手机号
text = re.sub(r'\S+@\S+', '[EMAIL]', text) # 替换邮箱
text = re.sub(r'\d{4}-\d{2}-\d{2}', '[DATE]', text) # 替换日期
text
():
anonymized_data = []
example dataset:
messages = example[]
anonymized_messages = []
message messages:
message[] == :
message[] = message[].replace(, )
message[] = replace_sensitive_info(message[])
anonymized_messages.append(message)
anonymized_data.append({: anonymized_messages})
anonymized_data
item_list data:
item item_list:
item:
()
()
conversation = {: []}
message item[]:
role = message[]
content = message[]
()
content = replace_sensitive_info(content)
role == :
role == :
from_role =
role == :
from_role =
conversation[].append({: from_role, : content})
converted_data.append(conversation)
(, , encoding=) file:
json.dump(converted_data, file, ensure_ascii=, indent=)
()
python Data_Preprocessing.py。converted_data.json 数据集存放在 LLaMA-Factory 相对路径下的 data 文件夹中。dataset_info.json 文件。dataset_info.json 文件,以便 LLaMA-Factory 识别训练。添加以下内容:"converted_data": {
"file_name": "converted_data.json",
"formatting": "sharegpt",
"columns": {
"messages": "conversations"
}
},
data 文件夹有个 README_zh.md 的文件打开它,它记录的就是 alpaca 和 sharegpt 格式数据集如何配置。dataset_info.json 文件需要填充的内容如上所示。因为不需要 tools(工具描述),所以直接删除也行。如果有需求也可以加上,只要把数据集修改一下就行了。模型下载地址:deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B
命令行输出说明:
saves 文件夹下。评估指标说明:
requirements.txt 文件,也就是依赖安装文件,方便后期快速部署。transformers>=4.41.2,<=4.48.3,!=4.46.*,!=4.47.*,!=4.48.0,!=4.48.1,!=4.48.2;python_version<'3.10'
transformers>=4.41.2,<=4.48.3,!=4.46.*,!=4.47.*,!=4.48.0;python_version>='3.10'
datasets>=2.16.0,<=3.2.0
accelerate>=0.34.0,<=1.2.1
peft>=0.11.1,<=0.12.0
trl>=0.8.6,<=0.9.6
tokenizers>=0.19.0,<=0.21.0
gradio>=4.38.0,<=5.12.0
pandas>=2.0.0
scipy
einops
sentencepiece
tiktoken
protobuf
uvicorn
pydantic
fastapi
sse-starlette
matplotlib>=3.7.0
fire
packaging
pyyaml
numpy<2.0.0
av
librosa
tyro<0.9.0

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online