> 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/zh/ji-chu-zhi-shi/inference-and-deployment/sglang-guide.md).

# SGLang 部署与推理指南

关于将 LLM 保存并部署到 SGLang 以在生产环境中提供 LLM 服务的指南

你可以通过以下方式提供任何 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: 致命错误：flashinfer/attention/prefill.cuh：没有那个文件或目录
    #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 compile
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&amp;token=e7a5170b-eabb-4a11-ae4b-f27a11213ae3" alt=""><figcaption></figcaption></figure>

然后你可以使用 OpenAI Chat Completions 库来调用该模型（在另一个终端中或使用 tmux）：

```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": "2+2 等于多少？"},],
)
print(completion.choices[0].message.content)
```

然后你将得到 `2 + 2 = 4.`

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

微调后 [Fine-tuning Guide](/docs/zh/kuai-su-kai-shi/fine-tuning-llms-guide.md) 或者使用我们在以下位置提供的笔记本 [Unsloth 笔记本](/docs/zh/kuai-su-kai-shi/unsloth-notebooks.md)，你可以在单一工作流中直接通过 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 部署指南

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

{% stepper %}
{% step %}

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

如果你是微调新手，可以阅读我们的 [指南](/docs/zh/kuai-su-kai-shi/fine-tuning-llms-guide.md)，或者试试位于以下位置的 gpt-oss 20B 微调笔记本 [gpt-oss](/docs/zh/mo-xing/gpt-oss-how-to-run-and-fine-tune.md) 训练后，你可以将模型导出为多种格式：

{% 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": "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% 更低的内存占用，并支持 2 倍更长的上下文长度，你可以执行以下操作：

{% 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&amp;token=05687013-8af5-4731-8dae-b8cc05d44f21" alt=""><figcaption></figcaption></figure>

我们使用了 B200x1 GPU 和 gpt-oss-20b，得到以下结果（吞吐量约 2,500 tokens）

| 批次/输入/输出    | 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
```


---

# 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/zh/ji-chu-zhi-shi/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.
