SGLang 101
Serving language models with SGLang, from one request to a fleet, with the judgment the flag list leaves out
- Start
- The Request Path
- The KV Cache
- Each Forward Pass
- Measuring a Server
- One Server Becomes a Fleet
- Production and Training
How to read this manual
Install SGLang, serve your model, and then learn which few settings matter for your traffic, with the numbers we measured when we changed them.
This manual is for the engineer who wants an open model on their own GPU this week. It starts with a server that answers, and it ends with a fleet that you can measure and run.
These commands make an environment, install SGLang, start a server, and send it one request:
uv venv --python 3.12
source .venv/bin/activate
uv pip install --prerelease=allow "sglang==0.5.22"
sglang serve --model-path Qwen/Qwen3-8B --host 127.0.0.1 --port 30000 \
--enable-cache-report --enable-metrics --mem-fraction-static 0.85
curl -s http://127.0.0.1:30000/generate -H 'Content-Type: application/json' \
-d '{"text": "The capital of France is", "sampling_params": {"max_new_tokens": 12, "temperature": 0}}'Section 1.1 runs them step by step, with the output to expect after each one and the fix for each common error. We ran the uv install and the server command on an NVIDIA L4 with SGLang 0.5.22. The Apple silicon steps come from our Mac runs, and the Docker command follows the SGLang install page. Every measured number in this manual names the machine that it came from: an NVIDIA L4, an NVIDIA DGX Spark, or the Mac.
What you can do after this manual
- Install SGLang, serve a model, and get the first answer from both of its APIs in about ten minutes.
- Size the KV pool for your GPU, and fix a server that runs out of memory.
- Tune the server for your traffic: shared prompts, long documents, many users, or FP8.
- Benchmark your own server, and watch it in production with its metrics.
- Choose how to scale to many GPUs, and judge a published benchmark before you trust it.
Who this manual is for
You have called a model through an API, and now you want to serve an open model yourself. You know what a token and a GPU are. You have not tuned a serving engine before, and you want to know which settings matter before you pay for them.
sglang serve --help lists 535 options at version 0.5.22. The SGLang documentation describes each of them. This manual tells you which ones to change on your first day, and which defaults assume a machine that you do not have. It also shows what each change did on our GPUs.
How the parts are ordered
Part 1 starts a server and checks it. Part 2 follows one request through the processes and the scheduler. Part 3 is the KV cache, which decides how many users one GPU serves.
Part 4 makes each forward pass fast, and Part 5 measures a server. Part 6 spreads one model over many GPUs. Part 7 operates SGLang and closes with reinforcement learning. The Reference holds the lookup tables and how this manual was made:
| Part | What it covers |
|---|---|
| 1 · Start | Install with uv or Docker, the first answer from both APIs, the health checks and startup lines, then prefill against decode and the four numbers. |
| 2 · The Request Path | sglang serve, the scheduler loop and its policies, admission and retraction, the overlap scheduler, and the response path. |
| 3 · The KV Cache | Bytes per token, startup sizing, RadixCache, prefix-friendly prompts, eviction and HiCache, and hybrid models. |
| 4 · Each Forward Pass | ForwardMode and CUDA graphs, attention backends, quantization, speculative decoding, structured outputs, and deterministic inference. |
| 5 · Measuring a Server | sglang.benchmark.serving, the /metrics endpoint, and how to read benchmarks that other people publish. |
| 6 · One Server Becomes a Fleet | Tensor, data, attention-data, and expert parallelism, MoE serving, prefill-decode disaggregation, and the model gateway. |
| 7 · Production and Training | Deploying and tuning in order, and SGLang as the rollout engine of Miles. |
| R · Reference | The flags, metrics, incidents, terms, and sources this manual uses, in one place. |
Each section ends with an "Our position" part that says what to do, and a short list of actions. Read those first when you need an answer today. Read the rest when you want the reason.
Seven lessons go deeper into the ideas this manual applies. The serving internals lesson builds paged attention and continuous batching. The goodput lesson defines the metrics. The speculative decoding lesson builds EAGLE-3, and the quantization lesson covers the formats. The serving selection lesson, the inference optimization lesson, and the prompt caching lesson complete the set. This manual stays with SGLang.
Colour in figures
Each hue keeps one meaning in every figure:
| blue | the SGLang server process: tokenizer manager, scheduler, detokenizer |
| violet | the model and its forward pass: kernels, attention backends, CUDA graphs |
| green | the KV cache: pool slots, radix tree nodes, cached tokens |
| plum | model compute: prefill and decode steps |
| olive | the client and the network: HTTP, the OpenAI API, the benchmark client |
| indigo | streams and messages: ZMQ messages and streamed tokens |
| amber | lifecycle: request states and scheduler phases |
| teal | durable state: host memory and storage tiers, weights on disk |
| rose | failure: out of memory, retraction, aborts, crashes |
| grey | outside SGLang: the operating system, other programs, the GPU driver |
Figure 0.1 teaches the arrow styles with exchanges from our capture.
Start
Install SGLang, serve a model, check that the server is healthy, and learn the two phases and four numbers behind every request.
Install SGLang and serve your first model
In about ten minutes, we install SGLang, start a server on one GPU, and get the same answers from it that our recorded run got.
We start from a Linux machine with one NVIDIA GPU and its driver. We end with a server on port 30000 that answers curl and the OpenAI Python client.
When you finish this section, you can install SGLang with uv or Docker and start a server. You can also compare its first answers with ours and fix the common start errors.
What you need
- Linux with one NVIDIA GPU and a driver for CUDA 13. SGLang 0.5.22 publishes CUDA 13 wheels and images only.
- 24 GB of GPU memory for the model in this section,
Qwen/Qwen3-8B. With less memory, useQwen/Qwen3-0.6B. The steps stay the same, and the numbers in the output change. - About 16 GB of free disk for the weights of
Qwen/Qwen3-8B. - Docker with the NVIDIA Container Toolkit, or Python 3.11 or newer with
uv.
We recorded every output in this section on an NVIDIA L4 with 24 GB. The listings name the capture file, so you can compare your run with ours line by line.
Check the GPU
First, check that the driver can see the GPU:
nvidia-smiThe table names your GPU and the driver version. If the command is not found, install the NVIDIA driver before you go on. SGLang cannot start without it.
Install SGLang
Choose one path. Use Docker on a machine that has only the GPU driver. Use uv on a machine that already has the full CUDA toolkit, including nvcc.
On an L4 host with only a driver, pip install sglang==0.5.22 finished with no error. Then the first four starts of the server failed, each on a different missing part of the toolkit. Section 7.1 lists the four errors and the repairs.
With Docker
Pull the image for the version this manual tests:
docker pull lmsysorg/sglang:v0.5.22We pin the tag. The latest tag moves to each new release, and the releases change defaults.
With uv
Create an environment and install SGLang with the version pinned:
uv venv --python 3.12
source .venv/bin/activate
uv pip install --prerelease=allow "sglang==0.5.22"Keep --prerelease=allow. Some dependencies of SGLang publish only prereleases, and without the flag an older uv installs SGLang 0.5.9 with no warning.
Now check the version:
sglang version$ sglang version
sglang version: 0.5.22
git revision: N/AIf you see another version, the install picked another release. Run the install command again with the version pinned.
Start the server
Start the server in the environment where you installed SGLang. This is the command of our recorded L4 run:
sglang serve --model-path Qwen/Qwen3-8B --host 127.0.0.1 --port 30000 \
--enable-cache-report --enable-metrics --mem-fraction-static 0.85With Docker, run the same server inside the container. Mount your Hugging Face cache, so the weights download once:
docker run --rm --gpus all --ipc=host --shm-size 32g -p 127.0.0.1:30000:30000 \
-v "$HOME/.cache/huggingface:/root/.cache/huggingface" \
lmsysorg/sglang:v0.5.22 \
sglang serve --model-path Qwen/Qwen3-8B --host 0.0.0.0 --port 30000 \
--enable-cache-report --enable-metrics --mem-fraction-static 0.85We ran the uv path. The Docker command follows the SGLang install page. It uses --host 0.0.0.0 because the port must be open outside the container. The 127.0.0.1: prefix on -p keeps that port on your own machine. The server has no API key, so do not publish it on a network interface.
Three flags in the command are our choice:
--enable-cache-reportputscached_tokensin every response. Without it, a client cannot see the cache hits of its own request.--enable-metricsturns on the/metricsendpoint, which section 1.2 reads.--mem-fraction-static 0.85sets how much GPU memory SGLang takes. Section 3.2 shows how to choose the value.
The first start downloads the weights. Then the server sizes its memory and prepares its kernels. Wait for the last line of this listing:
[2026-10-17 14:42:45] KV Cache is allocated. dtype: torch.bfloat16, #tokens: 22939, K size: 1.58 GB, V size: 1.58 GB
…
[2026-10-17 14:43:36] max_total_num_tokens=22939, chunked_prefill_size=4096, max_prefill_tokens=16384, max_running_requests=2048, context_len=40960, available_gpu_mem=1.31 GB
…
[2026-10-17 14:43:36] Tree cache initialized: source=default impl=UnifiedRadixCache hybrid_swa=False hybrid_ssm=False hicache_attached=False
[2026-10-17 14:43:37] Engine startup timings (s): load_weight=3.73, kv_cache_allocation=0.40, scheduler_e2e=59.11, cuda_graph={prefill=48.33, decode=2.61, target_verify=0.00, draft_prefill=0.00, draft_decode=0.00, draft_extend=0.00}, tokenizer_e2e=69.10
…
[2026-10-17 14:43:38] The server is fired up and ready to roll!Our weights were already on disk, so loading them took 3.73 s. The start still took about a minute. Most of that minute, 48.33 s, went to the capture of CUDA graphs for prefill. A later start on the same machine can reuse the compiled kernels from ~/.cache/sglang.
If the server does not start
Read the last error line in the log, then find it here:
- The log names
Python.h,nvcc, or-lcudart. The host has no full CUDA toolkit. Use the Docker path, or apply the four repairs in section 7.1. - The log says the GPU is out of memory. The model and its cache do not fit. Lower
--mem-fraction-static, or use a smaller model. Section 3.2 shows the crash and the fix. - The download fails. Check the network and the model name. With
HF_HUB_OFFLINE=1, the model must already be in the cache. - Another program uses port 30000. Start the server with
--port 30001, and use that port in every request below.
Send a request with curl
Open a second terminal. Send a request to the native API of SGLang:
curl -s http://127.0.0.1:30000/generate \
-H 'Content-Type: application/json' \
-d '{"text": "The capital of France is", "sampling_params": {"max_new_tokens": 12, "temperature": 0}}'Our L4 server answered like this:
"text": " Paris. The capital of Italy is Rome. The capital of",
…
"meta_info": {
…
"finish_reason": {
"type": "length",
"length": 12
…
"prompt_tokens": 5,
…
"completion_tokens": 12,
"cached_tokens": 2,
…
"e2e_latency": 0.7252887019421905,At temperature 0, your text with Qwen/Qwen3-8B can match ours word for word. The answer stopped after 12 tokens because we asked for 12, and finish_reason says length.
Two of the five prompt tokens were already in the cache. At startup, the server sent itself the prompt "The capital city of France is". Our prompt shares its first two tokens with that warm-up prompt, so the prefix cache skipped them.
Send the same question through the OpenAI API
Most clients use the OpenAI chat API, and SGLang serves it on the same port. First, send a chat request with curl:
curl -s http://127.0.0.1:30000/v1/chat/completions \
-H 'Content-Type: application/json' \
-d '{"model": "default", "messages": [{"role": "user", "content": "Name one planet. Answer in one word."}], "max_tokens": 64, "temperature": 0, "chat_template_kwargs": {"enable_thinking": false}}' "model": "default",
…
"message": {
"role": "assistant",
"content": "Earth",
…
"finish_reason": "stop",
…
"usage": {
"prompt_tokens": 21,
"total_tokens": 23,
"completion_tokens": 2,
"prompt_tokens_details": {
"cached_tokens": 0
},
"reasoning_tokens": 0The question has seven words and became 21 prompt tokens. The chat template adds role markers around the message, so count them when you plan the context length. "enable_thinking": false turns off the thinking mode of Qwen3, so the answer is one word, and reasoning_tokens is 0.
Now send the same request from Python with the OpenAI client:
from openai import OpenAI
client = OpenAI(base_url="http://127.0.0.1:30000/v1", api_key="none")
response = client.chat.completions.create(
model="default",
messages=[{"role": "user", "content": "Name one planet. Answer in one word."}],
max_tokens=64,
temperature=0,
extra_body={"chat_template_kwargs": {"enable_thinking": False}},
)
print(response.choices[0].message.content)The script prints the content field of the response. Our capture sent the same JSON body with the Python standard library and got Earth. Without --api-key on the server, SGLang does not check the key, so any value works.
Stop the server
Press Ctrl+C in the server terminal to stop the server. In production, send the stop signal to the main process only. Section 7.1 explains why.
On an Apple silicon Mac
SGLang also runs on Apple silicon through its MLX backend. You need macOS 14 or newer and about 8 GB of free disk. Install SGLang from the tag with the MLX extra:
git clone --branch v0.5.22 --depth 1 https://github.com/sgl-project/sglang.git
cd sglang
uv venv -p 3.12 .venv && source .venv/bin/activate
cp python/pyproject_other.toml python/pyproject.toml
uv pip install -e "python[srt_mps]"On our Mac, the install took 3 minutes and 15 seconds. Start a server with a small 4-bit model:
SGLANG_USE_MLX=1 sglang serve --model-path mlx-community/Qwen3-0.6B-4bit \
--disable-cuda-graph --enable-cache-report --mem-fraction-static 0.4Then send the same /generate request as above. Our Mac answered " Paris, and the capital of Germany is Berlin. The capital". The smaller model gives other text, and the token counts stay the same. Set --mem-fraction-static on a Mac that you also use for other work. Section 3.2 shows the crash we got without it.
Check that the server is healthy
Before you send traffic, confirm that the server answers, that it can produce a token, and that it chose the memory sizes you expect.
The ready line in the log says that the server started. It does not say that the server can serve your traffic. A pool that is too small, or a server that cannot produce a token, still prints the same line.
When you finish this section, you can choose the right health endpoint for a script or a probe. You can also read the three startup lines that size the server, warm it up, and read its first metrics.
Wait until /health returns 200
To wait for the server in a script, ask /health until it returns 200:
until curl -sf -o /dev/null http://127.0.0.1:30000/health; do sleep 2; doneOur capture kit did the same, every 2 seconds. The server log shows the answer change from 503 to 200:
[2026-10-17 14:43:37] INFO: 127.0.0.1:58250 - "GET /health HTTP/1.1" 503 Service Unavailable
…
[2026-10-17 14:43:38] INFO: 127.0.0.1:58272 - "POST /generate HTTP/1.1" 200 OK
[2026-10-17 14:43:38] INFO: 127.0.0.1:58288 - "POST /freeze_gc HTTP/1.1" 200 OK
[2026-10-17 14:43:38] The server is fired up and ready to roll!
[2026-10-17 14:43:40] Prefill batch, #new-seq: 1, #new-token: 1, #cached-token: 0, token usage: 0.00, #running-req: 0, #queue-req: 0, #pending-token: 0, cuda graph: False, input throughput (token/s): 0.58
[2026-10-17 14:43:40] INFO: 127.0.0.1:58298 - "GET /health HTTP/1.1" 200 OKLook at the line before the 200. The scheduler ran a one-token prefill for the health check. By default, /health does not only answer. It sends a one-token request through the model and waits for the result.
Choose the endpoint for the job
SGLang has three health endpoints. Pick one by the question you ask:
- Is the server up and accepting requests? Use
/ready. It returns 200 when the tokenizer manager is ready, and it sends no request to the model. - Can the server produce a token now? Use
/health_generate. It sends a one-token request and returns 503 when no output arrives within 20 s. /healthshares the handler of/health_generate. With the default settings, it also generates a token.
For a script that waits for a start, any of the three works. For Kubernetes probes, the choice matters under load. A probe that generates waits in the same queue as your users. Section 7.1 gives the probe settings we recommend and the incident behind them.
Read the three startup lines
Three lines in the startup log tell you how much the server can hold. Read them on every start, because SGLang computes them for you:
[2026-10-17 14:42:45] KV Cache is allocated. dtype: torch.bfloat16, #tokens: 22939, K size: 1.58 GB, V size: 1.58 GB
…
[2026-10-17 14:43:36] max_total_num_tokens=22939, chunked_prefill_size=4096, max_prefill_tokens=16384, max_running_requests=2048, context_len=40960, available_gpu_mem=1.31 GB
…
[2026-10-17 14:43:36] Tree cache initialized: source=default impl=UnifiedRadixCache hybrid_swa=False hybrid_ssm=False hicache_attached=FalseKV pool: the GPU memory that holds the keys and values of every token that the server keeps, for all requests together. Our pool holds 22,939 tokens.
Compare the pool with context_len=40960. One request can be longer than the whole pool, so a single long request can fill it. Twenty-three users with 1,000 tokens each also fill it.
max_running_requests=2048 is the most requests that the scheduler runs at once. The server computed this value, and we did not set it. The pool is the real limit long before 2,048 requests.
The last line names the prefix cache that the server uses. UnifiedRadixCache is the default radix cache, and hicache_attached=False says that HiCache is off. Section 3.5 explains when to turn it on.
If the pool is smaller than your traffic needs, go to section 3.1 to count the memory, and to section 3.2 to change the size.
Warm up the server before you measure
The listing in the first part of this section shows a POST /generate and a POST /freeze_gc before the ready line. The server sent itself one request. Then it froze the Python garbage collector, so the objects from the start are not scanned again.
The freeze has a history. A field report from LinkedIn found garbage collection pauses of 100 to 300 ms every few seconds on a small ranking model. The fix was this warm-up and the frozen collector, merged as pull request 9241.
The warm-up does not make your first request fast on every machine. On our L4, the first request after the start reached its first token in 68 ms. On our Mac, the first request of the same kind took 889 ms. Send a few requests of your own before you measure anything.
Check the first metrics
The server that we started with --enable-metrics serves Prometheus metrics on /metrics. Read four of them now, and keep the command for later:
curl -s http://127.0.0.1:30000/metrics | grep -E '^sglang:(num_running_reqs|num_queue_reqs|token_usage|cache_hit_rate)\{'sglang:num_running_reqs{engine_type="unified",model_name="Qwen/Qwen3-8B",moe_ep_rank="0",pp_rank="0",tp_rank="0"} 0.0
sglang:num_queue_reqs{engine_type="unified",model_name="Qwen/Qwen3-8B",moe_ep_rank="0",pp_rank="0",tp_rank="0"} 0.0
sglang:cache_hit_rate{engine_type="unified",model_name="Qwen/Qwen3-8B",moe_ep_rank="0",pp_rank="0",tp_rank="0"} 0.956268221574344
sglang:token_usage{engine_type="unified",model_name="Qwen/Qwen3-8B",moe_ep_rank="0",pp_rank="0",tp_rank="0"} 0.0num_running_reqsandnum_queue_reqscount the requests that run now and the requests that wait.token_usageis the share of the KV pool in use, from 0 to 1.cache_hit_rateis the share of prompt tokens that the prefix cache found.
Our hit rate is 0.956 because our benchmarks sent many prompts with a shared prefix. On an idle server, all four values are near 0.
The endpoint is off by default. If the command prints nothing, start the server again with --enable-metrics. Section 5.2 lists the metrics to alert on.
What the server does with your request
Every request has two phases with different costs, and four numbers tell you how a server handles them for all its users.
You sent two requests in section 1.1, and both came back in under a second. With ten users, the same server can make some of them wait seconds for the first word. The reason is in the two phases of every request.
When you finish this section, you can name the two phases of a request and the four numbers a server is judged by. You can also say what SGLang controls and what stays with the model and with you.
Two phases with two different costs
Prefill: the forward pass over the whole prompt. It computes the keys and values of every prompt token in one batch and produces the first output token. Decode: the loop that produces each next token, one forward pass per token per request.
The two phases use the GPU in different ways. Prefill has many tokens in each pass, so it keeps the arithmetic units busy. Decode has one new token per request in each pass.
Each decode step reads the weights that the step needs, and the cached keys and values, to do little arithmetic. For a dense model, that is every weight. For a mixture-of-experts model, it is the shared weights and the experts that the router chose. Memory bandwidth sets the speed of decode, and compute sets the speed of prefill.
We measured the difference on a Mac with a 0.6B model. A 512-token prompt reached its first token in a median of 163 ms. After that, each new token took 4.38 ms on average.
Max request concurrency: 1
Successful requests: 16
…
Median TTFT (ms): 162.98
…
Mean TPOT (ms): 4.38 That is at most about 0.32 ms per prompt token against 4.38 ms per output token, a factor of about 14 on this Mac. The 0.32 ms is an upper bound, because the TTFT also holds the queue and the first decode step. On our L4 with Qwen3-8B the factor was about 160: 189 ms for a 512-token prompt, against 60 ms per output token. A serving engine can share and skip prefill work. It mostly batches decode work, so that one read of the weights serves many requests. Section 4.4 shows the other way to cut decode steps.
The four numbers
Judge a server by four numbers together. A report that gives one of them tells you little.
- Time to first token (TTFT): how long a user waits before the first word. Prefill and the queue set it.
- Time per output token (TPOT): the average gap between tokens after the first. Inter-token latency (ITL) is the same gap, measured one token at a time, so its tail shows stalls. Decode sets both.
- Throughput: output tokens per second across all users. Batching sets it.
- Goodput: requests per second that meet a TTFT target and a TPOT target at the same time. Your users feel this number.
The first three trade against each other. A larger batch raises throughput and makes the tokens of each user slower. A large prefill chunk finishes a long prompt sooner and stalls every decode in the batch while it runs. Section 5.1 shows the trade on a real sweep.
The SGLang benchmark tool prints TTFT, TPOT, ITL, and throughput. It does not print goodput at version 0.5.22, so compute it from the records of each request. The inference metrics lesson builds that calculation.
What SGLang owns, and what it does not
SGLang owns the time between a request and its tokens. It decides which prompt tokens to compute, which to reuse, and when each request runs.
Three things stay outside. The model decides what the answer says. On our Mac, a 0.6B model asked to name a planet answered "Ardens", which is no planet. SGLang served that answer correctly and fast, and no serving engine can make a model right.
You, the operator, decide how much memory SGLang gets and which machine a request goes to. SGLang has a separate router for that second job, and section 6.4 covers it.
The path of one request
Inside SGLang, your /generate request crossed three processes. The tokenizer manager turned the text into token ids. The scheduler found two of the five prompt tokens in the cache and computed the other three. The detokenizer turned the new token ids into text.
The scheduler logged its side of the request in one line:
[2026-10-17 14:43:41] Prefill batch, #new-seq: 1, #new-token: 3, #cached-token: 2, token usage: 0.00, #running-req: 0, #queue-req: 0, #pending-token: 0, cuda graph: True, input throughput (token/s): 2.82
[2026-10-17 14:43:41] INFO: 127.0.0.1:58314 - "POST /generate HTTP/1.1" 200 OK#new-token: 3 and #cached-token: 2 add up to the five prompt tokens. This pair is the most useful line that SGLang prints. Section 3.4 uses it alone to find a prompt that misses the cache.
Our position
Choose SGLang for the shape of your traffic, never for a headline number. Agents, chat with a fixed system prompt, and retrieval with a fixed preamble all share long prefixes. For that traffic, the prefix cache saves prefill work on every request. If every prompt is unique and long, measure two engines on your own prompts before you decide.
Distrust any SGLang benchmark that does not name its version. The most repeated number on the web, "SGLang 29% faster than vLLM", comes from one offline test that lists SGLang v0.2.3. Section 5.3 shows where independent tests agree, and our own head-to-head runs.
To see how the scheduler, the cache, and each forward pass do this work, read Parts 2 to 4. Start with section 2.1, which follows the request through the three processes.
The Request Path
A request crosses three processes, and the scheduler between them decides who runs, who waits, and who gets thrown out.
sglang serve and the three processes
SGLang splits one server into a tokenizer process, a scheduler process, and a detokenizer process, because Python text work must never delay the loop that feeds the GPU.
You start a server, send one request, and it works. Then you put real traffic on it, and the GPU sits at 40 percent while users wait. Most people blame the kernels first. LinkedIn did the work to find out, and the slow parts were the tokenizer, the messages between processes, Python garbage collection, and the GIL.
When you finish this section, you can start SGLang with sglang serve and name the three processes it starts. You can also read the startup log for the numbers that decide everything later.
The cost: one Python thread cannot do everything
A language model server does two kinds of work. GPU work is the forward pass: one prefill or decode step every few milliseconds. CPU work is everything around it: parsing HTTP, applying the chat template, tokenizing, turning token ids back into text, and checking stop strings.
The obvious design puts all of it in one Python process. That design fails under load. Python runs one thread at a time under the GIL. A 3,000-token prompt that is being tokenized holds the interpreter that must launch the next GPU step. Every millisecond of text work becomes a millisecond of idle GPU.
LinkedIn measured this on H100 GPUs with small ranking models. Batch tokenization alone moved P99 latency from 4,583 ms to 464 ms at 500 queries per second. The model did not change. Only the CPU path around it changed.
What SGLang starts
TokenizerManager: the object in the main process that receives each request, applies the chat template, tokenizes the text, and waits for the answer. The HTTP server and the TokenizerManager share one process and one asyncio loop.
Scheduler: a separate process that owns the GPU. It decides which tokens run next, builds the batch, runs the forward pass, and samples. With tensor parallelism there is one scheduler process per GPU.
DetokenizerManager: a third process that turns output token ids into text, one small piece at a time, and sends the text back to the TokenizerManager.
The processes talk over ZMQ sockets. The TokenizerManager sends a TokenizedGenerateReqInput to the scheduler. The scheduler sends a BatchTokenIDOutput to the detokenizer. The detokenizer sends a BatchStrOutput back. At v0.5.22 the messages are pickled by default, because SGLANG_USE_PICKLE_IPC is true.
With tensor parallelism, only rank 0 of the scheduler opens the ZMQ sockets. It broadcasts each request to the other ranks, so every GPU builds the same batch. No rank decides on its own.
The command we ran
We started the server on an Apple silicon Mac with the MLX backend and a 4-bit Qwen3 0.6B model. sglang serve is the recommended command at v0.5.22. The older python -m sglang.launch_server still works and prints a warning that names sglang serve as the recommended entrypoint.
SGLANG_USE_MLX=1 sglang serve --model-path mlx-community/Qwen3-0.6B-4bit --disable-cuda-graph --host 127.0.0.1 --port 30000 --enable-cache-report --enable-metrics --mem-fraction-static 0.4Three flags are not defaults, and all three are deliberate. --enable-cache-report puts the cached token count into every OpenAI-style response, so section 2.5 can show it. --enable-metrics turns on the /metrics endpoint that section 5.2 reads. --mem-fraction-static 0.4 limits the KV pool, and section 3.2 explains the crash we had without it.
The log objects to one flag. The Apple silicon page of the SGLang docs tells you to pass --disable-cuda-graph. The second line of our log says the flag "is deprecated and will be removed in a future release", and names --cuda-graph-backend-{decode,prefill}=disabled as the replacement.
The docs and the code disagree here, and the code wins. The flag still works at v0.5.22. Plan to replace it before the next release removes it.
Read the startup log before anything else
The startup log tells you what SGLang decided on your behalf. Most of those numbers are not flags you set. They are values that SGLang computed from your memory, your model, and your hardware.
[2026-10-16 13:58:05] max_total_num_tokens=181574, chunked_prefill_size=4096, max_prefill_tokens=16384, max_running_requests=4096, context_len=40960, available_gpu_mem=47.96 GB
…
[2026-10-16 13:58:06] Using the Python TreeCore: the Rust TreeCore supports Linux only
[2026-10-16 13:58:06] Tree cache initialized: source=default impl=UnifiedRadixCache hybrid_swa=False hybrid_ssm=False hicache_attached=False
[2026-10-16 13:58:06] Engine startup timings (s): load_weight=0.00, kv_cache_allocation=0.00, scheduler_e2e=7.01, cuda_graph={prefill=0.00, decode=0.00, target_verify=0.00, draft_prefill=0.00, draft_decode=0.00, draft_extend=0.00}, tokenizer_e2e=11.92Read the first line field by field:
max_total_num_tokens=181574is the size of the KV pool in tokens. Part 3 shows where it comes from.chunked_prefill_size=4096is the largest piece of one prompt that runs in one step. A longer prompt runs in pieces.max_running_requests=4096is how many requests can decode at the same time. It is a computed value, not a promise of good latency.context_len=40960is the longest sequence the model accepts.
The tree cache lines matter too. On Linux the radix tree runs in Rust by default since v0.5.21. On our Mac it runs in Python, and the log says so.
The warm-up and the garbage collector
Before the server says it is ready, it sends itself one request. Then it calls its own /freeze_gc endpoint.
[2026-10-16 13:58:08] Prefill batch, #new-seq: 1, #new-token: 6, #cached-token: 0, token usage: 0.00, #running-req: 0, #queue-req: 0, #pending-token: 0, cuda graph: False, input throughput (token/s): 3.85
[2026-10-16 13:58:08] INFO: 127.0.0.1:63781 - "POST /generate HTTP/1.1" 200 OK
[2026-10-16 13:58:08] INFO: 127.0.0.1:63785 - "POST /freeze_gc HTTP/1.1" 200 OK
[2026-10-16 13:58:08] The server is fired up and ready to roll!That /freeze_gc call has a history. LinkedIn saw garbage collection pauses of 100 to 300 ms every few seconds and fixed them with a warm-up and gc.freeze(). At v0.5.22 the server does the same thing for you after its warm-up, for the scheduler and the detokenizer too.
The processes in the shutdown log
The clearest proof of the process split comes when the server stops. Our capture kit stops each server with SIGTERM.
[2026-10-16 14:01:45] SIGTERM received. signum=None frame=None. Draining requests and shutting down...
[2026-10-16 14:01:45] Subprocess scheduler_0 (pid=5909) crashed with exit code -15. Triggering SIGQUIT for cleanup...The main process is pid 5782 and the scheduler is pid 5909. Exit code -15 is our own SIGTERM, so the word "crashed" is misleading. A real scheduler crash looks different. It prints a traceback and then "SIGQUIT received ... It usually means one child failed", as section 2.4 shows.
Our position
Treat the CPU path as part of the model server. When time to first token is high and the GPU is not busy, look at the tokenizer process before you look at kernels. SGLang gives you more workers for both ends: --tokenizer-worker-num and --detokenizer-worker-num, both 1 by default.
Do not run every experiment on the defaults that the startup log reports. Write the computed limits down, then decide which ones to set yourself. Section 7.1 gives the order.
The scheduler loop and --schedule-policy
The scheduler answers one question every few milliseconds, which tokens the GPU computes next, and at v0.5.22 its default answer is first come, first served.
Eight users send prompts in the same second. One of them pasted a 4,000-token document, and the others typed a sentence each. Should the long prompt go first, or the short ones? Should the request that shares a system prompt with yesterday's traffic jump the queue? Somebody has to decide, on every step, and in SGLang that somebody is the scheduler loop.
When you finish this section, you can read the scheduler's Prefill batch and Decode batch log lines. You can name the policy that orders the waiting queue and decide whether to change it.
The cost of a bad order
For a dense model on a memory-bound GPU, a decode step costs about the same whether it computes tokens for 1 request or for 8. On our L4 with Qwen3-8B, one step took 60 ms for 1 user and 66 ms for 8. A mixture-of-experts model is different. On our GB10 the step grew from 33 ms to 102 ms, and a bigger batch can read more experts.
So the scheduler wants big batches. A user who waits in the queue sees nothing at all. So the scheduler also wants short queues. Every policy is a trade between those two costs.
The obvious fix is a smart order, for example the request with the most cached prefix first. The SGLang paper proposed exactly that, longest prefix match, and proved it optimal for an offline batch. Online traffic is not an offline batch, and the smart order costs CPU time on every step.
One turn of the loop
Scheduler loop: the function that runs forever in the scheduler process. Each turn takes new requests, picks the next batch, runs it on the GPU, and processes the results.
One turn does four things in order:
- Ingest. Drain new requests from the ZMQ socket and add them to the waiting queue.
- Pick. If the last batch was a prefill, merge it into the running decode batch. Then try to build a new prefill batch from the waiting queue. If one exists, run it. If not, run one decode step for every running request.
- Run. Build a
ForwardBatchfrom theScheduleBatchand run the model. - Process. Append the sampled tokens, check stop conditions, free or cache the KV of finished requests, and send results to the detokenizer.
A request rides one prefill batch, possibly over several chunks, and then joins the long-lived decode batch until it stops. Prefill wins when the scheduler can admit something. That rule keeps time to first token low, and section 2.3 shows the budget check that decides "can admit".
The two log lines
The scheduler prints one line per prefill batch and one decode line every 40 decode steps, the default of --decode-log-interval. These lines are the most useful text the server writes. Here are three consecutive lines from our benchmark at concurrency 8.
[2026-10-16 13:59:07] Prefill batch, #new-seq: 1, #new-token: 511, #cached-token: 1, token usage: 0.00, #running-req: 0, #queue-req: 7, #pending-token: 0, cuda graph: False, input throughput (token/s): 155.03
[2026-10-16 13:59:09] Prefill batch, #new-seq: 7, #new-token: 3553, #cached-token: 2, token usage: 0.02, #running-req: 1, #queue-req: 0, #pending-token: 0, cuda graph: False, input throughput (token/s): 1914.13
[2026-10-16 13:59:09] Decode batch, #running-req: 8, #token: 4075, token usage: 0.02, cuda graph: False, gen throughput (token/s): 98.37, #queue-req: 0Read the fields:
#new-seqis how many requests this prefill admits.#new-tokenis how many prompt tokens it computes, and#cached-tokenis how many it reused from the radix cache.token usageis the share of the KV pool in use. Our pool is large, so usage stays near zero here.#running-reqcounts requests that are decoding.#queue-reqcounts requests that are waiting.cuda graph: Falseis expected on a Mac. On CUDA,Truemeans the decode step replayed a captured graph, and section 4.1 explains why that matters.
The first line admits one request while seven wait. The next prefill admits the other seven together, 3,553 new tokens in one step at 1,914 tokens per second. Then all eight decode as one batch. Batching prefill is where the throughput comes from, and the log shows it happen.
The policies
Schedule policy: the rule that orders the waiting queue before admission. Set it with --schedule-policy.
The default at v0.5.22 is fcfs. The choices split into two groups.
| Group | Policies | What they use |
|---|---|---|
| Cache-aware | lpm, dfs-weight, hrrn, shortest-prefill-first | the radix tree: how much of each prompt is already cached |
| Cache-agnostic | fcfs, lof, random, routing-key | arrival order, output length, or a routing key |
The parser also accepts --schedule-policy priority, but the scheduler has no such order, and the server stops with "Unknown schedule_policy". To order by priority, use --enable-priority-scheduling with fcfs.
Many readers expect lpm, because the paper describes it. It was the default in v0.4.3 and became fcfs by v0.4.6. The research for this manual did not find the pull request that changed it.
Two rules in the code limit the cache-aware policies:
- When the waiting queue holds more than 128 requests,
lpmandhrrnchange to FCFS for that turn. The code comment says why: prefix matching and sorting cost too much when the queue is long. - When the radix cache is off,
lpm,dfs-weight, andhrrnbecome FCFS.shortest-prefill-firstrefuses to start.
So lpm helps only in a narrow band. The queue must be long enough to reorder, short enough to stay under 128, and full of shared prefixes.
Chunk size under long prompts
Chunked prefill: the rule that splits a long prompt into pieces of at most --chunked-prefill-size tokens, one piece per prefill batch. The default depends on GPU memory, as the table in section 4.1 shows. It is 4,096 on a 22 GB L4 and 8,192 on the GB10.
The common advice is to make the chunk smaller, so that decode steps run more often between pieces of a long prompt. We tested that advice. Each run sent 48 prompts of 1,024 to 4,096 tokens, with 256 tokens of output. Requests arrived at a Poisson rate of 0.5, 1, or 2 per second, with three seeds.
| GPU, model | Chunk | Rate, per second | Output tok/s | Median TTFT | P99 ITL | Median SM clock |
|---|---|---|---|---|---|---|
| GB10, Qwen3-30B-A3B | 8,192, the default | 0.5 | 70.1 | 892 ms | 929 ms | 2,411 MHz |
| GB10, Qwen3-30B-A3B | 1,024 | 0.5 | 68.1 | 1,253 ms | 1,977 ms | 2,398 MHz |
| GB10, Qwen3-30B-A3B | 8,192, the default | 2 | 129.3 | 269 ms | 312 ms | 2,411 MHz |
| GB10, Qwen3-30B-A3B | 1,024 | 2 | 130.1 | 256 ms | 260 ms | 2,411 MHz |
| L4, Qwen3-8B | 4,096, the default | 0.5 | 44.1 | 36.0 s | 2,579 ms | 773 MHz |
| L4, Qwen3-8B | 1,024 | 0.5 | 43.3 | 37.4 s | 2,922 ms | 690 MHz |
| L4, Qwen3-8B | 4,096, the default | 2 | 46.2 | 59.8 s | 2,512 ms | 915 MHz |
| L4, Qwen3-8B | 1,024 | 2 | 44.0 | 62.5 s | 2,930 ms | 825 MHz |
We measured no gain from a smaller chunk on either machine. On the GB10 we ran the default, an explicit 8,192, and 1,024. At 1 and 2 requests per second, all three were inside the seed spread of each other. At 0.5 per second, the 1,024 chunk was worse. Its P99 ITL was 1,977 against 929 ms, and the seed ranges did not overlap. Raw runs
A 2025 study of chunked prefill on MoE models gives a likely reason for that loss. Each chunk of a prompt loads the expert weights again, and in that study the extra loads raised memory traffic by up to 39 percent. Qwen3-30B-A3B is an MoE model. With a chunk of 1,024, a prompt of up to 4,096 tokens runs as up to four chunks. Each chunk reads the experts again. We did not measure the expert traffic, so this is a reading, not a result.
The rates of 1 and 2 per second need a second caution. In each seed, the sweep sent the same 48 prompts at every rate to one server, and it did not flush the cache. The rate of 0.5 ran first. The GB10 pool could hold those prompts, so the later runs could find many of them in the cache. That can explain why the first token at 1 and 2 per second was faster than at 0.5. Section 5.1 gives the protocol that prevents this.
On the L4, this workload was more than the card could serve at every rate. Output stayed near 44 tokens per second, and the median first token took 36 to 62 seconds. The card throttled, at a median clock of 690 to 915 MHz, and this sweep did not repeat throttled runs. The worst token gap stayed between 2.5 and 2.9 s with either chunk. The 1,024 runs also ran 80 to 90 MHz slower than the default at 0.5 and 2 per second. So the small gap between the two chunks is not a chunk effect.
The scheduler rule from the start of this section fits the L4 result. Prefill wins whenever the scheduler can admit something. With a full queue, a smaller chunk adds more prefill turns ahead of the decode steps, and the stream still waits.
--enable-mixed-chunk puts the decode tokens into the prefill batch, so a decode step does not wait for a prefill turn. We ran it on the L4 against a new default run in the same session, at a median clock of 953 to 1,095 MHz.
| Rate, per second | Output tok/s, default / mixed chunk | P99 ITL, default / mixed chunk |
|---|---|---|
| 0.5 | 46.5 / 46.5 | 2,521 / 2,406 ms |
| 1 | 46.6 / 47.5 | 2,491 / 2,289 ms |
| 2 | 47.3 / 47.6 | 2,572 / 2,418 ms |
The mixed chunk lowered the median P99 ITL by 5 to 8 percent, and the seed ranges overlapped at every rate. The worst token gap still took more than 2.2 s. On our L4 with Qwen3-8B, a card that cannot keep up with these prompts, neither flag gave the stream a smooth flow. We expect the fix to be more prefill capacity or fewer long prompts per second, but we did not test it.
The GB10 keeps up with this workload, and there the mixed chunk did help. We ran it with the same sweep on 2026-10-21, against a new default run on the same day. The default server had a pool of 251,910 tokens and the mixed-chunk server 236,751 tokens. Every run had a median clock of 2,405 MHz or more.
[2026-10-21 06:26:47] KV Cache is allocated. dtype: torch.bfloat16, #tokens: 236751, K size: 10.84 GB, V size: 10.84 GB| Rate, per second | P99 ITL, default / mixed chunk | Median TTFT, default / mixed chunk | Output tok/s, default / mixed chunk |
|---|---|---|---|
| 0.5 | 922 / 781 ms | 841 / 910 ms | 70.9 / 72.1 |
| 1 | 219 / 177 ms | 244 / 362 ms | 108.8 / 112.6 |
| 2 | 261 / 221 ms | 238 / 416 ms | 133.2 / 138.1 |
We measured a smoother stream and a slower first token. The P99 ITL fell by 15 to 19 percent, outside the seed spread at 0.5 and at 2 per second. The median TTFT rose by 49 to 74 percent at 1 and 2 per second, outside the seed spread. Throughput rose by 2 to 4 percent, inside the spread. Raw runs
The default run from 2026-10-17 gave the same direction. Against it, the P99 ITL fell by 16 to 29 percent. The median TTFT rose by 35 and 54 percent at 1 and 2 per second. The cache caution above applies to both servers at 1 and 2 per second.
On our two cards with this workload, the flag was a trade, and the card decided whether you get it. When prefill keeps up, the decode tokens that ride in the prefill batch stop waiting, and each new prompt waits a little longer. When prefill cannot keep up, as on the L4, the queue sets the pace and the flag changes little.
[2026-10-18 07:27:15] Memory pool end. avail mem=2.90 GB
Capturing prefill shape (num_tokens=8192 avail_mem=2.33 GB)
torch.AcceleratorError: CUDA error: out of memory
[2026-10-18 07:28:44] RuntimeError: num_active_captures_ > 0 INTERNAL ASSERT FAILED at "/__w/pytorch/pytorch/c10/cuda/CUDACachingAllocator.cpp":3209, please report a bug to PyTorch. markCaptureEnd called with no captures in progressThe other direction failed on the L4 at startup. With a chunk of 8,192, the KV pool took the same 24,094 tokens as before. The prefill graph for 8,192 tokens then needed more than the 2.33 GB that remained. The last line of the log is a PyTorch assert that asks for a bug report. The real error is the out-of-memory line above it.
Our position
Keep fcfs. It is fair, it does not sort the queue by prefix, and the radix cache still gives you the cache hits. A shared prefix that arrived first is in the tree when the next request matches it, whatever the order.
Switch to lpm only when three things are true. Your traffic shares long prefixes. Your queue is often between a few and 128 requests deep. You measured the cache hit rate before and after with /metrics. Section 5.2 shows the cache_hit_rate series to compare.
If you need tiers of users, use --enable-priority-scheduling instead of a cache policy. A new request can then preempt running ones when its priority beats theirs by --priority-scheduling-preemption-threshold, 10 by default.
An incident: the limit you set is not the limit you get
A user served a hybrid Mamba model and set --max-running-requests 8. The server accepted the flag and reported 8. Throughput flattened at 2 streams anyway. Only an info line in the log said that the Mamba state cache capped max_running_requests to 2.
The scheduler loop admits against every limit at once, and the smallest one wins. The fix the reporter used was more Mamba cache, --max-mamba-cache-size 40 with bf16 state and --mem-fraction-static 0.90, for 75 percent more throughput at concurrency 12. At v0.5.22 the cap is a warning. Read the log for the limit that the loop really uses, not the one you typed.
Admission and retraction
SGLang admits a request only when a forecast of its future tokens fits the KV pool, so a full server queues new users instead of breaking the running ones.
Your dashboard says the GPU has free memory, yet new requests wait 28 seconds for their first token. Nothing crashed, nothing was dropped, and the per-token speed is fine. Users still feel that the service is down. This is what admission control looks like when it does its job, and you need to know why it chose to make them wait.
When you finish this section, you can explain the token budget that decides admission and compute how many requests fit in a pool. You can also tell a healthy queue from a retraction problem in the log.
The cost: memory you will need later
A request needs KV cache for its prompt now, and for every token it generates later. The scheduler does not know how many tokens a request will generate. It knows only max_new_tokens, the upper limit.
There are two obvious fixes, and both fail. Reserve the full max_new_tokens for everyone, and most of the pool sits empty, because most requests stop early at an end-of-sequence token. Reserve nothing, and the pool fills during decode, and the server must throw away work.
The forecast
SGLang uses a forecast with a correction. Two rules decide admission:
- A new request must fit its uncached prompt tokens plus its remaining
max_new_tokens, clipped to 4,096 bySGLANG_CLIP_MAX_NEW_TOKENS_ESTIMATION. - Each running request holds back its remaining
max_new_tokenstimes the new token ratio.
New token ratio: the share of remaining output that the scheduler expects a running request to use. It starts at 0.7 times --schedule-conservativeness (1.0 by default). It falls linearly to 0.14 of its start value, which is 0.098 at defaults, over 600 decode steps.
The ratio falls because most requests stop early. The scheduler grows bolder the longer things go well. A request with ignore_eos set cannot stop early, so its ratio is always 1.0.
What we measured with a small pool
We started a server with --max-total-tokens 4096, a pool far smaller than our Mac allows. Then we ran the benchmark at concurrency 16 with 256-token prompts and 512-token outputs.
The benchmark client sets ignore_eos to true by default, so every request generates exactly 512 tokens. Each request therefore reserves 256 plus 512, which is 768 tokens. Five requests reserve 3,840 tokens, and a sixth would need 4,608. The scheduler admitted exactly five.
[2026-10-16 14:08:02] Prefill batch, #new-seq: 1, #new-token: 1, #cached-token: 255, token usage: 0.06, #running-req: 0, #queue-req: 15, #pending-token: 0, cuda graph: False, input throughput (token/s): 0.80
[2026-10-16 14:08:02] Prefill batch, #new-seq: 4, #new-token: 896, #cached-token: 0, token usage: 0.28, #running-req: 1, #queue-req: 11, #pending-token: 2808, cuda graph: False, input throughput (token/s): 3889.60
…
[2026-10-16 14:08:14] Decode batch, #running-req: 5, #token: 1517, token usage: 0.37, cuda graph: False, gen throughput (token/s): 170.33, #queue-req: 11
[2026-10-16 14:08:17] Decode batch, #running-req: 5, #token: 2117, token usage: 0.52, cuda graph: False, gen throughput (token/s): 205.04, #queue-req: 11
…
[2026-10-16 14:08:26] Decode batch, #running-req: 5, #token: 3717, token usage: 0.91, cuda graph: False, gen throughput (token/s): 139.02, #queue-req: 11Watch token usage. It climbs from 0.28 to 0.91 as the five requests generate into the space that the forecast reserved for them. Eleven requests wait the whole time. When the five finish, the next five start, and the log repeats in waves.
The client saw the cost of this order:
Successful requests: 32
…
Concurrency: 13.06
…
Median TTFT (ms): 27943.11
…
Mean TPOT (ms): 24.26 Every request succeeded. Once a request started, each token took 24 ms. The median user still waited 27.9 seconds for the first token. The Concurrency value of 13.06 is the client's average number of open requests. Only five of them were on the GPU at any time.
Retraction: when the forecast is wrong
The forecast can be too bold, because the ratio decays to 0.098. Requests that run long then need more slots than the pool has. Before each decode step, the scheduler checks that every running request can get one more slot.
Retraction: removing running requests from the decode batch to free their KV slots, and putting them back in the waiting queue. They prefill again later.
When the check fails, SGLang logs KV cache pool is full. Retract requests.. It retracts the requests with the fewest output tokens first, and among those the longest prompts first, because they lost the least work. It resets the ratio to a new estimate: tokens decoded so far plus 20 per request, divided by the total max_new_tokens. At v0.5.22, if even the last request cannot fit, it aborts that request with "Out of memory even after retracting all other requests" instead of looping.
Our small-pool run had no retractions at all. Its server log has no Retract requests line. The metrics endpoint agrees, with one limit. num_retracted_reqs is a gauge that the scheduler resets after each log interval. So a reading of 0 covers only the last interval. The counter num_retracted_requests_total covers the whole run.
sglang:num_retracted_reqs{engine_type="unified",model_name="mlx-community/Qwen3-0.6B-4bit",moe_ep_rank="0",pid="38678",pp_rank="0",tp_rank="0"} 0.0The forecast had nothing to correct. With ignore_eos, the reservation was exact. Real traffic stops early, so the ratio decays and admission becomes bolder, and retraction becomes possible.
Incidents: when retraction is the problem
A server running DeepSeek-R1 on eight H20 GPUs logged KV cache pool is full. Retract requests. on every rank, again and again, and then stopped answering health checks. A commenter traced it to retraction that could not free enough memory and repeated forever. The issue closed without a fix. At v0.5.22 the scheduler aborts the last request when it is still out of memory after it retracts all the others. That abort is meant to end the loop. We did not reproduce the issue.
Another user saw decode throughput fall from about 429 to between 20 and 38 tokens per second after a retraction, and stay there. That issue closed for inactivity with no recorded cause. The lesson stands: a retraction in the log is a performance alarm.
Our position
Queueing is the honest failure. A queue keeps every running request fast and makes the overload visible in #queue-req and in time to first token. Retraction hides overload as wasted prefill.
The SGLang tuning docs say an occasional retraction, about one per minute, is fine. Treat more than that as a configuration bug. Raise --schedule-conservativeness, for example to 1.3, so the forecast starts higher. Or lower --max-running-requests. Do not fix it with a larger --mem-fraction-static alone, because section 3.2 shows what that costs.
Set realistic max_new_tokens in your clients. A client that asks for 4,096 tokens and uses 200 makes the output reservation of every new request about 20 times too big.
The overlap scheduler
The overlap scheduler prepares batch N+1 on the CPU while the GPU runs batch N, and at v0.5.22 it is the default path.
Profile a simple serving loop and you find gaps on the GPU timeline between decode steps. In each gap the GPU waits while Python reads the sampled tokens, checks stop strings, frees memory, and builds the next batch. A decode step on a small model takes a few milliseconds, so a gap of one millisecond is a large share of the step.
When you finish this section, you can explain how SGLang hides the CPU work between steps and say when the overlap is off. You can decide whether --disable-overlap-schedule belongs in your command.
The cost: CPU time between GPU steps
Overlap scheduling: running the CPU work for one batch at the same time as the GPU work of another batch.
The SGLang team described the problem in the v0.4 release post. Batch scheduling, memory allocation, and prefix matching leave the GPU idle between steps. Their answer is a scheduler that runs one batch ahead and prepares all the metadata for the next batch. They report a 1.1x throughput gain from it. That number is their claim, measured on their GPUs.
The obvious fix is a second thread that builds batches while the first one runs the GPU. Python threads share one interpreter, so a scheduler thread and a forward thread take turns. SGLang tried a thread first. Since pull request #11210 in October 2025 it uses two CUDA streams in one thread instead.
How it works on CUDA
The loop launches batch N+1 on the GPU first, and then processes the results of batch N on the CPU. The GPU never waits for the bookkeeping of the step before.
There is a problem. Batch N+1 needs the tokens that batch N sampled, and those tokens are still on the GPU when N+1 is built. SGLang builds N+1 with placeholder token ids. A FutureMap fills in the placeholders on the GPU from the output of N. The CPU never needs to read the tokens before the launch.
How it works on a Mac
The MLX backend has its own overlap loop, event_loop_overlap_mlx. MLX evaluates lazily, so the loop keeps two decode graphs queued with mx.async_eval. The docstring says that the GPU runs the next step right after the current one, with no scheduling gap on the device. The chain breaks when a prefill arrives, a request finishes, or the waiting queue has new work. Then the loop builds a fresh step.
The scheduler is the same Python scheduler on CUDA and on MLX. The batching, the radix tree bookkeeping, and the log lines in section 2.2 are the same. Only the forward pass and the overlap mechanism differ.
What happened when we turned it off
The Apple silicon page of the SGLang docs lists --disable-overlap-schedule as one of the key parameters for the MLX backend. We added it to our server command and ran the concurrency 8 benchmark. The server answered its own warm-up and the benchmark warm-up. Then the scheduler died on the first batch of the real run.
[2026-10-16 14:07:15] Prefill batch, #new-seq: 1, #new-token: 1, #cached-token: 511, token usage: 0.00, #running-req: 0, #queue-req: 0, #pending-token: 0, cuda graph: False, input throughput (token/s): 0.39
[2026-10-16 14:07:16] Scheduler hit an exception: Traceback (most recent call last):
…
scheduler.event_loop_normal()
…
File "/private/tmp/sglang-research/sglang-v0.5.22/python/sglang/srt/managers/scheduler.py", line 4746, in run_batch
self._relay_forward_payload(
File "/private/tmp/sglang-research/sglang-v0.5.22/python/sglang/srt/managers/scheduler.py", line 4852, in _relay_forward_payload
self.future_map.stash(future_indices, payload)
File "/private/tmp/sglang-research/sglang-v0.5.22/python/sglang/srt/managers/overlap_utils.py", line 639, in stash
self.output_tokens_buf[indices] = payload.bonus_tokens.to(
…
RuntimeError: Expected all tensors to be on the same device, but found at least two devices, mps:0 and cpu!Read the stack from the bottom. With the overlap off, the dispatcher picks event_loop_normal, the generic loop. That loop calls run_batch, which still relays the sampled tokens through the FutureMap of the overlap machinery. On MLX the buffer lives on the Metal device and the sampled tokens arrive on the CPU, and PyTorch refuses to mix them. The overlap loop for MLX does not take this path, so the default server never reaches it.
The main process then shut everything down. Every one of the 32 benchmark requests failed: 8 were cut off during their response, and 24 could not connect after the server was gone.
Warmup completed with 1 sequences. Starting main benchmark run...
…
requests.exceptions.ConnectionError: HTTPConnectionPool(host='0.0.0.0', port=30000): Max retries exceeded with url: /server_info (Caused by NewConnectionError("HTTPConnection(host='0.0.0.0', port=30000): Failed to establish a new connection: [Errno 61] Connection refused"))It failed this way in our one MLX recording. We report it as we found it: a flag that the platform docs recommend crashed the platform at the pinned release.
The same kit configuration ran on CUDA without errors, on the L4 and on the GB10, with 64 of 64 requests served. Each card ran it once with the overlap on and once with it off, at 8 users. The two results disagree:
| Card, model | Output tok/s, overlap on / off | Median TPOT, overlap on / off |
|---|---|---|
| L4, Qwen3-8B | 73.71 / 84.17 | 91.24 / 69.38 ms |
| GB10, Qwen3-30B-A3B | 78.92 / 73.59 | 97.30 / 103.21 ms |
On the L4 the server without the overlap was 14 percent faster, and on the GB10 it was 7 percent slower. These are single runs without clock records, so a hot card can explain either one. They do not show the 1.1x gain that the SGLang team reports, and they do not disprove it.
A GPU incident with the same root
On CUDA, a user ran with overlap on and hit an allocation failure right after KV cache pool is full at 94 percent token usage. Under overlap, the next batch is planned while the tokens of the previous one are still being computed. Retraction had to reason about requests that would finish one step later. A fix proposed in pull request #15626 closed without merge. At v0.5.22 the scheduler removes requests that will finish by length from the next decode batch. It also skips retraction in a step where finishing requests will free KV.
Both stories have one lesson. Overlap is a second copy of the timeline in the scheduler's head, and every feature has to agree with it.
Our position
Leave the overlap on unless a measurement on your own card says otherwise. It is the default, and it is designed to hide CPU time that you would otherwise pay on every step. Our two single runs on CUDA disagreed, so measure both settings with a clock record before you change it.
Turn it off for one reason: to rule it out while you debug a wrong output or a hang. Expect the off path to be less tested, and test it on your hardware before you depend on it. SGLang itself turns the overlap off where it cannot work, for example on Apple MPS without MLX and for speculative decoding on CPU.
Streaming, stop strings, and the OpenAI API
SGLang checks stop conditions in the scheduler and builds text in the detokenizer, and its native /generate endpoint reports the timing and cache data that the OpenAI format leaves out.
You stream a reply to a chat window, and the last word before your stop string arrives late. Or the stop string itself leaks into the text when speculative decoding is on. Or the client shows no cached_tokens at all, so you cannot tell whether your prompt hit the cache. All three are decisions about where text is made and who reports what.
When you finish this section, you can choose between the native /generate endpoint and the OpenAI endpoints. You can read every timing field in a native response and explain why streamed text sometimes waits.
Two APIs on one server
Native API: SGLang's own endpoints, mainly POST /generate. It takes text or token ids and sampling_params, and it returns a meta_info object with SGLang's own data.
OpenAI API: the /v1/chat/completions, /v1/completions, and /v1/models endpoints, in the format that OpenAI clients expect. The server applies the chat template before it tokenizes.
Both endpoints build the same internal request and cross the same three processes from section 2.1. The difference is what comes back.
What the native response tells you
Our capture kit sends one native request with 12 output tokens at temperature 0.
{
"text": " Paris, and the capital of Germany is Berlin. The capital",
…
"meta_info": {
"id": "e272e3ffc4064bfeaa0223b86408e107",
"finish_reason": {
"type": "length",
"length": 12
},
"prompt_tokens": 5,
…
"num_retractions": 0,
…
"queue_time": 0.0002437499351799488,
"reasoning_tokens": 0,
"completion_tokens": 12,
"cached_tokens": 2,
…
"cached_tokens_details": {
"device": 2,
"host": 0
},
"dp_rank": null,
"e2e_latency": 0.9496850408613682,
…
"first_token_latency": 0.8885334208607674,
…
"decode_throughput": 179.8807619469758,
…
}
}Every field answers a question you will ask in production:
finish_reasonsays why it stopped:lengthhere, because the request asked for 12 tokens and got 12.queue_timeis 0.24 ms, so the request did not wait. Under load, this number grows while requests wait in the queue.first_token_latencyis 889 ms ande2e_latencyis 950 ms. The first token cost most of the time on a cold server.num_retractionsis 0. Section 2.3 explains what a nonzero value costs.cached_tokensis 2 of 5 prompt tokens, all on the device and none from host memory.
Two cached tokens on the first request of our kit is a small mystery with a clean answer. Before it accepts traffic, the server warms up with the prompt The capital city of France is. Our prompt was The capital of France is. The first two tokens matched the warm-up in the radix tree. The cache does not care which user sent a prefix.
What the OpenAI response tells you
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Ardens",
"reasoning_content": null
},
"logprobs": null,
"finish_reason": "stop",
"matched_stop": 151645
}
],
"usage": {
"prompt_tokens": 21,
"total_tokens": 25,
"completion_tokens": 4,
"prompt_tokens_details": {
"cached_tokens": 0
},
"reasoning_tokens": 0
},We asked for one planet in one word. The 4-bit 0.6B model answered "Ardens", which is not a planet. Keep that in mind when you judge a serving engine with a tiny model. The engine did its job: it stopped at token 151645, the end-of-turn token, and reported matched_stop.
The cached_tokens field is there only because our server runs with --enable-cache-report. Without the flag, SGLang omits the cache details from OpenAI usage, even though it computes them for every request. The native meta_info reports cached_tokens either way.
A note for Mac readers. On MLX at v0.5.22, decode is greedy unless you pass --mlx-enable-sampling, so temperature, grammar masks, and output logprobs have no effect there. The help text of sglang serve says so. Our kit uses temperature 0, so its outputs are the same either way. Section 4.6 covers sampling and logprobs on GPUs.
Where stop strings are checked
Stop condition: a rule that ends a request. It can be a stop token, a stop string, a regex, the max_new_tokens limit, an abort, or the end of a grammar.
SGLang checks stop conditions in the scheduler, after each step, in a fixed order. A stop string is checked before the end-of-sequence token. The code comment gives the reason. Speculative decoding can accept more than one token in a step. A check by token would trim only the last token, and the rest of the stop string would leak into the output. The detokenizer only trims the matched stop text from the output.
Why streamed text waits
Two rules can delay a chunk:
- Incomplete characters. The detokenizer decodes incrementally with two offsets per request. If the new text ends in an incomplete UTF-8 character, it waits for the next token before it sends anything.
- A possible stop string. If the tail of the text could be the start of a stop string, the output streamer holds it back. If the next tokens complete the stop string, the text never appears. If they do not, the held text goes out with the next chunk.
With the default --stream-interval 1, SGLang streams after every step. A non-streaming request still sends progress inside the server every 50 tokens, SGLANG_FORCE_STREAM_INTERVAL, so the TokenizerManager can track it.
An incident: the detokenizer that never moved
The incomplete-character rule has a cost when the tokens never complete a character. The detokenizer waits while the text ends in the replacement character U+FFFD. Byte tokens that never complete a character never advance the offsets. Every step then decodes the whole tail again, and the work grows with the square of the length. The report found it with a test setting that fills id 100, which decodes to U+FFFD on DeepSeek-V4-Pro. The issue was open when we checked.
Our position
Use the native /generate endpoint when you debug, measure, or build your own client. Its meta_info tells you queue time, first token latency, cache hits, and retractions per request. The OpenAI format has no place for most of that.
Use the OpenAI endpoints for applications that already speak that format. Start every server with --enable-cache-report, so those clients can see cache hits too. We did not measure a cost, and part 3 shows how much the number is worth.
The KV Cache
Memory, not compute, decides how many users one GPU can serve, and the radix tree decides how much of that memory you pay for twice.
The KV pool and bytes per token
SGLang stores every token of every running request in one pool of fixed-size slots, so a model's bytes per token decide how many users one GPU can serve.
You rent a GPU with 80 GB of memory for an 8-billion-parameter model. The weights take about 16 GB, so most people expect room for a large number of users. Then the server queues requests at a few dozen concurrent conversations, and the GPU still shows free compute. The weights did not fill the memory. The keys and values of every token did.
When you finish this section, you can compute the KV cost of a model from its config. You can find the same number in the startup log and explain why SGLang counts capacity in tokens.
Why the cache exists
KV cache: the stored keys and values of every earlier token, for every layer, kept so that decode does not compute them again. A decode step makes one new token. That token attends to the keys and values of all the tokens before it. Without the cache, each new token would repeat the whole prefill of the conversation.
So the cache grows with two things: the length of each conversation and the number of conversations that run at the same time. After the weights, it is the largest user of memory in a serving engine. Every scheduling decision in Part 2 is a decision about this memory.
The formula, and our first measured number
For a model with ordinary multi-head or grouped-query attention, one token costs this many bytes:
2 × layers × KV heads × head dim × bytes per value
The 2 counts the key and the value. Grouped-query attention: several query heads share one key and value head, which is why modern models have far fewer KV heads than attention heads. SGLang computes this number when it starts. On our Mac, the MLX backend printed it in the first lines of the log.
[2026-10-16 13:58:03] Auto-sized attention KV pool: sys_available=48.49 GB, mlx_limit=51.8 GB, mlx_used=0.31 GB, kv_budget=19.39 GB, bytes_per_slot=114688, pool_size=181574
…
[2026-10-16 13:58:08] MlxAttentionKVPool: 181575 slots x 28 layers x 8 heads x 128 dim, dtype=mlx.core.bfloat16, ~19859.8 MBWe measured bytes_per_slot=114688 for Qwen3-0.6B. The second line gives every term: 28 layers, 8 KV heads, a head dimension of 128, and bfloat16, which is 2 bytes. So the cost is 2 × 28 × 8 × 128 × 2, which is 114,688 bytes, or 112 KiB per token. The formula and the log agree to the byte.
The same arithmetic on public model configs gives these costs:
| Model | Attention | Bytes per token, bf16 | Per GPU |
|---|---|---|---|
| Qwen3-0.6B (our capture) | GQA, 28 layers, 8 KV heads | 112 KiB | 112 KiB on one GPU |
| Llama-3.1-8B | GQA, 32 layers, 8 KV heads | 128 KiB | 128 KiB on one GPU |
| Llama-3.1-70B | GQA, 80 layers, 8 KV heads | 320 KiB | 40 KiB with 8-way tensor parallelism |
| DeepSeek-V3 | MLA, 61 layers, latent 512 plus 64 | 68.6 KiB | 68.6 KiB on every GPU |
Two results surprise most people. A 0.6B model costs almost as much per token as an 8B model. The layer count and the KV heads decide the cost, and the parameter count does not. A 100,000-token conversation on Llama-3.1-8B holds 12.2 GiB of KV, which is close to the size of the weights.
Multi-head latent attention (MLA): DeepSeek's attention, which stores one compressed latent per token instead of separate keys and values per head. MLA is small per token, but every tensor-parallel rank stores the full latent. Add GPUs with tensor parallelism and you do not add tokens. Section 6.1 shows how data-parallel attention answers that problem.
Two tables, one pool
SGLang keeps the KV cache in a pool of fixed-size slots, one slot per token. Two tables sit in front of it, and they answer different questions.
ReqToTokenPool: a table with one row per running request and one column per token position. Each cell holds the index of a slot in the KV pool. Row 0 is padding, so that padded batch entries write to a harmless place.
TokenToKVPoolAllocator: the free list of KV slots. It gives out slot indices when a request needs room and takes them back when the request ends. Slot 0 is reserved for the same padding reason. That is why our log shows a buffer of 181,575 slots for a pool of 181,574.
The physical pool holds the tensors. Attention kernels read the keys and values through the request's row in ReqToTokenPool. This design has one large effect. Two requests that share a prefix can point their rows at the same slots, so the shared tokens exist once in memory. Section 3.3 shows the radix tree that finds those shared slots.
The cache is the pool
SGLang has no separate setting for cache size. The SGLang paper makes this a design choice: cached tokens and running requests use one memory pool. A cached prefix is KV that no running request locks right now. When a new request needs room, SGLang evicts prefixes that no request locks, from the same pool.
This is why the startup log reports one number, max_total_num_tokens, and not two. On our Mac with --mem-fraction-static 0.4, that number was 181,574 tokens. The model allows a context of 40,960 tokens. So the pool holds four full-length conversations, or about 180 conversations of 1,000 tokens each. Running requests and cached prefixes compete for those same slots.
Our position: count tokens, not gigabytes
Size a deployment from max_total_num_tokens, not from free memory. Multiply your typical context length by the concurrency you need, and compare the product with that number. If the product is larger, the scheduler retracts or queues requests, and section 2.3 shows what that costs.
The two levers that change the number are the memory fraction in section 3.2 and the KV data type. --kv-cache-dtype defaults to auto, which keeps the model data type unless the checkpoint asks for FP8. FP8 halves the bytes per token.
A field report shows the size of that lever. Cloudflare reported that FP8 KV raised the context held in memory for Kimi K2.6 from about 686,000 to about 1.37 million tokens. The same report measured a few percent less throughput per request at low concurrency. At concurrency 64, the BF16 configuration ran out of memory, and the FP8 configuration reached 2,192 tokens per second. In that report, FP8 KV traded a little speed per token for twice the users.
Our own FP8 runs changed the weights and the KV cache together, and they were faster per user. On the L4 they gave 24.5 against 13.4 tokens per second at 1 user, as section 4.3 shows. Read the Cloudflare post for their accuracy checks before you copy the change.
The Inside an LLM Serving GPU machine draws the KV pool as cells on the six GDDR6 packages of an L4. This link opens the BF16 run at 64 users: the 24,094-token pool holds 37 requests of 640 tokens, and the other 27 wait. Switch the weights and the KV cache to FP8 to see the pool grow to 142,369 tokens.
What to measure
- Read
bytes_per_slotor compute it, and check that the two agree. - Read
max_total_num_tokensin the startup log, and divide it by your typical context length. - Watch
token usagein the scheduler log. It is the fraction of the pool that running requests and cached prefixes hold.
The lesson on inference optimization builds a KV cache from scratch, if you want the mechanism below SGLang.
--mem-fraction-static and startup sizing
SGLang sizes the KV pool once at startup from a snapshot of free memory, so a machine that changes after startup can kill the whole server.
One of our first SGLang servers on the capture Mac ran for four minutes. Then a benchmark at 32 concurrent requests crashed it with a Metal out-of-memory error, and every process of the server exited. The KV pool at that moment was 95 percent empty. The memory had gone to the pool, and the next prefill had nowhere to run.
When you finish this section, you can read how SGLang divides memory at startup and predict when that division fails. You can also set --mem-fraction-static on purpose.
The crash we recorded
We started the server twice before the capture kit existed, with the same command and no --mem-fraction-static. The two startups sized the pool very differently.
# run 1 startup
[2026-10-16 13:30:31] Auto-sized attention KV pool: sys_available=27.81 GB, mlx_limit=51.8 GB, mlx_used=0.31 GB, kv_budget=24.25 GB, bytes_per_slot=114688, pool_size=227022
# run 2 startup
'mem_fraction_static': 0.872
[2026-10-16 13:38:58] Auto-sized attention KV pool: sys_available=38.29 GB, mlx_limit=51.8 GB, mlx_used=0.31 GB, kv_budget=33.39 GB, bytes_per_slot=114688, pool_size=312581Nothing changed in SGLang between the runs. Other programs on the Mac used less memory at the second start, so sys_available grew from 27.81 GB to 38.29 GB. The pool grew with it, from 24.25 GB to 33.39 GB. Both budgets are 87.2 percent of the free memory, because the automatic mem_fraction_static resolved to 0.872.
[2026-10-16 13:42:53] Decode batch, #running-req: 32, #token: 16095, token usage: 0.05, cuda graph: False, gen throughput (token/s): 564.55, #queue-req: 0
[2026-10-16 13:42:55] Prefill batch, #new-seq: 1, #new-token: 511, #cached-token: 0, token usage: 0.00, #running-req: 0, #queue-req: 9, #pending-token: 0, cuda graph: False, input throughput (token/s): 66.85
RuntimeError: [METAL] Command buffer execution failed: Insufficient Memory (00000008:kIOGPUCommandBufferCallbackErrorOutOfMemory).
[2026-10-16 13:42:57] SIGQUIT received. signum=None, frame=None. It usually means one child failed.
…
[2026-10-16 13:43:02] kill_process_tree called: parent_pid=81559, include_parent=True, pid=81559Read token usage: 0.05 first. Thirty-two requests held 16,095 tokens, which is 5 percent of a 312,581-token pool. The pool reserved 33 GB and used under 2 GB of it. The activations of the next forward pass needed memory outside the pool, and the operating system had none left. One failed command buffer took down the scheduler, and the server killed its whole process tree.
How SGLang decides the split
--mem-fraction-static: the share of memory that SGLang gives to the model weights plus the KV pool. Everything outside that share is for activations, CUDA graphs, and other programs. The flag defaults to None, and SGLang computes a value at startup.
On a GPU, the automatic value comes from a reserve. SGLang starts with 512 MB and adds 1.5 MB for each token of the prefill chunk. Then it adds more for tensor and pipeline parallelism and for CUDA graphs. On a GPU with more than 60 GB, the reserve is at least 10 GiB. The fraction is then the GPU memory minus the reserve, divided by the GPU memory. When SGLang cannot read the device capacity, it uses 0.95.
After the weights load, SGLang measures free memory again. The KV budget is the free memory minus the 1 - fraction share of the memory that was free before loading. The pool holds that budget divided by the bytes per token from section 3.1. If the budget is not positive, startup stops and prints the smallest fraction that would work.
The MLX backend on Apple silicon uses a simpler rule. It takes the smaller of two numbers. The first is the fraction of the Metal working set, minus memory already in use. The second is the fraction of system memory available right now. The second term is the snapshot that changed between our two runs.
Read the fraction as the share for the weights and the KV pool together. That is what the code does.
The default assumes the machine belongs to SGLang
The automatic rule is reasonable on a dedicated GPU. Nothing else allocates memory there, and the reserve covers the activations of one prefill chunk and the CUDA graphs. The rule fails in three common cases.
- A shared machine. A laptop, a workstation, or a node with other jobs. The snapshot at startup does not hold for the life of the server.
- Unknown capacity. On a device where SGLang cannot read the memory size, the fraction becomes 0.95 and leaves 5 percent for activations. Issue #39675 reports exactly that failure on Apple MPS, an out-of-memory error on the first prefill.
- Extra memory the estimate does not know about. Issue #42510 shows draft-model copies that stay in memory while the target pool is sized, so the draft pool allocation fails. Issue #6027 shows a 64K-token DeepSeek-V3 prompt that ran out of memory in attention, although the log reported room for 274,934 KV tokens.
Unified memory on a GB10
We measured the same rule on an NVIDIA GB10, the chip of a DGX Spark. Its CPU and GPU share 121.7 GiB of memory. There is no separate GPU memory, and that changes what each number in the startup log means. Raw runs
[2026-10-17 14:12:57] Failed to get GPU memory capacity from nvidia-smi. Falling back to torch.cuda.mem_get_info(). Reported total GPU memory per device (MiB): [124610], using min: 124610 MiB.
…
[2026-10-17 14:13:05] Load weight begin. avail mem=112.59 GB
…
[2026-10-17 14:18:29] Load weight end. elapsed=323.61 s, type=Qwen3MoeForCausalLM, avail mem=54.84 GB, mem usage=57.75 GB.
[2026-10-17 14:18:32] KV Cache is allocated. dtype: torch.bfloat16, #tokens: 227243, K size: 10.40 GB, V size: 10.40 GB
[2026-10-17 14:18:32] Memory pool end. avail mem=31.22 GBThe first line is the capacity. nvidia-smi reports no memory size for the GB10, so SGLang takes the total from PyTorch.
The second line is free memory, and here the code is careful. On a device that shares system memory, torch.cuda.mem_get_info() counts the file cache of the kernel as used. On a day with a large file cache, that reading can be far below what the machine can give. SGLang checks whether the device is integrated, and then it reads the available memory of the operating system instead. That number counts cache that the kernel can free. In our recording after a reboot, the two numbers agreed: 112.1 GiB from PyTorch and 112.59 GB from SGLang.
The cost of that choice is that the pool size moves with the rest of the machine. Six BF16 starts used the same command and the same weights:
| Configuration | Available before weights | Weights, as SGLang measured them | KV pool, tokens |
|---|---|---|---|
| default | 112.59 GB | 57.75 GB | 227,243 |
| no CUDA graph | 113.21 GB | 54.78 GB | 258,017 |
| deterministic | 113.44 GB | 57.90 GB | 234,517 |
| no radix cache | 113.17 GB | 57.34 GB | 236,315 |
| no overlap | 113.37 GB | 57.92 GB | 233,822 |
| EAGLE-3, with a draft model | 113.45 GB | 57.49 GB | 216,775 |
The weights did not change, yet their measured size went from 54.78 GB to 57.92 GB. SGLang measures them as the drop in available memory, and the kernel cache changed during each load. Among the five starts without a draft model, the pool differs by 14 percent. The flags do not explain the spread, because the same weights measured 3 GB apart. On unified memory, a pool size from one start is an estimate for the next start, not a constant.
A pool that other programs see
On a GB10, the KV pool is tens of GB, and SGLang allocates it in a few seconds. Every other program on the machine sees that memory go. Our GB10 also ran a memory guard daemon for its other users. It stops the process that grows fastest when free memory gets low. It stopped our scheduler three times during startup:
2026-10-16T12:53:16+00:00 2026/10/16 12:53:16 guardian level: Critical: 34.2 GiB left before the freeze zone.
2026-10-16T12:53:16+00:00 2026/10/16 12:53:16 guardian pause: Paused sglang::schedul (pid 2983880, rohit): it grew 36.7 GiB in 5s with 34.2 GiB left. Resume or stop it from the app.We did not keep the server logs of those three starts. The guard log shows the scheduler growing by 36.7 GiB in 5 seconds, which is the size of a KV pool allocation. The guard was correct by its own rule: the scheduler was the fastest-growing process. Seconds later the guard logged "Back to normal", because the pool was complete. We agreed with the owner of the machine to stop the guard for the time of our runs.
The NVIDIA driver also reports memory errors at startup. The kernel log of the GB10 holds bursts of this line:
NVRM: nvCheckOkFailedNoLog: Check failed: Out of memory [NV_ERR_NO_MEMORY] (0x00000051) returned from _memdescAllocInternal(pMemDesc) @ mem_desc.c:1359The bursts are dated 2026-10-16, the day of our first test and sweep starts on the GB10. We did not keep the server logs of that day, so we cannot match each burst to one start. Every server in our later captures became healthy and finished its benchmarks.
Our position: on unified memory, the KV pool is memory that the whole machine gives up. Pass --mem-fraction-static on purpose, and tell the other users of the machine before you start. Do not alert on the driver line alone. Alert when a server does not become healthy.
Memory outside the fraction
The fraction does not bound all the memory that SGLang takes at startup. One user served a 27B model with SGLang on a DGX Spark. The user reported 25 to 40 GB of short-lived allocations outside the memory accounting of SGLang. The FlashInfer autotuner and the CUDA graph capture made them. Run directly on the host, the server froze the machine, and it needed a power cycle. The user then ran it in a container with a memory cap and --mem-fraction-static 0.50.
That is a field report from before v0.5.22, and it does not name its SGLang version. Treat it as a warning, not as a fact about v0.5.22. We did not measure it ourselves. Our guard log above shows a fast growth at startup, but it does not separate the pool from the other allocations.
On a GB10 that other programs share, start SGLang in a container with a memory limit. Start below the fraction of 0.7 that our kit used. Log the free memory of the machine once a second during startup. Raise the fraction only after you saw the peak.
Our position: set the fraction yourself on any shared machine
On a machine that runs anything besides SGLang, pass --mem-fraction-static yourself. The capture kit uses 0.4 on the Mac. With that value, the same benchmark that crashed run 2 finished all 128 requests at concurrency 32.
[2026-10-16 13:58:03] Auto-sized attention KV pool: sys_available=48.49 GB, mlx_limit=51.8 GB, mlx_used=0.31 GB, kv_budget=19.39 GB, bytes_per_slot=114688, pool_size=181574The budget is now 19.39 GB, which is 0.4 of the 48.49 GB snapshot. The pool still holds 181,574 tokens, far more than 32 requests of 640 tokens need. A smaller pool cost nothing in this workload, because the workload never filled the pool.
We tested the other direction on the GB10. The load sweep of section 5.1 ran twice, at the kit's fraction of 0.7 on 2026-10-16 and at 0.82 on 2026-10-17, three seeds per point.
[2026-10-17 16:35:26] KV Cache is allocated. dtype: torch.bfloat16, #tokens: 383065, K size: 17.54 GB, V size: 17.54 GB
[2026-10-17 16:47:45] Decode batch, #running-req: 64, #token: 40751, token usage: 0.11, cuda graph: True, gen throughput (token/s): 263.88, #queue-req: 0We measured a BF16 pool of 383,065 tokens against 234,600, 63 percent more. The FP8 pool grew from 1,084,458 to 1,378,545 tokens. The throughput did not move. At 64 users, BF16 gave 238.72 against 235.38 tok/s, and FP8 gave 442.71 against 440.86. At every concurrency, the two medians were within 2 percent of each other. Raw runs
The log line explains it. Sixty-four requests held 40,751 tokens, 11 percent of the pool. On the kit's server at 0.7, the highest token usage was 18 percent. The pool was never the limit, so a larger pool had nothing to do. Compare the L4 in section 4.3, where the BF16 pool was full at 64 users and FP8 nearly tripled the throughput.
The open-loop sweep of section 5.1 gave the other half of the answer. At 16 requests per second, more than the GB10 serves, requests kept arriving while earlier ones still ran. There the larger pool did matter.
[2026-10-16 19:08:23] Decode batch, #running-req: 374, #token: 227530, token usage: 0.96, cuda graph: False, gen throughput (token/s): 866.37, #queue-req: 101[2026-10-17 18:00:45] Decode batch, #running-req: 480, #token: 289721, token usage: 0.75, cuda graph: False, gen throughput (token/s): 994.20, #queue-req: 0At 0.7 the pool was 96 percent full, and 101 requests waited outside it. At 0.82 all 480 requests of the run fit at once. We measured 5.19 completed requests per second against 3.88, 34 percent more, and 664 against 497 output tok/s, three seeds each. The two runs were a day apart, so part of the gap can be the machine. The log lines show the mechanism, and the size of the gain belongs to this run. FP8 had a pool of over a million tokens at both fractions, and its rate did not change: 8.29 against 8.26.
So the extra 13.6 GB bought nothing at 64 users and a third more throughput in an overload. Size the pool from your token usage at peak load, including the burst that arrives faster than you serve. On a machine that the GB10 shares with other programs, memory you do not need is memory another program cannot use.
On a dedicated GPU, trust the automatic value first. Raise the fraction in steps of 0.02 only when the scheduler log shows a full pool and retractions. Find the upper limit in staging with your longest prompts, then run production one or two steps below it. Lower it when long prompts fail in attention, as in issue #6027.
The fraction also changes comparisons. One independent benchmark ran SGLang with its automatic fraction and vLLM with its default of 0.9 of GPU memory. The two engines had KV pools of very different sizes. Read section 5.3 before you trust a comparison that does not state both values.
What to measure
- The
max_total_num_tokensline at startup. It is the result of the whole calculation. token usagein decode lines. A value near 1.0 means the pool is full.- The free memory of the machine during the heaviest prefill, from the operating system.
One more caution for Apple silicon. The kv_cache_memory_usage_gb metric read 0.0 in our capture, because the MLX backend allocates its own pool outside the accounting that the metric reads. Use the MlxAttentionKVPool log line, which reported about 19,860 MB.
RadixCache
RadixCache indexes every cached token run in a tree, so a new request reuses the longest matching prefix and prefills only the tokens after it.
A chat product sends the same 2,000-token system prompt with every question. A server without prefix reuse computes those 2,000 tokens for every request, and every user waits for the same work again. On our Mac, that repeated work made a shared-prefix benchmark take 129.7 seconds. With the radix cache on, the same benchmark took 48.8 seconds.
When you finish this section, you can explain how the tree finds a prefix and why a running request keeps its prefix. You can also say how eviction removes cached tokens. You can also read the scheduler log lines that prove a hit.
The same workload with and without the tree
The capture kit runs SGLang's own shared-prefix benchmark twice. Four groups of 16 prompts share a 2,048-token system prompt per group, and each prompt adds a 128-token question. The second server starts with --disable-radix-cache.
| Result | Radix cache on | --disable-radix-cache |
|---|---|---|
| Benchmark duration | 48.81 s | 129.68 s |
| Median time to first token | 1,358 ms | 7,222 ms |
| P99 time to first token | 3,277 ms | 13,548 ms |
| Output tokens per second | 83.91 | 31.59 |
We measured a 2.7 times shorter run and a 5.3 times shorter median wait for the first token. The scheduler log shows where the time went.
[2026-10-16 14:01:00] Prefill batch, #new-seq: 7, #new-token: 955, #cached-token: 15102, token usage: 0.05, #running-req: 1, #queue-req: 0, #pending-token: 0, cuda graph: False, input throughput (token/s): 1472.94[2026-10-16 14:02:34] Prefill batch, #new-seq: 3, #new-token: 4096, #cached-token: 0, token usage: 0.06, #running-req: 2, #queue-req: 3, #pending-token: 7883, cuda graph: False, input throughput (token/s): 2261.21
[2026-10-16 14:02:36] Prefill batch, #new-seq: 3, #new-token: 4096, #cached-token: 0, token usage: 0.08, #running-req: 4, #queue-req: 1, #pending-token: 3787, cuda graph: False, input throughput (token/s): 2245.89
[2026-10-16 14:02:38] Prefill batch, #new-seq: 2, #new-token: 3787, #cached-token: 0, token usage: 0.10, #running-req: 6, #queue-req: 0, #pending-token: 0, cuda graph: False, input throughput (token/s): 1626.02With the tree, seven new requests needed 955 new tokens, and 15,102 tokens came from the cache. Without the tree, the scheduler filled three batches of up to 4,096 tokens for eight requests, all computed from zero. The 4,096 is the chunked prefill size from section 2.2.
The same test on a 24 GB L4
A Mac makes every prefill slow, so we repeated the test on an NVIDIA L4 with Qwen/Qwen3-8B. This time we changed the length of the shared system prompt from 0 to 4,096 tokens. Each run had four groups of 16 prompts, a 128-token question, 64 output tokens, and a cap of eight concurrent requests. We ran three seeds per length.
… Prefill batch, #new-seq: 3, #new-token: 405, #cached-token: 12952, token usage: 0.58, #running-req: 1, #queue-req: 0, #pending-token: 0, cuda graph: True, input throughput (token/s): 1452.28
… Prefill batch, #new-seq: 4, #new-token: 546, #cached-token: 17269, token usage: 0.58, #running-req: 4, #queue-req: 0, #pending-token: 0, cuda graph: True, input throughput (token/s): 2532.09… Prefill batch, #new-seq: 2, #new-token: 4096, #cached-token: 0, token usage: 0.68, #running-req: 1, #queue-req: 0, #pending-token: 5527, cuda graph: True, input throughput (token/s): 1632.42
… Prefill batch, #new-seq: 2, #new-token: 4096, #cached-token: 0, token usage: 0.74, #running-req: 2, #queue-req: 0, #pending-token: 1431, cuda graph: True, input throughput (token/s): 1634.70In this run the L4 prefilled about 1,600 tokens per second, on a card that was throttling. Each 4,096-token batch cost about 2.5 seconds, and without the tree every request paid for its full prompt.
| Shared prompt | Median TTFT, cache on | Median TTFT, cache off | Output tok/s, cache on | Output tok/s, cache off |
|---|---|---|---|---|
| 0 | 349 ms | 379 ms | 113.56 | 113.33 |
| 1,024 | 462 ms | 2,202 ms | 105.76 | 70.15 |
| 4,096 | 479 ms | 14,706 ms | 88.87 | 20.80 |
The median SM clock was 1,440 MHz with the cache and 930 MHz without it at 4,096 shared tokens. Every seed of the run without the cache stayed under our floor of 1,000 MHz.
We measured a 30.7 times shorter median wait and 4.3 times the throughput at 4,096 shared tokens. Treat both factors as upper bounds. The run without the cache had a thermal throttle flag in 62 percent of its samples and a 35 percent lower clock. A cool card would shrink the factor, but a 35 percent clock gap cannot explain a factor of 30. With no shared prompt, the median TTFT differed by 8 percent, inside the seed spread, and the throughput was the same. Raw runs
The same sweep on the GB10 with Qwen/Qwen3-30B-A3B-Instruct-2507 gave a smaller factor. At 4,096 shared tokens, the median TTFT was 589 ms with the tree and 5,208 ms without it, 8.8 times. The output rate was 120.66 against 49.73 tok/s. The server without the tree ran a day after the other one. It ran at a median clock of 2,376 MHz, with a throttle flag in 37 percent of its samples. The server with the tree ran at 2,496 MHz.
Our hypothesis for these two cards is that prefill was cheaper on the GB10. That model activates about 3 billion parameters per token, so each repeated prompt cost less to compute again. Two confounds remain: the throttled L4 run without the cache inflates the L4 factor, and the GB10 pair ran on two days at different clocks.
The tree
RadixCache: a radix tree over token sequences, whose nodes hold the KV slot indices of the tokens on their edges. The design comes from the SGLang paper, which calls the mechanism RadixAttention. A radix tree stores runs of tokens on its edges, so one node can hold a whole system prompt.
TreeNode: one node of the tree. It holds its children, keyed by their first token, and the token run on its edge. It also holds the KV slot indices for those tokens, a lock count, a last-access time, and a hit count.
Four operations do all the work.
- match_prefix walks from the root and follows the child whose first token matches. If the match ends inside an edge, it splits that node so the boundary is exact. Every node on the path gets a new access time.
- insert walks the same way and adds a leaf for the tokens that did not match. If another request already inserted the same tokens, SGLang frees the duplicate slots and points the request at the tree's copy.
- inc_lock_ref and dec_lock_ref count the running requests that use a node. A count above zero protects the whole path to the root.
- evict frees leaves that no request locks, oldest first, and moves up the branch as leaves disappear.
One rule surprises people. A match can cover at most the prompt length minus one. The last prompt token always goes through prefill, because the model needs its logits to sample the first output token. Our cache experiment shows that rule: a 2,999-token prompt reported 2,998 cached tokens and 1 new token.
Which tree you get at v0.5.22
The class name in old blog posts and issues is RadixCache. At v0.5.22 the default is UnifiedRadixCache, one tree that also handles sliding-window and Mamba state. The tree walks run in a Rust core by default since v0.5.21. The log on our Mac shows the exception.
[2026-10-16 13:58:06] Using the Python TreeCore: the Rust TreeCore supports Linux only
[2026-10-16 13:58:06] Init Unified Radix Cache. Components: (<ComponentType.FULL: 0>,). Tree Core: UnifiedTreeCore
[2026-10-16 13:58:06] Tree cache initialized: source=default impl=UnifiedRadixCache hybrid_swa=False hybrid_ssm=False hicache_attached=FalseThe no-cache server printed the same three lines. --disable-radix-cache still builds UnifiedRadixCache, in a disabled mode that matches nothing and inserts nothing. The separate ChunkCache class that older posts describe was deleted on 2026-10-08.
How the scheduler uses the tree
The default --schedule-policy is fcfs, first come, first served. The paper's longest-prefix-match order, lpm, is a choice you make. The code sorts by prefix length only while 128 or fewer requests wait, because matching every waiting request costs time. Above that, lpm uses the FCFS order.
The scheduler also avoids a waste inside one round. When several waiting requests share a prefix that is not cached yet, it lets one of them prefill the shared part first. The others reuse it in the next round. Section 2.2 covers the policies in full.
Our position: leave the radix cache on
In our runs without a shared prompt, on the L4 and on the GB10, the cache cost nothing measurable. We did not test its cost under heavy eviction. Cached tokens live in the same pool as running requests, and eviction frees them on demand. We know of one reason to turn it off: to test whether a wrong answer comes from reused KV. Even then, try --kv-canary log first, which checks KV slots for corruption while the cache stays on.
Then measure the hit rate together with every other feature you add. Issue #32459 is the warning. A team that replayed multi-turn agent traffic saw a deep-prompt hit rate of 97 percent without speculative decoding, and 40 to 53 percent with EAGLE. Input throughput fell from 43,981 to 12,881 tokens per second, with no error in the logs. The candidate cause was the extra KV that speculative decoding reserves, which forced the tree to evict cached prompts.
Field reports put the folklore in proportion. vLLM also reuses prefixes, so engine comparisons measure two caches against each other. One independent test of 16 models on an A10G found SGLang ahead on repeated prefixes. The gain was 20 to 40 ms of first-token time at 7B to 9B. A RunPod test of a 70B model with a cached 7,000-token context measured 35.0 against 32.8 tokens per second per stream. The SGLang paper reports up to 6.4 times higher throughput, which is the authors' best case against the systems of 2024.
Prefix-friendly prompts
The prefix cache matches tokens from the first one, so one changing token near the start of a prompt can cost more than server tuning recovers.
A team runs DeepSeek-V4 for long agent sessions on eight GPUs, with hierarchical caching turned on. Their dashboards show #cached-token: 0 on requests that repeat 100,000 tokens of history. They tune the cache tiers and the write policy. The hit rate barely moves. Then they find a random hash that their relay put into the system prompt of every request.
When you finish this section, you can predict which prompts hit the prefix cache before you send them. You can also prove the hit rate with cached_tokens, the scheduler log, and /metrics.
The experiment: one identifier, three places
The capture kit sends one 2,999-token system prompt and one short question, five times in each of three forms. The server runs with --enable-cache-report, so each response reports its cached tokens to the client. The kit sends two warm-up requests first.
- Stable: the same system prompt every time.
- ID at start: the system prompt starts with
Request id <random hex>., a new value on every request. - ID at end: the same random ID goes at the end of the system prompt.
…
{"summary": "stable-system-prompt", "median_ttft_ms": 45.1, "min_ttft_ms": 34.0, "max_ttft_ms": 62.5, "median_cached_tokens": 2998.0, "prompt_tokens": 2999}
{"summary": "id-at-start", "median_ttft_ms": 1255.3, "min_ttft_ms": 1102.6, "max_ttft_ms": 2197.3, "median_cached_tokens": 5, "prompt_tokens": 3034}
{"summary": "id-at-end", "median_ttft_ms": 88.2, "min_ttft_ms": 83.7, "max_ttft_ms": 118.1, "median_cached_tokens": 2985, "prompt_tokens": 3028}We measured a 28 times longer wait for the first token when the ID sits at the start: 1,255 ms against 45 ms. The run used our Mac with Qwen3-0.6B in 4-bit MLX. The factor depends on the prefill speed of the card. The number of missed tokens does not.
The same ID at the end cost 43 ms more than the stable prompt. The tokens are almost the same in all three cases. Only their order differs.
The cached-token counts explain the times. The stable prompt reused 2,998 of 2,999 tokens, the maximum from section 3.3. The ID at the start matched only the first 5 tokens, the ones that come before the random hex digits. Every token after a change is a different branch of the tree, even when the rest of the prompt is identical.
Why the order matters
The radix tree compares tokens from the first one onward, and it stops at the first difference. Nothing after a difference can match, because the attention values of every later token depend on every earlier token. A cache that reused the later tokens would return wrong answers. So prefix caching is exact by design, and it is unforgiving by the same design.
The same rule applies to each part of a chat request. The chat template turns the messages into one token sequence in a fixed order: system prompt, tool list, earlier turns, new message. A change in the system prompt invalidates everything. A change in the newest message invalidates only that message.
The incident
Issue #35129 is the story at the top of this section. The reporter found three causes stacked on top of each other.
- The relay put a per-session random
cch=hash and a rotating system message into each request. Removing them moved the engine hit rate from 66.8 percent to 94.4 percent. - The client wrote its task-list snapshot at the end of the system prompt. Every task update changed the system prompt, so it invalidated more than 100,000 tokens of history after it.
- Hierarchical cache load-back, when it could not find room, evicted the prefixes of other sessions. The reporter counted 250,000 evict calls against 376 completed load-backs.
The first fix was a prompt edit. No server flag in section 3.5 could have recovered the 27.6 points that the hash cost.
Our position: fix prompts before you tune the server
Treat the prompt layout as part of the serving system. Before you change any cache flag, check these rules against your real requests.
- Put content that never changes first: the system prompt, then the tool list in a fixed order.
- Put content that changes per session after that, and content that changes per request last.
- Never put timestamps, request IDs, session hashes, or random sampling seeds in the system prompt. Send them as request metadata, or at the end.
- Keep tool and function definitions in a stable order. A JSON object whose keys change order is a different token sequence.
- Append to the conversation. Do not rewrite earlier turns, for example to summarize them, unless you accept a full prefill.
Two server-side settings break reuse in ways that look like prompt problems. A request for prompt log probabilities from position k can reuse only the first k tokens. Different LoRA adapters never share tree nodes, even for identical tokens, because the adapter is part of the tree key.
Routing can break reuse too. With several servers, a request that goes to a server without its prefix misses the cache, whatever the prompt looks like. Jarvislabs reported that routing each conversation to the same server moved their hit rate from 64.7 percent to 92.1 percent. Section 6.4 shows how the gateway routes by prefix.
How to prove a hit
Use three measurements, from the closest to the request to the most general.
- In the response. Start the server with
--enable-cache-report, which defaults to off. The usage block then reportscached_tokens. The native/generateAPI returnscached_tokensinmeta_infowithout the flag. - In the scheduler log. Every
Prefill batchline reports#new-tokenand#cached-token. - In the metrics.
/metricsexportssglang:cache_hit_rate, a gauge of recent prefill batches. After the shared-prefix benchmark in section 3.3, our server reported 0.94. The server with--disable-radix-cachereported 0.0.
[2026-10-16 13:58:12] Prefill batch, #new-seq: 1, #new-token: 1, #cached-token: 2998, token usage: 0.02, #running-req: 0, #queue-req: 0, #pending-token: 0, cuda graph: False, input throughput (token/s): 7.09
…
[2026-10-16 13:58:14] Prefill batch, #new-seq: 1, #new-token: 3031, #cached-token: 3, token usage: 0.02, #running-req: 0, #queue-req: 0, #pending-token: 0, cuda graph: False, input throughput (token/s): 1937.91
…
[2026-10-16 13:58:20] Prefill batch, #new-seq: 1, #new-token: 45, #cached-token: 2983, token usage: 0.02, #running-req: 0, #queue-req: 0, #pending-token: 0, cuda graph: False, input throughput (token/s): 225.19The lessons on prompt caching and on caching and cost show the same rule for hosted model APIs. Those APIs bill cached input tokens at a lower price.
Eviction policies and HiCache
When the GPU pool is full, SGLang evicts the least recently used prefix by default, and HiCache keeps evicted prefixes in host memory and in optional storage.
A coding agent holds a session of eight turns, and its history grows past 25,000 tokens. The GPU pool holds ninety such sessions. The ninety-first user arrives, and SGLang must evict a cached prefix to make room. When the first user returns, their history is gone, and the server computes all 25,000 tokens again.
When you finish this section, you can choose an eviction policy from a measured hit rate. You can also decide when hierarchical caching pays for its cost and which of its settings to change first.
What eviction removes
Eviction removes only cached tokens that no running request locks, the leaves of the radix tree. It never removes the KV of a running request. That case is retraction, and section 2.3 covers it. Eviction starts from the leaves with the lowest score and moves toward the root.
--radix-eviction-policy decides the score. The default is lru.
| Policy | Evicts first | When it helps |
|---|---|---|
lru | the prefix with the oldest last access | most workloads, the default |
lfu | the prefix with the fewest hits, then the oldest | a hot set of prompts that stays stable for hours |
slru | prefixes with fewer than 2 hits, then the oldest | a stable hot set with a stream of one-time prompts |
priority | prefixes of lower-priority requests | mixed traffic with request priorities |
tlru | history that cannot change the next turn's prefill time | multi-turn agents with a tail-latency target |
Tail-Optimized LRU (tlru): a policy that keeps only the part of a conversation that the next turn's latency target needs, and evicts the rest first. It comes from a paper that the code names, arXiv 2510.15152. The SGLang team reports 43.9 percent lower p99 inter-token latency on DeepSeek-V4-Pro at concurrency 32. That number comes from the release notes of v0.5.21, and we found no independent test of it.
tlru does not start without --radix-eviction-policy-config. That config needs a threshold larger than its next_prompt_estimate. We started it with {"threshold": 512, "next_prompt_estimate": 256}.
Our position: keep lru until you have measured a reason
The SGLang docs give the same advice: start with lru and change it only against a measured hit rate. Frequency-based policies hurt when popularity shifts, because yesterday's popular prompt stays in memory and today's prompt pays for it. Change the policy only when you can name the workload that the new policy serves, and measure the hit rate before and after.
A 2026 study of production traces from two companies supports that default. It tested 14 eviction policies, and the policies built for other caches gave little gain over LRU. In those traces, active sessions sent their next turns at a regular pace, so recency predicted reuse well.
The study found gains in two narrow cases. One is quick eviction of prefixes that are used only once, when such prompts fill the cache. The other is eviction that weighs how much a miss costs to compute again. We did not measure these results ourselves. Of the SGLang policies, slru is the closest to the first case.
What we measured with a multi-turn trace
We ran a trace of 24 chat sessions with Qwen/Qwen3-0.6B on 2026-10-23. Each session had its own system prompt and 6 turns of ShareGPT questions, with 64-token answers. The sessions took turns at a concurrency of 8, and each turn sent the whole history again. The hit rate is the cached prompt tokens divided by the prompt tokens. This was on the second GPU of our L4 node, which its owner shares and which had no clock lock. The clock does not change a hit rate, so read the hit rates and not the times.
pool, policy whole trace hit rate per turn 1 to 6 median SM clock
8,192 tokens, lru 0.19, 0.19 0.11, 0.31, 0.58, 0.39, 0.016, 0.013 615 MHz
…
8,192 tokens, lfu 0.375 0.11, 0.31, 0.58, 0.53, 0.34, 0.25 1,140 MHz
8,192 tokens, slru 0.367 0.11, 0.31, 0.58, 0.53, 0.31, 0.26 960 MHz
16,384 tokens, lru 0.685 rises to 0.83 at turn 6 810 MHz- A small pool made LRU thrash. At 8,192 tokens, the cycle of 24 sessions was larger than the pool. LRU evicted each session's prefix just before its next turn, and the hit rate fell to about 1.5 percent at turns 5 and 6.
- LFU and SLRU helped only there. At the same pool they kept 25 to 34 percent at turns 5 and 6. Over the whole trace, that was about twice the hit rate of LRU.
- A bigger pool fixed it. At 16,384 tokens and at the default pool, every policy we ran reached about 0.69 over the whole trace.
So a different policy helps only when the pool is too small for the sessions that return. Grow the pool first, with --mem-fraction-static or an FP8 KV cache, and then measure the policy again. At this pool size the server also crashed in some runs. Section 7.1 describes the symptom.
HiCache: three tiers for one tree
HiCache: SGLang's hierarchical cache, which extends the radix tree from GPU memory to host memory and to a storage backend. --enable-hierarchical-cache turns it on, and it defaults to off. The tiers have names in the code and the docs.
- L1: the GPU pool from section 3.1.
- L2: a pool in pinned host memory, private to one server instance.
- L3: an optional storage backend shared across instances, set with
--hicache-storage-backend. The choices includefile,mooncake,hf3fs, andnixl.
The tree records where the KV of each node lives. A match returns a GPU hit and a host hit length. SGLang then loads the host part back into fresh GPU slots, one layer ahead of the computation that needs it.
--hicache-write-policy decides when a node gets a copy in host memory. The default is write_through. The code sets a hit threshold of 1 for write_through and 2 for write_through_selective. So write_through copies a prefix on its first hit, and write_through_selective waits for a second hit. write_back copies a node only when the GPU evicts it.
The settings that decide whether it helps
L3 prefetch has its own rules. SGLang skips a storage prefetch when the storage hit is shorter than 256 tokens. The default prefetch policy is timeout, which stops waiting for storage after a time that grows with the prompt.
The docs and the code disagree on that time. The docs give a base of 2 seconds, 0.1 seconds per 1,024 tokens, and a maximum of 30 seconds. The code at v0.5.22 uses a base of 1.0 second and 0.25 seconds per 1,024 tokens. We found no maximum in the cache code. The code wins. A 100,000-token prompt can wait about 25 seconds for storage before SGLang computes it again.
The host pool size comes from --hicache-ratio or --hicache-size. Without either, SGLang takes up to --hicache-host-memory-fraction, which defaults to 0.8 of available host memory.
What other teams measured
We could not run HiCache on the capture Mac, and the field evidence is thin. The next section has our own test on an L4. The numbers we found come from the SGLang team and its partners.
- The SGLang RBG team and the Mooncake team ran a multi-turn benchmark on Kubernetes. The average time to first token was 5.91 seconds with GPU memory only. The L2 tier lowered it to 3.77 seconds, and a Mooncake L3 lowered it to 2.58 seconds.
- The SGLang HiCache post quotes Novita. Novita reported a 56 percent lower average time to first token, and a hit rate that rose from 40 to 80 percent.
The failure reports are better documented than the successes. In issue #35129, load-back that found no room evicted other sessions' GPU prefixes, with 250,000 evict calls against 376 completed load-backs. Issue #30760 shows one tensor-parallel rank waiting forever in a prefetch check while the other ranks moved on. Issue #42465 shows bursts of 540,000-token prompts that hang every rank with HiCache on and run without it.
What we measured on an L4
We tested L2 on one 24 GB L4 with Qwen/Qwen3-8B. Each group of 8 requests shared one 2,048-token system prompt and added a 64-token question. We changed the number of groups from 4 to 64, kept a cap of 8 concurrent requests, and ran three seeds per point. The second server added --enable-hierarchical-cache --hicache-ratio 4.
The GPU pool held 24,094 tokens, about 11 system prompts. So at 16 groups or more, the default server had to evict prompts that it would need again.
[2026-10-17 17:35:15] Allocating kv hierarchical KV host pool: 96377 tokens, 14.21 GB host memory.
[2026-10-17 18:19:03] Prefill batch, #new-seq: 4, #new-token: 4096, #cached-token: 2196, token usage: 0.65, #running-req: 2, #queue-req: 0, #pending-token: 5234, cuda graph: True, input throughput (token/s): 1431.87
[2026-10-17 18:19:03] Prefill batch, #new-seq: 3, #new-token: 953, #cached-token: 4281, token usage: 0.65, #running-req: 5, #queue-req: 0, #pending-token: 0, cuda graph: True, input throughput (token/s): 1251.76[2026-10-17 17:34:02] Prefill batch, #new-seq: 3, #new-token: 4096, #cached-token: 0, token usage: 0.65, #running-req: 5, #queue-req: 0, #pending-token: 1138, cuda graph: True, input throughput (token/s): 1573.58
[2026-10-17 17:34:03] Prefill batch, #new-seq: 1, #new-token: 1138, #cached-token: 0, token usage: 0.65, #running-req: 7, #queue-req: 0, #pending-token: 0, cuda graph: True, input throughput (token/s): 1347.58| Groups | Prompt tokens to keep | Median TTFT, GPU only / HiCache | Output tok/s, GPU only / HiCache | Median SM clock, GPU only / HiCache |
|---|---|---|---|---|
| 4 | 8,192 | 360 / 361 ms | 82.39 / 81.64 | 1,455 / 1,440 MHz |
| 16 | 32,768 | 3,259 / 553 ms | 37.95 / 74.75 | 788 / 1,223 MHz |
| 32 | 65,536 | 5,449 / 817 ms | 25.72 / 69.29 | 465 / 765 MHz |
| 64 | 131,072 | 6,821 / 3,610 ms | 21.37 / 35.93 | 450 / 450 MHz |
We measured no cost at 4 groups, when every prompt fit on the GPU. At 32 groups the host tier cut the median wait 6.7 times and served 2.7 times the throughput. Both servers ran far below our clock floor of 1,000 MHz there. The HiCache server ran at 1.65 times the clock of the default server. So the 6.7 times mixes the cache effect with a clock gap. Raw runs
At 64 groups, the prompts needed more than the GPU and host pools held together, about 120,000 tokens. HiCache still cut the wait 1.9 times, but it was no longer near the 4-group result.
The card was hot in these runs. From 16 groups up, 52 to 95 percent of the samples had the thermal flag set, on both servers. The default server recomputed more and ran hotter, so part of its loss is the clock. The cache hit lines above do not depend on the clock, and they are the stronger evidence.
The GB10 ran the same workload as a control, on a different model, Qwen/Qwen3-30B-A3B-Instruct-2507, and without HiCache. We left the host tier off there. The GB10 has one memory for the CPU and the GPU, so a host copy would take memory from the same place as the pool.
[2026-10-17 19:33:31] KV Cache is allocated. dtype: torch.bfloat16, #tokens: 260013, K size: 11.90 GB, V size: 11.90 GB
[2026-10-17 19:52:36] Prefill batch, #new-seq: 1, #new-token: 67, #cached-token: 2196, token usage: 0.01, #running-req: 0, #queue-req: 0, #pending-token: 0, cuda graph: True, input throughput (token/s): 29.36
[2026-10-17 19:52:36] Prefill batch, #new-seq: 7, #new-token: 476, #cached-token: 15146, token usage: 0.06, #running-req: 1, #queue-req: 0, #pending-token: 0, cuda graph: True, input throughput (token/s): 1605.53Its pool held 260,013 tokens, room for all 64 system prompts at once. The second prefill line found 15,146 tokens in the cache for 7 new requests. The median TTFT stayed between 448 and 460 ms from 4 groups to 64. Nothing was evicted, so there was nothing for a host tier to bring back.
Our test points to one rule: the size of your working set. Add up the distinct prefixes that your users come back to within a few minutes. In our test, the host tier paid when that sum was larger than the GPU pool and smaller than the GPU and host pools together. When it was smaller than the GPU pool, the host tier added nothing.
Our position: add HiCache for long sessions, and add it in steps
HiCache pays for itself when sessions outlive the GPU pool: multi-turn chat, coding agents, and long documents asked several times. For short one-time prompts it adds copies and load-backs with nothing to reuse. Add it in this order, and measure the hit rate and the p99 time to first token at each step.
- Make prompts prefix-stable first, as in section 3.4.
- Turn on L2 only, with the default
write_through. - Switch to
write_through_selectiveif host copies use too much PCIe bandwidth. - Add an L3 backend when several instances should share prefixes.
- Change the eviction policy last.
Hybrid models and the cache
Sliding-window and Mamba layers keep state that a token-level tree cannot split at any position, so hybrid models are where many reported cache failures sit at v0.5.22.
A team serves a hybrid model that mixes linear-attention layers with full-attention layers. They turn on HiCache and run twenty requests that hit the host tier. All twenty answers are fluent and on topic for a different prompt. The usage block reports full cached tokens, and nothing in the logs warns them.
When you finish this section, you can say why hybrid models break the simple picture of the radix tree. You can also test the cache on your model before your users test it for you.
Three kinds of layer state
The radix tree in section 3.3 works because full attention stores one key and one value per token. A cached prefix of any length is valid, so the tree can split a node at any token. Two other kinds of layer break that rule.
Sliding-window attention (SWA): attention that reads only the last few thousand tokens. A SWA layer needs only the window, so SGLang keeps a smaller pool for SWA layers and drops KV that leaves the window. A cached prefix is useful only where the window's KV still exists.
Mamba layer: a state-space or linear-attention layer that keeps one fixed-size recurrent state per sequence, updated token by token. The state at token 2,000 summarizes all 2,000 tokens. It cannot be cut back to token 1,500. A prefix can resume only where SGLang saved a snapshot of the state.
Our capture model has neither. The startup log says so.
[2026-10-16 13:58:06] Tree cache initialized: source=default impl=UnifiedRadixCache hybrid_swa=False hybrid_ssm=False hicache_attached=False
…
[2026-10-16 13:58:08] Attention KV pool initialized: pool_size=181574 (buffer size 181575 incl. padding slot 0), 28 full-attention layers (0 sliding-window layers stay per-request), 8 kv_heads, 128 head_dimRead these two lines on your own model first. hybrid_swa=True or hybrid_ssm=True means that everything in this section applies to you.
How SGLang handles each kind
UnifiedRadixCache keeps one tree with a component for each kind of state. Each node holds data for the full-attention component and, when needed, for the SWA and Mamba components. A match advances only while every component agrees that the state at that position is valid.
For SWA, the tree keeps a marker where window KV was dropped, and a match stops at the marker. --swa-full-tokens-ratio sets the size of the SWA pool against the full pool. It defaults to None, and model-specific overrides set it. The DeepSeek-V4 override sets it to 0.1.
For Mamba, the tree stores state snapshots on some nodes and copies a snapshot when a request reuses it. --mamba-radix-cache-strategy chooses how SGLang keeps snapshots: auto by default, no_buffer, extra_buffer, or extra_buffer_lazy. --mamba-track-interval sets how often decode saves a snapshot, every 256 tokens by default.
What goes wrong, in the issues
Many reported cache bugs at v0.5.22 involve hybrid models. We did not run a hybrid model ourselves. These four issues show the range.
- A wrong answer from a host-tier hit. Issue #39830 is the opening story of this section. A hybrid linear-attention model with HiCache gave fluent answers to a different prompt on 20 of 20 host-tier hits. Cold requests and GPU hits were correct.
- Zero reuse for an identical prompt. In issue #22935, the match of a repeated prompt ends inside an edge, and the node split creates a node with no Mamba state. The match stops at the last node with state, so the identical prompt reuses nothing.
- A strategy that makes the first token 4.7 times slower. In issue #37834, an option forced the
no_bufferstrategy. The snapshot sat at a depth that later requests could not reach. On a retrieval workload the hit rate fell from 88.2 to 65.9 percent. The mean time to first token rose from 226 ms to 1,063 ms. - A default that slowed decode. Issue #36131 reports a new default that frees SWA slots outside the window. It reduced single-stream decode throughput for hybrid SWA models on DGX Spark and Thor.
Our position: test the cache on a hybrid model before you trust it
On a full-attention model, a wrong cache hit is rare enough that we leave the cache on and move on. On a hybrid model, run three checks before production. Each one takes minutes.
- Correctness. Send the same prompts cold, with a GPU hit, and, if you use HiCache, with a host-tier hit. Compare the outputs at temperature 0. Run
--kv-canary logduring the test, which checks KV slots for corruption and keeps the server running. - Reuse. Repeat a prompt and read
#cached-token. An identical prompt that shows a small count has hit the split problem of issue #22935. - Latency. Measure the time to first token with
--mamba-radix-cache-strategy autoand with the strategy your deployment guide recommends. Keep the faster one only if the hit rate holds.
Then read the open issues for your model family before each upgrade. Between 2026-09-01 and the v0.5.22 tag, about 330 commits touched the cache code in python/sglang/srt/mem_cache. On hybrid models, a new release can fix one of these bugs and add another.
Each Forward Pass
Most decode time is launch overhead and memory traffic, so SGLang picks graphs, kernels, and draft tokens for your GPU before you ask.
ForwardMode and CUDA graphs
A decode step is too small to keep a GPU busy, so SGLang records its kernel launches once as a CUDA graph and replays the record on every step.
You serve a small model to one user on an H100 and watch tokens arrive. The GPU is fast, yet a profiler shows gaps between kernels. A field report from Hazy Research measured that SGLang and vLLM used about half of the H100 memory bandwidth for Llama-1B at batch 1. The GPU waits for the CPU to tell it what to do next.
When you finish this section, you can name the mode of any forward pass and explain what a CUDA graph saves. You can also read the batch sizes SGLang captures and keep busy decode inside a graph.
Every forward pass has a mode
ForwardMode: the label on a batch that tells the model runner what kind of pass to run. The scheduler sets it, and the model runner, the attention backend, and the graph runners all read it.
| Mode | What the pass does |
|---|---|
EXTEND | Prefill. It writes KV entries for many new tokens. Part of the prompt can already be in the cache. |
DECODE | One new token for each running request. |
MIXED | A chunk of prefill and the decode tokens in one batch. Off unless you pass --enable-mixed-chunk. |
IDLE | No tokens. A data-parallel attention rank with no work runs it so that collective calls still match. |
TARGET_VERIFY | Speculative decoding: the target model scores the draft tokens. |
DRAFT_EXTEND_V2 | Speculative decoding: the draft model reads the accepted tokens. |
PREBUILT | A decode worker in prefill-decode disaggregation. The KV cache arrived from another server. |
SPLIT_PREFILL | A prefill that runs a few layers at a time, for prefill-decode multiplexing. |
SGLang calls any pass that writes many KV entries per request "extend". That is why TARGET_VERIFY counts as extend in the code. The target model runs over several draft positions per request, like a small prefill with a tree mask.
The cost: one decode step is a long list of small launches
A transformer layer is a sequence of kernels: a norm, the QKV projection, attention, the output projection, a second norm, and the MLP. A 28-layer model launches hundreds of kernels to produce one token. During prefill each kernel works on thousands of tokens, so launch time is small next to compute time. During decode each kernel works on one token per request.
At batch 1 the GPU often finishes a kernel before the Python process has sent the next one. The obvious fix is a faster launch path, such as fewer Python calls. That helps a little, but each kernel still needs its own CPU launch, and the count does not change.
CUDA graph: a record of kernel launches with fixed tensor shapes and addresses, which the GPU can replay with one CPU call.
The record has a price. Every captured shape uses GPU memory, and a batch must match a captured shape exactly. SGLang pays that price for decode and pads each batch up to the next captured size.
What SGLang captures, and when it gives up
Capture bucket: one batch size that SGLang records a decode graph for at startup. Without speculative decoding, v0.5.22 captures sizes 1, 2, 4, 8, and 12, then every eighth size from 16 to 256. Above 256 it captures every sixteenth size to 511, then every thirty-second size up to the largest. A batch of 13 requests replays the graph for 16 and wastes three slots.
The largest bucket, max_bs, depends on GPU memory and tensor parallel size. The startup code picks it when you do not set --cuda-graph-max-bs-decode.
| GPU memory | Example GPUs | Decode max_bs at TP below 4 | At TP 4 or more | chunked_prefill_size |
|---|---|---|---|---|
| under 20 GB | T4, RTX 4080 | 8 | 8 | 2048 |
| 20 to 35 GB | A10, RTX 4090, RTX 5090 | 48 | 160 | 4096 |
| 35 to 60 GB | A100 40 GB, L40 | 32 | 160 | 4096 |
| 60 to 90 GB | H100, A100 80 GB | 256 | 512 | 8192 |
| 90 to 160 GB | H200 | 256 | 512 | 8192 |
| 160 GB and more | B200, MI300X | 512 | 512 | 16384 |
When a decode batch is larger than max_bs, the graph runner cannot replay. The step runs eager, with one launch per kernel. Nothing fails and no warning appears. The scheduler log line for that batch says cuda graph: False, and latency per token rises.
The code does not change your shapes for prefill the same way. Since PR #29458 (2026-07-01), CUDA builds use a breakable graph for prefill. Breakable graph: a capture that ends a segment at each op marked to run eager, runs that op eagerly, and starts the next segment. A model with one op that a graph cannot hold still gets graphs for every other op. On other platforms prefill graphs are off, and our Mac capture logs both facts.
… Disable prefill CUDA graph because cuda_graph_config resolved prefill.backend='disabled' (e.g. via --cuda-graph-backend-prefill=disabled or auto-disable rules).
… Prefill batch, #new-seq: 1, #new-token: 6, #cached-token: 0, token usage: 0.00, #running-req: 0, #queue-req: 0, #pending-token: 0, cuda graph: False, …Every scheduler batch line ends with cuda graph:. On a CUDA server, watch that field on your decode batches.
The older torch.compile path for prefill graphs is being removed in PRs #42285 to #42287. A blog post that says "piecewise CUDA graphs use torch.compile" describes that older path.
The cliff in field reports
A field report from Jarvislabs ran Qwen2.5-7B on one H100 with default SGLang flags. At concurrency 300, mean inter-token latency was 17.72 ms against 12.28 ms for vLLM. With no concurrency cap it was 100.92 ms against 28.84 ms. The post does not record the SGLang version or the server logs.
Our reading is a hypothesis, labeled as one. The default decode max_bs on that GPU is 256, and the latency break sits just above it. The maintainers saw the same shape on smaller cards. The code comment on the 20 to 35 GB tier explains why. The old cap made every decode batch of 32 or more run eager, and throughput at high concurrency fell far behind vLLM. PR #37898 raised that cap from 24 to 48 on 2026-09-04.
What we measured on a GB10
The cost above assumes a fast GPU and a small model. We tested a different case: Qwen/Qwen3-30B-A3B-Instruct-2507, a mixture-of-experts model, on one NVIDIA GB10. The GB10 has one memory for the CPU and the GPU, with less bandwidth than the HBM of a data-center GPU.
We measured two servers with three seeds at each concurrency from 1 to 64. The default server replayed a decode graph on every decode batch, and its log says cuda graph: True. The server with both graph backends set to disabled logged cuda graph: False. The results were almost the same: Raw runs
| Concurrency | Median TPOT with graphs | Median TPOT without | Output tok/s with graphs | Output tok/s without |
|---|---|---|---|---|
| 1 | 32.52 ms | 33.09 ms | 29.14 | 28.72 |
| 8 | 102.21 ms | 104.77 ms | 74.11 | 73.46 |
| 64 | 254.06 ms | 253.77 ms | 235.38 | 235.79 |
The two lines lie on top of each other in figure 5.1c. The graphs still cost startup time and memory. The decode capture took 4.61 s and 1.73 GB, and the prefill capture took 35.06 s and 2.14 GB.
Our reading of this result: one decode step of this model takes about 32 ms at batch 1. The launch time that a graph removes is small next to that step. Each step reads the weights of the experts that its tokens chose, and memory bandwidth sets the time.
What we measured on an L4
Our first sweep on an L4, with the dense Qwen/Qwen3-8B, was wrong. The card ran at 87 C with a thermal slowdown, at an SM clock of 360 MHz out of 2,040. A throttled GPU is slow on every step, so the launch saving disappears in the noise. We removed those numbers. Record GPU clocks and temperature with every benchmark, as section 5.1 shows.
We then ran the same pair on a cooled L4. Every run of the same-day pair started at 72 C or below. A run with a median SM clock under 1,000 MHz was repeated, up to three times. The first pair ran on two days, 2026-10-16 and 2026-10-18. We ran both servers again on 2026-10-21, one after the other, with the same pool of 24,094 tokens. The table shows the same-day pair.
[2026-10-16 20:32:22] Decode batch, #running-req: 33, #token: 19597, token usage: 0.81, cuda graph: True, gen throughput (token/s): 319.70, #queue-req: 0
[2026-10-18 18:01:00] Decode batch, #running-req: 33, #token: 20422, token usage: 0.85, cuda graph: False, gen throughput (token/s): 350.78, #queue-req: 0| Concurrency | Median TPOT with graphs / without | Output tok/s with / without | P99 ITL with / without |
|---|---|---|---|
| 1 | 60.15 / 60.64 ms | 13.93 / 14.67 | 104 / 104 ms |
| 8 | 66.01 / 66.60 ms | 112.60 / 111.67 | 70 / 68 ms |
| 16 | 70.08 / 70.59 ms | 201.21 / 200.16 | 80 / 73 ms |
| 32 | 95.65 / 94.12 ms | 270.61 / 270.81 | 103 / 87 ms |
| 64, see the note below | 103.39 / 103.12 ms | 264.10 / 265.30 | 109 / 90 ms |
The L4 servers captured decode graphs only up to 48 running requests. At 64 users, batches above 48 ran eager on both servers, so the last row does not measure graphs.
We measured a small difference on the L4 as well. Up to 16 users, the graphs saved 0.5 to 0.7 ms of a 60 to 70 ms step, about 1 percent. Throughput was within 1.2 percent from 2 users up, and 5 percent apart at 1 user. Raw runs
At 16 and 32 users, the server without graphs had the lower P99 ITL, with no seed overlap. It was 73 against 80 ms, and 87 against 103 ms. Both servers replayed graphs at those batch sizes. We do not have a mechanism for the gap yet, so we report it and do not explain it.
The GB10 gave no such gap on the same day. Its P99 ITL with and without graphs stayed within 7 percent at every concurrency, and the median TPOT within 2 percent.
Our reading: a step of an 8B model at batch 1 reads about 16 GB of weights from memory. The launch time that a graph removes is small next to that read.
The Inside an LLM Serving GPU machine shows one decode step on the L4 as a weight read and the work after it. This link opens the run without graphs at one user. Launch commands cross PCIe for every kernel, and in our first pair the step grew by 0.47 ms to 60.63 ms.
Our position
Keep CUDA graphs on, and size them to your traffic. The default max_bs suits moderate concurrency. If your benchmark or your production peak runs more requests than that, set --cuda-graph-max-bs-decode and --max-running-requests to your target before you measure. SemiAnalysis InferenceX recipes derive both values from the concurrency they test.
Do not expect graphs to make a slow decode fast on every machine. On the GB10, one decode step of a mixture-of-experts model takes tens of milliseconds, and graphs changed it by 3 percent or less. On the L4, with a dense 8B model, they saved about 1 percent. The worst token gap was shorter without them at 16 and 32 users. Measure the median and the tail, with and without graphs, before you blame the launch path.
Do not turn graphs off to fix memory. If capture runs out of memory, lower --cuda-graph-max-bs-decode or --mem-fraction-static. A server without decode graphs pays launch time on every token for every user.
Two flag names changed in v0.5.22, and old recipes break on them. --disable-cuda-graph still works, and the help text marks it as deprecated.
--disable-cuda-graph Deprecated. Use --cuda-graph-
backend-{decode,prefill}=disabled instead.The flag --cuda-graph-max-bs no longer exists. We passed it to the v0.5.22 argument parser and it exited with ambiguous option: --cuda-graph-max-bs could match --cuda-graph-max-bs-decode, --cuda-graph-max-bs-prefill.
Incidents
Capture runs out of memory with data-parallel attention. Issue #23769 (2026-04-26): DeepSeek-V4-Pro-FP8 on two nodes of eight H200 exited during graph capture. With data-parallel attention, the graph batch size counts per rank, so the captured graphs were larger than the traffic needed. The fix was a smaller graph batch size or a lower --mem-fraction-static.
A renamed field broke the Python API. Issue #36478 (2026-08-26): sgl.Engine(..., disable_piecewise_cuda_graph=True) raised TypeError, while the command-line flag still worked. PR #23906 folded the field into the per-phase graph config and kept only the command-line alias. The fix is cuda_graph_backend_prefill="disabled".
A new GPU needed eager mode. A field report from joshua8.ai ran SGLang on an RTX PRO 6000 Blackwell (SM120). It needed --disable-cuda-graph to run at all. On new architectures, check that capture works before you compare engines.
--attention-backend
SGLang has many attention kernels because none wins on every GPU and model, and its default choice records regressions that someone already paid for.
In January 2026 a user upgraded FlashInfer and served Qwen3-235B on H20 GPUs. Median inter-token latency went from 39.44 ms to 283.52 ms, seven times slower, and nothing else in the setup had changed. The FA3 kernel gave 56.73 ms on the same run. That report is issue #17411, and the code that picks your attention backend at v0.5.22 still cites it.
When you finish this section, you can name the backend SGLang picks for your GPU and model, and explain why. You can also split prefill and decode across two backends and decide when to override the default.
What an attention backend is
Attention backend: the class that computes attention over the paged KV cache for one batch. Every backend implements the same interface. It builds per-batch metadata such as page tables and index buffers. It prepares state for CUDA graph capture and replay. It runs forward_extend for prefill and forward_decode for decode.
The model code never calls a kernel by name. Each attention layer calls whatever backend the model runner installed at startup. So one flag swaps the kernel for every layer of every model.
At v0.5.22 the flag accepts 25 names. Two are aliases (nsa for dsa, and compressed for dsv4), so there are 23 backends.
| Backend | What it is for |
|---|---|
flashinfer | Paged MHA and MLA. Supports speculative topk above 1 and page sizes above 1. The general default. |
fa3 | FlashAttention 3 for Hopper. The Hopper default. |
fa4 | FlashAttention 4, for Blackwell. Picked when a model has different K and V head widths. |
trtllm_mha, trtllm_mla | TensorRT-LLM kernels through FlashInfer, for Blackwell SM100 and SM103. |
flashmla, cutedsl_mla, tokenspeed_mla | Decode kernels for MLA models such as DeepSeek. |
dsa, dsv4, qsa, minicpm_* | Sparse attention for one model family each. |
triton | Portable Triton kernels. The default when FlashInfer cannot run the model. |
torch_native, flex_attention | PyTorch reference paths. torch_native is the default on Apple MPS and ARM64 CPUs. |
aiter, wave | AMD ROCm kernels. aiter is the default on AMD for MHA. |
intel_amx, intel_xpu, ascend, hpc_ops | x86 CPUs with AMX, Intel GPUs, Huawei NPUs, and Tencent kernels for SM90. |
llada2_cfg_flashinfer | A diffusion language model variant. |
The obvious fix, and why it fails
The obvious fix is to read a benchmark, find the fastest kernel, and pass it on every server. That fails because each backend has limits that a benchmark does not show.
trtllm_mha rejects speculative decoding with topk above 1 and does not run on SM120. FlashInfer cannot run models that use attention sinks. fa4 has a native page size of 128. Some backends accept FP8 KV caches and some do not. A kernel that wins on one model and GPU can refuse to start on the next.
How SGLang picks a default
When you do not pass --attention-backend, startup calls one function that reads your GPU, the attention type of the model, and your speculative decoding settings.
For MHA models, such as Llama and Qwen, the order is this:
- On Hopper with CUDA 12.3 or later, and no speculative topk above 1, the default is
fa3. The code comment cites issue #17411. - On Blackwell SM100 or SM103, the default is
trtllm_mha, orfa4when K and V widths differ. - On AMD the default is
aiter, and on Apple MPS it istorch_native. - In every other case the default is
flashinferwhen it is installed and the model has no attention sinks, elsetriton.
For MLA models, such as DeepSeek V3, Hopper gets fa3 and Blackwell gets flashinfer. AMD gets aiter when each rank has 16 or 128 KV heads. A model override then moves DeepSeek V3 on SM100 to trtllm_mla.
The docstring of the same function says FA3 is avoided when the page size is above 1. The code does not check the page size. When a comment and the code disagree, the code is what runs.
Two backends in one server
Prefill and decode stress different things. Prefill reads long query blocks, and decode reads one query against a long cache. --prefill-attention-backend and --decode-attention-backend set each phase separately. When they differ, SGLang wraps both in a hybrid backend that dispatches by ForwardMode. With speculative decoding, --speculative-attention-mode decides which of the two runs the verify pass. Its default is prefill.
Docs and code disagree
The attention backend page in the docs at v0.5.22 still lists Cutlass MLA and Dual Chunk FlashAttention. PR #32114 deleted both on 2026-09-10, and neither name is a valid choice at the tag. The same page says Blackwell MHA uses trtllm_mha. The code picks fa4 for models with asymmetric K and V widths. In both cases the code wins, and this manual follows the code.
What to measure
Read the resolved backend in the startup log before you benchmark anything. Then change one flag, rerun the same benchmark at your real concurrency, and compare inter-token latency at p50 and p99. Attention is one part of a decode step, so a faster kernel can move end-to-end numbers less than its own benchmark suggests.
On our Mac capture, SGLang ran through the MLX runtime. The server arguments resolve to torch_native, but MLX runs its own attention path, so none of these backends ran there.
What we measured on an L4
We ran the load sweep of section 5.1 on one L4 with Qwen/Qwen3-8B, three seeds per point. The default server resolved its backend to flashinfer and ran on 2026-10-16. The second server set --attention-backend triton and ran on 2026-10-18. Both had the same pool of 24,094 tokens and replayed decode graphs up to 48 running requests. Every run had a median SM clock of 1,000 MHz or more.
[2026-10-18 14:28:40] KV Cache is allocated. dtype: torch.bfloat16, #tokens: 24094, K size: 1.65 GB, V size: 1.65 GB
[2026-10-18 16:11:42] Decode batch, #running-req: 33, #token: 20422, token usage: 0.85, cuda graph: True, gen throughput (token/s): 311.50, #queue-req: 0| Concurrency | Output tok/s, flashinfer / triton | Median TPOT, flashinfer / triton | Median TTFT, flashinfer / triton |
|---|---|---|---|
| 1 | 13.42 / 13.94 | 60.16 / 59.98 ms | 189 / 183 ms |
| 8 | 112.62 / 112.90 | 66.01 / 65.83 ms | 170 / 187 ms |
| 32 | 270.11 / 270.91 | 96.18 / 96.99 ms | 2,970 / 2,833 ms |
| 64 | 250.85 / 257.29 | 107.42 / 107.76 ms | 18,349 / 18,260 ms |
We measured a tie on throughput and time per token. Throughput was within 4 percent and the median time per token within 1 ms at every concurrency. The median TTFT differed by up to 9 percent, in both directions, outside the seed spread at 2, 16, and 32 users. The two servers ran two days apart. Our reading: on a dense 8B model with contexts under 1,000 tokens, the attention kernel is a small part of each step. The weight reads set the pace. Raw runs
Our position
Leave --attention-backend unset unless you have a benchmark on your own traffic. The default encodes regressions that other users found, such as #17411, and model overrides, such as DeepSeek V3 on SM100. The same issue is also the exception: a user who measures can beat a default that a library upgrade broke. Measure, then override, and write the reason next to the flag.
Prefer the backend that supports every feature you need over the one that wins a microbenchmark. Speculative decoding with topk above 1 needs flashinfer, fa3, or triton when the page size is above 1.
Incidents
A library upgrade made Hopper seven times slower. Issue #17411 (2026-01-20): FlashInfer 0.6.1 regressed the Hopper attention kernel. Median inter-token latency on H20 went from 39.44 ms to 283.52 ms. SGLang made fa3 the Hopper MHA default two days later.
The other engine lost its graphs. A field report by Varad More measured Gemma 3 4B on one A10G at 149 tok/s on SGLang and 84 tok/s on vLLM. The cause was outside attention speed. vLLM ran that model with --enforce-eager, without CUDA graphs, because of its interleaved sliding-window attention. A backend comparison is only fair when both servers replay graphs.
--quantization and --kv-cache-dtype
Quantization buys memory first and speed second, and SGLang keeps weights, GEMM kernels, and the KV cache as three separate choices so that you can buy only what you need.
Cloudflare served Kimi K2.6 with a BF16 KV cache and raised concurrency step by step. At 32 concurrent requests the server produced 1,558 tok/s. At 64 it ran out of memory. With an FP8 KV cache the same service reached 2,192 tok/s at 64 requests, about 41% above the best BF16 result. The FP8 cache was slower per token at every concurrency both versions could run. It won because twice as many requests fit.
When you finish this section, you can tell weight quantization from KV cache quantization, and load a quantized checkpoint without breaking detection. You can also size the memory gain before you measure speed, and decide where a lower precision belongs.
Three choices, three flags
Weight quantization: storing the model weights in fewer bits, such as FP8, FP4, or INT4. It shrinks the weights and the memory traffic of each GEMM. --quantization selects the method.
GEMM backend: the kernel library that multiplies quantized weights. --fp8-gemm-backend and --fp4-gemm-backend select it, and both default to auto, which picks by GPU generation.
KV cache dtype: the format of the cached keys and values. --kv-cache-dtype selects it, separately from the weights. Its default auto uses the model dtype.
A model can run FP8 weights with a BF16 KV cache, or BF16 weights with an FP8 KV cache. Each choice moves a different budget, so treat them as three decisions.
Weights: offline first
At v0.5.22, --quantization accepts 31 method names. Most of them describe a checkpoint that someone already quantized: AWQ, GPTQ, ModelOpt FP8 and FP4, compressed-tensors, GGUF, Quark, and others. A few quantize BF16 weights while the model loads: fp8, mxfp8, nvfp4_online, and mlx_q4 or mlx_q8 on Apple silicon.
Offline quantization: the checkpoint already stores low-bit weights and their scales. Online quantization: SGLang converts full-precision weights at load time.
When you load a quantized checkpoint, do not pass --quantization. The model config check reads quantization_config.quant_method from the checkpoint and uses it. If you pass a method that differs, the check accepts only known compatible pairs, such as modelopt_fp4 on a modelopt checkpoint. For a requantization it logs that you should validate accuracy again. Every other mismatch raises at startup.
The flag can also block an upgrade. A GPTQ checkpoint loaded with no flag is detected, converted at runtime, and served by the Marlin kernel. The upgrade code accepts that conversion only when you passed no method or gptq_marlin.
PR #32114 deleted the plain GPTQ CUDA kernel on 2026-09-10, and on a CUDA build the method registry has no gptq entry. The flag parser still accepts --quantization gptq. The model config check then skips the Marlin upgrade and raises Unknown quantization method: gptq. We read this path in the code and did not run it on a GPU.
The KV cache: capacity, with a scale
--kv-cache-dtype accepts auto, bf16, fp8_e4m3, fp8_e5m2, mxfp8 (FA4 only), nvfp4, and fp4_mx_block16. FP8 halves the bytes per token and FP4 quarters them, so the same pool holds two or four times as many tokens. Section 3.1 shows how to compute bytes per token for your model.
FP8 needs a scale for each tensor. The help text of --quantization-param-path says to supply the scales file when the KV cache dtype is FP8. Without it, every scale is 1.0, and accuracy can drop. Run an accuracy check whenever you change the KV cache dtype.
The vLLM team treats a scale of 1.0 as the worst case for accuracy. They tested uncalibrated FP8 KV caches in 2026, and most models stayed close to BF16 in their tests. They named Kimi-K2.5 on the FlashMLA backend as a model that needs calibrated scales. We did not measure these results ourselves.
Cloudflare published its check. On Kimi K2.6, BF16 against FP8 KV scored 94.24 and 94.09 on GSM8K, 89.11 and 89.04 on MMLU, and 80.29 and 79.29 on MMLU-Pro. Those are their numbers on their model, and your model can differ.
We ran our own check on 2026-10-23, on our L4: the first 500 GSM8K questions, 8-shot and greedy, with Qwen/Qwen3-8B and Qwen/Qwen3-8B-FP8. Neither checkpoint has KV scales, so the FP8 KV runs used a scale of 1.0.
engine config correct accuracy Wilson 95% interval
SGLang BF16 458/500 91.6% 88.8 to 93.7
SGLang FP8 weights 456/500 91.2% 88.4 to 93.4
SGLang FP8 KV cache 458/500 91.6% 88.8 to 93.7
SGLang FP8 weights + FP8 KV 460/500 92.0% 89.3 to 94.1
…All four intervals overlap, so this run did not show a difference. With 500 questions, it cannot rule out a loss of a few points. That is one model and one benchmark, so it does not remove the check on your model.
Check that your scales load
The warning Using FP8 KV cache but no scaling factors provided prints whenever you pass no --quantization-param-path. A checkpoint can also carry its scales in its weight files. So the warning alone does not tell you which scales the server uses.
First, look for scales in the checkpoint. Search the weight index for tensor names that end in k_scale or v_scale:
grep -oE '"[^"]*(k|v)_scale"' model.safetensors.index.json | sort -uWe ran this search on the index of Qwen/Qwen3-30B-A3B-Instruct-2507-FP8 on 2026-10-22. It lists weight scales and no KV scales, so our FP8 server below used a KV scale of 1.0.
Then read the load log. Before PR #35455, SGLang dropped the KV scales of compressed-tensors checkpoints, and the log reported each k_scale parameter as not found. The fix is in the v0.5.22 source. A warning about a missing k_scale or v_scale still means that the loader skipped those scales. On a checkpoint with scales close to 1.0, the PR measured GSM8K at 0.960 with dropped scales and 0.965 with loaded scales.
Last, run your own prompts with and without FP8, and compare the answers before you go to production.
Quantization is a capacity decision
Cloudflare also tested INT4 weights on GLM 5.2. Decode got faster, 60 to 92 tok/s at concurrency 1 and 1,672 to 1,933 tok/s at 64. Prefill got slower, from about 10,160 tok/s with FP8 to about 8,660 with INT4.
Decode is limited by memory traffic, so smaller weights help. Prefill is limited by compute, and dequantizing INT4 costs compute. Cloudflare split the two phases across servers and runs INT4 for decode and FP8 for prefill. Section 6.3 explains the split.
What we measured on a GB10
We served Qwen/Qwen3-30B-A3B-Instruct-2507 twice on one NVIDIA GB10. The first server loaded the BF16 checkpoint. The second loaded the FP8 checkpoint Qwen/Qwen3-30B-A3B-Instruct-2507-FP8 with --kv-cache-dtype fp8_e4m3. Both used --mem-fraction-static 0.7, and we passed no --quantization flag.
… Detected fp8 checkpoint.
… Using FP8 KV cache but no scaling factors provided. Defaulting to scaling factors of 1.0.
… Load weight end. elapsed=152.29 s, type=Qwen3MoeForCausalLM, quant=fp8, fmt=e4m3, avail mem=83.63 GB, mem usage=29.75 GB.
… KV Cache is allocated. dtype: torch.float8_e4m3fn, #tokens: 1083008, K size: 24.79 GB, V size: 24.79 GBWe measured what the two choices bought. The weights went from 57.75 GB to 29.75 GB, and the load time went from 323.61 s to 152.29 s. The pool went from 227,243 tokens to 1,083,008 tokens, 4.77 times as many. Raw runs
Two effects multiply in that number. The smaller weights freed 28.00 GB, and the pool grew by 28.78 GB, from 20.80 GB to 49.58 GB in the units of the log. Each token then took half the bytes, 49,152 against 98,304 for 48 layers with 4 KV heads of size 128.
The second line of the listing is the warning from the previous subsection. We gave no scale file, so every scale is 1.0. Both servers wrote the same 12 tokens for our first request at temperature 0. That is one prompt, and it is not an accuracy check.
Speed changed at every load. The table comes from the sweep servers, which had pools of 234,600 and 1,084,458 tokens. The sweep ran three seeds at each concurrency:
| Concurrency | BF16 output tok/s | FP8 output tok/s | BF16 median TPOT | FP8 median TPOT |
|---|---|---|---|---|
| 1 | 29.14 | 51.50 | 32.52 ms | 18.41 ms |
| 8 | 74.11 | 137.00 | 102.21 ms | 54.96 ms |
| 32 | 150.66 | 283.19 | 201.91 ms | 104.12 ms |
| 64 | 235.38 | 440.86 | 254.06 ms | 131.78 ms |
This result differs from the Cloudflare result above. There, the FP8 cache was a little slower per token and won on capacity. Here, the weights were FP8 too. Decode on this machine reads weights from a memory with modest bandwidth, so half the bytes gave almost twice the speed.
The same test on a 24 GB L4
The GB10 has 121.7 GiB of memory, so its BF16 pool never ran short. We wanted to see the other case, so we ran the same pair on one NVIDIA L4 with Qwen/Qwen3-8B and Qwen/Qwen3-8B-FP8. Both servers used --mem-fraction-static 0.85. The sweep waited for the card to cool to 72°C before each run.
… Load weight end. elapsed=3.92 s, type=Qwen3ForCausalLM, avail mem=6.59 GB, mem usage=15.28 GB.
… KV Cache is allocated. dtype: torch.bfloat16, #tokens: 24094, K size: 1.65 GB, V size: 1.65 GB… Load weight end. elapsed=2.54 s, type=Qwen3ForCausalLM, quant=fp8, fmt=e4m3, avail mem=13.06 GB, mem usage=8.81 GB.
… KV Cache is allocated. dtype: torch.float8_e4m3fn, #tokens: 142369, K size: 4.89 GB, V size: 4.89 GBWe measured a pool of 24,094 tokens for BF16 and 142,369 tokens for FP8, 5.91 times as many. Each request in the sweep had 512 input tokens and 128 output tokens. The BF16 pool held about 37 such requests. Raw runs
| Concurrency | BF16 output tok/s | FP8 output tok/s | BF16 median TTFT | FP8 median TTFT |
|---|---|---|---|---|
| 1 | 13.42 | 24.53 | 189.16 ms | 140.72 ms |
| 16 | 201.09 | 313.92 | 211.78 ms | 147.52 ms |
| 32 | 270.11 | 507.20 | 2,969.61 ms | 199.09 ms |
| 64 | 250.85 | 735.91 | 18,348.57 ms | 296.42 ms |
The scheduler log of the sweep shows the cause at concurrency 64. The BF16 server ran at most 38 requests, with token usage at 0.99 and 26 requests in the queue. The FP8 server ran all 64 requests at token usage 0.29 with an empty queue. The BF16 throughput fell from 32 to 64 because more requests waited, and each waiting request added its wait to TTFT.
At concurrency 1 the pool size does not matter, and FP8 was still faster: 39.66 ms per token against 60.16 ms. That is the GB10 effect again. Decode on an L4 reads every weight for every token, and FP8 weights are half the bytes.
On this card the goodput result is clear. Our target was TTFT under 1 s and TPOT under 100 ms. BF16 served 0 requests per second within target at concurrency 32 and 64. FP8 served 2.87 requests per second within target at 64.
When the pool is too small for the prefixes
The L4 test above gave BF16 a full pool. We then gave both builds the same smaller budget, --mem-fraction-static 0.74, and ran the shared-prefix sweep of section 3.3. Each run sent 64 prompts in 4 groups of 16 at 8 users, with a shared system prompt of 0 to 4,096 tokens. Four groups at 4,096 tokens need about 16,000 tokens of prefix in the cache.
[2026-10-18 19:35:26] KV Cache is allocated. dtype: torch.bfloat16, #tokens: 6559, K size: 0.45 GB, V size: 0.45 GB
[2026-10-18 22:02:58] KV Cache is allocated. dtype: torch.float8_e4m3fn, #tokens: 107299, K size: 3.68 GB, V size: 3.68 GB| Shared prompt tokens | Output tok/s, BF16 / FP8 | Median TTFT, BF16 / FP8 |
|---|---|---|
| 0 | 113.5 / 180.1 | 354 / 255 ms |
| 1,024 | 95.0 / 164.1 | 470 / 349 ms |
| 2,048 | 25.9 / 155.1 | 12,576 / 380 ms |
| 4,096 | 10.9 / 134.8 | 40,126 / 372 ms |
We measured a cliff for BF16 and none for FP8. The BF16 pool held 6,559 tokens, so at 2,048 shared tokens the four prefixes no longer fitted. Its median first token went from 470 ms to 12.6 s. The FP8 pool held 107,299 tokens and kept every prefix, with a first token under 400 ms at every length. At 2,048 shared tokens, FP8 gave 6.0 times the output of BF16. Raw runs
One caveat belongs with the last row. The BF16 runs at 4,096 shared tokens stayed under our 1,000 MHz clock floor after three tries, at a median of 390 MHz. Read the 2,048 row as the result. Its BF16 runs had a median clock of 1,275 MHz, above the floor, but half of their samples had the thermal flag set. The FP8 runs had a median clock of 1,200 to 1,260 MHz.
The Inside an LLM Serving GPU machine runs the small-pool test on an L4. This link opens BF16 at a fraction of 0.74 with 2,048 shared tokens. The four prefixes do not fit in 6,559 tokens together, so the tree evicts prefixes and requests compute them again. Switch the weights to FP8 to keep every prefix in 107,299 tokens.
Our position
Use an offline-quantized checkpoint and pass no --quantization flag. The SGLang docs give the same advice. Online quantization adds load time and gives you a checkpoint that nobody evaluated.
Choose a KV cache dtype from memory, not from speed. If your server queues requests because the pool is full, FP8 is the cheapest capacity we measured. Our runs changed the weights and the KV cache together. For an FP8 KV cache alone, the evidence is the field report in section 3.1, and you need a scale file. If the pool has room, keep the model dtype.
On our GB10 with Qwen3-30B-A3B, FP8 weights with an FP8 KV cache gave 1.73 to 1.88 times the throughput at every concurrency. Decode on that card waits for memory, so smaller weights are faster. Check accuracy on your own tasks before you serve it.
Quantize per phase when you run prefill and decode on separate servers. Smaller weights help decode, and they can slow prefill.
Incidents
The BF16 cache ran out at 64 requests. Cloudflare reported that Kimi K2.6 with a BF16 KV cache ran out of memory at concurrency 64. The FP8 cache held about 1.37 million tokens against about 686,000 and served the same load.
A container could not run NVFP4. A field report from joshua8.ai used an RTX PRO 6000 Blackwell. NVFP4 did not run in its SGLang container, so it compared SGLang on GPTQ-INT4 against vLLM on NVFP4. Compare engines on the same weight format, or the result measures the format.
FP4 needs one GPU generation. A user summary on Pivot News reported that SGLang crashed when RTX 4090 cards joined a Blackwell pipeline. Its FP4 path required compute capability 10.0 and had no software path for older cards. This report reached us through a secondary summary of a Reddit post.
--speculative-algorithm
Speculative decoding spends idle GPU compute to commit several tokens per step, so it cuts latency at low load and can cost throughput when the GPU is already full.
A user turned on EAGLE-3 for Llama-3.1-8B on an A6000 and ran two tests. At batch 1, output went from 42.0 to 92.5 tok/s, more than twice as fast. At concurrency 20, output fell from 217.8 to 164.4 tok/s, a quarter slower. Both numbers are in issue #5274, and both are correct. A maintainer answered that speculative decoding is meant for small batches, not for stress tests.
When you finish this section, you can explain draft, verify, and acceptance length, and read the defaults SGLang picks. You can also find the request limit that speculation sets and decide where speculation belongs.
The cost: decode is one token at a time
Each decode step commits one token per request, and the next step needs that token as input. At batch 1 a step reads every weight of the model to compute one token. The GPU has compute to spare and memory traffic is the limit. A larger batch fills that spare compute with other requests.
Speculative decoding fills it with guesses. Draft model: a small model, or a small head trained on the target model, that proposes the next few tokens cheaply. Verify pass: one forward of the target model over all proposed tokens at once. The target accepts the longest prefix that matches what it would have produced, and adds one token of its own.
Acceptance length: the number of tokens committed per verify pass, accepted drafts plus that one bonus token. An acceptance length of 3 means one target forward commits three tokens.
One step in SGLang
- Draft. The draft model runs
--speculative-num-stepstimes. With--speculative-eagle-topkabove 1, each step keeps several candidates per node and grows a tree. A tree builder keeps the best--speculative-num-draft-tokensnodes and builds a tree mask. - Verify. The target runs once in
TARGET_VERIFYmode over every draft token with the tree mask. For greedy requests it keeps the longest matching path. For sampled requests it compares probabilities with temperature, top-k, and top-p applied. - Draft extend. The draft model reads the accepted tokens in
DRAFT_EXTEND_V2mode, so its cache is ready for the next step.
The accept thresholds --speculative-accept-threshold-single and --speculative-accept-threshold-acc default to 1.0. With those values, a greedy request produces the same tokens it would produce without speculation.
The algorithms and the defaults
--speculative-algorithm accepts EAGLE, EAGLE3, NEXTN, STANDALONE, NGRAM, DFLASH, DSPARK, and UNO. NEXTN is another name for EAGLE. For DeepSeek V3 and other models that include multi-token prediction layers in the checkpoint, SGLang sets the draft model path to the model path. NGRAM needs no draft model at all. It looks up repeated token sequences in the text it has already seen.
With NGRAM, SGLang turns off mixed chunked prefill. The docs page at v0.5.22 also says that NGRAM turns off the overlap scheduler and runs on CUDA only. The v0.5.22 code accepts CUDA, CPU, and XPU, and it turns the overlap off only on CPU. Read disable_overlap_schedule from GET /server_info to see what your server runs. When you compare NGRAM with no speculation, run both with the same overlap setting.
When you leave the shape unset, SGLang chooses (num_steps, topk, num_draft_tokens) from the model architecture.
| Model | Default shape |
|---|---|
LlamaForCausalLM, Grok | (5, 4, 8): a tree of up to 8 drafts |
DeepSeek, GLM, GPT-OSS, MiMo, STANDALONE, and every other model | (3, 1, 4): a chain of 3 drafts |
With topk 1, the code forces the draft token count to the step count plus one.
The limit nobody asked for
The EAGLE, NGRAM, DFLASH, and DSPARK handlers at v0.5.22 each do the same thing when you did not set --max-running-requests. It sets the value to 48 and logs one warning: Max running requests is reset to 48 for speculative decoding. Speculation needs memory for draft tokens and works best at small batch, so the cap protects the server. It also caps your benchmark.
A throughput test with speculation on and no explicit limit measures a server that admits 48 requests. If your traffic runs 200 concurrent requests, the other 152 wait in the queue, and time to first token grows. The warning prints once at startup, and it scrolls away before the first request.
What to measure
The scheduler logs accept len and accept rate on each decode log line, and /metrics exports sglang:spec_accept_length and sglang:spec_accept_rate. Measure them on your own prompts, because acceptance depends on the text and on the draft. A field report by David Noel Ng on two GH200 measured 3.5 to 5.05 tokens on DeepSeek-V4-Flash after a loader fix.
Run a sample of your own traffic with and without speculation. Keep your real output lengths, and pass --disable-ignore-eos to the benchmark client. With no traffic sample, --dataset-name speed-bench reads a local copy of the SPEED-Bench prompts at v0.5.22. Compare these numbers:
- The acceptance length, from
sglang:spec_accept_length. - The median TPOT and the output throughput.
- The P99 ITL and the P99 TTFT, because a gain in the median can hide a loss in the tail.
- The acceptance length of your longest answers alone. Each
/generateresponse gives it asspec_accept_lengthinmeta_info.
Then sweep concurrency with speculation on and off, and find where the two lines cross. Ant Group measured this on DeepSeek-R1 on H20. Longer drafts gained 21% at batch 1 and lost about 18% at batch 32.
What we measured on a GB10
We ran EAGLE-3 on Qwen/Qwen3-30B-A3B-Instruct-2507 on one NVIDIA GB10. The draft was lmsys/SGLang-EAGLE3-Qwen3-30B-A3B-Instruct-2507-SpecForge-Nex, with the shape (3, 1, 4) that the SGLang cookbook uses for this pair.
The first start failed. The draft config says 2,048 positions, and the target says 262,144. The context length check raised ValueError and ended with To allow overriding this maximum, set the env var SGLANG_ALLOW_OVERWRITE_LONGER_CONTEXT_LEN=1. The cookbook command for this pair sets that variable, so we set it too.
… Warning: Target model's context_length (262144) is greater than the derived context_length (2048). This may lead to incorrect model outputs or CUDA errors. Note that the derived context_length may differ from max_position_embeddings in the model's config.
… Overriding the draft model's max_position_embeddings to 262144.
… Max running requests is reset to 48 for speculative decoding. You can override this by explicitly setting --max-running-requests.The variable only removes the check. It does not teach the draft to read long prompts, which is the failure in issue #6783 below. Our prompts had 512 tokens, so this run says nothing about long contexts.
We expected the same refusal on a 24 GB L4. We started Qwen/Qwen3-8B with the draft Tengyunw/qwen3_8b_eagle3 and no variable, and the server started. That draft declares 40,960 positions, the same as its target, so the check had nothing to refuse. The variable belongs to one draft config, not to EAGLE-3. Compare max_position_embeddings in both configs before you set it.
… Load weight end. elapsed=3.89 s, type=Qwen3ForCausalLM, avail mem=6.41 GB, mem usage=15.28 GB.
… Load weight end. elapsed=0.67 s, type=LlamaForCausalLMEagle3, avail mem=4.50 GB, mem usage=1.90 GB.
… KV Cache is allocated. dtype: torch.bfloat16, #tokens: 8827, K size: 0.61 GB, V size: 0.61 GB
… max_total_num_tokens=8827, chunked_prefill_size=4096, max_prefill_tokens=16384, max_running_requests=48, context_len=40960, available_gpu_mem=1.19 GBThe same start shows the price of a draft on a small card. The target alone had a pool of 24,094 tokens on this L4. With the draft loaded, the pool held 8,827 tokens, about 14 of our 640-token requests. The sweep server on the same card started with more free memory and held 9,951 tokens.
We measured three seeds at each concurrency from 1 to 64, with the BF16 server as the baseline: Raw runs
| Concurrency | Baseline median TPOT | EAGLE-3 median TPOT | Baseline output tok/s | EAGLE-3 output tok/s |
|---|---|---|---|---|
| 1 | 32.52 ms | 20.30 ms | 29.14 | 40.93 |
| 8 | 102.21 ms | 59.44 ms | 74.11 | 97.06 |
| 32 | 201.91 ms | 106.97 ms | 150.66 | 228.78 |
| 64 | 254.06 ms | 138.41 ms | 235.38 | 276.32 |
The acceptance length stayed between 2.71 and 2.74 tokens per step at every concurrency. The gain per token stayed at 1.56 times or more at every load. It peaked at 1.89 times at concurrency 32, and it was 1.84 times at 64.
This result goes against the A6000 report above, and the model explains it. A dense model reads all its weights for each step, and a larger batch already uses the spare compute. A mixture-of-experts model reads only the experts that the tokens of the step chose. The verify pass scores four positions per request with the expert weights it already read for that step. That is our reading, measured on one model and one GPU.
The cap is the limit. At concurrency 64, throughput was still higher than the baseline, 276.32 against 235.38 tok/s. The median time to first token was 7,772 ms against 557 ms. The server admits 48 requests, and the other 16 waited in the queue.
What we measured on a 24 GB L4
We ran the same sweep with the dense Qwen/Qwen3-8B and the Tengyunw/qwen3_8b_eagle3 draft on one L4. The default server ran on 2026-10-16 and the EAGLE-3 server on 2026-10-17, both at a median clock of 1,080 MHz or more. This time we set the variable, as the sweep does for every EAGLE-3 server.
… KV Cache is allocated. dtype: torch.bfloat16, #tokens: 9951, K size: 0.68 GB, V size: 0.68 GB
… max_total_num_tokens=9951, chunked_prefill_size=4096, max_prefill_tokens=16384, max_running_requests=48, context_len=40960, available_gpu_mem=1.23 GBWe measured a pool of 9,951 tokens against 24,094 without the draft. That pool holds about 15 of our 640-token requests, fewer than the cap of 48. Raw runs
| Concurrency | Default median TPOT | EAGLE-3 median TPOT | Default output tok/s | EAGLE-3 output tok/s |
|---|---|---|---|---|
| 1 | 60.16 ms | 25.61 ms | 13.42 | 31.81 |
| 8 | 66.01 ms | 35.58 ms | 112.62 | 181.55 |
| 32 | 96.18 ms | 43.82 ms | 270.11 | 269.42 |
| 64 | 107.42 ms | 51.50 ms | 250.85 | 245.34 |
The acceptance length was 2.73 to 2.74 tokens per step at every concurrency. Each token came out 1.6 to 2.3 times faster at every load. Yet from concurrency 32, the server delivered no more tokens per second than the default.
The pool explains the difference. With 15 requests in the pool, the rest waited for a slot. At concurrency 32, the median time to first token was 8,040 ms with EAGLE-3 and 2,970 ms without it. On a card where the KV pool is the limit, the draft spends the memory that the batch needs.
Know the limits of our results
Both sweeps used the random dataset of the benchmark client, with 512 tokens in, 128 tokens out, and ignore_eos on. At v0.5.22 that dataset takes the first turn of ShareGPT conversations, then cuts or repeats it to 512 tokens. It is real text, but it is not your traffic.
Other teams found that tests like ours can overstate the gain. We did not measure these effects ourselves:
- A 2026 benchmark study by NVIDIA researchers, SPEED-Bench, found that synthetic prompts overstated speculative throughput by 23 percent on average. It also found that the best draft length fell to 1 as the batch grew.
- The same study found that random token ids left 20 to 30 percent of the experts idle in some layers of an MoE target.
- A 2026 study of EAGLE-3 and other drafts, Test-Time Speculation, found that the acceptance length falls as the answer grows. On MATH answers that ran toward 20,000 tokens, it fell from about 3.7 to about 1.5.
- A 2025 study of serving benchmarks compared speculation with the baseline. The median TPOT was 1.3 times lower, and the P99 TPOT was 1.16 times higher. TTFT also rose, because the draft runs its own prefill.
So our gains hold for 128 generated tokens with the end token ignored, on our test prompts. They do not predict the gain on long chat answers or on reasoning traces. Our reading of the GB10 result also depends on how real tokens choose their experts, and we did not measure the routing.
Real prompts on the L4
On 2026-10-23 we ran the same L4 sweep on four datasets: the random set, ShareGPT, GSM8K questions, and code prompts. The clock was locked at 900 MHz, the cache was flushed before each run, and each point had two seeds.
median TPOT at 8 users: default / EAGLE3 / NGRAM
random 67.6 to 68.2 / 33.8 to 39.4 / 68.2 to 71.4 ms
ShareGPT 66.4 to 68.6 / 39.5 to 43.1 / 69.5 to 72.4 ms
GSM8K 65.5 / 33.3 to 34.3 / 54.6 to 55.0 ms
code 65.9 to 66.4 / 36.8 / 58.2 to 58.8 ms
…
output tok/s at 32 users: default / EAGLE3 / NGRAM
random 250 to 254 / 239 to 242 / 236 to 250
ShareGPT 281 to 288 / 277 to 283 / 245 to 256
GSM8K 397 / 648 to 660 / 433 to 435
code 365 to 366 / 566 to 581 / 377 to 386
…EAGLE-3 cut the time per token about in half at 8 users on every dataset, with an acceptance length of 2.35 to 2.78. At 32 users it gave 1.6 times the output on GSM8K and code. On the random set and ShareGPT it gave no more output. There its first token came 2 to 3 times later, because the draft took pool space that the queue needed.
NGRAM helped only on GSM8K and code, by about 1.1 to 1.2 times at 8 users. On the other two sets it was slower, and its P99 ITL rose to 244 to 779 ms. So the dataset changed the result more than the random set suggests. Test on your own traffic.
Acceptance over a long answer
We tested the claim of Test-Time Speculation on shorter answers. On 2026-10-23 we ran Qwen/Qwen3-8B-FP8 with an EAGLE-3 draft, 3 steps, top-k 1, and 4 draft tokens. This was on the second GPU of our L4 node, which its owner shares and which had no clock lock. Each of 8 prompts ran with thinking on, greedy, alone, up to 4,096 tokens. We read spec_verify_ct after answers of 256, 512, 1,024, 2,048, and 4,096 tokens.
segment of the output SGLang vLLM
0 to 256 2.05 to 2.64 (8) 2.14 to 2.51 (8)
256 to 512 1.95 to 2.64 (8) 2.09 to 2.55 (8)
512 to 1,024 2.11 to 2.77 (8) 2.12 to 2.79 (8)
1,024 to 2,048 2.09 to 2.47 (5) 1.72 to 2.66 (5)
2,048 to 4,096 2.33 and 2.48 (2) 2.35 and 2.60 (2)Up to 4,096 tokens, the acceptance length did not fall steadily. It stayed at about 2.1 to 2.8 tokens for each verify step on both engines. Only 2 of the 8 prompts ran past 2,048 tokens before the end token, so the last segment rests on two answers. The clock changes the speed and not the acceptance. Our limit of 4,096 tokens came from the memory we could use on that GPU. So our test did not reach the range of the study.
A second test used Qwen/Qwen3-8B in BF16 at 8 users, with answers of up to 2,048 tokens and no ignore-eos. The median answer was 1,800 to 2,000 tokens.
engine dataset mean acceptance length accepted per draft position 1 / 2 / 3
SGLang EAGLE3 GSM8K 2.68
SGLang EAGLE3 ShareGPT 2.32
vLLM EAGLE3 GSM8K 2.69 0.77 / 0.54 / 0.38
vLLM EAGLE3 ShareGPT 2.35 0.67 / 0.42 / 0.26On short answers in the same session, SGLang gave 2.69 to 2.78 on GSM8K and 2.33 to 2.43 on ShareGPT. Its long answers stayed within 0.01 of those ranges. We have no short-answer acceptance for vLLM from this session, so its rows show only the level on long answers.
Our position
Treat speculative decoding as a latency tool for low and middle concurrency. Turn it on for interactive traffic with a few users per replica. Leave it off for batch jobs and high concurrency on a card where the KV pool is the limit, as on our L4. On the GB10, where the pool had room, speculation still gave 1.17 times the throughput at 64 users.
Measure the cross point on your model before you accept that rule. On the mixture-of-experts model above, speculation still won at concurrency 32 on the GB10. On the dense model on the L4, it gave no more throughput at 32, because the draft took nearly 60 percent of the pool. Measure it with your own prompts and output lengths, with the list in the section on what to measure.
Always set --max-running-requests yourself when speculation is on. Choose it from the concurrency where your sweep shows speculation still wins.
Use the draft layers that come with your model first. A model with multi-token prediction layers needs no extra download. For EAGLE-3, check that the draft model supports your prompt length, and train a draft on your own traffic when acceptance is low. Google Cloud and Modal with Decagon both trained their own drafts. Modal reported 38% longer acceptance than open-source drafts. Both are vendor reports.
Incidents
Speculation made a stress test slower. Issue #5274 (2025-04-11): EAGLE-3 on an A6000 lowered throughput at concurrency 20 from 217.8 to 164.4 tok/s. It raised batch-1 speed from 42.0 to 92.5 tok/s. The fix was to run speculation only at small batch.
The draft could not read long prompts. Issue #6783 (2025-05-30): Llama-3.3-70B FP8 with EAGLE-3 accepted 3.2 tokens at 1k input, 1.6 at 3k, and 1.2 at 10k. At 10k it produced 63.9 tok/s against 102.7 without speculation. The draft config had 2,048 positions and no rope scaling. Adding Llama 3 rope scaling and 131,072 positions to the draft config fixed it.
A loader bug hid the expert weights. David Noel Ng found SGLang slower than vLLM on DeepSeek-V4-Flash. Acceptance was 1.3 to 1.8 tokens, and only a log warning pointed at the cause. The draft loader never mapped the shared expert weights into the fused slot. After a local fix, decode went from 115.7 to 176.0 tok/s, and PR #33276 fixed it upstream.
--grammar-backend and structured outputs
SGLang turns a JSON schema or regex into a token mask for every decode step, and compiles each grammar outside the batch loop.
Your agent asks the model for a tool call and parses the reply with json.loads. Most replies parse. A few have a missing brace, a trailing comment, or a field the schema does not allow, and the agent retries. Each retry costs a full generation and a full round trip, and the slow tail of your latency is now made of retries.
When you finish this section, you can constrain output with a JSON schema, a regex, or an EBNF grammar. You can also explain what the mask costs, read the grammar queue, and decide what to check after generation.
The obvious fix, and why it fails
The obvious fix is to validate after generation and retry on failure. That works and stays slow. It also fails in the cases you care about most. At temperature 0, a retry of the same prompt gives the same broken reply.
Constrained decoding: removing every token that would break the grammar before the sampler picks one. The output then satisfies every rule that the backend enforces, so those rules become a property of the server.
What SGLang does
A request carries one constraint in its sampling parameters: json_schema, regex, ebnf, or structural_tag. The OpenAI chat API maps response_format to the same fields. --grammar-backend picks the engine that compiles it. The default at v0.5.22 is xgrammar, and outlines, llguidance, and none are the other choices.
- Look up. The grammar manager builds a key from the constraint type and its text, such as
("json", schema). A compiled grammar for that key comes back from the cache at once. - Compile. On a miss, compilation starts in a thread pool and returns a future. The request moves to the grammar queue instead of the waiting queue.
- Admit. Each scheduler loop polls the futures. With tensor or data parallelism, a request is admitted only when its grammar is ready on every rank. It fails if compilation failed on any rank. An invalid grammar is cached as invalid, so the next request with the same schema fails at once.
- Mask. At every step the grammar fills a vocabulary bitmask, and the model runner applies it to the logits before sampling. With the overlap scheduler, the mask for the next step is built while the GPU runs the current one.
- Advance. After sampling, the grammar accepts the chosen token. With speculative decoding, it rolls back the rejected draft tokens.
On Apple silicon, the MLX runtime applies grammar masks only with --mlx-enable-sampling. Without that flag every decode step takes the highest logit, as section 4.6 shows from the help text.
Grammar queue: the list of requests whose grammar is still compiling. /metrics exports its length as sglang:num_grammar_queue_reqs.
Jump-forward is not active at v0.5.22
The SGLang paper describes jump-forward decoding. When the grammar allows only one continuation, such as the fixed text {"name": ", the server writes it without running the model. The grammar classes at v0.5.22 still have the jump-forward methods. A search of the runtime finds no caller outside the grammar classes. The scheduler does not use them, so expect one forward per token even inside fixed text. We read this in the code and did not run a timing test.
What to measure
Measure three things on your own schemas. First, the time to first token for the first request with a new schema against the second request with the same schema. The difference is compile time. Second, inter-token latency with and without the constraint at your real concurrency. The mask costs CPU time on every step. Third, the grammar queue length under load.
A field report by Varad More measured structured generation on one A10G across 16 models from 2B to 9B. On 14 of the 16, vLLM was faster. The report does not separate compile time from per-token cost, so read it as a reason to measure, not as a verdict.
What we measured on a GB10
We ran a small probe against Qwen/Qwen3-30B-A3B-Instruct-2507 on one NVIDIA GB10, with the default xgrammar backend. The probe asks "Describe one GPU for a model server as a JSON object." five times, one request at a time. The schema has four required fields, an integer memory_gb from 1 to 1024, an enum for the vendor, and no extra properties.
| Request | Constraint | Latency | Completion tokens | Valid |
|---|---|---|---|---|
| 1 | none | 3,943.9 ms | 128 | no schema |
| 2 | a new schema | 1,636.6 ms | 41 | yes |
| 3 | the same schema | 1,309.2 ms | 41 | yes |
| 4 | the same schema | 1,310.9 ms | 41 | yes |
| 5 | a second new schema | 1,291.1 ms | 41 | yes |
We measured one run, so read the table as a direction. Every constrained reply was valid JSON with exactly the four fields. The unconstrained reply ran to the 128-token limit and invented its own keys, such as gpu_id and power_consumption. Raw runs
The first constrained request cost about 330 ms more than the repeats. The second new schema showed no such cost. Our reading is that the first cost belongs to the first grammar after startup. The compile of one small schema was too short to see next to a decode of 41 tokens.
The schema fixed the shape and not the facts. The constrained replies named an "NVIDIA A100" with 40 GB, and the unconstrained one gave it "80 GB GDDR6". A grammar checks syntax, and your validator still checks meaning.
Our position
Constrain every response that a program parses. A mask adds work to each step, and a retry repeats the whole request. We did not measure the cost of the mask per step.
Do not trust the grammar backend to enforce every JSON Schema keyword. Test each keyword your consumer depends on, such as minLength, pattern, minimum, and enum, with a request that tries to break it. Keep a cheap validator behind the server for the fields that matter.
Send one constrained request after every deploy, so the first user request does not pay the startup cost of the grammar backend. On the GB10 that first request paid about 330 ms. Our probe showed no extra cost for a second, new small schema.
Incidents
A schema rule was dropped without an error. Issue #37707 (2026-09-03): with xgrammar, a string field accepted values shorter than its minLength when the same field also had a pattern. The same report says outlines dropped pattern and numeric bounds. The issue was open when this manual was verified.
Grammar work grew with output length under speculation. Issue #38863 (2026-09-10): with speculative decoding, the host CPU time to build bitmasks grew with the length of the output. The cause was a rollback method that copied a debug list on every call. The issue was open as a performance report.
--enable-deterministic-inference and logprobs
The same prompt can give different tokens when the batch around it changes, and SGLang fixes the reduction order for each model and backend it has tested.
You run an evaluation twice at temperature 0 and the scores differ. You send one prompt alone and then inside a busy batch, and the second answer diverges after forty tokens. Nothing in your request changed. The server changed the batch your request ran in, and the batch changed the arithmetic.
When you finish this section, you can explain why batching changes output and what deterministic mode switches. You can also read the logprobs SGLang returns and test whether your model is deterministic.
The cost: addition order depends on the batch
Floating-point addition is not associative. Summing the same numbers in a different order can change the last bits of the result. A matrix multiply, a softmax, or a norm splits its sums into tiles, and many kernels pick the tile split from the batch size. A request in a batch of 1 and the same request in a batch of 37 go through different splits.
A difference in the last bit can change which token has the highest logit. After one different token, every later token is conditioned on a different text. Thinking Machines described this effect in a 2025 post on nondeterminism in inference, and SGLang built its deterministic mode on the same approach.
Batch invariance: a kernel property. The result for one row does not depend on the other rows in the batch, because the reduction order is fixed.
What the flag switches
--enable-deterministic-inference is off by default. --rl-on-policy-target fsdp turns it on too. When it is on, startup does the following:
- It replaces the PyTorch operators
aten::mm,addmm,_log_softmax,mean.dim,rms_norm, andbmmwith batch-invariant kernels. - It forces the
pytorchsampling backend. - With tensor parallelism on CUDA, it sets
NCCL_ALGO=allreduce:tree, so the all-reduce sums in a fixed order. On AMD it uses a one-stage all-reduce. - It accepts only the attention backends
ascend,fa3,fa4,flashinfer,intel_xpu, andtriton. - It turns the radix cache off unless the attention backend is
ascend,fa3,fa4, ortriton. - It gives every request without a
sampling_seedthe seed 42.
The fifth point matters most for a server. With flashinfer, deterministic mode turns off prefix caching. Every repeated prefix pays its full prefill again. Section 3.3 explains what that cache saves.
Logprobs are temperature-scaled
Logprob: the log probability of a token under the distribution the server sampled from. SGLang returns it when a request sets return_logprob or the OpenAI logprobs field.
The sampler computes returned logprobs as log_softmax(logits / temperature) when the batch is not all greedy. It returns log_softmax(logits) without the temperature only for all-greedy batches or when the environment variable SGLANG_RETURN_ORIGINAL_LOGPROB is set. A request at temperature 0.7 gets logprobs of the sharpened distribution.
In our test, top-p did not change the returned value. The test used return_logprob at temperature 1 and top-p 0.9. We ran it on the second GPU of our L4 node on 2026-10-23, with Qwen/Qwen3-0.6B in BF16. We sent 16 prompts of 48 tokens. We compared each returned logprob with a float32 Transformers pass over the full vocabulary.
engine and mode returned minus reference, median median absolute
…
SGLang return_logprob, ORIGINAL_LOGPROB=0 0.0000 0.0066
SGLang return_logprob, ORIGINAL_LOGPROB=1 0.0000 0.0066SGLang returned the logprob from before top-p, with the environment variable at 0 or at 1. At temperature 1 the two settings compute the same value. On the same prompts, the logprob after top-p was higher by minus the log of the kept mass, a median of about 0.053. So a trainer that renormalizes over the kept tokens must not compare with this value directly. The GPU was shared and had no clock lock, which does not change these values.
At a temperature other than 1, the scaled value is correct for sampling. It surprises anyone who compares those numbers with a model run at temperature 1. A reinforcement learning trainer that computes logprobs from the raw logits sees a mismatch on every token, and the mismatch looks like a numerical bug. Section 7.2 shows why that matters for training.
On Apple silicon
Our capture ran on the MLX runtime, and MLX treats sampling differently. The help text for --mlx-enable-sampling says what changes.
--mlx-enable-sampling
MLX backend only: sample decode tokens (temperature /
top-k / top-p / min-p) instead of greedy argmax.
…
exact argmax behavior. Also enables on the MLX path:
grammar vocab masks and custom logit processors (these
break decode chaining per step; custom processors run
on pure-decode steps only), logit_bias, output
logprobs (sampled token / top-k / token_ids; prompt
input logprobs are not computed), NaN sanitization
(SGLANG_SANITIZE_NAN_LOGITS), and per-request
sampling_seed under --enable-deterministic-inference
(deterministic within MLX only). Penalties are not
applied.Without that flag, every decode step on MLX takes the token with the highest logit, whatever temperature the request asks for. Grammar masks and output logprobs also need the flag, and penalties never apply on MLX. Our capture kit sends temperature 0, so its results do not depend on this flag.
What to measure
SGLang includes a test that sends one prompt in random batch sizes and counts distinct outputs. It has three modes: single, prefix for shared prefixes, and radix_cache for cached against uncached prefill.
python3 -m sglang.test.test_deterministic --n-trials 50 --test-mode single
python3 -m sglang.test.test_deterministic --n-start 1 --n-trials 50 --test-mode prefixRun it against your model, your attention backend, and your parallel layout. One distinct output per prompt is the pass condition. Then measure throughput with the flag on and off, because batch-invariant kernels give up some speed.
What we measured on a GB10
Our probe sends one prompt at temperature 0 with 128 new tokens. It sends the prompt five times alone, then five times inside a batch of 16 with 15 other prompts. We ran it against Qwen/Qwen3-30B-A3B-Instruct-2507 on one NVIDIA GB10, first on the default server and then with --enable-deterministic-inference.
We measured two different answers from the default server. The first request alone and all five batched requests wrote one text. The next four requests alone wrote another text, which left the first after 238 characters. Nothing in the request changed between those runs. Raw runs
Our reading is that the first request computed its prompt from nothing. The four later ones found that prompt in the radix cache and ran a different prefill path. The radix_cache mode of the test above checks that case.
With the flag on, all ten requests wrote the same text. The startup log shows the switches from the list above:
… Sampling backend is set to pytorch for deterministic inference.
… Attention backend not specified. Falling back to 'flashinfer' for deterministic inference. You can explicitly set --attention-backend to one of ['ascend', 'fa3', 'fa4', 'flashinfer', 'intel_xpu', 'tri…
… Currently radix cache is not compatible with flashinfer attention backend for deterministic inference. It will be supported in the future.In one run per server, the price at concurrency 8 was 18 percent of the throughput. Output fell from 78.92 to 64.83 tok/s, and the median time per token rose from 97.30 to 117.43 ms. The radix cache was off, so a workload with shared prefixes pays more than this test shows.
What we measured on an L4
On an L4 with Qwen/Qwen3-8B in BF16, the four later requests alone also matched each other and not the first. The batched requests there wrote two more texts, so the default server gave four different answers to one prompt. With the flag on, all ten matched on the L4 too.
A later check used Qwen/Qwen3-8B-FP8 on the second GPU of the same L4 node. The first request alone again differed from the four later ones. This time the batch added one more text, not two. With the flag on, all ten matched again.
That check also showed a backend change. With the flag on and no --attention-backend, SGLang chose fa3 on the L4, which is SM 8.9. The default server on the same GPU uses flashinfer.
Attention backend not specified. Falling back to 'fa3' for deterministic inference
The server ran on fa3 on SM 8.9 with no error. The default server on this GPU uses flashinfer.So on this GPU the flag changes the attention backend too. With fa3, the fifth point of the list above keeps the radix cache on.
What the cache, the batch, and the dtype changed
We counted how many greedy outputs changed between two runs. The prompts were ShareGPT questions after one shared system prompt of about 170 tokens, with 128 output tokens and thinking off. This was on the second GPU of our L4 node with Qwen/Qwen3-0.6B, which its owner shares and which had no clock lock. A clock changes the speed and not the greedy tokens.
comparison SGLang 0.6B vLLM 0.6B
flushed repeat against fresh 0 of 32 0 of 32
cache off against cache off 0 of 32 0 of 32
fresh against warm cache 21 of 32 (45) 11 of 32 (57)
cache on against cache off 25 of 32 (26) 21 of 32 (48)- One request at a time, the same cache state. A repeat after a flush, or a repeat with the radix cache off, gave the same text for all 32 prompts.
- One request at a time, a warm cache. The same prompts against a warm cache changed 21 of 32 outputs. The cache on against the cache off changed 25 of 32.
- 64 requests at once. Two runs with the cache off differed in 27 of 64 outputs. The batch alone changed many outputs, so the cache effect could not be separated at that load.
- The dtype. We sent 64 questions at a concurrency of 1 with the cache off. BF16 against FP16 changed 51 of 64 outputs for Qwen3-0.6B and 57 of 64 for Qwen3-1.7B. The first different token came at a median position of 41 and 54. A repeat in the same dtype changed none.
A 2026 study of two serving engines found the same cache split. Our counts come from small models on one GPU, so test your own model the same way.
Know the limits of our result
Our 18 percent is one run at one concurrency on one model. Other teams measured the cost and the gaps of deterministic modes. We did not measure these results ourselves:
- The speed cost. Thinking Machines Lab ran 1,000 Qwen3-8B requests on vLLM in 26 s by default and in 55 s with batch-invariant kernels. A better attention kernel brought it to 42 s.
- A larger cost under load. A 2026 study, CoRun, measured batch-invariant kernels at more than twice the latency and up to 74 percent less throughput.
- Other changes in execution. A 2026 verification study, Vosti, tested changes such as prompt chunking and KV cache reuse. The deterministic mode of SGLang gave different logits under some of them.
So measure the cost at the concurrency you serve. Test the exact setup: the model, the attention backend, the parallel layout, the chunk size, and the cache setting.
Our position
Treat --enable-deterministic-inference as a promise for one model on one backend, and test that promise. Turn it on for reinforcement learning rollouts and for evaluations you want to reproduce. Leave it off for production traffic, where prefix caching and faster kernels are worth more than identical bits. Do not assume that temperature 0 alone gives identical text. On the GB10 it did not.
Set sampling_seed on each request that must reproduce. Seed 42 for everyone makes every sampled request draw the same random numbers.
Run the same eval twice and compare the outputs token by token, not only the score. Between the two runs, call POST /flush_cache or restart the server, as section 5.1 shows. Write the cache setting and the cached tokens next to the result.
Incidents
The flag was accepted and the output still varied. Issue #43055 (2026-10-08): gpt-oss-20b gave several different greedy outputs for one prompt in prefix mode. Comments traced it to the deterministic Triton extend kernel on sliding-window layers. It aligned KV tiles to the trimmed prefix and not to absolute positions. The issue was open when this manual was verified.
Some architectures are not covered yet. Issue #43413 reported that a Mamba2 hybrid model was not batch-invariant. Issues #36174 and #31261 list DeepSeek-V4 and Qwen3.5 as not yet supported in deterministic mode.
A restart changed greedy output. Issue #39597 (2026-09-15): with the DFLASH speculative algorithm, the same prompt gave different text after a restart. FlashInfer autotuning picked different kernel tactics on each start. The workaround was --disable-flashinfer-autotune or deterministic mode.
Measuring a Server
A throughput number without a latency target describes nothing, so measure the knee before you tune anything.
sglang.benchmark.serving
One benchmark run measures one concurrency, so you sweep concurrency until extra load stops adding throughput and only adds waiting.
A teammate posts "SGLang does 255 tokens per second on my laptop" in the team channel. The number is true. It came from our capture. It is also useless on its own. The same server gave that throughput with a median first token of 0.8 s at one load and 3.9 s at another. A throughput number without the latency that came with it describes nothing a user feels.
When you finish this section, you can run sglang.benchmark.serving with settings you can defend and read every line of its report. You can find the knee where more concurrency stops paying. You can also say which of your own numbers will transfer to a GPU and which will not.
The command we ran
The server is one process with the model mlx-community/Qwen3-0.6B-4bit on the capture Mac. Every run in this section talks to this one server.
SGLANG_USE_MLX=1 sglang serve --model-path mlx-community/Qwen3-0.6B-4bit --disable-cuda-graph --host 127.0.0.1 --port 30000 --enable-cache-report --enable-metrics --mem-fraction-static 0.4Two flags in that command need a note. SGLang's Apple silicon guide still passes --disable-cuda-graph, and the v0.5.22 help marks it deprecated in favor of --cuda-graph-backend-{decode,prefill}=disabled. On the MLX backend, decode is greedy unless you add --mlx-enable-sampling, so our runs measured the greedy path. The benchmark sends temperature 0 by default, so the client and the server agree here.
The client is the benchmark module that comes with SGLang. We ran it three times, with a concurrency cap of 1, 8, and 32. The run at 8 looks like this:
python -m sglang.benchmark.serving --backend sglang --port 30000 \
--dataset-name random --random-input-len 512 --random-output-len 128 \
--random-range-ratio 1.0 --num-prompts 32 --max-concurrency 8 --seed 7The path changed. The benchmark tools moved into the sglang.benchmark package in 2026-06. python -m sglang.bench_serving still runs as a deprecated alias that imports the new module. python -m sglang.bench_one_batch and python -m sglang.bench_offline_throughput do not run at v0.5.22. PR #40795 deleted both aliases on 2026-09-22. If a tutorial uses those two paths, it was written for an older SGLang, and its other flags are suspect too.
Four defaults that change the result
The client makes choices before it measures anything. Each one changes the number you report, and most published benchmarks do not say which ones they kept.
| Setting | Default at v0.5.22 | What it does to the result |
|---|---|---|
--random-range-ratio | 0.0 | Each length is drawn from 1 to the length you asked for, so the average prompt is about half of --random-input-len |
ignore_eos | on | The server ignores the end token, so every request generates exactly --random-output-len tokens |
--request-rate | inf | All requests are sent at time 0, and only --max-concurrency holds them back |
--warmup-requests | 1 | One request runs before the clock starts |
The first row is the trap. With the default ratio, --random-input-len 512 gives an average prompt near 256 tokens. Your report then says 512 and describes half the work. We set the ratio to 1.0, and the report confirms it. 32 prompts of 512 tokens give Total input tokens: 16384. With ignore_eos, the run gives Total generated tokens: 4096, exactly 32 times 128.
Our position: pass --random-range-ratio 1.0 every time, or write the length distribution next to the result. A benchmark that hides its lengths cannot be compared with anything.
Read the report, block by block
============ Serving Benchmark Result ============
Backend: sglang
Traffic request rate: inf
Max request concurrency: 8
Successful requests: 32
Benchmark duration (s): 16.02
Total input tokens: 16384
Total generated tokens: 4096
Request throughput (req/s): 2.00
Output token throughput (tok/s): 255.63
Peak output token throughput (tok/s): 440.00
Peak concurrent requests: 16
Total token throughput (tok/s): 1278.13
Concurrency: 7.96
…
Median TTFT (ms): 785.79
P99 TTFT (ms): 2180.87
…
Mean TPOT (ms): 23.02
Median TPOT (ms): 22.52
…
Median ITL (ms): 20.35
P99 ITL (ms): 78.79
Max ITL (ms): 1948.37The function calculate_metrics in the benchmark module computes every line. Five of them are easy to misread.
Concurrency: the sum of every request's end-to-end latency divided by the run duration. It is the average number of requests in progress, measured after the fact. Here it is 7.96 against a cap of 8. It tells you the cap was reached, and nothing more.
Peak concurrent requests: the run is cut into one-second buckets, and each request counts in every bucket that its interval touches. The line reports the largest bucket count. Two requests that run one after the other inside the same second both count, so the number can exceed the cap. That is why the report says 16 at a cap of 8, and 64 at a cap of 32.
TTFT: the time from sending the request to receiving the first streamed chunk. It contains queueing, prefill, and the network.
TPOT: for each request, the time after the first token divided by the remaining tokens, (latency - ttft) / (output_len - 1). The report gives the mean and percentiles over requests. ITL: every gap between two streamed chunks, pooled across all requests. A chunk with several tokens counts as one gap.
Max ITL: the single longest gap, here 1,948 ms. One request waited almost two seconds between two tokens while new prompts ran their prefill. The median ITL of 20 ms hides that stall. The P99 of 79 ms shows part of it.
The sweep and the knee
One run tells you one point. Three runs at caps of 1, 8, and 32 tell you the shape.
| Cap | Output tok/s | Median TTFT | P99 TTFT | Median TPOT | Concurrency |
|---|---|---|---|---|---|
| 1 | 175.15 | 162.98 ms | 270.18 ms | 4.38 ms | 0.99 |
| 8 | 255.63 | 785.79 ms | 2180.87 ms | 22.52 ms | 7.96 |
| 32 | 252.74 | 3917.54 ms | 8262.86 ms | 93.61 ms | 31.94 |
We measured this on the capture Mac. From 1 to 8, output throughput rises 46 percent and the median first token gets 4.8 times slower. From 8 to 32, throughput falls about 1 percent. The median first token gets 5 times slower, and the median time per token gets 4.2 times slower. Raw runs
The knee is the cap after which throughput stops rising. On this machine it is at or below 8. Past the knee, the server has no idle compute left to give. New requests only wait for a share of the same decode steps. The scheduler in section 2.2 accepts them anyway, because its admission limit on this Mac was max_running_requests=4096.
What transfers to a GPU. The absolute numbers do not. A 0.6B model on Apple silicon says nothing about an H100. The shape transferred to the servers we measured. Each one had a latency knee, the latency past it grew faster than the throughput, and the default admission limit sat far above it.
The same sweep on a GPU, run as an experiment
One run on a GPU told us something false. The GPU kit started the default server on an NVIDIA GB10 with Qwen3-30B-A3B and ran each cap once.
sglang serve --model-path Qwen/Qwen3-30B-A3B-Instruct-2507 --host 127.0.0.1 --port 30000 --enable-cache-report --enable-metrics --mem-fraction-static 0.7At a cap of 8 the single run reported a median first token of 677.61 ms. At a cap of 32 it reported 390.38 ms. More load gave a faster first token, and no queue explains that. One run is one sample, and one sample can be wrong for reasons you never see.
So we ran the sweep the way a model team runs a training comparison. Our sweep script runs every cap from 1 to 64 three times, with seeds 1, 2, and 3. It passes --output-details, so each run keeps the TTFT and the token gaps of every request. Our summary script reduces the three runs of each point to the median, the lowest, and the highest value.
| Cap | Single kit run, median TTFT | Three seeds, median TTFT (lowest to highest) |
|---|---|---|
| 8 | 677.61 ms | 209.98 ms (185.25 to 216.02) |
| 32 | 390.38 ms | 416.37 ms (338.06 to 434.64) |
We measured both on the same GB10, with two different servers. The single kit run had a pool of 227,243 tokens on 2026-10-17, and the sweep a pool of 234,600 tokens on 2026-10-16. The 677.61 ms result did not come back in three more runs. From a cap of 2 up, the first token gets slower as the cap grows, as the queue predicts. Raw runs
Later we found the cause of the false result in the server log of the kit run. The kit sent every run with seed 7 to one server, and it never cleared the prefix cache. With one seed, the client sends the same first prompts in every run. So each run found the prompts of the run before it in the cache:
[2026-10-17 14:23:00] Prefill batch, #new-seq: 14, #new-token: 14, #cached-token: 6879, token usage: 0.07, …
[2026-10-17 14:23:00] Prefill batch, #new-seq: 15, #new-token: 15, #cached-token: 7634, token usage: 0.07, …
[2026-10-17 14:23:47] Prefill batch, #new-seq: 1, #new-token: 510, #cached-token: 2, token usage: 0.01, …We counted the prefill lines of each kit run. At a cap of 8, 16 of the 64 prompts were in the cache before the run started. At a cap of 32, 64 of the 128 prompts were, and at a cap of 64, 128 of the 256. A cached prompt skips its prefill, so its first token comes fast. Half of the requests at a cap of 32 had that advantage, and a quarter at a cap of 8. That is why the median first token fell.
The widest band in the figure is EAGLE-3 at a cap of 8, from 86.93 to 107.23 tok/s. Every other band is inside about 10 percent of its median. With that spread, a gap of 1.9 times is real. At a cap of 64, FP8 gave 440.86 tok/s and BF16 gave 235.38 tok/s. The run without CUDA graphs lies on the default line, and section 4.1 explains why.
A median hides two populations
--output-details writes the first-token time of every request. We sorted all requests of the three seeds at a cap of 16 and plotted them.
We measured two groups on the GB10. For BF16, the fastest half of the requests had a first token from 186.3 to 211.8 ms. From the 68th percentile, requests waited 1,639.8 to 1,743.4 ms. The median was 237.6 ms and P90 was 1,721.5 ms, 7.2 times more. FP8 had the same two groups: 122.7 to 139.5 ms for the fast half, and 589.9 to 1,162.2 ms for the slow half. Raw runs
EAGLE-3 had the slowest median, 579.3 ms, and the shortest tail, 1,007.4 ms at P90. Its time per token had the widest spread instead: 82.8 ms at the median and 191.3 ms at P98. The number of draft tokens accepted changes from step to step.
Our reading of the two groups: the workload made them. Every request asked for exactly 128 tokens, because --random-range-ratio 1.0 fixes the length. Requests that start together therefore finish together, and their replacements arrive together. Each wave then queues for prefill behind the requests ahead of it. Real traffic has mixed lengths. If you test with fixed lengths, read P90 as the cost of a burst, not as the cost of a normal request.
The prefix cache gives a second reading, and we cannot rule it out. The sweep also kept one server for all the runs of one configuration, with no flush. Each seed sent the same first prompts at every cap. At a cap of 16, 32 of the 64 prompts were the prompts of the run at a cap of 8. If they were still in the pool, half of the requests skipped their prefill. We did not keep the full server logs of the sweep, so we cannot count the hits.
We tested this reading on the L4, not on the GB10. On 2026-10-23 we ran the load sweep of Qwen3-8B with a flush before each run and a 900 MHz lock. We compared it with a run of the same session that had no flush:
median TTFT, flushed against unflushed
users vLLM SGLang
4 650 / 145 ms (4.5x) 532 to 645 / 141 ms (3.8 to 4.6x)
8 951 to 978 / 264 to 274 ms (3.6x) 1,174 to 1,273 / 173 to 178 ms (6.6 to 7.3x)
16 1,550 to 1,587 / 294 to 295 ms (5.3x) 1,804 to 1,944 / 218 ms (8.3 to 8.9x)
…On the L4, the flush raised the median TTFT of SGLang 4 to 9 times at 4 to 16 users. The time per token changed by less than 10 percent. So on the L4, the cache made most of the fast group. On the GB10 we did not rerun the sweep, so both readings stay open there.
We tested the waves on an L4
A reading is a hypothesis until you change the variable it blames. We ran Qwen3-8B on one L4 with a cap of 16 and 64 prompts, three seeds per point. Only --random-range-ratio changed, from 1.0 to 0.5 to 0.0.
[2026-10-17 15:54:33] Prefill batch, #new-seq: 8, #new-token: 4096, #cached-token: 1, token usage: 0.34, #running-req: 1, #queue-req: 0, #pending-token: 513, cuda graph: True, input throughput (token/s): 3509.80
[2026-10-17 15:54:34] Prefill batch, #new-seq: 8, #new-token: 3583, #cached-token: 0, token usage: 0.34, #running-req: 8, #queue-req: 0, #pending-token: 0, cuda graph: True, input throughput (token/s): 3503.78
[2026-10-17 15:54:35] Decode batch, #running-req: 16, #token: 8240, token usage: 0.34, cuda graph: True, gen throughput (token/s): 2.62, #queue-req: 0
[2026-10-17 15:54:37] Decode batch, #running-req: 16, #token: 8880, token usage: 0.37, cuda graph: True, gen throughput (token/s): 231.07, #queue-req: 0
[2026-10-17 15:54:40] Decode batch, #running-req: 16, #token: 9520, token usage: 0.40, cuda graph: True, gen throughput (token/s): 229.85, #queue-req: 0The wave is in the log. Only one request was running, so fifteen had just finished together, and their replacements arrived together. The scheduler prefilled them as two chunks of up to 4,096 tokens, and then all 16 decoded together.
| Ratio | BF16 median TTFT | BF16 P99 ITL | FP8 median TTFT | FP8 P99 ITL |
|---|---|---|---|---|
| 1.0 | 1,996 ms | 82 ms | 1,526 ms | 55 ms |
| 0.5 | 364 ms | 396 ms | 130 ms | 95 ms |
| 0.0 | 291 ms | 300 ms | 129 ms | 95 ms |
We measured a first token 6.9 times slower with fixed lengths on BF16, and 11.8 times slower on FP8. The FP8 runs at the two ratios had median clocks of 1,185 and 2,040 MHz. So part of the FP8 factor is the clock. Mixed lengths sent fewer tokens. In seed 1 they sent 17,870 input tokens at a ratio of 0.0, against 32,768 at 1.0. So part of the gap is less work. Raw runs
The cache can explain another part. In each seed, the run at 1.0 came first and started with an empty cache. The runs at 0.5 and 0.0 came after it. Each of their prompts is the first part of a prompt from the run at 1.0. The BF16 pool of 24,094 tokens held only part of the 32,768 tokens of that run. The FP8 pool of 142,369 tokens could hold all of them.
Less work and the cache do not explain the other half of the result. With mixed lengths, P99 ITL rose from 82 to 300 ms. New prompts arrived one by one, and each prefill stopped the running decodes. With fixed lengths, prefill happened only between waves.
The GB10 gave the same shape with Qwen3-30B-A3B, three seeds per point. With fixed lengths, the BF16 median TTFT was 1,650 ms and P99 ITL 169 ms. With mixed lengths, they were 320 ms and 230 ms. FP8 went from 1,050 ms and 92 ms to 188 ms and 127 ms. Two GPUs and two models show the same trade, so on both of our machines it came from the workload, not from the hardware.
The two settings measure two different servers. Fixed lengths measure bursts: a slow first token and smooth tokens after it. Mixed lengths measure steady traffic: a fast first token and stalls in the stream. Keep --random-range-ratio 1.0 when you compare two builds, because it repeats exactly. Before you set a latency target from it, run your real length distribution too.
Reset the prefix cache between runs
The prefix cache keeps the KV of earlier prompts after a run ends. It changes two things in the next run: the speed, and sometimes the greedy output, as section 4.6 shows.
To see the size of the speed effect, we ran one load four times in a row with the same seed. We used Qwen/Qwen3-0.6B, 64 prompts at a cap of 16, 512 tokens in and 128 out. This was on the second GPU of our L4 node, which its owner shares and which had no clock lock. So trust the ratios, not the times.
engine fresh repeat, not flushed repeat after a flush repeat, not flushed
SGLang 0.6B 394 82.5 289 77
…The repeat without a flush read a median TTFT about 4.8 times lower than the fresh run. After a flush, the TTFT went back near the fresh run. The time per token changed by less than 15 percent.
Use this protocol for every run that you compare:
- Start each run with an empty cache. Pass
--flush-cachetosglang.benchmark.serving, which calls/flush_cacheafter the warm-up request. You can also callPOST /flush_cacheyourself, or restart the server. - Check that the flush ran. The server flushes only when no request runs or waits. Otherwise the route answers with HTTP 400, and the log says
Cache not flushed because there are pending requests. - Use a new
--seedfor each run, so that the client sends new prompts. - Record the cached tokens. Read
sglang:cached_tokens_totalfrom/metricsbefore and after the run. With--enable-cache-report, each OpenAI-style response also givesusage.prompt_tokens_details.cached_tokens. - Write the cache setting and the cached tokens next to the result.
Our kit and our sweeps did not follow this protocol. Only the first run of each seed on each server started with an empty cache. The later TTFT numbers on this page can be too low, most of all on the GB10, whose pool held every prompt we sent. The time per token is less exposed, because a cache hit removes prefill work and leaves the decode work the same.
Goodput finds the knee that throughput hides
On the GB10, BF16 throughput still rises at a cap of 64, because the KV pool holds 234,600 tokens. A throughput curve with no knee does not tell you where to stop. A latency target does.
Goodput: the number of requests per second that finish inside the latency target. Our summary script counts a request when its first token comes in under 1 s and its mean time per token is under 100 ms.
| Cap | BF16 goodput | BF16 median TPOT | FP8 goodput | FP8 median TPOT |
|---|---|---|---|---|
| 4 | 0.44 req/s | 71.01 ms | 0.80 req/s | 38.60 ms |
| 8 | 0, and up to 0.04 in one seed | 102.21 ms | 1.07 req/s | 54.96 ms |
| 16 | 0 | 154.24 ms | 1.10 req/s | 81.90 ms |
| 32 | 0 | 201.91 ms | 0 | 104.12 ms |
BF16 goodput is highest at a cap of 4. From a cap of 8, the median request takes longer than 100 ms per token, so goodput is 0. Throughput at that cap is 74.11 tok/s and still rising. FP8 holds the target up to a cap of 16. Our position: choose the cap from goodput at your own target, and use the throughput curve only to explain it.
A cap is a closed loop. Each client waits for its answer before it sends the next request, so the server can never receive more work than it finishes. Real users do not wait for each other. --request-rate sends requests at Poisson arrival times instead, and the queue grows when the server is slower than the arrivals. We ran the same model at 0.5 to 16 requests per second, three seeds each.
We measured this on the GB10. At 0.5 requests per second, BF16 already had a median time per token of 177.5 ms. The arrivals overlap: at 0.52 requests per second, each 128 tokens long at 177.5 ms per token, about 12 requests share each decode step. Only 0.07 requests per second met the target. FP8 met the target for every request up to 1 per second, then fell to 0.17 at 2. Raw runs
At 16 per second, BF16 completed 3.88 requests per second, and its P99 first token took 55,640.4 ms. FP8 completed 8.26. The GPU clock stayed at 2,496 MHz up to 4 requests per second. At 16, the GPU reached 89 C and spent 7.3 percent of the samples in thermal slowdown. The last BF16 point measures a hot GPU as well as a full queue.
We ran the same open loop on one 24 GB L4 with Qwen3-8B, with the cool-down to 72°C before each run.
We measured a different shape on the smaller card. Both servers met the target for every request up to 1 per second. BF16 held 0.88 within the target at 2 offered and none from 4. FP8 held 3.18 within the target at 4 offered, three times the best BF16 point. The FP8 server also had a pool of 142,369 tokens against 24,094 for BF16. From 4 offered, the BF16 pool was the limit. Raw runs
Past its peak, BF16 completed fewer requests as we offered more: 2.01 per second at 4 offered, 1.91 at 8, and 1.62 at 16. The telemetry shows why. The median SM clock fell from 1,320 MHz at 4 offered to 465 MHz at 16. At 16, 70 percent of the samples showed thermal slowdown. On our passively cooled L4, overload cost throughput as well as latency.
Check the client at high rates
sglang.benchmark.serving sends every request from one Python process with asyncio. A 2026 study of benchmark clients found that such a client adds its own queue at high request rates. The client then reports a TTFT and a TPOT that are higher than what the server did. The study uses a client that runs in several processes instead.
We did not measure this effect. Our open loop stopped at 16 requests per second, and we did not record the CPU use of the client. Before you trust a TTFT at a high rate, compare one client process with two processes that each send half the rate.
Compare two clients on one server
Our sweep tables came from sglang.benchmark.serving at temperature 0, its default. Another client can read a different number from the same server. We ran three clients against one vLLM 0.31.0 server with Qwen/Qwen3-0.6B on 2026-10-23. They were this client with --backend vllm, vllm bench serve, and its Rust version. The GPU was the shared second L4 of our node. Its clock was throttled, but it stayed at 420 to 495 MHz for every run.
users temperature SGLang client vllm bench vllm bench, Rust
1 0 154, 164 149, 150 144, 144
…
16 0 1,077, 1,045 1,033, 1,027 1,088, 1,038
…
64 0 1,688, 1,838 1,624, 1,667 1,674, 1,789- Our client read a median TTFT 3 to 10 percent higher than
vllm bench serve. At 16 and 64 users, it read an output throughput 2 to 8 percent lower. At one user, one of its rounds read a higher throughput than every other round, so we give no throughput gap there. - The Python and the Rust versions of
vllm bench serveagreed within the noise. - The clients send different prompt tokens from their random datasets, so part of a small gap can come from the prompts.
- Temperature 0.7 raised the median TPOT over temperature 0. It was 10 to 13 percent higher at one user, and 3 to 6 percent higher at 16 and 64 users.
So a gap of a few percent between two published numbers can come from the client alone. Report the client and the temperature with every result.
Record the GPU clock with every run
Our first sweep on an NVIDIA L4 reported that CUDA graphs did nothing. The median time per token at a cap of 1 was 103.4 ms with graphs and 103.4 ms without. The three seeds at that cap gave from 10.0 to 14.9 tok/s, a spread of half the median. Then we read nvidia-smi during the sweep.
index, temperature.gpu, power.draw [W], power.limit [W], clocks.current.sm [MHz], clocks.max.sm [MHz], clocks_event_reasons.active, clocks_event_reasons.sw_thermal_slowdown, clocks_event_reasons.hw_thermal_slowdown, clocks_event_reasons.sw_power_cap, utilization.gpu [%]
0, 87, 58.36 W, 72.00 W, 360 MHz, 2040 MHz, 0x0000000000000020, Active, Not Active, Not Active, 100 %The GPU was at 87 C with software thermal slowdown active, and its SM clock was 360 MHz of 2040. The L4 is a 72 W card with passive cooling, and the second card in the same chassis ran other work at the same time. We had measured a hot GPU, and the server under it was not the cause.
Now the sweep script samples nvidia-smi once a second into a .gpu.csv file beside each run. Before each run it waits up to 900 s for the GPU to cool below the --cool limit, 65 C by default. The L4 in this chassis runs warm, so we ran with --cool 72. The summary script adds the median SM clock, the highest temperature, and the share of samples with a thermal slowdown bit to each point. The GB10 load sweep in figure 5.1c ran before we added the sampler, so its tight bands are the only check on it.
We ran the L4 sweep again with the same command and the cool-down. The throttled sweep is the rose line in the next figure.
We measured the difference on the L4. At a cap of 32, the cooled sweep gave 270.11 tok/s and the hot sweep gave 194.16 tok/s. At a cap of 1, the median time per token was 60.16 ms against 103.38 ms. Raw runs
The cooled runs are not at full speed either. Their median SM clock was 1,080 to 1,515 MHz of 2,040. At caps of 1 and 64, in the worst seed, 41 to 49 percent of the samples still had the thermal bit set. The cool-down removes the worst error, and the recorded clock tells you how much is left.
Our position: a benchmark without the clock and the temperature of each run is not evidence. Read the clock first, then the throughput.
Our position
Report the highest concurrency that still meets your latency target, and report its throughput together with p50 and p99 TTFT and TPOT. "255 tok/s at a cap of 8, with a median first token of 0.79 s" is a result. "255 tok/s" is a slogan.
Then enforce the knee outside the engine. The engine's own limit is set from memory, and memory runs out long after latency is unacceptable. Put the cap in your client, your gateway, or --max-running-requests, and size it from the sweep.
The incident: a hand-written script
Issue #3196 reported 13 tok/s for DeepSeek V3 on eight H200 GPUs, against 60 tok/s from the DeepSeek API. Another user reached 33 tok/s on two H100 nodes. The measuring script counted words split on spaces and included the first-token time in the rate. A word is not a token, and TTFT is not decode time, so the script reported less than the server did. The fix was to measure with the benchmark client, which counts tokens and keeps TTFT and TPOT apart.
The /metrics endpoint
Gauges report one instant, and the cache hit rate gauge reports one log interval, so you alert on counters and histograms over a time window.
Your dashboard says the prefix cache hit rate is 94 percent. Over the same run, the server computed 104,057 prompt tokens and took 182,079 from the cache, a real hit rate of 64 percent. Both numbers came from one scrape of the server in our capture. One is a gauge that remembers the last prefill batch it logged. The other is a pair of counters that remember everything.
When you finish this section, you can turn the endpoint on and tell a gauge from a counter and a histogram. You can compute a hit rate that means something, and write six alerts for a server past its knee.
Turn it on first
The endpoint is off by default. The field enable_metrics defaults to False at v0.5.22, and without --enable-metrics the server does not mount the path /metrics at all. Our capture server started with the flag, as section 5.1 shows. After the default experiments, it exported 81 metric families in 603 sample lines that start with sglang:.
Our position: start every server with --enable-metrics, including the one on your laptop. We did not measure its cost, and we expect it to be small next to a decode step. The cost of an incident without history is the whole investigation.
Three kinds of series
Gauge: a value the scheduler overwrites on each log interval, such as the number of running requests. A scrape sees the latest value only. Counter: a total that only grows, such as the number of prompt tokens processed. You read it with a rate over a window. Histogram: a set of counters, one per bucket, that counts how many requests fell under each limit. You read percentiles from it with a rate over a window.
The snapshot below was taken when the server was idle, after all default experiments.
sglang:num_running_reqs{…} 0.0
sglang:num_queue_reqs{…} 0.0
sglang:gen_throughput{…} 0.0
sglang:token_usage{…} 0.0
sglang:cache_hit_rate{…} 0.9418739997090062
sglang:num_retracted_reqs{…} 0.0Five gauges show an idle server. One does not. The cache hit rate still holds the value from the last prefill batch that ran, which was the shared-prefix benchmark. A gauge answers "what happened in the last interval", and when nothing happens, some gauges decay and some keep their last value.
The cache hit rate, two ways
The scheduler computes the gauge from the prefill tokens of one log interval. The value is hit tokens divided by hit tokens plus computed tokens. The counters below add up the same two quantities since the server started.
# HELP sglang:prefill_effective_tokens_total Effective prefill tokens with retracted-request re-counts excluded, updated on each log interval. mode: device_hit, host_hit, storage_hit, input. Windowed prefix cache hit rate = rate(sum of *_hit) / rate(sum of all modes); per-tier rate uses a single *_hit mode in the numerator.
sglang:prefill_effective_tokens_total{…mode="input"…} 104057.0
sglang:prefill_effective_tokens_total{…mode="device_hit"…} 182079.0
sglang:prefill_effective_tokens_total{…mode="host_hit"…} 0.0
sglang:prefill_effective_tokens_total{…mode="storage_hit"…} 0.0The HELP text says that re-counted tokens are excluded. In the code, that is true only for the input mode. The three hit modes add the raw hit counts, so after a retraction they can count the same tokens twice. Our run had no retractions, so the numbers below are exact.
From the counters, the hit rate over the whole run is 182,079 divided by 286,136, which is 0.636. The gauge says 0.942. Both are correct, and they answer different questions. The gauge describes the shared-prefix benchmark at the end of the run. The counters describe all of it, including the random-prompt benchmarks that could hit nothing.
The HELP text of the counter gives the formula for a windowed rate. In PromQL it reads like this:
sum(rate(sglang:prefill_effective_tokens_total{mode=~".*_hit"}[5m]))
/ sum(rate(sglang:prefill_effective_tokens_total[5m]))The server with --disable-radix-cache reported a gauge of 0.0 in its own snapshot, so the gauge does reach zero when nothing can hit. A low value from the counters is the signal section 3.4 teaches you to act on.
What to alert on
These six series cover the failures in this manual. Every name below appears in our capture.
| Series | Type | Alert when | Why |
|---|---|---|---|
time_to_first_token_seconds | histogram | p99 over 5 min is above your target | users wait for the first token before anything else |
inter_token_latency_seconds | histogram | p99 over 5 min is above your target | prefill batches stall running decodes, as the 1,948 ms gap in section 5.1 showed |
num_queue_reqs | gauge | above 0 for several minutes | the server is past its knee, and new requests only wait |
token_usage | gauge | near 1.0 for several minutes | the KV pool is full, and retraction comes next |
num_retracted_requests_total | counter | rate above about 1 per minute | the scheduler threw out requests and computes them again, see section 2.3 |
prefill_effective_tokens_total | counter | windowed hit rate drops after a deploy | a prompt change broke the prefix, see section 3.4 |
The p99 of a histogram comes from its buckets:
histogram_quantile(0.99,
sum by (le) (rate(sglang:time_to_first_token_seconds_bucket[5m])))We measured both histograms in the same snapshot. The queue time histogram has a sum of 251.7 s over 266 requests, a mean of 0.95 s. The streaming TTFT histogram has a sum of 612.7 s over 261 requests, a mean of 2.35 s. The two series count different requests, so their ratio is an estimate, not a measured share. It suggests that queueing was a large part of the first-token time on this Mac. For an exact share, compare queue time and TTFT of the same requests. Raw runs
sglang:queue_time_seconds_sum{…} 251.74525608913973
sglang:queue_time_seconds_count{…} 266.0
sglang:time_to_first_token_seconds_sum{…is_streaming="true"…} 612.7282021734864
sglang:time_to_first_token_seconds_count{…is_streaming="true"…} 261.0Our position
Alert on latency and activity with histogram percentiles and counter rates over a window. Alert on state with a gauge only when the condition lasts, such as num_queue_reqs above 0 or token_usage near 1.0 for several minutes. A single gauge scrape describes the last few seconds. When a gauge and a counter disagree, as the cache hit rate did here, the counter is the one to trust.
Read every new metric in its HELP text and in the code before you build on it. Not every gauge works.
The incidents
A gauge that never moves. The scheduler code at v0.5.22 carries a comment that sglang:utilization stays at 0 since a regression it links to #22713. Our capture agrees: the gauge reads 0.0 after a run that kept the server busy for minutes. A dashboard panel built on it would show an idle fleet during an outage.
A health probe that piled up work. Issue #35884 reported that a timed-out /health call did not cancel its request in the scheduler. Each failed probe left one more orphaned request behind, and under load the probes added to the load they were trying to detect. A related report, issue #22511, shows the message "health check failed" under high load on a large model. Watch the queue and latency series, and treat a failing probe as one more symptom.
Reading other people's SGLang benchmarks
A published SGLang result depends on its version, workload, memory budget, graph ceiling, and kernels, so you read those five before you read the number.
The most repeated SGLang number on the web is "29 percent faster than vLLM": 16,215 tokens per second against 12,553. It comes from one offline test by the analyst firm AIMultiple, updated 2026-01-25. That page lists SGLang as "v0.2.3" next to vLLM 0.11.0, a gap of about two years of releases. At least five later posts repeat the pair, some under the names of other companies. None of them reran the test.
When you finish this section, you can take a published SGLang benchmark apart into its five inputs. You can decide whether it applies to you and name the mechanism behind it. You can also say where the independent tests agree, which is a shorter list than the headlines suggest.
The five inputs behind every result
A benchmark result is a function of five inputs. Most disagreements between published reports trace back to one of them.
- Workload shape. Input length, output length, concurrency, and the share of the prompt that repeats. The radix cache helps only when prefixes repeat. Long inputs stress prefill. High concurrency stresses the scheduler and the KV pool.
- Memory budget. SGLang computes
--mem-fraction-staticfrom the GPU when you leave it unset. vLLM uses--gpu-memory-utilization 0.9. A test that sets one and not the other compares two different KV pools. - CUDA graph ceiling. The decode step replays a captured CUDA graph only up to a batch size limit. Above it, decode runs eager, one kernel launch at a time. Section 4.1 explains the mechanism.
- Kernel path. The attention backend, the MoE kernel, and the quantization format. Several reports below were decided by a kernel that did or did not exist for one GPU.
- Version and date. One analyst measured the same model on the same AMD GPU at 20.4 and then 2,256 tokens per second per GPU, 26 days apart.
The code sets the third input from GPU memory at startup. Take an 80 GB H100 with tensor parallel size below 4. The default decode graph limit is 256, and the chunked prefill size is 8,192. On a 32 GB card the limit is 48, raised from 24 on 2026-09-04. The code comment on that change says the old cap made throughput at high concurrency fall far behind vLLM.
Six questions before you trust a number
- Is the SGLang version stated? Without it, the result describes an unknown build.
- Does the workload match yours? Unique prompts say nothing about a chat server with a long shared system prompt.
- Were the memory budgets matched across engines?
- Did the concurrency pass the decode graph limit? If yes, the test measured eager decode.
- Are the flags mapped correctly? The same idea has different flag names in each engine.
- Who paid for the test? A GPU cloud, a hardware vendor, a competitor, or the SGLang team each has a reason to like one answer.
Where independent tests agree
These reports come from people outside the SGLang team. Each row names the mechanism from earlier sections that explains it.
| Finding | Field reports | Mechanism |
|---|---|---|
| Dense models with unique prompts: a tie | Spheron, SGLang 0.5.9, Llama 3.3 70B FP8 on one H100: 1,920 against 1,850 tok/s at 50 users. Modal: about 17 queries per second for both on 8 H100s. Varad More: 7B to 9B models within 3 percent on an A10G | both engines now use the same kernel families, paged KV, and continuous batching |
| Repeated prefixes: SGLang wins, by less than the folklore | Steve Rawlinson, SGLang 0.5.6 on 2 H100s: first token 583 ms against 2,141 ms at one user. RunPod: 35.0 against 32.8 tok/s per stream on a cached 7k context. Varad More: SGLang ahead on 10 of 16 models by 20 to 40 ms | the radix cache, see section 3.3 |
| Long prompts: slower first token, faster tokens after it | Jarvislabs, 16k-token prompts on one H100 at 60 users: first token 10,802 ms against 1,874 ms, time per token 63 to 81 ms against 97 to 120 ms | chunked prefill at 8,192 tokens splits a long prompt and protects running decodes |
| Very high load with defaults: decode latency collapses | Jarvislabs, no concurrency cap: mean ITL 100.92 ms against 28.84 ms | probably decode past the graph limit of 256. This is our hypothesis, not theirs |
| DeepSeek-class MoE on many GPUs: SGLang is the reference | SemiAnalysis InferenceMAX chose SGLang as the default engine for DeepSeek R1. Crusoe's audited MLPerf v6.1 result used SGLang 0.5.15.post1 on 512 MI355X GPUs | attention data parallel and expert parallel, see section 6.2 |
| Speculative decoding: helps large GPUs, hurts small ones | InferenceX, GLM-5 with MTP on B200 at 4 users: time per token 18.43 ms down to 9.92 ms. Varad More on an A10G: 7 to 28 percent slower | draft cost against acceptance, see section 4.4 |
The links: Spheron, Modal, Varad More, Steve Rawlinson, RunPod, Jarvislabs, SemiAnalysis, Crusoe, and InferenceX.
Read the caveats with the numbers. Rawlinson left SGLang memory at its default and vLLM at 0.9, so the two KV pools differed. Jarvislabs did not record either engine version. Spheron, RunPod, Modal, and Jarvislabs sell GPU time, which is a reason to run tests and no reason to favor one engine. The Crusoe result is the only one here that passed an external audit. Its p99 time per token was 79.98 ms against a limit of 80.
Fragile on new hardware
The same reports show one more pattern. A Blackwell workstation card ran SGLang only with --disable-cuda-graph, according to joshua8.ai. A mixed cluster crashed when an older card joined, because the FP4 path required compute capability 10.0. Pivot News summarized that community post. The fast paths are written per GPU generation, and the paths for other GPUs are fewer. On new hardware, expect the first SGLang release to be slow or broken, and measure again every week.
What our own machines showed
Field reports tell you which mechanism to test. We tested them on a DGX Spark with a GB10 and on a machine with two 24 GB L4s. Each row below links to the section with the listings, the seeds, and the chart.
| Where | What we ran | Result | Mechanism |
|---|---|---|---|
| L4 | 4,096-token shared prompt, cache on and off | median TTFT 479 ms against 14,706 ms, 4.3 times the throughput, with the cache-off run at 930 MHz, under our clock floor, section 3.3 | the radix cache |
| L4 | FP8 weights and KV against BF16 at 64 users | 736 against 251 tok/s, a pool of 142,369 tokens against 24,094, section 4.3 | more KV per GB |
| GB10 | EAGLE-3 on Qwen3-30B-A3B | time per token 1.56 to 1.89 times shorter, largest at 16 to 64 users, section 4.4 | MoE verify reuses the expert weights it read |
| L4 | EAGLE-3 on dense Qwen3-8B | 2.37 times the throughput at one user, with the default at a 19 percent lower clock, and 1.00 at 32, section 4.4 | the draft took 59 percent of the pool |
| L4 pair | --dp-size 2 with one shared card | 42 against 251 tok/s at 64 users, with the pair at 675 MHz, under our clock floor, section 6.1 | round robin fed a copy with an eighth of the pool |
| L4 | SGLang 0.5.22 against vLLM 0.31.0, same pool, 64 users | 257 against 241 tok/s, P99 ITL 114 against 1,363 ms, median TTFT 18,356 against 10,953 ms, below | two different admission choices at a full pool |
| L4 | the same pair on a 4,096-token shared prompt | 88.4 against 86.8 tok/s, median TTFT 474 against 375 ms, below | two prefix caches that both hit |
| L4 | the same pair at 4 requests per second, Poisson arrivals | 257.5 against 286.6 tok/s, P99 TPOT 127 against 187 ms, below | the same admission choice under a fixed rate |
| L4 | the same pair with mixed prompt lengths at 16 users | 159.6 against 169.6 tok/s, P99 ITL 363 against 191 ms, below | how each engine mixes prefill into the stream |
| L4 pair | --tp-size 2 with one shared card | refused at startup, section 6.1 | the memory balance check |
| L4 pair | prefill and decode split over TCP | every request after minute three came back empty with HTTP 200, section 6.3 | the transfer session failed and did not recover |
Most rows follow one pattern. A mechanism wins by a large factor when it removes repeated work, in either engine. Examples are the prefill of a shared prompt and the bytes of each cached token. It loses when a feature spends memory that the batch needs, or when two parts of a deployment are not the same size. None of the losses at runtime printed an error that a dashboard would show. Two of them looked like success in the benchmark summary.
SGLang against vLLM on the same L4
Every field report above compares two engines that someone else configured. We ran our own pair on one L4 with Qwen/Qwen3-8B and the closed-loop sweep of section 5.1. We made three choices so that only the engine differed.
- The same KV pool. The vLLM server got
--num-gpu-blocks-override 1506, which is 1,506 blocks of 16 tokens. SGLang sized 24,094 tokens for itself on the same card. - The same card state. Both engines ran in one session on one GPU, and every run started at 72 C or below. A run with a median SM clock under 1,000 MHz was set aside and repeated, up to three times.
- No accidental handicap. The vLLM server got
--max-model-len 8192, which every request fits, andVLLM_USE_FLASHINFER_SAMPLER=0, because its FlashInfer sampler did not compile in our install. The benchmark is greedy, so the sampler does not change the output.
[2026-10-17 18:27:40] KV Cache is allocated. dtype: torch.bfloat16, #tokens: 24094, K size: 1.65 GB, V size: 1.65 GB
[2026-10-17 20:12:04] Decode batch, #running-req: 37, #token: 22162, token usage: 0.92, cuda graph: True, gen throughput (token/s): 432.55, #queue-req: 27INFO 10-17 20:13:17 [kv_cache_utils.py:2464] GPU KV cache size: 24,096 tokens, Maximum concurrency for 8,192 tokens per request: 2.94x
INFO 10-17 22:35:43 [loggers.py:320] Engine 000: Avg prompt throughput: 460.3 tokens/s, Avg generation throughput: 323.6 tokens/s, Running: 40 reqs, Waiting: 11 reqs, GPU KV cache usage: 99.5%, Prefix cache hit rate: 8.7%| Concurrency | Output tok/s, SGLang / vLLM | Median TTFT, SGLang / vLLM | P99 ITL, SGLang / vLLM | Median SM clock, SGLang / vLLM |
|---|---|---|---|---|
| 1 | 13.84 / 13.51 | 185 / 192 ms | 104 / 105 ms | 1,290 / 1,290 MHz |
| 8 | 112.46 / 112.79 | 170 / 253 ms | 71 / 68 ms | 1,485 / 1,470 MHz |
| 16 | 201.13 / 200.90 | 212 / 289 ms | 81 / 80 ms | 1,470 / 1,425 MHz |
| 32 | 271.28 / 273.93 | 2,871 / 1,813 ms | 102 / 619 ms | 1,320 / 1,275 MHz |
| 64 | 256.62 / 241.39 | 18,356 / 10,953 ms | 114 / 1,363 ms | 1,215 / 1,013 MHz |
We measured a tie in throughput. Up to 32 users, the two engines were within 3 percent of each other, and time per token was within 6 percent. At 64 users the median time per token was 106 ms on SGLang and 129 ms on vLLM. Below the point where the pool fills, SGLang gave the first token sooner, 170 against 253 ms at 8 users. Raw runs
Above that point, the engines made different choices, and the stats lines show both. SGLang ran 37 requests and kept 27 waiting, with the pool 92 percent full. The vLLM server ran 40 requests and kept 11 waiting. It filled 99.5 percent of its pool while it prefilled new prompts at 460 tokens per second.
The vLLM server started more requests, so their first token came sooner. Each new prefill then shared the step with the running decodes, so the streams stalled. At 64 users the P99 inter-token gap was 1,363 ms on vLLM and 114 ms on SGLang.
The clock caveat belongs with the last row. Even after three tries, the vLLM runs at 64 users had a median clock of 1,013 MHz against 1,215 MHz for SGLang. So part of the throughput gap at 64 can be the card. The 12-times gap in inter-token latency is too large for a 17 percent clock difference.
The same pair on shared prompts
We then ran the prefix sweep of section 3.3 on the same pair, with the same pools and the same cool-down rule. Each run sent 64 prompts in 4 groups of 16, at 8 users. The prompts in a group shared a system prompt of 0 to 4,096 tokens, then had a 128-token question and 64 tokens of output. SGLang used its radix cache. The vLLM server used its prefix caching, which is on by default at 0.31.0.
INFO 10-17 23:37:11 [kv_cache_utils.py:2464] GPU KV cache size: 24,096 tokens, Maximum concurrency for 8,192 tokens per request: 2.94x
INFO 10-18 00:43:16 [loggers.py:320] Engine 000: Avg prompt throughput: 231.0 tokens/s, Avg generation throughput: 93.6 tokens/s, Running: 8 reqs, Waiting: 0 reqs, GPU KV cache usage: 77.2%, Prefix cache hit rate: 87.2%The SGLang log shows the same thing in its own words. In one prefill batch at 4,096 shared tokens, 12,952 tokens came from the cache and 406 were new.
| Shared prompt tokens | Output tok/s, SGLang / vLLM | Median TTFT, SGLang / vLLM | P99 TTFT, SGLang / vLLM |
|---|---|---|---|
| 0 | 113.5 / 113.8 | 354 / 408 ms | 483 / 485 ms |
| 256 | 110.9 / 111.5 | 470 / 488 ms | 856 / 616 ms |
| 1,024 | 105.7 / 106.0 | 466 / 396 ms | 1,887 / 1,303 ms |
| 2,048 | 100.4 / 100.2 | 441 / 410 ms | 2,317 / 1,767 ms |
| 4,096 | 88.4 / 86.8 | 474 / 375 ms | 4,275 / 4,019 ms |
We measured a tie on throughput, within 2 percent at every shared length. The median TTFT of both engines stayed between 354 and 488 ms. At 0 and 256 shared tokens, SGLang gave the first token sooner, outside the seed spread: 354 against 408 ms and 470 against 488 ms. From 1,024 tokens up, the seed ranges overlapped. Raw runs
vLLM leaned ahead on the tail. Its P99 TTFT was lower from 256 shared tokens up, 1,303 against 1,887 ms at 1,024. SGLang had the shorter time per token at 4,096, 75.6 against 80.8 ms. The median SM clock of every run was 1,395 MHz or higher.
The size of the result is in the third line. With the cache off, a separate SGLang run needed 14,706 ms for the median first token at 4,096 shared tokens. That card ran under our clock floor. Both cached runs stayed under 500 ms. The difference between the two caches was about 100 ms.
We then ran the vLLM server with --no-enable-prefix-caching, with the same pool and the same sweep. Its log shows the cache off and every prompt token prefilled again.
INFO 10-21 06:20:24 [kv_cache_utils.py:2464] GPU KV cache size: 24,096 tokens, Maximum concurrency for 8,192 tokens per request: 2.94x
INFO 10-21 08:07:49 [loggers.py:320] Engine 000: Avg prompt throughput: 1607.0 tokens/s, Avg generation throughput: 6.4 tokens/s, Running: 8 reqs, Waiting: 0 reqs, GPU KV cache usage: 76.7%| Shared prompt tokens | Median TTFT, cache on / off, SGLang | Median TTFT, cache on / off, vLLM | Output tok/s, cache off, SGLang / vLLM |
|---|---|---|---|
| 256 | 470 / 985 ms | 488 / 753 ms | 99.4 / 99.1 |
| 1,024 | 466 / 2,202 ms | 396 / 1,213 ms | 70.2 / 70.9 |
| 4,096 | 474 / 14,706 ms | 375 / 13,353 ms | 20.8 / 19.6 |
We measured the same size of gain in both engines. At 4,096 shared tokens, the cache cut the median first token about 31 times on SGLang and 36 times on vLLM. It gave 4.2 times the output on SGLang and 4.4 times on vLLM. Without a cache, the two engines tied on throughput within 7 percent. Raw runs
Without a cache, the vLLM server gave the first token sooner at 256 to 2,048 shared tokens. Its SGLang counterpart ran on another day. The vLLM run with the cache off was on 2026-10-21, four days after the vLLM run with the cache on. The runs at 4,096 shared tokens stayed under our clock floor after three tries, at 930 and 675 MHz. Read that row for its size, not its exact value.
The same pair at a fixed arrival rate
A closed loop sends a new request only when one comes back, so the engine sets the pace. Production traffic does not wait for the engine. We ran the rate sweep of section 5.1 on the same pair, with the same pools and the same rules for heat and clock. Requests arrived at a Poisson rate from 0.5 to 16 per second, with 512 input and 128 output tokens. Each run sent at least 32 prompts, or 30 seconds of arrivals.
[2026-10-18 00:43:57] KV Cache is allocated. dtype: torch.bfloat16, #tokens: 24094, K size: 1.65 GB, V size: 1.65 GB
[2026-10-18 03:13:55] Decode batch, #running-req: 37, #token: 22424, token usage: 0.93, cuda graph: True, gen throughput (token/s): 370.33, #queue-req: 71INFO 10-18 03:15:35 [kv_cache_utils.py:2464] GPU KV cache size: 24,096 tokens, Maximum concurrency for 8,192 tokens per request: 2.94x
INFO 10-18 06:10:22 [loggers.py:320] Engine 000: Avg prompt throughput: 1326.7 tokens/s, Avg generation throughput: 158.4 tokens/s, Running: 43 reqs, Waiting: 30 reqs, GPU KV cache usage: 99.7%, Prefix cache hit rate: 0.6%| Requests per second | Output tok/s, SGLang / vLLM | Median TTFT, SGLang / vLLM | Median TPOT, SGLang / vLLM | P99 TPOT, SGLang / vLLM | Median SM clock, SGLang / vLLM |
|---|---|---|---|---|---|
| 0.5 | 70.6 / 70.6 | 284 / 317 ms | 74.7 / 72.7 ms | 81 / 78 ms | 1,485 / 1,485 MHz |
| 1 | 123.3 / 123.6 | 166 / 180 ms | 74.0 / 68.2 ms | 76 / 69 ms | 1,500 / 1,485 MHz |
| 2 | 226.3 / 227.8 | 221 / 233 ms | 99.9 / 88.7 ms | 120 / 109 ms | 1,433 / 1,418 MHz |
| 4 | 257.5 / 286.6 | 9,575 / 8,304 ms | 115.1 / 126.9 ms | 127 / 187 ms | 1,350 / 1,245 MHz |
| 8 | 253.9 / 261.8 | 37,211 / 27,510 ms | 105.2 / 126.0 ms | 151 / 248 ms | 1,215 / 1,035 MHz |
| 16 | 218.2 / 205.8 | 97,542 / 94,322 ms | 115.2 / 185.2 ms | 189 / 322 ms | 600 / 450 MHz |
We measured a tie up to 2 requests per second. Both engines kept up with the arrivals, so throughput was within 1 percent. SGLang gave the first token sooner at 0.5 and 1 per second, outside the seed spread. The medians were 284 against 317 ms and 166 against 180 ms. vLLM had the shorter time per token. It was 68 against 74 ms at 1 per second, outside the spread, and 89 against 100 ms at 2. Raw runs
Goodput shows what that means for a target. We set the target at 1 s to the first token and 100 ms per token. At 2 requests per second, vLLM served a median of 1.36 requests per second within the target, and SGLang 0.88. The seed ranges overlapped, 1.09 to 1.44 against 0.54 to 1.18. The SGLang median time per token was 99.9 ms, on the line of the target.
From 4 requests per second, both engines fell behind the arrivals, and no request met the target. The stats lines show the same admission choice as in the closed loop. SGLang ran 37 requests with the pool 93 percent full. The vLLM server ran 43 requests and filled 99.7 percent of its pool.
At 4 per second, vLLM gave 286.6 against 257.5 tok/s, 11 percent more and outside the seed spread. Its median first token came at 8.3 against 9.6 s, but those seed ranges overlapped. The cost was the stream: its P99 time per token was 187 against 127 ms, outside the spread.
The clock does not explain the gap at 4. The vLLM runs had the lower median clock, 1,245 against 1,350 MHz. At 8 per second the throughput ranges overlapped. At 16 per second, every run of both engines stayed under 1,000 MHz after three tries, so we do not compare that row.
The same pair on waves
The last workload is the one from section 5.1 that makes requests arrive in waves. Each run sent 64 prompts of 512 tokens with 128 tokens of output, at a cap of 16 users. Only --random-range-ratio changed. At 1.0 every prompt has the same length, so requests finish together and their replacements arrive together. At 0.5 and 0.0 the lengths are mixed, so requests arrive one by one.
INFO 10-18 18:38:07 [kv_cache_utils.py:2464] GPU KV cache size: 24,096 tokens, Maximum concurrency for 8,192 tokens per request: 2.94x
INFO 10-18 19:14:22 [loggers.py:320] Engine 000: Avg prompt throughput: 960.0 tokens/s, Avg generation throughput: 187.3 tokens/s, Running: 16 reqs, Waiting: 0 reqs, GPU KV cache usage: 22.6%, Prefix cache hit rate: 8.5%| Length ratio | Output tok/s, SGLang / vLLM | Median TTFT, SGLang / vLLM | Median TPOT, SGLang / vLLM | P99 ITL, SGLang / vLLM |
|---|---|---|---|---|
| 1.0, fixed lengths | 182.3 / 181.7 | 1,775 / 1,499 ms | 74.7 / 76.8 ms | 81 / 502 ms |
| 0.5, mixed | 159.6 / 169.6 | 325 / 353 ms | 87.8 / 81.4 ms | 363 / 191 ms |
| 0.0, mixed | 158.2 / 174.4 | 283 / 284 ms | 86.7 / 75.0 ms | 302 / 202 ms |
We measured a different winner for each traffic shape. With fixed lengths, the two engines tied on throughput. They made the same trade as at a full pool. The vLLM server gave the first token sooner, 1,499 against 1,775 ms, outside the seed spread. SGLang kept the stream smooth, with a P99 ITL of 81 against 502 ms. Raw runs
With mixed lengths, vLLM led. At a ratio of 0.5 it gave 169.6 against 159.6 tok/s, 6 percent more and outside the seed spread. Its median time per token was 81.4 against 87.8 ms, and its P99 ITL was 191 against 363 ms. At 0.0 the throughput ranges overlapped, and vLLM still had the lower time per token and the lower P99 ITL. Every median clock was 1,410 MHz or higher.
Our reading: when new prompts arrive one by one, each prefill shares a step with the running decodes. The vLLM server split that work so that the stream stalled less.
To test that reading, we ran SGLang again with --enable-mixed-chunk on 2026-10-21, with the same sweep and the same pool. This flag puts the running decodes into the prefill batch, so a new prompt does not stop the stream. The log shows one prefill of 514 tokens with 15 requests running in the same batch.
[2026-10-21 08:34:19] KV Cache is allocated. dtype: torch.bfloat16, #tokens: 24094, K size: 1.65 GB, V size: 1.65 GB
[2026-10-21 08:39:51] Decode batch, #running-req: 16, #token: 8889, token usage: 0.37, cuda graph: True, gen throughput (token/s): 231.46, #queue-req: 0
[2026-10-21 08:40:22] Prefill batch, #new-seq: 1, #new-token: 514, #cached-token: 0, token usage: 0.34, #running-req: 15, #queue-req: 0, #pending-token: 0, cuda graph: True, input throughput (token/s): 2569.89| Length ratio | Output tok/s, SGLang mixed chunk / vLLM | Median TPOT, SGLang mixed chunk / vLLM | P99 ITL, SGLang default / mixed chunk / vLLM |
|---|---|---|---|
| 1.0, fixed lengths | 182.3 / 181.7 | 73.1 / 76.8 ms | 81 / 203 / 502 ms |
| 0.5, mixed | 171.8 / 169.6 | 80.8 / 81.4 ms | 363 / 193 / 191 ms |
| 0.0, mixed | 171.9 / 174.4 | 76.8 / 75.0 ms | 302 / 196 / 202 ms |
We measured that the mixed chunk closed the gap. With mixed lengths, SGLang now tied vLLM on throughput, time per token, and P99 ITL, and every seed range overlapped. Against SGLang without the flag, the P99 ITL fell from 363 to 193 ms at 0.5 and from 302 to 196 ms at 0.0. The output rose by about 8 percent. Raw runs
The flag had a cost with fixed lengths. The median P99 ITL rose from 81 to 203 ms, and the three seeds spread from 83 to 349 ms. When a whole wave arrives together, the prefills now share steps with the decodes, so the stream loses the clean gaps that it had before. The vLLM server stayed worse there, at 502 ms.
The GB10 with Qwen3-30B-A3B, against a default run on the same day, moved in the same direction, but every change was inside the seed spread. With mixed lengths, the median P99 ITL went from 198 to 164 ms at 0.5 and from 214 to 202 ms at 0.0. With fixed lengths, it went from 159 to 210 ms. The flag also raised the median TTFT at 0.0 from 324 to 442 ms, outside the spread. Read the GB10 as a weak second sign, not a second proof.
One caveat applies. The SGLang default run on the L4 was from 2026-10-18, three days before the mixed-chunk run. The median clocks were 1,425 to 1,508 MHz with the flag and 1,440 to 1,485 MHz without it. The clock does not explain the gap.
This is one model, one GPU, and four workloads. It agrees with the field reports on the main point. On a dense model with unique prompts, the engines were within 3 percent on throughput in the closed loop up to 32 users. Under load they were up to 11 percent apart.
The sweep adds the part that a throughput chart hides. When the pool is full, you choose between a fast first token and a smooth stream, and the two engines chose differently by default. With mixed prompt lengths, vLLM was ahead by default on throughput and stream smoothness. SGLang still gave the first token at the same time or sooner. One SGLang flag, --enable-mixed-chunk, removed that lead.
To see why one GPU number differs from another, run the Inside an LLM Serving GPU machine. It reads its pool sizes, step times and throughputs from the same summaries as this section, for the L4 and the GB10. It says when a setting was not measured.
Our position
On our L4 with Qwen3-8B and unique prompts, the choice of engine was mostly not a throughput decision. It was a latency decision, and the shape of the traffic picked the winner. When requests arrived together, at a full pool or in waves, SGLang protected the stream and vLLM the first token. When prompts of mixed lengths arrive one by one, vLLM led by default on throughput and stream smoothness. With the mixed chunk on, SGLang tied it.
At 4 requests per second, past the full pool, vLLM also gave 11 percent more output on our L4. At 8 per second the seed ranges overlapped. Decide on model support, startup time, and the hardware you have, then measure your own length mix.
For repeated prefixes, check that the prefix cache is on, then measure. On our L4, with prefixes that fit the pool, the two caches tied under 500 ms. With the cache off, SGLang took 14,706 ms and vLLM 13,353 ms. The cache is the result, not the engine. For DeepSeek-class MoE models on many GPUs, start from SGLang, because that is where the field runs them.
Above all, do not import a result. Run the sweep from section 5.1 on your own workload. A published number tells you which mechanism to test, and nothing more.
The incidents
A memory result that was a flag error. In vLLM discussion #17221, a user first saw SGLang use 7 GB against vLLM's 21 GB on one A10. Then the user found that the flag that matches vLLM's --max-model-len is --context-length, not --max-total-tokens. With the right flag, memory use was about the same.
Advice that no longer parses. Field reports from 2026 advise raising the decode graph limit with --cuda-graph-max-bs. At v0.5.22 that flag is split into --cuda-graph-max-bs-decode and --cuda-graph-max-bs-prefill. The code rejects the old spelling. The argument parser of sglang serve stops with ambiguous option: --cuda-graph-max-bs could match --cuda-graph-max-bs-decode, --cuda-graph-max-bs-prefill. A tuning recipe is tied to its version as tightly as a benchmark is.
The recycled number. The 29 percent pair from the start of this section was criticized by DeepInfra on 2026-08-04 for its version gap. The author answered on 2026-10-14 that the result does not carry over to long context. The SGLang team made a larger claim in 2024: up to 3.1 times the throughput on Llama-70B. No independent report found in this research reproduced a gap of that size on a dense model with unique prompts.
One Server Becomes a Fleet
Split a model across GPUs only after one GPU is saturated, and split prefill from decode only after you measured that prefill hurts.
--tp-size, --dp-size, and --attn-dp-size
Tensor parallelism makes a model fit, data parallelism adds capacity, and attention data parallelism removes the KV copies that tensor parallelism makes for MLA models.
You have eight GPUs and one large model. The first command most people type is --tp-size 8, and the model loads. Then a teammate asks why the server holds so few tokens of KV cache for a DeepSeek model on 640 GB of memory. The answer is in how SGLang splits one model across GPUs, and in a flag whose meaning changed in v0.5.22.
When you finish this section, you can choose --tp-size, --dp-size, and --attn-dp-size for a model and a GPU count. You can also say which GPUs share which work, and read an old recipe that uses --enable-dp-attention.
One world, many ways to split it
Model world: the set of GPUs that together hold one copy of the model. SGLang builds it from two numbers only. The code raises an error when the world size is not tp_size times pp_size.
Tensor parallelism (TP): each layer's weight matrices are cut into --tp-size slices, one per GPU. Every layer then ends with a collective operation that joins the slices. Pipeline parallelism (PP): whole layers go to different GPUs in order, and --pp-size sets the number of stages.
Everything else splits that same world. Attention data parallelism, expert parallelism, and context parallelism do not add GPUs. They regroup the GPUs of the TP group differently for different layers.
Keep one mental model, and every later flag reads clearly. TP size is the number of GPUs in one model copy. The other widths are ways to cut that set.
The default of every one of these flags is 1. So a plain sglang serve uses one GPU, one scheduler, and one copy of the model.
Two meanings of "data parallel"
Data parallelism (DP): several complete copies of the model, each with its own requests and its own KV cache. --dp-size 2 with --tp-size 4 uses eight GPUs as two worlds of four. A data parallel controller process gives each new request to one of the copies. Its default method, auto, resolves to round_robin outside prefill-decode disaggregation.
Attention data parallelism: inside one TP group, the attention layers run data parallel while the feed-forward or expert layers stay split across all GPUs. Each attention group has its own scheduler, its own requests, and its own KV cache. --attn-dp-size 4 with --tp-size 8 gives four attention groups of two GPUs each.
Before v0.5.22, one flag carried both meanings. --dp-size counted model copies, unless --enable-dp-attention was also set, when it counted attention groups. Pull request #41818 gave the reason for the change in one sentence: "--dp-size means two different things... Every reader has to look at both flags to know which meaning it has." It was merged on 2026-09-30.
The code at v0.5.22 does three things with the old spelling:
| You pass | SGLang does |
|---|---|
--dp-size 8 --enable-dp-attention | rewrites it to --attn-dp-size 8 --dp-size 1 and prints a deprecation warning |
--attn-dp-size 8 | the new spelling, the same layout |
--dp-size 2 --attn-dp-size 4 | raises an error: replicas combined with attention data parallelism are not supported |
The warning names the new flag, and a comment in the code says to remove the old flag after 2026-12-31. Many DeepSeek recipes on the web still use the old spelling. They work today and stop working in a later release.
Why attention gets its own data parallel mode
DeepSeek models use multi-head latent attention (MLA). MLA stores one compressed latent vector per token and layer, which is one KV "head". Section 3.1 works through its size. Tensor parallelism cannot split one head across GPUs, so with --tp-size 8 every GPU stores the full latent cache for every token. Eight GPUs then hold eight copies of the same KV cache.
The SGLang team gave this reason when they added the mode in v0.4. With attention data parallelism, each attention group keeps only its own requests. The KV capacity of the server grows with the number of groups. The team reported up to 1.9 times more decode throughput for DeepSeek models, which is their claim.
For a dense model with grouped-query attention (GQA), the reason does not hold. GQA has several KV heads, so tensor parallelism already splits the cache without copies.
What attention data parallelism changes for you
Turning on attention data parallelism changes two other settings without a flag of their own:
chunked_prefill_sizeis divided by--attn-dp-size. A chunk size that you tuned on one GPU becomes smaller per attention group. The server log prints the old and the new value.schedule_conservativenessis multiplied by 0.3. The scheduler then admits new requests with a smaller reservation for future tokens. Section 2.3 explains that reservation.
The first change is the one that surprises people. A team that measured TTFT with --chunked-prefill-size 8192 and then added --attn-dp-size 8 now runs chunks of 1024 tokens. Long prompts take more scheduler steps to prefill.
Our position
Use tensor parallelism to make the model fit, and nothing more. Add capacity with data parallel copies, inside one server with --dp-size or as separate servers behind the gateway in section 6.4. Give every copy about the same pool. Our only pair had unequal pools, and it lost at every load. Use --attn-dp-size equal to --tp-size for MLA mixture-of-experts models such as DeepSeek and Kimi, and leave it at 1 for dense GQA models.
A field report supports the order. A student team tuned DeepSeek-R1 for a competition on H100 and H200 nodes. Plain --tp 16 gave about 5.9k tokens per second offline. Their best layout, TP4 with DP4, PP2, and attention data parallelism on one H200 node, gave 17,417 tokens per second. Use their numbers as one data point, because the write-up explains --mem-fraction-static incorrectly.
Ant Group made the same kind of choice in production. Their DeepSeek-R1 decode runs on two nodes with 16 attention groups and 16-way expert parallelism.
Several nodes
One model world can span machines. Three flags describe it:
| Flag | Default | Meaning |
|---|---|---|
--nnodes | 1 | the number of machines in one world |
--node-rank | 0 | this machine's position, from 0 |
--dist-init-addr | none | the host:port where all ranks meet to build their groups |
Only node 0 runs the tokenizer and the HTTP API. Other nodes run their scheduler processes, a small health server, and nothing else. Point your load balancer at node 0. Also keep adjacent ranks on the same machine, because TP groups are contiguous rank ranges and their collectives need the fast links inside one box.
A real incident shows how a network detail can stop all of this. A user ran attention data parallelism across nodes with an IPv6 address in --dist-init-addr (issue #19953). The server hung on its first message to the schedulers, and no request was ever served. The cause was a ZeroMQ socket that the controller bound without IPv6 turned on. A fix was proposed in the thread. We could not confirm that it was merged.
What to measure
Before you add GPUs, measure one copy with the benchmark in section 5.1. Watch sglang:num_queue_reqs and sglang:token_usage from section 5.2. A queue that grows while token usage stays low points to compute limits, and more copies help. Token usage near 1.0 points to KV memory limits, and a smaller KV cache per token helps first.
For attention data parallelism, watch sglang:dp_attention_token_imbalance_ratio. It reports the busiest group's tokens over the average, and 1.0 means balanced. Our /metrics capture lists it even on a single Mac, so your dashboards can include it before you need it.
What happened on two L4s
We had two NVIDIA L4 cards in one machine, and the second card also ran two small pods for another team. Each pod held 1,746 MiB. We started Qwen/Qwen3-8B with --tp-size 2, and the server stopped two seconds after NCCL started.
RuntimeError: The memory capacity is unbalanced. Some GPUs may be occupied by other processes. pre_model_load_memory=18.28375244140625, local_gpu_memory=21.70391845703125, local_gpu_memory * 0.9=19.533526611328124Before it loads weights, each rank measures its free memory, and the group keeps the smallest value. If that value is less than 90 percent of the local free memory, the server stops. The second card had 18.28 GB free against the 19.53 GB that the check required. No flag turns the check off at v0.5.22.
The check is right to stop. Each rank of a TP group holds the same share of weights and the same pool. The smallest card sets the size for all of them. On a shared machine, give a TP group whole GPUs. --dp-size 2 does not have this check, because each copy sizes its own pool, so it started on the same pair.
Data parallelism on the same pair lost
We expected two copies to serve about twice as much as one. They served less than one. We ran the closed-loop sweep of section 4.3 with three seeds per point. Each request had 512 input tokens and 128 output tokens. The first run used one L4, and the second used --dp-size 2 on both.
… DP0] Load weight end. elapsed=3.61 s, type=Qwen3ForCausalLM, avail mem=6.59 GB, mem usage=15.28 GB.
… DP1] Load weight end. elapsed=3.73 s, type=Qwen3ForCausalLM, avail mem=3.17 GB, mem usage=15.28 GB.
… DP0] KV Cache is allocated. dtype: torch.bfloat16, #tokens: 24094, K size: 1.65 GB, V size: 1.65 GB
… DP1] KV Cache is allocated. dtype: torch.bfloat16, #tokens: 2925, K size: 0.20 GB, V size: 0.20 GB
… DP1] Decode batch, #running-req: 4, #token: 2385, token usage: 0.82, cuda graph: True, gen throughput (token/s): 25.48, #queue-req: 59
… DP0] Decode batch, #running-req: 1, #token: 590, token usage: 0.02, cuda graph: True, gen throughput (token/s): 9.67, #queue-req: 0
… DP1] Decode batch, #running-req: 4, #token: 2545, token usage: 0.87, cuda graph: True, gen throughput (token/s): 25.79, #queue-req: 59
… DP0] Decode batch, #running-req: 3, #token: 1665, token usage: 0.07, cuda graph: True, gen throughput (token/s): 9.49, #queue-req: 0The second card had 3.17 GB free after the weights, against 6.59 GB on the first, because the two pods held the rest. We measured a pool of 2,925 tokens on that copy, an eighth of the first. Four requests of 640 tokens fill it.
The controller still sent every second request to that copy, because round_robin does not look at pools or queues. The benchmark keeps 64 requests open at a time. At concurrency 64, 63 of them sat on the small copy, 4 running and 59 waiting. The large copy had one to three requests and used 2 to 7 percent of its pool. The client could not send it more work until the small copy gave a slot back.
We measured the cost at the tail too. At concurrency 64, the median p99 TTFT of three seeds was 33.4 seconds on one L4 and 391 seconds with two copies. The one-card run was on 2026-10-16 and the pair on 2026-10-17. At 32 and 64 users the pair ran at 765 and 675 MHz, under our clock floor. One card ran at 1,320 and 1,080 MHz, so part of that loss is the clock. Raw runs
Up to concurrency 4, the two copies were already 16 to 41 percent slower, for a reason we did not isolate. At 1 user the pair took 79.6 ms per token against 60.2 ms, at a higher clock.
The open-loop sweep of section 5.1 agreed. With requests arriving at a fixed rate, two copies completed at most 0.21 requests per second inside our latency target. One L4 alone completed 0.96.
We then measured one of the two settings that could help. --load-balance-method total_tokens sends each request to the copy that holds the fewest tokens.
[2026-10-19 00:24:05 DP0] KV Cache is allocated. dtype: torch.bfloat16, #tokens: 24094, K size: 1.65 GB, V size: 1.65 GB
[2026-10-19 00:24:06 DP1] KV Cache is allocated. dtype: torch.bfloat16, #tokens: 2925, K size: 0.20 GB, V size: 0.20 GBWe measured a large gain over round robin, and still a loss against one card. The three runs were on 2026-10-19, 2026-10-17, and 2026-10-16. Raw runs
At 64 users the pair gave 114.7 tok/s routed by tokens, against 41.7 with round robin and 250.9 on one L4. At 8 users it gave 92.1 against 64.2 and 112.6. The median TTFT at 64 users fell from 4,763 to 3,977 ms. The median clock at 64 users was 1,020 MHz, against 675 MHz in the round-robin run. So part of the gain can be the card.
The other setting is two separate servers behind the gateway in section 6.4, each with a weight. We did not measure it. We did not measure a pair with equal pools either. On our unequal pair, --dp-size 2 lost at every load. We expect data parallelism to add capacity only when every copy has about the same pool. Check the #tokens line of each DP rank before you trust the sum.
MoE serving: --moe-a2a-backend, DeepEP, and EPLB
A mixture-of-experts layer sends every token to the GPUs that hold its experts, so MoE serving is mostly communication, and the busiest GPU sets the pace.
A mixture-of-experts (MoE) model such as DeepSeek-V3 activates a few experts per token out of many. On paper that is cheap compute. In a server it is a traffic problem. Each token must travel to the GPUs that hold its chosen experts, and each result must travel back, in every MoE layer of every step. One overloaded GPU then makes all the others wait.
When you finish this section, you can follow one token through an MoE layer in SGLang. You can also choose an all-to-all backend and an expert parallel size, and decide when to turn on load balancing and batch overlap.
One MoE layer, five stages
Expert parallelism (EP): the experts of each MoE layer are divided among GPUs, and tokens move to the experts. --ep-size sets how many GPUs share the experts. Its default is 1.
SGLang cuts the MoE forward pass into stages with one owner each. The router picks experts for each token. The dispatcher moves tokens to the GPUs that hold those experts. A runner computes all local experts with grouped matrix multiplications. The dispatcher then moves results back and combines them.
Three flags pick the implementations:
| Flag | Default | Picks |
|---|---|---|
--moe-a2a-backend | none | how tokens move between GPUs: deepep, mooncake, nixl, mori, pplx, flashinfer, and others |
--moe-runner-backend | auto | which grouped matrix multiply kernel runs the experts |
--deepep-mode | auto | normal dispatch for prefill batches and low_latency dispatch for decode batches |
With none, SGLang moves tokens with all-reduce or all-gather collectives. That works for any layout and costs more bandwidth at scale. The all-to-all backends send each token only where it must go.
The layout rules that SGLang enforces
The all-to-all backends span the whole TP group. When you choose one of them, SGLang sets --ep-size equal to --tp-size and logs the change at info level. You cannot run DeepEP across four of eight GPUs. A mixed layout with expert parallelism smaller than tensor parallelism works only with none.
DeepEP has two dispatch modes. Normal mode sends large prefill batches with high throughput, and it cannot be captured in a CUDA graph. Low-latency mode sends small decode batches and works inside CUDA graphs. The default auto uses each mode where it fits. If you force --deepep-mode normal, SGLang turns off decode CUDA graphs and prints one warning line. Section 4.1 shows what decode without graphs costs.
Choose the expert parallel size from your batch
Wider expert parallelism spreads experts thinner and moves more traffic over slower links. Ant Group measured this on H20 GPUs with DeepSeek-R1 decode:
| Decode batch | EP16 | EP32 |
|---|---|---|
| 8 | 278 tokens/s | 293 tokens/s |
| 32 | 675 tokens/s | 585 tokens/s |
EP32 won at the small batch and lost by 13 percent at the batch they run in production. They explained the result with traffic: about half of the MoE traffic stays on NVLink at EP16, against about a quarter at EP32. They also chose EP16 to limit how many requests one failed GPU takes down. Their post appeared on the LMSYS blog, and the measurements are theirs.
Expert load balancing
Real traffic does not spread evenly over experts. Some experts get most of the tokens, and the GPUs that hold them become the slowest rank in every step.
EPLB: the expert parallelism load balancer. It records which experts each forward pass uses. Every --eplb-rebalance-num-iterations passes, 1000 by default, it computes a new placement and moves expert weights. --ep-num-redundant-experts adds extra copies of popular experts, and its default is 0. A threshold flag skips the rebalance when GPU utilization is already high. Its default of 1.0 means that it never skips.
EPLB is off by default (--enable-eplb is false). Turn it on when your measurements show imbalance, not before. Run with --expert-balancedness-report-mode prometheus and watch sglang:eplb_balancedness. The SGLang team reported EPLB speedups of 1.49 times for prefill and 2.54 times for decode. Those numbers came from a simulated imbalance, so expect less on traffic that is already balanced.
Overlapping communication with compute
Two-batch overlap (TBO): the scheduler cuts a batch into two micro-batches. One micro-batch runs attention while the other one waits on dispatch or combine. Turn it on with --enable-two-batch-overlap. It is off by default.
For prefill, SGLang splits by token count. If no split puts at least 48 percent of the tokens on each side, it cuts one sequence across both halves. That is --tbo-token-distribution-threshold, 0.48 by default.
The SGLang docs say that TBO can give up to twice the throughput. The blog post that the docs link to measured 27 to 35 percent on 96 H100 GPUs. Plan for the measured number.
Ant Group turned TBO down on H20. It helped only at batch sizes of 64 or 128, and at those sizes their time per output token missed its target. They used single-batch overlap instead, --enable-single-batch-overlap, which overlaps shared experts with the combine step. They measured 8 to 10 percent at batches of 20 to 56.
One GPU, one MoE model: the batch reads more experts
On one GPU there is no dispatch across GPUs, so MoE looks cheap. We served Qwen3-30B-A3B on one NVIDIA GB10 and swept concurrency from 1 to 64. Its config has 48 layers, 128 experts in each MoE layer, and 8 active experts per token.
| Concurrency | BF16 median TPOT | FP8 median TPOT |
|---|---|---|
| 1 | 32.52 ms | 18.41 ms |
| 8 | 102.21 ms | 54.96 ms |
| 64 | 254.06 ms | 131.78 ms |
We measured this with three seeds per point. From 1 to 64 concurrent requests, the time per output token grows 7.8 times with BF16 and 7.2 times with FP8. In a dense model, one decode step reads each weight once for the whole batch. In an MoE model, the set of weights that a step reads grows with the batch. We did not run a dense control on the GB10. Raw runs
One likely cause is the union of experts. At concurrency 1, each layer reads the weights of 8 experts in a decode step. At 64, 64 tokens each choose 8 of 128 experts. If routing were uniform, one step would read about 126 of the 128 experts in each layer.
That is arithmetic, not a measurement, and real routing is less even. The time per token kept rising from 32 to 64 users, where the union grows only about 13 percent. So attention, KV reads, and prefill steps in the sweep grow with the batch too. The name says the model activates about 3B parameters per token. A batch of 64 reads close to all 30B.
Our prompts limit this result too. The random dataset sends ShareGPT text, cut or repeated to 512 tokens, and every answer ran to 128 tokens.
A 2026 benchmark study by NVIDIA researchers, SPEED-Bench, tested an MoE model with random token ids. In some layers, 20 to 30 percent of the experts stayed idle. Our prompts are real text, and they are still different from your traffic. We did not measure which experts they chose. Run the same sweep with a sample of your own prompts before you plan capacity from it.
Our position: on one box, plan an MoE model by the bytes a full batch reads, not by its active parameters. Quantize first. The FP8 checkpoint with an FP8 KV cache cut the time per token to between 0.52 and 0.57 of BF16 at every concurrency we measured. It quantized all weights and the KV cache, so we cannot assign the gain to the experts alone.
Our position
Leave --deepep-mode at auto in a server that does both prefill and decode. Choose --ep-size from the batch size that meets your latency target, not from the largest published run. Turn on EPLB only after sglang:eplb_balancedness shows imbalance. Treat TBO as a throughput feature for large decode batches, and measure it against your time per output token before you keep it.
Two field reports at full scale
One result in this part passed an external audit. Crusoe submitted DeepSeek-R1 on 512 AMD MI355X GPUs to MLPerf Inference v6.1 with SGLang 0.5.15.post1. Each node ran TP8 with EP8 and eight attention groups. The offline score was about 2.90 million tokens per second. In the server scenario, p99 time per output token was 79.98 ms against a limit of 80 ms. Their write-up lists the flags.
The SGLang team's 96-GPU run reported 52.3k input and 22.3k output tokens per second per node. It used 12 nodes of eight H100 GPUs, with prefill and decode on separate nodes. Section 6.3 explains that split.
A real incident: one GPU runs out of memory
A team ran DeepSeek V3 with four prefill and six decode servers and large expert parallelism (issue #9787). Under load, one prefill rank's GPU utilization dropped to zero, and then every prefill process crashed. The thread traced it to DeepEP dispatch. Imbalanced routing sent too many tokens to one GPU, and that GPU ran out of memory. The suggested fixes were a smaller chunked prefill per attention group, a tuned initial expert placement, and EPLB. The lesson is general: in MoE serving, the busiest GPU sets both your speed and your memory limit.
Prefill-decode disaggregation: --disaggregation-mode
Disaggregation moves prefill to its own servers so long prompts stop delaying other users' tokens, and it pays off only when that delay is your measured problem.
Your chat users see smooth streaming until someone pastes a long document. Then every stream pauses while the server prefills the document. Prefill is compute work on many tokens at once, and decode is one token per request per step. On one server, they share the same GPU steps, and the long prefill takes the step. Chunked prefill makes the pause shorter but cannot remove it.
When you finish this section, you can explain how SGLang moves a request's KV cache from a prefill server to a decode server. You can also start the smallest disaggregated setup and decide from measurements whether you need it.
Two servers, one request
Prefill-decode disaggregation (PD): two kinds of SGLang servers, started with --disaggregation-mode prefill and --disaggregation-mode decode. The default is null, which means one server does both. A prefill server computes the prompt's KV cache and the first token. A decode server receives that KV cache and generates the rest.
The SGLang docs give two reasons for the split. Prefill batches interrupt decode batches. With attention data parallelism, one group can prefill while another decodes, so the decoding group waits for the slowest group in each step. Separate servers remove both kinds of waiting. Each pool can also use its own parallel layout, for example a wide TP for prefill and attention data parallelism for decode.
How the KV cache moves
The gateway in section 6.4 starts every exchange. It picks one prefill server and one decode server. It adds three fields to the request: the prefill server's bootstrap host, its bootstrap port, and a random 63-bit number called the bootstrap room. Then it sends the same request to both servers at the same time.
Bootstrap room: the number that both servers use to find each other's half of one request. Think of it as a reservation number: the decode server books KV slots, and the prefill server writes into them.
- The decode server creates a receiver, finds the prefill rank through the bootstrap server, and reserves KV slots for the prompt.
- It sends the addresses of those slots to the prefill side.
- The prefill server runs a normal prefill forward pass for the prompt.
- It writes the KV pages into the decode server's reserved slots. With the default Mooncake backend, this is a one-sided RDMA write. Mooncake groups contiguous pages on both sides into one batch transfer.
- The decode server sees the transfer finish and adds the request to its running batch without another prefill.
- The client stream comes from the decode server.
The bootstrap server runs on the prefill host. Its default port is 8998. Each side tracks a transfer with five states: Failed, Bootstrapping, WaitingForInput, Transferring, and Success.
Settings that matter
| Setting | Default | Meaning |
|---|---|---|
--disaggregation-mode | null | prefill or decode for the two roles |
--disaggregation-transfer-backend | mooncake | also mooncake_tcp, nixl, mori, ascend, fake |
--disaggregation-bootstrap-port | 8998 | the bootstrap server port on the prefill host |
--num-reserved-decode-tokens | 512 | decode tokens reserved in memory when a request joins the running batch |
SGLANG_DISAGGREGATION_BOOTSTRAP_TIMEOUT | 300 | seconds that prefill waits for the decode side's slot addresses |
SGLANG_DISAGGREGATION_WAITING_TIMEOUT | 300 | seconds that decode waits for the KV pages |
SGLANG_DISAGGREGATION_QUEUE_SIZE | 4 | parallel transfer queues |
All defaults come from the v0.5.22 code. mooncake_tcp exists for clusters without RDMA network cards. We did not measure its speed.
Do not send requests straight to a prefill or decode server. The scheduler asserts that a bootstrap room exists, and its error message tells you to send requests to the router instead.
Our position
Do not start with disaggregation. Start with one server, then add data parallel copies behind the gateway. Split prefill from decode only after you measured that prefill interference hurts your inter-token latency at the concurrency you serve. Disaggregation adds a second set of failures: the bootstrap step, the RDMA transfer, two timeouts, and a router that must pair servers correctly.
Even for the tail, the gain is a condition, not a default. A 2025 study compared split servers with servers that run both stages. It found that the gain is not guaranteed, and that it depends on the request load and on the path that moves the KV cache. We did not measure this ourselves. Before you keep a split, compare it with the same GPUs run as plain servers, at your real load.
A real incident shows the cost of skipping that measurement. A user ran one prefill and one decode server, each with TP4 (issue #12591). Time to first token was higher than on one TP4 server without disaggregation. The cause was an old Mooncake transfer engine. Upgrading it fixed the problem, and a maintainer also suggested SGLANG_DISAGGREGATION_QUEUE_SIZE=1 without attention data parallelism. Without the single-server baseline, nobody would have known that disaggregation made things worse.
Two more incidents, both from the router
At 64 concurrent requests, a GLM-4.5 setup logged many "Prefill bootstrap failed" and "Aborted by AbortReq" errors on the prefill side (issue #9266). Four to seven concurrent requests worked. The router's timeout for the prefill client was too short, so the router aborted requests that were still running. Pull request #9803 fixed the timeout.
A maintainer gave the general rule in a related thread (issue #9926). "Aborted by AbortReq" means that the client or the router aborted. Check timeouts before you suspect the transfer.
Novita AI found a different delay with GLM-4.7 on H200. With disaggregation and the overlap scheduler, throughput rose about 10 percent but time to first token got much worse. On prefill, the KV transfer waited until the next batch's kernel launch. Without CUDA graphs, that launch took hundreds of milliseconds for their 92-layer model. Their fix added a flag, --disaggregation-async-transfer. We could not find that flag in the v0.5.22 code, so check your version before you copy their command.
How many prefill servers for each decode server
The ratio depends on your traffic. dstack tested gpt-oss-120b on eight H200 GPUs with SGLang disaggregation and tensor parallelism only. At high concurrency, one prefill server for three decode servers won every metric, for prefill-heavy, decode-heavy, and balanced loads. At low concurrency, three to one and two to two gave a better time to first token. Their post shows charts without absolute numbers, so use it for the direction only.
At the largest scale, the SGLang team ran DeepSeek on 12 nodes of eight H100 GPUs. They reported 52.3k input and 22.3k output tokens per second per node for 2000-token inputs. They measured prefill on 4 nodes and decode on 9 nodes, in separate runs. The Mooncake team reported Kimi K2 on 128 H200 GPUs with 4 prefill and 12 decode nodes. They gave decode more nodes so that the KV pool could hold a batch of 480. Both are reports from the teams that built the system.
What happened on two L4s
We split Qwen3-8B into one prefill server on the first L4 and one decode server on the second. Our two cards have no RDMA, so we used --disaggregation-transfer-backend mooncake_tcp. The second card also ran another team's pods, so the decode pool held 2,925 tokens against 24,094 on prefill. We then ran the open-loop sweep of section 5.1 through the router.
… Decode batch, #running-req: 2, #token: 1206, token usage: 0.41, pre-allocated usage: 0.00, #prealloc-req: 19, #transfer-req: 0, #retracted-req: 0
… TCP lane queue-full rejection count: 4096
… Session 151.242.195.41:15367 failed.
Prefill transfer failed lines: 2902
Successful requests: 240
Total generated tokens (retokenized): 0
Mean TTFT (ms): 0.00Decode could run only two requests at a time, and 19 more waited for decode memory. Prefill kept producing KV caches for them, and the TCP transfer queue to decode filled. Three minutes into the sweep, the transfer session failed, and it did not come back. Every later request failed its transfer.
The dangerous part came next. Each failed request still counted as a success through the router, with no text. The benchmark counted 240 successful requests out of 240 at 8 requests per second. It printed 751.85 output tokens per second, higher than the 728.61 of the FP8 server at the same rate. Only two numbers gave it away: zero retokenized output tokens and a mean TTFT of 0.00 ms.
We did not publish those throughput numbers. Our kit now refuses a run in which every request has a TTFT of 0.
We then ran the split the other way round. Decode had the full pool of 24,094 tokens, and prefill had the shared card with 2,925. From 1 to 8 users, every request came back with text. At 16 users, only 2,048 of 8,192 generated tokens came back as text. At 32 users, every request came back empty, and the kit stopped the sweep.
c8: Successful requests: 32
c8: Total generated tokens: 4096
c8: Total generated tokens (retokenized): 4096
c16: Successful requests: 64
c16: Total generated tokens: 8192
c16: Total generated tokens (retokenized): 2048
c32: Successful requests: 128
c32: Total generated tokens: 16384
c32: Total generated tokens (retokenized): 0 The original direction failed early in both sweeps. At 2 users only 512 of 2,048 generated tokens came back as text, and at 4 users none did. The fixed-rate sweep lost most of its text from 0.5 requests per second. We have no measured result for the split under load on this pair of cards, and we do not claim one. Check Total generated tokens (retokenized) in every disaggregated benchmark before you read its throughput.
What to measure
Measure TTFT and inter-token latency on one server first, with the benchmark in section 5.1. If inter-token latency rises when long prompts arrive, disaggregation can help. After the split, watch these metrics:
sglang:num_bootstrap_failed_reqs_totalandsglang:num_transfer_failed_reqs_total, which must stay flatsglang:kv_transfer_latency_msandsglang:kv_transfer_speed_gb_s, which show the cost of each movesglang:num_decode_prealloc_queue_reqsandsglang:num_decode_transfer_queue_reqs, which show requests that wait for memory or for a transfer.
sgl-model-gateway and cache-aware routing
With several servers, the router decides your cache hit rate, so send each conversation back to the server that already holds its prefix.
You start a second server to double capacity. Throughput rises, but time to first token gets worse for long conversations. Each server has its own KV cache, and turn 5 of a chat goes to the server that never saw turns 1 to 4. That server prefills the whole history again. Section 3.4 measured what a prefix miss costs on one server. A router that ignores prefixes makes the same miss on purpose.
When you finish this section, you can explain how sgl-model-gateway picks a server for each request. You can also choose a routing policy for your traffic and check that the gateway keeps your hit rate.
Two places where requests get routed
SGLang routes requests in two places, with different defaults.
Inside one server: with --dp-size above 1, a data parallel controller gives requests to the copies. Its default method, auto, resolves to round_robin outside disaggregation. Round robin ignores prefixes, as figure 6.1b shows.
In front of servers: sgl-model-gateway is a separate Rust program that routes to many SGLang servers. It was named sgl-router until pull request #14312 renamed it on 2025-12-05, for "less confusion". Its default policy is cache_aware.
A field report shows the difference. Jarvislabs found that the default routing sends each request to the next GPU in turn. It does not look at where the cache of a conversation is.
On their traffic, 23 percent of input tokens were computed again. One request header that pinned each conversation to one GPU raised their cache hit rate from 64.7 to 92.1 percent and halved median TTFT. Their post does not name the component that did the round robin. The in-server default matches their description.
How cache_aware picks a server
The gateway keeps one approximate radix tree per model. Each tree node records which servers have seen that prefix. The tree stores characters of the request text, not tokens, so the gateway never runs a tokenizer to route.
Match rate: the number of characters of a new request that match the tree, divided by the request length.
For each request, select_worker does three things:
- It checks balance. The system is imbalanced when two tests pass. The busiest server's load is more than 64 above the lightest, and more than 1.5 times the lightest. Then the request goes to the least-loaded server.
- Otherwise it computes the match rate. Above 0.3, the request goes to the server with the longest match.
- Below 0.3, the request goes to the least-loaded server, with a random choice among ties.
The gateway then inserts the request text under the chosen server. Every 120 seconds, a background task removes least recently used leaves until each tree is at most 67,108,864 nodes.
A comment at the top of the policy file says that a low match goes to "the worker with smallest tree size". The code sends it to the least-loaded worker. The code wins, and this manual describes the code.
The tree is a guess
The gateway never asks a server what it caches. Its tree records where it sent text, and a server can evict that prefix later. So the gateway can send a request to a server that no longer holds its prefix. That request then prefills like any other miss. Check the hit rate on the servers, with sglang:cache_hit_rate from section 5.2, and not only the routing decisions.
Settings that matter
| Flag | Default | Effect |
|---|---|---|
--policy | cache_aware | also random, round_robin, power_of_two, prefix_hash, manual |
--cache-threshold | 0.3 | the match rate above which prefix affinity wins |
--balance-abs-threshold | 64 | the load gap that marks the system as imbalanced |
--balance-rel-threshold | 1.5 | the load ratio that marks the system as imbalanced |
--eviction-interval | 120 | seconds between tree cleanups |
--max-tree-size | 67108864 | tree nodes kept per model |
--prometheus-port | 29000 | the gateway's own metrics |
--request-timeout-secs | 1800 | the longest request the gateway waits for |
All defaults come from the gateway source in the v0.5.22 release. That source says version 0.3.2. The newest gateway tag in the repository, gateway-v0.3.1, points at a commit from 2026-01-08. Pin the gateway by the commit you run, not by that tag.
The source also has bucket and consistent_hashing policies. The command line does not accept them at v0.5.22. For two plain servers, the start command is python -m sglang_router.launch_router --worker-urls http://127.0.0.1:30000 http://127.0.0.1:30001 --policy cache_aware.
Our position
Use cache_aware for chat and agent traffic, where turns share long prefixes. Use power_of_two or round_robin for batch traffic with unique prompts, because a match rate under 0.3 gives no affinity anyway. Do not put multi-turn traffic behind in-server --dp-size with its round robin default. Run separate servers behind the gateway, or set a different --load-balance-method.
The SGLang team introduced the cache-aware router in v0.4. They reported up to 1.9 times more throughput and a 3.8 times better hit rate. Those are their numbers on their workload. Measure your own hit rate before and after.
Pin the router with the engine
A user reported a two times throughput regression in SGLang on GB200 NVL72 with DeepSeek-R1 (issue #22095). The regression was in the router outside SGLang. With the same SGLang build, Dynamo router 0.8.1 gave 132,140 tokens per second and Dynamo router 1.0.0 gave 69,767. Benchmark the router and the engine as one system, and pin both versions.
A second incident shows that routing and service discovery interact. With disaggregation and Kubernetes service discovery, cache_aware failed with "Failed to select prefill/decode worker", and users switched to round robin (issue #10608). The issue was closed, and we could not find the fix that closed it. Test your exact deployment mode before you depend on a policy.
What to measure
Compare sglang:cache_hit_rate on every server before and after you change the policy. Watch the gateway's metrics on port 29000 for retries and open circuits. The gateway retries a failed request up to 5 times by default, and it opens a server's circuit after 10 failures. A rising TTFT with a falling hit rate means that requests no longer reach the server that holds their prefix. For a broader view of gateways in production, see the lesson on AI gateways.
Production and Training
Operate SGLang with its defaults written down, and expect reinforcement learning to treat the server as part of the training loop.
Operating SGLang
Run SGLang so that a restart costs seconds and drops no request: pin the image, keep the compiled kernels, signal only the main process, and tune in a measured order.
The first production incident with a new serving engine is rarely about tokens per second. A rolling update kills ten requests in the middle of their answers. A new pod takes four minutes to become ready, so the autoscaler starts three more. A liveness probe times out under load and restarts the busiest pod. None of these appear in a benchmark, and all of them cost more than a slow kernel.
When you finish this section, you can choose an image tag and keep startup short. You can connect the health probes to the right endpoints and stop a server without losing work. You can also change settings in the order that this manual measured, and read three production reports for what each one teaches.
Pin the image you run
The SGLang team publishes images on Docker Hub as lmsysorg/sglang. At v0.5.22 the latest tag holds the newest stable release, and latest-runtime holds a smaller image of the same release. Nightly tags follow main. The images contain CUDA 13 only. The docs name lmsysorg/sglang:v0.5.19-cu129 as the last CUDA 12 tag, so a host with an older driver needs that tag or a driver upgrade.
The documented start command gives the container a large shared memory segment and the host IPC namespace:
docker run -it --gpus all \
--shm-size 32g \
-p 30000:30000 \
-v "$HF_CACHE_DIR:/root/.cache/huggingface" \
--ipc=host \
lmsysorg/sglang:latest bashOur position: never deploy latest. SGLang tagged v0.5.20, v0.5.21, and v0.5.22 within four weeks, from 2026-09-18 to 2026-10-13, and each release changed defaults that this manual measures. A pinned tag such as v0.5.22 makes a regression a choice that you made. The tag latest makes it something that happened to you on a restart.
What pip install leaves out
The image exists for a reason that a pip install hides. We measured this on a host with two NVIDIA L4 GPUs, Ubuntu 24.04, a driver, and no CUDA toolkit. pip install sglang==0.5.22 finished with no error. The first sglang serve then failed, and so did the next three, each for a new reason:
=== attempt: out-l4-nopyheaders/server-default.log
<site-packages>/triton/backends/nvidia/driver.c:9:10: fatal error: Python.h: No such file or directory
…
=== attempt: out-l4-nonvcc/server-default.log
[2026-10-16 14:21:19] RuntimeError: Could not find nvcc and default cuda_home='/usr/local/cuda' doesn't exist
…
=== attempt: out-l4-jitmismatch/server-default.log
…
<site-packages>/flashinfer/data/cccl/libcudacxx/include/cuda/std/__cccl/cuda_toolkit.h:41:8: error: #error "CUDA compiler and CUDA toolkit headers are incompatible, please check your include paths"
…
=== attempt: out-l4-nolibcudart/server-default.log
/usr/bin/ld: cannot find -lcudart: No such file or directoryAll four failures come from one fact. SGLang, Triton, and FlashInfer compile kernels on the target machine at startup, and a compiler needs a complete toolchain.
- Triton compiles a small C helper against the Python headers. The system Python of Ubuntu has no
Python.h. We changed to a Python build that includes its headers, fromuv. - SGLang looks for
nvccunder/usr/local/cuda. The pip wheels includenvcc13.4 undernvidia/cu13in site-packages, but nothing points to it. We setCUDA_HOMEto that directory. - FlashInfer then compiled its attention kernels with that
nvccagainst its own bundled headers, and the versions did not match. We installedflashinfer-jit-cache, which holds kernels compiled in advance for SM 8.9. - The JIT kernels of SGLang link with
-lcudartfrom$CUDA_HOME/lib64. The wheel has onlylib/libcudart.so.13. We made aCUDA_HOMEwith alib64directory that holdslibcudart.so.
The fifth start served requests. Our GB10 never had this problem, because its DGX operating system has a full toolkit in /usr/local/cuda.
The benchmark client has one more dependency that a firewall exposes. Its random dataset takes its text from ShareGPT and downloads that file from the Hugging Face Hub. With HF_HUB_OFFLINE=1, our first GPU benchmark failed although every model was on disk. We did not keep that log. Use --dataset-name random-ids on a machine without network access, or pass a local ShareGPT file with --dataset-path.
Our position: run SGLang from the pinned image or on a host with a full CUDA toolkit. A pip install on a host with only a driver works after our four repairs. Each SGLang upgrade can need them again.
Cold start is weights plus compilers
A new SGLang process loads the weights, compiles or loads kernels, sizes the KV pool, and captures graphs. Our capture logs each phase on one line. This run used a model that was already on disk:
[2026-10-16 13:58:06] Engine startup timings (s): load_weight=0.00, kv_cache_allocation=0.00, scheduler_e2e=7.01, cuda_graph={prefill=0.00, decode=0.00, target_verify=0.00, draft_prefill=0.00, draft_decode=0.00, draft_extend=0.00}, tokenizer_e2e=11.92We measured 18 s from the first log line to "The server is fired up and ready to roll!" for a 0.6B model on the Mac. A large model on GPUs is a different problem. A field report from Doubleword, an engineer blog dated 2026-04, timed SGLang v0.5.10 with Qwen3.5-122B-A10B-FP8 on 8 B200 GPUs. A cold start took 695 s, and 531 s of that was weight loading. With kernel caches kept between runs, a warm start took 88 s. With a process checkpoint and weights staged in host memory, it took 9.6 s. Raw runs
The code helps with the cheap part of that work. When Python imports sglang, it points the Triton, TorchInductor, CUDA, TileLang, and FlashInfer caches into one directory, SGLANG_CACHE_DIR, which defaults to ~/.cache/sglang. Mount that directory and the Hugging Face cache on volumes that survive the pod. Then a restart reuses compiled kernels and downloaded weights.
The same field report defends the slow start. To them, 10 percent more tokens per second is worth more than a start that is 10 seconds faster. We agree for a fleet that runs for days. For a fleet that scales to zero every night, startup time is a real cost, and the persistent caches are the first fix.
Health checks: /ready, /health, and /health_generate
SGLang has two kinds of health endpoint:
/readyreturns 200 when the tokenizer manager is ready and 503 before that./healthand/health_generateshare one handler. They return 503 while the server starts and while it shuts down.- Otherwise the handler sends a one-token request with
max_new_tokens1 and waits for any output from the detokenizer. SGLANG_ENABLE_HEALTH_ENDPOINT_GENERATIONdefaults to true, so a plain/healthalso generates that token.- The wait is
SGLANG_HEALTH_CHECK_TIMEOUT, 20 s by default. With no output in that time, the handler marks the serverUnHealthyand returns 503.
The docstring says that the probe request costs nothing when the server is busy, because any output from the scheduler counts as proof of life. That is true for the work, and false for the timing. A real incident: issue #22511 reports "health check failed. server could not get a response from detokenizer for last 20 seconds" on GLM-5 with 2 H800 GPUs under high load, on v0.5.10. A related issue, #35884, found that a timed-out probe left its request in the scheduler, so failed probes accumulated.
Our position: use /ready for the readiness probe. Keep the liveness probe from generating. Set SGLANG_ENABLE_HEALTH_ENDPOINT_GENERATION=false, and /health then returns 200 without a request to the scheduler. Use /health_generate for a slower deep check that alerts a person and restarts nothing. A busy server then does not lose its busiest pod to a probe that waited in the queue.
Graceful shutdown: signal the main process only
On SIGTERM, the HTTP server sets gracefully_exit, and /health starts to return 503. A watchdog in the tokenizer manager checks the flag every 5 s. It then logs the remaining requests every 5 s until none remain. Then it sends ShutdownReq to the schedulers and gives them 15 s to exit before it kills them. Figure 7.1 shows this path and the two paths that skip the drain.
We measured both cases on the Mac. Our capture kit stopped each server by sending SIGTERM to its whole process group. The scheduler child received the signal too and died first: Raw runs
[2026-10-16 14:01:45] SIGTERM received. signum=None frame=None. Draining requests and shutting down...
[2026-10-16 14:01:45] Subprocess scheduler_0 (pid=5909) crashed with exit code -15. Triggering SIGQUIT for cleanup...
[2026-10-16 14:01:45] SIGQUIT received. signum=None, frame=None. It usually means one child failed.
[2026-10-16 14:01:46] Sleeping 5 seconds before crash diagnostics to let GPU activity settle.The parent saw a crashed child, took the crash path, and killed the process tree. No request was running at that moment, so nothing was lost. Under load, every running request would have failed. We then started a server, sent it a request for 3,000 output tokens, and sent SIGTERM to the main process only:
[2026-10-16 14:13:54] SIGTERM received. signum=None frame=None. Draining requests and shutting down...
…
[2026-10-16 14:13:55] INFO: 127.0.0.1:53237 - "GET /health HTTP/1.1" 503 Service Unavailable
…
[2026-10-16 14:13:57] Gracefully exiting... Remaining number of requests 1. Remaining requests remaining_rids=['ef12359aaaaf40d78fedb4e7f7aaed25'].
…
[2026-10-16 14:14:04] INFO: 127.0.0.1:53209 - "POST /generate HTTP/1.1" 200 OK
[2026-10-16 14:14:07] Gracefully exiting... Remaining number of requests 0. Remaining requests remaining_rids=[].
…
[2026-10-16 14:14:07] INFO: Finished server process [53853]health before SIGTERM: 200
sent SIGTERM to the server process only
health during drain: 503
in-flight request: {"status": 200, "completion_tokens": 3000, "finish_reason": {"type": "length", "length": 3000}, "seconds": 14.2}
server exit code: 0The request finished with all 3,000 tokens, and /health returned 503 during the drain. The server exited with code 0, thirteen seconds after the signal. docker stop and Kubernetes send SIGTERM to the main process of the container. That is the correct target when sglang serve is the main process, so start it with exec or as the entrypoint. The interactive command above makes bash the main process, and bash does not pass the signal on. A wrapper script that forwards the signal to a process group, or a supervisor that kills the group, gives you the first log instead.
The code has two exits that skip the drain. If the server is already UnHealthy, the watchdog exits at once. It also exits at once if the environment variable SGL_FORCE_SHUTDOWN is true. At v0.5.22 the watchdog reads that old name directly.
The environment module declares the new name SGLANG_FORCE_SHUTDOWN. Its compatibility code copies SGL_ variables to SGLANG_ names, never the other way. The code shows that setting only SGLANG_FORCE_SHUTDOWN does not reach the watchdog. We read this in the code and did not run it, so we call it a likely bug. If you need a forced stop, set SGL_FORCE_SHUTDOWN=1.
Our position: set the termination grace period longer than your longest request at your output cap. A 32K-token answer at 30 tokens per second needs more than 18 minutes. Cap max_tokens before you set the grace period, or a drain can never finish in time.
Before you trust a measurement
Three checks prevent most of the false results that we found on our own machines:
- Flush the prefix cache before each run that you compare, and record the cached tokens, as in section 5.1. In our kit, a warm cache made a run at a higher load look faster. In a later test with
Qwen/Qwen3-0.6Bat a cap of 16, a repeat with no flush read a median TTFT about 4.8 times lower. - Record the SM clock and the temperature with every run, as in section 5.1. A hot L4 reported up to 28 percent less throughput.
- On a shared GB10, run SGLang in a container with a memory limit, and log free memory during startup, as in section 3.2.
When a greedy output changes between two runs, check the cache first. A request that finds its prompt in the cache runs a different prefill path, as section 4.6 shows. One request at a time, a warm cache changed 21 of 32 of our greedy outputs, and a flush brought exact repeats back. These two tests ran on a shared L4 GPU with no clock lock, so trust the ratio and the counts, not the times.
The server aborts or hangs under heavy eviction
Symptom: in the middle of a multi-turn load, the server stops with CUDA error: an illegal memory access was encountered. Or the log stops with no error while the GPU stays at 100 percent.
We saw this on SGLang 0.5.22 with Qwen/Qwen3-0.6B, a pool of 8,192 tokens, and the trace of section 3.5. From the fourth turn, the pool evicted prefixes on almost every step. CUDA graphs and the overlap scheduler were on, which is the default. The runs were on the second GPU of our L4 node on 2026-10-23, which its owner shares and which had no clock lock.
variant runs aborts hangs clean
lru, CUDA graph and overlap on (default) 6 1 3 2
lru, CUDA_LAUNCH_BLOCKING=1 3 0 0 3
lru, --disable-cuda-graph 4 0 0 4
lru, --enable-hierarchical-cache 3 1 0 2
lru, HiCache, CUDA_LAUNCH_BLOCKING=1 2 0 0 2With the defaults, 4 of 6 runs failed. HiCache did not prevent it, and 1 of its 3 runs aborted. The abort and every hang stopped in the same place: the scheduler waited for the copy of a decode result to finish. With CUDA graphs off, 0 of 4 runs failed. With CUDA_LAUNCH_BLOCKING=1, 0 of 3 failed.
We did not find the kernel that faults, because the fault did not occur with blocking launches. Nothing was filed upstream.
Workaround: add --disable-cuda-graph. On our L4 with an 8B model, graphs saved about 1 percent of each decode step, as section 4.1 shows. A small model spends a larger share of each step on launches, so measure the cost on your model. CUDA_LAUNCH_BLOCKING=1 also hid the fault, but it makes every kernel launch wait for the one before it. Use it to debug, never to serve.
Also test: a larger pool. With a pool of 16,384 tokens or more, the same trace stopped thrashing, as section 3.5 shows. We did not count crashes at the larger pools, so this is not a proven fix.
The order to change settings
Most tuning advice lists flags. The order matters more than the list, because each step changes what the next step measures. Figure 7.1b shows the order this manual uses, and each row links to the section that measures it.
- Measure with
sglang.benchmark.servingat three concurrency levels, as in section 5.1. Without a baseline, no later change has a number. - Set
--mem-fraction-staticfor the machine you share, as in section 3.2. On our Mac the automatic value crashed the server at concurrency 32. - Put shared text first in every prompt, as in section 3.4. One request id at the start of a system prompt cost us about 14 times the time to first token.
- Cap
--max-running-requestsat the knee you measured. Past the knee on our L4, throughput fell while time to first token grew. Our GB10 kept rising to 64 users, and we did not measure a cap itself. - Only now change CUDA graph settings and
--attention-backend, one change per run, as in section 4.1 and section 4.2. At v0.5.22--disable-cuda-graphis deprecated in favour of--cuda-graph-backend-decodeand--cuda-graph-backend-prefill. - Add tensor, data, or attention-data parallelism when one replica is saturated, as in section 6.1.
- Split prefill from decode last, and only after you measured that prefill delays decode, as in section 6.3.
What production teams report
Three reports by teams outside SGLang show where operating effort goes.
LinkedIn, an independent engineering blog dated 2026-02-20, serves ranking models of 375M to 0.6B parameters on H100 GPUs. The workload needs only prefill and the logits of the last token. Their bottlenecks were the tokenizer, ZMQ messages, Python garbage collection, the GIL, and the scheduler, and none of them were GPU kernels.
Batch tokenization took P99 latency from 4,583 ms to 464 ms. A scoring path that skips decode took P99 from 6,220 ms to 454 ms. Garbage collection pauses of 100 to 300 ms went away with a warm-up and gc.freeze(). The 375M ranker went from 750 to 2,200 items per second per GPU. LinkedIn wrote most of the pull requests involved, so their "before" is an older SGLang.
CERIT-SC, a Czech academic service, moved from vLLM to SGLang in 2025 and reported 100 billion tokens served by 2026-04. Their traffic shape is the lesson. For Kimi K2.6 the median prompt was 2,179 tokens and the 95th percentile was 99,746 tokens, which they attribute to agentic coding tools. Their SGLang problems were tool calls that leaked into reasoning output, rare hangs, and model loops that held KV cache. Their fix was operational: an output cap of 32K tokens and a presence penalty for workloads that loop. They still run both engines, chosen per model.
Ant Group published a DeepSeek-R1 deployment on H20 GPUs with SGLang v0.5.2 on the LMSYS blog, dated 2025-09-26. They chose expert parallelism of 16 over 32 because at batch 32 EP16 gave 675 tokens per second against 585 for EP32. More speculative draft tokens gained 21% at batch 1 and lost about 18% at batch 32. They sell three latency tiers, and the strictest tier, below 30 ms TPOT, runs at batch 12. The measured tier table is a product decision, which is the point.
Our position: read a production report for its traffic shape and its order of fixes, never for its throughput number. LinkedIn fixed CPU work before GPU work. CERIT-SC capped output before it tuned anything. Ant Group chose the smaller expert group because the fault radius and the batch size it sells mattered more than peak throughput.
SGLang as an RL rollout engine
In reinforcement learning the server becomes part of the training loop, so its memory, its weights, and its log probabilities all become the trainer's problem.
You train a model with GRPO. Every step, an inference server writes thousands of answers, a reward function scores them, and the trainer updates the weights. Then the server must answer the next prompts with the new weights, on the same GPUs that the trainer just used. A serving engine built for chat never had to give its memory back or change its weights while it runs. It never had to match another program's numbers to the last bit.
When you finish this section, you can describe one RL step with SGLang as the rollout engine and name the SGLang endpoints each phase calls. You can also choose a weight transfer method and say what "true on-policy" covers and what it does not. The example is Miles v0.1.2 (commit a22fd824), the RL framework that RadixArk maintains next to SGLang.
The receipt for training on stale numbers
Miles is a fork of slime, an RL framework from THUDM, and keeps slime's history. RadixArk describes it as "Enterprise-Grade Reinforcement Learning for Large-Scale Model Post-Training". The docs never define "enterprise". In the code it means three things: correctness checks between rollout and training, recovery from engine faults, and observability.
Each of those exists because RL changes what an inference server is. The server's output is the training data. The log probabilities it reports are the "old policy" in the PPO and GRPO ratio. So any numerical difference between SGLang kernels and the trainer's kernels becomes a bias in the gradient. Miles is the receipt for training on numbers that the server did not produce.
The loop that borrows the server
The training driver is short on purpose. At v0.1.2, train.py has 175 lines. These are the lines of one step when the trainer and SGLang share GPUs:
for rollout_id in range(args.start_rollout_id, args.num_rollout):
await inference_controller.prepare_rollout(rollout_id)
rollout_data_pack = await rollout_executor.get(rollout_id)
if args.offload_rollout:
...
offload_tags = [GPU_MEMORY_TYPE_CUDA_GRAPH]
if "kv_cache" in args.offload_rollout_level:
offload_tags.append(GPU_MEMORY_TYPE_KV_CACHE)
if "weight" in args.offload_rollout_level:
offload_tags.append(GPU_MEMORY_TYPE_WEIGHTS)
await inference_controller.offload(tags=offload_tags)
...
await actor_model.train(rollout_id, rollout_data_pack)
...
await offload_train()
if args.offload_rollout:
await inference_controller.onload_weights()
await update_weights(args, actor_model, rollout_executor, inference_controller, rollout_id=rollout_id)
if args.offload_rollout:
await inference_controller.onload_kv()Read it as a rental. SGLang generates and scores the rollout. SGLang releases its CUDA graphs, KV cache, and weights. The trainer loads, trains, and offloads itself. SGLang gets its weights back, receives the new weights, and then gets its KV cache and CUDA graphs back. Figure 7.2b shows which memory is on the GPU in each phase.
What stock SGLang gives the trainer
The rental works through SGLang HTTP endpoints that exist in stock v0.5.22. The RL guide of SGLang states the design rule. SGLang acts as a library that the trainer calls, not as a framework that owns the loop. Miles drives each engine as an ordinary sglang serve process over HTTP.
Memory release: POST /release_memory_occupation frees GPU memory by tag, and POST /resume_memory_occupation gives it back. The server needs --enable-memory-saver, which is off by default. The tags are kv_cache, weights, and cuda_graph. The docs list only the first two, and the code accepts all three, so the code wins. The memory saver frees physical memory but keeps the virtual addresses, so captured CUDA graphs stay valid without a new capture. The call asserts that the server is idle, so pause generation first.
Pause and resume: POST /pause_generation takes a mode. SGLang's default is abort, which ends every running request. Miles uses retract by default, which puts running requests back in the waiting queue so they prefill again after the update. A third mode, in_place, keeps their KV cache from the old weights.
The weight-update session: begin_weight_update, then one or more update_weights_from_* calls, then end_weight_update. The session exists because quantized layers need a one-time repack after loading. Doing it once per refit is cheaper than once per bucket. After the session, update_weight_version stamps the new version. A request that lived through a refit reports weight_versions spans in its meta_info, so you can see which tokens came from which weights. Figure 7.2 shows one update with the default transfer.
Four ways to move the weights
Miles picks the transfer with --update-weight-transfer-mode:
| Mode | How the bytes move | Where it fits |
|---|---|---|
broadcast (default) | one NCCL group per pipeline stage, trainer rank 0 broadcasts each bucket to every engine GPU | separate trainer and engine GPUs |
broadcast_packed | the same group, one flat byte tensor per bucket | Megatron, not colocated |
p2p | Mooncake RDMA writes into the GPU addresses that each engine rank publishes | multi-node MoE |
disk-delta | changed bytes of the checkpoint go to shared storage, and each engine patches a local copy | no RDMA or NCCL path |
With --colocate, Miles ignores this flag and always sends CUDA IPC handles through /update_weights_from_tensor. A team that sets p2p on a colocated run measures the wrong thing and never knows.
The Miles team reports P2P timings on H100 clusters with a 1 GB bucket. Qwen3-235B-A22B on 8 nodes went from 10,754 ms with NCCL broadcast to 3,162 ms, 71% less. Kimi-K2 on 32 nodes went from 53,279 ms to 7,227 ms, 86% less. On one node P2P was slower: GLM-4.7-9B-Flash took 68.6% longer and a 4-layer GLM-5 test took 72.2% longer. The reason is in the design. Broadcast sends the full model to every engine rank, and with expert parallelism each rank needs only a fraction of it.
RadixArk reports that about 2% of BF16 parameters change in one step. For GLM-4.7-Flash the disk-delta payload fell from 62.4 GB to 0.69 to 0.83 GB per update, with a generation pause of 3 to 5 s. These are their numbers from the Miles v0.1 post of 2026-08-18. We did not reproduce them.
Our position: start colocated on one node with the CUDA IPC path. Move to separate GPUs only when rollout time dominates the step. Choose p2p only for multi-node MoE, where the vendor table shows the gain, and keep broadcast everywhere else.
True on-policy, and where it stops
Here the serving engine and the trainer must agree on a number. Give SGLang and Megatron or FSDP the same weights and the same tokens. Their kernels can still return different log probabilities, because their reductions run in a different order. Then the PPO ratio mixes "the policy changed" with "the kernels differ". Miles reports the gap as train/train_rollout_logprob_abs_diff, which should be exactly 0 in true on-policy mode.
Two SGLang facts matter first. SGLang returns log probabilities after temperature scaling unless the request is greedy or SGLANG_RETURN_ORIGINAL_LOGPROB is set, as section 4.6 explains. Sometimes the rollout samples at a temperature other than 1, and the trainer computes log probabilities at temperature 1. Then the trainer sees a mismatch that no kernel causes.
Second, --rl-on-policy-target accepts one value at v0.5.22, fsdp, and it forces deterministic inference. That mode replaces matrix multiply, softmax, and norm kernels with batch-invariant versions and forces the PyTorch sampler. It also turns off the radix cache unless the attention backend is fa3, fa4, triton, or ascend.
Miles builds on that with a launch plan that sets matching flags on both sides. The coverage is narrow. At v0.1.2 the only model profile is Qwen3 dense: Qwen3-0.6B, Qwen3-4B, Qwen3-4B-Base, and Qwen3-4B-Instruct-2507. Three open issues in the Miles repository show where bitwise parity still breaks:
- Issue #1485: Qwen3-4B
down_projoutputs differ at tensor parallel 2. SGLang sums 38 partial results in two groups of 19, and Miles sums them in a pairwise tree. BF16 addition is not associative. - Issue #3714: deterministic serving pins the NCCL channel limit to 8 while the trainer uses 24. Weight transfer then fails with
Message truncated : received 6144 bytes instead of 2048. - Issue #3277: after a retract, re-prefill under the new weights overwrites the recorded MoE routes. The response then carries new routes with old log probabilities.
Our position: treat true on-policy as a diagnostic for Qwen3 dense models, not a switch for every run. Log the log-probability gap on every run anyway. A large gap means a conversion or kernel problem, and no RL algorithm fixes that.
What we measured with Miles on a GB10
We ran GRPO with the radixark/miles:latest image on one NVIDIA GB10. The image held Miles commit 08752a12 and SGLang 0.5.22.dev46+g7b6993a. The model was Qwen/Qwen3-0.6B on GSM8K, with FSDP and SGLang colocated on the one GPU. Each of the 12 steps sampled 32 prompts 8 times, up to 1,024 response tokens, at temperature 1. SGLang had a memory fraction of 0.4.
metrics.py:94 - perf 0: {'rollout/raw_reward_unfiltered': 0.62890625, 'rollout/num_training_samples': 256, 'rollout/episode_raw_reward': 0.62890625, 'rollout/episode_response_length/mean': 739.92578125, 'rollout/episode_response_length/median': 759.5, 'rollout
{'train/loss': -4.656612873077393e-10, 'train/pg_loss': -4.656612873077393e-10, 'train/entropy_loss': 0.0, 'train/pg_clipfrac': 0.0, 'train/ppo_kl': 0.0, 'train/ess_ratio': 1.0, 'train/train_rollout_logprob_abs_diff': 0.015336457639932632, 'train/train_rollout_kl': 0.0006840902497060597, 'train/grad_norm': 0.5216571092605591, 'train/lr-pg_0': 1e-06, 'train/step': 0}
timer.py:42 - Timer update_weights end (elapsed: 0.7s)
[2026-10-17 15:55:01] post-warmup freeze_gc failedWe measured the step time by phase. The SGLang rollout took a median of 57.2 s, at about 3,113 tokens per second. The trainer then recomputed log probabilities in 25.2 s and trained in 80.3 s. The weight update into SGLang took 0.65 s through CUDA IPC. Releasing the SGLang memory took a median of 0.8 s and at most 4.0 s, and taking it back took 0.9 s. Raw runs
The rollout was not the bottleneck at this size. For a 0.6B model on one GPU, a faster serving engine would save at most about a third of the step, 35 percent. The weight update and the memory release, which much of this section is about, cost 2.4 s. The step took about 165 s, summed from the phase medians.
The log-probability gap stayed between 0.0143 and 0.0163 in all 12 steps. That is the number true on-policy mode exists to drive to 0, and plain mode does not move it. The raw reward went up and down between 0.586 and 0.758. Twelve steps are too few to show learning, so read the run as a timing and a gap, not as a training curve.
Forty-eight steps
We then ran the same job for 48 steps, with the same settings: memory fraction 0.4 and temperature 1, first with the default seed. Over those steps the policy started to learn, and the rollout got faster as it did.
metrics.py:94 - perf 47: {'rollout/raw_reward_unfiltered': 0.79296875, 'rollout/num_training_samples': 256, 'rollout/episode_raw_reward': 0.79296875, 'rollout/episode_response_length/mean': 421.73046875, 'rollout/episode_response_length/median': 369.5, 'rollou
{'train/loss': -3.4924596548080444e-09, 'train/pg_loss': -3.4924596548080444e-09, 'train/entropy_loss': 0.0, 'train/pg_clipfrac': 0.0, 'train/ppo_kl': 0.0, 'train/ess_ratio': 1.0, 'train/train_rollout_logprob_abs_diff': 0.014126655645668507, 'train/train_rollo
Subprocess scheduler_0 (pid=3263) crashed with exit code -15. Triggering SIGQUIT for cleanup...
Job 'raysubmit_MKE9XLVeZ87U7iQV' succeededWe measured a mean raw reward of 0.636 over the first 8 steps and 0.758 over the last 8. The responses got shorter. Their mean length fell from 724 to 447 tokens, and the share of samples cut at the 1,024-token limit fell from 0.33 to 0.08. SGLang had fewer tokens to make, so the rollout fell from 60.2 s to 32.7 s per step. Its rate went up from 3,084 to 3,501 tokens per second. Raw runs
From one step to the next the reward changed by as much as 0.207, from 0.801 at step 30 to 0.594 at step 31. Read the trend from the 8-step means, not from one step.
The log-probability gap did not move. It was 0.0153 over the first 8 steps and 0.0146 over the last 8, and it stayed between 0.0138 and 0.0162 in all 48. In 48 steps of this 0.6B run, training did not close the gap. Miles attributes the gap to differences between the SGLang and FSDP kernels. True on-policy mode is the part of Miles that works on it.
The last log lines also need a note. The SGLang scheduler printed crashed with exit code -15, and the Ray job then reported success. Exit code -15 means the scheduler got SIGTERM, here at the end of a finished job. Alert on the job status, not on that line alone.
Two log lines are worth knowing before you trust a run. About 30 percent of the samples in the 12-step run hit the 1,024-token limit, and 20 percent over the 48 steps. So the reward includes answers cut off before the end. And SGLang printed post-warmup freeze_gc failed once at startup. Training ran normally after it, so the warning cost nothing here.
Two more seeds
We ran the same 48 steps twice more, with MILES_SEED=2 and MILES_SEED=3. The variable sets the train seed and the rollout seed. The GB10 shut down three times under this load on 2026-10-18, and its boot list shows three short boots that day. So these runs had a guard. A script paused the container when the GPU reached 84 C, or 80 C in the first 30 minutes. It resumed the container after about 45 to 60 seconds, at 72 C or below.
Over the 9.3 hours of seeds 2 and 3, the container was paused for about 58 percent of the time. A pause stops the process and does not change its arithmetic. So we read the reward, the lengths, the cut share, and the log-probability gap as valid. We did not test this with a paused and an unpaused run of the same seed. The rollout times are not, and we do not report them for seeds 2 and 3.
metrics.py:94 - perf 47: {'rollout/raw_reward_unfiltered': 0.6484375, 'rollout/num_training_samples': 256, 'rollout/episode_raw_reward': 0.6484375, 'rollout/episode_response_length/mean': 514.0390625, 'rollout/episode_response_length/median
{'train/loss': -5.122274160385132e-09, 'train/pg_loss': -5.122274160385132e-09, 'train/entropy_loss': 0.0, 'train/pg_clipfrac': 0.0, 'train/ppo_kl': 0.0, 'train/ess_ratio': 1.0, 'train/train_rollout_logprob_abs_diff': 0.014963770285248756,
Job 'raysubmit_y4umCbEa8Qp5Bbad' succeeded| Mean, first 8 steps / last 8 steps | Default seed | Seed 2 | Seed 3 |
|---|---|---|---|
| Raw reward | 0.636 / 0.758 | 0.653 / 0.736 | 0.614 / 0.766 |
| Response length, tokens | 724 / 447 | 712 / 480 | 734 / 456 |
| Share cut at 1,024 tokens | 0.33 / 0.08 | 0.30 / 0.12 | 0.34 / 0.09 |
| Log-probability gap | 0.0153 / 0.0146 | 0.0153 / 0.0150 | 0.0156 / 0.0146 |
We measured the same result with all three seeds. The reward went up, the responses got shorter, and fewer of them were cut. The log-probability gap stayed between 0.0136 and 0.0164 in all 144 steps. The largest change in reward from one step to the next was 0.207, 0.160, and 0.203 for the three seeds. Raw runs
True on-policy did not start on a GB10
We then set --true-on-policy-mode with the flags of the Miles Triton example. SGLang started, and the trainer stopped 61 seconds after the launcher began.
[2026-10-17 16:28:41.340 launcher] common.py:290 - EXEC: mkdir -p /root/lab/mode
ValueError: Specified `attn_implementation="triton"` is not supported. The only possible arguments are `attn_implementation="eager"`, `"paged|eager"`, `"attn_implementation=flash_attention_2"`, `"attn_implementation=paged|flash_attention_2"`, `"attn_implementa
[2026-10-17 16:29:42.606 trainer_controller_actor] cell.py:251 - ft op=execute phase=fail cell=trainer-engine-actor-00000 fn=init elapsed_s=0.7The flag value came from the wrong example. In the FSDP actor, the SGLang Triton attention bridge turns on only when torch.version.hip is set, which means AMD GPUs. On an NVIDIA GPU the value goes straight to transformers, which has no attention named triton.
The only true on-policy contract in Miles pairs the SGLang fa3 backend with flash_attention_3 in FSDP. We ran the job again with the contract flags to see where it stops.
[2026-10-17 21:03:03] Enable deterministic inference because of legacy rl_on_policy_target.
AssertionError: FlashAttention v3 Backend requires SM>=80 and SM<=90. Please use `--attention-backend flashinfer`.
[2026-10-17 21:03:24] Received sigquit from a child process. It usually means the child failed.
[2026-10-17 21:03:30.637 rollout_executor] http_utils.py:241 - Error: Server error '503 Service Unavailable' for url 'http://172.17.0.3:20035/generate'
[2026-10-17 22:06:46.137 rollout_executor] http_utils.py:241 - Error: Server error '503 Service Unavailable' for url 'http://172.17.0.3:20035/generate'SGLang stopped 21 seconds after it started. Its FA3 backend accepts GPUs from SM 8.0 to SM 9.0, and the GB10 is SM 12.1. With the Miles image we ran, at commit 08752a12, the only true on-policy contract needs FA3, so it cannot start on a GB10.
What happened next is the part to remember. The rollout engine was gone, but the Miles job did not stop. Its rollout loop kept sending requests to the router, which answered 503 Service Unavailable. The log holds about 200,000 of those errors over 63 minutes, until we stopped the container. The job never reported a failure. We did not record the GPU during that hour.
Our position on the GB10 result: before you plan a true on-policy run, check that your GPU and image have both kernels of the contract. Then watch the SGLang server log, not only the trainer, because a dead rollout engine can look like a slow one. In the image we ran, at Miles commit 08752a12, that contract means FlashAttention 3 on both sides, a path written for Hopper GPUs.
Miles runs on its own SGLang
Miles does not use the SGLang release that the rest of this manual describes. Its Docker image builds on lmsysorg/sglang:v0.5.21 and checks out the sglang-miles branch. The v0.1.2 release lock pins SGLang commit b84bec5761a6. The Miles docs say it plainly: stock sglang or upstream Megatron-LM installed next to Miles does not work.
At least four things that Miles calls do not exist at v0.5.22: the /pull_weights endpoint for disk-delta, register_lora_adapter, get_parallelism_info, and the --true-on-policy-contract flag.
That branch is a fair summary of this section. RL asks a serving engine for things that serving users never asked for. It must give memory back and change weights in a session. It must report which weights produced each token and match another program bit for bit. Some of those requests are now in stock SGLang. The rest live on a branch until they are ready.
A real incident: issue #860 in the Miles repository reports that /release_memory_occupation "silently does nothing" for models with sliding-window attention. The sliding-window KV pool turns the memory saver off in its constructor, so a colocated run runs out of memory when Megatron starts. One user saw 30.19 GB of KV pool stay resident on DeepSeek-V4-Flash. The issue was open on 2026-10-16. Check that every memory tag really frees memory on a new model before you trust colocation.
Reference
The flags, metrics, incidents, terms, and sources this manual uses, in one place.
Flags and defaults
These are the flags this manual changes or explains, with the default the code sets, the value our Mac resolved, and when to change it.
sglang serve --help lists 535 options at 0.5.22 (the captured help output). Most of them never matter to you. The table below holds the main ones this manual uses. The sections name a few more flags where they apply.
Many defaults are None in the code. A startup hook replaces them with a value that depends on the GPU, the model, and the free memory. The "On our Mac" column shows that resolved value, from the server_args line of the default server log.
Memory and admission
| Flag | Default in the code | On our Mac | Change it when | Section |
|---|---|---|---|---|
--mem-fraction-static | None, derived from GPU size at startup | 0.4, set by the kit | the machine runs other programs, or the server crashes on large batches | 3.2 |
--max-total-tokens | None, derived from the memory budget | 181,574 tokens in the pool | you want a fixed pool size for a test | 2.3 |
--max-running-requests | None, derived from the pool and the context length | 4,096 | you know your concurrency limit, or you turn on speculative decoding | 2.3 |
--chunked-prefill-size | None, derived from GPU memory | 4,096 | long prompts stall decode, or prefill is too slow | 2.2 |
--max-prefill-tokens | 16,384 | 16,384 | rarely | 2.2 |
--schedule-conservativeness | 1.0 | 1.0 | you see retractions in the log, raise it | 2.3 |
--page-size | None, derived per attention backend | 1 | the attention backend needs pages | 3.1 |
Scheduling
| Flag | Default in the code | On our Mac | Change it when | Section |
|---|---|---|---|---|
--schedule-policy | fcfs | fcfs | many queued requests share long prefixes, try lpm | 2.2 |
--disable-overlap-schedule | False | False | only to debug, and never on MLX at 0.5.22, where it crashed | 2.4 |
--stream-interval | 1 | 1 | you stream to many clients and want fewer messages | 2.5 |
Cache
| Flag | Default in the code | On our Mac | Change it when | Section |
|---|---|---|---|---|
--disable-radix-cache | False | False | only to measure the cache, as our kit does | 3.3 |
--radix-eviction-policy | lru | lru | a few prefixes are hot and many are cold | 3.5 |
--enable-hierarchical-cache | off | off | the working set of prefixes is larger than GPU memory | 3.5 |
--kv-cache-dtype | auto | auto | you need more context per GPU and can test the quality | 4.3 |
--enable-cache-report | False | True, set by the kit | always, so clients see cached_tokens | 3.4 |
Execution
| Flag | Default in the code | On our Mac | Change it when | Section |
|---|---|---|---|---|
--attention-backend | None, chosen per GPU and model | torch_native, which MLX does not use | you measured a better backend for your model | 4.2 |
--grammar-backend | None, which resolves to xgrammar | xgrammar | a grammar fails to compile | 4.5 |
--disable-cuda-graph, deprecated | False | True, as the Apple instructions say | on Apple silicon, where CUDA graphs do not exist. Prefer --cuda-graph-backend-decode disabled and --cuda-graph-backend-prefill disabled | 4.1 |
--speculative-algorithm | None | None | decode latency at low concurrency matters most | 4.4 |
--enable-deterministic-inference | False | False | you need the same output for the same input in any batch | 4.6 |
--disable-cuda-graph still works at 0.5.22, and the per-phase flags --cuda-graph-backend-decode and --cuda-graph-backend-prefill replace it.
Parallelism and operations
| Flag | Default in the code | On our Mac | Change it when | Section |
|---|---|---|---|---|
--tp-size | 1 | 1 | one GPU cannot hold the weights | 6.1 |
--dp-size | 1 | 1 | one copy of the model is saturated and you have GPUs for another | 6.1 |
--attn-dp-size | 1 | 1 | you serve an MLA model such as DeepSeek on many GPUs | 6.1 |
--ep-size | 1 | 1 | you serve a large MoE model | 6.2 |
--enable-metrics | False | True, set by the kit | always in production | 5.2 |
--watchdog-timeout | 300 s | 300 s | a single forward pass can take longer than five minutes | 7.1 |
Metrics
These are the Prometheus series this manual reads, what each one measures, and the question each one answers in production.
--enable-metrics turns on /metrics. Without the flag, the endpoint does not exist, and the default is off. Our default server exported 81 metric families with the prefix sglang: (the metrics capture). Section 5.2 explains which ones to alert on. This table keeps the ones the manual uses.
Latency
| Series | Type | Measures | The question it answers |
|---|---|---|---|
sglang:time_to_first_token_seconds | histogram | the time from arrival to the first output token | are users waiting before they see anything |
sglang:inter_token_latency_seconds | histogram | the time between two output tokens | does the stream stutter |
sglang:request_time_per_output_token_seconds | histogram | per request, the decode time divided by the output tokens after the first | is decode slow for each user |
sglang:e2e_request_latency_seconds | histogram | the time from arrival to the last token | how long does a full answer take |
sglang:queue_time_seconds | histogram | the time a request waits before its first prefill | is the scheduler holding requests back |
Load and memory
| Series | Type | Measures | The question it answers |
|---|---|---|---|
sglang:num_running_reqs | gauge | requests in the running batch | how much work is on the GPU now |
sglang:num_queue_reqs | gauge | requests in the waiting queue | is admission the bottleneck |
sglang:token_usage | gauge | the fraction of pool slots in use | how close the pool is to full |
sglang:num_retracted_reqs | gauge | requests the scheduler moved back to the queue in the last log interval | did the admission forecast fail just now |
sglang:num_retracted_requests_total | counter | requests the scheduler moved back to the queue since start | how often does the admission forecast fail |
sglang:max_total_num_tokens | gauge | the size of the KV pool in tokens | what did startup sizing decide |
sglang:kv_cache_memory_usage_gb | gauge | memory used by the KV pools | how much memory the cache holds |
sglang:gen_throughput | gauge | output tokens per second in the last interval | is the server producing tokens |
sglang:scheduler_idle_seconds_total | counter | time with no runnable or queued work | is the server underused |
Cache and tokens
| Series | Type | Measures | The question it answers |
|---|---|---|---|
sglang:cache_hit_rate | gauge | the prefix cache hit rate | are prompts reusing the cache |
sglang:cached_tokens_total | counter | cached prompt tokens, by source: device, host, or storage | which cache tier served the hits |
sglang:prompt_tokens_total | counter | prefill tokens processed | how much prompt work arrived |
sglang:uncached_prompt_tokens_histogram | histogram | prompt tokens that needed compute | how much prompt work was new |
sglang:generation_tokens_total | counter | output tokens produced | how much decode work was done |
sglang:num_requests_total | counter | finished requests | how many requests were served |
sglang:num_paused_reqs | gauge | requests paused for a weight update | is an RL trainer pausing the server |
What our runs recorded
After the shared-prefix benchmark, the default server reported sglang:cache_hit_rate 0.94. The server with --disable-radix-cache reported 0.0 for the same benchmark. The gauge covers a recent window.
The counters cover the whole life of each server, and the two servers ran different sets of benchmarks before the scrape. The default server counted 286,134 prompt tokens, 286,102 streamed plus 32. Of those, 182,079 came from the cache, a lifetime ratio of 0.64. Each counter appears once per label set, so sum the rows before you divide.
Incident index
The failures this manual tells as stories, with their symptom, their cause, their fix or status, and the section that explains each one.
The sections use real incidents as evidence. Each one comes from an SGLang or Miles issue, a pull request, a field report, or our own capture. This index lists them by part, so you can search it with a symptom you see in your own logs. A status of open or closed was checked on 2026-10-16.
Our capture
| Incident | Symptom | Cause | Fix or status | Section |
|---|---|---|---|---|
| Out of memory at concurrency 32 (log) | Metal reported Insufficient Memory, and the whole server process tree exited | The pool took 87 percent of the free memory that startup saw | --mem-fraction-static 0.4 | 3.2 |
--disable-overlap-schedule on MLX (log) | RuntimeError on the first real batch, then the server exited through SIGQUIT and killed its process tree | The path without overlap still calls FutureMap.stash with tensors on two devices | Open at 0.5.22. Keep overlap on | 2.4 |
| Process-group SIGTERM (log) | The log reports a crash at shutdown | The scheduler child died first, so the parent took the crash path without a drain | Send SIGTERM to the main process only | 7.1 |
| Memory guard on a GB10 (record) | Startup stopped while the scheduler allocated the KV pool. We did not keep the server logs of those starts | A guard daemon of the machine stopped the scheduler, which grew up to 36.7 GiB in 5 s | Stop or configure the guard for the server | 3.2 |
Driver NV_ERR_NO_MEMORY on a GB10 (record) | Bursts of driver out-of-memory lines in the kernel log | The bursts fall on 2026-10-16, the day of our first starts. We did not keep the server logs of that day, so we cannot match each burst to one start | Every server in our later captures became healthy. Alert on health, not on this line | 3.2 |
| pip install on an L4 host with no CUDA toolkit (record) | Four failed starts: Python.h, nvcc, FlashInfer headers, then -lcudart | Kernel compilers at startup need a complete toolchain | Use the image or a host with a full CUDA toolkit | 7.1 |
Benchmark with HF_HUB_OFFLINE=1, log not kept | The random dataset failed with every model on disk | The dataset downloads ShareGPT from the Hugging Face Hub | --dataset-name random-ids or a local --dataset-path | 7.1 |
--chunked-prefill-size 8192 on an L4 (record) | Startup ended with a PyTorch INTERNAL ASSERT FAILED | The prefill graph for 8,192 tokens needed more than the 2.33 GB that the KV pool left | Keep the default chunk of 4,096 on a 24 GB card | 2.2 |
--tp-size 2 with a shared second L4 (record) | RuntimeError: The memory capacity is unbalanced at startup | Two pods of another user held 3.5 GB of the second GPU | Use GPUs that nothing else holds, or one GPU | 6.1 |
| Prefill and decode on two L4s over TCP (record, summary lines) | The benchmark counted every request as a success, with 0 retokenized output tokens and a mean TTFT of 0.00 ms | The transfer queue to a small decode pool filled, and the transfer session failed | Read Total generated tokens (retokenized) in every disaggregated benchmark | 6.3 |
| vLLM FlashInfer sampler on the L4 (record) | Engine core initialization failed after a JIT build | The CUDA compiler and the CUDA toolkit headers in the install did not match | VLLM_USE_FLASHINFER_SAMPLER=0 for a greedy benchmark | 5.3 |
Miles with --attn-implementation triton (log) | ValueError: Specified attn_implementation="triton" is not supported | The trainer side does not accept the Triton backend | Use a contract that both sides support | 7.2 |
| Miles true on-policy on a GB10 (log) | SGLang stopped with the FA3 SM assertion, then the job logged about 200,000 503 errors over 63 minutes and never failed | FA3 accepts SM 8.0 to 9.0, and the rollout loop retries a dead engine | Watch the SGLang log, and check the contract kernels for your GPU | 7.2 |
| GB10 shutdowns under Miles load (record) | The machine shut down three times on 2026-10-18 | The logs do not record a cause | A script pauses the container when the GPU reaches 84 C | 7.2 |
| EAGLE-3 draft for Qwen3-30B-A3B | Startup refused: the target context length of 262144 is greater than the derived 2048 | The draft config declares 2,048 positions | SGLANG_ALLOW_OVERWRITE_LONGER_CONTEXT_LEN=1, as the SGLang cookbook sets it. The Qwen3-8B draft declares 40,960 positions and starts without it | 4.4 |
| Thermal throttle in an L4 sweep (record) | CUDA graphs showed no gain, and seeds of one point differed by 49 percent | GPU 0 ran at 87 °C and 360 MHz of 2,040 MHz, with thermal slowdown active | Record GPU clocks and temperature with every run | 5.1 |
| Temperature 0 on a default server (log) | 2 different answers in 5 identical requests on a GB10 | Not isolated in our runs | --enable-deterministic-inference gave 1 answer in 5 | 4.6 |
Part 1 and Part 2: the request path
| Incident | Symptom | Cause | Fix or status | Section |
|---|---|---|---|---|
| LinkedIn field report, 2026-02 | P99 latency of seconds on small ranking models | Tokenization, ZMQ messages, garbage collection, the GIL, and the scheduler | Batch tokenization, a scoring path, and gc.freeze after warm-up (pull request 9241) | 1.2, 2.1 |
| #36889 | --max-running-requests 8 accepted, but throughput flat at 2 streams | The Mamba state cache capped running requests to 2 | Only an info line reports the cap | 2.2 |
| #8463 | KV cache pool is full. Retract requests. again and again, then failed health checks | Retraction could not free enough memory and repeated | Closed without a fix. At 0.5.22 the scheduler aborts the last request | 2.3 |
| #26248 | Decode fell from about 429 to 20 to 38 tokens per second after a retraction | Not recorded | Closed for inactivity | 2.3 |
| #14972 | Allocation failure after KV cache pool is full at 94 percent usage, with overlap on | Retraction did not account for requests that finish one step later | Pull request #15626 closed without merge. The 0.5.22 scheduler handles it | 2.4 |
| #34740 | Detokenization work grew with the square of the output length | Byte tokens that never complete a character never advance the offsets | Open | 2.5 |
Part 3: the KV cache
| Incident | Symptom | Cause | Fix or status | Section |
|---|---|---|---|---|
| #39675 | Out of memory on the first prefill on Apple MPS | Unknown capacity made the fraction 0.95 | Set --mem-fraction-static | 3.2 |
| #42510 | The draft pool allocation failed | Draft-model copies stayed in memory while the target pool was sized | Reported | 3.2 |
| #6027 | A 64K-token DeepSeek-V3 prompt ran out of memory in attention | The log reported room for 274,934 KV tokens, and attention still ran out | Lower the fraction | 3.2 |
| #43201 | Older posts describe a ChunkCache class that no longer exists | The class was deleted on 2026-10-08 | --disable-radix-cache builds a disabled UnifiedRadixCache | 3.3 |
| #32459 | Deep-prompt hit rate fell from 97 to 40 to 53 percent with EAGLE | The extra KV for speculation forced the tree to evict prompts | Measure the hit rate with each feature you add | 3.3 |
| #35129 | Hit rate of 66.8 percent, and HiCache load-back evicted other sessions | A random hash and a rotating message in the system prompt, and load-back with no room | Prompt edits moved the hit rate to 94.4 percent | 3.4, 3.5 |
| Jarvislabs field report, 2026-08 | 23 percent of input tokens computed again | Requests went to servers without their prefix | One header pinned each conversation to one GPU: 64.7 to 92.1 percent hits | 3.4, 6.4 |
| #30760 | One tensor-parallel rank waited forever in a prefetch check while the others moved on | Not recorded | Reported | 3.5 |
| #42465 | Bursts of 540,000-token prompts hung every rank with HiCache on | Not recorded | The same prompts run without HiCache | 3.5 |
| #39830 | Fluent answers to a different prompt on 20 of 20 host-tier hits | A HiCache host-tier hit on a hybrid linear-attention model | Test hybrid models before you trust the cache | 3.6 |
| #22935 | An identical prompt reused no tokens | A node split created a node with no Mamba state | Read #cached-token for repeated prompts | 3.6 |
| #37834 | Hit rate fell from 88.2 to 65.9 percent, and TTFT rose from 226 ms to 1,063 ms | An option forced the no_buffer Mamba strategy | Keep --mamba-radix-cache-strategy auto unless you measured better | 3.6 |
| #36131 | Lower single-stream decode for hybrid SWA models | A new default freed SWA slots outside the window | Reported | 3.6 |
Part 4: each forward pass
| Incident | Symptom | Cause | Fix or status | Section |
|---|---|---|---|---|
| #23769 | DeepSeek-V4-Pro-FP8 exited during graph capture | With attention data parallelism, the graph batch size counts per rank | A smaller graph batch size or a lower fraction | 4.1 |
| #36478 | disable_piecewise_cuda_graph=True raised TypeError in the Python API | Pull request #23906 moved the field into the per-phase graph config | cuda_graph_backend_prefill="disabled" | 4.1 |
| joshua8.ai field report, 2026-01 | SGLang ran on an SM120 card only in eager mode, and NVFP4 did not run | New architecture support | Check capture and the weight format before you compare engines | 4.1, 4.3 |
| #17411 | Median ITL on H20 went from 39.44 ms to 283.52 ms | FlashInfer 0.6.1 regressed the Hopper attention kernel | SGLang made fa3 the Hopper default | 4.2 |
| Cloudflare field report, 2026-08 | A BF16 KV cache ran out of memory at concurrency 64 | The cache did not fit | An FP8 KV cache held twice the tokens | 3.1, 4.3 |
| Pivot News summary, 2026-05 | A mixed cluster crashed when RTX 4090 cards joined | The FP4 path required compute capability 10.0 | No software path for older cards | 4.3, 5.3 |
| #5274 | EAGLE-3 lowered throughput at concurrency 20 from 217.8 to 164.4 tokens per second | Speculation spends compute that a full batch needs | Run speculation at small batch | 4.4 |
| #6783 | Acceptance fell to 1.2 tokens at 10K input | The draft config had 2,048 positions and no rope scaling | Add rope scaling and 131,072 positions to the draft config | 4.4 |
| David Noel Ng field report, 2026-08 | Acceptance of 1.3 to 1.8 tokens on DeepSeek-V4-Flash | The draft loader did not map the shared expert weights | Pull request #33276 | 4.4 |
| #37707 | A string field accepted values shorter than its minLength | xgrammar dropped the rule when the field also had a pattern | Open | 4.5 |
| #38863 | Bitmask CPU time grew with output length under speculation | A rollback method copied a debug list on every call | Open | 4.5 |
| #43055 | gpt-oss-20b gave different greedy outputs in prefix mode | The deterministic Triton kernel aligned KV tiles to the trimmed prefix | Open | 4.6 |
| #43413, #36174, #31261 | Deterministic mode does not cover Mamba2 hybrids, DeepSeek-V4, or Qwen3.5 | Architectures without batch-invariant kernels | Not yet supported | 4.6 |
| #39597 | Greedy text changed after a restart with DFLASH | FlashInfer autotuning picked other kernel tactics | --disable-flashinfer-autotune or deterministic mode | 4.6 |
Part 5: measuring
| Incident | Symptom | Cause | Fix or status | Section |
|---|---|---|---|---|
| #3196 | 13 tokens per second for DeepSeek V3 on eight H200 GPUs | The script counted words and included TTFT in the rate | Measure with the benchmark client | 5.1 |
sglang:utilization | The gauge reads 0 on a busy server | A regression that the code comment links to #22713 | Use the queue and latency series | 5.2 |
| #35884 | Failed health probes added load | A timed-out /health call did not cancel its request | Treat a failing probe as one symptom | 5.2, 7.1 |
| #22511 | "health check failed" under high load on GLM-5 | No output reached the detokenizer for 20 s under load | Use /ready for readiness | 5.2, 7.1 |
| AIMultiple, 2026-01 | "SGLang 29% faster" repeated by at least five posts | One offline test that lists SGLang v0.2.3 | Ignore results without a version | 1.3, 5.3 |
| vLLM discussion #17221 | SGLang appeared to use 7 GB against 21 GB | The wrong flag: --context-length matches --max-model-len | Compare engines with matching flags | 5.3 |
Part 6 and Part 7: fleets and operations
| Incident | Symptom | Cause | Fix or status | Section |
|---|---|---|---|---|
| #19953 | Attention data parallelism across nodes hung on its first message | A ZeroMQ socket bound without IPv6 for an IPv6 --dist-init-addr | A fix was proposed. We could not confirm the merge | 6.1 |
| #9787 | One prefill GPU went idle, then every prefill process crashed | Imbalanced routing sent too many tokens to one GPU in DeepEP dispatch | Smaller chunks, a tuned expert placement, and EPLB | 6.2 |
| #12591 | TTFT with disaggregation was higher than on one server | An old Mooncake transfer engine | Upgrade Mooncake | 6.3 |
| #9266 | "Prefill bootstrap failed" at 64 concurrent requests | The router timeout for the prefill client was too short | Pull request #9803 | 6.3 |
| #9926 | "Aborted by AbortReq" errors | The client or the router aborted | Check timeouts before the transfer | 6.3 |
| Novita AI field report, 2026-01 | TTFT got much worse with disaggregation and overlap | The KV transfer waited for the next kernel launch | Their flag is not in the 0.5.22 code | 6.3 |
| #22095 | A two times throughput regression on GB200 NVL72 | The router outside SGLang changed version | Pin and benchmark the router with the engine | 6.4 |
| #10608 | "Failed to select prefill/decode worker" with cache_aware | Routing with disaggregation and Kubernetes discovery | Users switched to round robin | 6.4 |
| CERIT-SC field report, 2026-04 | Tool calls in reasoning output, rare hangs, and loops that held KV | Agentic traffic with very long prompts | A 32K output cap and a presence penalty | 7.1 |
| Doubleword field report, 2026-04 | A cold start of 695 s | 531 s of weight loading and cold kernel caches | Persistent caches and a process checkpoint: 9.6 s | 7.1 |
| radixark/miles#860 | /release_memory_occupation did nothing for sliding-window models | The SWA pool turns the memory saver off | Open | 7.2 |
| radixark/miles#1485 | down_proj outputs differed at tensor parallel 2 | The two engines summed BF16 partial results in different orders | Open | 7.2 |
| radixark/miles#3714 | Weight transfer failed with Message truncated | Deterministic serving pinned the NCCL channel limit to 8, and the trainer used 24 | Open | 7.2 |
| radixark/miles#3277 | New MoE routes next to old log probabilities after a retract | Re-prefill under new weights overwrote the recorded routes | Open | 7.2 |
Glossary
Each term below has one meaning across the manual and names the section that defines it.
Every term is defined once, in the section the last column names. The meanings come from the SGLang source at the tag, the captures, and the papers that the sections cite.
| Term | Meaning in this manual | Defined in |
|---|---|---|
| Acceptance length | The number of tokens committed per verify pass: the accepted draft tokens plus one bonus token | 4.4 |
| Attention backend | The class that computes attention over the paged KV cache for one batch | 4.2 |
| Attention data parallelism | Inside one TP group, the attention layers run data parallel while the feed-forward or expert layers stay split across all GPUs | 6.1 |
| Batch invariance | A kernel property: the result for one row does not depend on the other rows, because the reduction order is fixed | 4.6 |
| Bootstrap room | The number that a prefill server and a decode server use to find each other's half of one request | 6.3 |
| Breakable graph | A capture that ends a segment at each op that must run eagerly, runs that op, and starts the next segment | 4.1 |
| Capture bucket | One batch size that SGLang records a decode graph for at startup | 4.1 |
| Concurrency (benchmark) | The sum of the end-to-end latency of every request divided by the run duration | 5.1 |
| Constrained decoding | Removing every token that would break the grammar before the sampler picks one | 4.5 |
| Counter | A Prometheus total that only grows, read with a rate over a window | 5.2 |
| CUDA graph | A record of kernel launches with fixed shapes and addresses that the GPU replays with one CPU call | 4.1 |
| Data parallelism (DP) | Several complete copies of the model, each with its own requests and its own KV cache | 6.1 |
| Decode | The loop that produces each next token, one forward pass per token per request | 1.3 |
| DetokenizerManager | The process that turns output token ids into text and sends it back to the TokenizerManager | 2.1 |
| Draft model | A small model or head that proposes the next few tokens cheaply | 4.4 |
| EPLB | The expert parallelism load balancer, which records expert use and moves experts between GPUs | 6.2 |
| Expert parallelism (EP) | The experts of each MoE layer are divided among GPUs, and tokens move to the experts | 6.2 |
| ForwardMode | The label on a batch that tells the model runner what kind of pass to run | 4.1 |
| Gauge | A value the scheduler overwrites on each log interval, so a scrape sees the latest value only | 5.2 |
| GEMM backend | The kernel library that multiplies quantized weights | 4.3 |
| Goodput | Requests per second that meet a TTFT target and a TPOT target at the same time | 1.3 |
| Grammar queue | The list of requests whose grammar is still compiling | 4.5 |
| Grouped-query attention | Several query heads share one key and value head, so a model has fewer KV heads than attention heads | 3.1 |
| HiCache | The hierarchical cache, which extends the radix tree from GPU memory to host memory and to storage | 3.5 |
| Histogram | A set of counters, one per bucket, from which you read percentiles with a rate over a window | 5.2 |
| ITL | Every gap between two streamed chunks, pooled across all requests | 5.1 |
| KV cache | The stored keys and values of every earlier token, for every layer, kept so that decode does not compute them again | 3.1 |
| KV cache dtype | The format of the cached keys and values | 4.3 |
| KV pool | The memory that holds the keys and values of every token the server keeps | 1.2 |
| L1, L2, L3 | The HiCache tiers: the GPU pool, a pool in pinned host memory, and an optional shared storage backend | 3.5 |
| Logprob | The log probability of a token under the distribution the server sampled from | 4.6 |
| Mamba layer | A state-space or linear-attention layer that keeps one fixed-size state per sequence | 3.6 |
| Match rate | The characters of a new request that match the gateway tree, divided by the request length | 6.4 |
| Memory release | POST /release_memory_occupation frees GPU memory by tag, and POST /resume_memory_occupation gives it back | 7.2 |
| Model world | The set of GPUs that together hold one copy of the model | 6.1 |
| Multi-head latent attention (MLA) | DeepSeek attention, which stores one compressed latent per token in place of keys and values per head | 3.1 |
| Native API | The SGLang endpoints, mainly POST /generate | 2.5 |
| New token ratio | The share of remaining output that the scheduler expects a running request to use | 2.3 |
| Offline quantization | The checkpoint already stores low-bit weights and their scales | 4.3 |
| Online quantization | SGLang converts full-precision weights at load time | 4.3 |
| OpenAI API | The /v1/chat/completions, /v1/completions, and /v1/models endpoints in the OpenAI format | 2.5 |
| Overlap scheduling | Running the CPU work for one batch at the same time as the GPU work of another batch | 2.4 |
| Pause and resume | POST /pause_generation with a mode, whose default abort ends every running request | 7.2 |
| Peak concurrent requests | The largest count of requests active at any point inside one second of a benchmark run | 5.1 |
| Pipeline parallelism (PP) | Whole layers go to different GPUs in order, and --pp-size sets the number of stages | 6.1 |
| Prefill | The forward pass over the whole prompt, which computes its keys and values and the first output token | 1.3 |
| Prefill-decode disaggregation (PD) | Two kinds of SGLang servers, one for prefill and one for decode, with KV moved between them | 6.3 |
| RadixCache | A radix tree over token sequences whose nodes hold the KV slot indices of the tokens on their edges | 3.3 |
| ReqToTokenPool | A table with one row per running request and one column per token position | 3.1 |
| Retraction | Removing running requests from the decode batch to free their KV slots and putting them back in the queue | 2.3 |
| Schedule policy | The rule that orders the waiting queue before admission, set with --schedule-policy | 2.2 |
| Scheduler | The separate process that owns the GPU, builds each batch, runs it, and samples | 2.1 |
| Scheduler loop | The function that runs forever in the scheduler process, one batch per turn | 2.2 |
| Sliding-window attention (SWA) | Attention that reads only the last few thousand tokens | 3.6 |
| Stop condition | A rule that ends a request: a stop token, a stop string, a regex, a length limit, an abort, or the end of a grammar | 2.5 |
| Tail-Optimized LRU (tlru) | An eviction policy that keeps only the part of a conversation that the next turn's latency target needs | 3.5 |
| Tensor parallelism (TP) | The weight matrices of each layer are cut into --tp-size slices, one per GPU | 6.1 |
| Throughput | Output tokens per second across all users | 1.3 |
| TokenizerManager | The object in the main process that receives each request, applies the chat template, and tokenizes it | 2.1 |
| TokenToKVPoolAllocator | The free list of KV slots | 3.1 |
| TPOT | For each request, the time after the first token divided by the remaining output tokens | 5.1 |
| TreeNode | One node of the radix tree, with its children keyed by their first token and the token run on its edge | 3.3 |
| TTFT | The time from sending a request to receiving the first streamed chunk | 5.1 |
| Two-batch overlap (TBO) | The scheduler cuts a batch into two micro-batches, so one runs attention while the other waits on communication | 6.2 |
| Verify pass | One forward of the target model over all proposed tokens, which accepts the longest matching prefix and adds one token | 4.4 |
| Weight quantization | Storing the model weights in fewer bits, such as FP8, FP4, or INT4 | 4.3 |
| Weight-update session | begin_weight_update, one or more update_weights_from_* calls, then end_weight_update | 7.2 |
Sources
The manual ranks its sources by authority, and this page lists every external source the sections cite, with the sections that use each one.
The ranks match how this manual was made. When two sources disagree, the higher one wins and the section says so. The SGLang source files each section used are recorded in the manual source and checked by the audit. They are not listed here. Every page below was read on 2026-10-16. The studies and reports added for the research update were read on 2026-10-22.
The ranked sources
| Rank | Source | What the manual takes from it | Source key |
|---|---|---|---|
| 1 | the SGLang source at the tag, baa9befa | every default and every mechanism | the source files of each section, in the manual source |
| 2 | the captured runs on the Mac and on the GPUs | every listing and every number marked as measured | the capture file name |
| 3 | SGLang issues and pull requests | incidents and the design history of each feature | issue and its number |
| 4 | papers | the original design of RadixAttention and the methods SGLang implements | paper and a title |
| 5 | the SGLang documentation at the tag | documented behaviour, checked against the code | docs and a heading |
| 6 | independent field reports | GPUs and scales that this manual could not run | field, the author, and the month |
| 7 | SGLang team and vendor reports | claims, always labeled as the claim of the author | team or the vendor, and the month |
Rank 1 and rank 2: the code and the captures
| Source | Used in |
|---|---|
SGLang 0.5.22, tag v0.5.22, commit baa9befa381511cd4d56f83980951e5a45fffc6d, github.com/sgl-project/sglang | every section |
Miles 0.1.2, tag v0.1.2, commit a22fd824, github.com/radixark/miles | 7.2 |
| The capture kit and its Mac runs, recorded on 2026-10-16 | every section with a listing |
| The GPU kit and its runs, recorded from 2026-10-16 to 2026-10-21 on an NVIDIA L4 node and a DGX Spark (GB10) | every section with a GPU measurement |
The Miles image radixark/miles:latest at Miles commit 08752a12, with SGLang 0.5.22.dev46+g7b6993a | 7.2 |
Rank 3: pull requests
The issues are in the incident index. These pull requests explain a design change.
| Pull request | What it changed | Used in |
|---|---|---|
| #9241 | warm-up followed by a frozen garbage collector | 1.2 |
| #11210 | overlap with two CUDA streams in one thread | 2.4 |
| #14312 | renamed sgl-router to sgl-model-gateway | 6.4 |
| #23906 | moved the prefill graph field into the per-phase config | 4.1 |
| #29458 | breakable prefill graphs on CUDA | 4.1 |
| #32114 | deleted Cutlass MLA, Dual Chunk FlashAttention, and the plain GPTQ CUDA kernel | 4.2, 4.3 |
| #37898 | raised the decode graph cap on 20 to 35 GB GPUs from 24 to 48 | 4.1 |
| #35455 | loaded the KV scales of compressed-tensors checkpoints, merged 2026-08-20 | 4.3 |
| #40795 | deleted the old benchmark aliases | 5.1 |
| #41818 | added --attn-dp-size and gave --dp-size one meaning | 6.1 |
| #42285, #42286, #42287 | remove the torch.compile path for prefill graphs | 4.1 |
Rank 4: papers
| Paper | Used in |
|---|---|
| Zheng and others, SGLang: Efficient Execution of Structured Language Model Programs, arXiv 2312.07104 | 2.2, 3.1, 3.3, 4.5 |
| The tail-optimized LRU policy that the code names, arXiv 2510.15152 | 3.5 |
| Lee and others, From Tokens to Layers: Redefining Stall-Free Scheduling for MoE Serving with Layered Prefill, arXiv 2510.08055 | 2.2 |
| Liu, Yu, and Yang, When Fancy Eviction Fails: Rethinking Cache Replacement For LLM Prefix Reuse, arXiv 2609.28870 | 3.5 |
| Abramovich and others, SPEED-Bench: A Unified and Diverse Benchmark for Speculative Decoding, arXiv 2604.09557 | 4.4, 6.2 |
| Kumar, Sanghavi, and Das, Test-Time Speculation, arXiv 2605.09329 | 4.4 |
| Agrawal and others, On Evaluating Performance of LLM Inference Serving Systems, arXiv 2507.09019 | 4.4 |
| Zhao and others, CoRun: Padding is Simple and Efficient for Deterministic LLM Inference, arXiv 2608.14376 | 4.6 |
| Qin and others, Vosti: Specifying, Implementing, and Verifying Deterministic LLM Inference, arXiv 2609.38981 | 4.6 |
| Patodiya, Same Request, Different Answer: Quantization Amplifies Cache-Induced Divergence in LLM Serving, arXiv 2609.04748 | 4.6 |
| Chandrasekar and Kramberger, Identifying and Mitigating Systemic Measurement Bias in Production LLM Inference Benchmarks, arXiv 2605.24217 | 5.1 |
| Li and others, Revisiting Disaggregated Large Language Model Serving for Performance and Energy Implications, arXiv 2601.08833 | 6.3 |
Rank 5: SGLang documentation at the tag
| Page | Used in |
|---|---|
docs/docs/hardware-platforms/apple_metal.mdx | the front matter, 2.1, 2.4 |
docs/docs/advanced_features/hyperparameter_tuning.mdx | 2.3 |
docs/docs/advanced_features/hicache_design.mdx and radix_eviction_policy.mdx | 3.5 |
docs/docs/advanced_features/attention_backend.mdx | 4.2 |
docs/docs/advanced_features/quantization.mdx | 4.3 |
docs/docs/advanced_features/speculative_decoding.mdx | 4.4 |
docs/docs/advanced_features/expert_parallelism.mdx | 6.2 |
docs/docs/advanced_features/pd_disaggregation.mdx | 6.3 |
docs/docs/get-started/install.mdx | 7.1 |
docs/docs/advanced_features/sglang_for_rl.mdx | 7.2 |
Rank 6: independent field reports
Rank 7: SGLang team and vendor reports
| Author | Report | Month | Used in |
|---|---|---|---|
| The vLLM team | The state of FP8 KV cache and attention quantization in vLLM | 2026-04 | 4.3 |
| LMSYS | SGLang with Llama 3 | 2024-07 | 5.3 |
| LMSYS | SGLang v0.4: zero-overhead batch scheduler | 2024-12 | 2.4, 6.1, 6.4 |
| LMSYS | DeepSeek with PD disaggregation and large-scale EP on 96 H100 GPUs | 2025-05 | 6.2, 6.3 |
| The Mooncake team on the LMSYS blog | Kimi K2 with large-scale EP | 2025-07 | 6.3 |
| LMSYS | SGLang HiCache | 2025-09 | 3.5 |
| SGLang | v0.5.21 release notes | 2026-10 | 3.5 |
| Google Cloud | EAGLE-3 on Vertex AI | 2025-11 | 4.4 |
| Modal with Decagon | Decagon case study | 2025-11 | 4.4 |
| LMSYS and RadixArk | Miles | 2025-11 | 7.2 |
| RadixArk | Miles v0.1 | 2026-08 | 7.2 |
| The Miles team | docs/advanced/p2p-weight-transfer.md at Miles v0.1.2 | 2026-10 | 7.2 |
Index of figures
Every figure of this manual, in order, by the one claim its caption makes.
Each row links to its figure, and the claim is the claim: field of each figure block. Measured numbers in a figure come from our runs on the Mac or on the GPUs, and each section links the files it uses. Numbers from a field report name the report. The colours follow the palette of the front matter:
- blue is the SGLang server process: the tokenizer manager, the scheduler, and the detokenizer
- violet is the model and its forward pass: kernels, attention backends, and CUDA graphs
- green is the KV cache: pool slots, radix tree nodes, and cached tokens
- plum is model compute: prefill and decode steps
- olive is the client and the network
- indigo is streams and messages
- amber is a lifecycle state, such as a request state or a scheduler phase
- teal is durable state: host memory, storage tiers, and weights on disk
- rose is a failure: out of memory, retraction, an abort, or a crash
- grey is outside SGLang: the operating system, other programs, and the GPU driver
| Fig. | The claim it makes |
|---|---|
| 0.1 | Each arrow style marks one kind of exchange, and every label is a real name, message, or number from our recorded runs. |
| 1.1 | The median TTFT divided by the prompt length is about 0.32 ms per prompt token, and one output token costs 4.38 ms in decode. |
| 1.2 | SGLang owns tokenizing, scheduling, the KV cache, and the forward pass, while the model and the operator own quality, memory, and routing. |
| 1.3 | The tokenizer manager, the scheduler, and the detokenizer each touched the request once, and the prefill computed 3 of 5 tokens. |
| 2.1 | One request crosses three processes over ZMQ, and only the scheduler touches the model, so text work never runs on the thread that launches GPU steps. |
| 2.2 | Each turn ingests requests, orders the queue by policy, admits what fits the budget, and runs either one prefill batch or one decode step. |
| 2.3 | With ignore_eos, each request reserves its 256 prompt tokens and all 512 output tokens, so five requests use 3,840 tokens and a sixth would need 4,608. |
| 2.4 | The ratio starts at 0.7, falls to 0.098 after 600 decode steps, and jumps back up after a retraction, so admission grows bolder until it fails. |
| 2.5 | Without overlap the GPU waits for CPU bookkeeping after every step, and with overlap the CPU processes step N while the GPU already runs step N+1. |
| 2.6 | The scheduler decides when a request stops, the detokenizer turns ids into text, and the output streamer holds back text that could start a stop string. |
| 3.1 | One token of Qwen3-0.6B costs 114,688 bytes, the product of five numbers from the model config. |
| 3.2 | Two requests that share a system prompt point their first rows at the same KV slots, so the prefix exists once in memory. |
| 3.3 | A pool sized at 87 percent of free memory left too little for activations, and a fraction of 0.4 kept the server alive. |
| 3.4 | Raising the fraction from 0.7 to 0.82 on the GB10 grew the BF16 pool by 63 percent and changed closed-loop throughput by less than 2 percent. |
| 3.5 | The radix cache cut the shared-prefix benchmark from 129.7 to 48.8 seconds and the median first-token wait from 7,222 to 1,358 ms. |
| 3.6 | With a 4,096-token shared prompt on the L4, the radix cache cut the median TTFT from 14,706 to 479 ms. |
| 3.7 | Two running requests share one system-prompt node, and the tree splits exactly where their questions start. |
| 3.8 | A random ID at the start of the prompt made about 3,027 tokens miss the cache, and the same ID at the end cost about 45 tokens. |
| 3.9 | Under write_through, a prefix gets a host copy on its first hit, so GPU eviction no longer forces a full prefill. |
| 3.10 | At 32 distinct system prompts on the L4, HiCache cut the median TTFT from 5,449 to 817 ms. |
| 3.11 | A new request that matches 1,800 tokens of a Mamba model resumes from the last snapshot at 1,792 tokens, and prefills 8 tokens. |
| 4.1 | In eager mode the CPU launches each kernel of every layer, and in graph mode one replay call runs the whole recorded decode step. |
| 4.2 | A decode batch replays the next captured graph when it fits under max_bs, and runs eager with one launch per kernel when it does not. |
| 4.3 | SGLang picks the attention backend from the GPU generation and the attention type of the model, and each branch records a measured limit. |
| 4.4 | The checkpoint names its own quantization method, and a --quantization flag only helps when it matches that method or a known upgrade. |
| 4.5 | The FP8 KV cache is a few percent slower at every load both caches can run, and keeps scaling after the BF16 cache runs out of memory. |
| 4.6 | On the GB10, FP8 weights and FP8 KV gave more tokens per second and less time per token at every concurrency from 1 to 64. |
| 4.7 | On one L4, BF16 throughput stopped at 270 tokens per second at concurrency 32, and FP8 kept climbing to 736 at 64. |
| 4.8 | One EAGLE step drafts a chain of tokens, verifies them in one target forward, and commits the accepted prefix plus one bonus token. |
| 4.9 | Speculation doubled single-request speed and cut throughput at concurrency 20 on the same GPU and model. |
| 4.10 | On the GB10, EAGLE-3 cut the median time per token by 1.60 times at concurrency 1 and by 1.89 times at 32. |
| 4.11 | On the L4, EAGLE-3 gave 2.37 times the output throughput at concurrency 1 and 1.00 times at 32. |
| 4.12 | A schema compiles once in a thread pool while the request waits in the grammar queue, then masks the logits at every decode step. |
| 4.13 | A default kernel splits the same row differently in two batches, and a batch-invariant kernel uses one split for every batch. |
| 5.1 | Concurrency and peak concurrent requests come from request timestamps after the run, so neither line repeats the cap you set. |
| 5.2 | Raising the cap from 8 to 32 added no throughput and made the median first token five times slower. |
| 5.3 | Three seeds per point agree closely, so each line is a measurement and the gaps between the lines are real. |
| 5.4 | About half of the requests waited several times longer than the other half, so the median describes neither group. |
| 5.5 | With fixed lengths the median TTFT was 1,996 ms and P99 ITL 82 ms, and with mixed lengths they were 291 ms and 300 ms. |
| 5.6 | FP8 served 1.03 requests per second within the target at 1 offered, and BF16 served almost no request within the target at any rate. |
| 5.7 | On the L4, FP8 served 3.18 requests per second within the target at 4 offered, and BF16 served none within the target from 4 offered. |
| 5.8 | The hot sweep reported up to 28 percent less throughput than the cooled sweep, with the same command on the same card. |
| 5.9 | The gauge reported the last prefill interval at 0.942, while the counters over the whole run gave 0.636. |
| 5.10 | A result that fails the version or workload question tells you nothing about your server, however large its number is. |
| 5.11 | Every independent result in this section traces to one mechanism you can test on your own server. |
| 5.12 | At 64 users on the L4, vLLM gave the first token 1.7 times sooner and SGLang kept the P99 inter-token latency 12 times lower. |
| 5.13 | On the L4, both prefix caches kept the median TTFT under 500 ms at every shared length, and the cache-off run reached 14,706 ms. |
| 5.14 | At 4 requests per second on the L4, vLLM gave 11 percent more output and SGLang kept the P99 time per token 32 percent lower. |
| 6.1 | With --tp-size 8, --attn-dp-size 4, and --ep-size 8, the same eight GPUs form one TP group, four attention groups, and one expert group. |
| 6.2 | Round robin sends alternate requests to two worlds that share no KV cache, so a repeated prefix can miss in the other world. |
| 6.3 | One L4 reached 270 tokens per second, and the shared pair with --dp-size 2 peaked at 64 and fell to 42 as its clock fell. |
| 6.4 | Dispatch and combine move every token across GPUs twice per MoE layer, and the grouped matrix multiply in between is the only expert compute. |
| 6.5 | The time per output token grew 7.8 times while the batch grew 64 times, and each extra request can read other experts. |
| 6.6 | Wider expert parallelism won at batch 8 and lost 13 percent at batch 32, because less of its traffic stayed on NVLink. |
| 6.7 | The decode server reserves KV slots and publishes their addresses, then the prefill server writes the KV pages straight into decode memory. |
| 6.8 | Every transfer moves forward through bootstrapping, waiting, and transferring to success, and any stage can end in failure. |
| 6.9 | The gateway checks load balance first, then sends a request to the server with the longest match only when more than 30 percent of its text matches. |
| 7.1 | Only a SIGTERM to the main process drains running requests, and a forced exit or a signal to the process group stops work in progress. |
| 7.2 | Measure first, then fix memory, prompts, and concurrency, and only then touch kernels, parallelism, and disaggregation. |
| 7.3 | SGLang and the trainer never hold the GPU at the same time in this mode, and SGLang gets its KV cache back only after the new weights arrive. |
| 7.4 | A weight update is a session: pause, begin, send every bucket, end with one repack, set the version, and resume. |
| 7.5 | On one GB10, the trainer phases took 1.8 times as long as the SGLang rollout, and the weight update took under a second. |
| 7.6 | Over 48 steps the raw reward went up from a mean of 0.636 to 0.758, and the share of cut samples went down from 0.33 to 0.08. |
How this manual was made
This page records the version, the sources, the machines, and the capture kits behind every fact and number in the manual.
The version
The manual pins SGLang 0.5.22, tagged on 2026-10-13 at commit baa9befa381511cd4d56f83980951e5a45fffc6d. The facts were verified on 2026-10-16. SGLang releases about every three weeks, and several defaults changed between 0.5.20 and 0.5.22. A recipe written for an older version can be wrong at this one, and the sections say where.
The sources, ranked
Facts come from seven sources, ranked by authority. When two of them disagree, the higher one wins and the text says so.
| Rank | Source | What the manual takes from it | Cited as |
|---|---|---|---|
| 1 | the SGLang source at the tag, baa9befa | every default and every mechanism | the file list in the Sources line of each section |
| 2 | the captured runs on the Mac and on the GPUs | every listing and every number marked as measured | the capture file name |
| 3 | SGLang issues and pull requests | incidents and the design history of each feature | issue and its number |
| 4 | papers | the original design of RadixAttention and the methods SGLang implements | paper and a title |
| 5 | the SGLang documentation at the tag | documented behaviour, checked against the code | docs and a heading |
| 6 | independent field reports | GPU setups that we could not run, such as many GPUs in one server | field, the author, and the month |
| 7 | SGLang team and vendor reports | claims, always labeled as the claim of the author | team or the vendor, and the month |
The documentation ranks below the code on purpose. At 0.5.22 the documentation still lists two attention backends that the code removed. It also gives other HiCache prefetch timeouts than the code uses. When we say the default, we mean the value the code sets.
Four kinds of evidence
Every number in this manual carries one of four labels in the text.
We measured: the number comes from our runs on the Mac or on the GPUs, recorded on the machines in the tables below. You can run the kit and get the same facts.
The code: the default or the mechanism comes from the SGLang source at the tag. The Sources line names the files.
A field report: an engineer or a company outside the SGLang team ran SGLang and published the result. The text names them, the month, the version when they stated it, and what they tuned.
The team reports or the vendor reports: the SGLang team, RadixArk, or a hardware vendor published the number. We repeat it as their claim and set it against independent results where they exist.
DeepEP and prefill-decode disaggregation across many GPUs need hardware that we did not have. For those sections, the code and the field reports carry the argument, and the label says so.
The capture kit
The capture kit starts the real SGLang server on Apple silicon through its MLX backend. It sends requests, runs the official benchmark, and writes what it sees to its output folder. python3 capture/run.py records everything. python3 capture/run.py --check records again into a temporary directory and compares the facts that must not change. Those facts are the generated text at temperature 0, the token and cached-token counts, and the request counts. The KV bytes per token and the metric names are facts too.
Timings change on every run, so the check does not compare them.
The kit needs SGLang 0.5.22 with its MLX extra on Apple silicon, so it cannot run in the repository CI. Without that setup, --check prints skipped with the reason and exits 0. Every file of the Mac runs was recorded on one machine:
| Item | Value |
|---|---|
| Host | an Apple silicon laptop, macOS 26.2, build 25C56, arm64 |
| SGLang | 0.5.22, installed from the tag with the srt_mps extra |
| Frameworks | PyTorch 2.13.0, MLX 0.32.4, Python 3.12.12 |
| Model | mlx-community/Qwen3-0.6B-4bit |
| Server flags | SGLANG_USE_MLX=1, --disable-cuda-graph, --enable-cache-report, --enable-metrics, --mem-fraction-static 0.4 |
| Recorded on | 2026-10-16 |
The kit starts four servers. They are the default configuration, one without the radix cache, one without the overlap scheduler, and one with a 4,096-token pool. The server without the overlap scheduler crashed on its first real batch at 0.5.22, and the kit records that crash on purpose. Section 2.4 reads it.
The GPU kit
The GPU kit runs the same idea on an NVIDIA GPU. Its run script starts eight server configurations and writes the GB10 run logs. The sweep script repeats each benchmark point with three seeds and records the GPU clock and temperature of every run. The summary script writes one summary for each machine: the GB10 summary data, the L4 summary data, and the throttled L4 summary data. The Miles summary script writes the Miles summary data. The charts read those four files.
Each row below is one sweep of the GPU kit. The link opens its summary file, and each section gives the date and the clocks of the runs that it uses.
| Experiment | Hardware | Configurations | Seeds per point | Data |
|---|---|---|---|---|
| load | NVIDIA GB10 | 8 | 3 | Raw runs |
| prefix | NVIDIA GB10 | 2 | 3 | Raw runs |
| rate | NVIDIA GB10 | 4 | 3 | Raw runs |
| waves | NVIDIA GB10 | 4 | 3 | Raw runs |
| working-set | NVIDIA GB10 | 1 | 3 | Raw runs |
| mixed | NVIDIA GB10 | 5 | 3 | Raw runs |
| load | NVIDIA L4, throttled | 4 | 3 | Raw runs |
| rate | NVIDIA L4, throttled | 2 | 2 to 3 | Raw runs |
| load | NVIDIA L4 | 11 | 3 | Raw runs |
| rate | NVIDIA L4 | 5 | 3 | Raw runs |
| prefix | NVIDIA L4 | 7 | 3 | Raw runs |
| waves | NVIDIA L4 | 5 | 3 | Raw runs |
| working-set | NVIDIA L4 | 2 | 3 | Raw runs |
| mixed | NVIDIA L4 | 4 | 3 | Raw runs |
| plain | see the section | 1 | 1 | Raw runs |
| true-on-policy | see the section | 1 | none, the job stopped before its first rollout | Raw runs |
| true-on-policy-fa3 | see the section | 1 | none, the job stopped before its first rollout | Raw runs |
| plain-48 | see the section | 1 | 1 | Raw runs |
| plain-48-s2 | see the section | 1 | 1 | Raw runs |
| plain-48-s3 | see the section | 1 | 1 | Raw runs |
Every GB10 run log and the GB10 summary data were recorded on one machine:
| Item | Value |
|---|---|
| Host | an NVIDIA DGX Spark, Ubuntu 24.04, aarch64 |
| GPU | NVIDIA GB10, compute capability 12.1, 121.7 GiB of memory shared with the CPU |
| SGLang | 0.5.22 from PyPI, sglang-kernel 0.4.9, flashinfer 0.7.1 |
| Frameworks | PyTorch 2.14.1+cu130, CUDA 13.0, driver 580.159.03, Python 3.12.3 |
| Models | Qwen/Qwen3-30B-A3B-Instruct-2507, its FP8 checkpoint, and the EAGLE-3 draft lmsys/SGLang-EAGLE3-Qwen3-30B-A3B-Instruct-2507-SpecForge-Nex |
| Server flags | --enable-cache-report, --enable-metrics, --mem-fraction-static 0.7 |
| Recorded on | 2026-10-16 |
The kit also has an l4 profile for Qwen3-8B on an NVIDIA L4, which wrote the L4 run logs and the L4 summary data. Part 1 uses that L4 server for its listings. Our first L4 sweep ran hot and throttled, and section 5.1 tells it as an incident. We then ran the L4 again with a cool-down to 72°C before each run. Section 4.3, section 4.4, and section 5.1 use those runs, and section 5.1 shows that the cooled card still lowered its clock under long load.
Conventions
sglang serve starts the server in every command. The older python -m sglang.launch_server still works at 0.5.22 and prints a deprecation warning. Ports are the default 30000. ~ stands for the home directory in recorded output.
Citations name a place. {{issue #35129}} names an issue in the SGLang repository. {{field Jarvislabs 2026-05}} names a field report by its author and month, and the text links it. The SGLang source files a section was written from are listed once, in the Sources line at its end. A listing copies lines from a capture file unchanged, and a … marks a cut that the note explains.
Figures animate on the web, where a Replay button runs the steps again. Print and reduced motion show the final frame.
SGLang 101, edition 2026.10, by Rohit Ghumare. It is part of AI Engineering from Scratch, an open source course at aiengineeringfromscratch.com. The newest edition is always at aiengineeringfromscratch.com/manual-sglang-101.html.
SGLang 0.5.22 is the subject, at commit baa9befa381511cd4d56f83980951e5a45fffc6d of 2026-10-13, checked on 2026-10-16. Every listing comes from a recorded run of the capture kit in the manual's source directory, and every rule is written in our own words from a declared source.
© 2026 Rohit Ghumare · MIT license. You can copy and share this manual. Keep this page and the copyright line with it. Report an error at github.com/rohitg00/ai-engineering-from-scratch/issues.