基础任务
使用 XTuner 微调 InternLM2-Chat-7B 实现自己的小助手认知,记录复现过程并截图。
环境配置与数据准备
首先用 conda 先构建一个 Python-3.10 的虚拟环境
cd ~
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
按如下方式安装 XTuner
git clone https://github.com/InternLM/xtuner.git
cd /root/finetune/xtuner
pip install -e '.[all]'
pip install torch==2.4.1 torchvision==0.19.1 torchaudio==2.4.1 --index-url https://download.pytorch.org/whl/cu121
pip install transformers==4.39.0
安装好后输入 xtuner list-cfg 检查是否正确,接着创建一个新的文件夹用于存储微调数据
mkdir -p /root/finetune/data && cd /root/finetune/data
cp -r /root/Tutorial/data/assistant_Tuner.jsonl /root/finetune/data
写一个脚本生成修改需要的微调训练数据,在当前目录下创建一个 change_script.py 文件,内容如下:
import json
import argparse
from tqdm import tqdm
def process_line(line, old_text, new_text):
# 解析 JSON 行
data = json.loads(line)
# 递归函数来处理嵌套的字典和列表
def replace_text(obj):
if isinstance(obj, dict):
return {k: replace_text(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [replace_text(item) for item in obj]
elif isinstance(obj, str):
return obj.replace(old_text, new_text)
else:
return obj
# 处理整个 JSON 对象
processed_data = replace_text(data)
# 将处理后的对象转回 JSON 字符串
return json.dumps(processed_data, ensure_ascii=False)
def main(input_file, output_file, old_text, new_text):
with open(input_file, 'r', encoding='utf-8') as infile, \
open(output_file, 'w', encoding='utf-8') as outfile:
# 计算总行数用于进度条
total_lines = sum(1 for _ in infile)
infile.seek(0) # 重置文件指针到开头
# 使用 tqdm 创建进度条
for line in tqdm(infile, total=total_lines, desc="Processing"):
processed_line = process_line(line.strip(), old_text, new_text)
outfile.write(processed_line + '\n')
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Replace text in a JSONL file.")
parser.add_argument("input_file", help="Input JSONL file to process")
parser.add_argument("output_file", help="Output file for processed JSONL")
parser.add_argument("--old_text", default="尖米", help="Text to be replaced")
parser.add_argument("--new_text", default="antgwy", help="Text to replace with")
args = parser.parse_args()
main(args.input_file, args.output_file, args.old_text, args.new_text)
执行如下脚本, 获得符合 XTuner 格式的训练数据 assistant_Tuner_change.jsonl。
cd ~/finetune/data
python change_script.py ./assistant_Tuner.jsonl ./assistant_Tuner_change.jsonl
可按如下方式查看数据
cat assistant_Tuner_change.jsonl | head -n 3
训练启动
首先按如下方式复制模型并修改 config,改好的在 ~/Tutorial/configs/internlm2_5_chat_7b_qlora_alpaca_e3_copy.py
mkdir /root/finetune/models
ln -s /root/share/new_models/Shanghai_AI_Laboratory/internlm2_5-7b-chat /root/finetune/models/internlm2_5-7b-chat
cd /root/finetune
mkdir ./config
cd config
xtuner copy-cfg internlm2_5_chat_7b_qlora_alpaca_e3 ./
运行如下命令进行微调
cd /root/finetune
conda activate xtuner-env
xtuner train ./config/internlm2_5_chat_7b_qlora_alpaca_e3_copy.py --deepspeed deepspeed_zero2 --work-dir ./work_dirs/assistTuner


然后将使用 Pytorch 训练出来的模型权重文件转换为目前通用的 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

转换完成后,可以看到模型被转换为 HuggingFace 中常用的 .bin 格式文件,这就代表着文件成功被转化为 HuggingFace 格式了。此时,hf 文件夹即为我们平时所理解的所谓 “LoRA 模型文件”
对于 LoRA 或者 QLoRA 微调出来的模型其实并不是一个完整的模型,而是一个额外的层(Adapter),训练完的这个层最终还是要与原模型进行合并才能被正常的使用。
对于全量微调的模型(full)其实是不需要进行整合这一步的,因为全量微调修改的是原模型的权重而非微调一个新的 Adapter ,因此是不需要进行模型整合的。
在 XTuner 中提供了一键合并的命令 xtuner convert merge,在使用前我们需要准备好三个路径,包括原模型的路径、训练好的 Adapter 层的(模型格式转换后的)路径以及最终保存的路径。
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


微调后修改模型路径,运行 xtuner_streamlit_demo.py 脚本来观察微调后的对话效果
streamlit run /root/Tutorial/tools/L1_XTuner_code/xtuner_streamlit_demo.py
# 确保端口映射正确
ssh -CNg -L 8501:127.0.0.1:8501 root@ssh.intern-ai.org.cn -p 36666

进阶任务
将自我认知的模型上传到 HuggingFace/Modelscope/魔乐平台,并将应用部署到 HuggingFace/Modelscope/魔乐平台
cd ~/finetune/work_dirs/assistTuner
git clone https://www.modelscope.cn/antgwy/InternLM-L1G5.git
cp -r ./merged/* ./InternLM-L1G5/
apt install git-lfs
git lfs install
git add .
git commit -m "init InternLM-L1G5"
git remote set-url origin https://antgwy:<token>@modelscope.cn/antgwy/InternLM-L1G5
git push
https://www.modelscope.cn/models/antgwy/InternLM-L1G5/files
部署应用到 Modelscope 平台,创建空间提交 requirements.txt 和 app.py 即可,见
https://www.modelscope.cn/studios/antgwy/InternLM-L1G5-Space

2149



被折叠的 条评论
为什么被折叠?



