LLM推理引擎怎么选?TensorRT vs vLLM vs LMDeploy vs MLC-LLM

本文涉及的产品
检索分析服务 Elasticsearch 版,2核4GB开发者规格 1个月
实时计算 Flink 版,5000CU*H 3个月
智能开放搜索 OpenSearch行业算法版,1GB 20LCU 1个月
简介: 有很多个框架和包可以优化LLM推理和服务,所以在本文中我将整理一些常用的推理引擎并进行比较。

LLM擅长文本生成应用程序,如聊天和代码完成模型,能够高度理解和流畅。但是它们的大尺寸也给推理带来了挑战。有很多个框架和包可以优化LLM推理和服务,所以在本文中我将整理一些常用的推理引擎并进行比较。

TensorRT-LLM

TensorRT-LLM是NV发布的一个推理引擎。llm被编译成TensorRT后与triton服务器一起部署并支持多GPU-多节点推理和FP8。

我们将比较HF模型、tensorrt模型和TensorRT-INT8模型(量化)的执行时间、ROUGE分数、延迟和吞吐量。

我这里在Linux上安装Nvidia-container-toolkit,初始化Git LFS(用于下载HF Models),并下载所需的软件包如下:

 !curl -fsSL https://nvidia.github.io/libnvidia-container/gpgkey | sudo gpg --dearmor -o /usr/share/keyrings/nvidia-container-toolkit-keyring.gpg \
   && curl -s -L https://nvidia.github.io/libnvidia-container/stable/deb/nvidia-container-toolkit.list | \
     sed 's#deb https://#deb [signed-by=/usr/share/keyrings/nvidia-container-toolkit-keyring.gpg] https://#g' | \
     sudo tee /etc/apt/sources.list.d/nvidia-container-toolkit.list
 !apt-get update
 !git clone https://github.com/NVIDIA/TensorRT-LLM/
 !apt-get update && apt-get -y install python3.10 python3-pip openmpi-bin libopenmpi-dev
 !pip3 install tensorrt_llm -U --pre --extra-index-url https://pypi.nvidia.com
 !pip install -r TensorRT-LLM/examples/phi/requirements.txt
 !pip install flash_attn pytest
 !curl -s https://packagecloud.io/install/repositories/github/git-lfs/script.deb.sh | bash
 !apt-get install git-lfs

然后下载模型权重

 PHI_PATH="TensorRT-LLM/examples/phi"
 !rm -rf $PHI_PATH/7B
 !mkdir -p $PHI_PATH/7B && git clone https://huggingface.co/microsoft/Phi-3-small-128k-instruct $PHI_PATH/7B

使用下面的命令将模型转换为TensorRT-LLM格式,并从检查点构建TensorRT-LLM。

 !python3 $PHI_PATH/convert_checkpoint.py --model_dir $PHI_PATH/7B/ \
                 --dtype bfloat16 \
                 --output_dir $PHI_PATH/7B/trt_ckpt/bf16/1-gpu/
 # Build TensorRT-LLM model from checkpoint
 !trtllm-build --checkpoint_dir $PHI_PATH/7B/trt_ckpt/bf16/1-gpu/ \
                 --gemm_plugin bfloat16 \
                 --output_dir $PHI_PATH/7B/trt_engines/bf16/1-gpu/

我们还测试INT8的量化应用

 !python3 $PHI_PATH/convert_checkpoint.py --model_dir $PHI_PATH/7B \
                 --dtype bfloat16 \
                 --use_weight_only \
                 --output_dir $PHI_PATH/7B/trt_ckpt/int8_weight_only/1-gpu/
 !trtllm-build --checkpoint_dir $PHI_PATH/7B/trt_ckpt/int8_weight_only/1-gpu/ \
                 --gemm_plugin bfloat16 \
                 --output_dir $PHI_PATH/7B/trt_engines/int8_weight_only/1-gpu/

