第五节课《LMDeploy 量化部署 LLM 实践》

LMDeploy 量化部署 LLM-VLM 实践_哔哩哔哩_bilibili

PDF链接:https://pan.baidu.com/s/1JFtvBWgEGFWJq8pHafvIUg?pwd=6666 
提取码:6666

https://github.com/InternLM/Tutorial/blob/camp2/lmdeploy/README.md

一、大模型部署背景

RAG范式开发大模型

Xtuner微调大模型

LMDeploy部署大模型

  •         服务端:CPU、GPU/TPU/NPU,多卡,集群
  • 移动端/边缘:机器人、手机

1、计算量巨大

2、内存开销巨大

 3、访存瓶颈和动态请求:batchsize访问

 二、大模型部署方法

1、模型剪枝(Pruning):移除模型中不必要或者多余组件

  • 非结构化剪枝:SparseGPT,LoRAPrune,Wanda(将低于阈值的参数置零)
  • 结构化剪枝:LLM-Pruner(一次性移除连接或分层整组权重)

2、知识蒸馏(Knowledge Distillation,KD):模型压缩,引导轻量化的学生模型

  • 上下文学习(ICL):ICL distillation
  • 思维链(CoT):MT-COT,Fine-tune-CoT等
  • 指令跟随(IF):LaMini-LM

