Ascend-SACT/Qwen3-VL-4B-GRPO-MS-SWIFT
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

基于ms-swift的Qwen3-VL-4B的强化学习微调指导

1. 概述

本实验在 Qwen3-VL-4B 模型上进行 VQA(视觉问答)任务的 GRPO(Group Relative Policy Optimization)强化学习微调,使用 ms-swift 框架。


2. 环境搭建

2.1 Docker 环境

使用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/bash

2.2 解决循环导入bug

vllm-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')
"

2.3 安装依赖

pip install "ms-swift[vlm,rl]" "qwen_vl_utils>=0.0.14"

2.4 验证环境

# 检查 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__)"

2.5 下载原始权重

https://www.modelscope.cn/models/Qwen/Qwen3-VL-4B-Instruct 放在 ./qwen3/pytorch_4b 目录下


3. 数据集

3.1 原始数据来源

使用 COCO val2014 数据集的 VQAv2 问题,通过 vqa_eval.py 脚本评测 Qwen3-VL-4B OM 模型,随机收集了1000份错误案例作为训练数据(VQA准确率<0.5)。

数据集下载地址:https://visualqa.org/

3.2 数据统计

指标数量
收集错误案例1,000
训练集900
测试集100

3.3 数据格式

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> 占位符和 question
  • answer: 标准答案(用于 ground_truth)
  • images: 图片路径列表
  • all_answers: 10 个标注者答案(用于 reward 计算)
  • answer_type: 答案类型(yes/no/number/other)

4. 奖励函数

4.1 VQA Reward 实现

使用自定义 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

4.2 奖励映射规则

VQA 准确率奖励值
≥ 1.0 (3+ 标注者一致)5.0
≥ 0.67 (2 标注者一致)3.0
≥ 0.33 (1 标注者一致)1.0
< 0.33-1.0

5. 训练配置

5.1 环境

  • 框架:ms-swift
  • 模型:Qwen3-VL-4B-Instruct
  • 微调方法:LoRA
  • 强化学习方法:GRPO
  • 硬件:单卡 Ascend 910B
  • vLLM:用于 Rollout 生成

5.2 训练参数

参数值
learning_rate1e-5
num_train_epochs2
per_device_train_batch_size1
gradient_accumulation_steps8
max_steps1800 (实际)
beta (KL 系数)0.03
temperature1.0
max_grad_norm1.0
num_generations8
num_generations_eval1

5.3 训练耗时

  • 总耗时:约 14 小时 51 分钟
  • 每步耗时:约 29.7 秒
  • 生成 checkpoint:checkpoint-1800

6. 完整流程

6.1 vllm 服务启动

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

6.2 训练

启动命令 (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 true

6.3 推理

ASCEND_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

7. 评测方法

7.1 评测脚本

使用 calculate_vqa_accuracy.py 脚本,与 vqa_eval.py 评测逻辑完全一致:

  • VQA 标准准确率:min(1, 匹配标注者数 / 3)
  • 精确匹配率:归一化后与 GT 完全一致的比例
  • 包含匹配:is_correct = exact_match or contains

7.2 评测命令

python 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)"

7.3 输出示例

============================================================
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

8. 评测结果

8.1 总体结果

指标基座模型GRPO 微调后
VQA 标准准确率66.33%70.33%
精确匹配率48.00%54.00%
评测样本数100100

8.2 按类型统计

answer_typeVQA准确率(基座)VQA准确率(GRPO)精确匹配(基座)精确匹配(GRPO)数量
yes/no59.7%66.7%41.7%45.8%24
number60.6%69.7%54.5%63.6%11
other69.7%71.8%49.2%55.4%65