sglang について
SGLangは、LLMと視覚言語モデルを提供するフレームワークで、構造化生成とRadixAttentionによる共有プロンプト前置部分のキャッシュに対応します。エージェントのワークフローやマルチターンアプリ、推論サービスを構築するチーム向けです。
主な機能
- 01RadixAttentionによる前置部分のキャッシュ
- 02JSON・正規表現・文法による制約付き生成
- 03関数呼び出しワークフロー
- 04マルチモーダルな視覚モデル推論
- 05OpenAI互換API
活用シーン
- 01システムプロンプトを再利用するエージェントの提供
- 02スキーマに沿った出力の生成
- 03共有コンテキストでのマルチターン会話
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ orchestra-research/ ai-research-skills --skill sglangインストール後、Claude Code で/sglangを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
references/deployment.mdradix-attention.mdstructured-generation.md詳細
SGLang
RadixAttention による自動プレフィックスキャッシュを備えた、LLM と VLM 向けの高性能サービングフレームワークです。
SGLang を使うべき場合
SGLang を使うべき場合:
- 構造化された出力(JSON、正規表現、文法)が必要な場合
- 繰り返し使われるプレフィックス(システムプロンプト、ツール)を持つエージェントを構築する場合
- 関数呼び出しを伴うエージェントワークフローの場合
- 共有コンテキストを持つマルチターン会話の場合
- より高速な JSON デコーディングが必要な場合(標準比 3×)
代わりに vLLM を使うべき場合:
- 構造化なしのシンプルなテキスト生成の場合
- プレフィックスキャッシュが不要な場合
- 成熟しており、広く検証されている本番システムを求める場合
代わりに TensorRT-LLM を使うべき場合:
- 単一リクエストの最大レイテンシが重要な場合(バッチ処理が不要)
- NVIDIA のみの環境にデプロイする場合
- H100 で FP8/INT4 量子化が必要な場合
クイックスタート
インストール
# pip install (recommended)
pip install "sglang[all]"
# With FlashInfer (faster, CUDA 11.8/12.1)
pip install sglang[all] flashinfer -i https://flashinfer.ai/whl/cu121/torch2.4/
# From source
git clone https://github.com/sgl-project/sglang.git
cd sglang
pip install -e "python[all]"
サーバーの起動
# Basic server (Llama 3-8B)
python -m sglang.launch_server \
--model-path meta-llama/Meta-Llama-3-8B-Instruct \
--port 30000
# With RadixAttention (automatic prefix caching)
python -m sglang.launch_server \
--model-path meta-llama/Meta-Llama-3-8B-Instruct \
--port 30000 \
--enable-radix-cache # Default: enabled
# Multi-GPU (tensor parallelism)
python -m sglang.launch_server \
--model-path meta-llama/Meta-Llama-3-70B-Instruct \
--tp 4 \
--port 30000
基本的な推論
import sglang as sgl
# Set backend
sgl.set_default_backend(sgl.OpenAI("http://localhost:30000/v1"))
# Simple generation
@sgl.function
def simple_gen(s, question):
s += "Q: " + question + "\n"
s += "A:" + sgl.gen("answer", max_tokens=100)
# Run
state = simple_gen.run(question="What is the capital of France?")
print(state["answer"])
# Output: "The capital of France is Paris."
構造化 JSON 出力
import sglang as sgl
@sgl.function
def extract_person(s, text):
s += f"Extract person information from: {text}\n"
s += "Output JSON:\n"
# Constrained JSON generation
s += sgl.gen(
"json_output",
max_tokens=200,
regex=r'\{"name": "[^"]+", "age": \d+, "occupation": "[^"]+"\}'
)
# Run
state = extract_person.run(
text="John Smith is a 35-year-old software engineer."
)
print(state["json_output"])
# Output: {"name": "John Smith", "age": 35, "occupation": "software engineer"}
RadixAttention(主要なイノベーション)
機能: 共通のプレフィックスをリクエスト間で自動的にキャッシュし、再利用します。
パフォーマンス:
- 共有システムプロンプトを持つエージェントワークロードで 5× 高速
- 繰り返し例を含む few-shot プロンプティングで 10× 高速
- 設定不要 - 自動的に動作します
仕組み:
- 処理済みのすべてのトークンの基数木(radix tree)を構築
- 共有プレフィックスを自動的に検出
- 一致するプレフィックスの KV キャッシュを再利用
- 新しいトークンのみを計算
例(システムプロンプトを持つエージェント):
Request 1: [SYSTEM_PROMPT] + "What's the weather?"
→ Computes full prompt (1000 tokens)
Request 2: [SAME_SYSTEM_PROMPT] + "Book a flight"
→ Reuses system prompt KV cache (998 tokens)
→ Only computes 2 new tokens
→ 5× faster!
構造化生成パターン
スキーマ付き JSON
@sgl.function
def structured_extraction(s, article):
s += f"Article: {article}\n\n"
s += "Extract key information as JSON:\n"
# JSON schema constraint
schema = {
"type": "object",
"properties": {
"title": {"type": "string"},
"author": {"type": "string"},
"summary": {"type": "string"},
"sentiment": {"type": "string", "enum": ["positive", "negative", "neutral"]}
},
"required": ["title", "author", "summary", "sentiment"]
}
s += sgl.gen("info", max_tokens=300, json_schema=schema)
state = structured_extraction.run(article="...")
print(state["info"])
# Output: Valid JSON matching schema
正規表現で制約された生成
@sgl.function
def extract_email(s, text):
s += f"Extract email from: {text}\n"
s += "Email: "
# Email regex pattern
s += sgl.gen(
"email",
max_tokens=50,
regex=r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'
)
state = extract_email.run(text="Contact [email protected] for details")
print(state["email"])
# Output: "[email protected]"
文法ベースの生成
@sgl.function
def generate_code(s, description):
s += f"Generate Python code for: {description}\n"
s += "```python\n"
# EBNF grammar for Python
python_grammar = """
?start: function_def
function_def: "def" NAME "(" [parameters] "):" suite
parameters: parameter ("," parameter)*
parameter: NAME
suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT
"""
s += sgl.gen("code", max_tokens=200, grammar=python_grammar)
s += "\n```"
関数呼び出しを伴うエージェントワークフロー
import sglang as sgl
# Define tools
tools = [
{
"name": "get_weather",
"description": "Get weather for a location",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string"}
}
}
},
{
"name": "book_flight",
"description": "Book a flight",
"parameters": {
"type": "object",
"properties": {
"from": {"type": "string"},
"to": {"type": "string"},
"date": {"type": "string"}
}
}
}
]
@sgl.function
def agent_workflow(s, user_query, tools):
# System prompt (cached with RadixAttention)
s += "You are a helpful assistant with access to tools.\n"
s += f"Available tools: {tools}\n\n"
# User query
s += f"User: {user_query}\n"
s += "Assistant: "
# Generate with function calling
s += sgl.gen(
"response",
max_tokens=200,
tools=tools, # SGLang handles tool call format
stop=["User:", "\n\n"]
)
# Multiple queries reuse system prompt
state1 = agent_workflow.run(
user_query="What's the weather in NYC?",
tools=tools
)
# First call: Computes full system prompt
state2 = agent_workflow.run(
user_query="Book a flight to LA",
tools=tools
)
# Second call: Reuses system prompt (5× faster)
パフォーマンスベンチマーク
RadixAttention による高速化
Few-shot プロンプティング(プロンプト内に 10 個の例):
- vLLM: 2.5 秒/リクエスト
- SGLang: 0.25 秒/リクエスト(10× 高速)
- スループット: 4× 高い
エージェントワークフロー(1000 トークンのシステムプロンプト):
- vLLM: 1.8 秒/リクエスト
- SGLang: 0.35 秒/リクエスト(5× 高速)
JSON デコーディング:
- 標準: 45 tok/s
- SGLang: 135 tok/s(3× 高速)
スループット(Llama 3-8B、A100)
| ワークロード | vLLM | SGLang | 高速化率 |
|---|---|---|---|
| シンプルな生成 | 2500 tok/s | 2800 tok/s | 1.12× |
| Few-shot(10 例) | 500 tok/s | 5000 tok/s | 10× |
| エージェント(ツール呼び出し) | 800 tok/s | 4000 tok/s | 5× |
| JSON 出力 | 600 tok/s | 2400 tok/s | 4× |
マルチターン会話
@sgl.function
def multi_turn_chat(s, history, new_message):
# System prompt (always cached)
s += "You are a helpful AI assistant.\n\n"
# Conversation history (cached as it grows)
for msg in history:
s += f"{msg['role']}: {msg['content']}\n"
# New user message (only new part)
s += f"User: {new_message}\n"
s += "Assistant: "
s += sgl.gen("response", max_tokens=200)
# Turn 1
history = []
state = multi_turn_chat.run(history=history, new_message="Hi there!")
history.append({"role": "User", "content": "Hi there!"})
history.append({"role": "Assistant", "content": state["response"]})
# Turn 2 (reuses Turn 1 KV cache)
state = multi_turn_chat.run(history=history, new_message="What's 2+2?")
# Only computes new message (much faster!)
# Turn 3 (reuses Turn 1 + Turn 2 KV cache)
state = multi_turn_chat.run(history=history, new_message="Tell me a joke")
# Progressively faster as history grows
高度な機能
投機的デコーディング
# Launch with draft model (2-3× faster)
python -m sglang.launch_server \
--model-path meta-llama/Meta-Llama-3-70B-Instruct \
--speculative-model meta-llama/Meta-Llama-3-8B-Instruct \
--speculative-num-steps 5
マルチモーダル(ビジョンモデル)
@sgl.function
def describe_image(s, image_path):
s += sgl.image(image_path)
s += "Describe this image in detail: "
s += sgl.gen("description", max_tokens=200)
state = describe_image.run(image_path="photo.jpg")
print(state["description"])
バッチ処理と並列リクエスト
# Automatic batching (continuous batching)
states = sgl.run_batch(
[
simple_gen.bind(question="What is AI?"),
simple_gen.bind(question="What is ML?"),
simple_gen.bind(question="What is DL?"),
]
)
# All 3 processed in single batch (efficient)
OpenAI 互換 API
# Start server with OpenAI API
python -m sglang.launch_server \
--model-path meta-llama/Meta-Llama-3-8B-Instruct \
--port 30000
# Use with OpenAI client
curl http://localhost:30000/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "default",
"messages": [
{"role": "system", "content": "You are helpful"},
{"role": "user", "content": "Hello"}
],
"temperature": 0.7,
"max_tokens": 100
}'
# Works with OpenAI Python SDK
from openai import OpenAI
client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY")
response = client.chat.completions.create(
model="default",
messages=[{"role": "user", "content": "Hello"}]
)
対応モデル
テキストモデル:
- Llama 2、Llama 3、Llama 3.1、Llama 3.2
- Mistral、Mixtral
- Qwen、Qwen2、QwQ
- DeepSeek-V2、DeepSeek-V3
- Gemma、Phi-3
ビジョンモデル:
- LLaVA、LLaVA-OneVision
- Phi-3-Vision
- Qwen2-VL
HuggingFace の 100 以上のモデル
ハードウェアサポート
NVIDIA: A100、H100、L4、T4(CUDA 11.8 以降) AMD: MI300、MI250(ROCm 6.0 以降) Intel: GPU 搭載の Xeon(近日対応予定) Apple: MPS 経由の M1/M2/M3(実験的対応)
参考資料
- 構造化生成ガイド - JSON スキーマ、正規表現、文法、検証
- RadixAttention 詳解 - 仕組み、最適化、ベンチマーク
- 本番環境へのデプロイ - マルチ GPU、モニタリング、オートスケーリング
リソース
- GitHub: https://github.com/sgl-project/sglang
- ドキュメント: https://sgl-project.github.io/
- 論文: RadixAttention(arXiv:2312.07104)
- Discord: https://discord.gg/sglang
コメント
Markdown 対応