Qwen2-VL的新特性
主要增强功能:
模型架构更新:

我们有三个参数量分别为20亿、80亿和720亿的模型。此仓库包含经过指令调优的720亿参数Qwen2-VL模型。更多信息,请访问我们的博客和GitHub。Qwen2-VL-72B-Instruct可用8卡进行DPO,配套版本如下表格:
| 配套 | 版本 |
|---|---|
| 硬件 | 910B3 |
| 架构 | arm |
| CANN | 8.5.2 |
| torch | 2.7.1 |
| torch_npu | 2.7.1 |
| transformers | 4.57.0 |
| mindspeed-mm | v26.0.0 |
拉取基础镜像cann:8.5.2-910b-openeuler24.03-py3.11,并且基于基础镜像启动容器
docker pull quay.io/ascend/cann:8.5.2-910b-openeuler24.03-py3.11
docker run -itd \
--name mindspeed-mm-install \
--shm-size=128g \
--device=/dev/davinci0 --device=/dev/davinci1 \
--device=/dev/davinci2 --device=/dev/davinci3 \
--device=/dev/davinci4 --device=/dev/davinci5 \
--device=/dev/davinci6 --device=/dev/davinci7 \
--device=/dev/davinci_manager --device=/dev/devmm_svm --device=/dev/hisi_hdc \
-v /usr/local/Ascend/driver:/usr/local/Ascend/driver:ro \
-v /usr/local/Ascend/firmware:/usr/local/Ascend/firmware:ro \
-v /usr/local/sbin/npu-smi:/usr/local/sbin/npu-smi:ro \
-v /etc/ascend_install.info:/etc/ascend_install.info:ro \
quay.io/ascend/cann:8.5.2-910b-openeuler24.03-py3.11 \
bash启动容器,创建目录
mkdir -p /workspace
cd /workspace环境搭建
git clone --branch 26.0.0 https://gitcode.com/Ascend/MindSpeed-MM.git
git clone https://github.com/NVIDIA/Megatron-LM.git
cd Megatron-LM
git checkout core_v0.12.1
cp -r megatron ../MindSpeed-MM/
cd ..
cd MindSpeed-MM
# 安装加速库
git clone https://gitcode.com/Ascend/MindSpeed.git
cd MindSpeed
# checkout commit from MindSpeed core_r0.12.1
git checkout 5176c6f5f133111e55a404d82bd2dc14a809a6ab
# 安装mindspeed及依赖
pip install -e .
cd ..
# 安装mindspeed mm及依赖
pip install -e .
请确保torch和torch_npu版本都是2.7.1:
pip show torch
pip show torch_npu如果不是,请执行下面的命令
pip install torch==2.7.1 torch-npu==2.7.1git clone https://www.modelscope.cn/Qwen/Qwen2-VL-72B-Instruct.git # 从modelscope下载
git clone https://huggingface.co/Qwen/Qwen2-VL-72B-Instruct # 从huggingface下载MindSpeed MM修改了部分原始网络的结构名称,使用mm-convert工具对原始预训练权重进行转换。该工具实现了huggingface权重和MindSpeed MM权重的互相转换以及PP(Pipeline Parallel)权重的重切分。
mm-convert Qwen2VLConverter hf_to_mm \
--cfg.mm_dir "/Qwen2-VL-72B-Instruct-mm" \
--cfg.hf_config.hf_dir "/mnt/public/models/huggface_models/Qwen/Qwen2-VL-72B-Instruct" \
--cfg.parallel_config.llm_pp_layers [[20,20,20,20]] \
--cfg.parallel_config.vit_pp_layers [[32,0,0,0]] \
--cfg.parallel_config.tp_size 2
# 其中:
# mm_dir: 转换后保存目录
# hf_dir: huggingface权重目录
# llm_pp_layers: llm在每个卡上切分的层数,注意要和/workspace/MindSpeed-MM/examples/qwen2vl/model_72b.json中配置的text_decoder.pipeline_num_layers一致
# vit_pp_layers: vit在每个卡上切分的层数,注意要和/workspace/MindSpeed-MM/examples/qwen2vl/model_72b.json中配置的image_encoder.vision_encoder.pipeline_num_layers一致
# tp_size: tp并行数量,注意要和微调启动脚本/workspace/MindSpeed-MM/examples/qwen2vl/finetune_qwen2vl_72b_dpo.sh中TP=2的配置一致保存成rlhf-v.jsonl
{"id": "1", "messages": [{"role": "user", "content": "<image>\nDescribe it!"}], "chosen": {"role": "assistant", "content": "hello world"}, "rejected": {"role": "assistant", "content": "hi world"}, "images": ["/workspace/MindSpeed-MM/data/demo.jpeg"]}
{"id": "2", "messages": [{"role": "user", "content": "<image>\nDescribe it!"}], "chosen": {"role": "assistant", "content": "hello world"}, "rejected": {"role": "assistant", "content": "hi world"}, "images": ["/workspace/MindSpeed-MM/data/demo.jpeg"]}
{"id": "3", "messages": [{"role": "user", "content": "<image>\nDescribe it!"}], "chosen": {"role": "assistant", "content": "hello world"}, "rejected": {"role": "assistant", "content": "hi world"}, "images": ["/workspace/MindSpeed-MM/data/demo.jpeg"]}
{"id": "4", "messages": [{"role": "user", "content": "<image>\nDescribe it!"}], "chosen": {"role": "assistant", "content": "hello world"}, "rejected": {"role": "assistant", "content": "hi world"}, "images": ["/workspace/MindSpeed-MM/data/demo.jpeg"]}
{"id": "5", "messages": [{"role": "user", "content": "<image>\nDescribe it!"}], "chosen": {"role": "assistant", "content": "hello world"}, "rejected": {"role": "assistant", "content": "hi world"}, "images": ["/workspace/MindSpeed-MM/data/demo.jpeg"]}
{"id": "6", "messages": [{"role": "user", "content": "<image>\nDescribe it!"}], "chosen": {"role": "assistant", "content": "hello world"}, "rejected": {"role": "assistant", "content": "hi world"}, "images": ["/workspace/MindSpeed-MM/data/demo.jpeg"]}
{"id": "7", "messages": [{"role": "user", "content": "<image>\nDescribe it!"}], "chosen": {"role": "assistant", "content": "hello world"}, "rejected": {"role": "assistant", "content": "hi world"}, "images": ["/workspace/MindSpeed-MM/data/demo.jpeg"]}
{"id": "8", "messages": [{"role": "user", "content": "<image>\nDescribe it!"}], "chosen": {"role": "assistant", "content": "hello world"}, "rejected": {"role": "assistant", "content": "hi world"}, "images": ["/workspace/MindSpeed-MM/data/demo.jpeg"]}
{"id": "9", "messages": [{"role": "user", "content": "<image>\nDescribe it!"}], "chosen": {"role": "assistant", "content": "hello world"}, "rejected": {"role": "assistant", "content": "hi world"}, "images": ["/workspace/MindSpeed-MM/data/demo.jpeg"]}
{"id": "10", "messages": [{"role": "user", "content": "<image>\nDescribe it!"}], "chosen": {"role": "assistant", "content": "hello world"}, "rejected": {"role": "assistant", "content": "hi world"}, "images": ["/workspace/MindSpeed-MM/data/demo.jpeg"]}
{"id": "11", "messages": [{"role": "user", "content": "<image>\nDescribe it!"}], "chosen": {"role": "assistant", "content": "hello world"}, "rejected": {"role": "assistant", "content": "hi world"}, "images": ["/workspace/MindSpeed-MM/data/demo.jpeg"]}
{"id": "12", "messages": [{"role": "user", "content": "<image>\nDescribe it!"}], "chosen": {"role": "assistant", "content": "hello world"}, "rejected": {"role": "assistant", "content": "hi world"}, "images": ["/workspace/MindSpeed-MM/data/demo.jpeg"]}{
"dataset_param": {
"dataset_type": "huggingface",
"preprocess_parameters": {
"model_name_or_path": "/mnt/public/models/huggface_models/Qwen/Qwen2-VL-72B-Instruct",
"use_fast_tokenizer": true,
"split_special_tokens": false,
"image_max_pixels": 262144,
"image_min_pixels": 0,
"video_max_pixels": 16384,
"video_min_pixels": 0,
"video_fps": 2.0,
"video_maxlen": 64
},
"basic_parameters": {
"template": "qwen2vl",
"dataset_dir": "./data",
"dataset": "/workspace/MindSpeed-MM/data/rlhf-v.jsonl",
"cache_dir": "./data/cache_dir",
"train_on_prompt": false,
"mask_history": false,
"preprocessing_batch_size": 1000,
"preprocessing_num_workers": 16,
"max_samples": null,
"tool_format": null
},
"attr": {
"ranking": true,
"system": null,
"images": "images",
"videos": null,
"messages": "messages",
"role_tag": "role",
"content_tag": "content",
"user_tag": "user",
"assistant_tag": "assistant",
"observation_tag": null,
"function_tag": null,
"system_tag": null,
"chosen": "chosen",
"rejected": "rejected"
}
},
"dataloader_param": {
"dataloader_mode": "sampler",
"drop_last": true,
"sampler_type": "BaseRandomBatchSampler",
"collate_param": {
"model_name": "qwen2vl_dpo",
"ignore_pad_token_for_loss": true
},
"pin_memory": true,
"shuffle": true
}
}关键参数配置
| 参数 | 参数解释 |
|---|---|
| model_name_or_path | 转换前hf格式权重文件路径 |
| dataset | 训练数据集 |
{
"model_id": "qwen2vl",
"img_context_token_id": 151655,
"video_token_id": 151656,
"vision_start_token_id": 151652,
"image_encoder": {
"vision_encoder": {
"model_id": "qwen2vit",
"num_layers": 32,
"hidden_size": 1280,
"ffn_hidden_size": 5120,
"llm_hidden_size": 8192,
"num_attention_heads": 16,
"hidden_dropout": 0.0,
"attention_dropout": 0.0,
"in_channels": 3,
"patch_size": 14,
"spatial_merge_size": 2,
"temporal_patch_size": 2,
"layernorm_epsilon": 1e-06,
"normalization": "LayerNorm",
"fp16": false,
"bf16": true,
"params_dtype": "bf16",
"activation_func": "quick_gelu",
"freeze": true,
"use_fused_rotary_pos_emb": true,
"post_layer_norm": false,
"pipeline_num_layers": [32, 0, 0, 0],
"attention_mask_type": "general"
},
"vision_projector": {
"model_id": "lnmlp",
"num_layers": 1,
"gated_linear_unit": false,
"bias_activation_fusion": false,
"add_bias_linear": true,
"input_size": 1280,
"hidden_size": 8192,
"ffn_hidden_size": 5120,
"activation_func": "gelu",
"bf16": true,
"params_dtype": "bf16",
"freeze": true,
"layernorm_epsilon": 1e-06,
"normalization": "LayerNorm"
}
},
"text_decoder": {
"model_id": "qwen2lm",
"kv_channels": 128,
"num_layers": 80,
"pipeline_num_layers": [20, 20, 20, 20],
"hidden_size": 8192,
"ffn_hidden_size": 29568,
"num_attention_heads": 64,
"max_position_embeddings": 32768,
"vocab_size": 152064,
"rope_theta": 1000000.0,
"untie_embeddings_and_output_weights": true,
"disable_bias_linear": true,
"attention_dropout": 0.0,
"init_method_std": 0.01,
"hidden_dropout": 0.0,
"position_embedding_type": "mrope",
"normalization": "RMSNorm",
"activation_func": "silu",
"use_fused_rotary_pos_emb": true,
"attention_softmax_in_fp32": true,
"params_dtype": "bf16",
"bf16": true,
"parallel_output": true,
"group_query_attention": true,
"num_query_groups": 8,
"rope_scaling": null,
"gated_linear_unit": true,
"layernorm_epsilon": 1e-06,
"mrope_section": [16, 24, 24],
"add_bias_linear": false,
"add_qkv_bias": true,
"recompute_granularity": "full",
"recompute_method": "uniform",
"recompute_num_layers": 1
},
"text_encoder": null,
"video_encoder": null
}关键参数配置
| 参数 | 参数解释 |
|---|---|
| image_encoder.vision_encoder.pipeline_num_layers | vit在每个卡上切分的层数 |
| text_decoder.pipeline_num_layers | llm在每个卡上切分的层数 |
以下是单机主要训练参数配置,具体训练脚本见/workspace/MindSpeed-MM/examples/qwen2vl/finetune_qwen2vl_72b_dpo.sh
#!/bin/bash
source /usr/local/Ascend/cann/set_env.sh
# 该变量只用于规避megatron对其校验,对npu无效
export CUDA_DEVICE_MAX_CONNECTIONS=1
export ASCEND_SLOG_PRINT_TO_STDOUT=0
export ASCEND_GLOBAL_LOG_LEVEL=3
export TASK_QUEUE_ENABLE=2
export COMBINED_ENABLE=1
export CPU_AFFINITY_CONF=2
export HCCL_CONNECT_TIMEOUT=1200
export NPU_ASD_ENABLE=0
export ASCEND_LAUNCH_BLOCKING=0
export ACLNN_CACHE_LIMIT=100000
export MULTI_STREAM_MEMORY_REUSE=2
export PYTORCH_NPU_ALLOC_CONF="expandable_segments:True"
NPUS_PER_NODE=8
MASTER_ADDR=localhost
MASTER_PORT=6000
NNODES=1
NODE_RANK=0
WORLD_SIZE=$(($NPUS_PER_NODE*$NNODES))
MM_DATA="/workspace/MindSpeed-MM/examples/qwen2vl/data_72b_dpo.json"
MM_MODEL="/workspace/MindSpeed-MM/examples/qwen2vl/model_72b.json"
MM_TOOL="/workspace/MindSpeed-MM/mindspeed_mm/tools/tools.json"
# 需要先根据readme把huggingface格式模型转换为mm格式
LOAD_PATH="/Qwen2-VL-72B-Instruct-mm"
SAVE_PATH="./save_dir"
TP=2
# 注意修改MM_MODEL里面PP配置,详见readme
PP=4
CP=1
MBS=1
GRAD_ACC_STEP=64
DP=$(($WORLD_SIZE/$TP/$PP/$CP))
GBS=$(($MBS*$GRAD_ACC_STEP*$DP))
DISTRIBUTED_ARGS="
--nproc_per_node $NPUS_PER_NODE \
--nnodes $NNODES \
--node_rank $NODE_RANK \
--master_addr $MASTER_ADDR \
--master_port $MASTER_PORT
"
# GPT_ARGS中模型相关参数具体配置在example/qwen2vl/model_72b.json中,训练相关参数配置在这里
GPT_ARGS="
--use-mcore-models \
--tensor-model-parallel-size ${TP} \
--pipeline-model-parallel-size ${PP} \
--context-parallel-size ${CP} \
--micro-batch-size ${MBS} \
--global-batch-size ${GBS} \
--tokenizer-type NullTokenizer \
--vocab-size 152064 \
--seq-length 1024 \
--make-vocab-size-divisible-by 1 \
--normalization RMSNorm \
--use-fused-rmsnorm \
--swiglu \
--use-fused-swiglu \
--no-masked-softmax-fusion \
--lr 5.0e-6 \
--lr-decay-style cosine \
--weight-decay 0 \
--train-iters 60 \
--lr-warmup-fraction 0.1 \
--clip-grad 0.0 \
--adam-beta1 0.9 \
--adam-beta2 0.999 \
--no-gradient-accumulation-fusion \
--seed 42 \
--bf16 \
--load $LOAD_PATH \
--variable-seq-lengths \
--use-distributed-optimizer \
--reuse-fp32-param \
--use-flash-attn \
--no-load-optim \
--no-load-rng \
--no-save-optim \
--no-save-rng \
--num-workers 8 \
"
MM_ARGS="
--mm-data $MM_DATA \
--mm-model $MM_MODEL \
--mm-tool $MM_TOOL
"
OUTPUT_ARGS="
--log-interval 1 \
--save-interval 30 \
--eval-interval 30 \
--eval-iters 10 \
--save $SAVE_PATH \
--ckpt-format torch \
"
DPO_ARGS="
--dpo-beta 0.1 \
--dpo-loss-type sigmoid \
--dpo-label-smoothing 0.0 \
--pref-ftx 0.0 \
--ref-model $LOAD_PATH \
"
logfile=$(date +%Y%m%d)_$(date +%H%M%S)
mkdir -p logs
torchrun $DISTRIBUTED_ARGS /workspace/MindSpeed-MM/posttrain_qwen2vl_dpo.py \
$GPT_ARGS \
$MM_ARGS \
$OUTPUT_ARGS \
$DPO_ARGS \
--distributed-backend nccl \
--lora-target-modules linear_qkv linear_proj linear_fc1 linear_fc2 \
2>&1 | tee logs/train_${logfile}.log
chmod 440 logs/train_${logfile}.log
find $SAVE_PATH -type d -exec chmod 750 {} \;
find $SAVE_PATH -type f -exec chmod 640 {} \;
STEP_TIME=`grep "elapsed time per iteration" logs/train_${logfile}.log | awk -F ':' '{print$5}' | awk -F '|' '{print$1}' | head -n 150 | tail -n 100 | awk '{sum+=$1} END {if (NR != 0) printf("%.1f",sum/NR)}'`
SAMPLES_PER_SECOND=`awk 'BEGIN{printf "%.3f\n", '${GBS}'*1000/'${STEP_TIME}'}'`
echo "Elapsed Time Per iteration: $STEP_TIME"
echo "Average Samples per Second: $SAMPLES_PER_SECOND"
LOG_TOKENS_PER_SECOND=`grep "tokens per sample" logs/train_${logfile}.log`
if [ "$LOG_TOKENS_PER_SECOND" ]; then
AVERAGE_TOKENS=`grep "tokens per sample" logs/train_${logfile}.log | awk -F 'tokens per sample:' '{print$2}' | awk -F '|' '{print$1}' | head -n 150 | tail -n 100 | awk '{sum+=$1} END {if (NR != 0) printf("%.1f",sum/NR)}'`
TOKENS_PER_SECOND=`awk 'BEGIN{printf "%.3f\n", '${SAMPLES_PER_SECOND}'*'${AVERAGE_TOKENS}'}'`
echo "Consumed Tokens per Second: $TOKENS_PER_SECOND"
fi| 参数 | 参数解释 |
|---|---|
| MM_DATA | data_72b_dpo.json路径 |
| MM_MODEL | model_72b.json路径 |
| MM_TOOL | tools.json路径 |
| LOAD_PATH | mm格式模型权重路径 |
| SAVE_PATH | 训练后模型权重保存路径 |
| --train-iters | 总训练次数 |
| --save-interval | 检查点保存频率。每 30 个迭代步骤保存一次模型权重。 |
| --eval-interval | 评估频率。每 30 个迭代步骤在验证集上运行一次评估 |
| --eval-iters | 评估迭代次数。在评估过程中,运行 恰好 10 个批次/步骤来计算验证指标 |
bash finetune_qwen2vl_72b_dpo.shMindSpeed MM修改了部分原始网络的结构名称,在微调后,如果需要将权重转回huggingface格式,可使用mm-convert权重转换工具对微调后的权重进行转换,将权重名称修改为与原始网络一致。
mm-convert Qwen2VLConverter mm_to_hf \
--cfg.save_hf_dir "/workspace/MindSpeed-MM/examples/qwen2vl/save_dir_hf/Qwen2-VL-72B-Instruct" \
--cfg.mm_dir "/workspace/MindSpeed-MM/examples/qwen2vl/save_dir" \
--cfg.hf_config.hf_dir "/mnt/public/models/huggface_models/Qwen/Qwen2-VL-72B-Instruct" \
--cfg.parallel_config.llm_pp_layers [20,20,20,20] \
--cfg.parallel_config.vit_pp_layers [32,0,0,0] \
--cfg.parallel_config.tp_size 2
# 其中:
# save_hf_dir: mm微调后转换回hf模型格式的目录
# mm_dir: 微调后保存的权重目录
# hf_dir: huggingface权重目录
# llm_pp_layers: llm在每个卡上切分的层数,注意要和微调时model.json中配置的pipeline_num_layers一致
# vit_pp_layers: vit在每个卡上切分的层数,注意要和微调时model.json中配置的pipeline_num_layers一致
# tp_size: tp并行数量,注意要和微调启动脚本中的配置一致推理采用vllm_ascend部署,拉取vllm_ascend v0.21.0rc1镜像
docker pull quay.io/ascend/vllm-ascend:v0.21.0rc1启动容器
export image_id=quay.io/ascend/vllm-ascend:v0.21.0rc1
export docker_name=qwen2_vl_infer
docker run -itd --privileged --name=$docker_name --net=host \
--shm-size 200g \
--device=/dev/davinci0 \
--device=/dev/davinci1 \
--device=/dev/davinci2 \
--device=/dev/davinci3 \
--device=/dev/davinci4 \
--device=/dev/davinci5 \
--device=/dev/davinci6 \
--device=/dev/davinci7 \
--device=/dev/davinci_manager \
--device=/dev/hisi_hdc \
--device /dev/devmm_svm \
-v /usr/local/Ascend/driver:/usr/local/Ascend/driver \
-v /usr/local/Ascend/firmware:/usr/local/Ascend/firmware \
-v /usr/local/sbin/npu-smi:/usr/local/sbin/npu-smi \
-v /usr/local/sbin:/usr/local/sbin \
-v /etc/hccn.conf:/etc/hccn.conf \
-v $model_data:/data \
$image_id \
bash进入容器
docker exec -it $docker_name bash在容器内执行以下脚本启动推理服务
export PYTORCH_NPU_ALLOC_CONF="expandable_segments:True"
export HCCL_OP_EXPANSION_MODE="AIV"
export HCCL_BUFFERSIZE=1024
export OMP_NUM_THREADS=10
export OMP_PROC_BIND=false
weight_path="/data"
# 替换为使用的NPU卡
ASCEND_RT_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 \
vllm serve $weight_path \
--served-model-name "qwen2-VL-72B" \
--host 0.0.0.0 \
--port 8011 \
--data-parallel-size 1 \
--tensor-parallel-size 4 \
--max-model-length 32768 \
--max-num-batched-tokens 16384 \
--max-num-seqs 128 \
--gpu-memory-utilization 0.94 \
--trust-remote-code \
--async-scheduling \
--allowed-local-media-path / \
--mm-processor-cache-gb 0 \
--compilation-config '{"cudagraph_mode": "FULL_DECODE_ONLY"}' \
--additional-config '{"enable_cpu_binding":true, "multistream_overlap_shared_expert": true}'curl http://{IP}:{PORT}/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "qwen2-VL-72B",
"messages": [
{"role": "user", "content": [
{"type": "text", "text": "你好!"}
]}],
"max_tokens": 32768, # 注意训练后模型长度设置
"stream": false,
"temperature": 0.1,
"chat_template_kwargs": {"enable_thinking": false} # 是否开启思考模式
}'vllm推理启动配置allowed-local-media-path参数,允许请求使用file://协议读取本地图片等媒体文件
curl http://{IP}:{PORT}/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "qwen2-VL-72B",
"messages": [
{"role": "user", "content": [
{"type": "image_url", "image_url": {"url": "file://FILE_PATH/example.jpg"}},
{"type": "text", "text": "请描述图片中的内容。"}
]}
],
"max_tokens": 32768, # 注意训练后模型长度设置
"stream": false,
"temperature": 0.1,
"chat_template_kwargs": {"enable_thinking": false}
}'