Inside SGLang-Omni (1): Architecture, Traced Through One Transcription Request

• 12 min read

SGLang-Omni is a serving runtime for omni, speech, and TTS models. Its docs describe each layer’s design well. What I couldn’t find was a walk through the code, following one request function by function. This series is that walkthrough.

Series:

  1. Architecture, traced through one transcription request (this post)
  2. Streaming: SSE token deltas vs. realtime re-decoding
  3. Keeping audio off the LLM’s critical path
  4. The data plane: ZMQ, CUDA IPC, and KV page transfer
  5. Making it fast: radix cache, CUDA graphs, torch.compile, speculative decoding
  6. Running Qwen3-ASR on a 12 GB RTX 5070

All code links point at upstream commit 8f07378. The project moves fast, so file and line references will drift.

What problem it solves

Plain SGLang is very good at one thing: running one autoregressive model with continuous batching, a paged KV cache, and a radix prefix cache. Omni and speech models don’t fit that shape. Qwen3-Omni, for example, chains several models:

flowchart TD
    P["preprocessing"] --> E["image / audio encoders"] --> T["thinker (LLM)"] --> K["talker (LLM)"] --> V["code2wav (vocoder)"]

Each piece has a different compute pattern. Encoders are one-shot and compute-bound. The LLMs decode step by step. Vocoders consume a stream of codes. SGLang-Omni owns the pipeline topology (what runs where and what feeds what), stage lifecycle, inter-stage transport, and an OpenAI-compatible API. It delegates the autoregressive parts to SGLang’s scheduler and model execution.

The layers

flowchart TD
    A["HTTP API"] --> B["Client"] --> C["Coordinator"] --> D["Stage"] --> E["Scheduler"] --> F["ModelRunner"] --> G["model forward"]
LayerWhereResponsibility
HTTP APIsglang_omni/serve/OpenAI schemas, SSE, websockets, HTTP errors
Clientsglang_omni/client/turns an API request into an internal OmniRequest, aggregates results
Coordinatorpipeline/coordinator.pyglobal router: submits to the entry stage, collects terminal results, broadcasts aborts
Stagepipeline/stage/an I/O shell: receives control messages, moves payloads, does fan-in, routes outputs
Schedulerscheduling/the per-stage execution loop, behind an inbox/outbox queue pair
ModelRunnermodel_runner/the forward path for autoregressive stages

Stage never branches on scheduler type. Every scheduler exposes the same surface (an inbox, an outbox, start/stop/abort), so the stage doesn’t care which one it’s driving. There are four main ones:

  • OmniScheduler wraps SGLang’s upstream scheduler for autoregressive stages, reusing its batching, KV cache, and prefill/decode logic.
  • SimpleScheduler is a plain inbox.get() → fn → outbox.put() loop for encoders, preprocessing, and decode.
  • Streaming vocoder schedulers turn a stream of codes into audio chunks.
  • SessionScheduler is for stateful, full-duplex models that keep per-session state.

A model is a config, not a class hierarchy

Each model lives in sglang_omni/models/<model>/. The config.py there declares a PipelineConfig subclass listing StageConfigs. Each stage names three things:

  • a factory (factory_path): the function that builds its scheduler
  • placement (process, gpu): where it runs
  • graph edges (next, stream_to, terminal): what it feeds

Qwen3-ASR is the simplest possible pipeline: one stage, asr, running OmniScheduler, marked terminal=True (models/qwen3_asr/config.py). Qwen3-Omni’s config wires up the full chain above, with stream_to edges from the thinker to the talker and from the talker to code2wav (models/qwen3_omni/config.py).

YAML files in examples/configs/ override those defaults per deployment, and the sgl-omni CLI launches them.

Because Qwen3-ASR has only one stage, it’s the cleanest way to see every layer without cross-stage complexity. The rest of this post follows one request:

curl -F file=@a.wav -F model=qwen3-asr http://localhost:8000/v1/audio/transcriptions

The whole path

