前言

        本篇文章是基于lora对qwen的微调,但是对于每个人的机器配置以及cuda环境,可能会导致一些问题,如果遇到问题可以发在评论区,大家一起研究,同时测试数据我放到下面了,需要的自行获取。

        更新:qwen1.5微调文章已经更新

五步炼丹,qwen通义千问1.5版本微调实战

1、环境准备

首先需要克隆qwen仓库的代码:

git clone https://github.com/QwenLM/Qwen.git

接着跳转到项目目录下:

cd Qwen

然后安装项目所需的依赖包:

pip install deepspeed transformers==4.32.0 peft pydantic==1.10.13 transformers_stream_generator einops tiktoken

数据格式最终要求是列表中存在多个字典数据(如下官方数据实例):(数据自行整理,如果使用下面代码文件命名为chat.json)

基于lora的通义千问qwen大模型微调实战_nlp

现在让我们下载模型文件(我这里用的1.8b的小模型,7b以上的去modelscope或huggingface下载模型文件):

git clone https://modelscope.cn/qwen/Qwen-1_8B-Chat.git

2、单机单卡训练 

做好前期的准备工作后就可以进行单机单卡的微调了:

export CUDA_DEVICE_MAX_CONNECTIONS=1
export CUDA_VISIBLE_DEVICES=0

执行Python文件

python finetune.py --model_name_or_path Qwen-1_8B-Chat --data_path chat.json --fp16 True --output_dir output_qwen --num_train_epochs 5 --per_device_train_batch_size 2 --per_device_eval_batch_size 1 --gradient_accumulation_steps 8 --evaluation_strategy "no" --save_strategy "steps" --save_steps 1000 --save_total_limit 10 --learning_rate 3e-4 --weight_decay 0.1 --adam_beta2 0.95 --warmup_ratio 0.01 --lr_scheduler_type "cosine" --logging_steps 1 --report_to "none" --model_max_length 512 --lazy_preprocess True --gradient_checkpointing --use_lora

参数及解释:

--model_name_or_path Qwen-1_8B-Chat:指定预训练模型的名称或路径,这里是使用名为"Qwen-1_8B-Chat"的预训练模型。
--data_path chat.json:指定训练数据和验证数据的路径,这里是使用名为"chat.json"的文件。
--fp16 True:指定是否使用半精度浮点数(float16)进行训练,这里设置为True。
--output_dir output_qwen:指定输出目录,这里是将训练结果保存到名为"output_qwen"的文件夹中。
--num_train_epochs 5:指定训练的轮数,这里是训练5轮。
--per_device_train_batch_size 2:指定每个设备(如GPU)上用于训练的批次大小,这里是每个设备上训练2个样本。
--per_device_eval_batch_size 1:指定每个设备上用于评估的批次大小,这里是每个设备上评估1个样本。
--gradient_accumulation_steps 8:指定梯度累积步数,这里是梯度累积8步后再更新模型参数。
--evaluation_strategy "no":指定评估策略,这里是不进行评估。
--save_strategy "steps":指定保存策略,这里是每隔一定步数(如1000步)保存一次模型。
--save_steps 1000:指定保存步数,这里是每隔1000步保存一次模型。
--save_total_limit 10:指定最多保存的模型数量,这里是最多保存10个模型。
--learning_rate 3e-4:指定学习率,这里是3e-4。
--weight_decay 0.1:指定权重衰减系数,这里是0.1。
--adam_beta2 0.95:指定Adam优化器的beta2参数,这里是0.95。
--warmup_ratio 0.01:指定预热比例,这里是预热比例为总步数的1%。
--lr_scheduler_type "cosine":指定学习率调度器类型,这里是余弦退火调度器。
--logging_steps 1:指定日志记录步数,这里是每1步记录一次日志。
--report_to "none":指定报告目标,这里是不报告任何信息。
--model_max_length 512:指定模型的最大输入长度,这里是512个字符。
--lazy_preprocess True:指定是否使用懒加载预处理,这里设置为True。
--gradient_checkpointing:启用梯度检查点技术,可以在训练过程中节省显存并加速训练。
--use_lora:指定是否使用LORA(Layer-wise Relevance Analysis)技术,这里设置为True

建议:根据自己的场景调参,如训练的轮次不能太少

3、单机多卡

 单机多卡:

sed -i 's/"auto"/None/g' finetune.py
export CUDA_DEVICE_MAX_CONNECTIONS=1
torchrun --nproc_per_node 2 --nnodes 1 --node_rank 0 --master_addr localhost --master_port 6001 finetune.py --model_name_or_path Qwen-1_8B-Chat --data_path chat.json --fp16 True --output_dir output_qwen --num_train_epochs 5 --per_device_train_batch_size 2 --per_device_eval_batch_size 1 --gradient_accumulation_steps 8 --evaluation_strategy "no" --save_strategy "steps" --save_steps 1000 --save_total_limit 10 --learning_rate 3e-4 --weight_decay 0.1 --adam_beta2 0.95  --warmup_ratio 0.01  --lr_scheduler_type "cosine"  --logging_steps 1 --report_to "none"  --model_max_length 128  --lazy_preprocess True   --use_lora  --gradient_checkpointing  --deepspeed finetune/ds_config_zero3.json

4、保存与测试

微调后得到的是小模型,现在让我们将它和原始模型进行合并创建py文件随便命名,然后 python x.py 执行下面代码:

from peft import AutoPeftModelForCausalLM 
from transformers import AutoTokenizer 
model = AutoPeftModelForCausalLM.from_pretrained( "output_qwen", device_map="auto", trust_remote_code=True ).eval() 
merged_model = model.merge_and_unload() 
merged_model.save_pretrained("qwen-1_8b-finetune", max_shard_size="2048MB", safe_serialization=True) # 最大分片2g
tokenizer = AutoTokenizer.from_pretrained( "output_qwen", trust_remote_code=True ) 

tokenizer.save_pretrained("qwen-1_8b-finetune")

最终我们就可以使用微调后的模型了测试代码:

from transformers import AutoModelForCausalLM, AutoTokenizer, GenerationConfig 
tokenizer = AutoTokenizer.from_pretrained("qwen-1_8b-finetune", trust_remote_code=True)
 
model = AutoModelForCausalLM.from_pretrained("qwen-1_8b-finetune", device_map="auto", 
trust_remote_code=True).eval() 
response, history = model.chat(tokenizer, "", history=None) 
print(response)

测试效果:

基于lora的通义千问qwen大模型微调实战_人工智能_02

以上是单机单卡的微调,如果没有数据,但是想测试数据可以私信我

额,发现要测试数据的人有点多,我就git上建了仓库,有需要的直接去拉数据就行了

地址:

https://github.com/liukangjia666/qwen_data_process

讨论交流

关注公众浩【AI疯人院】