大模型微调指南之 Xtuner 篇:3步实现Qwen1.5中文对话模型优化

一、介绍

Xtuner 是一款用来微调大语言模型(LLM)的工具。在微调的过程中,用户可以直观地看到验证数据的训练情况。因此,Xtuner 更适合用来微调主观类的数据。

二、安装使用

2.1 构建虚拟环境

推荐使用 Python-3.10 的 conda 虚拟环境安装 XTuner

2.1.1 创建虚拟环境

1
conda create -n xtuner python=3.10 -y && conda activate xtuner

2.1.2 安装 Xtuner

  • 方案 a:通过 pip 直接安装
1
pip install -U 'xtuner[deepspeed]'
  • 方案 b:通过源码安装【推荐】
1
2
3
4
# 拉取 XTuner
git clone <https://github.com/InternLM/xtuner.git>
cd xtuner
pip install -e '.[all]'

2.2 下载模型

此文以从 modelscope 平台下载 Qwen/Qwen1.5-0.5B-Chat 模型为例

1
2
from modelscope import snapshot_download
model_dir = snapshot_download('Qwen/Qwen1.5-0.5B-Chat',cache_dir='/root/workspace/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 的低资源微调

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    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 量化

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    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 修改微调训练配置文件

以下列举常用修改参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#######################################################################
# PART 1 Settings #
#######################################################################
# 预训练模型路径,使用绝对路径
pretrained_model_name_or_path = '/root/workspace/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/ 根目录下执行:

1
2
3
# FINETUNE_CFG:配置文件名
xtuner train ${FINETUNE_CFG}
# 例如:xtuner train qwen1_5_0_5b_chat_qlora_alpaca_e3.py

模型在训练过程中,会在 `xtuner/work_dirs/<mode 给我重新修改下这几篇文章的标题,主要用于 csdn 博客

训练完成(模型微调数据已经收敛或者已经达到期望的训练效果,此时可能之前设置的训练轮次还没执行完)后,执行以下命令进行模型转换:

1
2
3
4
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),出现以下提示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
`low_cpu_mem_usage` was None, now default to True since model is quantized.
Traceback (most recent call last):
File "/root/workspace/ai/tools/xtuner/xtuner/tools/model_converters/pth_to_hf.py", line 151, in <module>
main()
File "/root/workspace/ai/tools/xtuner/xtuner/tools/model_converters/pth_to_hf.py", line 123, in main
state_dict = guess_load_checkpoint(args.pth_model)
File "/root/workspace/ai/tools/xtuner/xtuner/model/utils.py", line 314, in guess_load_checkpoint
state_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 load
raise 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. 查看提示(1)
  2. 找到 xtuner/xtuner/model/utils.py 源码文件
  3. 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 微调:生成的仅仅是适配器,必须与基座模型结合使用

如果期望获得合并后的模型权重(例如用于后续评测),则需要对模型进行合并:

1
2
3
4
5
# LLM:基座模型路径
# LLM_ADAPTER:模型转换后得到的适配器 Adapter 参数,选择上一步输出的保存路径即可
# SAVE_PATH:合并后的模型保存路径
xtuner convert merge ${LLM} ${LLM_ADAPTER} ${SAVE_PATH}
# 例如:xtuner convert merge /root/workspace/ai/models/modelscope/Qwen/Qwen1.5-0.5B-Chat out/qwen1_5_0_5b_chat_qlora_alpaca_e3 /root/workspace/ai/models/custom/qwen1_5_0_5b_chat_qlora_alpaca_e3/

至此,得到 /root/workspace/ai/models/custom/qwen1_5_0_5b_chat_qlora_alpaca_e3/ 下的文件即为微调后的完整模型,可以直接使用


大模型微调指南之 Xtuner 篇:3步实现Qwen1.5中文对话模型优化
https://blog.echo-silence.top/posts/3897029f.html
作者
极客奶爸
发布于
2025年5月20日
许可协议