本文不生产技术,只做技术的搬运工!!
前言
公开的Qwen2.5-VL模型虽然功能非常强大,但有时面对专业垂直领域的问题往往会出现一些莫名其妙的回复,这时候大家一版选择对模型进行微调,而微调后的模型如果直接部署则显存开销过大,这时就需要执行量化,下面将介绍执行本地AWQ量化的具体流程。
实验环境
这里作者使用4卡A100(40G)进行Qwen2.5-vl-32B的AWQ量化,首先需要配置python环境
ms-swift
由于作者没有找到AutoAWQ框架下进行Qwen2.5-VL的量化教程,所以干脆偷懒,使用ms-swift进行量化
conda create -n ms-swift python=3.10 -y
conda activate ms-swift
git clone https://github.com/modelscope/ms-swift.git
cd ms-swift
pip install -e '.[all]'
AutoAWQ
git clone https://github.com/casper-hansen/AutoAWQ.git
cd AutoAWQ
pip install -e .
执行量化
CUDA_VISIBLE_DEVICES=0,1,2,3 \
swift export \
--model /data/qwen2.5-vl/model-32b/ \
--dataset 'AI-ModelScope/alpaca-gpt4-data-zh#500' \
'AI-ModelScope/alpaca-gpt4-data-en#500' \
--quant_n_samples 256 \
--quant_batch_size -1 \
--max_length 2048 \
--quant_method awq \
--quant_bits 4 \
--output_dir /data/qwen2.5-vl/model-32b-awq/
VLLM部署
git clone https://github.com/QwenLM/Qwen2.5-VL.git
cd Qwen2.5-VL
conda create -n qwen2.5-vl python=3.11 -y
conda activate qwen2.5-vl
pip install -r requirements_web_demo.txt
pip install flash-attn==2.6.1
pip install vllm==0.7.3
pip install autoawq --no-deps
CUDA_VISIBLE_DEVICES=0,1,2,3 vllm serve /data/qwen2.5-vl/model-32b-awq/ --port 8084 --host 0.0.0.0 --dtype bfloat16 --limit-mm-per-prompt image=5,video=5 --max-model-len 16384 --tensor-parallel-size 4 --gpu-memory-utilization 0.8 --enforce-eager
推理测试
from openai import OpenAI
import time
import base64
# Set OpenAI's API key and API base to use vLLM's API server.
openai_api_key = "EMPTY"
openai_api_base = "http://127.0.0.1:8084/v1"
client = OpenAI(
api_key=openai_api_key,
base_url=openai_api_base,
)
times = [] # 记录每次调用的时间
image_path = r"/home/workspace/0a8e9a66f39f45989415c102f0ec227a.jpg"
with open(image_path, "rb") as f:
encoded_image = base64.b64encode(f.read())
encoded_image_text = encoded_image.decode("utf-8")
base64_qwen = f"data:image;base64,{encoded_image_text}"
for i in range(20):
start_time = time.time() # 开始时间-
chat_response = client.chat.completions.create(
model="/data/qwen2.5-vl/model-32b-awq/",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": base64_qwen
},
},
{"type": "text", "text": "描述一下这张图像"},
],
},
]
)
end_time = time.time() # 结束时间
elapsed_time = end_time - start_time # 计算耗时
times.append(elapsed_time) # 添加到列表中
print(f"第 {i + 1} 次调用结果: {chat_response.choices[0].message.content}")
print(f"第 {i + 1} 次调用耗时: {elapsed_time:.4f} 秒")
# 去掉最大值和最小值
if len(times) >= 3:
times.remove(max(times))
times.remove(min(times))
# 计算平均耗时
average_time = sum(times) / len(times) if times else 0
print(f"去掉一个最大值和一个最小值后,平均每次调用耗时: {average_time:.4f} 秒")
备注
关于VLLM部署的问题,作者发现不管是官方提供的AWQ模型还是自己量化的AWQ模型推理速度都慢于未量化版,目前还没找到原因;另外就是作者的设备使用VLLM部署时7b-awq不需要加--enforce-eager,但是32b-awq和72b-awq都需要加这个参数,目前推测是显存不够,真实原因有待考证。