# TGI（Text Generation Inference）

文本生成推理（TGI）是 HuggingFace 的生产级大型语言模型服务框架，旨在实现高吞吐和低延迟推理。它开箱即支持 Flash Attention 2、连续批处理、PagedAttention 和张量并行——使其成为在 CLORE.AI GPU 服务器上大规模部署大型语言模型的首选解决方案。

{% hint style="success" %}
所有示例都可以在通过以下方式租用的 GPU 服务器上运行 [CLORE.AI 市场](https://clore.ai/marketplace).
{% endhint %}

## 服务器要求

| 参数       | 最低要求                                         | 推荐配置               |
| -------- | -------------------------------------------- | ------------------ |
| 内存（RAM）  | 16 GB                                        | 32 GB+             |
| 显存（VRAM） | 8 GB                                         | 24 GB 以上           |
| 磁盘       | 50 GB                                        | 200 GB+            |
| GPU      | 任何 NVIDIA（用于 Flash Attention 的 Ampere 及更新架构） | A100、H100、RTX 4090 |

{% hint style="info" %}
Flash Attention 2 需要 Ampere 架构或更新（RTX 3000+、A100、H100）。对于较旧的 GPU，TGI 将自动回退到标准注意力实现。
{% endhint %}

## 在 CLORE.AI 上快速部署

**Docker 镜像：** `ghcr.io/huggingface/text-generation-inference:latest`

**端口：** `22/tcp`, `8080/http`

**环境变量：**

| 变量                 | 示例                                   | 描述                     |
| ------------------ | ------------------------------------ | ---------------------- |
| `MODEL_ID`         | `mistralai/Mistral-7B-Instruct-v0.3` | HuggingFace 模型 ID      |
| `HF_TOKEN`         | `hf_xxx...`                          | HuggingFace 令牌（用于受限模型） |
| `NUM_SHARD`        | `2`                                  | 用于张量并行的 GPU 数量         |
| `MAX_INPUT_LENGTH` | `4096`                               | 最大输入令牌数                |
| `MAX_TOTAL_TOKENS` | `8192`                               | 最大输入+输出令牌数             |
| `QUANTIZE`         | `bitsandbytes-nf4`                   | 量化方法                   |

## 逐步设置

### 1. 在 CLORE.AI 上租用 GPU 服务器

前往 [CLORE.AI 市场](https://clore.ai/marketplace) 并按以下条件筛选服务器：

* 7B 模型（全精度）需 VRAM ≥ 24 GB
* 7B 模型（4 位量化）需 VRAM ≥ 12 GB
* 70B 模型（全精度，单 GPU）需 VRAM ≥ 80 GB

### 2. 通过 SSH 连接

订单确认后，使用 CLORE.AI 仪表板中的 SSH 详情连接到您的服务器：

```bash
ssh -p <PORT> root@<SERVER_IP>
```

或者在您的 CLORE.AI 订单面板中使用 Web 终端。

### 3. 拉取 TGI Docker 镜像

```bash
docker pull ghcr.io/huggingface/text-generation-inference:latest
```

### 4. 使用模型启动 TGI

**基本启动（Mistral 7B）：**

```bash
docker run -d \
  --name tgi \
  --gpus all \
  --shm-size 1g \
  -p 8080:80 \
  -v /root/models:/data \
  -e MODEL_ID=mistralai/Mistral-7B-Instruct-v0.3 \
  ghcr.io/huggingface/text-generation-inference:latest \
  --model-id mistralai/Mistral-7B-Instruct-v0.3 \
  --max-input-length 4096 \
  --max-total-tokens 8192
```

**使用 HuggingFace 令牌（用于受限模型，如 Llama 3）：**

```bash
docker run -d \
  --name tgi \
  --gpus all \
  --shm-size 1g \
  -p 8080:80 \
  -v /root/models:/data \
  -e HUGGING_FACE_HUB_TOKEN=hf_your_token_here \
  ghcr.io/huggingface/text-generation-inference:latest \
  --model-id meta-llama/Meta-Llama-3-8B-Instruct \
  --max-input-length 8192 \
  --max-total-tokens 16384
```

**使用 4 位量化（用于较小 VRAM）：**

```bash
docker run -d \
  --name tgi \
  --gpus all \
  --shm-size 1g \
  -p 8080:80 \
  -v /root/models:/data \
  ghcr.io/huggingface/text-generation-inference:latest \
  --model-id mistralai/Mixtral-8x7B-Instruct-v0.1 \
  --quantize bitsandbytes-nf4 \
  --max-input-length 4096 \
  --max-total-tokens 8192
```

**多 GPU 张量并行（用于 70B 模型）：**

```bash
docker run -d \
  --name tgi \
  --gpus all \
  --shm-size 2g \
  -p 8080:80 \
  -v /root/models:/data \
  ghcr.io/huggingface/text-generation-inference:latest \
  --model-id meta-llama/Meta-Llama-3-70B-Instruct \
  --num-shard 2 \
  --max-input-length 8192 \
  --max-total-tokens 16384
```

### 5. 验证服务器是否在运行

```bash
# 查看日志
docker logs -f tgi

# 等待“Connected”消息，然后测试：
curl http://localhost:8080/health
```

预期响应： `{"status":"ok"}`

### 6. 通过 CLORE.AI HTTP 代理访问

在您的 CLORE.AI 订单面板中，您会看到您的 `http_pub` 端口 8080 的 URL。这样可以在不进行 SSH 隧道的情况下通过浏览器/API 访问：

```
https://<order-id>.clore.ai/
```

***

## 使用示例

### 示例 1：基本文本生成

```bash
curl http://localhost:8080/generate \
  -X POST \
  -H 'Content-Type: application/json' \
  -d '{
    "inputs": "法国的首都是什么？",
    "parameters": {
      "max_new_tokens": 100,
      "temperature": 0.7
    }
  }'
```

### 示例 2：聊天补全（兼容 OpenAI）

TGI 支持 OpenAI 聊天补全 API 格式：

```bash
curl http://localhost:8080/v1/chat/completions \
  -X POST \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "tgi",
    "messages": [
      {"role": "system", "content": "You are a helpful assistant."},
      {"role": "user", "content": "用简单的语言解释量子纠缠。"}
    ],
    "max_tokens": 512,
    "temperature": 0.8,
    "stream": false
  }'
```

### 示例 3：流式响应

```bash
curl http://localhost:8080/generate_stream \
  -X POST \
  -H 'Content-Type: application/json' \
  -d '{
    "inputs": "编写一个用于计算斐波那契数列的 Python 函数：",
    "parameters": {
      "max_new_tokens": 300,
      "temperature": 0.2
    }
  }' \
  --no-buffer
```

### 示例 4：Python 客户端

```python
from huggingface_hub import InferenceClient

# 用您的 CLORE.AI http_pub URL 替换
client = InferenceClient(model="http://localhost:8080")

# 简单生成
response = client.text_generation(
    "翻译成法语：Hello, how are you?",
    max_new_tokens=100,
    temperature=0.7,
)
print(response)

# 聊天
for token in client.chat_completion(
    messages=[{"role": "user", "content": "什么是机器学习？"}],
    max_tokens=200,
    stream=True,
):
    print(token.choices[0].delta.content, end="", flush=True)
```

### 示例 5：批量请求

```python
import requests

BASE_URL = "http://localhost:8080"  # 或者您的 CLORE.AI http_pub URL

prompts = [
    "用三句话概述法国大革命。",
    "写一首关于 GPU 计算的俳句。",
    "相比 C++，Rust 的主要优点是什么？",
]

results = []
for prompt in prompts:
    response = requests.post(
        f"{BASE_URL}/generate",
        json={"inputs": prompt, "parameters": {"max_new_tokens": 150}},
    )
    results.append(response.json()["generated_text"])

for prompt, result in zip(prompts, results):
    print(f"Prompt: {prompt}\nAnswer: {result}\n{'-'*50}")
```

***

## invokeai.yaml 配置文件

### 关键 CLI 参数

| 参数                          | 默认    | 描述                                    |
| --------------------------- | ----- | ------------------------------------- |
| `--model-id`                | 必填    | HuggingFace 模型 ID 或本地路径               |
| `--num-shard`               | 1     | GPU 分片数量（张量并行）                        |
| `--max-concurrent-requests` | 128   | 最大并发请求数                               |
| `--max-input-length`        | 1024  | 最大输入令牌长度                              |
| `--max-total-tokens`        | 2048  | 最大输入+输出令牌数                            |
| `--max-batch-total-tokens`  | auto  | 每个批次的最大令牌数                            |
| `--quantize`                | none  | 量化： `bitsandbytes-nf4`, `gptq`, `awq` |
| `--dtype`                   | auto  | `float16`, `bfloat16`                 |
| `--trust-remote-code`       | false | 允许自定义模型代码                             |
| `--port`                    | 80    | 服务器端口                                 |

### 使用本地模型

如果您已在本地下载模型：

```bash
docker run -d \
  --name tgi \
  --gpus all \
  --shm-size 1g \
  -p 8080:80 \
  -v /path/to/your/model:/model \
  ghcr.io/huggingface/text-generation-inference:latest \
  --model-id /model
```

### AWQ 量化（比 NF4 更快）

```bash
docker run -d \
  --name tgi \
  --gpus all \
  --shm-size 1g \
  -p 8080:80 \
  -v /root/models:/data \
  ghcr.io/huggingface/text-generation-inference:latest \
  --model-id casperhansen/mistral-7b-instruct-v0.2-awq \
  --quantize awq
```

***

## 1. 使用 SDXL-Turbo 或 SDXL-Lightning 以实现快速生成

### 1. 启用 Flash Attention 2

在 Ampere 及更新 GPU（RTX 3000+、A100、H100）上会自动启用 Flash Attention 2。无需额外配置。

### 2. 调整最大批次大小

在高吞吐场景下，增大批次大小：

```bash
--max-batch-total-tokens 32000 \
--max-waiting-tokens 20
```

### 3. 在 Ampere 及更新 GPU 上使用 bfloat16

```bash
--dtype bfloat16
```

这比 float16 更数值稳定，并且在现代 GPU 上性能相同。

### 4. 将模型预下载到持久存储

```bash
# 在服务器上，在启动 TGI 之前预下载
pip install huggingface_hub
python -c "
from huggingface_hub import snapshot_download
snapshot_download('mistralai/Mistral-7B-Instruct-v0.3', local_dir='/root/models/mistral-7b')
"
```

然后挂载本地路径以避免重启时重新下载。

### 5. GPU 内存管理

对于 RTX 3090/4090（24GB VRAM）：

```bash
# 7B 模型以 float16 完全适配
--max-total-tokens 8192

# 13B 模型需要量化
--quantize bitsandbytes-nf4
--max-total-tokens 4096
```

### 6. 预测式解码（Speculative Decoding）

对于较小模型，可作为草稿以加速生成：

```bash
--speculate 4  # 预测令牌数量
```

***

## 故障排除

### 解决方案：

```
错误：CUDA 内存不足。尝试分配 X GiB
```

**解决方案：** 减少 `--max-total-tokens` 或启用量化：

```bash
--quantize bitsandbytes-nf4
--max-total-tokens 4096
```

### 问题：模型下载很慢

**解决方案：** 使用 HuggingFace 镜像或预下载：

```bash
# 设置镜像
-e HF_ENDPOINT=https://hf-mirror.com
```

### 问题：通过 http\_pub 无法访问服务器

**解决方案：** 确保端口 8080 正确映射。TGI 在容器内部监听端口 80，但您将其映射到外部的 8080：

```bash
-p 8080:80  # 主机:容器
```

### 问题：需要 "trust\_remote\_code"

某些模型（例如 Falcon、Phi）需要自定义代码：

```bash
--trust-remote-code
```

### 问题：首次响应慢

第一次请求会触发模型加载到显存中。这是正常的。后续请求会很快。

```bash
# 检查加载进度
docker logs -f tgi | grep -E "Connected|Error|Loading"
```

### 问题：容器立即退出

```bash
# 检查错误
docker logs tgi

# 常见修复：增加共享内存
--shm-size 2g
```

***

## 文档

* [GitHub](https://github.com/huggingface/text-generation-inference)
* [文档](https://huggingface.co/docs/text-generation-inference)
* [Clore.ai GPU 建议](https://github.com/huggingface/text-generation-inference/pkgs/container/text-generation-inference)
* [支持的模型](https://huggingface.co/docs/text-generation-inference/supported_models)
* [CLORE.AI 市场](https://clore.ai/marketplace)

***

## Clore.ai 的 GPU 建议

| 在 Clore.ai 上的预估费用 | 开发/测试            | RTX 3090（24GB） |
| ----------------- | ---------------- | -------------- |
| \~$0.12/每 GPU/每小时 | 生产               | RTX 4090（24GB） |
| 生产（7B–13B）        | 大规模              | A100 80GB      |
| 大型模型（70B+）        | A100 80GB / H100 | Clore.ai       |

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