【学习笔记】L1G5000 XTuner 微调个人小助手认知

84 阅读2分钟

一、背景

今天,继续我的大模型学习之旅,使用XTuner进行模型微调。

二、环境准备

  1. 创建开发机

  1. 创建虚拟环境
cd ~
#git clone 本repo
git clone https://github.com/InternLM/Tutorial.git -b camp4
mkdir -p /root/finetune && cd /root/finetune
conda create -n xtuner-env python=3.10 -y
conda activate xtuner-env

3. 安装XTuner

# 上一步中clone的代码库,使用已freeze的requirements.txt 
cd /root/Tutorial/docs/L1/XTuner
pip install -r requirements.txt
pip install torch==2.4.1 torchvision==0.19.1 torchaudio==2.4.1 --index-url https://download.pytorch.org/whl/cu121
# 验证安装是否成功,会列出所有可供微调的模型
xtuner list-cfg

  1. 准备数据
# 将上面clone路径下的文件拷贝出来
mkdir -p /root/finetune/data && cd /root/finetune/data
cp -r /root/Tutorial/data/assistant_Tuner.jsonl  /root/finetune/data
# 创建 `change_script.py` 文件用于修改数据,将文本尖米替换为小可爱
touch /root/finetune/data/change_script.py
# 执行替换
python change_script.py ./assistant_Tuner.jsonl ./assistant_Tuner_change.jsonl
# 验证结果
cat assistant_Tuner_change.jsonl | head -n 3

三、开始训练

  1. 准备训练模型
mkdir /root/finetune/models
# 直接使用环境中已有的模型,创建软连接
ln -s /root/share/new_models/Shanghai_AI_Laboratory/internlm2_5-7b-chat /root/finetune/models/internlm2_5-7b-chat
# 修改config
cd /root/finetune 
mkdir ./config && cd ./config
xtuner copy-cfg internlm2_5_chat_7b_qlora_alpaca_e3 ./

2. 执行微调

xtuner train ./config/internlm2_5_chat_7b_qlora_alpaca_e3_copy.py --deepspeed deepspeed_zero2 --work-dir ./work_dirs/assistTuner

说明:

  1. xtuner train命令启动微调,该命令需要一个参数:CONFIG 用于指定微调配置文件
  2. --work-dir 指定特定的文件保存位置。
  3. --deepspeed 则为使用 deepspeed, deepspeed 可以节约显存。

查看结果文件如下:

  1. 权重转换
  1. 转换为huggin face文件

xtuner convert pth_to_hf 命令用于进行模型格式转换。该命令需要三个参数:CONFIG 表示微调的配置文件, PATH_TO_PTH_MODEL 表示微调的模型权重文件路径,即要转换的模型权重, SAVE_PATH_TO_HF_MODEL 表示转换后的 HuggingFace 格式文件的保存路径。

cd /root/finetune/work_dirs/assistTuner

conda activate xtuner-env

# 先获取最后保存的一个pth文件
pth_file=`ls -t /root/finetune/work_dirs/assistTuner/*.pth | head -n 1 | sed 's/:$//'`
export MKL_SERVICE_FORCE_INTEL=1
export MKL_THREADING_LAYER=GNU
xtuner convert pth_to_hf ./internlm2_5_chat_7b_qlora_alpaca_e3_copy.py ${pth_file} ./hf

查看结果文件如下:

2) 合并最终模型

xtuner convert merge命令用于合并模型。该命令需要三个参数:LLM 表示原模型路径,ADAPTER 表示 Adapter 层的路径, SAVE_PATH 表示合并后的模型最终的保存路径。

cd /root/finetune/work_dirs/assistTuner
conda activate xtuner-env

export MKL_SERVICE_FORCE_INTEL=1
export MKL_THREADING_LAYER=GNU
xtuner convert merge /root/finetune/models/internlm2_5-7b-chat ./hf ./merged --max-shard-size 2GB

结果文件目录如下:

四、验证

  1. 修改xtuner_streamlit_demo.py文件,将模型路径改为上面微调merge后的模型路径。
  2. 启动应用
conda activate xtuner-env

pip install streamlit==1.31.0
streamlit run /root/Tutorial/tools/L1_XTuner_code/xtuner_streamlit_demo.py
ssh -p 34359 root@ssh.intern-ai.org.cn -CNg -L {本地机器_PORT}:127.0.0.1:{开发机_PORT} -o StrictHostKeyChecking=no

效果如下: