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 scipyfrom vllm import LLM, SamplingParamsfrom datasets import load_datasetimport timefrom tqdm import tqdmfrom 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() - startgenerated_text = outputs[0].outputs[0].textreturn generated_text, takengenerated_text = []time_taken = 0for sample in tqdm(prompts):text, taken = generate_with_time(sample)time_taken += takengenerated_text.append(text)# Tokenize the outputs and calculate the throughputtokenizer = AutoTokenizer.from_pretrained("microsoft/Phi-3-mini-4k-instruct")token = 1for sample in generated_text:tokens = tokenizer(sample)tok = len(tokens.input_ids)token += tokprint(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