> 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/sglang.md).

# SGLang

Deploye SGLang für leistungsstarken LLM-Betrieb mit RadixAttention auf Clore.ai-GPUs

SGLang (Structured Generation Language) ist ein leistungsstarkes Framework für das Bereitstellen von LLMs, entwickelt vom LMSYS-Team, das für seine Arbeit an Vicuna und Chatbot Arena bekannt ist. Es bietet RadixAttention für das Teilen des KV-Caches, effiziente MoE-Unterstützung (Mixture of Experts) und eine OpenAI-kompatible API — damit ist es eine der schnellsten verfügbaren Open-Source-Inferenz-Engines 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        | NVIDIA Turing+ (RTX 2000+) | A100, H100, RTX 4090 |

{% hint style="info" %}
SGLang erreicht die beste Leistung auf Ampere+-GPUs mit aktiviertem FlashInfer. Für MoE-Modelle wie Mixtral oder DeepSeek werden Multi-GPU-Setups empfohlen.
{% endhint %}

## Schnellbereitstellung auf CLORE.AI

**Docker-Image:** `lmsysorg/sglang:latest`

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

**Umgebungsvariablen:**

| Variable               | Beispiel    | Beschreibung                             |
| ---------------------- | ----------- | ---------------------------------------- |
| `HF_TOKEN`             | `hf_xxx...` | HuggingFace-Token für geschützte Modelle |
| `CUDA_VISIBLE_DEVICES` | `0,1`       | Zu verwendende GPUs                      |

## Schritt-für-Schritt-Einrichtung

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

