Qwen3-VL 结合 LLaMA-Factory 实现 Grounding 任务 LoRA 微调
Qwen3-VL 是阿里云 Qwen 团队开发的多模态大语言模型系列,在空间感知和 OCR 能力上有了显著提升。它支持 2D/3D grounding,能判断物体方位、视角变化及遮挡关系;OCR 支持语言扩展至 32 种,对生僻字、古籍字及复杂场景的识别准确率更高。
环境配置
首先创建独立的 Conda 环境并安装依赖:
conda create -n Qwen3-vl python=3.10
conda activate Qwen3-vl
pip install accelerate
pip install qwen-vl-utils==0.0.14
uv pip install -U vllm
注意:vLLM 版本建议保持在
>=0.11.0。
下载模型权重
由于模型体积较大,推荐使用国内镜像加速下载。安装 ModelScope 后执行:
pip install modelscope
modelscope download --model Qwen/Qwen3-VL-2B-Instruct
若需使用 4B 版本,请相应调整下载命令中的模型名称。
推理测试
在微调前,先验证模型加载与推理是否正常。以下代码展示了如何加载模型并处理多模态查询(图像 + 文本):
from transformers import Qwen3VLForConditionalGeneration, AutoProcessor
import torch
from PIL import Image
def load_qwen3_vl_4b_model():
"""加载 Qwen3-VL-4B-Instruct 模型和处理器"""
model = Qwen3VLForConditionalGeneration.from_pretrained(
"Qwen/Qwen3-VL-4B-Instruct",
torch_dtype=torch.bfloat16,
device_map="auto",
attn_implementation="flash_attention_2" # 可选,用于加速
)
processor = AutoProcessor.from_pretrained("Qwen/Qwen3-VL-4B-Instruct")
return model, processor
def process_multimodal_query(model, processor, image_path, text_query):
"""处理多模态查询(图像 + 文本)"""
image = Image.open(image_path).convert('RGB')
messages = [
{
"role": "user",
"content": [
{: , : image},
{: , : text_query}
]
}
]
inputs = processor.apply_chat_template(
messages, tokenize=, add_generation_prompt=,
return_dict=, return_tensors=
)
generated_ids = model.generate(
**inputs, max_new_tokens=, do_sample=,
temperature=, top_p=
)
generated_ids_trimmed = [
out_ids[(in_ids):] in_ids, out_ids (inputs.input_ids, generated_ids)
]
output_text = processor.batch_decode(
generated_ids_trimmed, skip_special_tokens=, clean_up_tokenization_spaces=
)
output_text[] output_text
__name__ == :
model, processor = load_qwen3_vl_4b_model()
image_path =
query =
result = process_multimodal_query(model, processor, image_path, query)
(, result)


