> 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)

Führe HuggingFace Text Generation Inference (TGI) für den produktiven LLM-Betrieb auf Clore.ai-GPUs aus

Text Generation Inference (TGI) ist HuggingFaces produktionsreifes Framework für das Bereitstellen von LLMs, ausgelegt auf hohen Durchsatz und geringe Latenz bei der Inferenz. Es unterstützt Flash Attention 2, kontinuierliches Batching, PagedAttention und Tensor-Parallelismus standardmäßig – und ist damit die bevorzugte Lösung für die Skalierung großer Sprachmodelle auf CLORE.AI-GPU-Servern.

{% hint style="success" %}
Alle Beispiele können auf GPU-Servern ausgeführt werden, die gemietet wurden über [CLORE.AI-Marktplatz](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        | Beliebige NVIDIA (Ampere+ für Flash Attention) | A100, H100, RTX 4090 |

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

## Schnellbereitstellung 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 Eingabetokens                     |
| `MAX_TOTAL_TOKENS` | `8192`                               | Maximale Eingabe- + Ausgabetokens          |
| `QUANTIZE`         | `bitsandbytes-nf4`                   | Quantisierungsmethode                      |

## Schritt-für-Schritt-Einrichtung

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

Gehe zu [CLORE.AI-Marktplatz](https://clore.ai/marketplace) und Server filtern nach:

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

### 2. Per SSH verbinden

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. TGI-Docker-Image herunterladen

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

### 4. TGI mit einem Modell starten

**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 weniger 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
```

**Tensor-Parallelismus über mehrere GPUs (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. Prüfen, ob der Server läuft

```bash
# Protokolle prüfen
docker logs -f tgi

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

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

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

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

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

***

## Anwendungsbeispiele

### 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-Vervollständigungen (OpenAI-kompatibel)

TGI unterstützt das OpenAI-API-Format für Chat-Vervollständigungen:

```bash
curl http://localhost:8080/v1/chat/completions \\
  -X POST \\
  -H 'Content-Type: application/json' \
  -d '{
    "model": "tgi",
    "messages": [
      {"role": "system", "content": "Du bist ein hilfreicher Assistent."},
      {"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 von Fibonacci-Zahlen:",
    "parameters": {
      "max_new_tokens": 300,
      "temperature": 0.2
    }
  }' \
  --no-buffer
```

### Beispiel 4: Python-Client

```python
from huggingface_hub import InferenceClient

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

# Einfache Generierung
response = client.text_generation(
    "Übersetze ins Französische: 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}\nAntwort: {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 Eingabetokenlänge                       |
| `--max-total-tokens`        | 2048         | Maximale Eingabe- + Ausgabetokens                |
| `--max-batch-total-tokens`  | auto         | Maximale Token pro Batch                         |
| `--quantize`                | none         | Quantisierung: `bitsandbytes-nf4`, `gptq`, `awq` |
| `--dtype`                   | auto         | `float16`, `bfloat16`                            |
| `--trust-remote-code`       | false        | Benutzerdefinierten Modellcode erlauben          |
| `--port`                    | 80           | Server-Port                                      |

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

***

## Leistungstipps

### 1. Flash Attention 2 aktivieren

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

### 2. Maximale Batchgröße anpassen

Für Szenarien mit hohem Durchsatz erhöhen Sie die Batchgröße:

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

### 3. bfloat16 auf Ampere+-GPUs verwenden

```bash
--dtype bfloat16
```

Dies ist numerisch stabiler als float16 und verhält sich auf modernen GPUs identisch.

### 4. Modelle vorab auf persistenten Speicher 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')
"
```

Dann den lokalen Pfad einbinden, um erneute Downloads nach Neustarts zu vermeiden.

### 5. GPU-Speicherverwaltung

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

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

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

### 6. Spekulative Dekodierung

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. Attempted to allocate X GiB
```

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

```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 festlegen
-e HF_ENDPOINT=https://hf-mirror.com
```

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

**Lösung:** Stellen Sie sicher, dass Port 8080 korrekt zugeordnet ist. TGI lauscht intern auf Port 80, aber Sie ordnen ihn extern 8080 zu:

```bash
-p 8080:80  # Host:Container
```

### Problem: "trust\_remote\_code is required"

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 werden schnell sein.

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

### Problem: Container beendet sich sofort

```bash
# Nach Fehlern suchen
docker logs tgi

# Häufige Lösung: gemeinsam genutzten Speicher erhöhen
--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-Marktplatz](https://clore.ai/marketplace)

***

## GPU-Empfehlungen für Clore.ai

| Anwendungsfall       | Empfohlene GPU   | Geschätzte Kosten bei Clore.ai |
| -------------------- | ---------------- | ------------------------------ |
| Entwicklung/Testen   | RTX 3090 (24 GB) | 0,07–0,21 $/GPU/Stunde         |
| Produktion (7B–13B)  | RTX 4090 (24 GB) | 0,14–0,42 $/GPU/Stunde         |
| Große Modelle (70B+) | A100 80GB / H100 | \~1,04 $/GPU/Stunde            |

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

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