InternLM实战营第二期笔记·⑤「LMDeploy 量化部署 LLM 实践」

1.LMDeploy环境部署

InternStudio上提供了快速创建conda环境的方法。打开命令行终端,创建一个名为lmdeploy的环境:

studio-conda -t lmdeploy -o pytorch-2.1.2

成功后显示:

可以运行如下命令查看开发机的共享目录中常用的预训练模型:

ls /root/share/new_models/Shanghai_AI_Laboratory/

显示如下,每一个文件夹都对应一个预训练模型。

使用Transformer库运行模型

新建pipeline_transformer.py

touch /root/pipeline_transformer.py 

将以下内容复制粘贴进入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)

Ctrl+S键保存(Mac用户按Command+S)。

回到终端,激活conda环境。

conda activate lmdeploy

运行python代码:

python /root/pipeline_transformer.py

显示结果:

使用LMDeploy与模型对话

首先激活创建好的conda环境:

conda activate lmdeploy

执行如下命令运行下载的1.8B模型:

lmdeploy chat /root/internlm2-chat-1_8b

然后可以成功进行对话:

LMDeploy模型量化(lite)

调整--cache-max-entry-count参数。首先保持不加该参数(默认0.8),运行1.8B模型。

lmdeploy chat /root/internlm2-chat-1_8b

与模型对话,查看右上角资源监视器中的显存占用情况。

此时显存占用为7856MB。

改变--cache-max-entry-count参数,设为0.5。

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

与模型对话,再次查看右上角资源监视器中的显存占用情况。

显存占用明显降低,变为6608M。

--cache-max-entry-count参数设置为0.01,约等于禁止KV Cache占用显存。

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

使用W4A16量化

pip install einops==0.7.0
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

将KV Cache比例再次调为0.01,查看显存占用情况。

4.LMDeploy服务

最近更新

  1. TCP协议是安全的吗?

    2024-04-25 00:16:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-25 00:16:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-25 00:16:01       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-25 00:16:01       20 阅读

热门阅读

  1. C++中输入输出速度的优化

    2024-04-25 00:16:01       12 阅读
  2. Chisel3 入门 (1)

    2024-04-25 00:16:01       10 阅读
  3. int和byte数组相互转换详解

    2024-04-25 00:16:01       14 阅读
  4. 测试开发-celery框架详解

    2024-04-25 00:16:01       14 阅读
  5. n-gram模型

    2024-04-25 00:16:01       11 阅读
  6. Unity用非常简单的例子解释抽象

    2024-04-25 00:16:01       14 阅读
  7. 如何在 C# 中选择使用抽象类或接口?

    2024-04-25 00:16:01       13 阅读
  8. 【Python】如何在Ubuntu上设置Python脚本开机自启

    2024-04-25 00:16:01       13 阅读
  9. 深入理解汇编:平栈、CALL和RET指令详解

    2024-04-25 00:16:01       12 阅读