# 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-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 compile を無効にする
4. --disable-cuda-graph で CUDA グラフを無効にする。（推奨されません。大幅な性能低下）
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&#x26;token=e7a5170b-eabb-4a11-ae4b-f27a11213ae3" alt=""><figcaption></figcaption></figure>

その後、OpenAI Chat completionsライブラリを使用してモデルを呼び出すことができます（別のターミナルまたはtmuxを使用）：

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

そして次のような結果が得られます `2 + 2 = 4.`

### 🦥SGLangでのUnslothファインチューンのデプロイ

ファインチューニング後 [fine-tuning-llms-guide](https://unsloth.ai/docs/jp/meru/fine-tuning-llms-guide "mention") または当社のノートブックを使用して [unsloth-notebooks](https://unsloth.ai/docs/jp/meru/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 デプロイガイド

以下は、をトレーニングして [gpt-oss](https://unsloth.ai/docs/jp/moderu/gpt-oss-how-to-run-and-fine-tune)Unslothで-20bを使用してSGLangでデプロイする手順付きのステップバイステップチュートリアルです。複数の量子化フォーマットでの性能ベンチマークを含みます。

{% stepper %}
{% step %}

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

ファインチューニングが初めての場合は、私たちの [ガイド](https://unsloth.ai/docs/jp/meru/fine-tuning-llms-guide)を読むか、gpt-oss 20B ファインチューニングノートブックをで試してみてください [gpt-oss-how-to-run-and-fine-tune](https://unsloth.ai/docs/jp/moderu/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%減少し、コンテキスト長のサポートが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://735611837-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>

我々は gpt-oss-20b を B200x1 GPU で使用し、以下の結果を得ました（約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-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: 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://unsloth.ai/docs/jp/ji-ben/inference-and-deployment/sglang-guide.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.
