跳到主要内容Qwen3-VL 基于 Llama-Factory 的 QLoRA 微调与部署全流程实战 | 极客日志PythonAI算法
Qwen3-VL 基于 Llama-Factory 的 QLoRA 微调与部署全流程实战
Qwen3-VL 基于 Llama-Factory 的 QLoRA 微调与部署全流程实战。内容涵盖环境配置、Open-EQA 数据集训练、评估指标分析、模型合并以及 Ollama 和 LMDeploy 两种部署方案。重点展示在 16GB 显存 T4 显卡上的实操细节,包括 Unsloth 加速、TensorBoard 监控及 PyTorch 后端推理优化,为具身智能多模态任务提供完整落地参考。
山野来信1 浏览 Qwen3-VL 基于 Llama-Factory 的 QLoRA 微调与部署全流程实战
本次实战以具身智能数据集 Open-EQA 为例,演示如何在 16GB 显存的 NVIDIA Tesla T4 环境下,完成 Qwen3-VL-2B-Instruct 模型的嵌套量化 QLoRA 训练、评估、导出及 Ollama/LMDeploy 部署。每个样本包含八张图片,经过处理后划分为训练 - 验证集和测试集。
1. 环境准备与训练配置
有 CUDA 显卡的用户建议安装 Unsloth 来加速训练和推理。同时,为了完整记录训练过程,避免中断后只能看到部分曲线,务必安装 TensorBoard:
pip install unsloth tensorboard
在 saves/Qwen3-VL-2B-Instruct/qlora/train_openeqa 目录下创建 training_args.yaml。这里的关键是合理设置量化参数和显存占用策略。对于 T4 这种单卡环境,双量化(double_quantization)能有效节省显存。
model_name_or_path: model/Qwen3-VL-2B-Instruct
trust_remote_code: true
stage: sft
do_train: true
finetuning_type: lora
lora_target: all
lora_rank: 8
lora_alpha: 16
lora_dropout: 0.1
use_unsloth: false
flash_attn: auto
quantization_bit: 4
quantization_method: bitsandbytes
double_quantization: true
dataset: open_eqa_train_val
template: qwen3_vl_nothink
cutoff_len: 2048
max_samples:
100000
overwrite_cache:
true
preprocessing_num_workers:
8
output_dir:
saves/Qwen3-VL-2B-Instruct/qlora/train_openeqa
logging_steps:
10
save_steps:
25
resume_from_checkpoint:
false
overwrite_output_dir:
true
per_device_train_batch_size:
2
gradient_accumulation_steps:
4
learning_rate:
5.0e-5
num_train_epochs:
3.0
lr_scheduler_type:
cosine
warmup_ratio:
0.05
fp16:
true
ddp_timeout:
180000000
optim:
adamw_torch
report_to:
tensorboard
plot_loss:
true
video_max_pixels:
65536
video_min_pixels:
256
freeze_multi_modal_projector:
true
freeze_vision_tower:
true
image_max_pixels:
589824
image_min_pixels:
1024
do_eval:
true
per_device_eval_batch_size:
2
val_size:
0.125
eval_strategy:
steps
eval_steps:
25
eval_delay:
0
prediction_loss_only:
true
load_best_model_at_end:
true
启动训练命令如下。如果训练意外中断,只需将 resume_from_checkpoint 设为 true 即可恢复:
llamafactory-cli train saves/Qwen3-VL-2B-Instruct/qlora/train_openeqa/training_args.yaml
从损失曲线来看,训练损失初始值较高(约 5.5),前 100 步快速下降,200 步后稳定在 1.0~1.5 区间,最终训练损失为 1.3233。验证损失略低于训练损失(1.2683),说明模型泛化能力良好,未出现明显过拟合。整个训练耗时约 2 小时 27 分钟,共完成 453 步。
若需本地查看 TensorBoard 日志,可将服务器 runs 目录下的文件下载到本地,执行 tensorboard --logdir=/path/to/logs --port 6006 即可在浏览器中观察实时曲线。
2. 测试评估
训练完成后,需要评估模型在测试集上的表现。创建 eval_args.yaml,注意修改适配器路径和输出目录:
adapter_name_or_path: saves/Qwen3-VL-2B-Instruct/qlora/train_openeqa/
cutoff_len: 2048
dataset_dir: data
ddp_timeout: 180000000
do_predict: true
eval_dataset: open_eqa_test
finetuning_type: lora
flash_attn: auto
max_new_tokens: 128
max_samples: 99999
model_name_or_path: model/Qwen3-VL-2B-Instruct
output_dir: saves/Qwen3-VL-2B-Instruct/qlora/eval_openeqa
per_device_eval_batch_size: 2
predict_with_generate: true
preprocessing_num_workers: 4
report_to: none
stage: sft
temperature: 0.2
template: qwen3_vl_nothink
top_p: 1.0
trust_remote_code: true
llamafactory-cli train saves/Qwen3-VL-2B-Instruct/qlora/eval_openeqa/eval_args.yaml
评估结果显示,模型在 258 个测试样本上运行稳定,无显存溢出。生成指标方面,BLEU-4 达到 29.4966,ROUGE-1 为 36.2966,ROUGE-L 为 35.7659。这表明模型能有效捕捉具身智能任务中的核心信息,但在短句语义衔接(ROUGE-2 偏低)上仍有提升空间。推理耗时约 2 小时 55 分钟,主要瓶颈在于单样本 8 张图片的多模态特征提取。
3. 融合模型导出
为了便于部署,需要将 LoRA 权重合并到基座模型中。创建 merge_openeqa.yaml:
model_name_or_path: model/Qwen3-VL-2B-Instruct
adapter_name_or_path: saves/Qwen3-VL-2B-Instruct/qlora/train_openeqa/
template: qwen3_vl_nothink
finetuning_type: lora
trust_remote_code: true
export_dir: saves/Qwen3-VL-2B-Instruct/qlora/merge
export_size: 2
export_device: auto
export_legacy_format: false
llamafactory-cli export saves/Qwen3-VL-2B-Instruct/qlora/merge/merge_openeqa.yaml
4. 推理部署 API 服务
(1) Ollama 部署
将融合后的模型放入本地目录(如 /saves/Qwen3-VL-2B-Instruct/qlora/merge),并编写 Modelfile。这里定义了模板和停止符,确保对话格式正确。
FROM .
TEMPLATE """{{ if .System }}<|im_start|>system {{ .System }}<|im_end|> {{ end }}{{ range .Messages }}{{ if eq .Role "user" }}<|im_start|>user {{ .Content }}<|im_end|> <|im_start|>assistant {{ else if eq .Role "assistant" }}{{ .Content }}<|im_end|> {{ end }}{{ end }}"""
PARAMETER temperature 0.7
PARAMETER stop "<|im_end|>"
PARAMETER num_ctx 4096
ollama create qwen3-vl-2b -f Modelfile
ollama run qwen3-vl-2b "问题" 图片路径
支持命令行直接传入、交互式模式以及 curl 调用。使用 curl 时,建议先将图片转为 base64 编码再拼接进 JSON payload,以便通过 API 发送多模态请求。
(2) LMDeploy 部署
LMDeploy 提供了更高效的推理后端。首先安装库:
pip install --no-cache-dir lmdeploy
由于 T4 架构限制,必须使用 PyTorch 后端而非 TurboMind。编写测试脚本 test_offline.py 进行性能验证:
from lmdeploy import pipeline, TurbomindEngineConfig, PytorchEngineConfig, GenerationConfig
from lmdeploy.vl import load_image
import time
MODEL_PATH = "/workspace/LlamaFactory/saves/Qwen3-VL-2B-Instruct/qlora/merge"
IMAGE_PATH = "/workspace/LlamaFactory/data/open_eqa_frames/0a0c0f2b9ba65d1b/000.jpg"
print("🚀 使用 LMDeploy PyTorch 后端加载 Qwen3-VL...")
engine_config = PytorchEngineConfig(
tp=1,
session_len=4096,
max_batch_size=4,
cache_max_entry_count=0.6,
eager_mode=True
)
if __name__ == '__main__':
pipe = pipeline(MODEL_PATH, backend_config=engine_config)
print("✅ 模型加载成功!")
image = load_image(IMAGE_PATH)
prompts = [("描述这张图片", image)]
start = time.time()
response = pipe(prompts, gen_config=GenerationConfig(max_new_tokens=256, temperature=0.7))
latency = time.time() - start
print(f"⏱️ 延迟:{latency:.2f} s")
print(f"📝 输出:{response[0].text}")
测试表明,单图推理延迟约 9.63 秒,Batch 4 请求平均延迟降至 7.86 秒,吞吐量提升约 1.2 倍。后台服务启动命令如下,关键参数需根据显存大小调整:
nohup lmdeploy serve api_server /workspace/LlamaFactory/saves/Qwen3-VL-2B-Instruct/qlora/merge \
--model-name qwen3-vl --backend pytorch --tp 1 \
--session-len 4096 --cache-max-entry-count 0.6 \
--max-batch-size 4 --eager-mode --server-port 23333 > api_server.log 2>&1 &
--backend pytorch: T4 必须项,TurboMind 不支持 Qwen3-VL。
--cache-max-entry-count 0.6: 预留 9.6GB 给 KV Cache,防止 OOM。
--eager-mode: 禁用 CUDA Graph,避免旧架构指令错误。
服务启动后,可通过标准 OpenAI API 格式的 curl 请求进行测试,验证多模态输入与文本生成的稳定性。
相关免费在线工具
- 加密/解密文本
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
- RSA密钥对生成器
生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
- Mermaid 预览与可视化编辑
基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
- 随机西班牙地址生成器
随机生成西班牙地址(支持马德里、加泰罗尼亚、安达卢西亚、瓦伦西亚筛选),支持数量快捷选择、显示全部与下载。 在线工具,随机西班牙地址生成器在线工具,online
- Gemini 图片去水印
基于开源反向 Alpha 混合算法去除 Gemini/Nano Banana 图片水印,支持批量处理与下载。 在线工具,Gemini 图片去水印在线工具,online
- curl 转代码
解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online