本实验在 Qwen3-VL-4B 模型上进行 VQA(视觉问答)任务的 GRPO(Group Relative Policy Optimization)强化学习微调,使用 ms-swift 框架。
使用vllm-ascend镜像
# 启动容器
docker run -dit --net=host --shm-size=1000g --privileged \
--name qwen3-VL-4B_RL \
--device=/dev/davinci_manager \
--device=/dev/hisi_hdc \
--device=/dev/devmm_svm \
-v /usr/local/sbin:/usr/local/sbin \
-v /usr/local/bin/npu-smi:/usr/local/bin/npu-smi \
-v /usr/local/Ascend/driver:/usr/local/Ascend/driver \
-v /usr/local/Ascend/firmware:/usr/local/Ascend/firmware \
-v /usr/local/Ascend/driver/version.info:/usr/local/Ascend/driver/version.info \
-v /etc/ascend_install.info:/etc/ascend_install.info \
-v /home:/home \
-v /data:/data \
quay.io/ascend/vllm-ascend:v0.23.0rc1 \
/bin/bashvllm-ascend 存在循环导入 bug,需要修改,使用以下脚本或者手动修改 __init__.py ,注释掉 import vllm_ascend.ops.fused_moe.fused_moe 这一行
python3 -c "
path = '/vllm-workspace/vllm-ascend/vllm_ascend/ops/__init__.py'
with open(path) as f:
lines = f.readlines()
for i, line in enumerate(lines):
if 'fused_moe.fused_moe' in line and 'import' in line and not line.strip().startswith('#'):
lines[i] = line.replace('import', '# import')
print(f'Fixed line {i+1}: {lines[i].strip()}')
break
with open(path, 'w') as f:
f.writelines(lines)
print('Done')
"pip install "ms-swift[vlm,rl]" "qwen_vl_utils>=0.0.14"# 检查 NPU
python -c "import torch, torch_npu; print(f'torch:{torch.__version__}, torch_npu:{torch_npu.__version__}'); print(f'NPU available: {torch.npu.is_available()}'); print(f'NPU count: {torch.npu.device_count()}')"
# 检查 ms-swift 版本
python -c "import swift; print('swift:', swift.__version__)"
https://www.modelscope.cn/models/Qwen/Qwen3-VL-4B-Instruct 放在 ./qwen3/pytorch_4b 目录下
使用 COCO val2014 数据集的 VQAv2 问题,通过 vqa_eval.py 脚本评测 Qwen3-VL-4B OM 模型,随机收集了1000份错误案例作为训练数据(VQA准确率<0.5)。
数据集下载地址:https://visualqa.org/
| 指标 | 数量 |
|---|---|
| 收集错误案例 | 1,000 |
| 训练集 | 900 |
| 测试集 | 100 |
GRPO 训练数据格式 (rl_train.jsonl):
{
"images": ["/path/to/COCO_val2014_000000000139.jpg"],
"query": "<image>What is the person doing?",
"answer": "skiing",
"all_answers": ["skiing", "skiing", "ski", ...],
"answer_type": "other"
}关键字段:
query: 包含 <image> 占位符和 questionanswer: 标准答案(用于 ground_truth)images: 图片路径列表all_answers: 10 个标注者答案(用于 reward 计算)answer_type: 答案类型(yes/no/number/other)使用自定义 VQA reward 函数 (vqa_reward.py):
"""
VQA GRPO 奖励函数 - ms-swift ORM 格式
用于 ms-swift GRPO 训练,通过 --reward_funcs vqa 引用
"""
import re
from swift.rewards.orm import ORM, orms
class VQA(ORM):
"""VQA 规则奖励函数"""
def __call__(self, completions, **kwargs):
all_answers_list = kwargs.get('all_answers', [])
if isinstance(all_answers_list, list) and len(all_answers_list) > 0:
if isinstance(all_answers_list[0], str):
all_answers_list = [all_answers_list] * len(completions)
ground_truths = kwargs.get('ground_truth', kwargs.get('answer', []))
if isinstance(ground_truths, str):
ground_truths = [ground_truths] * len(completions)
rewards = []
for i, completion in enumerate(completions):
r = 0.0
all_answers = all_answers_list[i] if i < len(all_answers_list) else []
if not all_answers:
rewards.append(0.0)
continue
vqa_acc = self._compute_vqa_reward(completion, all_answers)
if vqa_acc >= 1.0:
r = 5.0
elif vqa_acc >= 0.67:
r = 3.0
elif vqa_acc >= 0.33:
r = 1.0
else:
r = -1.0
rewards.append(r)
return rewards
@staticmethod
def normalize_answer(ans: str) -> str:
"""答案归一化:VQA 官方标准"""
ans = ans.strip().lower()
ans = re.sub(r'[.,?!:;]', '', ans)
ans = re.sub(r'\b(a|an|the)\b', '', ans)
ans = ' '.join(ans.split())
return ans
@staticmethod
def extract_answer(model_output: str) -> str:
"""从模型输出中提取答案关键词"""
text = model_output.strip().lower()
text = ' '.join(text.split())
if not text:
return ""
text = re.sub(r'\*\*(.+?)\*\*', r'\1', text)
if text.startswith('yes,') or text.startswith('yes.') or text.startswith('yes '):
return 'yes'
if text.startswith('no,') or text.startswith('no.') or text.startswith('no '):
return 'no'
for sep in ['。', '.', ',', ',', '\n']:
if sep in text:
text = text.split(sep)[0]
break
text = text.strip()
prefixes = [
'based on the image,', 'based on the image',
'the answer is', 'it appears that', 'it is',
'this is', 'there is', 'there are',
]
for prefix in prefixes:
if text.startswith(prefix):
text = text[len(prefix):].strip()
break
return ' '.join(text.split())
@staticmethod
def _compute_vqa_reward(model_output: str, all_answers: list) -> float:
"""计算 VQA 奖励分数"""
pred_text = VQA.extract_answer(model_output)
if not pred_text:
return 0.0
pred_norm = VQA.normalize_answer(pred_text)
matching = 0
for a in all_answers:
a_norm = VQA.normalize_answer(a)
if a_norm == pred_norm or a_norm in pred_norm or pred_norm in a_norm:
matching += 1
return min(1.0, matching / 3.0)
# 注册到 ms-swift
orms['vqa'] = VQA
| VQA 准确率 | 奖励值 |
|---|---|
| ≥ 1.0 (3+ 标注者一致) | 5.0 |
| ≥ 0.67 (2 标注者一致) | 3.0 |
| ≥ 0.33 (1 标注者一致) | 1.0 |
| < 0.33 | -1.0 |
| 参数 | 值 |
|---|---|
| learning_rate | 1e-5 |
| num_train_epochs | 2 |
| per_device_train_batch_size | 1 |
| gradient_accumulation_steps | 8 |
| max_steps | 1800 (实际) |
| beta (KL 系数) | 0.03 |
| temperature | 1.0 |
| max_grad_norm | 1.0 |
| num_generations | 8 |
| num_generations_eval | 1 |
GRPO 需要 vllm Rollout 服务,先启动服务:
# 启动 vllm 服务(后台运行)
ASCEND_RT_VISIBLE_DEVICES=4 \
swift rollout \
--model ./qwen3/pytorch_4b \
--model_type qwen3_vl \
--template qwen3_vl \
--max_new_tokens 64 \
--temperature 1.0 \
--top_p 0.9 \
--port 8000 \
--vllm_max_model_len 2048 \
--vllm_gpu_memory_utilization 0.35 \
--vllm_enable_lora true \
--enable_npu_model_patch true启动命令 (start_rl.sh):
ASCEND_RT_VISIBLE_DEVICES=1 \
swift rlhf \
--rlhf_type grpo \
--model_type qwen3_vl \
--model ./qwen3/pytorch_4b \
--dataset ./dataset/VQAv2/rl_train.jsonl \
--template qwen3_vl \
--num_generations 8 \
--num_generations_eval 1 \
--reward_funcs vqa \
--learning_rate 1e-5 \
--per_device_train_batch_size 1 \
--gradient_accumulation_steps 8 \
--num_train_epochs 2 \
--torch_dtype bfloat16 \
--gradient_checkpointing true \
--output_dir ./output_qwen3vl_grpo \
--beta 0.03 \
--temperature 1.0 \
--max_grad_norm 1.0 \
--use_vllm true \
--vllm_mode server \
--vllm_server_host 127.0.0.1 \
--vllm_server_port 8000 \
--vllm_enable_lora true \
--external_plugins ./RL/vqa_reward.py \
--eval_strategy steps \
--eval_steps 50 \
--save_strategy steps \
--save_steps 50 \
--save_total_limit 2 \
--logging_steps 5 \
--warmup_ratio 0.1 \
--split_dataset_ratio 0 \
--max_length 2048 \
--attn_impl sdpa \
--enable_npu_model_patch trueASCEND_RT_VISIBLE_DEVICES=0 \
swift infer \
--model ./qwen3/pytorch_4b \
--model_type qwen3_vl \
--adapters ./output_qwen3vl_grpo/v2-20260818-021130/checkpoint-1800 \
--val_dataset ./dataset/VQAv2/rl_test.jsonl \
--stream true \
--max_new_tokens 32 \
--no_load_args \
--torch_dtype bfloat16 \
--enable_npu_model_patch true使用 calculate_vqa_accuracy.py 脚本,与 vqa_eval.py 评测逻辑完全一致:
min(1, 匹配标注者数 / 3)is_correct = exact_match or containspython calculate_vqa_accuracy.py \
--test_data ./dataset/VQAv2/rl_test.jsonl \
--infer_result ./output_qwen3vl_grpo/v2-20260818-021130/checkpoint-1800/infer_result/20260819-075728.jsonl \
--output ./qwen3_eval/grpo_eval_results.json \
--model_name "GRPO (Qwen3-VL-4B)"============================================================
GRPO (Qwen3-VL-4B) VQA 评测结果
============================================================
VQA 标准准确率: 70.33%
精确匹配率: 54.00%
评测样本数: 100
--- 按 answer_type 统计 ---
类型 VQA准确率 精确匹配 总数
------------------------------------------
yes/no 66.7% 45.8% 24
number 69.7% 63.6% 11
other 71.8% 55.4% 65
--- 错误样例 (前 5) ---
Q: Is this America?
GT: yes
模型: While the image doesn't explicitly show American flags, land
Q: Are there cars parked?
GT: no
模型: yes
Q: Has this area been windy lately?
GT: yes
模型: Based on the visual evidence in the image, it is **very like
Q: Where is the safety helmet?
GT: on handler's head
模型: on man's head
Q: When is this taken?
GT: in morning
模型: This photo was likely taken during the day, possibly in the| 指标 | 基座模型 | GRPO 微调后 |
|---|---|---|
| VQA 标准准确率 | 66.33% | 70.33% |
| 精确匹配率 | 48.00% | 54.00% |
| 评测样本数 | 100 | 100 |
| answer_type | VQA准确率(基座) | VQA准确率(GRPO) | 精确匹配(基座) | 精确匹配(GRPO) | 数量 |
|---|---|---|---|---|---|
| yes/no | 59.7% | 66.7% | 41.7% | 45.8% | 24 |
| number | 60.6% | 69.7% | 54.5% | 63.6% | 11 |
| other | 69.7% | 71.8% | 49.2% | 55.4% | 65 |