> 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

SGLang (Structured Generation Language) ist ein leistungsstarkes LLM-Serving-Framework, das vom LMSYS-Team entwickelt wurde, bekannt für ihre Arbeit an Vicuna und Chatbot Arena. Es verfügt über RadixAttention zur gemeinsamen Nutzung des KV-Caches, effiziente MoE (Mixture of Experts)-Unterstützung und eine OpenAI-kompatible API — wodurch es eine der schnellsten Open-Source-Inferenz-Engines auf CLORE.AI GPU-Servern ist.

{% 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        | 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 %}

## Schnelle Bereitstellung 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 gesperrte Modelle |
| `CUDA_VISIBLE_DEVICES` | `0,1`       | Zu verwendende GPUs                     |

## Schritt-für-Schritt Einrichtung

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

Besuchen Sie [CLORE.AI Marketplace](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. SSH in Ihren Server

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

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

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

### 4. Starten Sie den SGLang-Server

**Basisstart (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. Überprüfen Sie den Serverzustand

```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. Zugriff von Außen über den CLORE.AI-Proxy

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

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

Verwenden Sie diese URL als 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": "You are a helpful coding assistant."},
      {"role": "user", "content": "Write a quicksort implementation 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": "Explain how transformer attention works."}
    ],
    "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 erfordert standardmäßig keine Authentifizierung
)

response = client.chat.completions.create(
    model="meta-llama/Meta-Llama-3.1-8B-Instruct",
    messages=[
        {"role": "system", "content": "You are a data science expert."},
        {"role": "user", "content": "What is gradient boosting?"},
    ],
    max_tokens=400,
    temperature=0.7,
)

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

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

SGLangs native API bietet zusätzliche Kontrolle:

```python
import requests

# Generieren von Completions
response = requests.post(
    "http://localhost:30000/generate",
    json={
        "text": "The future of AI is",
        "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": "Extract information: John Smith, 35 years old, lives 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`       | Host binden (verwenden Sie `0.0.0.0` für extern) |
| `--port`                | `30000`           | Serverport                                       |
| `--tp`                  | `1`               | Grad der Tensor-Parallelität (Anzahl 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 Vorbefüllungsschritt     |
| `--context-length`      | modell max        | Überschreiben der maximalen Kontextlänge         |
| `--trust-remote-code`   | false             | Erlaube benutzerdefinierten Modellcode           |
| `--quantization`        | keine             | `awq`, `gptq`, `fp8`                             |
| `--load-format`         | `auto`            | `auto`, `pt`, `safetensors`                      |
| `--tokenizer-path`      | gleich wie Modell | Benutzerdefinierter Tokenizer-Pfad               |

### Quantisierungsoptionen

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

```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 Schlüsselvorteil

SGLangs RadixAttention verwendet automatisch den KV-Cache erneut für geteilte Prompt-Präfixe. Dies ist besonders nützlich für:

* Chatbots mit langen System-Prompts
* RAG-Anwendungen mit wiederholtem Kontext
* Batch-API-Aufrufe, die dasselbe Präfix teilen

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

### 2. Erhöhen Sie die KV-Cache-Größe

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

Seien Sie vorsichtig, nicht zu hoch zu gehen — lassen Sie Platz für Modellgewichte.

### 3. Gestückelte Vorbefüllung für lange Kontexte

```bash
--chunked-prefill-size 4096  # Verarbeiten Sie lange Prompts in Stücken
```

### 4. Aktivieren Sie das FlashInfer-Backend

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

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

### 5. Multi-GPU Tensor-Parallelismus

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

```bash
--tp 4  # Verwenden Sie 4 GPUs
```

Jede GPU muss genügend VRAM für ein Shard des Modells haben.

### 6. Abstimmung für Durchsatz vs. Latenz

**Niedrige Latenz (einzelner Benutzer):**

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

**Hoher Durchsatz (viele Benutzer):**

```bash
--max-running-requests 64 \
--schedule-policy lpm  # Longest Prefix Match Scheduling
```

***

## Fehlerbehebung

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

```
torch.cuda.OutOfMemoryError: CUDA out of memory
```

**Lösung:** Reduzieren Sie den Speicheranteil oder verwenden Sie Quantisierung:

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

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

```bash
# Überprüfen Sie die CUDA-Verfügbarkeit
docker exec -it sglang nvidia-smi

# Überprüfen Sie den Modell-Download-Fortschritt
docker logs -f sglang 2>&1 | tail -50
```

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

Fügen Sie `--trust-remote-code` zum 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 verwenden:

```bash
--dtype bfloat16  # Besser als float16 für MoE
--tp 2            # Auf GPUs aufteilen, falls verfügbar
```

### Problem: Fehler bei Kontextlänge

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

### Problem: Port 30000 nicht zugänglich

Stellen Sie sicher, dass der Port in Ihrer CLORE.AI-Bestellung freigegeben ist. Überprü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 Marketplace](https://clore.ai/marketplace)

***

## Clore.ai GPU-Empfehlungen

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

> 💡 Alle Beispiele in diesem Leitfaden können auf [Clore.ai](https://clore.ai/marketplace) GPU-Servern bereitgestellt werden. Durchsuchen Sie verfügbare GPUs und mieten Sie stundenweise — keine Verpflichtungen, vollständiger 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/sglang.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.
