> 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-de/sprachmodelle/tgi.md).

# TGI (Text Generation Inference)

Text Generation Inference (TGI) ist HuggingFaces produktionsreifes LLM-Serving-Framework, entwickelt für hohen Durchsatz und niedrige Latenz bei Inferenz. Es unterstützt Flash Attention 2, kontinuierliches Batching, PagedAttention und Tensor-Parallelismus Out-of-the-Box — und ist damit die bevorzugte Lösung zum Bereitstellen großer Sprachmodelle in großem Maßstab auf CLORE.AI GPU-Servern.

{% hint style="success" %}
Alle Beispiele können auf GPU-Servern ausgeführt werden, die über [CLORE.AI Marketplace](https://clore.ai/marketplace).
{% endhint %}

## Serveranforderungen

| Parameter  | Minimum                                   | Empfohlen            |
| ---------- | ----------------------------------------- | -------------------- |
| RAM        | 16 GB                                     | 32 GB+               |
| VRAM       | 8 GB                                      | 24 GB+               |
| Festplatte | 50 GB                                     | 200 GB+              |
| GPU        | Jede NVIDIA (Ampere+ für Flash Attention) | A100, H100, RTX 4090 |

{% hint style="info" %}
Flash Attention 2 erfordert die Ampere-Architektur oder neuer (RTX 3000+, A100, H100). Für ältere GPUs fällt TGI automatisch auf die Standard-Attention zurück.
{% endhint %}

## Schnelle Bereitstellung auf CLORE.AI

**Docker-Image:** `ghcr.io/huggingface/text-generation-inference:latest`

**Ports:** `22/tcp`, `8080/http`

**Umgebungsvariablen:**

| Variable           | Beispiel                             | Beschreibung                               |
| ------------------ | ------------------------------------ | ------------------------------------------ |
| `MODEL_ID`         | `mistralai/Mistral-7B-Instruct-v0.3` | HuggingFace Modell-ID                      |
| `HF_TOKEN`         | `hf_xxx...`                          | HuggingFace-Token (für geschützte Modelle) |
| `NUM_SHARD`        | `2`                                  | Anzahl der GPUs für Tensor-Parallelismus   |
| `MAX_INPUT_LENGTH` | `4096`                               | Maximale Eingabe-Token                     |
| `MAX_TOTAL_TOKENS` | `8192`                               | Maximale Eingabe- + Ausgabe-Token          |
| `QUANTIZE`         | `bitsandbytes-nf4`                   | Quantisierungsmethode                      |

## Schritt-für-Schritt-Einrichtung

### 1. Mieten Sie einen GPU-Server auf CLORE.AI

Gehe zu [CLORE.AI Marketplace](https://clore.ai/marketplace) und filtere Server nach:

* VRAM ≥ 24 GB für 7B-Modelle (volle Präzision)
* VRAM ≥ 12 GB für 7B-Modelle (4-Bit-Quantisierung)
* VRAM ≥ 80 GB für 70B-Modelle (volle Präzision, einzelne GPU)

### 2. Verbindung per SSH

Nachdem Ihre Bestellung bestätigt wurde, verbinden Sie sich mit Ihrem Server mithilfe der SSH-Daten aus Ihrem CLORE.AI-Dashboard:

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

Oder verwenden Sie das Web-Terminal aus Ihrem CLORE.AI-Bestellpanel.

### 3. Ziehen Sie das TGI-Docker-Image

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

### 4. Starten Sie TGI mit einem Modell

**Einfacher Start (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
```

**Mit HuggingFace-Token (für geschützte Modelle wie 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
```

**Mit 4-Bit-Quantisierung (für geringeren 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
```

**Multi-GPU Tensor-Parallelismus (für 70B-Modelle):**

```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. Überprüfen, ob der Server läuft

```bash
# Logs überprüfen
docker logs -f tgi

# Warten auf die Meldung "Connected", dann testen:
curl http://localhost:8080/health
```

Erwartete Antwort: `{"status":"ok"}`

### 6. Zugriff über CLORE.AI HTTP-Proxy

In Ihrem CLORE.AI-Bestellpanel sehen Sie Ihre `http_pub` URL für Port 8080. Dies ermöglicht Browser-/API-Zugriff ohne SSH-Tunneling:

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

***

## Beispielanwendungen

### Beispiel 1: Einfache Textgenerierung

```bash
curl http://localhost:8080/generate \\
  -X POST \
  -H 'Content-Type: application/json' \
  -d '{
    "inputs": "Was ist die Hauptstadt von Frankreich?",
    "parameters": {
      "max_new_tokens": 100,
      "temperature": 0.7
    }
  }'
```

### Beispiel 2: Chat-Completions (OpenAI-kompatibel)

TGI unterstützt das OpenAI-Format für Chat-Completions:

```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": "Erkläre Quantenverschränkung in einfachen Worten."}
    ],
    "max_tokens": 512,
    "temperature": 0.8,
    "stream": false
  }'
```

### Beispiel 3: Streaming-Antwort

```bash
curl http://localhost:8080/generate_stream \\
  -X POST \
  -H 'Content-Type: application/json' \
  -d '{
    "inputs": "Schreibe eine Python-Funktion zur Berechnung der Fibonacci-Zahlen:",
    "parameters": {
      "max_new_tokens": 300,
      "temperature": 0.2
    }
  }' \
  --no-buffer
```

### Beispiel 4: Python-Client

```python
from huggingface_hub import InferenceClient

# Ersetzen Sie durch Ihre CLORE.AI http_pub-URL
client = InferenceClient(model="http://localhost:8080")

# Einfache Generierung
response = client.text_generation(
    "Ins Französische übersetzen: Hallo, wie geht es dir?",
    max_new_tokens=100,
    temperature=0.7,
)
print(response)

# Chat
for token in client.chat_completion(
    messages=[{"role": "user", "content": "Was ist maschinelles Lernen?"}],
    max_tokens=200,
    stream=True,
):
    print(token.choices[0].delta.content, end="", flush=True)
```

### Beispiel 5: Batch-Anfragen

```python
import requests

BASE_URL = "http://localhost:8080"  # oder Ihre CLORE.AI http_pub-URL

prompts = [
    "Fasse die Französische Revolution in 3 Sätzen zusammen.",
    "Schreibe ein Haiku über GPU-Computing.",
    "Was sind die wichtigsten Vorteile von Rust gegenüber 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}")
```

***

## Konfiguration

### Wichtige CLI-Parameter

| Parameter                   | Standard     | Beschreibung                                     |
| --------------------------- | ------------ | ------------------------------------------------ |
| `--model-id`                | erforderlich | HuggingFace-Modell-ID oder lokaler Pfad          |
| `--num-shard`               | 1            | Anzahl der GPU-Shards (Tensor-Parallelismus)     |
| `--max-concurrent-requests` | 128          | Maximale gleichzeitige Anfragen                  |
| `--max-input-length`        | 1024         | Maximale Eingabe-Token-Länge                     |
| `--max-total-tokens`        | 2048         | Maximale Eingabe- + Ausgabe-Token                |
| `--max-batch-total-tokens`  | auto         | Maximale Token pro Batch                         |
| `--quantize`                | keine        | Quantisierung: `bitsandbytes-nf4`, `gptq`, `awq` |
| `--dtype`                   | auto         | `float16`, `bfloat16`                            |
| `--trust-remote-code`       | false        | Erlaube benutzerdefinierten Modellcode           |
| `--port`                    | 80           | Serverport                                       |

### Verwendung eines lokalen Modells

Wenn Sie ein Modell lokal heruntergeladen haben:

```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-Quantisierung (Schneller als 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
```

***

## Leistungs-Tipps

### 1. Flash Attention 2 aktivieren

Flash Attention 2 ist auf Ampere+-GPUs (RTX 3000+, A100, H100) automatisch aktiviert. Keine zusätzliche Konfiguration erforderlich.

### 2. Maximalen Batch-Size anpassen

Für Szenarien mit hohem Durchsatz erhöhen Sie die Batch-Größe:

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

### 3. Verwenden Sie bfloat16 auf Ampere+-GPUs

```bash
--dtype bfloat16
```

Dies ist numerisch stabiler als float16 und liefert auf modernen GPUs dieselbe Leistung.

### 4. Modelle vorab auf persistenter Speicherung herunterladen

```bash
# Auf dem Server vor dem Start von TGI vorab herunterladen
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')
"
```

Binden Sie dann den lokalen Pfad ein, um erneutes Herunterladen bei Neustarts zu vermeiden.

### 5. GPU-Speichermanagement

Für RTX 3090/4090 (24GB VRAM):

```bash
# 7B-Modell in float16 passt perfekt
--max-total-tokens 8192

# 13B-Modell benötigt Quantisierung
--quantize bitsandbytes-nf4
--max-total-tokens 4096
```

### 6. Spekulatives Decoding

Für schnellere Generierung mit kleineren Modellen als Entwurf:

```bash
--speculate 4  # Anzahl spekulativer Tokens
```

***

## Fehlerbehebung

### Problem: "CUDA out of memory"

```
Fehler: CUDA out of memory. Versuch, X GiB zuzuweisen
```

**Lösung:** Reduzieren Sie `--max-total-tokens` oder aktivieren Sie Quantisierung:

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

### Problem: Modell-Download ist langsam

**Lösung:** Verwenden Sie einen HuggingFace-Mirror oder laden Sie vorab herunter:

```bash
# Mirror setzen
-e HF_ENDPOINT=https://hf-mirror.com
```

### Problem: Server über http\_pub nicht erreichbar

**Lösung:** Stellen Sie sicher, dass Port 8080 korrekt gemappt ist. TGI hört intern auf Port 80, aber Sie mappen ihn extern auf 8080:

```bash
-p 8080:80  # host:container
```

### Problem: "trust\_remote\_code ist erforderlich"

Einige Modelle (z. B. Falcon, Phi) erfordern benutzerdefinierten Code:

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

### Problem: Langsame erste Antwort

Die erste Anfrage löst das Laden des Modells in den VRAM aus. Das ist normal. Nachfolgende Anfragen sind schnell.

```bash
# Ladefortschritt prüfen
docker logs -f tgi | grep -E "Connected|Error|Loading"
```

### Problem: Container beendet sich sofort

```bash
# Auf Fehler prüfen
docker logs tgi

# Häufige Lösung: geteilten Speicher vergrößern
--shm-size 2g
```

***

## Links

* [GitHub](https://github.com/huggingface/text-generation-inference)
* [Dokumentation](https://huggingface.co/docs/text-generation-inference)
* [Docker Hub / GHCR](https://github.com/huggingface/text-generation-inference/pkgs/container/text-generation-inference)
* [Unterstützte Modelle](https://huggingface.co/docs/text-generation-inference/supported_models)
* [CLORE.AI Marketplace](https://clore.ai/marketplace)

***

## Clore.ai GPU-Empfehlungen

| Anwendungsfall       | Empfohlene GPU   | Geschätzte Kosten auf Clore.ai |
| -------------------- | ---------------- | ------------------------------ |
| Entwicklung/Tests    | RTX 3090 (24GB)  | \~$0.12/gpu/hr                 |
| Produktion (7B–13B)  | RTX 4090 (24GB)  | \~$0.70/gpu/hr                 |
| Große Modelle (70B+) | A100 80GB / H100 | \~$1.20/gpu/hr                 |

> 💡 Alle Beispiele in diesem Leitfaden können bereitgestellt werden auf [Clore.ai](https://clore.ai/marketplace) GPU-Servern. Durchsuchen Sie verfügbare GPUs und mieten Sie stundenweise — keine Verpflichtungen, voller Root-Zugriff.


---

# 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:

```
GET https://docs.clore.ai/guides/guides_v2-de/sprachmodelle/tgi.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.