sequenceDiagram
    participant U as curl
    participant H as HTTP handler + Client
    participant Co as Coordinator
    participant St as Stage asr (own process)
    participant Sch as OmniScheduler
    U->>H: POST /v1/audio/transcriptions
    H->>H: build GenerateRequest (raw audio bytes)
    H->>Co: Client.completion → submit_request
    Co->>St: SubmitMessage (ZMQ)
    St->>Sch: inbox.put(payload)
    Sch->>Sch: request_builder: decode audio, build prompt, get embedding → SGLang Req
    Sch->>Sch: prefill and decode batches (SGLang)
    Sch->>St: result_adapter → outbox
    St->>Co: route_result → CompleteMessage (ZMQ)
    Co->>H: resolve the future
    H-->>U: JSON response (text, usage)

1. The HTTP handler

create_transcription parses the multipart form, creates a transcription-<uuid> request ID, and rejects segment-timestamp formats (verbose_json) that the model can’t produce. It also reads the duration from the file header, in a worker thread, without decoding the audio.

With stream=true, the request goes off to the SSE path (part 2). Otherwise it’s either a normal single request or long audio. Long audio has to pass a total-duration cap and then get a slot from LongAudioAdmission; if there’s no free slot, the client gets HTTP 503. Once admitted, the handler splits the audio into chunks and transcribes each one as its own request.

That’s why the duration comes from the header. A small compressed file can hold hours of audio, and decoding it just to find out would take gigabytes of memory.

2. A model-neutral request

build_speech_to_text_generate_request builds a GenerateRequest with:

  • prompt = {audio_bytes, filename, content_type}: the raw, undecoded bytes
  • extra_params = {task, language?, prompt?}
  • SamplingParams(temperature=0.0 default, ...)

The HTTP layer knows nothing about Qwen at this point. Model-specific handling happens later, inside the stage.

3. Client and Coordinator

Client.completion iterates over generate() and accumulates text, finish reason, and detected language. A disconnect watcher wraps the call, so when the HTTP client goes away, the pipeline aborts the request.

Coordinator.submit_request picks the entry stage (or one of its replicas), parks an asyncio.Future in completion_futures[request_id], and sends a SubmitMessage over ZMQ. From then on, the HTTP process just waits on that future.

4. The stage

The asr stage runs in its own OS process. Stage.handle_message hands the message to on_submit, which wraps the payload and calls scheduler.inbox.put(...). A single-stage pipeline needs no relay or tensor transfer. Part 4 covers what happens when there are several stages.

5. OmniScheduler: payload to SGLang request

The scheduler loop is easiest to read in event_loop_normal:

while self.running:
    recv_reqs = self.recv_requests()
    self.process_input_requests(recv_reqs)      # payload → SGLang Req
    batch = self.get_next_batch_to_run()        # upstream batch selection
    if batch:
        result = self.run_batch(batch)
        self.process_batch_result(batch, result)
    else:
        self.sleep_during_idle()

Qwen3-ASR actually runs a variant that overlaps decode steps (event_loop_async_decode), but the outline is the same.

Converting a payload into a Req is offloaded to a thread pool, so preparing a new request’s audio doesn’t stall the requests already decoding. Part 3 covers that pool in detail.

6. The Qwen-specific part

request_builder is where the model plugs in:

  • It decodes and resamples the audio to 16 kHz. Undecodable audio raises a ValueError, which becomes an HTTP 400.
  • It resolves the requested language and puts the optional biasing prompt into the system turn.
  • It scales the output token budget with audio length: max(floor, ceil(duration × tokens_per_second)).
  • It gets the audio embedding from a pre-LM encoder service, with a cache and deduplication of identical requests in flight.
  • It builds the SGLang Req with multimodal inputs attached.

SGLang then does what it always does: prefill, then decode in batches, with KV cache and CUDA graphs.

7. Back up the chain

When the request finishes, result_adapter works on the token IDs:

  • It finds the <asr_text> marker. The comment explains why at the token level: byte-level BPE decode→encode isn’t an identity transform for all whitespace and Unicode.
  • It parses an optional language X prefix as the detected language.
  • It decodes the transcript and returns a StagePayload to the outbox.

From there:

  1. Stage.drain_outbox calls route_result. Because asr is terminal, that sends a CompleteMessage.
  2. The coordinator resolves the future.
  3. The client builds a result chunk.
  4. The handler formats it as json, text, srt, and so on.

