LLM - 使用 vLLM 部署 Qwen2-VL 多模态大模型 (配置 FlashAttention) 教程

欢迎关注我的CSDN:https://spike.blog.csdn.net/
本文地址:https://spike.blog.csdn.net/article/details/142528967

免责声明:本文来源于个人知识与公开资料,仅用于学术交流,欢迎讨论,不支持转载。


vLLM
vLLM 用于 大语言模型(LLM) 的推理和服务,具有多项优化技术,包括先进的服务吞吐量、高效的内存管理、连续批处理请求、优化 CUDA 内核以及支持量化技术,如GPTQ、AWQ等。FlashAttention 是先进的注意力机制优化工具,通过减少内存访问和优化计算过程,显著提高大型语言模型的推理速度。

GitHub:

  • FlashAttention: https://github.com/Dao-AILab/flash-attention
  • Transformers: https://github.com/huggingface/transformers
  • vLLM: https://github.com/vllm-project/vllm

1. 配置 vLLM

准备 Qwen2-VL 模型,包括 7B 和 72B,即:

modelscope --token [your token] download --model Qwen/Qwen2-VL-7B-Instruct
modelscope --token [your token] download --model Qwen/Qwen2-VL-72B-Instruct-GPTQ-Int4

注意:Qwen2-VL 暂时不支持 GGUF 转换,因此不能使用 Ollama 提供服务。

配置 vLLM:

pip install vllm==0.6.1 -i https://pypi.tuna.tsinghua.edu.cn/simple

参考:vLLM - Using VLMs

注意:当前(2024.9.26)最新 Transformers 版本不支持 Qwen2-VL,需要使用固定 commit 版本,参考:

pip install git+https://github.com/huggingface/transformers.git@21fac7abba2a37fae86106f87fcf9974fd1e3830

Transformers 的 Commit ID (21fac7abba2a37fae86106f87fcf9974fd1e3830) 内容,以更新 Qwen2-VL 为主,即:

