快速本地化部署Qwen2.5-VL模型并解决安装flash-attn及模型权重下载中断问题


flash-attn下载存在问题的读者,请直接跳转并阅读第四步:离线下载flash-attention。


前言

由于LLM参数量巨大、且国内网络不佳,在服务器部署Qwen系列模型会存在缓存模型权重难等问题。依照Qwen官方的README部署模型会存在问题,比如模型下载过程中进度卡死、flash-attn相关库难以安装等问题。因为,为了解决上述问题,将整理一个教程,快速部署Qwen系列模型。


Qwen官网

https://github.com/QwenLM/Qwen2.5-VL


第一步:新建虚拟环境

conda create -n Qwen python=3.10.16 
conda activate Qwen

在这里插入图片描述


第二步:设置加速源

pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/

在这里插入图片描述


第三步:安装基础环境

创建Qwen文件夹,并新建requirements.txt,把下面内容复制到里面。

requirements.txt中的内容如下,复制下面内容到txt文件中

torch==2.6.0
torchvision==0.21.0
transformers==4.51.3
accelerate
qwen-vl-utils[decord]

安装需要的包

pip install -r requirements.txt

在这里插入图片描述


第四步:离线下载flash-attention

下载地址:https://github.com/Dao-AILab/flash-attention/releases/

找到你对应的版本flash_attn-2.74.post(cuda我是安装的12.0,其它的步骤一样就可以选择下面这个包,记得选择False这个版本。)

选择自己对应的离线版本即可。

下载版本:flash_attn-2.7.4.post1+cu12torch2.6cxx11abiFALSE-cp310-cp310-linux_x86_64.whl

CSDN下载:https://download.csdn.net/download/weixin_43312117/91177518?spm=1001.2014.3001.5501
在这里插入图片描述

把下载的离线文件上传到服务器当前用户的Download文件夹中,然后安装该文件

pip install flash_attn-2.7.4.post1+cu12torch2.6cxx11abiFALSE-cp310-cp310-linux_x86_64.whl

在这里插入图片描述


第五步:下载模型权重

近期,用huggface镜像下载会出现不稳定的情况;请改用modelscope下载权重

# 用魔塔社区下载
pip install modelscope
# 下载时指定路径,加载模型的时候要指向到该路径
modelscope download --model Qwen/Qwen2.5-VL-3B-Instruct --local_dir ./Qwen2.5-VL-3B-Instruct

在这里插入图片描述

下载完成

在这里插入图片描述


第六步:运行代码:修改对应模型权重路径

from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor
from qwen_vl_utils import process_vision_info

# default: Load the model on the available device(s)
model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
    "./Qwen2.5-VL-3B-Instruct", torch_dtype="auto", device_map="auto"
)

# We recommend enabling flash_attention_2 for better acceleration and memory saving, especially in multi-image and video scenarios.
# model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
#     "Qwen/Qwen2.5-VL-7B-Instruct",
#     torch_dtype=torch.bfloat16,
#     attn_implementation="flash_attention_2",
#     device_map="auto",
# )

# default processor
processor = AutoProcessor.from_pretrained("./Qwen2.5-VL-3B-Instruct")

# The default range for the number of visual tokens per image in the model is 4-16384.
# You can set min_pixels and max_pixels according to your needs, such as a token range of 256-1280, to balance performance and cost.
# min_pixels = 256*28*28
# max_pixels = 1280*28*28
# processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct", min_pixels=min_pixels, max_pixels=max_pixels)

messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "image",
                "image": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg",
            },
            {"type": "text", "text": "Describe this image."},
        ],
    }
]

# Preparation for inference
text = processor.apply_chat_template(
    messages, tokenize=False, add_generation_prompt=True
)
image_inputs, video_inputs = process_vision_info(messages)
inputs = processor(
    text=[text],
    images=image_inputs,
    videos=video_inputs,
    padding=True,
    return_tensors="pt",
)
inputs = inputs.to(model.device)

# Inference: Generation of the output
generated_ids = model.generate(**inputs, max_new_tokens=128)
generated_ids_trimmed = [
    out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
]
output_text = processor.batch_decode(
    generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
)
print(output_text)

轻松运行得到结果,如何和我设置一样就直接运行,不一致就把加载模型路径切换到你下载权重的地方。

在这里插入图片描述


