# TensorRT-LLM

> **通过 NVIDIA TensorRT 优化实现的最大 LLM 推理吞吐量 — 通过 Triton Inference Server 部署**

TensorRT-LLM 是 NVIDIA 的开源库，用于在 NVIDIA GPU 上优化大型语言模型的推理。它通过内核融合、量化（INT4、INT8、FP8）、飞行中批处理和分页 KV 缓存提供最新水平的性能。与 Triton Inference Server 结合，可获得生产级别的服务基础设施。

**GitHub：** [NVIDIA/TensorRT-LLM](https://github.com/NVIDIA/TensorRT-LLM) — 10K+ ⭐

***

## 为什么选择 TensorRT-LLM？

| 功能           | vLLM    | TensorRT-LLM |
| ------------ | ------- | ------------ |
| 吞吐量          | 适合照片级写实 | 同类最佳         |
| 延迟           | 快速      | 适合照片级写实      |
| INT4/INT8 量化 | 部分支持    | 原生           |
| 支持 FP8       | 有限      | 完整（Full）     |
| 多 GPU 张量并行   | 是       | 是            |
| 设置复杂度        | 低       | 中等-高         |

{% hint style="success" %}
**TensorRT-LLM 通常比标准 HuggingFace transformers 推理提供 2–4 倍更高的吞吐量** 在批量服务场景下，比 vLLM 提供约 30–50% 更好的吞吐量。
{% endhint %}

***

## 先决条件

* 具有 GPU 租用的 Clore.ai 帐户
* **具有安培（Ampere）架构或更新架构的 NVIDIA GPU** （RTX 3090、A100、RTX 4090、H100）
* 基本的 Linux 和 Docker 知识
* 为所选模型准备足够的显存（VRAM）

***

## 按模型划分的显存需求

| 模型            | FP16  | INT8 | INT4 |
| ------------- | ----- | ---- | ---- |
| Llama-3.1 8B  | 16GB  | 8GB  | 4GB  |
| Llama-3.1 70B | 140GB | 70GB | 35GB |
| Mistral 7B    | 14GB  | 7GB  | 4GB  |
| Mixtral 8x7B  | 90GB  | 45GB | 24GB |
| Qwen2.5 72B   | 144GB | 72GB | 36GB |

***

## 第 1 步 — 在 Clore.ai 上选择您的 GPU

1. 登录到 [clore.ai](https://clore.ai) → **市场**
2. **对于单 GPU 服务（7B–13B 模型）：** RTX 4090 24GB 或 RTX 3090 24GB
3. **对于大型模型（70B+）：** 多块 A100 80GB 或 H100

{% hint style="info" %}
**多 GPU 策略：**

* 2x A100 80GB → Llama 3.1 70B（FP16）或 Qwen2.5 72B
* 4x A100 80GB → Llama 3.1 405B（INT8）
* 在 Clore.ai 市场中选择列出多 GPU 的服务器
  {% endhint %}

***

## 第 2 步 — 使用 TRT-LLM 后端 部署 Triton Inference Server

**Docker 镜像：**

```
nvcr.io/nvidia/tritonserver:24.01-trtllm-python-py3
```

{% hint style="warning" %}
使用 `-trtllm-python-py3` 变体 — 其中预装了 TensorRT-LLM 后端。标签对应 NVIDIA 容器发布（24.01 = 2024 年 1 月）。检查 [NGC](https://catalog.ngc.nvidia.com/orgs/nvidia/containers/tritonserver/tags) 以获取最新标签。
{% endhint %}

**暴露端口：**

```
22
8000
```

**环境变量：**

```
NVIDIA_VISIBLE_DEVICES=all
NVIDIA_DRIVER_CAPABILITIES=compute,utility
TRANSFORMERS_CACHE=/workspace/hf_cache
HF_HOME=/workspace/hf_cache
```

**卷/磁盘：** 建议至少 100GB

***

## 第 3 步 — 连接并验证安装

```bash
ssh root@<server-ip> -p <ssh-port>

# 检查 GPU
nvidia-smi

# 检查 TensorRT 版本
python3 -c "import tensorrt_llm; print(tensorrt_llm.__version__)"

# 检查 Triton 是否可用
tritonserver --version
```

***

## 第 4 步 — 下载并准备模型

我们将以 Llama 3.1 8B 为示例。根据所选模型调整路径。

### 安装 HuggingFace CLI

```bash
pip install huggingface_hub
huggingface-cli login
# 提示时输入您的 HuggingFace 令牌
```

### 下载模型权重

```bash
mkdir -p /workspace/models/llama-3.1-8b
huggingface-cli download \
    meta-llama/Llama-3.1-8B-Instruct \
    --local-dir /workspace/models/llama-3.1-8b \
    --local-dir-use-symlinks False

# 或使用 snapshot_download
python3 << 'EOF'
from huggingface_hub import snapshot_download
snapshot_download(
    repo_id="meta-llama/Llama-3.1-8B-Instruct",
    local_dir="/workspace/models/llama-3.1-8b",
    local_dir_use_symlinks=False
)
EOF
```

***

## 第 5 步 — 构建 TensorRT 引擎

这是关键步骤 — 将模型编译为优化后的 TensorRT 引擎。

### FP16 引擎（最佳质量）

```bash
cd /workspace

# 将 HuggingFace 权重转换为 TRT-LLM 格式
python3 /usr/local/lib/python3.10/dist-packages/tensorrt_llm/examples/llama/convert_checkpoint.py \
    --model_dir /workspace/models/llama-3.1-8b \
    --output_dir /workspace/trt_checkpoints/llama-3.1-8b-fp16 \
    --dtype float16 \
    --tp_size 1

# 构建 TensorRT 引擎
trtllm-build \
    --checkpoint_dir /workspace/trt_checkpoints/llama-3.1-8b-fp16 \
    --output_dir /workspace/trt_engines/llama-3.1-8b-fp16 \
    --gemm_plugin float16 \
    --max_batch_size 32 \
    --max_input_len 4096 \
    --max_seq_len 8192 \
    --max_num_tokens 16384 \
    --use_paged_context_fmha enable
```

### INT8 SmoothQuant 引擎（更高吞吐量）

```bash
# 使用 SmoothQuant 进行转换量化
python3 /usr/local/lib/python3.10/dist-packages/tensorrt_llm/examples/llama/convert_checkpoint.py \
    --model_dir /workspace/models/llama-3.1-8b \
    --output_dir /workspace/trt_checkpoints/llama-3.1-8b-int8 \
    --dtype float16 \
    --smoothquant 0.5 \
    --per_channel \
    --per_token

trtllm-build \
    --checkpoint_dir /workspace/trt_checkpoints/llama-3.1-8b-int8 \
    --output_dir /workspace/trt_engines/llama-3.1-8b-int8 \
    --gemm_plugin float16 \
    --smoothquant_plugin float16 \
    --max_batch_size 64 \
    --max_input_len 4096 \
    --max_seq_len 8192
```

### INT4 AWQ 引擎（最大吞吐量 / 最小内存占用）

```bash
# 安装 auto-gptq 以进行量化
pip install autoawq

# 量化为 INT4 AWQ
python3 << 'EOF'
from awq import AutoAWQForCausalLM
from transformers import AutoTokenizer

model_path = "/workspace/models/llama-3.1-8b"
quant_path = "/workspace/models/llama-3.1-8b-awq-int4"

model = AutoAWQForCausalLM.from_pretrained(model_path)
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)

quant_config = {
    "zero_point": True,
    "q_group_size": 128,
    "w_bit": 4,
    "version": "GEMM"
}
model.quantize(tokenizer, quant_config=quant_config)
model.save_quantized(quant_path)
tokenizer.save_pretrained(quant_path)
EOF

# 将 AWQ 转换为 TRT-LLM
python3 /usr/local/lib/python3.10/dist-packages/tensorrt_llm/examples/llama/convert_checkpoint.py \
    --model_dir /workspace/models/llama-3.1-8b-awq-int4 \
    --output_dir /workspace/trt_checkpoints/llama-3.1-8b-int4 \
    --dtype float16 \
    --quant_ckpt_path /workspace/models/llama-3.1-8b-awq-int4 \
    --use_weight_only \
    --weight_only_precision int4_awq \
    --per_group

trtllm-build \
    --checkpoint_dir /workspace/trt_checkpoints/llama-3.1-8b-int4 \
    --output_dir /workspace/trt_engines/llama-3.1-8b-int4 \
    --gemm_plugin float16 \
    --max_batch_size 128 \
    --max_input_len 4096 \
    --max_seq_len 8192
```

{% hint style="info" %}
**引擎构建时间：** 取决于 GPU 与模型大小，需 10–30 分钟。这是一次性操作 — 构建完成后，引擎可以在数秒内加载。
{% endhint %}

***

## 第 6 步 — 使用 TRT-LLM Python API 快速测试

在设置 Triton 之前，先验证引擎是否可用：

```bash
python3 << 'EOF'
import tensorrt_llm
from tensorrt_llm.runtime import ModelRunner
from transformers import AutoTokenizer

engine_dir = "/workspace/trt_engines/llama-3.1-8b-fp16"
tokenizer_dir = "/workspace/models/llama-3.1-8b"

tokenizer = AutoTokenizer.from_pretrained(tokenizer_dir)
runner = ModelRunner.from_dir(
    engine_dir=engine_dir,
    rank=0
)

prompt = "What is the capital of France?"
input_ids = tokenizer.encode(prompt, return_tensors="pt")

output = runner.generate(
    batch_input_ids=[input_ids[0].tolist()],
    max_new_tokens=200,
    temperature=0.7,
    top_p=0.9
)

output_ids = output[0][0][len(input_ids[0]):]
response = tokenizer.decode(output_ids, skip_special_tokens=True)
print(f"Response: {response}")
EOF
```

***

## 第 7 步 — 设置 Triton Inference Server

### 创建模型仓库结构

```bash
mkdir -p /workspace/triton_model_repo/llama/1

# 创建模型配置
cat > /workspace/triton_model_repo/llama/config.pbtxt << 'EOF'
backend: "tensorrtllm"
name: "llama"
max_batch_size: 64
model_transaction_policy {
  decoupled: true
}

dynamic_batching {
  preferred_batch_size: [1, 2, 4, 8, 16, 32, 64]
  max_queue_delay_microseconds: 1000
}

input [
  {
    name: "input_ids"
    data_type: TYPE_INT32
    dims: [-1]
  },
  {
    name: "input_lengths"
    data_type: TYPE_INT32
    dims: [1]
    reshape: { shape: [] }
  },
  {
    name: "request_output_len"
    data_type: TYPE_INT32
    dims: [1]
    reshape: { shape: [] }
  },
  {
    name: "temperature"
    data_type: TYPE_FP32
    dims: [1]
    reshape: { shape: [] }
    optional: true
  }
]

output [
  {
    name: "output_ids"
    data_type: TYPE_INT32
    dims: [-1, -1]
  },
  {
    name: "sequence_length"
    data_type: TYPE_INT32
    dims: [1]
  }
]

instance_group [
  {
    count: 1
    kind: KIND_GPU
    gpus: [0]
  }
]

parameters: {
  key: "gpt_model_type"
  value: { string_value: "inflight_fused_batching" }
}

parameters: {
  key: "gpt_model_path"
  value: { string_value: "/workspace/trt_engines/llama-3.1-8b-fp16" }
}

parameters: {
  key: "max_tokens_in_paged_kv_cache"
  value: { string_value: "8192" }
}

parameters: {
  key: "batch_scheduler_policy"
  value: { string_value: "guaranteed_no_evict" }
}
EOF
```

### 创建引擎符号链接

```bash
ln -s /workspace/trt_engines/llama-3.1-8b-fp16 \
    /workspace/triton_model_repo/llama/1/
```

### 启动 Triton 服务器

```bash
tritonserver \
    --model-repository=/workspace/triton_model_repo \
    --http-port=8000 \
    --grpc-port=8001 \
    --metrics-port=8002 \
    --log-verbose=0 &

# 等待服务器启动
sleep 30

# 检查服务器健康状况
curl -s http://localhost:8000/v2/health/ready
```

***

## 第 8 步 — 查询 API

### 兼容 OpenAI 的客户端

```python
import requests
import json

def generate(prompt: str, max_tokens: int = 200) -> str:
    url = "http://localhost:8000/v2/models/llama/generate"
    
    "batch": {
        "text_input": prompt,
        "parameters": {
            "max_tokens": max_tokens,
            "temperature": 0.7,
            "top_p": 0.9
        }
    }
    
    response = requests.post(url, json=payload)
    result = response.json()
    return result.get("text_output", "")

# 测试
print(generate("以简单术语解释量子计算："))
```

### 基准吞吐量测试

```bash
# 安装 tritonclient
pip install tritonclient[all]

# 运行性能基准测试
perf_analyzer \
    -m llama \
    -u localhost:8001 \
    --protocol grpc \
    --input-data /workspace/sample_inputs.json \
    --concurrency-range 1:32:2 \
    --measurement-interval 10000 \
    --shape input_ids:512 \
    --shape input_lengths:1 \
    --shape request_output_len:1
```

***

## 第 9 步 — 添加兼容 OpenAI 的 API 封装

为更易集成，添加 FastAPI 封装：

```bash
pip install fastapi uvicorn tritonclient[all]

cat > /workspace/openai_server.py << 'EOF'
from fastapi import FastAPI
from pydantic import BaseModel
import tritonclient.http as httpclient
import numpy as np
from transformers import AutoTokenizer

app = FastAPI()
tokenizer = AutoTokenizer.from_pretrained("/workspace/models/llama-3.1-8b")
client = httpclient.InferenceServerClient("localhost:8000")

class ChatRequest(BaseModel):
    model: str = "llama"
    messages: list
    max_tokens: int = 512
    temperature: float = 0.7

@app.post("/v1/chat/completions")
async def chat(req: ChatRequest):
    prompt = tokenizer.apply_chat_template(
        req.messages,
        tokenize=False,
        add_generation_prompt=True
    )
    
    input_ids = tokenizer.encode(prompt)
    
    inputs = [
        httpclient.InferInput("input_ids", [len(input_ids)], "INT32"),
        httpclient.InferInput("input_lengths", [1], "INT32"),
        httpclient.InferInput("request_output_len", [1], "INT32"),
    ]
    inputs[0].set_data_from_numpy(np.array(input_ids, dtype=np.int32))
    inputs[1].set_data_from_numpy(np.array([len(input_ids)], dtype=np.int32))
    inputs[2].set_data_from_numpy(np.array([req.max_tokens], dtype=np.int32))
    
    result = client.infer("llama", inputs)
    output_ids = result.as_numpy("output_ids")[0][len(input_ids):]
    text = tokenizer.decode(output_ids, skip_special_tokens=True)
    
    return {
        "choices": [{"message": {"role": "assistant", "content": text}}]
    }

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8080)
EOF

python3 /workspace/openai_server.py &
```

***

## 故障排除

### 引擎构建 OOM（内存不足）

```bash
# 减小 max_batch_size 和 max_num_tokens
trtllm-build \
    --checkpoint_dir /workspace/trt_checkpoints/llama-3.1-8b-fp16 \
    --output_dir /workspace/trt_engines/llama-3.1-8b-fp16 \
    --gemm_plugin float16 \
    --max_batch_size 8 \        # 从 32 减小
    --max_input_len 2048 \      # 从 4096 减小
    --max_seq_len 4096          # 从 8192 减小
```

### Triton 服务器未启动

```bash
# 检查日志
cat /workspace/triton.log

# 验证引擎文件是否存在
ls -la /workspace/trt_engines/llama-3.1-8b-fp16/

# 检查 GPU 内存
nvidia-smi
```

### 低吞吐量

```bash
# 启用飞行中批处理并增加并发量
# 根据可用显存调整 max_tokens_in_paged_kv_cache
```

***

## Clore.ai GPU 上的性能基准

| 模型            | GPU         | 量化       | 吞吐量（tokens/秒） |
| ------------- | ----------- | -------- | ------------- |
| Llama 3.1 8B  | RTX 4090    | FP16     | \~3,500       |
| Llama 3.1 8B  | RTX 4090    | INT4 AWQ | \~6,200       |
| Llama 3.1 70B | 2x A100 80G | FP16     | \~1,800       |
| Mixtral 8x7B  | 2x RTX 4090 | INT8     | \~2,400       |

***

## 附加资源

* [TensorRT-LLM GitHub](https://github.com/NVIDIA/TensorRT-LLM)
* [Triton 推理服务器](https://github.com/triton-inference-server/server)
* [NGC 容器注册表](https://catalog.ngc.nvidia.com/)
* [TRT-LLM 文档](https://nvidia.github.io/TensorRT-LLM/)
* [AWQ 量化](https://github.com/mit-han-lab/llm-awq)

***

*当吞吐量和延迟至关重要时，Clore.ai 上的 TensorRT-LLM 是用于生产 LLM 服务的最佳选择。对于更简单的部署，可以考虑 vLLM 指南。*

***

## Clore.ai 的 GPU 建议

| 在 Clore.ai 上的预估费用 | 开发/测试             | RTX 3090（24GB） |
| ----------------- | ----------------- | -------------- |
| \~$0.12/每 GPU/每小时 | 生产                | RTX 4090（24GB） |
| 生产级推理             | 大规模               | A100 80GB      |
| 大型模型（70B+）        | 💡 本指南中的所有示例均可部署在 | Clore.ai       |

> GPU 服务器上。浏览可用 GPU 并按小时租用 — 无需承诺，提供完整的 root 访问权限。 [Clore.ai](https://clore.ai/marketplace) GPU 服务器。浏览可用 GPU 并按小时租用 — 无需承诺，提供完整的 root 访问权限。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.clore.ai/guides/guides_v2-zh/gpu-devops/tensorrt-llm.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
