> 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-ru/gpu-devops/tensorrt-llm.md).

# TensorRT-LLM

> **Максимальная пропускная способность инференса LLM с оптимизацией NVIDIA TensorRT — развернуто через Triton Inference Server**

TensorRT-LLM — это библиотека NVIDIA с открытым исходным кодом для оптимизации инференса больших языковых моделей на GPU NVIDIA. Она обеспечивает передовую производительность благодаря объединению ядер, квантизации (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                           | Ограниченная | Полный          |
| Тензорный параллелизм на нескольких GPU | Да           | Да              |
| Сложность настройки                     | Низкая       | Средне-высокая  |

{% hint style="success" %}
**TensorRT-LLM обычно обеспечивает пропускную способность в 2–4 раза выше** по сравнению со стандартным инференсом transformers HuggingFace и на 30–50% более высокую пропускную способность, чем vLLM, в сценариях пакетного обслуживания.
{% endhint %}

***

## Предварительные требования

* Аккаунт Clore.ai с арендой GPU
* **GPU NVIDIA с архитектурой Ampere или новее** (RTX 3090, A100, RTX 4090, H100)
* Базовые знания Linux и Docker
* Достаточный объём VRAM для выбранной модели

***

## Требования к VRAM по моделям

| Модель        | FP16   | INT8  | INT4  |
| ------------- | ------ | ----- | ----- |
| Llama-3.1 8B  | 16GB   | 8 ГБ  | 4 ГБ  |
| Llama-3.1 70B | 140GB  | 70 ГБ | 35 ГБ |
| Mistral 7B    | 14 ГБ  | 7 ГБ  | 4 ГБ  |
| Mixtral 8x7B  | 90GB   | 45GB  | 24 ГБ |
| Qwen2.5 72B   | 144 ГБ | 72 ГБ | 36 ГБ |

***

## Шаг 1 — Выберите свой GPU на Clore.ai

1. Войдите в [маркетплейсе clore.ai](https://clore.ai) → **Маркетплейс**
2. **Для обслуживания на одном GPU (модели 7B–13B):** RTX 4090 24 ГБ или RTX 3090 24 ГБ
3. **Для больших моделей (70B+):** Несколько A100 80 ГБ или H100

{% hint style="info" %}
**Стратегия для нескольких GPU:**

* 2x A100 80 ГБ → Llama 3.1 70B в FP16 или Qwen2.5 72B
* 4x A100 80 ГБ → Llama 3.1 405B в INT8
* Выберите серверы с несколькими GPU, указанными на маркетплейсе Clore.ai
  {% endhint %}

***

## Шаг 2 — Разверните Triton Inference Server с бэкендом TRT-LLM

**Docker-образ:**

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

{% hint style="warning" %}
Используйте `-trtllm-python-py3` вариант — он включает предустановленный бэкенд TensorRT-LLM. Тег соответствует релизу контейнера NVIDIA (24.01 = январь 2024). Проверьте [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
```

**Том/диск:** Рекомендуется минимум 100 ГБ

***

## Шаг 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" %}
**Время сборки движка:** 10–30 минут в зависимости от GPU и размера модели. Это операция, выполняемая один раз — после сборки движок загружается за секунды.
{% 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}")
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 Server

```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"
    
    payload = {
        "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 — Добавьте обёртку API, совместимую с OpenAI

Для более простой интеграции добавьте обёртку 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 &
```

***

## Устранение неполадок

### Недостаточно памяти при сборке движка

```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 Server не запускается

```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 в зависимости от доступной VRAM
```

***

## Бенчмарки производительности на GPU Clore.ai

| Модель        | GPU         | Квантование | Пропускная способность (токенов/с) |
| ------------- | ----------- | ----------- | ---------------------------------- |
| 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                            |

***

## Дополнительные ресурсы

* [GitHub TensorRT-LLM](https://github.com/NVIDIA/TensorRT-LLM)
* [Triton Inference Server](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)

***

*TensorRT-LLM на Clore.ai — оптимальный выбор для продакшн-обслуживания LLM, где критически важны пропускная способность и задержка. Для более простых конфигураций рассмотрите руководство по vLLM.*

***

## Рекомендации по GPU для Clore.ai

{% hint style="warning" %}
**Многопроцессорные конфигурации с GPU класса 80GB не представлены на маркетплейсе Clore.ai.** Самые крупные доступные сейчас машины — это 4× RTX PRO 6000 Blackwell (по 96GB, всего 380GB) и 8–11× RTX 5090 (по 32GB). Ёмкость A100 / H200 / B200 продаётся как [голое железо](https://clore.ai/bare-metal) по запросу. Проверьте [Цены и доступность GPU](/guides/guides_v2-ru/nachalo-raboty/pricing.md) перед выбором размера развёртывания.
{% endhint %}

| Сценарий использования  | Рекомендуемый GPU | Оценочная стоимость на Clore.ai             |
| ----------------------- | ----------------- | ------------------------------------------- |
| Разработка/тестирование | RTX 3090 (24 ГБ)  | $0.07–0.21/гпу/ч                            |
| Промышленный инференс   | RTX 4090 (24 ГБ)  | $0.14–0.42/гпу/ч                            |
| Крупные модели (70B+)   | A100 80 ГБ        | [голое железо](https://clore.ai/bare-metal) |

> 💡 Все примеры в этом руководстве можно развернуть на [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-ru/gpu-devops/tensorrt-llm.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.
