书生大模型第四期打卡 | 第五关 大模型微调之Xtuner

什么是Xtuner?

一种高效的微调框架,适合多种生态和硬件功能。集成了多种任务类型,支持很多开源生态。

大模型的两种微调范式:

1、增量预训练:通过文章、书籍、代码等,让基座模型学到一些新的知识,如某个垂类领域的常识

2、指令跟随微调:通过高质量的对话、问答数据,让模型学会对话模版,根据人类指令进行对话

一般大模型通过增量预训练得到垂类基座模型,再通过指令跟随得到垂类对话模型。

解决微调所需显存的问题:Lora和Qlora。

Lora:在原本的linear层之间新增一个支路adapter

上手!

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
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

这里注意不能用torch2.5,指定版本用2.4.1,并且在卡住的时候耐心等,不要急着Kill。

2、验证安装,环境配置成功时,输入xtuner list-cfg,不会报错。

3、修改提供的数据,创建新文件夹并创建修改脚本。

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

4、在脚本中放以下代码,将“机智流”换成自定义的名字。

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)

5、执行脚本,生成如下结构

|-- /finetune/data/
    |-- assistant_Tuner.jsonl
    |-- assistant_Tuner_change.jsonl

6、复制模型,进行训练

        这里推荐使用InternStudio开发机,如果使用其他机器,可以在魔搭社区或者hf上下载internlm2_5-7b-chat模型,放入以下路径。

mkdir /root/finetune/models

ln -s /root/share/new_models/Shanghai_AI_Laboratory/internlm2_5-7b-chat /root/finetune/models/internlm2_5-7b-chat

7、在finetune目录下新建文件夹,获取官方的config并进行修改

获取方式:

# cd {path/to/finetune}
cd /root/finetune
mkdir ./config
cd config
xtuner copy-cfg internlm2_5_chat_7b_qlora_alpaca_e3 ./

修改路径:

修改问题,这里的问题用于评测训练表现,应当与要微调的内容相关?

更改Dataloader:

8、开始微调

       微调命令 xtuner train,config是配置文件即internlm2_5_chat_7b_qlora_alpaca_e3_copy.py,deepseed节约显存,work-dir是文件保存位置。

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

        训练过程:就是模型的正常训练过程

9、将pytorch训练出来的格式转换为hf需要的格式

cd /root/finetune/work_dirs/assistTuner
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

转换后的目录结构:

├── hf
│   ├── README.md
│   ├── adapter_config.json
│   ├── adapter_model.bin
│   └── xtuner_config.py

10、查看微调后的对话效果

修改模型路径为微调后的:

建立网页:

streamlit run /root/Tutorial/tools/L1_XTuner_code/xtuner_streamlit_demo.py

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值