> For the complete documentation index, see [llms.txt](https://docs.clore.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.clore.ai/guides/guides_v2-zh/yu-yan-mo-xing/tgi.md).

# TGI（文本生成推理）

在 Clore.ai GPU 上运行 HuggingFace Text Generation Inference（TGI）用于生产级 LLM 服务

Text Generation Inference（TGI）是 HuggingFace 的生产级 LLM 服务框架，专为高吞吐量和低延迟推理而设计。它原生支持 Flash Attention 2、连续批处理、PagedAttention 和张量并行——使其成为在 CLORE.AI GPU 服务器上大规模部署大语言模型的首选方案。

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

## 服务器要求

| 参数  | 最低                                         | 推荐                 |
| --- | ------------------------------------------ | ------------------ |
| 内存  | 16 GB                                      | 32 GB+             |
| 显存  | 8 GB                                       | 24 GB+             |
| 磁盘  | 50 GB                                      | 200 GB+            |
| GPU | 任意 NVIDIA（用于 Flash Attention 的 Ampere 及以上） | A100、H100、RTX 4090 |

{% hint style="info" %}
Flash Attention 2 需要 Ampere 架构或更新的 GPU（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`                               | 最大输入 token 数           |
| `MAX_TOTAL_TOKENS` | `8192`                               | 输入 + 输出的最大 token 数     |
| `QUANTIZE`         | `bitsandbytes-nf4`                   | 量化方法                   |

## 逐步设置

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

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

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

### 2. 通过 SSH 连接

订单确认后，使用 CLORE.AI 控制面板中的 SSH 详情连接到你的服务器：

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

或者使用 CLORE.AI 订单面板中的 Web Terminal。

### 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(
    "Translate to French: Hello, how are you?",
    max_new_tokens=100,
    temperature=0.7,
)
打印(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 = [
    "用 3 句话概括法国大革命。",
    "写一首关于 GPU 计算的俳句。",
    "Rust 相比 C++ 的主要优势是什么？",
]

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}")
```

***

## 配置

### 关键 CLI 参数

| 参数                          | 默认值   | 描述                                    |
| --------------------------- | ----- | ------------------------------------- |
| `--model-id`                | 必需    | HuggingFace 模型 ID 或本地路径               |
| `--num-shard`               | 1     | GPU 分片数量（张量并行）                        |
| `--max-concurrent-requests` | 128   | 最大并发请求数                               |
| `--max-input-length`        | 1024  | 最大输入 token 长度                         |
| `--max-total-tokens`        | 2048  | 输入 + 输出的最大 token 数                    |
| `--max-batch-total-tokens`  | 自动    | 每个批次的最大 token 数                       |
| `--quantize`                | 无     | 量化： `bitsandbytes-nf4`, `gptq`, `awq` |
| `--dtype`                   | 自动    | `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. 启用 Flash Attention 2

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

### 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. 推测解码

为了让较小模型作为草稿模型时生成更快：

```bash
--speculate 4  # 推测 token 数量
```

***

## 故障排查

### 问题：“CUDA out of memory”

```
错误：CUDA out of memory. Tried to allocate 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 is required”

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

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

### 问题：首次响应很慢

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

```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)
* [Docker Hub / GHCR](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 推荐

| 使用场景         | 推荐 GPU           | Clore.ai 预计成本     |
| ------------ | ---------------- | ----------------- |
| 开发/测试        | RTX 3090（24GB）   | $0.07–0.21/gpu/hr |
| 生产环境（7B–13B） | RTX 4090（24GB）   | $0.14–0.42/gpu/hr |
| 大模型（70B+）    | A100 80GB / H100 | 约 $1.04/每 GPU/小时  |

> 💡 本指南中的所有示例都可以部署在 [Clore.ai](https://clore.ai/marketplace) GPU 服务器上。浏览可用 GPU 并按小时租用——无需承诺，拥有完整 root 访问权限。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://docs.clore.ai/guides/guides_v2-zh/yu-yan-mo-xing/tgi.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
