> For the complete documentation index, see [llms.txt](https://unsloth.ai/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://unsloth.ai/docs/de/grundlagen/inference-and-deployment/sglang-guide.md).

# SGLang-Bereitstellungs- & Inferenzleitfaden

Leitfaden zum Speichern und Bereitstellen von LLMs mit SGLang für das Bereitstellen von LLMs in der Produktion

Du kannst jedes LLM oder feinabgestimmte Modell über [SGLang](https://github.com/sgl-project/sglang) für latenzarme Inferenz mit hohem Durchsatz. SGLang unterstützt die Inferenz von Text-, Bild-/Video-Modellen auf jeder GPU-Konfiguration, mit Unterstützung für einige GGUFs.

### :computer:SGLang installieren

Um SGLang und Unsloth auf NVIDIA-GPUs zu installieren, kannst du das Folgende in einer virtuellen Umgebung verwenden (wodurch deine anderen Python-Bibliotheken nicht beeinträchtigt werden)

```shellscript
# OPTIONAL verwende eine virtuelle Umgebung
python -m venv unsloth_env
source unsloth_env/bin/activate

# Installiere Rust, outlines-core und dann SGLang
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env && sudo apt-get install -y pkg-config libssl-dev
pip install --upgrade pip && pip install uv
uv pip install "sglang" && uv pip install unsloth
```

Für **Docker** Setups ausführen:

{% code overflow="wrap" %}

```shellscript
docker run --gpus all \
    --shm-size 32g \
    -p 30000:30000 \
    -v ~/.cache/huggingface:/root/.cache/huggingface \
    --env "HF_TOKEN=<secret>" \
    --ipc=host \
    lmsysorg/sglang:latest \
    python3 -m sglang.launch_server --model-path unsloth/Llama-3.1-8B-Instruct --host 0.0.0.0 --port 30000
```

{% endcode %}

### :bug:Fehlerbehebung bei SGLang-Installationsproblemen

Hinweis: Wenn du das Folgende siehst, aktualisiere Rust und outlines-core wie in [#setting-up-sglang](#setting-up-sglang "mention")

{% code overflow="wrap" %}

```
Hinweis: Dies deutet normalerweise auf ein Problem mit dem Paket oder der Build-Umgebung hin.
  Hilfe: `outlines-core` (v0.1.26) wurde einbezogen, weil `sglang` (v0.5.5.post2) von `outlines` (v0.1.11) abhängt, das von `outlines-core` abhängt
```

{% endcode %}

Wenn du ein Flashinfer-Problem wie das folgende siehst:

```
/home/daniel/.cache/flashinfer/0.5.2/100a/generated/batch_prefill_with_kv_cache_dtype_q_bf16_dtype_kv_bf16_dtype_o_bf16_dtype_idx_i32_head_dim_qk_64_head_dim_vo_64_posenc_0_use_swa_False_use_logits_cap_False_f16qk_False/batch_prefill_ragged_kernel_mask_1.cu:1:10: schwerwiegender Fehler: flashinfer/attention/prefill.cuh: Keine solche Datei oder kein solches Verzeichnis
    1 | #include <flashinfer/attention/prefill.cuh>
      |          ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Kompilierung beendet.
ninja: Build gestoppt: Unterbefehl fehlgeschlagen.

Mögliche Lösungen:
1. setze --mem-fraction-static auf einen kleineren Wert (z. B. 0,8 oder 0,7)
2. setze --cuda-graph-max-bs auf einen kleineren Wert (z. B. 16)
3. deaktiviere torch compile, indem du --enable-torch-compile nicht verwendest
4. deaktiviere CUDA Graph mit --disable-cuda-graph. (Nicht empfohlen. Enorme Leistungseinbußen)
Öffne ein Issue auf GitHub https://github.com/sgl-project/sglang/issues/new/choose
```

Entferne den Flashinfer-Cache über `rm -rf .cache/flashinfer` und auch das im Fehlermeldung genannte Verzeichnis, also `rm -rf ~/.cache/flashinfer`

### :truck:SGLang-Modelle bereitstellen

Um ein beliebiges Modell bereitzustellen, zum Beispiel [unsloth/Llama-3.2-1B-Instruct](https://huggingface.co/unsloth/Llama-3.2-1B-Instruct), führe das Folgende in einem separaten Terminal aus (ansonsten blockiert es dein aktuelles Terminal – du kannst auch tmux verwenden):

{% code overflow="wrap" %}

```shellscript
python3 -m sglang.launch_server \
    --model-path unsloth/Llama-3.2-1B-Instruct \
    --host 0.0.0.0 --port 30000
```

{% endcode %}

<figure><img src="https://797013937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2Fq3rBt5dn2PhrpvvfhSzo%2Fimage.png?alt=media&amp;token=e7a5170b-eabb-4a11-ae4b-f27a11213ae3" alt=""><figcaption></figcaption></figure>

Du kannst dann die OpenAI-Chat-Completions-Bibliothek verwenden, um das Modell aufzurufen (in einem anderen Terminal oder mit tmux):

```python
# Installiere openai mit pip install openai
from openai import OpenAI
import json
openai_client = OpenAI(
    base_url = "http://0.0.0.0:30000/v1",
    api_key = "sk-no-key-required",
)
completion = openai_client.chat.completions.create(
    model = "unsloth/Llama-3.2-1B-Instruct",
    messages = [{"role": "user", "content": "Was ist 2+2?"},],
)
print(completion.choices[0].message.content)
```

Und du erhältst `2 + 2 = 4.`

### 🦥 Unsloth-Finetunes in SGLang bereitstellen

Nach dem Fine-Tuning [Fine-tuning Guide](/docs/de/loslegen/fine-tuning-llms-guide.md) oder mithilfe unserer Notebooks unter [Unsloth-Notebooks](/docs/de/loslegen/unsloth-notebooks.md), kannst du deine Modelle direkt über SGLang in einem einzigen Workflow speichern oder bereitstellen. Ein Beispiel für ein Unsloth-Finetuning-Skript wäre zum Beispiel:

```python
from unsloth import FastLanguageModel
import torch
model, tokenizer = FastLanguageModel.from_pretrained(
    model_name = "unsloth/gpt-oss-20b",
    max_seq_length = 2048,
    load_in_4bit = True,
)
model = FastLanguageModel.get_peft_model(model)
```

**Um für SGLang in 16-Bit zu speichern, verwende:**

```python
model.save_pretrained_merged("finetuned_model", tokenizer, save_method = "merged_16bit")
## ODER auf HuggingFace hochladen:
model.push_to_hub_merged("hf/model", tokenizer, save_method = "merged_16bit", token = "")
```

**Um nur die LoRA-Adapter zu speichern**, verwende entweder:

```python
model.save_pretrained("finetuned_model")
tokenizer.save_pretrained("finetuned_model")
```

Oder verwende einfach unsere eingebaute Funktion dafür:

```python
model.save_pretrained_merged("model", tokenizer, save_method = "lora")
## ODER auf HuggingFace hochladen
model.push_to_hub_merged("hf/model", tokenizer, save_method = "lora", token = "")
```

### :railway\_car:gpt-oss-20b: Unsloth- & SGLang-Bereitstellungsleitfaden

Nachfolgend findest du ein Schritt-für-Schritt-Tutorial mit Anweisungen zum Trainieren des [gpt-oss](/docs/de/modelle/gpt-oss-how-to-run-and-fine-tune.md)-20B mit Unsloth und zur Bereitstellung mit SGLang. Es enthält Leistungs-Benchmarks über mehrere Quantisierungsformate hinweg.

{% stepper %}
{% step %}

#### Unsloth-Fine-Tuning- und Exportformate

Wenn du neu im Fine-Tuning bist, kannst du unseren [Leitfaden](/docs/de/loslegen/fine-tuning-llms-guide.md), oder probiere das gpt-oss-20B-Finetuning-Notebook unter [gpt-oss](/docs/de/modelle/gpt-oss-how-to-run-and-fine-tune.md) Nach dem Training kannst du das Modell in mehreren Formaten exportieren:

{% code overflow="wrap" %}

```python
model.save_pretrained_merged(
    "finetuned_model", 
    tokenizer, 
    save_method = "merged_16bit",
)
## Für gpt-oss-spezifische mxfp4-Konvertierungen:
model.save_pretrained_merged(
    "finetuned_model", 
    tokenizer, 
    save_method = "mxfp4", # (NUR FÜR gpt-oss, sonst wähle "merged_16bit")
)
```

{% endcode %}
{% endstep %}

{% step %}

#### Bereitstellung mit SGLang

Wir haben unser gpt-oss-Finetune im Ordner "finetuned\_model" gespeichert, und deshalb können wir in einem neuen Terminal das finetunte Modell als Inferenz-Endpunkt mit SGLang starten:

```shellscript
python -m sglang.launch_server \
    --model-path finetuned_model \
    --host 0.0.0.0 --port 30002
```

Du musst vielleicht ein bisschen warten bei `Batch-Erfassung (bs=1 avail_mem=20.84 GB):` !
{% endstep %}

{% step %}

#### Den Inferenz-Endpunkt aufrufen:

Um den Inferenz-Endpunkt aufzurufen, öffne zuerst ein neues Terminal. Danach können wir das Modell wie unten aufrufen:

{% code overflow="wrap" %}

```python
from openai import OpenAI
import json
openai_client = OpenAI(
    base_url = "http://0.0.0.0:30002/v1",
    api_key = "sk-no-key-required",
)
completion = openai_client.chat.completions.create(
    model = "finetuned_model",
    messages = [{"role": "user", "content": "Was ist 2+2?"},],
)
print(completion.choices[0].message.content)

## AUSGABE ##
# <|channel|>analysis<|message|>Der Benutzer stellt eine einfache Mathematikfrage. Wir sollten 4 antworten. Außerdem sollten wir die Richtlinie einhalten. Keine Probleme.<|end|><|start|>assistant<|channel|>final<|message|>2 + 2 ergibt 4.
```

{% endcode %}
{% endstep %}
{% endstepper %}

### :gem:FP8-Online-Quantisierung

Um Modelle mit FP8-Online-Quantisierung bereitzustellen, die mit SGLang 30 bis 50 % mehr Durchsatz und 50 % weniger Speicherverbrauch bei 2-fach längerer Kontextlänge ermöglichen, kannst du Folgendes tun:

{% code overflow="wrap" %}

```shellscript
python -m sglang.launch_server \
    --model-path unsloth/Llama-3.2-1B-Instruct \
    --host 0.0.0.0 --port 30002 \
    --quantization fp8 \
    --kv-cache-dtype fp8_e4m3
```

{% endcode %}

Du kannst auch verwenden `--kv-cache-dtype fp8_e5m2` das einen größeren dynamischen Bereich hat, was FP8-Inferenzprobleme lösen könnte, falls du darauf stößt. Oder verwende unsere vorquantisierten Float8-Quants, die unter <https://huggingface.co/unsloth/models?search=-fp8> oder einige sind unten aufgeführt:

{% embed url="<https://huggingface.co/unsloth/Llama-3.2-3B-FP8-Dynamic>" %}

{% embed url="<https://huggingface.co/unsloth/Llama-3.3-70B-Instruct-FP8-Dynamic>" %}

### ⚡ SGLang benchmarken

Nachfolgend findest du etwas Code, den du ausführen kannst, um die Leistungsgeschwindigkeit deines feinabgestimmten Modells zu testen:

```shellscript
python -m sglang.launch_server \
    --model-path finetuned_model \
    --host 0.0.0.0 --port 30002
```

Dann in einem anderen Terminal oder über tmux:

```shellscript
# Batchgröße=8, Eingabe=1024, Ausgabe=1024
python -m sglang.bench_one_batch_server \
    --model finetuned_model \
    --base-url http://0.0.0.0:30002 \
    --batch-size 8 \
    --input-len 1024 \
    --output-len 1024
```

Du wirst den Benchmark-Lauf wie unten sehen:

<figure><img src="https://797013937-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FhcGy7cwC2xFaPA7FcJJq%2Fimage.png?alt=media&amp;token=05687013-8af5-4731-8dae-b8cc05d44f21" alt=""><figcaption></figcaption></figure>

Wir verwendeten eine B200x1-GPU mit gpt-oss-20b und erhielten die folgenden Ergebnisse (\~2.500 Tokens Durchsatz)

| Batch/Eingabe/Ausgabe | TTFT (s) | ITL (s) | Eingabe-Durchsatz | Ausgabe-Durchsatz |
| --------------------- | -------- | ------- | ----------------- | ----------------- |
| 8/1024/1024           | 0.40     | 3.59    | 20,718.95         | 2,562.87          |
| 8/8192/1024           | 0.42     | 3.74    | 154,459.01        | 2,473.84          |

Siehe <https://docs.sglang.ai/advanced_features/server_arguments.html> für die Server-Argumente von SGLang.

### :person\_running:Interaktiver Offline-Modus von SGLang

Du kannst SGLang auch im Offline-Modus (also nicht als Server) in einer interaktiven Python-Umgebung verwenden.

{% code overflow="wrap" %}

```python
import sglang as sgl
engine = sgl.Engine(model_path = "unsloth/Qwen3-0.6B", random_seed = 42)

prompt = "Today is a sunny day and I like"
sampling_params = {"temperature": 0, "max_new_tokens": 256}
outputs = engine.generate(prompt, sampling_params)["text"]
print(outputs)
engine.shutdown()
```

{% endcode %}

### :sparkler:GGUFs in SGLang

Interessanterweise unterstützt SGLang auch GGUFs! **Qwen3 MoE befindet sich noch in Arbeit, aber die meisten dichten Modelle (Llama 3, Qwen 3, Mistral usw.) werden unterstützt.**

Installiere zuerst das neueste gguf-Python-Paket über:

{% code overflow="wrap" %}

```shellscript
pip install -e "git+https://github.com/ggml-org/llama.cpp.git#egg=gguf&subdirectory=gguf-py" # installiere ein Python-Paket aus einem Repo-Unterverzeichnis
```

{% endcode %}

Dann kannst du zum Beispiel im Offline-Modus von SGLang Folgendes tun:

{% code overflow="wrap" %}

```python
from huggingface_hub import hf_hub_download
model_path = hf_hub_download(
    "unsloth/Qwen3-32B-GGUF",
    filename = "Qwen3-32B-UD-Q4_K_XL.gguf",
)
import sglang as sgl
engine = sgl.Engine(model_path = model_path, random_seed = 42)

prompt = "Today is a sunny day and I like"
sampling_params = {"temperature": 0, "max_new_tokens": 256}
outputs = engine.generate(prompt, sampling_params)["text"]
print(outputs)
engine.shutdown()
```

{% endcode %}

### :clapper:GGUF-Bereitstellung mit hohem Durchsatz mit SGLang

Lade zuerst die spezifische GGUF-Datei wie unten herunter:

{% code overflow="wrap" %}

```python
from huggingface_hub import hf_hub_download
hf_hub_download("unsloth/Qwen3-32B-GGUF", filename="Qwen3-32B-UD-Q4_K_XL.gguf", local_dir=".")
```

{% endcode %}

Dann stelle die spezifische Datei bereit `Qwen3-32B-UD-Q4_K_XL.gguf` und verwenden Sie `--served-model-name unsloth/Qwen3-32B` und außerdem benötigen wir den mit HuggingFace kompatiblen Tokenizer über `--tokenizer-path`

```shellscript
python -m sglang.launch_server \
    --model-path Qwen3-32B-UD-Q4_K_XL.gguf \
    --host 0.0.0.0 --port 30002 \
    --served-model-name unsloth/Qwen3-32B \
    --tokenizer-path unsloth/Qwen3-32B
```


---

# 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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://unsloth.ai/docs/de/grundlagen/inference-and-deployment/sglang-guide.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