What I took from the trace

Very little of this is Qwen-specific: a request builder, a result adapter, and an engine builder. The rest is shared framework code.

Backpressure shows up in four places. In order, a request can be turned away by long-audio admission at the HTTP layer (503), the request-build queue limit, the waiting-queue limit, and finally SGLang’s KV capacity.

Aborts travel the same way requests do. When the client disconnects, Client.abort fires, the coordinator broadcasts an AbortMessage over ZMQ PUB/SUB, and the scheduler drops the Req.

Try it: watch one request on your own GPU

Everything below ran on one consumer card: an RTX 5070 with 12 GB, driver 595.99, with the same SGLang-Omni code as the pinned commit. The launch flags shrink Qwen3-ASR’s defaults to fit 12 GB; on a larger card you can drop them. The clips are cut from LibriSpeech recordings: a.wav is the first 10 seconds of one, long.wav a 125-second one.

1. See the config the server will actually run

sgl-omni config resolve prints the merged configuration (model defaults, then config file, then CLI flags) without starting anything:

sgl-omni config resolve --model-path Qwen/Qwen3-ASR-1.7B \
    --asr.engine.max_running_requests 8 \
    --asr.engine.cuda_graph_max_bs 8 \
    --asr.engine.enable_torch_compile false \
    --mem-fraction-static 0.75 \
    --show diff

If you run with HF_HUB_OFFLINE=1, pass the local snapshot directory instead of the repo id; offline, the repo id can’t be resolved to a model architecture. --show diff lists only what the flags changed:

stages.asr.engine.cuda_graph_max_bs: None -> 8
stages.asr.engine.enable_torch_compile: True -> False
stages.asr.engine.max_running_requests: 64 -> 8
stages.asr.engine.mem_fraction_static: None -> 0.75

--show config prints the whole thing. The pipeline from the config section above is all there:

stages:
  asr:
    factory_path: sglang_omni.models.qwen3_asr.stages.create_sglang_qwen3_asr_executor
    next: null
    terminal: true
    gpu: 0
    tp_size: 1
    process: asr

One stage, no next, terminal, in its own process.

2. Start the server and read the startup log

sgl-omni serve --model-path Qwen/Qwen3-ASR-1.7B --model-name qwen3-asr --port 8000 \
    --asr.engine.max_running_requests 8 \
    --asr.engine.cuda_graph_max_bs 8 \
    --asr.engine.enable_torch_compile false \
    --mem-fraction-static 0.75 2>&1 | tee server.log

On the 5070 it reports healthy about 30 seconds after launch. These are the lines I look for:

grep -E "Qwen3-ASR runtime profile|memory checkpoint|captured encoder layer-stack graph" server.log
Qwen3-ASR runtime profile: dtype=auto attention_backend=None mm_attention_backend=triton_attn
    cuda_graph=True cuda_graph_bs=[1, 2, 3, 4, 5, 6, 7, 8] torch_compile=False max_running_requests=8 ...
Qwen3-ASR memory checkpoint=pre_model_load gpu=0 process_gpu_memory=0.16GiB
Qwen3-ASR memory checkpoint=post_static_allocation gpu=0 process_gpu_memory=8.94GiB
Qwen3-ASR memory checkpoint=post_cuda_graph_capture gpu=0 process_gpu_memory=9.51GiB
[qwen3-asr] captured encoder layer-stack graph bucket=128 windows=10 out=(1, 128, 2048)
[qwen3-asr] captured encoder layer-stack graph bucket=256 windows=11 out=(1, 256, 2048)
[qwen3-asr] captured encoder layer-stack graph bucket=512 windows=13 out=(1, 512, 2048)
[qwen3-asr] captured encoder layer-stack graph bucket=1024 windows=18 out=(1, 1024, 2048)
[qwen3-asr] captured encoder layer-stack graph bucket=2048 windows=28 out=(1, 2048, 2048)
[qwen3-asr] captured encoder layer-stack graph bucket=3159 windows=39 out=(1, 3159, 2048)
Qwen3-ASR memory checkpoint=post_encoder_graph_capture gpu=0 process_gpu_memory=10.00GiB

