Qwen-VL 视觉语言模型
Qwen-VL 是阿里云推出的视觉语言模型系列,基于 Qwen 语言模型扩展视觉理解能力,支持图像理解、视觉定位、OCR 和多模态对话等任务,在中文和英文场景中均有出色表现。
架构设计
Qwen-VL 的架构包含三个核心模块:
- 视觉编码器 ViT-bigG:提取图像的 patch 级特征
- 位置感知视觉-语言适配器:将视觉特征压缩并注入位置信息
- Qwen 语言模型:处理多模态输入序列的生成
视觉 Token 压缩
Qwen-VL 引入了视觉 Token 压缩机制,将 ViT 输出的 256 个 Token 压缩为 32 个:
python
class VisionLanguageAdapter(nn.Module):
"""Qwen-VL 位置感知适配器"""
def __init__(self, vision_dim=1664, llm_dim=4096, compress_ratio=4):
super().__init__()
self.compress = nn.Linear(
vision_dim * compress_ratio * compress_ratio,
llm_dim
)
self.position_embedding = nn.Parameter(
torch.zeros(1, 256 // (compress_ratio**2), llm_dim)
)
def forward(self, vision_features):
# vision_features: [B, 256, vision_dim]
B, N, D = vision_features.shape
# 2D 重排后压缩
h = w = int(N ** 0.5) # 16x16
feat_2d = vision_features.view(B, h, w, D)
# 压缩为 4x4 的网格
cr = 4 # compress_ratio
feat_2d = feat_2d.view(B, h//cr, cr, w//cr, cr, D)
feat_compressed = feat_2d.permute(0,1,3,2,4,5).reshape(
B, (h//cr)*(w//cr), D*cr*cr
)
# 线性投影
output = self.compress(feat_compressed)
# 加入位置编码
output = output + self.position_embedding
return output # [B, 32, llm_dim]Qwen-VL 版本演进
| 版本 | 视觉编码器 | 语言模型 | 分辨率 | 关键特性 |
|---|---|---|---|---|
| Qwen-VL | ViT-bigG | Qwen-7B | 448×448 | 定位、OCR、多语言 |
| Qwen-VL-Chat | ViT-bigG | Qwen-7B | 448×448 | 对话优化 |
| Qwen2-VL-2B | ViT | Qwen2-2B | 动态 | Naive Dynamic Resolution |
| Qwen2-VL-7B | ViT | Qwen2-7B | 动态 | MLLM 推理增强 |
| Qwen2-VL-72B | ViT | Qwen2-72B | 动态 | 顶级性能 |
Qwen2-VL 的核心改进
Qwen2-VL 引入了多项重要改进:
Naive Dynamic Resolution
不再将图像缩放到固定分辨率,而是直接处理任意分辨率的图像:
- 将图像按 28×28 的 patch 切分
- 保留原始宽高比,生成可变数量的视觉 Token
- 通过 RoPE 位置编码处理变长序列
M-RoPE 位置编码
多模态旋转位置编码(M-RoPE)将位置信息分为时间、高度、宽度三个维度:
- 文本 Token:时间和高度递增,宽度为 0
- 图像 Token:时间固定,高度和宽度按 2D 位置递增
- 视频 Token:时间维度按帧递增
python
# Qwen2-VL M-RoPE 示意
def compute_mrope_positions(text_len, image_h, image_w, num_frames=1):
positions = []
# 文本部分
for i in range(text_len):
positions.append((i, i, 0)) # (temporal, height, width)
# 图像部分
for f in range(num_frames):
for h in range(image_h):
for w in range(image_w):
positions.append((f, h, w))
return positions视频理解
Qwen2-VL 原生支持视频理解,将视频视为多帧图像序列,通过 M-RoPE 的时间维度编码帧间关系,支持最长约 20 分钟的视频输入。
视觉定位能力
Qwen-VL 独特的视觉定位(Grounding)能力:
- 输入图像和文本描述,输出目标对象的边界框坐标
- 使用
<box>和</box>特殊 Token 标注坐标 - 支持 Referring Expression Comprehension 和 Grounded Captioning