Inside SGLang-Omni (5): Making It Fast — Radix Cache, CUDA Graphs, torch.compile, Speculative Decoding
Series:
- Architecture, traced through one transcription request
- Streaming: SSE token deltas vs. realtime re-decoding
- Keeping audio off the LLM’s critical path
- The data plane: ZMQ, CUDA IPC, and KV page transfer
- Making it fast: radix cache, CUDA graphs, torch.compile, speculative decoding (this post)
- Running Qwen3-ASR on a 12 GB RTX 5070
Code links point at upstream commit 8f07378.
Most of SGLang-Omni’s speed comes from SGLang itself. This post separates what’s inherited from what the omni layer adds. The additions mostly come from two facts about audio models: much of their compute isn’t the LLM at all, and several stages often share one process.
1. The radix cache
The upstream mechanism
SGLang keeps three structures:
token_to_kv_pool one big GPU array of KV "slots"; 1 slot = 1 token
req_to_token_pool per running request: position i → slot
radix tree token-id sequences → slot indices of KV already computed
A radix tree is a compressed trie whose edges hold runs of tokens. Here’s how a request uses it:
- Match: when a request is admitted,
match_prefixwalks the tree as far as the tokens agree. - Lock: it locks that path so eviction can’t remove KV the request depends on.
- Prefill only the remainder. This is where time-to-first-token is saved.
- Insert while building: during chunked prefill, KV that’s still being built is inserted, so concurrent requests can already share it.
- Insert on finish: when the request finishes, its full sequence is inserted. Duplicate slots are freed, and the path is unlocked.
- Evict: when slots run out, unlocked leaves are evicted in LRU order.
Finished requests don’t release their KV immediately. It stays in the tree as cache until memory pressure evicts it.
What the omni layer adds
First, it picks the cache variant (create_tree_cache). For LRU that’s EvictHeapRadixCache, a subclass that keeps its eviction heap between evict() calls instead of rebuilding it each time; the eviction order is the same as upstream. Sliding-window and session-based models get the matching unified variants. Hybrid linear-attention models with the radix cache turned on are rejected at startup, because the cache can restore attention KV but not recurrent state, and a “hit” would resume with the wrong one.
Second, it keeps different audio from colliding. In Qwen3-ASR, the audio shows up in input_ids as N repeated <|audio_pad|> tokens, so two different clips of the same length would produce identical token IDs. The request builder guards against that twice. It replaces the pad tokens with a value derived from the audio hash, which is standard SGLang multimodal practice. It also sets Req(extra_key=audio_fingerprint); as I understand SGLang’s extra_key, prefixes only match between requests with the same key.
So different audio files share no prefix, not even the identical system prompt. ASR gets radix hits only for repeated audio. The reuse that matters more for ASR is the pre-LM embedding cache from part 3.
Third, it keeps stale KV out after a weight update. The scheduler bumps an epoch and appends :weights:{epoch} to cache keys (apply_prompt_cache_epoch), including requests already in the waiting queue. KV computed with the old weights can then never match a request running on the new ones, which matters for RL rollouts.
Finally, some models don’t decode plain tokens at all. MOSS-TTS Local decodes frames (a text channel plus 12 RVQ codebooks), but the radix tree needs one integer per position. A Triton kernel hashes each frame row into a single “radix token ID” on the GPU. That avoids a GPU→CPU sync on every frame, which would otherwise rule out CUDA graph capture (design note).
2. CUDA graphs
At small batch sizes, a decode step is hundreds of tiny kernels. The CPU launching them becomes the bottleneck. A CUDA graph records the launches once and replays them with a single call. The price is fixed shapes, fixed buffer addresses, no host syncs during capture, and a private memory pool per graph.
The repo uses graphs at three levels.
Level 1: SGLang decode graphs
Upstream’s CudaGraphRunner captures one decode graph per batch size, and is used unchanged. Qwen3-ASR captures every size from 1 to cuda_graph_max_bs instead of upstream’s sparse list. The comment says “exact-size replay avoids resetting padded slots”. It also enables prefill graphs for small prefill batches (engine_builder.py).
Level 2: graphs owned by the model
Encoders, vocoders, flow and DiT steps, and codebook loops aren’t SGLang code, so models capture them themselves through a platform-neutral backend (platforms/device_graph.py). The same code then works on CUDA/HIP/MUSA, Ascend NPU, and Intel XPU. About 28 files use it.
The Qwen3-ASR encoder (encoder_cuda_graph.py) is a good example. The convolutional front end reads each clip’s length, so it stays eager; only the 24-layer transformer stack is captured. By then the batch is packed as [total_tokens, hidden], so a single dimension picks the bucket, and the buckets are powers of two from 128 up to max_batch × max_tokens_per_clip.
Each bucket is warmed up three times on a side stream before it’s recorded, so cuBLAS handles, autotuning, and allocator growth all happen outside the recording. At replay, the encoder picks the smallest bucket that fits, pads with dummy attention windows so segment boundaries stay valid, copies into the static buffers, replays, and clone()s the output before the next replay overwrites it.
Every bucket gets its own memory pool. Graphs can only share a pool safely if they replay in capture order, and here the bucket depends on clip length, so any order is possible. A bucket that fails to capture just stays eager.
Level 3: the metadata glue graph
Attention metadata preparation before each decode step is itself a set of small kernels, and SGLang can capture it. The omni layer replaces that capture function for an omni-specific reason (metadata_glue.py): “torch.cuda.graph synchronizes the live encoder on entry.” The pre-LM encoder is running concurrently on another stream, and a device sync on every capture would stall it. So the code calls capture_begin(capture_error_mode="thread_local") on its own stream instead.
Problems specific to omni
| Problem | Cause | Handling |
|---|---|---|
| capture invalidated by another thread | co-located stages run in sibling threads; CUDA’s default global capture mode fails on any thread’s launch | capture_error_mode="thread_local" |
| capture stalls a concurrent stage | torch.cuda.graph() syncs on entry | dedicated capture streams, side-stream warmups |
| host syncs in the decode loop | e.g. hashing frames on the CPU | move the work onto the GPU (Triton radix hash) |
| graphs that share a pool or stream torn down at different times | dangling graphs | tear them down together (Qwen3-TTS codec graphs) |
3. torch.compile
torch.compile and CUDA graphs solve different problems, and they stack. Compile (Inductor) fuses small ops into fewer generated kernels. A graph then replays those kernels without per-launch CPU overhead.
The engine compile
Compile is on by default: any AR stage that doesn’t say otherwise gets compiled (server_args_builder.py). CI sets SGLANG_OMNI_TORCH_COMPILE_DEFAULT=0 so its speed thresholds measure the eager baseline. torch_compile_max_bs limits compiled decode graphs to small batches (Qwen3-ASR uses 2) to bound compile time and memory, and TORCHINDUCTOR_CACHE_DIR is pinned to ~/.cache/sglang-omni/torchinductor so restarts reuse the generated kernels.
Qwen3-ASR sets SGLANG_TORCH_COMPILE_MODE=default rather than max-autotune. The comment’s reason is that “max-autotune races each kernel’s configs at boot… so a slower config can win and serve until restart.”
The least obvious piece is the KV pool. With compile on, the standard pool is swapped for SeparateKVAllocationsPool (source). Inductor writes in place to only one input per storage, so if K and V share an allocation, it clones the whole buffer on every decode step. Giving them separate allocations removes that hidden copy.
Compiles owned by models
About 20 non-LLM components compile themselves. Some examples:
- Fun-ASR’s audio tower uses
dynamic=True. It warms up with at least 2 frames, because Dynamo always specializes sizes 0 and 1. - MOSS-Transcribe-Diarize’s Whisper encoder uses
dynamic=Falsewith fixed chunk buckets warmed up at startup. - MiniCPM-o’s flow blocks use
fullgraph=Truewithemulate_precision_castsso bf16 rounding matches eager. - The opposite case: Qwen3-TTS’s hand-written CuteDSL kernels are marked
@torch.compiler.disable. Dynamo can’t trace into them, so they run as opaque calls inside otherwise compiled code.
The rule of thumb in the codebase: dynamic=False only with fixed buckets warmed up at startup, dynamic=True for variable-length audio, and always warm up before the server reports ready.
4. Speculative decoding
A cheap draft model proposes k tokens, and the target model verifies all of them in one forward pass. With greedy decoding, the output is identical to the target running alone. ASR is a good fit, because the transcript is tightly determined by the audio, so drafts get accepted often.
The draft registry pins each draft to an exact Hugging Face revision, its engine settings, and its license. Drafts whose model card states no license stay off by default. Algorithms in use include DFLASH (Qwen3-ASR, MOSS-TD, the Qwen3-Omni thinker), EAGLE3, STANDALONE (a distilled Whisper), and DSPARK.
DFlash, as configured here, reads the target model’s hidden states from selected layers. It takes the last committed token plus block_size-1 mask tokens and proposes the whole block in one parallel forward pass.
Getting the ASR draft to load takes some adapting (dflash_draft.py). It was trained in the speculators format, so the adapter writes a flat SGLang config and symlinks the weights. It also shifts layer IDs by one: speculators’ aux ID i reads the residual stream before layer i, which SGLang records as layer i−1. Get that wrong and acceptance quietly collapses, with no error anywhere.
The draft also has its own head. SGLang’s built-in DFlash draft borrows the target’s LM head, but this one trained a smaller head over a subset of the vocabulary, plus a table that maps draft token IDs to target IDs. Both run inside the draft’s CUDA graph and write to fixed output storage.
On the target side, the target is an omni model rather than a plain LLM (target_worker.py). Prefill goes through the omni runner so the audio embeddings get injected. Verify uses the plain SGLang forward, followed by the same logits hooks a normal decode row gets, such as codec-token suppression; without them, verify could accept tokens that normal decoding would never produce. Under a draft, Qwen3-ASR’s “async decode” becomes SGLang’s speculative overlap scheduler, which a recent change made the default.
Each round commits anywhere from 1 to k+1 tokens per request. Those go through the same stream builder as SSE, so stream=true still works; the deltas just arrive in bursts. To see how well the draft is doing, pass return_spec_tokens_details=true, and the response’s sglext field includes spec_accept_length, spec_accept_rate, a histogram of accepted drafts, and the number of verify rounds.
Speculative decoding pays off most at low concurrency, where a verify round costs about the same as a single decode step. It costs extra memory for draft weights, draft KV, and draft graphs. For Qwen3-ASR it currently requires one CUDA GPU with TP=1.
Try it: measure each feature on a 12 GB card
Same RTX 5070 and launch flags as in part 1. For the timings, I sent 10-second LibriSpeech clips, each a distinct, never-seen clip, to a freshly started server, after 5 discarded warmup requests:
- c=1: 40 requests one at a time
- c=2: 40 requests, two at a time
- c=8: 64 requests, eight at a time
The numbers are wall-clock times from the client. They come from one run each, not the repeated runs a proper benchmark would use.
1. The radix cache, and why ASR barely uses it
SGLang logs every prefill batch. Sending the same clip twice, then a different one:
Prefill batch, #new-seq: 1, #new-token: 142, #cached-token: 0, ... # clip X
Prefill batch, #new-seq: 1, #new-token: 1, #cached-token: 141, ... # clip X again
Prefill batch, #new-seq: 1, #new-token: 142, #cached-token: 0, ... # clip Y
The repeat reuses 141 of its 142 prompt tokens. The different clip reuses none, even though both prompts start with the same system turn. That’s the extra_key=audio_fingerprint namespacing at work: requests with different audio never share KV.
For contrast, Qwen3-TTS from part 4 doesn’t salt its keys this way. Two different sentences cloned from the same reference clip shared the reference prefix:
Prefill batch, #new-seq: 1, #new-token: 35, #cached-token: 23, ... # new sentence, same reference
Prefill batch, #new-seq: 1, #new-token: 1, #cached-token: 57, ... # identical request again
2. CUDA graphs: on vs. off
Restart with both graph layers off: --asr.engine.disable_cuda_graph true --asr.factory.enable_encoder_cuda_graph false.
| graphs on | graphs off | |
|---|---|---|
| startup to healthy | 27 s | 18 s |
| GPU memory after startup | 10.00 GiB | 8.95 GiB |
| c=1 p50 latency | 227 ms | 281 ms (+24%) |
| c=8 throughput | 23.0 req/s | 19.6 req/s (−15%) |
The graphs cost 9 seconds of startup and about 1 GB, and pay it back with a quarter less latency per request. The c=1 gap is larger, which fits the explanation earlier in this post: at small batch sizes, the CPU launching kernels is the bottleneck, and replaying a graph removes it.
3. torch.compile: on vs. off
Restart with --asr.engine.enable_torch_compile true, once with an empty TORCHINDUCTOR_CACHE_DIR (cold) and once reusing it (warm):
| compile off | compile on | |
|---|---|---|
| startup, cold Inductor cache | 27 s | 51 s |
| startup, warm Inductor cache | 27 s | 39 s |
| c=1 p50 latency | 227 ms | 217 ms (−4%) |
| c=2 p50 latency | 258 ms | 255 ms (−1%) |
| c=8 throughput | 23.0 req/s | 23.1 req/s |
The generated kernels took only 12 MB of cache. The result matches the design: Qwen3-ASR compiles only batch sizes 1–2 (torch_compile_max_bs: 2), so the gain shows at c=1 and disappears by c=8. Here, compile buys about 10 ms per request at c=1 and costs 12–24 s at every startup. That’s why the profile I’m running leaves it off.
4. Speculative decoding: DFlash fits in 12 GB
Add the draft from the registry:
--asr.engine.speculative_algorithm DFLASH \
--asr.engine.speculative_draft_model_path wilsonzheng0327/Qwen3-ASR-1.7B-dflash \
--asr.engine.speculative_draft_model_revision d62bd4051e68282e02f93de774036a35f22f1373 \
--asr.engine.speculative_num_draft_tokens 8
It started in 45 s and fit: 10.42 GiB after startup, versus 10.00 GiB without the draft. The draft weights, its KV, and its CUDA graphs add about 0.4 GB.
| baseline | DFlash | |
|---|---|---|
| c=1 p50 latency | 227 ms | 76 ms (3.0× faster) |
| c=2 p50 latency | 258 ms | 92 ms |
| c=8 throughput | 23.0 req/s | 43.0 req/s (1.9×) |
This was the biggest effect in the whole series. Asking for the acceptance stats with -F return_spec_tokens_details=true shows why:
"sglext": {"spec_tokens_details": {"spec_accept_rate": 0.8, "spec_accept_length": 6.6,
"spec_num_correct_drafts": 28, "spec_num_proposed_drafts": 35, "spec_verify_ct": 5,
"spec_correct_drafts_histogram": [0, 0, 1, 0, 0, 1, 0, 3]}}
A ~35-token transcript took 5 verify rounds instead of ~35 decode steps. Each round committed 6.6 tokens on average, and three of the five accepted all 7 draft tokens (the last histogram bucket). Across the clips I checked, the accept length was 5.6–6.6. The transcript for the part 1 clip came out word-for-word identical to the baseline, as expected with greedy decoding. I only compared a few clips by eye, though, not a full WER run.
The gain held at c=8 too (1.9×), better than “pays off mostly at low concurrency” suggests. At 8 running requests on this card, verify rounds still cost much less than the decode steps they replace. The full SeedTTS run in part 6 confirms it: WER and CER are unchanged across all 9,324 scored requests, and throughput roughly doubles at every concurrency level. DFlash is the first thing I’d turn on for Qwen3-ASR on a small card.
Looking back
Most of what makes SGLang-Omni different from plain SGLang comes from stages sharing a process and a GPU. Thread-local graph capture, the encoder’s private stream, record_stream, and the cache namespaces all exist because something else is running next to the LLM. The other habit I kept noticing is falling back instead of failing: graph buckets drop to eager, failed batches retry item by item, and a failed metadata capture just runs eagerly.
Part 6 puts all of this under load on a 12 GB consumer GPU.