Xtuner微调大模型
文章目录
- Xtuner微调大模型
- 一、介绍
- 二、安装使用
- 2.1 构建虚拟环境
- 2.1.1 创建虚拟环境
- 2.1.2 安装Xtuner
- 2.2 下载模型
- 2.3 微调准备
- 2.3.1 创建微调训练配置文件
- 2.3.2 修改微调训练配置文件
- 2.4 微调训练
- 2.5 模型转换
- 2.6 模型合并
Xtuner微调大模型
环境背景:Ubuntu24.04 系统 + Python3.10 + Cuda12.4 + Cudnn9.1 + torch2.6.0 + transformers4.48
测试环境 requirements.txt 下载
一、介绍
Xtuner 是一款用来微调大语言模型(LLM)的工具。在微调的过程中,用户可以直观地看到验证数据的训练情况。因此,Xtuner 更适合用来微调主观类的数据。
二、安装使用
2.1 构建虚拟环境
推荐使用 Python-3.10 的 conda 虚拟环境安装 XTuner
2.1.1 创建虚拟环境
conda create -n xtuner python=3.10 -y && conda activate xtuner
2.1.2 安装Xtuner
- 方案a:通过 pip 直接安装
pip install -U 'xtuner[deepspeed]'
- 方案b:通过源码安装【推荐】
# 拉取 XTuner
git clone <https://github.com/InternLM/xtuner.git>
cd xtuner
pip install -e '.[all]'
2.2 下载模型
此文以从 modelscope 平台下载 Qwen/Qwen1.5-0.5B-Chat 模型为例
from modelscope import snapshot_download
model_dir = snapshot_download('Qwen/Qwen1.5-0.5B-Chat',cache_dir='/root/work/ai/models/modelscope')
2.3 微调准备
2.3.1 创建微调训练配置文件
在 xtuner 的文件夹下找到 xtuner/xtuner/configs/qwen/qwen1_5/qwen1_5_0_5b_chat/qwen1_5_0_5b_chat_qlora_alpaca_e3.py
文件,将该文件复制一份至 xtuner/
根目录(如果使用其他模型,需要找到对应模型的配置文件)
配置文件名中,有形如 <model>_full_*.py
、<model>_qlora_*.py
、<model>_int8_lora*.py
的不同文件,作以下说明:
-
full:表示对整个模型的所有参数进行微调
-
qlora:基于量化+LoRA的低资源微调
model = dict(type=SupervisedFinetune,use_varlen_attn=use_varlen_attn,llm=dict(type=AutoModelForCausalLM.from_pretrained,pretrained_model_name_or_path=pretrained_model_name_or_path,trust_remote_code=True,torch_dtype=torch.float16,quantization_config=dict(type=BitsAndBytesConfig,load_in_4bit=True, # 是否开启4位QLoRA量化load_in_8bit=False, # 是否开启8位QLoRA量化llm_int8_threshold=6.0,llm_int8_has_fp16_weight=False,bnb_4bit_compute_dtype=torch.float16,bnb_4bit_use_double_quant=True,bnb_4bit_quant_type="nf4",),),lora=dict(type=LoraConfig,r=32, # LoRA 秩(参数量)lora_alpha=64, # 缩放系数lora_dropout=0.1,bias="none",task_type="CAUSAL_LM",),)
-
int8_lora:8位QLoRA量化
model = dict(type=SupervisedFinetune,use_varlen_attn=use_varlen_attn,llm=dict(type=AutoModelForCausalLM.from_pretrained,pretrained_model_name_or_path=pretrained_model_name_or_path,trust_remote_code=True,torch_dtype=torch.float16,load_in_8bit=True, # 是否开启8位QLoRA量化),lora=dict(type=LoraConfig,r=16, # LoRA 秩(参数量)lora_alpha=16, # 缩放系数lora_dropout=0.05,target_modules=["gate_proj", "down_proj", "up_proj"],bias="none",task_type="CAUSAL_LM",),)
2.3.2 修改微调训练配置文件
以下列举常用修改参数
#######################################################################
# PART 1 Settings #
#######################################################################
# 预训练模型路径,使用绝对路径
pretrained_model_name_or_path = '/root/work/ai/models/modelscope/Qwen/Qwen1.5-0.5B-Chat'
# 训练中最大的文本长度(序列分词后的最大长度)
max_length = 512
# 每一批训练样本的大小(根据情况自定义修改)
batch_size = 2
# 最大训练轮数
max_epochs = 3
# 保存间隔步数
save_steps = 300
# 训练过程中保存的检查点文件(checkpoint)的最大数量(-1表示不作限制)
save_total_limit = 2
# 验证数据
evaluation_inputs = ["请给我介绍五个上海的景点", "Please tell me five scenic spots in Shanghai"]#######################################################################
# PART 2 Model & Tokenizer #
#######################################################################
# 考虑是否需要修改模型参数#######################################################################
# PART 3 Dataset & Dataloader #
#######################################################################
# 修改微调数据路径
# json数据格式,data_files即为微调数据路径
dataset=dict(type=load_dataset, path="json", data_files=data_files)
# json数据格式,需要将dataset_map_fn参数值改为None
dataset_map_fn=None# alpaca数据格式,alpaca_en_path即为微调数据路径
dataset=dict(type=load_dataset, path=alpaca_en_path)
dataset_map_fn=alpaca_map_fn
# 其他开源指令微调数据集类似alpaca所使用的方法#######################################################################
# PART 4 Scheduler & Optimizer #
#######################################################################
# 考虑是否修改学习率调度器和优化器#######################################################################
# PART 5 Runtime #
####################################################################
# 加载检查点(checkpoint)的路径
load_from = None
# 是否从检查点开始继续训练
resume = False
2.4 微调训练
在 xtuner/
根目录下执行:
# FINETUNE_CFG:配置文件名
xtuner train ${FINETUNE_CFG}
# 例如:xtuner train qwen1_5_0_5b_chat_qlora_alpaca_e3.py
模型在训练过程中,会在 xtuner/work_dirs/<model>/
(此处应为 xtuner/work_dirs/qwen1_5_0_5b_chat_qlora_alpaca_e3/
)目录下根据设置的保存参数周期性地自动保存训练检查点:
- 如果是单卡训练,则会生成 pth 模型文件(例如 iter_10000.pth)
- 如果使用多卡训练(DeepSpeed),则会生成一个文件夹
一般来说,越后面生成的检查点,效果会越好。
2.5 模型转换
训练完成(模型微调数据已经收敛或者已经达到期望的训练效果,此时可能之前设置的训练轮次还没执行完)后,执行以下命令进行模型转换:
# FINETUNE_CFG:配置文件名
# PTH_PATH:训练生成的检查点(单卡选择文件路径,多卡选择文件夹路径)
# SAVE_PATH:转换后的模型保存路径(路径不存在会自动创建)
xtuner convert pth_to_hf ${FINETUNE_CFG} ${PTH_PATH} ${SAVE_PATH}
# 例如:xtuner convert pth_to_hf qwen1_5_0_5b_chat_qlora_alpaca_e3.py work_dirs/qwen1_5_0_5b_chat_qlora_alpaca_e3/iter_10000.pth out/qwen1_5_0_5b_chat_qlora_alpaca_e3/
此时生成的模型仅仅是个适配器,并不是一个完整的模型(因为这里是QLoRA微调)
【问题】
博主测试使用的是Pytorch2.6 (requirements.txt),出现以下提示:
`low_cpu_mem_usage` was None, now default to True since model is quantized.
Traceback (most recent call last):File "/root/work/ai/tools/xtuner/xtuner/tools/model_converters/pth_to_hf.py", line 151, in <module>main()File "/root/work/ai/tools/xtuner/xtuner/tools/model_converters/pth_to_hf.py", line 123, in mainstate_dict = guess_load_checkpoint(args.pth_model)File "/root/work/ai/tools/xtuner/xtuner/model/utils.py", line 314, in guess_load_checkpointstate_dict = torch.load(pth_model, map_location="cpu")File "/root/software/miniconda3/envs/xtuner/lib/python3.10/site-packages/torch/serialization.py", line 1470, in loadraise pickle.UnpicklingError(_get_wo_message(str(e))) from None
_pickle.UnpicklingError: Weights only load failed. This file can still be loaded, to do so you have two options, do those steps only if you trust the source of the checkpoint. (1) In PyTorch 2.6, we changed the default value of the `weights_only` argument in `torch.load` from `False` to `True`. Re-running `torch.load` with `weights_only` set to `False` will likely succeed, but it can result in arbitrary code execution. Do it only if you got the file from a trusted source.(2) Alternatively, to load with `weights_only=True` please check the recommended steps in the following error message.WeightsUnpickler error: Unsupported global: GLOBAL mmengine.logging.history_buffer.HistoryBuffer was not an allowed global by default. Please use `torch.serialization.add_safe_globals([HistoryBuffer])` or the `torch.serialization.safe_globals([HistoryBuffer])` context manager to allowlist this global if you trust this class/function.Check the documentation of torch.load to learn more about types accepted by default with weights_only https://pytorch.org/docs/stable/generated/torch.load.html.
【解决】
- 查看提示(1)
- 找到
xtuner/xtuner/model/utils.py
源码文件 - 将
state_dict = torch.load(pth_model, map_location="cpu")
修改为state_dict = torch.load(pth_model, map_location="cpu", weights_only=False)
即可
2.6 模型合并
如果使用了 LoRA / QLoRA 微调,则模型转换后将得到适配器 Adapter 参数,而并不包含原 LLM 参数。
- Full Fine-Tuning 全参数微调:生成的是完整模型,无需依赖基座模型
- LoRA/QLoRA 微调:生成的仅仅是适配器,必须与基座模型结合使用
如果期望获得合并后的模型权重(例如用于后续评测),则需要对模型进行合并:
# LLM:基座模型路径
# PTH_PATH:训练生成的检查点(单卡选择文件路径,多卡选择文件夹路径)
# SAVE_PATH:合并后的模型保存路径
xtuner convert merge ${LLM} ${LLM_ADAPTER} ${SAVE_PATH}
# 例如:xtuner convert merge /root/work/ai/models/modelscope/Qwen/Qwen1.5-0.5B-Chat out/qwen1_5_0_5b_chat_qlora_alpaca_e3 /root/work/ai/models/custom/qwen1_5_0_5b_chat_qlora_alpaca_e3/
至此,得到 /root/work/ai/models/custom/qwen1_5_0_5b_chat_qlora_alpaca_e3/
下的文件即为微调后的完整模型,可以直接使用