# SGLang 部署与推理指南

您可以通过以下方式为任何大型语言模型（LLM）或微调模型提供服务 [SGLang](https://github.com/sgl-project/sglang) 以实现低延迟、高吞吐量的推理。SGLang 支持在任意 GPU 配置上进行文本、图像/视频模型推理，并支持部分 GGUF。

### :computer:安装 SGLang

要在 NVIDIA GPU 上安装 SGLang 和 Unsloth，您可以在虚拟环境中使用下面的命令（不会破坏您其他的 Python 库）

```shellscript
# 可选 使用虚拟环境
python -m venv unsloth_env
source unsloth_env/bin/activate

# 安装 Rust、outlines-core 然后安装 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
```

对于 **Docker** 部署，请运行：

{% 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:调试 SGLang 安装问题

注意：如果您看到下面的内容，请按说明更新 Rust 和 outlines-core [#setting-up-sglang](#setting-up-sglang "mention")

{% code overflow="wrap" %}

```
提示：这通常表示包或构建环境存在问题。
  帮助：`outlines-core` (v0.1.26) 被包含是因为 `sglang` (v0.5.5.post2) 依赖 `outlines` (v0.1.11)，而 `outlines` 又依赖 `outlines-core`
```

{% endcode %}

如果您看到类似下面的 Flashinfer 问题：

```
/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: fatal error: flashinfer/attention/prefill.cuh: No such file or directory
    1 | #include <flashinfer/attention/prefill.cuh>
      |          ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
编译终止。
ninja: 构建停止：子命令失败。

可能的解决方案：
1. 将 --mem-fraction-static 设置为较小的值（例如 0.8 或 0.7）
2. 将 --cuda-graph-max-bs 设置为较小的值（例如 16）
3. 通过不使用 --enable-torch-compile 来禁用 torch 编译
4. 通过 --disable-cuda-graph 禁用 CUDA graph。（不推荐，性能会大幅下降）
在 GitHub 上打开 issue https://github.com/sgl-project/sglang/issues/new/choose
```

通过以下命令删除 flashinfer 缓存 `rm -rf .cache/flashinfer` 以及错误消息中列出的目录，即 `rm -rf ~/.cache/flashinfer`

### :truck:部署 SGLang 模型

要部署任意模型，例如 [unsloth/Llama-3.2-1B-Instruct](https://huggingface.co/unsloth/Llama-3.2-1B-Instruct)，请在另一个终端执行下面操作（否则会阻塞当前终端——您也可以使用 tmux）：

{% 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://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2Fq3rBt5dn2PhrpvvfhSzo%2Fimage.png?alt=media&#x26;token=e7a5170b-eabb-4a11-ae4b-f27a11213ae3" alt=""><figcaption></figcaption></figure>

然后您可以在另一个终端或使用 tmux 使用 OpenAI Chat 完成库来调用该模型：

```python
# 通过 pip install openai 安装 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": "What is 2+2?"},],
)
print(completion.choices[0].message.content)
```

您将得到 `2 + 2 = 4.`

### 🦥 在 SGLang 中部署 Unsloth 微调模型

微调完成后 [fine-tuning-llms-guide](https://unsloth.ai/docs/zh/kai-shi-shi-yong/fine-tuning-llms-guide "mention") 或使用我们的笔记本在 [unsloth-notebooks](https://unsloth.ai/docs/zh/kai-shi-shi-yong/unsloth-notebooks "mention")，您可以通过单一工作流程直接通过 SGLang 保存或部署您的模型。例如一个 Unsloth 微调脚本示例：

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

**要为 SGLang 保存为 16 位，请使用：**

```python
model.save_pretrained_merged("finetuned_model", tokenizer, save_method = "merged_16bit")
## 或 上传到 HuggingFace：
model.push_to_hub_merged("hf/model", tokenizer, save_method = "merged_16bit", token = "")
```

**若只保存 LoRA 适配器**，可以使用：

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

或者直接使用我们内置的函数来完成：

```python
model.save_pretrained_merged("model", tokenizer, save_method = "lora")
## 或 上传到 HuggingFace
model.push_to_hub_merged("hf/model", tokenizer, save_method = "lora", token = "")
```

### :railway\_car:gpt-oss-20b：Unsloth 与 SGLang 部署指南

下面是一个逐步教程，包含使用 Unsloth 训练 [gpt-oss](https://unsloth.ai/docs/zh/mo-xing/gpt-oss-how-to-run-and-fine-tune)-20b 并使用 SGLang 部署的说明。它包含跨多种量化格式的性能基准测试。

{% stepper %}
{% step %}

#### Unsloth 微调与导出格式

如果您对微调不熟，可以阅读我们的 [指南](https://unsloth.ai/docs/zh/kai-shi-shi-yong/fine-tuning-llms-guide)，或尝试 gpt-oss 20B 微调笔记本，地址在 [gpt-oss-how-to-run-and-fine-tune](https://unsloth.ai/docs/zh/mo-xing/gpt-oss-how-to-run-and-fine-tune "mention") 训练完成后，您可以将模型导出为多种格式：

{% code overflow="wrap" %}

```python
model.save_pretrained_merged(
    "finetuned_model", 
    tokenizer, 
    save_method = "merged_16bit",
)
## 针对 gpt-oss 的 mxfp4 转换：
model.save_pretrained_merged(
    "finetuned_model", 
    tokenizer, 
    save_method = "mxfp4", #（仅适用于 gpt-oss，否则请选择 "merged_16bit"）
)
```

{% endcode %}
{% endstep %}

{% step %}

#### 使用 SGLang 部署

我们将 gpt-oss 微调结果保存到文件夹 "finetuned\_model"，因此在新终端中，我们可以用 SGLang 将微调模型作为推理端点启动：

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

您可能需要稍等一会儿，看到以下内容时： `捕获批次（bs=1 avail_mem=20.84 GB）：` !
{% endstep %}

{% step %}

#### 调用推理端点：

要调用推理端点，首先启动一个新终端。然后我们可以如下调用模型：

{% 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": "What is 2+2?"},],
)
print(completion.choices[0].message.content)

## 输出 ##
# <|channel|>analysis<|message|>用户提出了一个简单的数学问题。我们应该回答 4。同时我们应遵守政策。没有问题。<|end|><|start|>assistant<|channel|>final<|message|>2 + 2 等于 4。
```

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

### :gem:FP8 在线量化

要使用 FP8 在线量化部署模型，从而在 SGLang 中实现 30% 到 50% 的更高吞吐量、50% 的内存节省并支持更长两倍的上下文长度，您可以执行以下操作：

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

您也可以使用 `--kv-cache-dtype fp8_e5m2` 该选项具有更大的动态范围，如果您遇到 FP8 推理问题可能会有所帮助。或者使用我们在以下列出的预量化 float8 量化模型： <https://huggingface.co/unsloth/models?search=-fp8> 或者下面列出的一些：

{% 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 基准测试

下面是一些您可以运行以测试微调模型性能速度的代码：

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

然后在另一个终端或通过 tmux：

```shellscript
# 批次大小=8，输入=1024，输出=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
```

您将看到类似下面的基准运行输出：

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

我们使用 B200x1 GPU 对 gpt-oss-20b 进行了测试，得到以下结果（约 2,500 标记的吞吐量）

| 批次/输入/输出    | TTFT（秒） | ITL（秒） | 输入吞吐量      | 输出吞吐量    |
| ----------- | ------- | ------ | ---------- | -------- |
| 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 |

请参见 <https://docs.sglang.ai/advanced_features/server_arguments.html> 以获取 SGLang 的服务器参数说明。

### :person\_running:SGLang 交互式离线模式

您也可以在 Python 交互环境中以离线模式（即非服务器）使用 SGLang。

{% 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:SGLang 中的 GGUF

有趣的是，SGLang 也支持 GGUF！ **Qwen3 MoE 仍在构建中，但大多数密集模型（Llama 3、Qwen 3、Mistral 等）均受支持。**

首先通过以下命令安装最新的 gguf Python 包：

{% code overflow="wrap" %}

```shellscript
pip install -e "git+https://github.com/ggml-org/llama.cpp.git#egg=gguf&subdirectory=gguf-py" # 从仓库子目录安装 Python 包
```

{% endcode %}

然后例如在 SGLang 的离线模式中，您可以这样做：

{% 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:使用 SGLang 提供高吞吐量的 GGUF 服务

首先像下面这样下载特定的 GGUF 文件：

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

然后提供该特定文件 `Qwen3-32B-UD-Q4_K_XL.gguf` 并使用 `--served-model-name unsloth/Qwen3-32B` 同时我们还需要通过 HuggingFace 兼容的 tokenizer，使用 `--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
```
