Qwen3-VL 微调全流程:从环境搭建到 vLLM 部署
本文旨在详细介绍使用 LLaMA-Factory 对多模态大模型(如 Qwen3-VL)进行 SFT 微调的完整链路,涵盖环境配置、数据集构造、LoRA 训练与合并,以及基于 vLLM 的高并发部署方案。
1. 环境准备
获取 LLaMA-Factory
推荐使用 Git 克隆项目,效率更高:
git clone --depth 1 https://github.com/hiyouga/LLaMA-Factory.git
若网络受限,也可下载压缩包解压至本地。
Python 依赖安装
创建虚拟环境并安装核心依赖。建议指定清华源加速下载:
conda create -n llama_env python=3.12
conda activate llama_env
cd LLaMA-Factory
pip install -e ".[torch,metrics]" --no-build-isolation -i https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple/
2. 模型下载
从 ModelScope 或 HuggingFace 下载基础模型。以 Qwen3-VL-2B-Instruct 为例:
modelscope download --model Qwen/Qwen3-VL-2B-Instruct --local_dir ./qwen3_vl_model
确保路径在后续配置中正确引用。
3. 启动微调 (SFT)
在 Linux 环境下,命令行是最高效的训练方式。我们首先使用官方示例数据集验证流程。
修改配置文件
进入 examples/train_lora 目录,编辑对应模型的 YAML 文件(如 qwen2_5vl_lora_sft.yaml)。关键配置说明如下:
### model
model_name_or_path: /data/hcb/LLaMA-Factory-main/qwen3_vl_model # 替换为你的模型路径
image_max_pixels: 262144
video_max_pixels: 16384
trust_remote_code: true
### method
stage: sft
do_train: true
finetuning_type: lora
lora_rank: 8
lora_target: all
### dataset
dataset: mllm_demo,identity,alpaca_en_demo # 默认测试数据集
template: qwen3_vl # 必须匹配模型对应的模板
cutoff_len: 2048
max_samples: 1000
overwrite_cache: true
preprocessing_num_workers: 16
### output
output_dir: saves/qwen3vl-2b/lora/sft
logging_steps: 10
save_steps: 500
plot_loss: true
report_to: none
### train
per_device_train_batch_size: 1
gradient_accumulation_steps: 8
learning_rate: 1.0e-4
num_train_epochs: 1.0
lr_scheduler_type: cosine
warmup_ratio: 0.1
bf16: true
ddp_timeout: 180000000
执行训练
设置可见 GPU 并启动训练脚本:
CUDA_VISIBLE_DEVICES=6 llamafactory-cli train examples/train_lora/qwen2_5vl_lora_sft.yaml
训练完成后,LoRA 权重将保存在 output_dir 指定的路径下。
4. 模型合并
微调结束后,需将 LoRA 权重合并回基座模型以便部署。
配置合并脚本
编辑 examples/merge_lora 下的 YAML 文件:
### model
model_name_or_path: /data/hcb/LLaMA-Factory-main/qwen3_vl_model # 原模型路径
adapter_name_or_path: saves/qwen3vl-2b/lora/sft # LoRA 权重路径
template: qwen3_vl
trust_remote_code: true
### export
export_dir: output/qwen3vl_lora_sft
export_size: 5
export_device: cpu
export_legacy_format: false
执行导出
运行以下命令完成合并:
llamafactory-cli export examples/merge_lora/qwen2_5vl_lora_sft.yaml
合并后的模型位于 export_dir 中,可直接用于推理服务。
5. 私有数据集构造
实际落地往往需要自定义数据。LLaMA-Factory 支持多种格式,多模态任务推荐参考 ShareGPT 格式。
注册新数据集
- 将整理好的 JSON 文件放入
data目录。 - 在
dataset_info.json中注册该数据集,指向文件名及图片存储路径。 - 确保图片路径与 JSON 中的
images字段一致。
例如,构造一个表格识别数据集 table_reg:
{
"type": "sharegpt",
"columns": {
"messages": "messages",
"images": "images"
}
}
提示词中需包含图像占位符,并在 images 列表中添加相对路径。配置完成后,在训练 YAML 的 dataset 字段填入注册名称即可开始训练。
6. 模型部署 (vLLM)
为了支持高并发和工业级调用,推荐使用 vLLM 部署合并后的模型,并暴露 OpenAI 兼容接口。
安装 vLLM
在虚拟环境中安装指定版本:
pip install vllm==0.11.0 -i https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple/
启动服务
使用以下命令启动 API 服务器。注意调整显存利用率和并行度以适应硬件:
export CUDA_VISIBLE_DEVICES=6
python -m vllm.entrypoints.openai.api_server \
--host 0.0.0.0 \
--port 8003 \
--model /data/hcb/LLaMA-Factory-main/output/qwen3vl_lora_sft \
--served-model-name qwen3_vl \
--trust-remote-code \
--dtype float16 \
--gpu-memory-utilization 0.8 \
--tp 1
启动成功后,服务将监听在 8003 端口。
客户端调用示例
编写 Python 脚本通过 OpenAI SDK 发起请求。注意处理 Base64 编码和多模态消息结构:
import openai
import base64
import os
from openai import OpenAI
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode('utf-8')
def multimodal_chat(image_path=None, text_prompt="描述这张图片"):
client = OpenAI(
api_key="Empty",
base_url="http://localhost:8003/v1/"
)
messages = [{"role": "system", "content": "你是一个多模态智能助手,可以理解和分析图像内容。"}]
if image_path and os.path.exists(image_path):
base64_image = encode_image(image_path)
user_content = [
{"type": "text", "text": text_prompt},
{"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{base64_image}"}}
]
else:
user_content = text_prompt
messages.append({"role": "user", "content": user_content})
payload = {
"model": "qwen3_vl",
"messages": messages,
"temperature": 0.1,
"max_tokens": 2000
}
try:
response = client.chat.completions.create(**payload, timeout=30)
return response
except Exception as e:
print(f"请求失败:{e}")
return None
if __name__ == "__main__":
image_path = r"/path/to/your/image.png"
prompt = "描述这张图片中有什么"
if os.path.exists(image_path):
res = multimodal_chat(image_path=image_path, text_prompt=prompt)
if res and res.choices:
print("模型回复:")
print(res.choices[0].message.content)
else:
print("请求失败")
至此,微调与部署流程全部完成。根据实际业务需求调整 batch size、学习率及显存参数,即可获得稳定的推理服务。


