SGLang 빠른 시작
SGLang 빠른 시작 (Quickstart)
SGLang을 처음 써보려면 어디서부터 시작해야 할지 막막할 수 있어요. 설치하고, 서버를 띄우고, 첫 요청을 보내기까지의 흐름을 한 번에 따라 해보면 됩니다. 이 글을 마치면 SGLang 서버 하나가 프롬프트에 응답하는 모습을 직접 보게 돼요.
준비 사항 (Prerequisites)
먼저 환경이 맞는지 확인해요.
- Python: 3.10 이상
- GPU: CUDA를 지원하는 NVIDIA GPU (sm80 이상, 예: A10, A100, L4, L40S, H100)
- OS: Linux (권장)
다른 플랫폼은 전용 가이드가 따로 있어요. AMD GPU, Intel Xeon CPU, Google TPU, NVIDIA Jetson, Ascend NPU, Intel XPU 문서를 참고하면 됩니다.
설치 (Installation)
설치 방법이 여러 가지라 상황에 맞게 고르면 됩니다.
pip / uv (권장): uv를 쓰면 설치가 더 빨라요.
pip install --upgrade pip
pip install uv
uv pip install --prerelease=allow sglang
소스에서 설치: 직접 클론해서 설치하는 방식이에요.
# Clone and install from source
git clone https://github.com/sgl-project/sglang.git
cd sglang
pip install --upgrade pip
pip install -e "python"
Docker: Docker 이미지는 Docker Hub의 lmsysorg/sglang에서 받을 수 있어요. <secret> 자리에는 Hugging Face 토큰을 넣습니다.
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 meta-llama/Llama-3.1-8B-Instruct --host 0.0.0.0 --port 30000
프로덕션 배포라면 크기가 약 40% 줄어든 runtime 변형을 쓰는 편이 좋아요.
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-runtime \
python3 -m sglang.launch_server --model-path meta-llama/Llama-3.1-8B-Instruct --host 0.0.0.0 --port 30000
OSError: CUDA_HOME environment variable is not set같은 오류가 나면 CUDA 설치 루트를 가리키는 환경변수를 설정해 주세요.export CUDA_HOME=/usr/local/cuda-<your-cuda-version>
서버 실행 (Launch a Server)
모델을 지정해 SGLang 서버를 띄웁니다. 여기서는 가벼운 예시로 qwen/qwen2.5-0.5b-instruct를 써요.
python3 -m sglang.launch_server --model-path qwen/qwen2.5-0.5b-instruct --host 0.0.0.0 --port 30000
터미널에 The server is fired up and ready to roll!이라는 문구가 보일 때까지 기다리면 됩니다.
서버가 떠 있으면 API 문서도 함께 제공돼요.
- Swagger UI:
http://localhost:30000/docs- ReDoc:
http://localhost:30000/redoc- OpenAPI Spec:
http://localhost:30000/openapi.json
서버는 Hugging Face 토크나이저의 채팅 템플릿을 자동으로 적용합니다. 다른 템플릿을 쓰고 싶으면 서버 실행 시
--chat-template로 덮어쓸 수 있어요.
요청 보내기 (Send Requests)
SGLang은 OpenAI API와 완전히 호환돼서, 이미 알고 있는 도구와 라이브러리를 그대로 쓸 수 있어요.
cURL로 보내기
curl http://localhost:30000/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "qwen/qwen2.5-0.5b-instruct",
"messages": [
{"role": "user", "content": "What is the capital of France?"}
]
}'
OpenAI Python 클라이언트로 보내기
먼저 openai 라이브러리가 있어야 해요.
pip install openai
그다음 요청을 보내면 됩니다.
import openai
client = openai.Client(base_url="http://127.0.0.1:30000/v1", api_key="None")
response = client.chat.completions.create(
model="qwen/qwen2.5-0.5b-instruct",
messages=[
{"role": "user", "content": "List 3 countries and their capitals."},
],
temperature=0,
max_tokens=64,
)
print(response.choices[0].message.content)
스트리밍 (Streaming)
전체 답변을 기다리지 않고 토큰이 생길 때마다 조각조각 받으려면 stream=True를 씁니다.
import openai
client = openai.Client(base_url="http://127.0.0.1:30000/v1", api_key="None")
response = client.chat.completions.create(
model="qwen/qwen2.5-0.5b-instruct",
messages=[
{"role": "user", "content": "List 3 countries and their capitals."},
],
temperature=0,
max_tokens=64,
stream=True,
)
for chunk in response:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
Python requests로 보내기
import requests
url = "http://localhost:30000/v1/chat/completions"
data = {
"model": "qwen/qwen2.5-0.5b-instruct",
"messages": [{"role": "user", "content": "What is the capital of France?"}],
}
response = requests.post(url, json=data)
print(response.json())
네이티브 /generate API로 보내기
조금 더 유연한 네이티브 /generate 엔드포인트도 제공돼요.
import requests
response = requests.post(
"http://localhost:30000/generate",
json={
"text": "The capital of France is",
"sampling_params": {
"temperature": 0,
"max_new_tokens": 32,
},
},
)
print(response.json())
/generate로 스트리밍하기
import requests
import json
response = requests.post(
"http://localhost:30000/generate",
json={
"text": "The capital of France is",
"sampling_params": {
"temperature": 0,
"max_new_tokens": 32,
},
"stream": True,
},
stream=True,
)
prev = 0
for chunk in response.iter_lines(decode_unicode=False):
chunk = chunk.decode("utf-8")
if chunk and chunk.startswith("data:"):
if chunk == "data: [DONE]":
break
data = json.loads(chunk[5:].strip("\n"))
output = data["text"]
print(output[prev:], end="", flush=True)
prev = len(output)
오프라인 배치 추론 (서버 없이)
HTTP 서버가 필요 없는 상황도 있어요. Engine 클래스를 직접 만들어 오프라인 배치 추론을 돌릴 수 있습니다.
import sglang as sgl
llm = sgl.Engine(model_path="qwen/qwen2.5-0.5b-instruct")
prompts = [
"Hello, my name is",
"The president of the United States is",
"The capital of France is",
"The future of AI is",
]
sampling_params = {"temperature": 0.8, "top_p": 0.95}
outputs = llm.generate(prompts, sampling_params)
for prompt, output in zip(prompts, outputs):
print(f"Prompt: {prompt}\nGenerated text: {output['text']}\n")
llm.shutdown()
흔한 트러블슈팅 (Common Troubleshooting)
자주 겪는 문제와 해결책을 정리해 두었어요.
CUDA_HOME 미설정: CUDA_HOME 환경변수를 CUDA 설치 루트로 지정해 주세요.
export CUDA_HOME=/usr/local/cuda-<your-cuda-version>
FlashInfer 이슈 (sm75+ 기기): 서버 실행 시 다른 백엔드로 전환하면 됩니다.
--attention-backend triton --sampling-backend pytorch
FlashInfer 재설치: 강제로 재설치하고 캐시를 지워주면 됩니다.
pip3 install --upgrade flashinfer-python --force-reinstall --no-deps
rm -rf ~/.cache/flashinfer
B300/GB300 (sm_103a)의 ptxas 오류:
export TRITON_PTXAS_PATH=/usr/local/cuda/bin/ptxas
더 알아보기 (Learn more)
- 공식 문서의 설치는 Install SGLang에서 자세히 다뤄요.
- 요청 보내는 다양한 예시는 Sending a request를 참고해요.
- 네이티브 API에 대한 설명은 SGLang Native APIs에서 이어져요.