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

# SGLangデプロイメント＆推論ガイド

本番環境でLLMを提供するために、LLMを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: 致命的エラー: flashinfer/attention/prefill.cuh: そのようなファイルやディレクトリはありません
    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 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://735611837-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/jp/meru/fine-tuning-llms-guide.md) または以下のノートブックを使用すると [Unslothノートブック](/docs/jp/meru/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のデプロイガイド

以下は、Unsloth を使って [gpt-oss](/docs/jp/moderu/gpt-oss-how-to-run-and-fine-tune.md)-20b を学習し、SGLang でデプロイするための手順を含むステップバイステップのチュートリアルです。複数の量子化形式にわたる性能ベンチマークも含まれています。

{% stepper %}
{% step %}

#### Unslothのファインチューニングとエクスポート形式

ファインチューニングが初めてなら、次をお読みください [ガイド](/docs/jp/meru/fine-tuning-llms-guide.md)、または以下の gpt-oss 20B ファインチューニングノートブックを試してください [gpt-oss](/docs/jp/moderu/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オンライン量子化

SGLangで、30〜50%高いスループットと50%少ないメモリ使用量、さらに2倍長いコンテキスト長を可能にするFP8オンライン量子化でモデルをデプロイするには、次のようにします:

{% 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 quant を使用してください <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://735611837-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トークンのスループット）

| バッチ/入力/出力   | 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 = "今日は晴れた日で、私は"
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 = "今日は晴れた日で、私は"
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-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/jp/ji-chu/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.
