前言
报名了【Llama 3 五一超级课堂】的学习活动,有兴趣的一块参与学习~
XTuner 微调 Llama3 个人小助手认知
准备工作
首先,根据教程做准备工作 VSCode 远程连接 InternStudio 开发机
环境、模型准备
配置环境(未配置时看这里)
安装基础环境
# 使用如下指令便可以安装好一个 python=3.10 pytorch=2.1.2+cu121 的基础环境了。
conda create -n llama3 python=3.10
conda activate llama3
conda install pytorch==2.1.2 torchvision==0.16.2 torchaudio==2.1.2 pytorch-cuda=12.1 -c pytorch -c nvidia
安装XTuner
cd ~
git clone -b v0.1.18 https://github.com/InternLM/XTuner
cd XTuner
pip install -e .[all]
clone 教程仓库。
cd ~
git clone https://github.com/SmartFlowAI/Llama3-Tutorial
模型准备
准备 Llama3-8B-Instruct 模型权重
mkdir -p ~/model
cd ~/model
ln -s /root/share/new_models/meta-llama/Meta-Llama-3-8B-Instruct .
环境开启(以前配置过环境看这里)
conda activate llama3
运行demo
streamlit run ~/Llama3-Tutorial/tools/internstudio_web_demo.py \
~/model/Meta-Llama-3-8B-Instruct
微调前测试
问它一句:你是谁?(使用中午回答)。
它回答它是Llama 3
微调开始
自我认知训练数据集准备
平台贴心的提供了一个生成训练数据的工具,可以用以下命令快速生成测试用的训练数据。
cd ~/Llama3-Tutorial
python tools/gdata.py
以上脚本在生成了 ~/Llama3-Tutorial/data/personal_assistant.json 数据文件格式如下所示:
[
{
"conversation": [
{
"system": "你是一个懂中文的小助手",
"input": "你是(请用中文回答)",
"output": "您好,我是SmartFlowAI,一个由 SmartFlowAI 打造的人工智能助手,请问有什么可以帮助您的吗?"
}
]
},
{
"conversation": [
{
"system": "你是一个懂中文的小助手",
"input": "你是(请用中文回答)",
"output": "您好,我是SmartFlowAI,一个由 SmartFlowAI 打造的人工智能助手,请问有什么可以帮助您的吗?"
}
]
}
]
XTuner配置文件准备
平台贴心地为大佬们修改好了configs/assistant/llama3_8b_instruct_qlora_assistant.py 配置文件(主要修改了模型路径和对话模板),可直接享用~
训练模型
cd ~/Llama3-Tutorial
# 开始训练,使用 deepspeed 加速,A100 40G显存 耗时24分钟
xtuner train configs/assistant/llama3_8b_instruct_qlora_assistant.py --work-dir /root/llama3_pth
# Adapter PTH 转 HF 格式
xtuner convert pth_to_hf /root/llama3_pth/llama3_8b_instruct_qlora_assistant.py \
/root/llama3_pth/iter_500.pth \
/root/llama3_hf_adapter
# 模型合并
export MKL_SERVICE_FORCE_INTEL=1
xtuner convert merge /root/model/Meta-Llama-3-8B-Instruct \
/root/llama3_hf_adapter\
/root/llama3_hf_merged
推理验证
运行起来demo:
streamlit run ~/Llama3-Tutorial/tools/internstudio_web_demo.py \
/root/llama3_hf_merged
训练成功!
遇到的问题
报显存不足:
[rank0]: torch.cuda.OutOfMemoryError: CUDA out of memory. Tried to allocate 2.59 GiB. GPU
解决:开发机需要至少升级为24G显存配置
训练时报错:
尝试自己按照格式写训练数据时报的错误。
ValueError: end should be larger than begin, but got begin=0, end=0
解决:
训练数据可能太短(我只写了3条数据),将其又复制两份后解决。