Besuchen [CLORE.AI-Marktplatz](https://clore.ai/marketplace) und wählen Sie einen Server aus:

* **7B-Modelle**: mindestens 16 GB VRAM (RTX 4080, A10)
* **13B-Modelle**: 24 GB VRAM (RTX 3090, RTX 4090, A5000)
* **70B-Modelle**: 80 GB+ VRAM (A100 80GB) oder Multi-GPU
* **MoE-Modelle (Mixtral 8x7B)**: 48 GB VRAM oder 2× 24 GB

### 2. Verbinden Sie sich per SSH mit Ihrem Server

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

### 3. SGLang-Docker-Image herunterladen

```bash
docker pull lmsysorg/sglang:latest
```

### 4. SGLang-Server starten

**Einfacher Start (Llama 3.1 8B):**

```bash
docker run -d \
  --name sglang \
  --gpus all \
  --shm-size 16g \
  --ipc host \
  -p 30000:30000 \
  -v /root/models:/root/.cache/huggingface \
  lmsysorg/sglang:latest \
  python3 -m sglang.launch_server \
    --model-path meta-llama/Meta-Llama-3.1-8B-Instruct \
    --host 0.0.0.0 \
    --port 30000
```

**Mit HuggingFace-Token:**

```bash
docker run -d \
  --name sglang \
  --gpus all \
  --shm-size 16g \
  --ipc host \
  -p 30000:30000 \
  -v /root/models:/root/.cache/huggingface \
  -e HF_TOKEN=hf_your_token_here \
  lmsysorg/sglang:latest \
  python3 -m sglang.launch_server \
    --model-path meta-llama/Meta-Llama-3.1-8B-Instruct \
    --host 0.0.0.0 \
    --port 30000 \
    --dtype bfloat16
```

**Qwen2.5 72B auf Multi-GPU:**

```bash
docker run -d \
  --name sglang \
  --gpus all \
  --shm-size 32g \
  --ipc host \
  -p 30000:30000 \
  -v /root/models:/root/.cache/huggingface \
  lmsysorg/sglang:latest \
  python3 -m sglang.launch_server \
    --model-path Qwen/Qwen2.5-72B-Instruct \
    --host 0.0.0.0 \
    --port 30000 \
    --tp 2 \
    --dtype bfloat16
```

**DeepSeek-V2 (MoE-Modell):**

```bash
docker run -d \
  --name sglang \
  --gpus all \
  --shm-size 32g \
  --ipc host \
  -p 30000:30000 \
  -v /root/models:/root/.cache/huggingface \
  lmsysorg/sglang:latest \
  python3 -m sglang.launch_server \
    --model-path deepseek-ai/DeepSeek-V2-Lite-Chat \
    --host 0.0.0.0 \
    --port 30000 \
    --trust-remote-code \
    --tp 1
```

### 5. Serverzustand prüfen

```bash
# Logs anzeigen
docker logs -f sglang

# Gesundheitsprüfung (warten Sie ca. 2–3 Minuten, bis das Modell geladen ist)
curl http://localhost:30000/health

# Modellinformationen abrufen
curl http://localhost:30000/get_model_info
```

### 6. Von außen über den CLORE.AI-Proxy zugreifen

Ihr CLORE.AI-Dashboard bietet eine `http_pub` URL für Port 30000:

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

Verwenden Sie diese URL als Ihre Basis-URL in jedem OpenAI-kompatiblen Client.

***

## Anwendungsbeispiele

### Beispiel 1: OpenAI-kompatible Chat-Completions

```bash
curl http://localhost:30000/v1/chat/completions \
  -X POST \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "meta-llama/Meta-Llama-3.1-8B-Instruct",
    "messages": [
      {"role": "system", "content": "Du bist ein hilfreicher Coding-Assistent."},
      {"role": "user", "content": "Schreibe eine Quicksort-Implementierung in Python."}
    ],
    "max_tokens": 512,
    "temperature": 0.2
  }'
```

### Beispiel 2: Streaming-Antwort

```bash
curl http://localhost:30000/v1/chat/completions \
  -X POST \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "meta-llama/Meta-Llama-3.1-8B-Instruct",
    "messages": [
      {"role": "user", "content": "Erkläre, wie Transformer-Attention funktioniert."}
    ],
    "max_tokens": 800,
    "stream": true
  }' \
  --no-buffer
```

### Beispiel 3: Python OpenAI-Client

```python
from openai import OpenAI

# Zeigen Sie auf Ihren CLORE.AI-SGLang-Server
client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="none",  # SGLang benötigt standardmäßig keine Authentifizierung
)

response = client.chat.completions.create(
    model="meta-llama/Meta-Llama-3.1-8B-Instruct",
    messages=[
        {"role": "system", "content": "Du bist ein Experte für Data Science."},
        {"role": "user", "content": "Was ist Gradient Boosting?"},
    ],
    max_tokens=400,
    temperature=0.7,
)

print(response.choices[0].message.content)
```

### Beispiel 4: Batch-Inferenz mit der nativen SGLang-API

Die native API von SGLang bietet zusätzliche Steuerungsmöglichkeiten:

```python
import requests

# Completions generieren
response = requests.post(
    "http://localhost:30000/generate",
    json={
        "text": "Die Zukunft der KI ist",
        "sampling_params": {
            "max_new_tokens": 200,
            "temperature": 0.8,
            "top_p": 0.95,
        },
    },
)
print(response.json()["text"])
```

### Beispiel 5: Eingeschränkte JSON-Ausgabe

SGLang unterstützt die Erzeugung strukturierter Ausgaben:

```python
import requests

schema = {
    "type": "object",
    "properties": {
        "name": {"type": "string"},
        "age": {"type": "integer"},
        "city": {"type": "string"},
    },
    "required": ["name", "age", "city"],
}

response = requests.post(
    "http://localhost:30000/generate",
    json={
        "text": "Informationen extrahieren: John Smith, 35 Jahre alt, lebt in New York.",
        "sampling_params": {
            "max_new_tokens": 100,
            "temperature": 0.0,
        },
        "json_schema": schema,
    },
)
print(response.json()["text"])
# Ausgabe: {"name": "John Smith", "age": 35, "city": "New York"}
```

***

## Konfiguration

### Wichtige Startparameter

| Parameter               | Standard       | Beschreibung                                   |
| ----------------------- | -------------- | ---------------------------------------------- |
| `--model-path`          | erforderlich   | HuggingFace-Modell-ID oder lokaler Pfad        |
| `--host`                | `127.0.0.1`    | Bind-Host (verwenden Sie `0.0.0.0` für extern) |
| `--port`                | `30000`        | Serverport                                     |
| `--tp`                  | `1`            | Grad der Tensorparallelität (Anzahl der GPUs)  |
| `--dp`                  | `1`            | Grad der Datenparallelität                     |
| `--dtype`               | `auto`         | `float16`, `bfloat16`, `float32`               |
| `--mem-fraction-static` | `0.88`         | Anteil des VRAM für den KV-Cache               |
| `--max-prefill-tokens`  | auto           | Maximale Token in einem Prefill-Schritt        |
| `--context-length`      | Modellmaximum  | Maximale Kontextlänge überschreiben            |
| `--trust-remote-code`   | false          | Benutzerdefinierten Modellcode zulassen        |
| `--quantization`        | none           | `awq`, `gptq`, `fp8`                           |
| `--load-format`         | `auto`         | `auto`, `pt`, `safetensors`                    |
| `--tokenizer-path`      | wie das Modell | Benutzerdefinierter Tokenizer-Pfad             |

### Quantisierungsoptionen

**AWQ (empfohlen für Geschwindigkeit):**

```bash
python3 -m sglang.launch_server \
  --model-path casperhansen/mistral-7b-instruct-v0.2-awq \
  --quantization awq \
  --host 0.0.0.0 \
  --port 30000
```

**FP8 (für H100/A100):**

```bash
python3 -m sglang.launch_server \
  --model-path meta-llama/Meta-Llama-3.1-8B-Instruct \
  --quantization fp8 \
  --host 0.0.0.0 \
  --port 30000
```

***

## Leistungstipps

### 1. RadixAttention — Der entscheidende Vorteil

SGLangs RadixAttention verwendet den KV-Cache für geteilte Prompt-Präfixe automatisch wieder. Das ist besonders leistungsstark für:

* Chatbots mit langen System-Prompts
* RAG-Anwendungen mit wiederverwendetem Kontext
* Batch-API-Aufrufe mit demselben Präfix

Keine zusätzliche Konfiguration erforderlich — es ist immer aktiviert.

### 2. KV-Cache-Größe erhöhen

```bash
--mem-fraction-static 0.90  # 90 % des VRAM für den KV-Cache verwenden
```

Achten Sie darauf, nicht zu hoch zu gehen — lassen Sie Platz für die Modellgewichte.

### 3. Chunked Prefill für lange Kontexte

```bash
--chunked-prefill-size 4096  # Lange Prompts in Blöcken verarbeiten
```

### 4. FlashInfer-Backend aktivieren

SGLang verwendet automatisch FlashInfer, wenn verfügbar (Ampere+-GPUs):

```bash
--attention-backend flashinfer
```

### 5. Multi-GPU-Tensorparallelität

Für Modelle, die nicht auf eine einzelne GPU passen:

```bash
--tp 4  # 4 GPUs verwenden
```

Jede GPU muss über ausreichend VRAM für einen Modell-Shard verfügen.

### 6. Für Durchsatz vs. Latenz optimieren

**Geringe Latenz (Einzelnutzer):**

```bash
--max-running-requests 4
```

**Hoher Durchsatz (viele Nutzer):**

```bash
--max-running-requests 64 \
--schedule-policy lpm  # Scheduling mit längstem Präfix-Match
```

***

## Fehlerbehebung

### Problem: "torch.cuda.OutOfMemoryError"

```
torch.cuda.OutOfMemoryError: CUDA-Speicher voll
```

**Lösung:** Speicheranteil reduzieren oder Quantisierung verwenden:

```bash
--mem-fraction-static 0.80
# oder
--quantization awq
```

### Problem: Server startet nicht (hängt beim Laden)

```bash
# CUDA-Verfügbarkeit prüfen
docker exec -it sglang nvidia-smi

# Fortschritt des Modell-Downloads prüfen
docker logs -f sglang 2>&1 | tail -50
```

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

Fügen Sie `--trust-remote-code` dem Startbefehl für Modelle mit benutzerdefinierten Architekturen (DeepSeek, Falcon usw.) hinzu.

### Problem: Langsame Generierung bei MoE-Modellen

MoE-Modelle (Mixtral, DeepSeek) sind durch Speicherbandbreite begrenzt. Stellen Sie sicher, dass Sie Folgendes verwenden:

```bash
--dtype bfloat16  # Besser als float16 für MoE
--tp 2            # Falls verfügbar über GPUs aufteilen
```

### Problem: Fehler bei der Kontextlänge

```bash
# Kontextlänge überschreiben
--context-length 32768
```

### Problem: Port 30000 nicht erreichbar

Überprüfen Sie, ob der Port in Ihrer CLORE.AI-Bestellkonfiguration freigegeben ist. Prüfen Sie die http\_pub-URL in Ihrem Bestell-Dashboard, nicht localhost.

***

## Links

* [GitHub](https://github.com/sgl-project/sglang)
* [Dokumentation](https://sgl-project.github.io/start/install.html)
* [Docker Hub](https://hub.docker.com/r/lmsysorg/sglang)
* [Unterstützte Modelle](https://github.com/sgl-project/sglang?tab=readme-ov-file#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/sglang.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.