<think>好的,我现在需要帮助用户解决如何本地部署Qwen2.5-VL 3B模型提供API服务的问题。首先,我得仔细阅读用户提供的三个引用内容,看看有没有相关的信息可以直接使用。 引用[1]提到了Qwen2.5-VL-72B模型的应用场景和API调用示例,但用户需要的是3B版本的部署方法。可能需要参考类似的步骤,但需要注意模型大小的差异。引用[2]和[3]都是关于Qwen2.5-7B-Instruct模型的FastAPI部署教程,特别是提到了使用AutoDL平台的环境镜像和snapshot_download函数下载模型。虽然用户询问的是3B模型,但部署流程可能有共通之处,比如使用FastAPI框架、下载模型的方式等。 接下来,我需要整理出本地部署Qwen2.5-VL 3B的步骤。首先,环境准备应该包括Python环境、必要的库如transformers和modelscope,可能还需要CUDA支持。然后,模型下载部分,根据引用[3],可以使用modelscope的snapshot_download函数,需要确认3B模型的名称是否正确,可能需要查看官方文档。接着是API服务搭建,参考引用[2]中的FastAPI部署方法,编写启动脚本和API接口。此外,可能需要处理发请求和GPU资源管理,比如使用uvicorn运行应用,设置workers数量。 需要注意的是,用户可能对具体步骤不熟悉,比如如何安装依赖、如何调用API,所以需要详细说明每个步骤的命令和代码示例。同时,要提醒用户注意模型路径、端口设置以及依赖版本兼容性问题最后,生成的相关问题要围绕部署过程中可能遇到的难点和应用场景展开,帮助用户进一步探索。 需要验证一下模型名称是否正确,Qwen2.5-VL是否有3B版本,或者用户可能指的是Qwen1.5版本?如果引用中的模型名称可能有误,可能需要用户确认,但根据问题描述,假设存在Qwen2.5-VL 3B模型。此外,确保代码示例中的模型加载部分正确,比如使用AutoModelForCausalLM或AutoModel类,以及tokenizer的加载方式。还要考虑API的安全性和性能优化,比如超时设置和错误处理,但可能超出当前问题范围,可以简要提及。 总之,步骤大致分为环境准备、模型下载、API服务实现和测试调用。确保各部分衔接正确,引用相关参考来源,生成相关问题帮助用户深入理解。</think>### Qwen2.5-VL 3B模型本地部署及API服务配置指南 #### 一、环境准备 1. 安装Python 3.8+环境,推荐使用conda管理: ```bash conda create -n qwen_env python=3.10 conda activate qwen_env ``` 2. 安装核心依赖库: ```bash pip install "modelscope>=1.9.0" transformers fastapi uvicorn python-multipart ``` 3. 验证GPU驱动(需NVIDIA显): ```bash nvidia-smi # 确认CUDA版本≥11.7 ``` #### 二、模型下载 使用modelscope下载3B模型(注意替换模型名称)[^3]: ```python from modelscope import snapshot_download model_dir = snapshot_download('qwen/Qwen2.5-VL-3B', cache_dir='./models') ``` #### 三、API服务搭建 1. 创建`api_server.py`: ```python from fastapi import FastAPI from transformers import AutoModelForCausalLM, AutoTokenizer import uvicorn app = FastAPI() model_path = "./models/qwen/Qwen2.5-VL-3B" # 加载模型 tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True) model = AutoModelForCausalLM.from_pretrained( model_path, device_map="auto", trust_remote_code=True ) @app.post("/generate") async def generate_text(prompt: str, max_length: int = 512): inputs = tokenizer(prompt, return_tensors="pt").to(model.device) outputs = model.generate(**inputs, max_length=max_length) return {"response": tokenizer.decode(outputs[0])} if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=8000, workers=2) ``` #### 四、服务启动与测试 1. 启动服务: ```bash CUDA_VISIBLE_DEVICES=0 python api_server.py ``` 2. 调用测试(Python示例): ```python import requests response = requests.post("http://localhost:8000/generate", json={ "prompt": "解释量子计算基本原理", "max_length": 200 }) print(response.json()) ``` #### 五、注意事项 1. 显存需求:3B模型约需6GB显存,建议使用至少RTX 3060级别GPU 2. 模型加载参数: ```python model = AutoModelForCausalLM.from_pretrained( model_path, device_map="auto", torch_dtype=torch.float16, # 半精度加速 low_cpu_mem_usage=True ) ``` 3. 安全建议:生产环境需添加API密钥验证[^2]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陈嘿萌

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值