commit 21fac7abba2a37fae86106f87fcf9974fd1e3830 (HEAD)
Author: Shijie <821898965@qq.com>
Date:   Fri Sep 6 00:19:30 2024 +0800simple align qwen2vl kv_seq_len calculation with qwen2 (#33161)* qwen2vl_align_kv_seqlen_to_qwen2* flash att test* [run-slow] qwen2_vl* [run-slow] qwen2_vl fix OOM* [run-slow] qwen2_vl* Update tests/models/qwen2_vl/test_modeling_qwen2_vl.pyCo-authored-by: Raushan Turganbay <raushan.turganbay@alumni.nu.edu.kz>* Update tests/models/qwen2_vl/test_modeling_qwen2_vl.pyCo-authored-by: Raushan Turganbay <raushan.turganbay@alumni.nu.edu.kz>* code quality---------

vLLM 的视觉文本测试代码,如下:

  • 通过 SamplingParams 设置最大的 Tokens 数量。
  • 注意,不同的模型 Image Token 也不同,Qwen2-VL 是 <|image_pad|>,而 InternVL2-2B<image>

即:

from vllm import LLM, SamplingParams
import PIL
# from vllm.assets.image import ImageAsset
from vllm.assets.video import VideoAsset
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "1"def main():# Qwen2-VLllm = LLM(model="llm/Qwen/Qwen2-VL-7B-Instruct/")# 设置最大输出 Token 数量sampling_params = SamplingParams(max_tokens=8172)# InternVL2-2B# llm = LLM(model="llm/InternVL2-2B/", trust_remote_code=True)# Refer to the HuggingFace repo for the correct format to use# prompt = "USER: <image>\nWhat is the content of this image?\nASSISTANT:"# Load the image using PIL.Image# image = PIL.Image.open("llm/img_test.jpg")# -------------------- image -------------------- #prompt = "USER: <|image_pad|>\nWhat is the content of this image?\nASSISTANT:"image = PIL.Image.open("llm/image.jpg").convert("RGB")outputs = llm.generate({"prompt": prompt,"multi_modal_data": {"image": image},}, sampling_params)print("[Info] Image: \n")for o in outputs:generated_text = o.outputs[0].textprint(generated_text)# -------------------- image -------------------- ## -------------------- video -------------------- #prompt = "USER: <|video_pad|>\nWhat is the content of this video?\nASSISTANT:"video = VideoAsset(name="llm/video.mp4", num_frames=50).np_ndarraysoutputs = llm.generate({"prompt": prompt,"multi_modal_data": {"video": video},}, sampling_params)print("[Info] Video: \n")for o in outputs:generated_text = o.outputs[0].textprint(generated_text)# -------------------- video -------------------- #if __name__ == '__main__':main()

Image Qwen2-VL 的输出:

The image shows a close-up of a person’s feet wearing brown high-heeled shoes with a glossy finish. The shoes have a thick sole and a small platform heel. The background features a light-colored couch with books on top, suggesting an indoor setting, possibly a living room or study. The focus is on the shoes, which are the most prominent object in the image.
这张图片展示一个人的脚穿着棕色的高跟鞋,鞋子表面有光泽。鞋子有一个厚底和一个小的厚跟。背景是一张浅色的沙发,上面放着书,暗示了室内环境,可能是客厅或书房。焦点在鞋子上,它们是图片中最突出的对象。

Img

Video Qwen2-VL 的输出:

The video portrays a person sitting on a stool near a sheer curtain adorned with a floral pattern. Throughout the video, the person in the forefront appears to be a girl across a selection of scenes. She is wearing a light-colored, cozy-looking outfit, and she is moving her feet in a fluid motion. The overall atmosphere of the video is simple and quaint.
视频描绘一个人坐在一张凳子上,靠近一扇装饰有花卉图案的透明窗帘。在整个视频中,前景中的人似乎是一个女孩,她出现在一系列场景中。她穿着一件浅色的、看起来很舒服的衣服,她的脚在流畅地移动。视频的整体氛围简单而古雅。

Video

BugFix1:

  File "miniconda3/envs/torch-llm/lib/python3.9/site-packages/vllm/transformers_utils/configs/__init__.py", line 13, in <module>from vllm.transformers_utils.configs.mllama import MllamaConfigFile "miniconda3/envs/torch-llm/lib/python3.9/site-packages/vllm/transformers_utils/configs/mllama.py", line 1, in <module>from transformers.models.mllama import configuration_mllama as mllama_hf_config
ModuleNotFoundError: No module named 'transformers.models.mllama'

原因:降级 vLLM 版本至 0.6.1vllm/transformers_utils/configs/mllama.py0.6.2 版本加入,即:

pip install vllm==0.6.1 -i https://pypi.tuna.tsinghua.edu.cn/simple

BugFix2:

[rank0]:   File "miniconda3/envs/torch-llm/lib/python3.9/site-packages/vllm/inputs/registry.py", line 256, in process_input
[rank0]:     return processor(InputContext(model_config), inputs)
[rank0]:   File "miniconda3/envs/torch-llm/lib/python3.9/site-packages/vllm/model_executor/models/qwen2_vl.py", line 770, in input_processor_for_qwen2_vl
[rank0]:     assert len(image_indices) == len(image_inputs)
[rank0]: AssertionError

原因,参考 vllm/model_executor/models/qwen2_vl.pyhf_config.image_token_id 与当前 Prompt 的 Image Token (<image>),不一致,即:

prompt_token_ids = llm_inputs.get("prompt_token_ids", None)
if prompt_token_ids is None:prompt = llm_inputs["prompt"]prompt_token_ids = processor.tokenizer(prompt,padding=True,return_tensors=None,)["input_ids"]
print(f"[Info] decode prompt: \n{processor.decode(prompt_token_ids)}\n")
print(f"[Info] decode image_token_id (151655): {processor.decode([151655])}")# Expand image pad tokens.
if image_inputs is not None:image_indices = [idx for idx, token in enumerate(prompt_token_ids)if token == hf_config.image_token_id]print(f"[Info] hf_config.image_token_id: {hf_config.image_token_id}, prompt_token_ids: {prompt_token_ids}")image_inputs = make_batched_images(image_inputs)print(f"[Info] image_indices: {len(image_indices)} and image_inputs: {len(image_inputs)}")assert len(image_indices) == len(image_inputs)

经过分析,确定 Qwen2-VL 的 Image Token 是 <|image_pad|>,而不是 <image>,替换 Prompt 即可。

输出:

[Info] decode prompt: 
USER: <|image_pad|>
What is the content of this image?
ASSISTANT:
[Info] decode image_token_id (151655): <|image_pad|>
[Info] hf_config.image_token_id: 151655, prompt_token_ids: [6448, 25, 220, 151655, 198, 3838, 374, 279, 2213, 315, 419, 2168, 5267, 4939, 3846, 2821, 25]
[Info] image_indices: 1 and image_inputs: 1

2. 配置 FlashAttention

FlashAttention 可以加速大模型的推理过程,配置 FlashAttention,参考,安装依赖的 Python 包:

pip install packaging
pip install ninja

测试 ninja 包是否可用,即:

ninja --version  # 1.11.1.git.kitware.jobserver-1
echo $?  # 0

Ninja 类似于 Makefile,语法简单,但是比 Makefile 更加简洁。

不推荐 直接安装 flash-attn,建议使用源码安装,安装过程可控,请耐心等待,即:

pip install flash-attn --no-build-isolation# log
Building wheels for collected packages: flash-attnBuilding wheel for flash-attn (setup.py) ... |

检测 Python 版本:

python --version # Python 3.9.19
nvidia-smi  # CUDA Version: 12.0pythonimport torch
print(torch.__version__)  # 2.4.0+cu121
print(torch.cuda.is_available())  
exit()

建议通过直接源码进行安装,即:

git clone git@github.com:Dao-AILab/flash-attention.git
python setup.py install

整体的编译过程,包括 85 步,耐心等待,即:

Using envvar MAX_JOBS (64) as the number of workers...
[1/85] c++ -MMD -MF ...
# ...
Using miniconda3/envs/torch-llm/lib/python3.9/site-packages
Finished processing dependencies for flash-attn==2.6.3

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/53940.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

ASCII码对应表

刚开始基础计算机编程的时候&#xff0c;学习的是二进制、十进制、十六进制。 十进制是生活习惯中最常用的计数方法&#xff0c;也是我们计数的思维逻辑。 后来接触了计算机基础&#xff0c;我们知道计算机都是用二进制表示的&#xff0c;但是这种表示方法让人理解很困难。 …

wordpress迁移到别的服务器

wordpress论坛网站搭建 于2023/11/16写的该文章 一-配置环境 配置LNMP&#xff08;linuxnginxmysqlphpphpmyadmin&#xff09;环境或者LAMP&#xff08;apache&#xff09; 可以选择集成了这些软件的套件 下载链接&#xff1a;https://www.xp.cn/download.html 手动下载这…

1.1.4 计算机网络的分类

按分布范围分类&#xff1a; 广域网&#xff08;wan&#xff09; 城域网&#xff08;man&#xff09; 局域网&#xff08;lan&#xff09; 个域网&#xff08;pan&#xff09; 注意&#xff1a;如今局域网几乎采用“以太网技术实现”&#xff0c;因此“以太网”几乎成了“局域…

C#源码安装ZedGraph组件,并且立即演示使用

要想源码安装ZedGraph,那么就需要先找到源码,而源码的来源,显然就是鼎鼎大名的Github: https://github.com/ZedGraph/ZedGraph 下载源码的地址是: https://gitcode.com/gh_mirrors/ze/ZedGraph.git 这样就可以把代码全部下载下来,不过它是支持.net 3.5的版本,现在已经…

努比亚z17努比亚NX563j原厂固件卡刷包下载_刷机ROM固件包下载-原厂ROM固件-安卓刷机固件网

努比亚z17努比亚NX563j原厂固件卡刷包下载_刷机ROM固件包下载-原厂ROM固件-安卓刷机固件网 统版本&#xff1a;官方软件作者&#xff1a;热心网友rom大小&#xff1a;911MB发布日期&#xff1a;2018-12-23 努比亚z17努比亚NX563j原厂固件卡刷包下载_刷机ROM固件包下载-原厂RO…

ScrapeGraphAl AI爬虫

官网&#xff1a;https://scrapegraph-ai.readthedocs.io/en/latest/ from flask import Flask, request, jsonify from scrapegraphai.graphs import SmartScraperGraphapp Flask(__name__)openai_key "sk-xxxxxxxxxxxxxxxxxxxx"graph_config {"llm":…

Android 系统增加ro property

以下都是基于高通平台 一&#xff0c;Android.mk 中添加 新增自己的参考系统的device/qcom/xxxx/xxxx.mk #target specific runtime prop for qspm PRODUCT_PROPERTY_OVERRIDES \ ro.vendor.qspm.enabletrue 二&#xff0c;脚本添加。 build/tools/buildinfo.sh 里面很多…

react crash course 2024(7) react router dom

安装 npm i react-router-dom 引入 import {Route,createBrowserRouter,createRoutesFromElements,RouterProvider} from react-router-dom 在app.jsx const router createBrowserRouter(createRoutesFromElements(<Route index element {<h1>My App</h1>…

视频格式转换:avi格式转mp4格式

批量将avi格式的视频转换为mp4格式 # 批量avi格式视频转mp4格式 import os from moviepy.editor import VideoFileClip video_folder r视频文件路径 avi_files [f for f in os.listdir(video_folder) if f.endswith(.avi)] for avi_file in avi_files:avi_path os.path.joi…

电子证件照应用

一、亦仁分享 几乎每个人都有证件照需求&#xff0c;但绝大多数照相馆都不会给电子版&#xff0c;这衍生出自动生成证件照的需求。App Store 上&#xff0c;搜证件照&#xff0c;排名第一的 APP 付费 6 元&#xff0c;光点评就有 5439 份&#xff0c;更不用说下载量了。小程序…

如何高效管理知识产权全链条?

为了有效保护企业的创新成果&#xff0c;确保技术创意的顺利转化&#xff0c;以及高效管理知识产权案件&#xff0c;建立一套完善的知识产权管理体系至关重要。对于企业而言&#xff0c;如何有效地管理知识产权的各个环节&#xff0c;从研发项目到技术创意&#xff0c;再到提案…

计算机毕业设计 办公用品管理系统的设计与实现 Java实战项目 附源码+文档+视频讲解

博主介绍&#xff1a;✌从事软件开发10年之余&#xff0c;专注于Java技术领域、Python人工智能及数据挖掘、小程序项目开发和Android项目开发等。CSDN、掘金、华为云、InfoQ、阿里云等平台优质作者✌ &#x1f345;文末获取源码联系&#x1f345; &#x1f447;&#x1f3fb; 精…

基于Arduino的自弹尤克里里机器人

需要项目源码资料的可以私信我 基于Arduino的自弹尤克里里机器人 一、简介二、材料清单三、工具四、实现过程步骤1&#xff1a;实物图步骤2&#xff1a;3D打印部件步骤3&#xff1a;组装上半部分步骤4&#xff1a;组装下半部分步骤5&#xff1a;安装导轨步骤6&#xff1a;设置…

1. 如何在服务器上租GPU跑实验 (以AutoDL为例) - 深度学习·科研实践·从0到1

目录 前言 1. 在AutoDL上注册账号 2. 在算力市场选择GPU 3. 创建实例 4. 控制台-容器实例界面&#xff08;核心&#xff09; 4.1 无卡模式&#xff08;常用&#xff09; 5. 帮助文档 前言 好记性不如烂笔头&#xff0c;本专栏将详细记录下本人学习深度学习工程实践&…

从零开始手写STL库:Priority_Queue

从零开始手写STL库–Priority_Queue的实现 Gihub链接&#xff1a;miniSTL 文章目录 从零开始手写STL库–Priority_Queue的实现一、priority_queue是什么&#xff1f;二、堆是什么&#xff1f;三、priority_queue要包含什么函数总结 一、priority_queue是什么&#xff1f; 优先…

基于深度学习的图像去噪与去模糊

基于深度学习的图像去噪和去模糊是计算机视觉中的重要任务&#xff0c;旨在提升图像质量&#xff0c;去除噪声和模糊。以下是这两个领域的主要方法和技术概述&#xff1a; 1. 图像去噪 图像去噪的目标是去除图像中的噪声&#xff0c;同时尽量保留细节。主要方法包括&#xff…

程序一毛,人生九牛

Welcome 大家好&#xff0c;欢迎来到瑾芳玉洁的博客&#xff01; &#x1f611;励志开源分享诗和代码&#xff0c;三餐却无汤&#xff0c;顿顿都被噎。 &#x1f62d;有幸结识那个值得被认真、被珍惜、被捧在手掌心的女孩&#xff0c;不出意外被敷衍、被唾弃、被埋在了垃圾堆。…

ADRC线性跟踪微分器TD详细测试(Simulink 算法框图+CODESYS ST+博途SCL完整源代码)

1、ADRC线性跟踪微分器 ADRC线性跟踪微分器(ST+SCL语言)_adrc算法在博途编程中scl语言-CSDN博客文章浏览阅读784次。本文介绍了ADRC线性跟踪微分器的算法和源代码,包括在SMART PLC和H5U平台上的实现。文章提供了ST和SCL语言的详细代码,并讨论了跟踪微分器在自动控制中的作用…

Vue3动态导入后端路由

动态获取文件 // modules就是一个map&#xff0c;文件路径作为key&#xff0c;文件对象作为value const modulesimport.meta.glob(../views/**/*.vue)获取到的modules对象如下&#xff1a; 添加动态路由 import {createRouter, createWebHashHistory} from vue-routerconst m…

AutoGen实现多代理—AI Agentic Design Patterns with AutoGen(二)

1. AutoGen顺序对话在客户入职案例上的应用 如图&#xff0c;客户入职前会经历三个阶段&#xff0c;一个代理收集客户的信息&#xff0c;一个代理收集客户的感兴趣话题&#xff0c;一个代理根据前两个代理的基础信息与客户代理对话&#xff0c;产生聊天信息。 本节实验的地址&…