Inside SGLang-Omni (2): Streaming — SSE Token Deltas vs. Realtime Re-decoding
Series:
- Architecture, traced through one transcription request
- Streaming: SSE token deltas vs. realtime re-decoding (this post)
- 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
- Running Qwen3-ASR on a 12 GB RTX 5070
Code links point at upstream commit 8f07378.
SGLang-Omni offers two ways to get a transcript incrementally. From the client they look alike. Inside, they have very little in common:
POST /v1/audio/transcriptionswithstream=true: one request, and the text streams out as the model decodes tokens.WS /v1/realtime?intent=transcription: live audio goes in, and the server re-transcribes the current speech segment from scratch every couple of seconds, each time as an ordinary non-streaming request.
Part A: stream=true over SSE
The streaming path reuses the same pipeline as part 1. Only three places behave differently: the HTTP layer delays its response headers, the coordinator delivers results through a queue instead of a future, and the scheduler emits text while it decodes.
sequenceDiagram
participant U as Client
participant H as HTTP handler
participant Co as Coordinator
participant St as Stage asr
participant Sch as OmniScheduler
U->>H: POST /v1/audio/transcriptions (stream=true)
H->>Co: coordinator.stream(): submit with a queue
Co->>St: SubmitMessage (ZMQ)
St->>Sch: inbox.put(payload)
Note over H: response headers held back until the first chunk
loop each decode step (emits throttled to 50 ms)
Sch->>St: stream builder → outbox (type=stream)
St->>Co: StreamMessage (ZMQ)
Co->>H: queue → Client chunk
H-->>U: data: transcript.text.delta
end
Sch->>St: result_adapter → outbox (type=result)
St->>Co: CompleteMessage (ZMQ)
Co->>H: final chunk
H-->>U: data: transcript.text.done, then data: [DONE]
Headers wait for admission
Once SSE headers go out with a 200, you can no longer send a 503 or a 400. So create_speech_to_text_streaming_response waits for the backend’s first chunk before returning the response:
chunk_stream = client.generate(gen_req, request_id=request_id)
first_chunk = await first_speech_to_text_chunk(...) # wait for the first chunk
return ClosableStreamingResponse(speech_to_text_stream(...), media_type="text/event-stream")
Queue-full rejections, bad audio, and invalid parameters all surface during that wait, so they still map to real HTTP status codes. The source comment states the intent: “admit before headers so model validation remains an HTTP error instead of becoming an SSE error event.” While waiting, the handler also watches for a client disconnect and aborts the request if one happens.
Long audio isn’t chunked on this path. Anything longer than the stream clip limit gets a 400 that tells the client to use stream=false.
A queue instead of a future
Coordinator.stream submits the request together with an asyncio.Queue and yields messages until every expected terminal stage has completed. It also tracks a per-request backlog of undelivered bytes, so a slow reader can’t grow memory without limit. Its finally block aborts the request if the consumer leaves early.
On the stage side, a terminal stage with no stream_to targets forwards chunks through send_stream_to_coordinator, numbering them with chunk_id. A non-terminal stage that emits an untargeted stream gets an explicit error instead.
Emitting during decode
After each decode step, emit_stream_output calls the model’s stream_output_builder for each request in the batch. It skips aborted requests and ones that already finished, so no extra chunk slips out after an abort.
Qwen3-ASR’s builder (make_qwen3_asr_stream_output_builder) adds one rule on top of a generic token-to-text builder: it hides the language preamble. With automatic language detection, the model outputs language English<asr_text>…transcript…. The builder suppresses output until the multi-token <asr_text> marker has been seen. It matches the marker one token at a time and keeps the partial match on the request, because the marker can span several decode steps.
The generic builder underneath (scheduling/token_text_streaming.py) detokenizes incrementally and sends only the new text. It emits at most once per stream_emit_interval_s, which is 50 ms for Qwen3-ASR. And if a delta ends in �, only half of a multi-byte character has arrived, so it holds the delta until the next token completes it.
The SSE frames
speech_to_text_stream produces OpenAI-style events:
data: {"type":"transcript.text.delta","delta":"Hello"}
data: {"type":"transcript.text.delta","delta":" world"}
data: {"type":"transcript.text.done","text":"Hello world","usage":{"seconds":3}}
data: [DONE]
One detail I liked: the done event’s text comes from result_adapter, the same function the non-streaming path uses. It isn’t the concatenated deltas. Deltas are only for display, so any mismatch between the stream builder and the final parser can’t reach the final transcript.
The preamble has a cost you can see from the client: time-to-first-delta includes the hidden language preamble. Those tokens are generated but never shown, so passing language= explicitly gets the first visible text out a few tokens sooner.
Part B: the realtime websocket
Realtime transcription doesn’t use token streaming at all. The session keeps buffering audio and periodically re-runs a non-streaming completion over the whole current speech segment. Every partial result is a complete new guess. Almost all of the logic lives in the HTTP process, and the pipeline below just sees short, independent transcription jobs.
flowchart TD
WS["WS /v1/realtime?intent=transcription"] --> S["RealtimeTranscriptionSession<br/>one per socket"]
S -->|"input_audio_buffer.append<br/>base64 PCM16"| B["RealtimeAudioBuffer<br/>16 kHz PCM16"]
B --> VAD["server VAD"]
VAD -->|"speech started"| SEG["active segment"]
VAD -->|"speech stopped, 30 s cut, or commit"| FIN["pending finals queue"]
SEG -->|"every 2 s of new audio"| W["decode worker<br/>one task per session"]
FIN --> W
W -->|"finals first, then one partial"| STR["Qwen3ASRStreamingStrategy<br/>prefix + rollback"]
STR --> C["client.completion()<br/>the non-streaming path from part 1"]
C --> UPD["update_hypothesis"]
UPD --> OUT["to client: transcription.segment<br/>text, is_final"]
Opting in
A pipeline config opts in by declaring a RealtimeTranscriptionConfig. Qwen3-ASR’s sets a streaming strategy class, server-side voice activity detection (VAD), and max_segment_s=30. The decode interval defaults to 2000 ms. The route creates the session before accepting the websocket upgrade, so the connection counts toward the limit before the handshake completes. Without that config, intent=transcription is refused.
Segments and the decode worker
Each RealtimeTranscriptionSession holds:
- a bounded 16 kHz PCM16 buffer, with positions tracked as absolute sample offsets
- a Silero-backed VAD
- exactly one decode worker task, so a session never has more than one request in flight
When audio is appended:
- The VAD detects speech → a segment starts (including prefix padding), and the server sends
input_audio_buffer.speech_started. - The VAD detects the end of speech → the segment is cut out of the buffer, wrapped as WAV, and queued as a final (
input_audio_buffer.committed). - A segment exceeds
max_segment_s→ it’s cut there, finalized, and a new segment starts at the cut. - Between speech turns → silence is trimmed, so the buffer stays small.
- 2 s of new audio has arrived → a partial decode is scheduled.
The worker handles all pending finals first, in order, and then at most one partial. A partial always covers the segment from its start, not just the new audio. Partials whose segment closed while they were running are discarded, and segments that are entirely silence produce an empty final without calling the model.
Prefix and rollback
Re-transcribing a growing segment from scratch wastes work and makes earlier words flicker. Qwen3ASRStreamingStrategy reduces both:
- The first two decodes of a segment run with no prefix, so the language and the first words can settle.
- From the third decode on, once a language is known, it sends the previous transcript as
_asr_streaming_prefix_text, withrollback_tokens = 5. - On the stage side,
retained_streaming_prefixtokenizes that text, drops the last 5 tokens (the newest and least reliable words), backs off any partial UTF-8 character, and feeds the rest in as a forced prefix of the model’s output. - The model then generates only the continuation, and
result_adapterreassemblesprefix + continuation.
So older text stays put, the last few tokens can still change, and each decode generates far fewer tokens.
The wire
sequenceDiagram
participant C as Client
participant S as Server
loop while audio is flowing
C->>S: input_audio_buffer.append (base64 PCM16, 16 kHz)
end
S-->>C: input_audio_buffer.speech_started (segment 0)
S-->>C: transcription.segment "hello" (is_final false)
S-->>C: transcription.segment "hello there how" (is_final false)
S-->>C: input_audio_buffer.speech_stopped
S-->>C: input_audio_buffer.committed (segment 0)
S-->>C: transcription.segment "Hello there, how are you?" (is_final true)
C->>S: transcription.done
S-->>C: transcription.completed (full text, language)
Audio travels as base64 inside JSON text frames, following the OpenAI Realtime convention. Binary frames are rejected: the transcription session answers with an invalid_json error, and the conversation session says binary frames are unsupported outright. Base64 adds about 33% to the size, which hardly matters next to the model cost. Inside the server, the audio is decoded once to raw PCM. Each decode slice is wrapped as WAV bytes, travels to the stage as binary msgpack over ZMQ, and is decoded into a float waveform there.
Comparing the three paths
| non-streaming POST | stream=true SSE | /v1/realtime | |
|---|---|---|---|
| Input | whole file | whole file | live PCM16 chunks |
| Requests per audio | 1 (or 1 per chunk) | 1 | many: a partial every ~2 s, plus a final per segment |
| Incremental text from | — | token deltas | repeated full re-decodes |
| Long audio | server-side chunking | rejected | VAD segments + 30 s cut |
| Lives mostly in | HTTP + pipeline | HTTP + pipeline | the HTTP process (session) |
Capacity follows from this. A realtime speaker generates a steady stream of requests, about one every 2 seconds per active segment plus one per final. Each partial also covers more audio than the last, up to 30 s, so its encoder and prefill cost grows as the segment goes on. decode_interval_ms trades how fresh partials are against how much load they create.
Try it: see both streaming paths
The server launch is the same as part 1’s, plus --enable-realtime for Part B. All output below is from the same RTX 5070.
1. Watch SSE deltas arrive
curl -N turns off buffering, so events print as they arrive. Piping through a line timestamper shows the timing. ts -s '%.s' from moreutils works. I used a five-line Python equivalent that prints the seconds elapsed before each line:
curl -sN -F file=@a.wav -F model=qwen3-asr -F stream=true \
http://localhost:8000/v1/audio/transcriptions | ts -s '%.s'
0.037s data: {"type":"transcript.text.delta","delta":"Mr"}
0.092s data: {"type":"transcript.text.delta","delta":". Quilter is the apostle of the"}
0.148s data: {"type":"transcript.text.delta","delta":" middle classes, and we are glad to welcome"}
0.204s data: {"type":"transcript.text.delta","delta":" his gospel. Nor is Mr. Quilter"}
0.253s data: {"type":"transcript.text.delta","delta":"'s manner less interesting than his."}
0.254s data: {"type":"transcript.text.done","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}}
0.254s data: [DONE]
Deltas come about every 55 ms, several tokens at a time. That’s the 50 ms throttle: the model decodes faster than that, so text piles up between emits. The first delta is just "Mr", whatever had been decoded past the hidden preamble when the first emit fired. And the done event carries the full transcript from result_adapter, not the deltas glued together.
2. The hidden preamble costs time
Run the same request with the language forced:
curl -sN -F file=@a.wav -F model=qwen3-asr -F stream=true -F language=English \
http://localhost:8000/v1/audio/transcriptions | ts -s '%.s'
To keep the caches out of the comparison, I used a different, never-seen clip for every request: five with automatic language detection, five forced, then five automatic again. Here’s the time to the first delta line:
| run 1 | run 2 | run 3 | run 4 | run 5 | |
|---|---|---|---|---|---|
| auto language | 34 ms | 37 ms | 36 ms | 36 ms | 37 ms |
language=English | 19 ms | 19 ms | 18 ms | 18 ms | 18 ms |
| auto language, again | 35 ms | 38 ms | 36 ms | 36 ms | 36 ms |
Forcing the language halves the time to first text, from ~36 ms to ~18 ms. The debug line in part 1 shows why: with automatic detection, the model first decodes three tokens (language, English, <asr_text>) that the stream builder hides. At small batch sizes, a few decode steps are a large share of a 36 ms budget.
3. Watch a realtime session re-decode
Convert a clip to the wire format, which is raw 16 kHz mono PCM16 with no header:
ffmpeg -y -i a.wav -ar 16000 -ac 1 -f s16le a.pcm
This small client sends the audio at real-time pace in 100 ms packets, then prints every event the server sends, with the elapsed time:
# realtime_demo.py — python realtime_demo.py a.pcm
import asyncio, base64, json, sys, time
import websockets
URL = "ws://localhost:8000/v1/realtime?intent=transcription"
CHUNK = 16000 * 2 // 10 # 100 ms of 16 kHz PCM16
async def main(path):
pcm = open(path, "rb").read() + b"\x00" * 16000 * 2 # 1 s trailing silence closes the turn
t0 = time.monotonic()
async with websockets.connect(URL, max_size=None) as ws:
async def reader():
async for raw in ws:
ev = json.loads(raw)
keep = {k: ev[k] for k in ("segment_id", "text", "is_final", "language") if k in ev}
print(f"{time.monotonic() - t0:6.2f}s {ev['type']:38} {keep}")
if ev["type"] == "transcription.completed":
return
task = asyncio.create_task(reader())
for i in range(0, len(pcm), CHUNK):
await ws.send(json.dumps({"type": "input_audio_buffer.append",
"audio": base64.b64encode(pcm[i:i + CHUNK]).decode()}))
await asyncio.sleep(0.1)
await ws.send(json.dumps({"type": "transcription.done"}))
await task
asyncio.run(main(sys.argv[1]))
Here’s a 12-second clip, the same recording as a.wav but 2 seconds longer:
0.09s session.created {}
0.60s input_audio_buffer.speech_started {'segment_id': 0}
2.60s transcription.segment {'segment_id': 0, 'text': 'Mr. Quilter is the apostle of.', 'is_final': False, 'language': 'English'}
4.46s transcription.segment {'segment_id': 0, 'text': 'Mr. Quilter is the apostle of the middle classes, and we are glad to.', 'is_final': False, 'language': 'English'}
6.13s input_audio_buffer.speech_stopped {'segment_id': 0}
6.13s input_audio_buffer.committed {'segment_id': 0}
6.20s transcription.segment {'segment_id': 0, 'text': 'Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.', 'is_final': True, 'language': 'English'}
6.53s input_audio_buffer.speech_started {'segment_id': 1}
8.25s transcription.segment {'segment_id': 1, 'text': "Nor is Mister Quilter's manner.", 'is_final': False, 'language': 'English'}
10.26s transcription.segment {'segment_id': 1, 'text': "Nor is Mister Quilter's manner less interesting than his matter.", 'is_final': False, 'language': 'English'}
10.96s input_audio_buffer.speech_stopped {'segment_id': 1}
10.96s input_audio_buffer.committed {'segment_id': 1}
11.01s transcription.segment {'segment_id': 1, 'text': "Nor is Mister Quilter's manner less interesting than his matter.", 'is_final': True, 'language': 'English'}
11.37s input_audio_buffer.speech_started {'segment_id': 2}
12.67s input_audio_buffer.speech_stopped {'segment_id': 2}
12.67s input_audio_buffer.committed {'segment_id': 2}
12.73s transcription.segment {'segment_id': 2, 'text': 'He tells us.', 'is_final': True, 'language': 'English'}
13.18s transcription.completed {'text': "Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel. Nor is Mister Quilter's manner less interesting than his matter. He tells us.", 'language': 'English'}
The VAD cuts at pauses, not just at the end. The speaker paused after “gospel” and again after “matter”, so one 12-second clip became three segments, each closed by speech_stopped, then committed, then a final.
Partials come about 2 s apart (2.60 → 4.46 s, 8.25 → 10.26 s), and each is a complete transcript of the segment so far. They also get revised. The first one ends "apostle of." with a period, because the model transcribed the audio it had as if that were the end. The next partial re-decodes those last words as "apostle of the middle classes", which is exactly what the rollback is for.
Finals land 50–70 ms after committed, since each is one ordinary non-streaming request over a short segment.
Segmenting has a price, though. The second segment says “Mister Quilter”, while the same audio sent as one HTTP request in part 1 came out as “Mr. Quilter”. Each segment is transcribed without the others as context.
Try {"type": "session.update", "session": {"decode_interval_ms": 1000}} as the first message to make partials twice as frequent. That also doubles the request load on the GPU, as described in the capacity paragraph above.
For proper latency numbers, the repo’s own client records full traces:
python -m benchmarks.eval.benchmark_asr_realtime --port 8000 --max-samples 20 --concurrencies 1
python -m benchmarks.realtime_asr.replay <trace-dir>/000000.json
Part 6 uses it to find out how many concurrent speakers fit on one card.
Next: part 3 covers how audio preparation and encoding are kept out of the LLM’s decode loop.