TensorRT-LLM 大模型推理加速实战指南
1. 简介
TensorRT-LLM 是由 NVIDIA 发布的高性能推理库,专为大型语言模型(LLM)设计。它提供了易于使用的 Python API,允许用户定义 LLM 并构建包含最先进优化的 TensorRT 引擎,从而在 NVIDIA GPU 上实现高效的推理执行。相比通用推理框架,TensorRT-LLM 针对 Transformer 架构进行了深度优化,支持量化、连续批处理等高级特性。
2. 环境准备与安装
2.1 基础依赖
建议直接使用 Docker 环境进行部署,以避免本地环境配置冲突。首先需要安装 NVIDIA TensorRT。
sudo dpkg -i nv-tensorrt-local-repo-ubuntu2204-8.6.1-cuda-12.0_1.0-1_amd64.deb
sudo cp /var/nv-tensorrt-local-repo-ubuntu2204-8.6.1-cuda-12.0/nv-tensorrt-local-42B2FC56-keyring.gpg /usr/share/keyrings/
sudo apt-get update
sudo apt-get install tensorrt
2.2 安装 TensorRT-LLM
通过 pip 安装预发布版本:
pip3 install tensorrt_llm -U --pre --extra-index-url https://pypi.nvidia.com
python3 -c "import tensorrt_llm"
注意:TensorRT-LLM 与 TGI(Text Generation Inference)软件版本可能存在冲突,请确保环境隔离。
2.3 Triton Inference Server
为了在生产环境中部署,通常结合 Triton Inference Server 使用。
docker pull nvcr.io/nvidia/tritonserver:24.01-trtllm-python-py3
3. 构建 TensorRT 引擎
要为现有模型创建 TensorRT 引擎,主要包含三个步骤:下载预训练权重、构建完全优化的模型引擎、部署引擎。
由于目前某些特定模型(如 Qwen2)可能尚未完全支持,示例中使用 Qwen-7B 模型。如果模型不在仓库 examples 目录下支持列表中,需要自行编写代码实现模型转化功能。
3.1 构建命令详解
python build.py --hf_model_dir /home/chuan/models/qwen/Qwen-7B-Chat-Int4 \
--quant_ckpt_path /home/chuan/models/qwen/Qwen-7B-Chat-Int4 \
--dtype float16 \
--remove_input_padding \
--use_gpt_attention_plugin float16 \
--enable_context_fmha \
--use_gemm_plugin float16 \
--use_weight_only \
--weight_only_precision int4_gptq \
--per_group \
--world_size 1 \
--tp_size 1 \
--output_dir /home/chuan/models/qwen/Qwen-7B-Chat-Int4/trt_engines/int4-gptq/1-gpu
参数说明:
--hf_model_dir: HuggingFace 模型目录路径。--quant_ckpt_path: 量化检查点路径。


