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

news2024/9/27 23:32:13

欢迎关注我的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 +0800
    simple 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.py
    Co-authored-by: Raushan Turganbay <raushan.turganbay@alumni.nu.edu.kz>
    * Update tests/models/qwen2_vl/test_modeling_qwen2_vl.py
    Co-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
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "1"


def main():
    # Qwen2-VL
    llm = LLM(model="llm/Qwen/Qwen2-VL-7B-Instruct/")
    prompt = "USER: <|image_pad|>\nWhat is the content of this image?\nASSISTANT:"
    
    # 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:"
    
    # 设置最大输出 Token 数量
    sampling_params = SamplingParams(max_tokens=8172)

    # Load the image using PIL.Image
    image = PIL.Image.open("llm/img_test.jpg")

    # Single prompt inference
    outputs = llm.generate({
        "prompt": prompt,
        "multi_modal_data": {"image": image},
    }, sampling_params)

    for o in outputs:
        generated_text = o.outputs[0].text
        print(generated_text)


if __name__ == '__main__':
    main()

Qwen2-VL 的输出:

The image shows a person standing on a road near a sidewalk. The person is dressed in a light-colored outfit consisting of a short-sleeved blouse and a skirt. The background features greenery, including trees and some buildings, with a few cars parked along the street. The overall scene appears to be a sunny day with good visibility.

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 MllamaConfig
  File "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-attn
  Building wheel for flash-attn (setup.py) ... |

检测 Python 版本:

python --version # Python 3.9.19
nvidia-smi  # CUDA Version: 12.0

python

import 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.coloradmin.cn/o/2167973.html

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

相关文章

VS Code使用Git Bash终端

Git Bash可以运行linux命令&#xff0c;在VS Code的终端界面&#xff0c;找到号旁边的箭头&#xff0c;就能直接切换了 当然&#xff0c;前提是安装了Git Bash&#xff0c;并且在资源管理器里&#xff0c;能鼠标右键出"Git Bash Here"

【个人笔记】线程和线程池的状态以及转换方式

线程和线程池的状态是不一样的&#xff01;&#xff01; 线程有 6 种状态&#xff0c;查看Thread的State枚举类&#xff1a; NEW&#xff1a;创建后没启动的线程就处于这种状态RUNNABLE&#xff1a;正在java虚拟机中执行的线程就处于这种状态BLOCKED&#xff1a;受阻塞并等待…

前端中CSS选择器权重的问题

前言 前端中很重要的CSS&#xff0c;使得网页更加丰满美丽&#xff0c;我们使用CSS时&#xff0c;必不可少的需要使用选择器&#xff0c;选择器也分为简单选择器和复合选择器。而在给选择器中填充内容时&#xff0c;有时候会有一些命令重复&#xff0c;会涉及到优先级的问题&a…

setInterval 实现匀速运动示例【JavaScript】

这段代码利用 setInterval 实现了一个简单的动画&#xff0c;当用户点击按钮时&#xff0c;页面上的方块会向右移动&#xff0c;直到到达一定的边界为止。 实现效果&#xff1a; 代码&#xff1a; <!DOCTYPE html> <html lang"zh"><head><met…

Java搭建法律AI助手,快速实现RAG应用

使用AI4J快速接入RAG应用 | 结合Pinecone实现法律AI助手RAG应用 本博文给大家介绍一下如何使用AI4J快速接入OpenAI大模型&#xff0c;并且结合Pinecone向量数据库实现一个刑法AI助手的RAG应用。 介绍 由于SpringAI需要使用JDK17和Spring Boot3&#xff0c;但是目前很多应用依…

初识 C 语言(一)

目录 一、 第一个 C 程序1. printf() 函数和 stdio.h 头文件2. main() 函数和 return 语句 二、类型和变量1. C 语言中的基本类型2. 变量的创建和命名规则3. 类型和变量的大小 三、printf() 函数和 scanf() 函数1. printf() 函数的使用2. 各种类型的输出格式3. scanf() 函数的使…

屏幕翻译下载哪个?建议试试这5个

国庆假期快到了&#xff0c;计划出国游或享受宅家追更海外剧的你&#xff0c;是否担心语言不通带来的小困扰&#xff1f; 别急&#xff0c;下面这篇文章就为你揭秘5款屏幕翻译免费软件&#xff0c;无论是浏览外国网站、阅读外语文档还是跨越语言障碍&#xff0c;都毫无压力。 …

YOLOv8-pose+streamlit 实现人体关键点检测/姿态估计系统(后续可用于健身时的姿态估计,训练纠正等....)

