Qwen3-VL 视觉模型微调实战
一、技术选型解析
1.1 LLaMA-Factory:轻量高效的微调框架
LLaMA-Factory 是一个专为大型语言模型设计的开源微调框架,支持超过 100 种主流模型(包括 Qwen 系列),提供命令行与 WebUI 双模式操作。
核心优势:
- 参数高效微调(PEFT)支持:内置 LoRA、IA³、Adapter 等多种方法,显著降低显存需求
- 多模态支持完善:原生支持图像输入(
token)、视频处理及图文混合训练
Qwen3-VL 视觉语言模型微调实践。使用 LLaMA-Factory 框架配合 LoRA 技术对 Qwen3-VL-4B-Instruct 进行参数高效微调。涵盖环境搭建、数据集构建(ShareGPT 格式)、YAML 配置优化、训练启动及权重合并流程。最终通过 Qwen3-VL-WEBUI Docker 镜像部署验证效果,解决 CUDA 资源不足及版本兼容性问题,实现定制化图文识别任务。
LLaMA-Factory 是一个专为大型语言模型设计的开源微调框架,支持超过 100 种主流模型(包括 Qwen 系列),提供命令行与 WebUI 双模式操作。
核心优势:
Qwen3-VL-WEBUI 是阿里官方发布的 Docker 镜像,集成了预加载的 Qwen3-VL-4B-Instruct 模型、完整依赖环境(PyTorch、Transformers ≥4.45.0)以及内置 Gradio Web 界面,支持上传图片/视频进行交互式测试。
| 组件 | 最低要求 | 推荐配置 |
|---|---|---|
| GPU | NVIDIA RTX 3090 (24GB) | A100/A6000/V100 × 2 或更高 |
| 显存 | ≥24GB | ≥48GB(便于全参数微调探索) |
| 存储 | ≥100GB SSD | ≥500GB NVMe(用于缓存模型与数据集) |
注意:若仅使用 LoRA 微调 Qwen3-VL-4B,单卡 4090D(24GB)即可满足基本训练需求。
# 创建虚拟环境
conda create -n qwen_vl python=3.10
conda activate qwen_vl
# 克隆项目
git clone https://github.com/hiyouga/LLaMA-Factory.git
cd LLaMA-Factory
安装核心依赖:
pip install -e ".[torch,metrics]"
pip install flash-attn==2.6.3 --no-build-isolation
pip install bitsandbytes==0.43.1 deepspeed==0.14.4
pip install --upgrade transformers>=4.45.0
git lfs install
git clone https://www.modelscope.cn/qwen/Qwen3-VL-4B-Instruct.git /data/model/qwen3-vl-4b-instruct
确保目录结构如下:
/data/model/qwen3-vl-4b-instruct/
├── config.json
├── model.safetensors.index.json
├── preprocessor_config.json
└── tokenizer_config.json
LLaMA-Factory 默认采用 sharegpt 格式,每条样本包含 messages 和 images 字段:
[
{
"messages": [
{ "role": "user", "content": "<image>请识别这张身份证上的姓名?" },
{ "role": "assistant", "content": "张三丰" }
],
"images": ["/path/to/id_card_001.jpg"]
}
]
创建 /data/service/LLaMA-Factory/data/images/ 目录存放图像,并生成 qwen_vl_demo.json:
[
{
"messages": [
{ "role": "user", "content": "<image>请识别图片中的人名?" },
{ "role": "assistant", "content": "张三丰" }
],
"images": ["/data/service/LLaMA-Factory/data/images/1.png"]
}
]
编辑 /data/service/LLaMA-Factory/data/dataset_info.json,添加:
"qwen_vl_demo": {
"file_name": "qwen_vl_demo.json",
"formatting": "sharegpt",
"columns": {
"messages": "messages",
"images": "images"
},
"tags": {
"role_tag": "role",
"content_tag": "content",
"user_tag": "user",
"assistant_tag": "assistant"
}
}
复制模板并修改:
cp examples/train_lora/qwen2vl_lora_sft.yaml examples/train_lora/qwen3vl_lora_sft.yaml
vim examples/train_lora/qwen3vl_lora_sft.yaml
关键参数说明如下:
### model
model_name_or_path: /data/model/qwen3-vl-4b-instruct
### method
stage: sft # SFT 阶段微调
do_train: true
finetuning_type: lora # 使用 LoRA
lora_target: all # 对所有线性层注入适配器
### dataset
dataset: qwen_vl_demo
template: qwen2_vl # 当前仍沿用 qwen2_vl 模板
cutoff_len: 2048
max_samples: 1000
preprocessing_num_workers: 8
### output
output_dir: /data/output/qwen3-vl-lora-ft
logging_steps: 10
save_steps: 100
plot_loss: true
### training
per_device_train_batch_size: 1
gradient_accumulation_steps: 16
learning_rate: 1e-4
num_train_epochs: 3
lr_scheduler_type: cosine
warmup_ratio: 0.1
bf16: false
ddp_timeout: 180000000
### evaluation
val_size: 0.1
eval_strategy: steps
eval_steps: 50
注意:
执行训练命令:
llamafactory-cli train examples/train_lora/qwen3vl_lora_sft.yaml
典型输出日志片段:
[INFO] loading configuration file /data/model/qwen3-vl-4b-instruct/config.json
[INFO] Model config Qwen3VLConfig { ... "model_type": "qwen3_vl" ... }
[INFO] Fine-tuning method: LoRA trainable params: 24,576,000 || all params: 4,200,000,000 || trainable%: 0.585%
***** Running training *****
Num examples = 90
Total optimization steps = 27
Epoch: 1.0, Step: 27/27, Loss: 0.214
Saving model checkpoint to /data/output/qwen3-vl-lora-ft
训练完成后会在输出目录生成:
/data/output/qwen3-vl-lora-ft/
├── adapter_model.bin # LoRA 权重
├── configuration.json
├── tokenizer_config.json
└── training_loss.png # 损失曲线图
使用 HuggingFace API 合并:
from peft import PeftModel
from transformers import AutoModelForCausalLM
base_model = AutoModelForCausalLM.from_pretrained("/data/model/qwen3-vl-4b-instruct")
lora_model = PeftModel.from_pretrained(base_model, "/data/output/qwen3-vl-lora-ft")
merged_model = lora_model.merge_and_unload()
merged_model.save_pretrained("/data/model/qwen3-vl-4b-instruct-finetuned")
拉取并运行官方镜像:
docker run -d \
-p 7860:7860 \
-v /data/model/qwen3-vl-4b-instruct-finetuned:/app/models \
--gpus all \
--shm-size="16gb" \
qwen3-vl-webui:latest
访问 http://localhost:7860 即可通过网页上传图片并测试微调后模型的表现。
错误原因:Transformers 库版本过低,未注册 Qwen3-VL 模型类型。 解决方法:
pip install --upgrade transformers>=4.45.0
验证是否成功:
from transformers import AutoConfig
config = AutoConfig.from_pretrained("/data/model/qwen3-vl-4b-instruct")
print(config.model_type) # 应输出 'qwen3_vl'
错误堆栈:
RuntimeError: CUDA error: too many resources requested for launch
根本原因:Qwen3-VL 默认使用 bfloat16 精度,某些旧 GPU(如 V100)不完全支持。 解决方案:修改模型配置文件
vi /data/model/qwen3-vl-4b-instruct/config.json
将 "torch_dtype": "bfloat16" 修改为 "torch_dtype": "float16"
本实践完成了基于 LLaMA-Factory 的 Qwen3-VL 视觉语言模型微调全流程。通过 LoRA 技术实现参数高效微调,结合 Qwen3-VL-WEBUI 完成部署验证。解决了环境配置、数据格式、显存优化及版本兼容等关键问题,实现了定制化图文识别任务的落地。

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online