3、量化(Quantization):浮点数转换为整数或者其他离散形式,访储降低。

  • 量化感知训练(QAT) LLM-QAT:
  • 量化感知微调(QAF) PEQA[,QLORA:
  • 训练后量化(PTQ) LLM.int8,AWQ:

三、LMDeploy

涵盖了 LLM 任务的全套轻量化、部署和服务解决方案,

  • 模型高效推理:lmdeploy chat -h。LLaMa 结构模型的支持(CUDA算子实现)、continuous batch推理模式(请求数量长度不确定)和可扩展的 KV 缓存管理器(不使用的从显存放到内存)。
  • 模型量化压缩:lmdeploy lite -h。KV8量化(INT8),W4A16量化(AWQ)  (INT4)。
  • 服务化部署:lmdeploy serve -h。HTTP API服务

 四、动手实践:安装、部署、量化

1、创建conda环境

conda create -n lmdeploy -y python=3.10

2、安装LMDeploy 

激活虚拟环境

conda activate lmdeploy

安装Imdeploy

pip install lmdeploy[all]==0.3.0

 

3.LMDeploy模型对话(chat)

3.1 Huggingface与TurboMind

HuggingFace:深度学习模型和数据集的在线托管社区,托管模型采用HF格式。modelscope(阿里)、openxlab(上海AI Lab)。

TurboMind:LMDeploy团队开发的LLM推理的高效推理引擎。LLaMa 结构模型的支持,continuous batch 推理模式和可扩展的 KV 缓存管理器。推理HF格式的模型时,会首先自动将HF格式模型转换为TurboMind格式的模型。

  • TurboMind与LMDeploy的关系:LMDeploy是涵盖了LLM 任务全套轻量化、部署和服务解决方案的集成功能包,TurboMind是LMDeploy的一个推理引擎,是一个子模块。LMDeploy也可以使用pytorch作为推理引擎。
  • TurboMind与TurboMind模型的关系:TurboMind是推理引擎的名字,TurboMind模型是一种模型存储格式,TurboMind引擎只能推理TurboMind格式的模型。

3.2 下载模型.

常用的预训练模型

ls /root/share/new_models/Shanghai_AI_Laboratory/

cd ~

ln -s /root/share/new_models/Shanghai_AI_Laboratory/internlm2-chat-1_8b /root/ #软连接
# cp -r /root/share/new_models/Shanghai_AI_Laboratory/internlm2-chat-1_8b /root/ #拷贝
ls

 

 3.3 使用transformer运行模型

Transformer库是Huggingface社区推出的用于运行HF模型的官方库。

新建pipeline_transformer.py

touch /root/pipeline_transformer.py
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM

tokenizer = AutoTokenizer.from_pretrained("/root/internlm2-chat-1_8b", trust_remote_code=True)

# Set `torch_dtype=torch.float16` to load model in float16, otherwise it will be loaded as float32 and cause OOM Error.
model = AutoModelForCausalLM.from_pretrained("/root/internlm2-chat-1_8b", torch_dtype=torch.float16, trust_remote_code=True).cuda()
model = model.eval()

inp = "hello"
print("[INPUT]", inp)
response, history = model.chat(tokenizer, inp, history=[])
print("[OUTPUT]", response)

inp = "please provide three suggestions about time management"
print("[INPUT]", inp)
response, history = model.chat(tokenizer, inp, history=history)
print("[OUTPUT]", response)

运行python代码:

conda activate lmdeploy
python /root/pipeline_transformer.py

4.使用LMDeploy与模型对话

使用LMDeploy与模型进行对话的通用命令格式为:lmdeploy chat [HF格式模型路径/TurboMind格式模型路径]

lmdeploy chat /root/internlm2-chat-1_8b

lmdeploy chat -h

5.LMDeploy模型量化(lite)

量化是一种以参数或计算中间结果精度下降换空间节省(以及同时带来的性能提升)的策略。

  • 计算密集(compute-bound): 指推理过程中,绝大部分时间消耗在数值计算上;针对计算密集型场景,可以通过使用更快的硬件计算单元来提升计算速度。
  • 访存密集(memory-bound): 指推理过程中,绝大部分时间消耗在数据读取上;针对访存密集型场景,一般通过减少访存次数、提高计算访存比或降低访存量来优化。

LLM 模型由于 Decoder Only 架构的特性,实际推理时大多数的时间都消耗在了逐 Token 生成阶段(Decoding 阶段),是典型的访存密集型场景。

KV8量化:将逐 Token(Decoding)生成过程中的上下文 K 和 V 中间结果进行 INT8 量化(计算时再反量化),以降低生成过程中的显存占用。

W4A16量化:将 FP16 的模型权重量化为 INT4,Kernel 计算时,访存量直接降为 FP16 模型的 1/4,大幅降低了访存成本。

Weight Only: 是指仅量化权重,数值计算依然采用 FP16(需要将 INT4 权重反量化)。

6. 设置最大KV Cache缓存大小

KV Cache是一种缓存技术,通过存储键值对的形式来复用计算结果,以达到提高性能和降低内存消耗的目的。

在大规模训练和推理中,KV Cache可以显著减少重复计算量,从而提升模型的推理速度。

当显存空间不足时,也可以将KV Cache放在内存,通过缓存管理器控制将当前需要使用的数据放入显存。

模型在运行时的显存占用:模型参数本身占用的显存、KV Cache占用的显存,以及中间运算结果占用的显存。

--cache-max-entry-count参数,控制KV缓存占用剩余显存的最大比例。默认的比例为0.8

lmdeploy chat /root/internlm2-chat-1_8b

lmdeploy chat /root/internlm2-chat-1_8b --cache-max-entry-count 0.5

lmdeploy chat /root/internlm2-chat-1_8b --cache-max-entry-count 0.01

显存占用仅为4660MB,代价是会降低模型推理速度。

 7. 使用W4A16量化

LMDeploy使用AWQ算法,实现模型4bit权重量化。

推理引擎TurboMind提供了非常高效的4bit推理cuda kernel。它支持以下NVIDIA显卡:

  • 图灵架构(sm75):20系列、T4
  • 安培架构(sm80,sm86):30系列、A10、A16、A30、A100
  • Ada Lovelace架构(sm90):40 系列

安装依赖库

pip install einops==0.7.0

模型量化:HF模型被保存到internlm2-chat-1_8b-4bit目录

lmdeploy lite auto_awq \
   /root/internlm2-chat-1_8b \
  --calib-dataset 'ptb' \
  --calib-samples 128 \
  --calib-seqlen 1024 \
  --w-bits 4 \
  --w-group-size 128 \
  --work-dir /root/internlm2-chat-1_8b-4bit

使用Chat功能运行W4A16量化

lmdeploy chat /root/internlm2-chat-1_8b-4bit --model-format awq

KV Cache比例再次调为0.01

lmdeploy chat /root/internlm2-chat-1_8b-4bit --model-format awq --cache-max-entry-count 0.01

LMDeploy的lite功能

lmdeploy lite -h

 

8. LMDeploy服务(serve)

  • 模型推理/服务:主要提供模型本身的推理,一般来说可以和具体业务解耦,专注模型推理本身性能的优化。可以以模块、API等多种方式提供。
  • API Server:中间协议层,把后端推理/服务通过HTTP,gRPC或其他形式的接口,供前端调用。
  • Client:可以理解为前端,与用户交互的地方。通过通过网页端/命令行去调用API接口,获取模型推理/服务。

实际中并不是绝对的划分。

8.1. 启动API服务器

lmdeploy serve api_server \
    /root/internlm2-chat-1_8b \
    --model-format hf \
    --quant-policy 0 \
    --server-name 0.0.0.0 \
    --server-port 23333 \
    --tp 1

model-format、quant-policy这些参数是与第三章中量化推理模型一致的;

server-name和server-port表示API服务器的服务IP与服务端口;

tp参数表示并行数量(GPU数量)。

ssh -CNg -L 23333:127.0.0.1:23333 root@ssh.intern-ai.org.cn -p 43158

http://127.0.0.1:23333/

8.2 命令行客户端连接API服务器

lmdeploy serve api_client http://localhost:23333

 

 

8.3 网页客户端连接API服务器

lmdeploy serve gradio http://localhost:23333 \
    --server-name 0.0.0.0 \
    --server-port 6006

http://127.0.0.1:6006/

 

9.Python代码集成

9.1 Python代码集成运行1.8B模型

新建Python源代码文件pipeline.py

touch /root/pipeline.py
from lmdeploy import pipeline #引入lmdeploy的pipeline模块 \

pipe = pipeline('/root/internlm2-chat-1_8b')#从目录“./internlm2-chat-1_8b”加载HF模型 \
response = pipe(['Hi, pls intro yourself', '上海是'])#运行pipeline,这里采用了批处理的方式,用一个列表包含两个输入,lmdeploy同时推理两个输入,产生两个输出结果,结果返回给response \
print(response)#输出response

9.2 向TurboMind后端传递参数

创建TurbomindEngineConfig,向lmdeploy传递参数。

新建python文件pipeline_kv.py

touch /root/pipeline_kv.py

设置KV Cache占用比例 

from lmdeploy import pipeline, TurbomindEngineConfig

# 调低 k/v cache内存占比调整为总显存的 20%
backend_config = TurbomindEngineConfig(cache_max_entry_count=0.2)

pipe = pipeline('/root/internlm2-chat-1_8b',
                backend_config=backend_config)
response = pipe(['Hi, pls intro yourself', '上海是'])
print(response)

10.拓展部分

10.1 使用LMDeploy运行视觉多模态大模型llava

使用pipeline推理llava-v1.6-7b

安装llava依赖库。

pip install git+https://github.com/haotian-liu/LLaVA.git@4e2277a060da264c4f21b364c867cc622c945874

 新建一个python文件

touch /root/pipeline_llava.py
from lmdeploy.vl import load_image #引入用于载入图片的load_image函数
from lmdeploy import pipeline, TurbomindEngineConfig#引入了lmdeploy的pipeline模块


backend_config = TurbomindEngineConfig(session_len=8192) #图片分辨率较高时请调高session_len
# pipe = pipeline('liuhaotian/llava-v1.6-vicuna-7b', backend_config=backend_config) 非开发机运行此命令
pipe = pipeline('/share/new_models/liuhaotian/llava-v1.6-vicuna-7b', backend_config=backend_config)# 创建了pipeline实例 

image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/tests/data/tiger.jpeg')#从github下载了一张关于老虎的图片
response = pipe(('describe this image', image))#输入提示词“describe this image”,和图片,结果返回至response 
print(response)

 运行pipeline

python /root/pipeline_llava.py

Llava模型对中文支持性不好

通过Gradio来运行llava模型

touch /root/gradio_llava.py
import gradio as gr
from lmdeploy import pipeline, TurbomindEngineConfig


backend_config = TurbomindEngineConfig(session_len=8192) # 图片分辨率较高时请调高session_len
# pipe = pipeline('liuhaotian/llava-v1.6-vicuna-7b', backend_config=backend_config) 非开发机运行此命令
pipe = pipeline('/share/new_models/liuhaotian/llava-v1.6-vicuna-7b', backend_config=backend_config)

def model(image, text):
    if image is None:
        return [(text, "请上传一张图片。")]
    else:
        response = pipe((text, image)).text
        return [(text, response)]

demo = gr.Interface(fn=model, inputs=[gr.Image(type="pil"), gr.Textbox()], outputs=gr.Chatbot())
demo.launch()   
ssh -CNg -L 7860:127.0.0.1:7860 root@ssh.intern-ai.org.cn -p 43158

10.2 使用LMDeploy运行第三方大模型

 

ModelSize
Llama7B - 65B
Llama27B - 70B
InternLM7B - 20B
InternLM27B - 20B
InternLM-XComposer7B
QWen7B - 72B
QWen-VL7B
QWen1.50.5B - 72B
QWen1.5-MoEA2.7B
Baichuan7B - 13B
Baichuan27B - 13B
Code Llama7B - 34B
ChatGLM26B
Falcon7B - 180B
YI6B - 34B
Mistral7B
DeepSeek-MoE16B
DeepSeek-VL7B
Mixtral8x7B
Gemma2B-7B
Dbrx132B

10.3 定量比较LMDeploy与Transformer库的推理速度差异

速度测试脚本

新建python文件,命名为benchmark_transformer.py

touch /root/benchmark_transformer.py

 

import torch
import datetime
from transformers import AutoTokenizer, AutoModelForCausalLM

tokenizer = AutoTokenizer.from_pretrained("/root/internlm2-chat-1_8b", trust_remote_code=True)

# Set `torch_dtype=torch.float16` to load model in float16, otherwise it will be loaded as float32 and cause OOM Error.
model = AutoModelForCausalLM.from_pretrained("/root/internlm2-chat-1_8b", torch_dtype=torch.float16, trust_remote_code=True).cuda()
model = model.eval()

# warmup
inp = "hello"
for i in range(5):
    print("Warm up...[{}/5]".format(i+1))
    response, history = model.chat(tokenizer, inp, history=[])

# test speed
inp = "请介绍一下你自己。"
times = 10
total_words = 0
start_time = datetime.datetime.now()
for i in range(times):
    response, history = model.chat(tokenizer, inp, history=history)
    total_words += len(response)
end_time = datetime.datetime.now()

delta_time = end_time - start_time
delta_time = delta_time.seconds + delta_time.microseconds / 1000000.0
speed = total_words / delta_time
print("Speed: {:.3f} words/s".format(speed))
python benchmark_transformer.py

 

touch /root/benchmark_lmdeploy.py

 

import datetime
from lmdeploy import pipeline

pipe = pipeline('/root/internlm2-chat-1_8b')

# warmup
inp = "hello"
for i in range(5):
    print("Warm up...[{}/5]".format(i+1))
    response = pipe([inp])

# test speed
inp = "请介绍一下你自己。"
times = 10
total_words = 0
start_time = datetime.datetime.now()
for i in range(times):
    response = pipe([inp])
    total_words += len(response[0].text)
end_time = datetime.datetime.now()

delta_time = end_time - start_time
delta_time = delta_time.seconds + delta_time.microseconds / 1000000.0
speed = total_words / delta_time
print("Speed: {:.3f} words/s".format(speed))
python benchmark_lmdeploy.py

 

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

neo4j-5.11.0安装APOC插件or配置允许使用过程的权限

在已经安装好neo4j和jdk的情况下安装apoc组件,之前使用neo4j-community-4.4.30,可以找到配置apoc-4.4.0.22-all.jar,但是高版本neo4j对应没有apoc-X.X.X-all.jar。解决如下所示: 1.安装好JDK与neo4j 已经安装对应版本的JDK 17.0…

ABAP 第二代增强-采购申请子屏幕增强

文章目录 第二代增强-采购申请子屏幕增强需求实现过程创建项目运行效果客户屏幕的PBO全局变量获取数据更新数据运行效果查询底表修改数据 第二代增强-采购申请子屏幕增强 需求 实现过程 创建项目 运行效果 客户屏幕的PBO 全局变量 *&------------------------------------…

点击短信链接唤起Android App实战

一.概述 在很多业务场景中,需要点击短信链接跳转到App的指定页面。在Android系统中,想要实现这个功能,可以通过DeepLink或AppLink实现。二.方案 2.1 DeepLink 2.1.1 方案效果 DeepLink是Android系统最基础、最普遍、最广泛的外部唤起App的方式,不受系统版本限制。当用户…

《21天学通C++》(第二十章)STL映射类(map和multimap)

为什么需要map和multimap: 1.查找高效: 映射类允许通过键快速查找对应的值,这对于需要频繁查找特定元素的场景非常适合。 2.自动排序: 会自动根据键的顺序对元素进行排序 3.多级映射: 映射类可以嵌套使用,创…

typescript类型基础

typescript类型基础 枚举类型 enum Season {Spring,Summer,Fall,Winter }数值型枚举 enum Direction {Up,Down,Left,Right } const direction:Direction Direction.up每个数值型枚举成员都表示一个具体的数字,如果在定义一个枚举的时候没有设置枚举成员的值&…

5款智能写作工具,为大家一键生成原创文案

好的文案是能吸引眼球、传递信息,但对于许多人来说,写出好文案是一项耗时耗力的任务。而随着一些智能写作工具的出现,它为我们带来了很大的便利,无论是写作文案还是写作其它的内容,智能写作工具都能轻松帮助我们完成。…

感谢有你 | FISCO BCOS 2024年度第一季度贡献者榜单

挥别春天,FISCO BCOS开源社区迎来了2024年第一季度的共建成果。FISCO BCOS秉承对区块链技术的信仰,汇聚超过5000家企业机构、10万余名个人成员共建共治共享,持续打造更加活跃更加繁荣的开源联盟链生态圈。 开启夏日,我们见证了社…

从源头把控风险:集团多主体合规管理实战技巧分享

官.网地址:合合TextIn - 合合信息旗下OCR云服务产品 集团合规管理中,为了规避内外部利益冲突,需要对员工、供应商、经销商、客户、黑名单企业等多主体及其关联主体之间,进行多维度、多层级的关系挖掘与排查,避免利益…

MybatisPlus学习笔记

具体源码见: https://github.com/cug-lucifer/mp-demo/tree/master 快速入门 入门案例 需求: 新增用户功能根据id查询用户根据id批量查询用户根据id更新用户根据id删除用户 使用MybatisPlus的基本步骤 引入MybatisPlus依赖,代替Mybatis…

【题目】2023年全国职业院校技能大赛 GZ073 网络系统管理赛项赛题第4套B模块

2023年全国职业院校技能大赛 GZ073网络系统管理赛项 赛题第4套 模块B:服务部署 信息安全管理与评估 网络系统管理 网络搭建与应用 云计算 软件测试 移动应用开发等多个赛项技术支持 任务书,赛题,解析等资料,知识点培训服务 添加…

HackBar 新手使用教程(入门)

啥是Hackbar? Hackbar是一个Firefox 的插件,它的功能类似于地址栏,但是它里面的数据不受服务器的相应触发的重定向等其它变化的影响。 有网址的载入于访问,联合查询,各种编码,数据加密功能。 这个Hackbar可以帮助你在测试SQL注入,XSS漏洞和网站的安全性,主要是帮助…

单单单单单の刁队列

在数据结构的学习中,队列是一种常用的线性数据结构,它遵循先进先出(FIFO)的原则。而单调队列是队列的一种变体,它在特定条件下保证了队列中的元素具有某种单调性质,例如单调递增或单调递减。单调队列在处理…

[Collection与数据结构] Map与Set(一):二叉搜索树与Map,Set的使用

🌸个人主页:https://blog.csdn.net/2301_80050796?spm1000.2115.3001.5343 🏵️热门专栏:🍕 Collection与数据结构 (91平均质量分)https://blog.csdn.net/2301_80050796/category_12621348.html?spm1001.2014.3001.5482 🧀Java …

Baidu Comate智能编码助手

Baidu Comate智能编码助手 🎈1.Baidu Comate的简介🎈2.安装Baidu Comate🎈3.Baidu Comate实现功能🎈4.使用注释进行智能代码提示🎈5.结束语 🎈1.Baidu Comate的简介 根据官网的介绍,我们了解到B…

模型onnx转ncnn小记

前期准备 Netron 模型准备:onnx模型,这里使用模型face【det_10g.onnx】 大佬文档引用:手工优化ncnn模型结构 - 知乎 ncnn算子描述参考:ncnn 算子操作描述-CSDN博客 模型优化 安装 pip install onnx-simplifier 先把我要转的模型优化合…

全网最详细的Python自动化测试(unittest框架)

🔥 交流讨论:欢迎加入我们一起学习! 🔥 资源分享:耗时200小时精选的「软件测试」资料包 🔥 教程推荐:火遍全网的《软件测试》教程 📢欢迎点赞 👍 收藏 ⭐留言 &#x1…

Web 功能以及源码讲解

Web 功能以及语言讲解 培训、环境、资料、考证 公众号:Geek极安云科 网络安全群:624032112 网络系统管理群:223627079 网络建设与运维群:870959784 移动应用开发群:548238632 短视频制作群: 744125867极…

【6D位姿估计】FoundationPose 跑通demo 训练记录

前言 本文记录在FoundationPose中,跑通基于CAD模型为输入的demo,输出位姿信息,可视化结果。 然后分享NeRF物体重建部分的训练,以及RGBD图为输入的demo。 1、搭建环境 方案1:基于docker镜像(推荐&#xf…

电脑windows系统压缩解压软件-Bandizip

一、软件功能 Bandizip是一款功能强大的压缩和解压缩软件,具有快速拖放、高速压缩、多核心支持以及广泛的文件格式支持等特点。 Bandizip软件的功能主要包括: 1. 支持多种文件格式 Bandizip可以处理多种压缩文件格式,包括ZIP, 7Z, RAR, A…

Win10环境下yolov8快速配置与测试-详细

0.0 说明 参考黄家驹的Win10 环境下YOLO V8部署,遇到一些问题,并解决实现,记录如下: 斜线字体是原博客中的创作 0.1 参考链接 https://blog.csdn.net/m0_72734364/article/details/128865904 1 Windows10下yolov8 tensorrt模型加速部署 …
最新文章