Qwen2模型Text2SQL微调与GGUF量化完整技术实现与步骤详解
类型:热点整理2026-07-17
使用Llama-Factory对Qwen2-1 5B模型进行Text2SQL微调,采用指令微调格式准备数据集并配置参数,BLEU-4达88 44。合并LoRA权重导出为safetensors,转换为GGUFFP16并用量化方法Q4_K_M压缩,实现本地高效部署。
这里,模型我们选择Qwen2-1.5B模型,微调框架使用Llama-Factory。

Qwen2-1.5B微调
首先从环境搭建入手。建议使用conda创建一个干净的Python环境,这是确保后续步骤顺利的基础。
**准备python环境**
```bash
conda create --name llama_factory python=3.11
conda activate llama_factory
```
**部署llama-factory**
接下来,克隆Llama-Factory框架并安装所需的依赖包。这里有几个容易踩坑的地方需要注意:例如在Windows系统下运行QLoRA量化时,需要单独安装bitsandbytes的Windows预编译版本;如果启动时报错`get_full_repo_name`,只需安装chardet库即可解决。
```bash
git clone --depth 1 https://github.com/hiyouga/LLaMA-Factory.git
cd LLaMA-Factory
pip3 install -e ".[torch,metrics]"
# 如果要在 Windows 平台上开启量化 LoRA(QLoRA),需要安装预编译的 bitsandbytes 库
pip3 install https://github.com/jllllll/bitsandbytes-windows-webui/releases/download/wheels/bitsandbytes-0.41.2.post2-py3-none-win_amd64.whl
# 安装pytorch
conda install pytorch torchvision torchaudio pytorch-cuda=11.8 -c pytorch -c nvidia
# 如启动报错,出现ImportError: cannot import name 'get_full_repo_name' from 'huggingface_hub',需安装chardet
pip3 install chardet
```
执行`python src/webui.py`启动,就可以看到图形化界面了:
**Text2SQL微调**
接下来是全文的核心环节——微调。我们分步骤详细说明。
**(1)准备样本数据集**。数据格式至关重要,采用典型的指令微调格式。一个完整的样本示例如下:
```json
{
"db_id":"department_management",
"instruction":"I want you to act as a SQL terminal in front of an example database, you need only to return the sql command to me.Below is an instruction that describes a task, Write a response that appropriately completes the request.\n\n##Instruction:\ndepartment_management contains tables such as department, head, management. Table department has columns such as Department_ID, Name, Creation, Ranking, Budget_in_Billions, Num_Employees. Department_ID is the primary key.\nTable head has columns such as head_ID, name, born_state, age. head_ID is the primary key.\nTable management has columns such as department_ID, head_ID, temporary_acting. department_ID is the primary key.\nThe head_ID of management is the foreign key of head_ID of head.\nThe department_ID of management is the foreign key of Department_ID of department.\n\n",
"input":"###Input:\nHow many heads of the departments are older than 56 ?\n\n###Response:",
"output":"SELECT count(*) FROM head WHERE age > 56",
"history":[]
}
```
**(2)注册数据集**。将制作好的JSON文件放置到`LLaMA-Factory/data`目录下,然后在`dataset_info.json`中添加相应的配置项。
```json
"text2sql_train": {
"file_name":"text2sql_train.json",
"columns":{
"prompt":"instruction",
"query":"input",
"response":"output",
"history":"history"
}
},
"text2sql_dev":{
"file_name":"text2sql_dev.json",
"columns":{
"prompt":"instruction",
"query":"input",
"response":"output",
"history":"history"
}
}
```
**(3)配置训练参数**。这一步虽然参数较多,但意义清晰明确。下面是一套可以直接参考的配置:
```bash
llamafactory-cli train `
--stage sft `
--do_train True`
--model_name_or_path D:\LLM\Qwen2-1.5B-Instruct `
--preprocessing_num_workers 16`
--finetuning_type lora `
--quantization_method bitsandbytes `
--template qwen `
--flash_attn auto `
--dataset_dir D:\python_project\LLaMA-Factory\data `
--dataset text2sql_train `
--cutoff_len 1024 `
--learning_rate 0.0001`
--num_train_epochs 2.0 `
--max_samples 100000`
--per_device_train_batch_size 2 `
--gradient_accumulation_steps 4`
--lr_scheduler_type cosine `
--max_grad_norm 1.0`
--logging_steps 20 `
--sa ve_steps 500`
--warmup_steps 0 `
--optim adamw_torch `
--packing False `
--report_to none `
--output_dir sa ves\Qwen2-1.5B-Chat\lora\train_2024-07-19-19-45-59 `
--bf16 True`
--plot_loss True `
--ddp_timeout 180000000`
--include_num_input_tokens_seen True `
--lora_rank 8`
--lora_alpha 16 `
--lora_dropout 0`
--lora_target all
```
**(4)推理评估**。训练完成后,使用测试集进行推理,评估模型效果。从评测指标来看,模型表现相当出色:
```json
{
"predict_bleu-4":88.43791015473889,
"predict_rouge-1":92.31425483558995,
"predict_rouge-2":85.43010570599614,
"predict_rouge-l":89.06327794970986,
"predict_runtime":1027.4111,
"predict_samples_per_second":1.006,
"predict_steps_per_second":0.503
}
```
这里简要解读一下各评估指标的含义:
* **predict_bleu-4**:BLEU-4分数,衡量生成文本与参考文本的4-gram匹配度,数值越高表示越接近标准答案,满分为100。
* **predict_rouge-1和predict_rouge-2**:ROUGE-1和ROUGE-2,分别评估单个词和双词序列的匹配程度,同样越高越好。
* **predict_rouge-l**:ROUGE-L,基于最长公共子序列的匹配度。
* **predict_runtime**:预测总耗时。
* **predict_samples_per_second**:每秒生成的样本数。
* **predict_steps_per_second**:每秒执行的预测步数。
从数据来看,模型效果令人满意,您可以基于自己的样本数据灵活调整各参数。
**(5)导出模型**。当效果达到预期后,可以将微调后的LoRA权重合并并导出。注意在导出时选择您训练好的checkpoint。
GGUF模型
微调完成后导出的模型通常是safetensors格式。为了让模型在本地更高效地运行,我们需要将其转换为GGUF格式,并使用llama.cpp进行部署。推荐使用`w64devkit + make`方案来编译llama.cpp。
**安装make**
下载地址:https://gnuwin32.sourceforge.net/packages/make.htm
安装完成后,将安装路径添加到系统环境变量PATH中。在终端验证一下,如果出现版本信息即表示安装成功:
```bash
>make -v
GNU Make 3.81
Copyright (C) 2006 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE.
This program built for i386-pc-mingw32
```
**安装MinGW**
下载MinGW,并将`mingw64/bin`目录也添加到环境变量PATH中。
**安装w64devkit**
下载地址:https://github.com/skeeto/w64devkit/releases
下载`w64devkit-fortran-1.23.0.zip`后解压。**注意**:解压路径中**不要包含中文**。
**编译llama.cpp**
下载地址:https://github.com/ggerganov/llama.cpp
使用w64devkit的终端进入llama.cpp目录,然后执行`make`。编译成功后,会生成一系列exe文件。
```bash
~ $ cd D:
D:/ $ cd /LLM/llama.cpp
D:/LLM/llama.cpp $ make
```
make成功后,安装Python依赖:
```bash
conda create --name llama_cpp python=3.11
conda activate llama_cpp
pip3 install -r requirements.txt
```
**转换为GGUF FP16格式**
准备工作就绪后,进入核心转换环节。使用`convert_hf_to_gguf.py`脚本即可将safetensors模型转换为GGUF的FP16格式:
```bash
# model_path/mymodel为我们实际的模型路径
python convert_hf_to_gguf.py model_path/mymodel
```
运行日志会详细展示转换过程,最终生成一个`.gguf`文件。
**模型量化**
FP16格式的模型虽然精度高,但占用空间较大。为了进一步压缩模型体积,可以对其进行量化。例如,使用Q4_K_M方法:
```bash
# model_path/mymodel-F16.gguf为刚刚得到的FP16模型,model_path/mymodel_Q4_k_M.gguf为要得到的量化模型,Q4_K_M为使用Q4_K_M方法
llama-quantize.exe model_path/mymodel-F16.gguf model_path/mymodel_Q4_k_M.gguf Q4_K_M
```
量化完成后,即可获得一个体积更小、推理速度更快的`Qwen2-1.5B-Instruct_Q4_k_M.gguf`模型。至此,从微调到部署的完整流程已全部打通。