我目前正在参加“书生大模型实战营”。这是一个旨在帮助学员掌握大模型开发和应用的实战课程。
为了更好地记录完成过程,我根据官方提供的教程文档提取了核心步骤,并去掉了详细的背景知识介绍和说明,这样后续一个手册查找起来会更加直观。
但建议大家在实际学习过程中还是多看看原文,因为原文档确实非常的详细和完整,方便了解每一步的具体原因和背后的原理,这样有助于更牢固地掌握知识,提高实战能力。
基础岛-第5关
本地环境:Win11。
完成任务步骤记录
任务一:微调小助手
目标:使用 XTuner 微调 InternLM2-Chat-7B 实现自己的小助手认知,如下图所示(图中的尖米需替换成自己的昵称)。
完成所需时间:半天,我是一边跑着任务,一边做着其它事情,时间可能比实际多一点,其中最大一块是“训练”-“启动微调”过程较久。
步骤:
- 使用 conda 先构建一个 Python-3.10 的虚拟环境:
和之前教程没有太大区别,建立本关卡使用的文件夹和环境。
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
2. 安装 XTuner:
VS Code远程链接开发机后,在VS Code的终端中运行命令:
# 创建新的conda环境,命名为 llamaindex。
conda create -n llamaindex python=3.10
# 激活 llamaindex conda环境。
conda activate llamaindex
# 安装python 依赖包
pip install einops==0.7.0 protobuf==5.26.
3. 修改提供的数据:
# 创建文件夹存放微调数据
mkdir -p /root/finetune/data && cd /root/finetune/data
cp -r /root/Tutorial/data/assistant_Tuner.jsonl /root/finetune/data
# 创建 `change_script.py` 文件,VS Code直接手动创建也一样
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
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="机智流", help="Text to replace with")
args = parser.parse_args()
main(args.input_file, args.output_file, args.old_text, args.new_text)
4. 训练:
# 复制模型
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 {path/to/finetune}
cd /root/finetune
mkdir ./config
cd config
xtuner copy-cfg internlm2_5_chat_7b_qlora_alpaca_e3 ./
# 拉取后更改配置文件,参考下方
# 启动微调
cd /root/finetune
xtuner train ./config/internlm2_5_chat_7b_qlora_alpaca_e3_copy.py --deepspeed deepspeed_zero2 --work-dir ./work_dirs/assistTuner
# 权重转换
cd /root/finetune/work_dirs/assistTuner
# 先获取最后保存的一个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
# 模型合并
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
修改配置文件 /root/finetune/config/internlm2_5_chat_7b_qlora_alpaca_e3_copy.py
可参考 ~/Tutorial/configs/internlm2_5_chat_7b_qlora_alpaca_e3_copy.py
。
- 验证:
cd ~/Tutorial/tools/L1_XTuner_code
# 修改模型为微调后的模型,具体代码参考后续代码块
# 启动
conda activate xtuner-env
streamlit run /root/Tutorial/tools/L1_XTuner_code/xtuner_streamlit_demo.py
# 直接修改脚本文件第18行
- model_name_or_path = "Shanghai_AI_Laboratory/internlm2_5-7b-chat"
+ model_name_or_path = "/root/finetune/work_dirs/assistTuner/merged"
启动成功截图如下:
我建立开发机之前已经建立过端口映射,这里不需要再次操作。
本地访问http://127.0.0.1:8501/
,截图如下:
任务二:模型上传
目标:将自我认知的模型上传到 HuggingFace/Modelscope/魔乐平台,并将应用部署到 HuggingFace/Modelscope/魔乐平台 。
完成所需时间:6小时,其中最大的时间就是发布应用,一直失败,最后升级云资源后成功,上传可能和我网速慢有关,仅供参考。
步骤:
之前操作过Hugging Face的流程,本次采用ModelScope。
- 前置准备:
注册并登录ModelScope。
通过Web界面建立模型。
- 上传模型:
(1)准备
# 检出模型库
git clone https://oauth2:<ModelScopt GIT 令牌>@www.modelscope.cn/<ModelScope用户名>/<建立模型库名称>.git
# 安装git-lfs
apt install git-lfs
git lfs install
- ModelScopt GIT 令牌
- ModelScope用户名:(见下图)
- 建立模型库名称:(见下图)
(2)git 提交,internlm2_5-7b-chat_flyfive_xtuner为我创建的模型名。
# 复制合并后的模型
mv /root/finetune/work_dirs/assistTuner/merged/* /root/finetune/internlm2_5-7b-chat_flyfive_xtuner/
cd /root/finetune/internlm2_5-7b-chat_flyfive_xtuner
# 提交并推送
git add .
git commit -m "init"
git push -u origin master
git add整个模型文件很慢,为了避免无法获取进度,大的模型文件,我是手动一个个git add的。
- 部署应用:
应用地址:www.modelscope.cn/studios/Fly…
由于开着都是费用,验证完成后已经下线。
(1)创建创空间
(2)提交代码
直接按照上一步创建成功页面的命令执行即可。
(3)验证
注意:ModelScope创空间的免费云资源跑任务一中的模型会出现Out of memory问题,我是升级了云资源后成功的。
资源配置:NVIDIA A10 * 1 • 16v CPU • 60G • ¥11.1/小时 • 1个实例 • 休眠时长60分钟
requirements.txt文件如下:
torch==2.5.0 --index-url https://download.pytorch.org/whl/cu121
torchvision==0.20.0 --index-url https://download.pytorch.org/whl/cu121
# 默认安装版本不兼容
transformers==4.39.0
dataclasses
最终结果如下: