추측 디코딩
추측 디코딩 (Speculative Decoding)
SGLang은 여러 추측 디코딩(speculative decoding) 옵션을 제공합니다. EAGLE-2/EAGLE-3, MTP, UNO, DFLASH, 클래식 드래프트 모델 디코딩, NGRAM 기반 변형이 여기에 포함됩니다. 구현은 속도와 효율을 최대화하는 것을 목표로 하며, 오픈소스 LLM 엔진 중 가장 빠른 축에 속합니다.
출처: 문서
본문
SGLang은 EAGLE-2/EAGLE-3, MTP, UNO, DFLASH, 클래식 드래프트 모델 디코딩, NGRAM 기반 변형 등 여러 추측 디코딩 옵션을 제공합니다. 구현은 속도와 효율을 최대화하는 것을 목표로 하며, 오픈소스 LLM 엔진 중 가장 빠른 것으로 간주됩니다.
요약 (Summary)
섹션으로 이동 (Jump to sections)
- EAGLE Decoding
- Multi Token Prediction
- UNO decoding
- DFlash Decoding
- Standalone Speculative Decoding (Small Draft Model)
- Speculative Decoding V2 (Overlap Scheduler)
- Ngram Speculative Decoding
- Full Parameter Reference
- OOM Troubleshooting
- References
빠른 가이드 (Quick guidance)
- 최고 속도/품질 (권장):
--speculative-algorithm EAGLE3으로 EAGLE-3 사용. - 강력한 기본 / 넓은 호환성:
--speculative-algorithm EAGLE으로 EAGLE-2 사용. - 시간에 따라 워크로드 수용도가 변하는 경우:
--speculative-eagle-topk 1로 EAGLE 위에 Adaptive speculative decoding 사용. - EAGLE-2의 낮은
lm_head오버헤드:--speculative-token-map으로 FR-Spec 활성화. - 모델이 MTP 지원: 추측 디코딩으로 MTP 사용(종종 작은
speculative_num_steps/topk/num_draft_tokens, 예제 섹션 참고). - 대상 모델용 UNO 어댑터 보유:
--speculative-algorithm UNO와--uno-lora-path ...으로 UNO 사용. - DFlash 드래프트 체크포인트 보유:
--speculative-algorithm DFLASH와--speculative-draft-model-path ...으로 DFLASH 사용. - 더 작은 드래프트 LLM 보유: STANDALONE 사용(
--speculative-algorithm STANDALONE). - 추가 모델 없음: NGRAM 사용(
--speculative-algorithm NGRAM, CUDA 전용).
방법 비교 (미니 테이블) (Method comparison)
| Method | Draft source | Separate draft model? | How to enable | Notes / constraints |
|---|---|---|---|---|
| EAGLE-2 | EAGLE 드래프트 모델 (feature drafting + tree) | 일반적으로 예 | --speculative-algorithm EAGLE + --speculative-draft-model-path ... |
--speculative-num-steps, --speculative-eagle-topk, --speculative-num-draft-tokens 튜닝 |
EAGLE-2 + torch.compile |
EAGLE-2와 동일 | 일반적으로 예 | --enable-torch-compile 추가 (선택적으로 --torch-compile-max-bs) |
이점은 하드웨어/모델에 따라 다름; 검증 필요 |
| EAGLE-2 + FR-Spec | EAGLE-2 + 토큰 서브셋과 동일 | 일반적으로 예 | --speculative-token-map ... 추가 |
고빈도 토큰 어휘로 lm_head 오버헤드 줄임 |
| EAGLE-3 | EAGLE3 드래프트 모델 | 예 | --speculative-algorithm EAGLE3 + --speculative-draft-model-path ... |
아래 벤치마크에서 최고 처리량 |
| MTP | 내장 멀티 토큰 헤드 (모델별) | 대개 아니오 | Multi Token Prediction 섹션 참고 | 추측 워크플로우 사용; 일부 모델은 드래프트 경로 자동 처리 |
| UNO | 훈련된 UNO LoRA가 있는 대상 모델 (linear chain 또는 tree) | 아니오 | --speculative-algorithm UNO + --uno-lora-path ... |
CUDA 및 FA3; 현재 TP=PP=1 필요 |
| DFLASH | DFlash 드래프트 모델 (linear block verification) | 예 | --speculative-algorithm DFLASH + --speculative-draft-model-path ... |
--enable-dp-attention 없음; pp_size == 1; overlap scheduler·mixed chunked prefill 비활성 |
| STANDALONE | 더 작은 드래프트 LLM (token-level) | 예 | --speculative-algorithm STANDALONE + --speculative-draft-model-path ... |
--enable-dp-attention 미지원 |
| NGRAM | 이전 토큰의 Ngram 캐시 | 아니오 | --speculative-algorithm NGRAM |
CUDA 전용; --enable-dp-attention 없음; overlap scheduler·mixed chunked prefill 비활성 |
성능 하이라이트 (Performance Highlights)
MT bench로 테스트한 LLaMA-Instruct 3.1 8B의 처리량에서 EAGLE3 디코딩이 달성하는 큰 개선을 아래에서 확인하세요. 자세한 내용은 EAGLE3 논문을 참고하세요.
| Method | Throughput (tokens/s) |
|---|---|
| SGLang (w/o speculative, 1x H100) | 158.34 tokens/s |
| SGLang + EAGLE-2 (1x H100) | 244.10 tokens/s |
| SGLang + EAGLE-3 (1x H100) | 373.25 tokens/s |
EAGLE 디코딩 (EAGLE Decoding)
EAGLE 추측 디코딩 활성화에 관련된 파라미터:
| Parameter | Description | Default |
|---|---|---|
--speculative-draft-model-path |
드래프트 모델 경로/가중치. EAGLE/EAGLE3·STANDALONE에 일반적으로 필요. 일부 MTP 지원 모델은 생략 가능. | None |
--speculative-num-steps |
자동회귀 드래프팅 깊이. 추측 범위를 늘리지만 거부 연쇄(rejection cascade) 위험. | Auto (5 for Llama/Grok; 3 for many other models) |
--speculative-eagle-topk |
단계별 분기 계수. 후보 다양성과 수용도를 높이지만 메모리/계산 증가. | Auto (4 for Llama/Grok; 1 for many other models) |
--speculative-num-draft-tokens |
최대 병렬 검증 용량. 더 깊은 트리 평가를 가능하게 하지만 GPU 메모리 사용 증가. | Auto (8 for Llama/Grok; 4 for many other models). topk=1이면 num_steps + 1로 조정. |
--speculative-accept-threshold-single |
단일 토큰 검증의 수용 임계값. 낮을수록 더 공격적으로 수용. | 1.0 |
--speculative-accept-threshold-acc |
단계 전반의 누적 수용 임계값. | 1.0 |
--speculative-attention-mode |
추측 연산의 어텐션 모드 (prefill 또는 decode). target 검증과 드래프트 확장 모두에 영향. |
"prefill" |
--speculative-draft-attention-backend |
드래프트 모델의 어텐션 백엔드 오버라이드. | None (target과 동일) |
--speculative-dsa-topk-backend |
--dsa-topk-backend와 독립적으로 추측 드래프트 워커의 DSA indexer top-k 백엔드 선택. 옵션: sgl-kernel, torch, flashinfer. torch는 SGLANG_DSA_FUSE_TOPK=false 필요. |
sgl-kernel |
--speculative-draft-model-quantization |
드래프트 모델의 양자화 방법. target 모델이 양자화되어도 강제로 무양자화하려면 "unquant" 사용. |
target 모델과 동일 |
--speculative-draft-model-revision |
로드할 드래프트 모델의 특정 revision/commit. | None (--speculative-draft-model-path 설정·revision 생략 시 "main"으로 자동 설정) |
--speculative-draft-load-format |
드래프트 모델 가중치의 로드 포맷. | None |
이 파라미터들은 대부분 EAGLE-2와 EAGLE-3에서 동일합니다. --speculative-token-map은 EAGLE-3 모델에서 무시됩니다.
--speculative-num-steps, --speculative-eagle-topk, --speculative-num-draft-tokens에 대해서는 세 가지 모두 미설정으로 두면 auto-tuning을 사용하고, 튜닝할 때는 세 가지 모두 명시적으로 설정하세요.
--speculative-eagle-topk 1로 EAGLE를 사용하고 요청 간 수용률이 다르면 Adaptive Speculative Decoding 참고하세요.
이 파라미터의 최상의 조합은 bench_speculative.py로 찾을 수 있습니다.
EAGLE-2 디코딩 (EAGLE-2 Decoding)
--speculative-algorithm EAGLE를 설정하고 적절한 모델을 선택해 EAGLE-2 디코딩을 활성화할 수 있습니다.
서버 시작:
python3 -m sglang.launch_server \
--model meta-llama/Llama-2-7b-chat-hf \
--speculative-algorithm EAGLE \
--speculative-draft-model-path lmsys/sglang-EAGLE-llama2-chat-7B \
--speculative-num-steps 3 \
--speculative-eagle-topk 4 \
--speculative-num-draft-tokens 16 \
--mem-fraction-static 0.7 \
--cuda-graph-max-bs-decode 8 \
--log-level warning
요청 보내기:
import openai
client = openai.Client(base_url="http://127.0.0.1:30000/v1", api_key="None")
response = client.chat.completions.create(
model="meta-llama/Llama-2-7b-chat-hf",
messages=[
{"role": "user", "content": "List 3 countries and their capitals."},
],
temperature=0,
max_tokens=64,
)
print(response.choices[0].message.content)
EAGLE-2 디코딩 + torch.compile
선택적으로 torch.compile을 활성화해 드래프트 모델에 커널 수준 최적화(연산자 융합, autotune)를 적용할 수 있습니다. 실제 속도 향상은 하드웨어, 모델 아키텍처, 배치 크기에 따라 달라집니다. 일부 구성(예: cuBLAS가 이미 최적이고 CUDA 그래프가 활성화된 H100의 작은 드래프트 모델)에서는 이점이 미미할 수 있습니다. 자신의 설정에서 이 플래그 유·무로 벤치마크해 도움이 되는지 확인하는 것을 권장합니다.
활성화하려면 --enable-torch-compile을 추가하고 선택적으로 --torch-compile-max-bs를 설정하세요:
python3 -m sglang.launch_server \
--model meta-llama/Llama-2-7b-chat-hf \
--speculative-algorithm EAGLE \
--speculative-draft-model-path lmsys/sglang-EAGLE-llama2-chat-7B \
--speculative-num-steps 3 \
--speculative-eagle-topk 4 \
--speculative-num-draft-tokens 16 \
--mem-fraction-static 0.7 \
--enable-torch-compile \
--torch-compile-max-bs 8 \
--log-level warning
요청 보내기:
import openai
client = openai.Client(base_url="http://127.0.0.1:30000/v1", api_key="None")
response = client.chat.completions.create(
model="meta-llama/Llama-2-7b-chat-hf",
messages=[
{"role": "user", "content": "List 3 countries and their capitals."},
],
temperature=0,
max_tokens=64,
)
print(response.choices[0].message.content)
EAGLE-2 디코딩 via Frequency-Ranked Speculative Sampling
드래프트 모델에서 잘린 고빈도 토큰 어휘를 사용하면, EAGLE 추측 디코딩은 품질 저하 없이 파이프라인을 가속하면서 lm_head 계산 오버헤드를 줄입니다. 자세한 내용은 the paper를 참고하세요.
구현에서 --speculative-token-map을 설정해 이 최적화를 활성화합니다. FR-Spec의 고빈도 토큰은 이 모델에서 얻을 수 있습니다. 또는 이 저장소에서 고빈도 토큰을 직접 다운로드할 수도 있습니다.
Weilin Zhao와 Zhousx의 기여에 감사드립니다.
python3 -m sglang.launch_server \
--model meta-llama/Meta-Llama-3-8B-Instruct \
--speculative-algorithm EAGLE \
--speculative-draft-model-path lmsys/sglang-EAGLE-LLaMA3-Instruct-8B \
--speculative-num-steps 3 \
--speculative-eagle-topk 4 \
--speculative-num-draft-tokens 16 \
--speculative-token-map thunlp/LLaMA3-Instruct-8B-FR-Spec/freq_32768.pt \
--mem-fraction-static 0.7 \
--cuda-graph-max-bs-decode 8 \
--dtype float16 \
--log-level warning
요청 보내기:
import openai
client = openai.Client(base_url="http://127.0.0.1:30000/v1", api_key="None")
response = client.chat.completions.create(
model="meta-llama/Meta-Llama-3-8B-Instruct",
messages=[
{"role": "user", "content": "List 3 countries and their capitals."},
],
temperature=0,
max_tokens=64,
)
print(response.choices[0].message.content)
EAGLE-3 디코딩 (EAGLE-3 Decoding)
--speculative-algorithm EAGLE3을 설정하고 적절한 모델을 선택해 EAGLE-3 디코딩을 활성화할 수 있습니다.
python3 -m sglang.launch_server \
--model meta-llama/Meta-Llama-3.1-8B-Instruct \
--speculative-algorithm EAGLE3 \
--speculative-draft-model-path jamesliu1/sglang-EAGLE3-Llama-3.1-Instruct-8B \
--speculative-num-steps 3 \
--speculative-eagle-topk 4 \
--speculative-num-draft-tokens 16 \
--mem-fraction-static 0.7 \
--cuda-graph-max-bs-decode 8 \
--dtype float16 \
--log-level warning
요청 보내기:
import openai
client = openai.Client(base_url="http://127.0.0.1:30000/v1", api_key="None")
response = client.chat.completions.create(
model="meta-llama/Meta-Llama-3.1-8B-Instruct",
messages=[
{"role": "user", "content": "List 3 countries and their capitals."},
],
temperature=0,
max_tokens=64,
)
print(response.choices[0].message.content)
멀티 토큰 예측 (Multi Token Prediction)
SGLang에서 MTP (Multi-Token Prediction)를 추측 디코딩으로 지원합니다. 여기서는 XiaomiMiMo/MiMo-7B-RL을 예로 사용합니다(DeepSeek MTP 사용은 DeepSeek-V3.2 cookbook §4.2.3 참고).
python3 -m sglang.launch_server \
--model XiaomiMiMo/MiMo-7B-RL \
--host 0.0.0.0 \
--trust-remote-code \
--speculative-algorithm EAGLE \
--speculative-num-steps 1 \
--speculative-eagle-topk 1 \
--speculative-num-draft-tokens 2 \
--mem-fraction-static 0.7 \
--cuda-graph-max-bs-decode 8 \
--log-level warning
DSA 기반 MTP의 경우 드래프트 워커가 기본적으로 sgl-kernel top-k 백엔드를 사용합니다. --speculative-dsa-topk-backend로 target 모델의 --dsa-topk-backend와 독립적으로 드래프트를 오버라이드하세요.
요청 보내기:
import requests
url = "http://localhost:30000/v1/chat/completions"
data = {
"model": "XiaomiMiMo/MiMo-7B-RL",
"messages": [{"role": "user", "content": "What is the capital of France?"}],
}
response = requests.post(url, json=data)
print(response.json())
UNO 디코딩 (UNO decoding)
UNO는 별도의 드래프트 모델을 로드하는 대신, 각 추측 디코드 사이클의 두 패스에 target 트랜스포머를 재사용합니다. 드래프트 forward 동안 각 요청의 첫 행은 base 가중치를, 나머지 B - 1 행은 훈련된 UNO LoRA를 사용합니다. Target 검증은 완전히 base 전용입니다.
UNO는 두 가지 샘플링 모드를 제공합니다:
- Linear는 DFlash의 제안 레이아웃과 유사하게 드래프트 토큰 체인 하나를 구성·검증합니다.
- Tree는 각 드래프트 깊이에서 여러 후보를 확장하고 SGLang의 EAGLE tree-verification 경로를 사용합니다.
UNO 모드에서 세 숫자는 B/K/V입니다: 드래프트 forward 폭, 확장당 유지 후보 수, 검증 폭. 따라서 Linear 8/1/8은 8-토큰 드래프트 폭, 확장당 후보 1개, 8-토큰 검증 폭을 사용합니다. UNO의 K는 제안 트리 폭을 제어하며 요청 샘플링 파라미터 top_k와 무관합니다. 명령줄 매핑은 모드에 따라 다릅니다:
- Linear 모드에서
B와V는 모두--speculative-num-draft-tokens입니다.--speculative-num-steps 1과--speculative-eagle-topk 1을 설정하세요. - Tree 모드에서
B는--speculative-num-steps + 1,K는--speculative-eagle-topk,V는--speculative-num-draft-tokens입니다.
정확한 target 모델 체크포인트에 대해 훈련된 어댑터를 사용하세요. 현재 통합은 Qwen/Qwen3-8B로 검증되었으며, 지원되지 않는 LoRA target 레이어는 시작 시 거부됩니다. 서버를 시작하기 전에 어댑터의 로컬 경로나 Hugging Face 저장소를 설정하세요:
Linear 8/1/8
export UNO_LORA_PATH="s-sahoo/uno-qwen3-8B"
sglang serve \
--model-path Qwen/Qwen3-8B \
--speculative-algorithm UNO \
--uno-lora-path "$UNO_LORA_PATH" \
--speculative-num-steps 1 \
--speculative-eagle-topk 1 \
--speculative-num-draft-tokens 8 \
--attention-backend fa3 \
--tp 1 \
--host 0.0.0.0 \
--port 30000
Tree 8/32/8
K가 1보다 크므로 다음 명령은 tree 모드를 선택합니다.
export UNO_LORA_PATH="s-sahoo/uno-qwen3-8B"
sglang serve \
--model-path Qwen/Qwen3-8B \
--speculative-algorithm UNO \
--uno-lora-path "$UNO_LORA_PATH" \
--speculative-num-steps 7 \
--speculative-eagle-topk 32 \
--speculative-num-draft-tokens 8 \
--attention-backend fa3 \
--tp 1 \
--host 0.0.0.0 \
--port 30000
표준 OpenAI 호환 API로 요청을 보내세요:
import openai
client = openai.Client(base_url="http://127.0.0.1:30000/v1", api_key="None")
response = client.chat.completions.create(
model="Qwen/Qwen3-8B",
messages=[{"role": "user", "content": "Explain speculative decoding."}],
max_tokens=128,
)
print(response.choices[0].message.content)
핵심 요구사항과 한계 (Key requirements and limitations)
- UNO는 prefill·decode용 FA3를 갖춘 CUDA, 텐서·파이프라인 병렬 크기 1, DP attention·context parallelism 없음이 필요합니다.
--uno-lora-path는 UNO의 고정 내부 어댑터를 로드하며 요청 선택 가능한 Multi-LoRA 서빙과 결합할 수 없습니다.- UNO는 자체 확률적 검증을 관리하므로
--speculative-use-rejection-sampling을 설정하지 마세요. - 문법 디코딩, 반환 logprobs·hidden states, 샘플링 패널티,
min_p, logit bias, 커스텀 logit 프로세서, strict thinking, 결정적 추론은 아직 지원되지 않습니다. - Tree 모드에서 두 추측 수용 임계값 모두 1.0이어야 하고,
V는 최소B이면서 최대 128,V * K는 2048을 넘지 않아야 합니다. SGLang은 시작 시 나머지 tree-capacity·EAGLE parent-representation 제약을 검증합니다. - Mixed chunked prefill은 UNO에서 비활성화됩니다.
- 일반 overlap 스케줄링은 지원됩니다. Tree 모드는 아직 PDMux나 별도의
--enable-two-batch-overlap기능을 지원하지 않습니다.
DFlash 디코딩 (DFlash Decoding)
SGLang은 전용 드래프트 모델 체크포인트를 사용하는 DFLASH 추측 디코딩도 지원합니다. EAGLE 스타일 트리 검증과 달리 DFLASH는 선형 드래프트 블록을 검증하며 블록 크기/드래프트 윈도우를 중심으로 구성됩니다. 이 경로는 target 모델에 맞는 DFlash 드래프트 체크포인트가 있을 때 유용합니다. 예: meta-llama/Llama-3.1-8B-Instruct + z-lab/LLaMA3.1-8B-Instruct-DFlash-UltraChat.
관련 파라미터:
| Parameter | Description | Default |
|---|---|---|
--speculative-draft-model-path |
필수 DFlash 드래프트 모델 경로/가중치. | None |
--speculative-num-draft-tokens |
DFlash 검증 블록 크기. | 드래프트 설정에서 추론, 아니면 16 |
--speculative-dflash-block-size |
DFlash용 --speculative-num-draft-tokens의 별칭. |
None |
--speculative-draft-window-size |
드래프트 KV 슬라이딩 윈도우 크기. 설정 시 >= speculative-num-draft-tokens여야 함. |
None |
python3 -m sglang.launch_server \
--model meta-llama/Llama-3.1-8B-Instruct \
--speculative-algorithm DFLASH \
--speculative-draft-model-path z-lab/LLaMA3.1-8B-Instruct-DFlash-UltraChat
요청 보내기:
import openai
client = openai.Client(base_url="http://127.0.0.1:30000/v1", api_key="None")
response = client.chat.completions.create(
model="meta-llama/Llama-3.1-8B-Instruct",
messages=[
{"role": "user", "content": "Write a quicksort implementation in Python."},
],
temperature=0,
max_tokens=128,
)
print(response.choices[0].message.content)
독립형 추측 디코딩 (작은 드래프트 모델) (Standalone Speculative Decoding, Small Draft Model)
EAGLE/MTP 외에도 SGLang은 더 작은 드래프트 모델을 사용한 토큰 수준 추측 디코딩을 지원합니다. --speculative-algorithm STANDALONE으로 활성화하고 --speculative-draft-model-path로 드래프트 모델을 제공하세요.
관련 파라미터:
| Parameter | Description | Default |
|---|---|---|
--speculative-draft-model-path |
드래프트 모델 가중치 (target 모델보다 작음). | None |
--speculative-num-steps |
드래프트 깊이 (드래프트 모델이 자동회귀로 실행하는 단계 수). | 3 (STANDALONE 자동 기본) |
--speculative-eagle-topk |
분기 계수 (단계별 토큰 후보 수). | 1 (STANDALONE 자동 기본) |
--speculative-num-draft-tokens |
검증 용량. | 4 (STANDALONE 자동 기본) |
--speculative-draft-model-quantization |
드래프트 모델용 양자화. target이 양자화되어도 드래프트 양자화를 비활성화하려면 "unquant" 사용. |
target과 동일 |
참고: 독립형 추측 디코딩은 현재
--enable-dp-attention을 지원하지 않습니다.
python3 -m sglang.launch_server \
--model Qwen/Qwen2.5-7B-Instruct \
--speculative-algorithm STANDALONE \
--speculative-draft-model-path Qwen/Qwen2.5-1.5B-Instruct \
--speculative-num-steps 4 \
--speculative-eagle-topk 2 \
--speculative-num-draft-tokens 7 \
--mem-fraction-static 0.7 \
--cuda-graph-max-bs-decode 8 \
--log-level warning
요청 보내기:
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-7B-Instruct",
messages=[
{"role": "user", "content": "List 3 countries and their capitals."},
],
temperature=0,
max_tokens=64,
)
print(response.choices[0].message.content)
추측 디코딩 V2 (오버랩 스케줄러) (Speculative Decoding V2, Overlap Scheduler)
추측 디코딩은 기본적으로 활성화된 overlap 스케줄러로 V2 추측 워커(예: StandaloneWorkerV2, EAGLEWorkerV2)를 실행합니다. --disable-overlap-schedule을 전달하면 동기(비오버랩) 경로로 폴백합니다.
참고:
- Overlap 스케줄러는 현재
--speculative-eagle-topk 1만 지원합니다.--speculative-eagle-topk 1을 명시적으로 설정하세요. --speculative-eagle-topk > 1을 명시적으로 설정하면 서버가 오류를 냅니다.--speculative-eagle-topk를 생략하면 일부 모델(예: Llama)에서 auto-tuning이topk > 1을 고를 수 있습니다. 이는 overlap 스케줄러와 호환되지 않으며 항상 즉시 설정 오류를 트리거하지는 않을 수 있으므로--speculative-eagle-topk 1을 명시적으로 설정하세요.
python3 -m sglang.launch_server \
--model Qwen/Qwen2.5-7B-Instruct \
--speculative-algorithm STANDALONE \
--speculative-draft-model-path Qwen/Qwen2.5-1.5B-Instruct \
--speculative-num-steps 4 \
--speculative-eagle-topk 1 \
--speculative-num-draft-tokens 5 \
--mem-fraction-static 0.7 \
--cuda-graph-max-bs-decode 8 \
--log-level warning
Ngram 추측 디코딩 (Ngram Speculative Decoding)
SGLang은 ngram 기반 추측 디코딩(별도 드래프트 모델 없음)도 지원합니다. 이전에 생성된 토큰으로 만든 ngram 캐시에서 드래프트 토큰을 가져온 뒤 target 모델로 검증합니다.
활성화:
--speculative-algorithm NGRAM
Ngram 전용 파라미터 (Ngram-specific parameters)
| Parameter | Description | Default |
|---|---|---|
--speculative-num-draft-tokens |
단계별 검증되는 드래프트 토큰 수. 생략 시 min(--speculative-ngram-max-trie-depth, 12). |
12 (기본 ngram 설정 기준) |
--speculative-ngram-min-bfs-breadth |
최소 BFS 넓이. | 1 |
--speculative-ngram-max-bfs-breadth |
최대 BFS 넓이. | 10 |
--speculative-ngram-match-type |
Ngram 트리 구축 모드: "BFS"는 최근성 기반 확장, "PROB"는 빈도 기반 확장. |
"BFS" |
--speculative-ngram-max-trie-depth |
ngram trie가 저장·매칭하는 최대 접미사 길이. | 18 |
--speculative-ngram-capacity |
캐시 용량 (항목 수). | 10,000,000 |
참고:
- Ngram 추측 디코딩은 CUDA만 지원합니다.
- 현재
--enable-dp-attention을 지원하지 않습니다. - overlap 스케줄러와 mixed chunked prefill을 비활성화합니다.
--speculative-ngram-max-bfs-breadth > 1(따라서speculative_eagle_topk > 1)이고page_size > 1이면--attention-backend flashinfer를 사용하세요. 그렇지 않으면 서버가 오류를 냅니다.- 선택적:
SGLANG_NGRAM_FORCE_GREEDY_VERIFY=True로 greedy 검증을 강제할 수 있습니다.
python3 -m sglang.launch_server \
--model Qwen/Qwen2.5-7B-Instruct \
--speculative-algorithm NGRAM \
--speculative-num-draft-tokens 16 \
--speculative-ngram-max-bfs-breadth 10 \
--mem-fraction-static 0.7 \
--cuda-graph-max-bs-decode 8 \
--log-level warning
요청 보내기:
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-7B-Instruct",
messages=[
{"role": "user", "content": "List 3 countries and their capitals."},
],
temperature=0,
max_tokens=64,
)
print(response.choices[0].message.content)
전체 파라미터 참조 (Full Parameter Reference)
다음은 SGLang에서 사용 가능한 모든 추측 디코딩 파라미터의 종합 목록입니다:
핵심 파라미터 (Core parameters)
| Parameter | Type | Default | Description |
|---|---|---|---|
--speculative-algorithm |
str |
None |
사용할 알고리즘: UNO, DFLASH, EAGLE, EAGLE3, STANDALONE, NGRAM, NEXTN (EAGLE의 별칭) |
--speculative-draft-model-path |
str |
None |
드래프트 모델 가중치 경로 |
--uno-lora-path |
str |
None |
드래프트 LoRA 체크포인트의 UNO 전용 경로 또는 Hugging Face 저장소 |
--speculative-draft-model-revision |
str |
None |
드래프트 모델의 특정 revision/commit (드래프트 경로 설정·revision 생략 시 "main" 자동 사용) |
--speculative-draft-load-format |
str |
None |
드래프트 모델 가중치 로드 포맷 |
--speculative-num-steps |
int |
None (생략 시 자동 선택) |
자동회귀 드래프팅 깊이. 일부 알고리즘은 자동 튜닝. Tree UNO는 필요하며 B = speculative_num_steps + 1 사용. |
--speculative-eagle-topk |
int |
None (생략 시 자동 선택) |
드래프팅 단계별 분기 계수. 일부 알고리즘은 자동 튜닝. UNO는 생략 값을 1로 처리하고, 1보다 큰 값은 UNO tree 모드 선택. |
--speculative-num-draft-tokens |
int |
None (생략 시 자동 선택) |
검증용 최대 드래프트 토큰 수. 일부 알고리즘은 자동 튜닝. UNO는 필요하며 linear 폭 또는 tree 검증 폭 V로 사용. |
--speculative-dflash-block-size |
int |
None |
--speculative-num-draft-tokens의 DFlash 전용 별칭 |
--speculative-draft-window-size |
int |
None |
DFlash 전용 드래프트 KV 슬라이딩 윈도우 크기 |
--speculative-accept-threshold-single |
float |
1.0 |
단일 토큰 수용 임계값 |
--speculative-accept-threshold-acc |
float |
1.0 |
누적 수용 임계값 |
--speculative-token-map |
str |
None |
FR-Spec 고빈도 토큰 맵 경로 |
--speculative-attention-mode |
str |
"prefill" |
추측 연산의 어텐션 모드 ("prefill" 또는 "decode") |
--speculative-draft-attention-backend |
str |
None |
드래프트 모델의 어텐션 백엔드 오버라이드 |
--speculative-dsa-topk-backend |
str |
sgl-kernel |
--dsa-topk-backend와 독립적인 추측 드래프트 워커의 DSA indexer top-k 백엔드 (sgl-kernel, torch, flashinfer) |
--speculative-moe-runner-backend |
str |
None |
드래프트 모델의 MoE 러너 백엔드 |
--speculative-moe-a2a-backend |
str |
None |
드래프트 모델의 MoE all-to-all 백엔드 |
--speculative-draft-model-quantization |
str |
target과 동일 | 드래프트 모델 양자화 ("unquant"로 비활성화) |
Ngram 전용 파라미터 (Ngram-specific parameters)
| Parameter | Type | Default | Description |
|---|---|---|---|
--speculative-ngram-min-bfs-breadth |
int |
1 |
최소 BFS 넓이 |
--speculative-ngram-max-bfs-breadth |
int |
10 |
최대 BFS 넓이 |
--speculative-ngram-match-type |
str |
"BFS" |
Ngram 트리 구축 모드: "BFS"는 최근성 기반, "PROB"는 빈도 기반 확장 |
--speculative-ngram-max-trie-depth |
int |
18 |
ngram trie가 저장·매칭하는 최대 접미사 길이 |
--speculative-ngram-capacity |
int |
10,000,000 |
캐시 용량 |
환경 변수 (Environment variables)
| Variable | Default | Description |
|---|---|---|
SGLANG_NGRAM_FORCE_GREEDY_VERIFY |
False |
ngram 디코딩에 greedy 검증 강제 |
기타 관련 플래그 (Other related flags)
| Parameter | Description |
|---|---|
--enable-multi-layer-eagle |
멀티 레이어 EAGLE 활성화 (MiMoV2·Step3p5 모델에서 자동 활성화) |
--enable-torch-compile |
커널 수준 최적화용 torch.compile 활성화 |
--torch-compile-max-bs |
torch.compile의 최대 배치 크기 |
OOM 문제 해결 (OOM Troubleshooting)
[!WARNING] Out of Memory (OOM)? 추측 디코딩은 드래프트 트리, CUDA 그래프, 검증 관련 버퍼가 추가 VRAM을 소비하므로 GPU 메모리 사용을 늘릴 수 있습니다. OOM 오류가 발생하면 다음 조정을 시도하세요.
1단계: 정적 메모리 비율 낮추기 (가장 효과적) (Step 1: Lower static memory fraction)
--mem-fraction-static 0.5 # when omitted, this value is auto-computed
--mem-fraction-static은 모델 가중치 + KV 캐시 풀의 메모리 예산을 제어합니다.- 낮추면 activations와 CUDA 그래프 버퍼의 동적 헤드룸이 직접 증가합니다.
- 생략하면 SGLang이 다른 설정에서 이 값을 자동 추정하며, 이 자동 설정도 일부 워크로드에 너무 공격적일 수 있습니다.
2단계: CUDA 그래프 배치 크기 줄이기 (Step 2: Reduce CUDA graph batch size)
# Fewer CUDA graph captures = less memory reserved
--cuda-graph-max-bs-decode 4 # or even 2 for tight memory situations
- 생략하면
--cuda-graph-max-bs-decode는 GPU 메모리와 TP 크기에 따라 자동 선택되며, 고메모리 GPU에서는 훨씬 클 수 있습니다.
3단계: 드래프트 트리 크기 줄이기 (Step 3: Reduce draft tree size)
이 세 파라미터가 드래프트 트리가 소비하는 메모리를 직접 제어합니다:
# Before (aggressive, high memory)
--speculative-num-steps 5 --speculative-eagle-topk 8 --speculative-num-draft-tokens 64
# After (conservative, lower memory)
--speculative-num-steps 3 --speculative-eagle-topk 1 --speculative-num-draft-tokens 4
4단계: 동시 요청 제한 (Step 4: Limit concurrent requests)
# Fewer concurrent requests lowers in-flight load and can reduce OOM risk
--max-running-requests 4
빠른 OOM 복구 레시피 (Quick OOM recovery recipe)
OOM이 나서 일단 동작하는 것을 원한다면, 이 최소 구성을 시작으로 확장하세요:
python3 -m sglang.launch_server \
--model <your-model> \
--speculative-algorithm EAGLE \
--speculative-draft-model-path <your-draft-model> \
--speculative-num-steps 3 \
--speculative-eagle-topk 1 \
--speculative-num-draft-tokens 4 \
--cuda-graph-max-bs-decode 2 \
--mem-fraction-static 0.5 \
--max-running-requests 4 \
--log-level warning
그런 다음 --speculative-num-draft-tokens, --speculative-eagle-topk, --cuda-graph-max-bs-decode를 점진적으로 늘리세요. --mem-fraction-static은 실행이 안정된 후에 마지막으로 늘리세요.
참고자료 (References)
EAGLE 과정은 다음과 같습니다:
- EAGLE 내에서 드래프트 모델은 feature 시퀀스 $(f_1, ..., f_k)$와 토큰 시퀀스 $(t_2, ..., t_{k+1})$를 사용해 원래 LLM의 마지막 hidden state인 다음 feature 벡터를 예측합니다.
- 다음 토큰은 $p_{k+2}=\text{LMHead}(f_{k+1})$에서 샘플링됩니다. 이후 두 시퀀스는 트리 방식으로 확장됩니다 — 여러 잠재 연속을 분기하며, 단계별 분기 계수는
speculative_eagle_topk파라미터로 제어됩니다 — 보다 일관된 컨텍스트 연결을 보장하고 다시 입력으로 주어집니다. - SGLang의 EAGLE-2 구현에서 드래프트 트리는 구성된 단계만큼 확장된 뒤 재순위화되어 상위
speculative_num_draft_tokens최종 노드를 드래프트 토큰으로 선택합니다. - EAGLE-3는 feature 예측 목표를 제거하고 저·중 레이어 feature를 통합하며 on-policy 방식으로 훈련됩니다.
이는 토큰 대신 feature로 동작해 더 규칙적인 입력을 만들고, 다음 timestep의 토큰을 추가로 전달해 샘플링 무작위성을 줄임으로써 드래프팅 정확도를 높입니다. 자세한 내용은 EAGLE-2와 EAGLE-3 논문을 참고하세요.
자신의 EAGLE 모델을 훈련하는 방법은 EAGLE repo를 참고하세요. EAGLE-3 훈련은 SGLang 팀이 EAGLE-3 추측 디코딩 모델용으로 설계한 훈련 프레임워크인 SpecForge를 확인하세요. SGLang 서빙으로 매끄럽게 이식됩니다. 자세한 내용은 SpecForge documentation과 blog post를 참고하세요.