然后就可以在摘要任务上测试phi3和两个TensorRT模型

 %%capture phi_hf_results
 # Huggingface
 !time python3 $PHI_PATH/../summarize.py --test_hf \
                        --hf_model_dir $PHI_PATH/7B/ \
                        --data_type bf16 \
                        --engine_dir $PHI_PATH/7B/trt_engines/bf16/1-gpu/
 %%capture phi_trt_results
 # TensorRT-LLM
 !time python3 $PHI_PATH/../summarize.py --test_trt_llm \
                        --hf_model_dir $PHI_PATH/7B/ \
                        --data_type bf16 \
                        --engine_dir $PHI_PATH/7B/trt_engines/bf16/1-gpu/
 %%capture phi_int8_results
 # TensorRT-LLM (INT8)
 !time python3 $PHI_PATH/../summarize.py --test_trt_llm \
                        --hf_model_dir $PHI_PATH/7B/ \
                        --data_type bf16 \
                        --engine_dir $PHI_PATH/7B/trt_engines/int8_weight_only/1-gpu/

得到结果后就可以解析输出并绘制图表,比较所有模型的执行时间、ROUGE分数、延迟和吞吐量。

可以看到速度提高了不少,所有结果我们最后一起总结。

vLLM

vLLM提供LLM推理和服务,具有SOTA吞吐量,分页注意力,连续批处理,量化(GPTQ, AWQ, FP8)的支持和优化的CUDA内核。

我们首先安装相应的包

 !pip install -q vllm
 !git clone https://github.com/vllm-project/vllm.git
 !pip install -q datasets
 !pip install transformers scipy
 from vllm import LLM, SamplingParams
 from datasets import load_dataset
 import time
 from tqdm import tqdm
 from transformers import AutoTokenizer

