(LLaMa Factory)大模型训练方法--监督微调(Qwen2-0.5B)
1、准备训练数据:
SFT
的数据格式有多种,例如:Alpaca格式、OpenAI格式等。
#其中Alpaca格式如下:
[
{
"instruction":"human instruction (required)",
"input":"human input (optional)",
"output":"model response (required)",
"system":"system prompt (optional)",
"history":[
[
"human instruction in the first round (optional)","model response in the first round (optional)"
],
[
"human instruction in the second round (optional)","model response in the second round (optional)"
]
]
}
]
根据以上的数据格式,我们在ModelScope的数据集找到中文医疗对话数据-Chinese-medical-dialogue符合上述格式。
# 使用git命令拉取数据集 至data目录下
git clone https://www.modelscope.cn/datasets/xiaofengalg/Chinese-medical-dialogue.git /mnt/workspace/LLaMA-Factory/data
注册自定义数据 : 在dataset_info.json
中添加如下数据集:
"custom_sft_train_data":{
"file_name":"Chinese-medical-dialogue/data/train_0001_of_0001.json",
"columns":{
"prompt":"instruction",
"query":"input",
"response":"output"
}
},
2、配置训练参数
• Model name: Qwen2-0.5B
• Model path: saves/Qwen2-0.5B/full/Qwen2_pretrain_output_demo1
• Finetuning method: full
• Stage : Supervised Fine-Tuning
• Dataset: custom_sft_train_data
• Output dir: Qwen2_sft_output_demo1
配置参数说明:
• Model path:我们选择第1阶段预训练模型的输出目录。
• Stage:这一阶段,因为我们要进行微调,选择Supervised Fine-Tuning。
• Output dir: 更换一个新的输出路径,以便后续开展第3阶段训练,例如:Qwen2_sft_output_demo1
3、启动训练 : 点击
Preview Command
预览命令行 , 命令行确认无误后,点击Start
即可开启训练。
llamafactory-cli train
--stage sft
--do_train True
--model_name_or_path saves/Qwen2-0.5B/full/Qwen2_pretrain_output_demo1
--preprocessing_num_workers 16
--finetuning_type full
--template default
--flash_attn auto
--dataset_dir data
--dataset custom_sft_train_data
--cutoff_len 1024
--learning_rate 5e-05
--num_train_epochs 3.0
--max_samples 100000
--per_device_train_batch_size 2
--gradient_accumulation_steps 8
--lr_scheduler_type cosine
--max_grad_norm 1.0
--logging_steps 5 #每 5 步记录一次训练日志。
--save_steps 100 #每 100 步保存一次模型检查点。这里最好将save_steps 设置大一点,否则训练过程会生成非常多的训练日志,导致硬盘空间不足而训练终止。
--warmup_steps 0
--optim adamw_torch
--packing False
--report_to none
--output_dir saves/Qwen2-0.5B/full/Qwen2_sft_output_demo1
--bf16 True
--plot_loss True
--ddp_timeout 180000000
--include_num_input_tokens_seen True
训练过程中,记得实时关注资源的消耗情况:
-
显存:使用
watch -n 1 nvidia-smi
实时查看显存开销。 -
硬盘:使用
watch -n 1 df -h /mnt
实施查看/mnt分区的磁盘使用情况。
历时6小时58分钟后,模型终于训练完毕。(配置的1张4090的卡,显存24GB)
# 验证模型
1. 在LLaMA Factory的WebUI界面上,切换至Chat界面
2. Model path: 输入刚才训练模型的输出目录,即saves/Qwen2-0.5B/full/Qwen2_sft_output_demo1
3. 其他配置保持默认不变;
4. 点击Load model,待模型加载成功后,输入看病相关的信息,测试模型的能力。
6、总结
LLaMA-Factory是一个开源的、可自定义的、可扩展的、可部署的、可训练的大模型训练平台。
训练过程的大致步骤为:
-
按照LLaMA-Factory官方README文档的数据格式,准备训练数据;
-
按照LlaMA-Factory官方README文档,在的dataset_info.json文件,注册自定义数据
-
根据训练阶段配置训练参数,包括模型名称、模型路径、训练方法、数据集、输出目录等;
-
预览训练命名无误后,启动训练。
-
如果启动训练失败,可以通过切换到启动
LLaMA Factory
的命令行查看日志信息排查问题。