Inside SGLang-Omni (3): Keeping Audio Off the LLM's Critical Path
Series:
- Architecture, traced through one transcription request
- Streaming: SSE token deltas vs. realtime re-decoding
- Keeping audio off the LLM’s critical path (this post)
- The data plane: ZMQ, CUDA IPC, and KV page transfer
- Making it fast: radix cache, CUDA graphs, torch.compile, speculative decoding
- Running Qwen3-ASR on a 12 GB RTX 5070
Code links point at upstream commit 8f07378.
An autoregressive decode loop is a shared resource. Anything that blocks it stalls every running request. A speech request needs a lot of preparation before it can decode: decode the audio file, resample, run a mel FFT, tokenize, build the prompt, and run a 24-layer audio encoder. Doing any of that on the scheduler thread, or inside the LLM’s prefill, shows up as stutter for everyone else.
SGLang-Omni moves this work out of the way twice. CPU-side preparation runs on a request build thread pool. The audio tower runs in a pre-LM encoder service, on its own thread and CUDA stream, with a cache in front. What ties the two together is deferred admission: a request can be built before its embedding exists, and it simply isn’t admitted until the embedding arrives.
The request build thread pool
OmniScheduler owns a plain ThreadPoolExecutor, set up here. Each worker runs the model’s request_builder(payload), which returns one of two things:
- a finished request object holding an SGLang
Req, or - a
DeferredAdmission(value, ready=future): “built, but don’t admit it until this future resolves”
| Knob | Qwen3-ASR default | Meaning |
|---|---|---|
request_build_max_workers | 8 | threads; 1 means no pool, builds run inline |
request_build_max_pending | 32 | maximum builds submitted to the pool at once |
| backlog limit | max(max_pending, max_queued_requests) | payloads waiting before submission; past this, reject |
| admission wait | 2 ms | how long the loop waits for the oldest build after submitting |
With tensor parallelism greater than 1, the pool is turned off and builds run with one worker. Every TP rank has to admit requests in exactly the same order, and threads finishing in different orders on different ranks would break that.
The four places a request can be
flowchart TD
IN["inbox payload"] --> ST{"stage_request_build_payloads()"}
ST -->|"queue full"| REJ["rejected: QueueFullError → HTTP 503"]
ST -->|"no free pool slot"| BL["backlog (deque)<br/>waiting for a pool slot"]
ST -->|"slot free"| PB["pending_request_builds<br/>building in the pool"]
BL -->|"a slot frees up"| PB
PB -->|"drain: finished request"| ENQ["enqueue_built_request()<br/>→ SGLang waiting_queue"]
PB -->|"drain: DeferredAdmission"| PA["pending_request_admissions<br/>waiting on the encoder future"]
PA -->|"future resolved"| ENQ
The queue-full check counts all of these together: waiting, building, awaiting admission, and backlogged (queued_admission_count). Backpressure therefore applies to requests that haven’t reached SGLang yet.
One pass of the scheduler loop
process_input_requests runs before each batch selection:
- It first drains anything that finished since the last pass.
- It allocates capacity (
stage_request_build_payloads). The backlog gets free slots first, oldest first, so new arrivals can’t overtake it. New payloads then take what’s left, wait in the backlog, or are rejected. - It submits each selected payload to the executor.
- It waits briefly, up to 2 ms for the oldest pending build. A fast build, such as a cache hit, then gets admitted in this same pass instead of the next.
- It drains again.
Admission order
By default the drain is strictly FIFO. It stops at the first unfinished build even if later ones are done, so a slow 30-second clip can’t be overtaken by short ones. The exception is async_prefill (on for Qwen3-ASR on CUDA when no draft model is configured). In that mode the drain takes any finished build, so one slow build can’t hold the others back.
While builds are pending, the idle loop sleeps 100 µs instead of blocking on the inbox, so finished builds are picked up almost immediately.
The pre-LM encoder service
Without this service, SGLang’s multimodal path runs the audio tower inside prefill:
flowchart TD
subgraph PF["one prefill batch: the whole AR loop waits for all of it"]
direction TB
M["mel"] --> T["audio tower<br/>24 layers"] --> E["splice embeds"] --> P["LLM prefill"]
end
With it:
flowchart TD
B["request-build thread"] --> W["encoder worker thread<br/>own CUDA stream"] --> A["embedding attached"]
subgraph AR["AR scheduler loop"]
direction TB
D["decode, decode, decode ..."] --> PF["prefill (LLM only)"]
end
A -->|"admits only ready requests"| PF
The audio encoder for upcoming requests runs at the same time as the LLM decodes. Prefill only copies precomputed embeddings into place. The framework base class is PreLMEncoderServiceBase. The models that implement it are Qwen3-ASR, Fun-ASR, Whisper, ARK-ASR, and MOSS-Transcribe-Diarize. I’ll follow Qwen3-ASR’s.
Construction order matters
- SGLang captures its LLM decode CUDA graphs.
- The encoder layer-stack graphs are captured, one per token-count bucket.
- Only then is the encoder service created, so its private stream “never interleaves with graph capture.”
1. Cache lookup before the mel FFT
Inside the request builder, the audio is decoded and fingerprinted, and the number of audio tokens is estimated from the sample count. Then the embedding cache is checked. On a hit, the mel FFT is skipped entirely, and repeated audio never enters the encoder queue.
2. Wait or defer
On a miss, the builder computes mel features, validates the prompt, and then decides (source):
# request_build_queue_fits_workers(): pending + backlog <= max_workers
if should_wait_for_encode():
audio_encoder_service.encode_item(audio_item) # block this build thread
return req_data
return DeferredAdmission(value=req_data, ready=audio_encoder_service.submit_item(audio_item))
Under light load the build thread just blocks on the encode. Nothing else is waiting on that thread, and blocking keeps the timeout and failure counting simple. Under heavy load the builder returns DeferredAdmission instead, which frees the thread to prepare the next request’s audio while the encoder works, and admit_or_defer_built_request holds the request until its future resolves.
Either way, a request is never admitted without its embedding. A failed encode fails the request before it reaches the LLM.
3. Single-flight deduplication
flowchart TD
K["key = namespace : audio_fingerprint"] --> H{"cached and valid?"}
H -->|yes| HIT["attach the embedding,<br/>return a completed future"]
H -->|no| F{"same key already<br/>being encoded?"}
F -->|yes| FOL["FOLLOWER: wait on the<br/>leader's future"]
F -->|no| LEAD["LEADER: register in inflight,<br/>enqueue the encode"]
Ten identical uploads arriving together produce one encode. The leader re-checks the cache under the lock before starting, so a stale miss can’t start a duplicate encode right after another leader cached the result.
4. Greedy batching
A single daemon thread takes the first queued item. It then takes more only if they’re already waiting, up to max_batch_size=8. With the default max_batch_wait_ms=0 it never waits for more to arrive. The comment explains: at concurrency 1, a batching window is pure added latency. Under load, items that queued during the previous encode are taken immediately, so batches still form.
5. Executing a batch
On the private stream, under inference_mode:
- Encode.
get_audio_featureruns the convolutional front end eagerly. The 24-layer stack replays a bucketed CUDA graph when one fits (covered in part 5). - Split. The output is checked against the expected token counts, hidden size, and dtype, then split per item and cloned, so a cached embedding doesn’t hold a reference to the whole batch tensor.
- Attach. The embedding is set as
item.precomputed_embeddings, and the mel features are dropped. This step also callsembedding.record_stream(default_stream). Without it, the CUDA caching allocator could reuse that memory for the next encoder batch while the LLM, on the default stream, is still reading it. - Synchronize. This waits for the encoder stream only. The LLM isn’t blocked.
- Cache. The result goes into an LRU on the CPU (2 GiB, 4096 entries by default).
- Resolve futures, which admits the waiting requests.
Correctness and failure handling
The cache namespace is a digest of the model path, the full model config, the feature-extractor settings, dtype, attention backend, and device type, so anything that would change the embeddings also changes the key. Hits are still checked on shape, row count, and dtype, and a bad entry is evicted and re-encoded.
Failures stay contained. A failed batch is retried item by item, so one bad clip fails only its own request. After an OOM the service synchronizes the stream and empties the CUDA cache so the next batch can run. If the worker thread dies, it records the error and later submissions fail fast instead of hanging.
One detail I wouldn’t have thought of: exceptions are stripped of their tracebacks before they’re stored on futures. A traceback holds references to stack frames, and after an OOM those frames would keep large encoder tensors alive.
How the pieces fit with prefill coalescing
The last link is in prefill. With prefill_coalesce_requires_pending_builds=True, the scheduler delays prefill briefly, but only while builds or admissions are still in progress (source). Qwen3-ASR holds for up to 16 requests or 40 ms. A burst of ten uploads builds in parallel, finishes at slightly different times, and is then prefilled together instead of in ten separate prefills. When nothing is being built, there’s nothing to wait for, and prefill runs immediately.
What to watch
The encoder service logs a cumulative stats line on its 1st, 51st, 101st, … batch: hits, misses, merged requests, queue wait (average and maximum), items per batch, and cache bytes. If queue_wait_avg_s keeps rising while items/batch sits near 8, the encoder is the bottleneck, not the LLM. For individual builds, the trace events scheduler_request_build_start and scheduler_request_build_end bracket each one.
Also keep in mind that the encoder worker is a Python thread in the same process as the scheduler loop. That’s why the loop explicitly yields the GIL when idle; a code note there says the audio encoder ran about 600× slower without it.
Try it: watch the encoder service work
The server launch is the same as part 1’s, with output saved to server.log. Everything below reads one log line:
grep "pre-LM encoder stage" server.log
The service prints it on its 1st batch and then every 50 batches after that. The counters are cumulative, so to read them after an experiment, push the batch count past the next multiple of 50. All output below is from the RTX 5070 used in part 1, with 10-second LibriSpeech clips.
1. The first request
Send one request, then check the log. The first batch prints immediately:
Qwen3-ASR pre-LM encoder stage: 1 batches, 1 items (avg 1.00 items/batch, last batch: 1),
cache: {'hits': 0, 'misses': 1, 'merged': 0, 'failed': 0, 'cache_hit_rate': 0.0, 'batches': 1, 'items': 1,
'queue_depth': 0, 'queue_wait_avg_s': 3.27e-05, 'queue_wait_max_s': 3.27e-05,
'encoder_time_s': 0.1159, 'cache_entries': 1, 'cache_bytes': 532480, 'cache_evictions': 0}
One miss and one cached embedding. 532,480 bytes is 130 audio tokens × 2048 hidden × 2 bytes (bf16) for 10 seconds of audio. The first encode took 116 ms. Later ones are much faster (step 4).
2. Repeated audio skips the encoder
Send a new clip twice and time both. I did this for three different clips:
for i in 1 2; do
curl -s -o /dev/null -w "request $i: %{time_total}s\n" \
-F file=@c1.wav -F model=qwen3-asr http://localhost:8000/v1/audio/transcriptions
done
c1 request 1: 0.240317s c1 request 2: 0.223335s
c2 request 1: 0.229486s c2 request 2: 0.216537s
c3 request 1: 0.251788s c3 request 2: 0.238101s
The repeat is faster, but only by 13–17 ms out of ~230. The stats line in step 4 shows about 14 ms of encoder time per item when warm (1.33 s across 96 items), so skipping the encoder saves exactly that. At concurrency 1, decoding dominates: generating ~40 output tokens takes far longer than encoding 10 seconds of audio once. The repeat also benefits from SGLang’s radix cache, which matches identical audio because the fingerprint is part of the cache key (part 5). The two effects together still come to only a few percent here. The cache matters for retries and duplicate uploads under load, not for single-request latency.
3. Identical requests in flight share one encode
Send ten copies of a new file at the same moment:
for i in $(seq 10); do
curl -s -o /dev/null -w "%{http_code} %{time_total}s\n" -F file=@fresh.wav -F model=qwen3-asr \
http://localhost:8000/v1/audio/transcriptions &
done; wait
200 0.315542s 200 0.315983s 200 0.316319s 200 0.315048s 200 0.316770s
200 0.316906s 200 0.316754s 200 0.315769s 200 0.543258s 200 0.542749s
The first copy to arrive becomes the leader and encodes. The other nine arrive while it’s still encoding, so they become followers: the stats line in step 4 shows 'merged': 9. The audio was encoded once.
The timings show something else, too. Eight requests finished together in 0.316 s, and two waited until 0.543 s. The server runs with max_running_requests 8, so the ninth and tenth requests had their embeddings ready but had to wait in SGLang’s waiting queue for a decode slot. Deduplication saved encoder work but couldn’t add decode capacity.
4. A burst forms batches
Make distinct clips by trimming one file at different millisecond offsets. Each clip has a different waveform, so a different fingerprint and no cache hit. Then send them 16 at a time:
mkdir -p clips
for i in $(seq 0 199); do
ffmpeg -loglevel error -y -ss "0.$(printf %03d $i)" -i b.wav -ar 16000 -ac 1 clips/$i.wav
done
send() { curl -s -o /dev/null -F file=@"$1" -F model=qwen3-asr \
http://localhost:8000/v1/audio/transcriptions; }
export -f send
ls clips/*.wav | head -120 | xargs -P 16 -I{} bash -c 'send {}'
# Keep sending one at a time until the batch-51 line appears.
for f in $(ls clips/*.wav | tail -80); do
[ "$(grep -c 'pre-LM encoder stage' server.log)" -ge 2 ] && break
send "$f"
done
grep "pre-LM encoder stage" server.log | tail -1
Batching packs several clips into one batch, so the burst alone isn’t guaranteed to reach batch 51. The loop afterwards sends single clips until the line prints. In my run, the line printed partway through the burst and no single clips were needed:
Qwen3-ASR pre-LM encoder stage: 51 batches, 96 items (avg 1.88 items/batch, last batch: 1),
cache: {'hits': 4, 'misses': 100, 'merged': 9, 'failed': 0, 'cache_hit_rate': 0.038, 'batches': 51, 'items': 96,
'queue_depth': 4, 'queue_wait_avg_s': 0.0195, 'queue_wait_max_s': 0.0674,
'encoder_time_s': 1.333, 'cache_entries': 96, 'cache_bytes': 50483200, 'cache_evictions': 0}
The counters are cumulative, so this covers everything since startup. The first five batches were single requests from steps 1 to 3, which leaves about 91 items in 46 batches for the burst: roughly two clips per encode, with no batching window at all (max_batch_wait_ms=0). Clips that queued while the previous batch was encoding got picked up together.
The waits stayed short. Under a 16-way burst, a clip waited 19.5 ms for the encoder on average and 67 ms at most, so the encoder kept up, which fits step 3, where decode slots were the limit. Warm encoding is cheap: 1.33 s of encoder time for 96 items, about 14 ms per 10-second clip.
The rest of the counters account for the earlier steps. merged: 9 is step 3’s nine followers. Three of the four hits are step 2’s repeats; the fourth means two of my trimmed clips came out with identical samples despite the different offsets. misses (100) is higher than items (96) because the line printed mid-burst, with four misses registered but still queued, matching queue_depth: 4.
5. Turn the service off
Restart with the encoder service disabled. The audio tower then runs inside prefill:
--asr.factory.enable_pre_lm_encoder false
I checked that the switch works: with it set, the server never prints a pre-LM encoder stage line, and requests still succeed. At concurrency 1 the timings were the same as with the service on: ~0.23 s per 10-second clip after a 0.48 s warmup request. That’s expected, since the service’s benefit is keeping encoder work out of other requests’ decode steps. Part 6 measures the difference under concurrent load, and it surprised me: on this card, the service comes out roughly neutral. It’s about 9% slower at concurrency 8 and 4% faster at 16. A 10-second clip encodes in ~14 ms, so the queue is almost always empty, and the service runs about one clip per encode while batched prefill can encode several at once. The design pays off when encodes are heavy, not on a single consumer card with a fast encoder.
Next: part 4 leaves single-stage pipelines and looks at how stages talk to each other and move tensors.