然后加载模型并在数据集的一小部分上生成它的输出。

 dataset = load_dataset("akemiH/MedQA-Reason", split="train").select(range(10))
 prompts = []
 for sample in dataset:
     prompts.append(sample)
 sampling_params = SamplingParams(max_tokens=524)
 llm = LLM(model="microsoft/Phi-3-mini-4k-instruct", trust_remote_code=True)
 def generate_with_time(prompt):
     start = time.time()
     outputs = llm.generate(prompt, sampling_params)
     taken = time.time() - start
     generated_text = outputs[0].outputs[0].text
     return generated_text, taken
 generated_text = []
 time_taken = 0
 for sample in tqdm(prompts):
     text, taken = generate_with_time(sample)
     time_taken += taken
     generated_text.append(text)

 # Tokenize the outputs and calculate the throughput
 tokenizer = AutoTokenizer.from_pretrained("microsoft/Phi-3-mini-4k-instruct")
 token = 1
 for sample in generated_text:
     tokens = tokenizer(sample)
     tok = len(tokens.input_ids)
     token += tok
 print(token)
 print("tok/s", token // time_taken)

通过vLLM在ShareGPT数据集上对模型的性能进行基准测试

 !wget https://huggingface.co/datasets/anon8231489123/ShareGPT_Vicuna_unfiltered/resolve/main/ShareGPT_V3_unfiltered_cleaned_split.json
 %cd vllm
 !python benchmarks/benchmark_throughput.py --backend vllm --dataset ../ShareGPT_V3_unfiltered_cleaned_split.json --model microsoft/Phi-3-mini-4k-instruct --tokenizer microsoft/Phi-3-mini-4k-instruct --num-prompts=1000

LMDeploy

LMDeploy允许压缩、部署和服务llm,同时提供高效的推理(持久批处理、阻塞KV缓存、动态分裂和融合、张量并行、高性能CUDA内核)、有效的量化(4位推理性能比FP16高2.4倍)。跨多台机器和GPU部署多模型服务。此外,它还允许分析令牌延迟和吞吐量、请求吞吐量、API服务器和triton推理服务器性能。

!pip install -q lmdeploy
!pip install nest_asyncio
import nest_asyncio
nest_asyncio.apply()
!git clone --depth=1 https://github.com/InternLM/lmdeploy
%cd lmdeploy/benchmark

LMdeploy还开发了两个推理引擎TurboMind和PyTorch。我们来使用PyTorch引擎。

!python3 profile_generation.py microsoft/Phi-3-mini-128k-instruct --backend pytorch

它在多个回合中对引擎进行配置,并报告每个回合的令牌延迟和吞吐量。

MLC-LLM

MLC-LLM提供了一个高性能的部署和推理引擎,称为MLCEngine。

conda activate your-environment
python -m pip install --pre -U -f https://mlc.ai/wheels mlc-llm-nightly-cu121 mlc-ai-nightly-cu121
conda env remove -n mlc-chat-venv
conda create -n mlc-chat-venv -c conda-forge \
    "cmake>=3.24" \
    rust \
    git \
    python=3.11
conda activate mlc-chat-venv
git clone --recursive https://github.com/mlc-ai/mlc-llm.git && cd mlc-llm/
mkdir -p build && cd build
python ../cmake/gen_cmake_config.py
cmake .. && cmake --build . --parallel $(nproc) && cd ..
set(USE_FLASHINFER ON)
conda activate your-own-env
cd mlc-llm/python
pip install -e .

我们需要将模型权重转换为MLC格式。通过Git LFS下载HF模型,然后转换权重。

mlc_llm convert_weight ./dist/models/Phi-3-small-128k-instruct/ \
    --quantization q0f16 \
    --model-type "phi3" \
    -o ./dist/Phi-3-small-128k-instruct-q0f16-MLC

现在将MLC格式模型加载到MLC引擎中

from mlc_llm import MLCEngine
# Create engine
model = "HF://mlc-ai/Phi-3-mini-128k-instruct-q0f16-MLC"
engine = MLCEngine(model)

# Now let’s calculate throughput
import time
from transformers import AutoTokenizer
start = time.time()
response = engine.chat.completions.create(
    messages=[{"role": "user", "content": "What is the Machine Learning?"}],
    model=model,
    stream=False,
)
taken = time.time() - start
tokenizer = AutoTokenizer.from_pretrained("microsoft/Phi-3-mini-128k-instruct")
print("tok/s", 82 // taken)

总结

TensorRT INT8模型在推理速度上优于HF模型和TensorRT模型,而TensorRT模型在总结任务上表现更好,ROUGE得分最高。可以看到这几个推理引擎都要比使用HF模型的速度快2倍左右,这是因为HF使用的是Python和Pytorch,也没有进行任何的优化。而者4个引擎在推理速度上相差不大,差距在5%-10%左右,这是因为目前这几个引擎都是用了优化的技术,区别只是代码实现的方式不同会产生一些差距,所以在实际使用时,我们只要选择一个兼容性好(或者符合你正在使用的大语言模型)的框架就可以了。

最后这里有个列表 TGI我不熟,就没测,不过结果应该差不多

https://avoid.overfit.cn/post/33f6420c91e74c0eb8d6737cb9471e27

作者:Zain ul Abideen

相关实践学习
部署Stable Diffusion玩转AI绘画(GPU云服务器)
本实验通过在ECS上从零开始部署Stable Diffusion来进行AI绘画创作,开启AIGC盲盒。
目录
相关文章
|
6天前
|
人工智能 Prometheus 监控
使用NVIDIA NIM在阿里云ACK中加速LLM推理
介绍在阿里云ACK集群上结合AI套件能力快速部署NVIDIA NIM模型推理服务,同时提供全面的监控指标和实现弹性伸缩。
|
1月前
|
人工智能 算法
等不来OpenAI的Q*,华为诺亚探索LLM推理的秘密武器MindStar先来了
【7月更文挑战第13天】华为诺亚方舟实验室推出MindStar,一种增强LLM推理能力的搜索框架。MindStar通过PRM奖励模型和Beam/Levin Search策略选择最佳推理路径,提升开源模型如LLaMA-2-13B、Mistral-7B的性能,与GPT-3.5等闭源模型媲美,但成本更低。尽管推理成本高和需预训练PRM,MindStar为LLM推理研究开辟新途径。[论文链接](https://arxiv.org/pdf/2405.16265v4)
42 9
|
1月前
|
算法 API 数据中心
魔搭社区利用 NVIDIA TensorRT-LLM 加速开源大语言模型推理
魔搭社区于 2022 年 11 月初创建,首次在业界提出了 “模型即服务”( MaaS, Model as a Service)的理念。
|
1月前
LLM用于时序预测真的不行,连推理能力都没用到
【7月更文挑战第15天】LLM在时序预测上的应用遇挫:研究显示,大型语言模型在多个实验中未显优势,甚至被简单注意力层替代时效果不变或更好。预训练知识未能有效利用,处理时序依赖性不足,且在小样本学习中未见提升。[链接:](https://arxiv.org/pdf/2406.16964)**
34 2
|
1月前
|
测试技术
谷歌DeepMind全新ToT基准:全面评估LLM时间推理能力
【7月更文挑战第10天】DeepMind的ToT基准测试了大型语言模型的时间推理能力,分为ToT-Semantic(合成数据,评估时间逻辑理解)和ToT-Arithmetic(真实数据,检查时间计算)。研究使用Claude-3-Sonnet、GPT-4和Gemini 1.5 Pro进行评估,发现模型在时间逻辑理解上表现各异,而时间计算上均较强。 Gemini 1.5 Pro在复杂问题上表现出色,而GPT-4在数学相关问题上较弱。[[1](https://arxiv.org/pdf/2406.09170)]
25 1
|
1月前
|
人工智能 安全 物联网
2024年6月后2周重要的大语言模型论文总结:LLM进展、微调、推理和对齐
本文总结了2024年6月后两周发表的一些最重要的大语言模型论文。这些论文涵盖了塑造下一代语言模型的各种主题,从模型优化和缩放到推理、基准测试和增强性能。
61 0
|
2月前
|
机器学习/深度学习 人工智能 测试技术
两句话,让LLM逻辑推理瞬间崩溃!最新爱丽丝梦游仙境曝出GPT、Claude等重大缺陷
【6月更文挑战第17天】新论文揭示GPT和Claude等LLM在逻辑推理上的重大缺陷。通过《爱丽丝梦游仙境》场景,研究显示这些模型在处理简单常识问题时给出错误答案并过度自信。即使面对明显逻辑矛盾,模型仍坚持错误推理,暴露了现有评估方法的不足。[链接:https://arxiv.org/abs/2406.02061]
320 1
|
2月前
|
人工智能 自然语言处理 安全
GPT-4欺骗人类高达99.16%惊人率!PNAS重磅研究曝出,LLM推理越强欺骗值越高
【6月更文挑战第17天】PNAS研究显示,GPT-4等大型语言模型(LLMs)在欺骗人类方面达到99.16%成功率,推理能力增强使欺骗风险升高。这一发现引发伦理讨论,强调需强化监管与伦理规范,同时考虑AI在社会中的安全应用。论文链接:[https://www.pnas.org/doi/full/10.1073/pnas.2317967121](https://www.pnas.org/doi/full/10.1073/pnas.2317967121)**
203 1
|
6天前
|
存储 人工智能 JSON
|
3天前
|
人工智能 PyTorch 算法框架/工具
Xinference实战指南:全面解析LLM大模型部署流程,携手Dify打造高效AI应用实践案例,加速AI项目落地进程
【8月更文挑战第6天】Xinference实战指南:全面解析LLM大模型部署流程,携手Dify打造高效AI应用实践案例,加速AI项目落地进程
Xinference实战指南:全面解析LLM大模型部署流程,携手Dify打造高效AI应用实践案例,加速AI项目落地进程