The runtime profile is the engine settings as SGLang will actually use them; cuda_graph_bs=[1, …, 8] is the exact-size decode graph list from part 5.

The memory checkpoints show where the 10 GB goes. 8.78 GB lands at once: the weights plus the KV pool sized by mem_fraction_static. Decode CUDA graphs add 0.57 GB and the encoder graphs another 0.49 GB. There’s one encoder graph per bucket, powers of two from 128 up to a top bucket sized for 8 clips of 30 seconds each.

nvidia-smi shows a single process holding the GPU: 10,236 MiB of the card’s 12,227. The process tree shows which one:

  PID  PPID   RSS  CMD
 8185  8177  1.3G  sgl-omni serve --model-path ...                       # HTTP server + coordinator
 8244  8185   14M   \_ multiprocessing.resource_tracker
 8245  8185  2.9G   \_ multiprocessing.spawn spawn_main ...              # the "asr" stage

The HTTP process doesn’t touch the GPU. The asr stage is a separate, spawned process that owns all of it, which is the “stage runs in its own OS process” step from section 4.

3. Send one request

curl -s -w '\ntime_total=%{time_total}s\n' \
     -F file=@a.wav -F model=qwen3-asr \
     http://localhost:8000/v1/audio/transcriptions
{"text":"Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel. Nor is Mr. Quilter's manner less interesting than his.","usage":{"type":"duration","seconds":10}}
time_total=0.456817s

That first request includes some warmup. Later 10-second clips take about 0.23 seconds end to end on this card.

4. Watch result_adapter see the raw tokens

Restart with --log-level debug and send the same request. The setting reaches the stage process, so result_adapter logs the raw output IDs and the decoded text, including the special tokens it looks for:

grep "\[qwen3-asr\] n_out" server.log
[qwen3-asr] n_out=39 ids=[11528, 6364, 151704, 12275, 13, 3406, 2044, 374, ..., 806, 13, 151645]
    raw="language English<asr_text>Mr. Quilter is the apostle of the middle classes, and we are
    glad to welcome his gospel. Nor is Mr. Quilter's manner less interesting than his.<|im_end|>"

The first three IDs are the preamble: language, English, and <asr_text> (151704). result_adapter searches for that marker at the token level. Everything before it becomes the detected language, and everything after it, up to <|im_end|>, becomes text. Those three tokens are also why the first streamed text arrives later than it could (part 2). Debug logging is very verbose, so switch back to info afterwards.

5. Hit the long-audio limit

Long-audio admission is the first layer of backpressure. Restart with admission capped at one long request, then send three long uploads at once:

# any recording longer than 30 s works; to make one from a short clip:
ffmpeg -y -stream_loop -1 -i a.wav -t 120 -ar 16000 -ac 1 long.wav

# restart the server with this extra flag:
#   --audio_chunking.max_concurrent_long_audio_requests 1

for i in 1 2 3; do
  curl -s -o resp$i.json -w "request $i: HTTP %{http_code} in %{time_total}s\n" \
       -F file=@long.wav -F model=qwen3-asr \
       http://localhost:8000/v1/audio/transcriptions &
done; wait

With the 125-second recording:

request 3: HTTP 503 in 0.013941s
request 1: HTTP 503 in 0.019455s
request 2: HTTP 200 in 0.906714s
{"detail":"Too many long-audio transcriptions in flight (limit 1); retry later, or raise audio_chunking.max_concurrent_long_audio_requests"}

The admitted request transcribed 125 seconds of audio in 0.91 seconds, split into 30-second chunks. The other two were turned away in 14–19 ms. The handler rejects them right after the header-based duration probe, before any audio is decoded.

Without the flag, the default limit is derived from max_running_requests: max(1, max_running_requests // (2 × max_concurrent_chunks)). With this post’s launch flags (8 running requests, 8 concurrent chunks), that’s already 1, so the flag only makes the cap explicit. With Qwen3-ASR’s default of 64 running requests, it’s 4.

Next: part 2 shows that stream=true and the realtime websocket look similar from the outside but work very differently inside.