Qwen3-VL 与 LLaMA-Factory Grounding 微调实战
模型背景
Qwen3-VL 在空间感知能力上有了显著提升,2D grounding 从绝对坐标转向相对坐标,支持判断物体方位、视角变化及遮挡关系,甚至能实现 3D grounding。此外,OCR 支持语言扩展至 32 种,对复杂光线、模糊场景表现更稳定。
技术层面主要包含三点改进:
- MRoPE-Interleave:原始 MRoPE 将特征维度按时间、高度、宽度顺序分块,Qwen3-VL 采用交错分布形式,实现对全频率覆盖,增强长视频理解鲁棒性。
- DeepStack 技术:融合 ViT 多层次特征,将视觉 tokens 注入到 LLM 的多层中而非单层,保留从底层到高层的丰富信息,提升图文对齐精度。
- 文本时间戳对齐机制:升级原有的 T-RoPE,采用'时间戳 - 视频帧'交错输入,原生支持秒数与 HMS 格式输出,提升时序推理精度。
环境配置
首先创建独立的 Conda 环境并安装依赖。注意命令中的 -n 参数用于指定环境名。
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>=0.11.0
模型加载与推理
下载完整模型库后,可以通过 Hugging Face 或 ModelScope 获取权重。以下是一个基础的推理示例,重点在于消息格式的构建和生成参数的调整。
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)