人体关键点检测系统 一、安装与配置1.1 安装 Streamlit1.2 配置文件1.3 运行Streamlit应用1.4 找模板 二、人体关键点检测算法2.1 关键点序号2.2 YOLOv8-pose图像推理 三、将YOLOv8-pose算法内置到streamlit中3.1 整体结构3.2 常见问题- RGB通道颠倒- Numpy与OpenCV之间的转换 …

java-必会jdk1.8新特性

1:抽象类的变化 前言&#xff1a; 接口里只能做方法定义不能有方法的实现&#xff0c;抽象类的方法不需要继承类必须去实现的一种方式。 定义一个抽象类TestAbstractclass 如下 package com.lm.jdk8.Abstractclass;/*** 抽象类*/ public abstract class Abstractclass {abstrac…

通信工程学习:什么是PNF物理网络功能

PNF:物理网络功能 PNF(Physical Network Function)即物理网络功能,是指支持网络功能的物理设备。以下是关于PNF的详细解释: 一、定义与特点 定义: PNF是网络设备厂商(如Cisco、华为、H3C等)通过专用硬件实体提供软件功能的设备。这些设备直接在物理服务器上运…

java:异常处理

背景 Java中的异常体系基于几个关键的概念和类&#xff0c;主要包括Throwable类、Exception类&#xff08;及其子类&#xff09;和Error类。 异常分类 1. Throwable 类 Throwable 是所有错误与异常的超类。它有两个直接子类&#xff1a;Error 和 Exception。 2. Error 类 …

【OpenAI o1思维链CoT必看论文】谷歌“思维链提示“让AI更懂人类推理

原创 超 超的闲思世界 AI的推理能力正迎来一场重大突破。谷歌大脑团队最新开发的"思维链提示"方法&#xff0c;让大型语言模型在复杂推理任务上展现出惊人的进步。这项创新技术无需对模型进行额外训练&#xff0c;却能显著提升AI的推理能力&#xff0c;让机器的思…

python命令行怎么换行

在命令行中“>>>”是python的输入提示符&#xff0c;按回车键则表示输入结束。那么如何在命令行中换行呢&#xff1f; 换行方法&#xff1a;\ 如&#xff1a; >>> print aaa; \ ... print bbb; \ ... print ccc 注意“&#xff1b;”的使用。python本身语句…

excel单元格增加可选下拉列表

excel单元格增加可选下拉列表 下拉设置&#xff1a;数据–数据验证-选择序列-填写来源&#xff08;来源数据用英文逗号分隔&#xff09;&#xff08;是,否&#xff09;- 区域应用&#xff1a;选定区域-数据验证-是-确认

2024年第十届信息学与商业工程国际会议(ICIBE 2024)将在泰国曼谷召开!

2024年第十届信息学与商业工程国际会议 (ICIBE 2024) 将于2024年12月20日-22日在泰国曼谷举办。ICIBE 2024由泰国兰实大学主办&#xff0c;中国澳门大学和菲律宾马普亚大学提供技术支持。本次会议为来自世界各地的专业人士、科学家、工程师、教育工作者、学生和研究人员提供了一…

tauri程序加载本地图片或者文件在前端页面展示

要想在前端页面中展示本地文件或者文件夹&#xff0c;需要使用convertfilesrc这个api&#xff0c;可以非常方便的展示内容&#xff0c;官方文档&#xff1a;tauri | Tauri Apps convertFileSrc甚至位于invoke之前&#xff0c;但我却一直没有注意到它&#xff0c;一方面是因为&…

街头摊贩检测系统源码分享

街头摊贩检测检测系统源码分享 [一条龙教学YOLOV8标注好的数据集一键训练_70全套改进创新点发刊_Web前端展示] 1.研究背景与意义 项目参考AAAI Association for the Advancement of Artificial Intelligence 项目来源AACV Association for the Advancement of Computer Vis…

磷酸化多肽及其修饰方法

【知识与技术分享~~~】 磷酸化多肽主要指肽链中的Ser、Tyr和Thr残基的侧链羟基被修饰成酸式磷酸酯多肽&#xff0c;有L构象和D构象之分&#xff0c;其结构如下&#xff1a; 楚肽生物提供 在固相多肽合成SPPS&#xff08;Solid-PhasePeptide Synthesis&#xff09;采用的是Fmoc-…

Day100 代码随想录打卡|动态规划篇--- 01背包问题(一维数组版)

题目&#xff08;卡玛网T46&#xff09;&#xff1a; 小明是一位科学家&#xff0c;他需要参加一场重要的国际科学大会&#xff0c;以展示自己的最新研究成果。他需要带一些研究材料&#xff0c;但是他的行李箱空间有限。这些研究材料包括实验设备、文献资料和实验样本等等&am…

2024外研社综合能力大赛第一场真题

网上找滴~自用 审核不过&#xff0c;备考指南发知乎了&#xff1a;https://zhuanlan.zhihu.com/p/730698685