A batch voice agent cannot start until you stop talking. A streaming stack works while you talk, and a frame-level model like Moshi answers in 200 ms, under the 230 ms gap people leave in conversation.
Pick a system and drag the sentence length. Watch the silence after your last word. Then we build each piece: the causal encoder, the chunk mask, the decoder that commits, the stable prefix, the early synthesizer and the ledger.
You need a spectrogram is sound as a picture and attention means each output looks at some inputs. We build the rest from zero. Background: Audio Representations and Whisper.
Published numbers come from the papers named beside them: Moshi (Défossez et al., 2024), Qwen2.5-Omni (2025), Emformer (Shi et al., 2020) and Whisper-Streaming (Macháček et al., 2023). Every other number on this page is an illustrative toy and says so.
The 200 ms frame-level gap is Moshi's measured latency and 230 ms is the human average it cites (Stivers et al., 2009). The batch and cascade stage times are an illustrative model built in Chapters 5 and 6.
Chapter 0
See why an offline speech model cannot start early, and what the obvious fix costs
You call an airline and say: "I'd like to move my flight to Tuesday morning." That takes about 4.2 seconds. Then you stop and wait.
An offline recognizer did nothing during those 4.2 seconds. Its first layer looks at the whole clip at once, so it cannot run until the clip ends. A streaming model emits text for the audio it has heard, and it never needs audio from far ahead to do so.
Keep the offline model. Re-run it on everything said so far, every 200 ms. The front end makes one frame (a 10 ms slice of audio features) every 10 ms. So 4.2 seconds is 420 frames and 21 runs. Self-attention compares every frame with every other frame, so one pass over T frames costs about T squared units of work.
Call the frames added between two runs f and the number of runs K. Run number k sees f times k frames.
W equals the sum over k from 1 to K of f times k, squared.
Run k sees f times k frames and pays that number squared. Add the cost of all K runs. Compare W with one pass over the whole clip.
With f = 20 and K = 21: W = 400 × (1 + 4 + … + 441) = 400 × 3,311 = 1,324,400. One pass over 420 frames costs 420 × 420 = 176,400. The loop does 7.5 times the work.
Each pink bar is one re-run; it grows because each run sees more audio. Shorten the interval or lengthen the sentence and watch the ratio.
A cost model that counts only attention pairs. Real encoders also pay per-frame costs, which make the ratio smaller but keep it above 1.
The loop also flickers. Each re-run is a fresh pass that sees the latest audio, so "move" can become "prove" and back again. Streaming needs a different architecture, not a loop. It rests on three properties:
Δ is the algorithmic latency, also called the lookahead: how far into the future the model waits before it commits.
Symptom: server load climbs with call length, and captions twitch.
Measure: log encoder work per second of audio against call duration. It should stay flat.
Fix: a causal, chunked encoder with a cache (Chapters 1 and 2).
Chapter 1
Find every part of an encoder that reads ahead, and make the reuse of past work possible
An encoder maps input frames x0 to xT into output states h0 to hT. Which inputs may ht read? That set is the receptive field. Its right edge is your latency.
| Encoder | ht reads | Wait before ht |
|---|---|---|
| Bidirectional | frames 0 to T | until the clip ends |
| Causal | frames 0 to t | zero |
| Chunked | up to its chunk's end, plus L frames | a few frames |
Each row is one encoder. Teal cells are inputs the query may read; warm cells are future frames it must wait for. Pick an encoder and slide the query frame.
Twelve frames at a 10 ms hop, a toy clip. The chunked row uses chunks of 4 frames and 1 frame of lookahead.
Speech encoders start with convolution layers. Whisper's stem has two of width 3. The second has a stride of 2: it steps two input frames per output. A width-3 kernel centred on frame t reads t + 1, so with symmetric padding each layer leaks one step of the future.
Call the kernel width of layer i ki and its stride si. The receptive field in input frames is R.
R equals 1 plus the sum over layers i of k-i minus 1, times the product of s-j over the layers j below i.
Each layer widens the view by k-i minus 1 of its own steps. Turn those steps into input frames by multiplying the strides below it. With symmetric padding, half of R minus 1 lies in the future.
Five layers of width 3, all stride 1: R = 1 + 5 × 2 = 11. That is 5 future frames, 50 ms. Now give layer 2 a stride of 2. Layers 3 to 5 each add 2 × 2 = 4. R = 1 + 2 + 2 + 4 + 4 + 4 = 17, so 8 future frames, 80 ms.
The fix is causal padding: pad k − 1 zeros on the left and none on the right. Output t then reads t − 2, t − 1 and t. The view keeps its size; it now ends at the present.
pythonimport torch, torch.nn.functional as F x = torch.tensor([[[1., 2., 3., 4., 5.]]]) # (batch 1, channel 1, T 5) w = torch.ones(1, 1, 3) # a width-3 moving sum F.conv1d(F.pad(x, (1, 1)), w) # [3, 6, 9, 12, 9] output t reads t+1: future F.conv1d(F.pad(x, (2, 0)), w) # [1, 3, 6, 9, 12] output t reads t-2..t: causal
In a causal model, frame 5's key and value vectors never change after frame 5 arrives. So the encoder stores them in a KV cache, and frame t compares one new query with t stored keys. Over 420 frames that is 1 + 2 + … + 420 = 88,410 comparisons. Recomputing the prefix at every frame costs about 12.4 million, 141 times more.
Symptom: the transcript still appears only when the caller stops.
Measure: run the model on frames 0 to t, then on 0 to T. The first t + 1 outputs must match exactly.
Fix: find the part that reads ahead (a symmetric convolution, a normalization over the whole clip, a bidirectional LSTM) and make it causal.
Chapter 2
Build the mask cell by cell, count what it keeps, and turn it into milliseconds
Causal attention gives up all of the future. Bidirectional attention waits for all of it. Chunked attention sits between them. Cut the frames into chunks of C frames. A query in chunk c may read every earlier frame, its own chunk, and L more frames past the chunk end.
So the right edge of chunk c is frame C × (c + 1) − 1 + L. Every frame in a chunk shares that edge, so the encoder runs the whole chunk as one batch. With C = 4, L = 1 and 12 frames, the edges are frames 4, 8 and 11 (12 clips to the last frame).
| Mask on 12 frames | Allowed pairs | Share of full |
|---|---|---|
| Bidirectional | 12 × 12 = 144 | 100% |
| Chunked, C 4, L 1 | 4 × 5 + 4 × 9 + 4 × 12 = 104 | 72% |
| Causal | 1 + 2 + … + 12 = 78 | 54% |
Rows are queries, columns are keys. Teal cells are history and the query's own chunk; warm cells are the lookahead. Set C = 4 and L = 1 to match the table.
A toy 12-frame clip at a 10 ms hop. The waits count frames only; compute time comes on top.
Now the cost in time. Call the frame hop h. The first frame of a chunk waits longest, so the worst-case wait is Dmax.
D-max equals C plus L minus 1, times h.
The first frame of a chunk waits for the other C minus 1 frames of its chunk, then for L lookahead frames. Multiply that count by the hop h. The last frame of a chunk waits only L frames.
Take C = 4, L = 1 and h = 10 ms. Then Dmax = 4 × 10 = 40 ms. In chunk 0 the waits are 4, 3, 2 and 1 frames, an average of 2.5 frames, 25 ms.
What does the mask take away? Take query frame 3 with scores 0.2, 1.0, 2.0, 1.4, 0.6 and 1.8 against keys 0 to 5. The softmax spreads weight over the keys the mask allows.
| Mask | Weight on key 2 | Weight on keys after 3 |
|---|---|---|
| Causal (keys 0 to 3) | 0.480 | 0 |
| Chunked, L 1 (keys 0 to 4) | 0.429 | 0.106 |
| Full (keys 0 to 5) | 0.318 | 0.338 |
A third of this head's attention pointed at the future. The causal model never gets it. Emformer (Shi et al., 2020) is a chunked encoder for streaming recognition. It caches the keys and values of the left context, so no chunk recomputes them.
Symptom: you trained with a chunk mask and latency did not drop.
Measure: log the time each chunk enters the encoder.
Fix: serve chunk by chunk with the cache. A masked model fed the whole file is still a batch system.
Chapter 3
Turn encoder frames into text with an alignment that only moves forward
The encoder makes vectors. The decoder makes text. An attention decoder, the kind Whisper uses, picks each next token by attending to any encoder frame. Nothing forces it forward in time, so it must wait for every frame.
CTC (Connectionist Temporal Classification, Graves et al., 2006) emits one symbol per frame. The symbols are the letters plus a blank, written _, which means "nothing new here". Two rules turn a frame string into text, in this order:
The order matters. "T _ T" keeps two T's, so CTC can spell "butter". Because each output belongs to one frame, CTC is monotonic: the text only moves forward with the audio. A frame's symbol can be committed the moment the frame arrives.
Columns are frames, rows are symbols, brightness is probability. The outlined cell wins each frame. Reveal frames one at a time, then push the blank bias.
The eight probability columns are a made-up example. The bias multiplies the blank's probability before each frame picks its winner.
Greedy decoding gives _ C C _ A _ T T. Merge repeats: _ C _ A _ T. Drop blanks: CAT. How likely is that one path? Call the probability the model gives symbol at at frame t pt(at), and the whole frame string a.
P of a equals the product over t from 1 to T of p-t of a-t.
Pick one symbol per frame. Multiply the T chosen probabilities. That is the chance of this path; the chance of the word is the sum over every path that collapses to it.
0.70 × 0.70 × 0.60 × 0.80 × 0.75 × 0.60 × 0.80 × 0.55 = 0.047. The CTC forward pass sums every path that collapses to CAT and gets 0.334, so the best path holds 14% of the word's probability.
CTC has no sense of which words follow which. The transducer (RNN-T, Graves, 2012) adds a small prediction network over the text so far. Its blank means "done with this frame, move on", so it can emit several symbols in one frame.
| Decoder | Alignment | Knows word order | Streams |
|---|---|---|---|
| CTC | forward only | no | yes |
| Transducer | forward only | yes, prediction network | yes |
| Attention decoder | free | yes | only with extra machinery |
Symptom: the transcript drops letters, or adds stray ones.
Measure: count deletions and insertions against a reference.
Fix: tune the blank bias. Too high swallows letters; too low invents them.
Chapter 4
Split the transcript into a promise and a guess, and price the promise
Watch live captions: "I'd like to prove" turns into "I'd like to move my". That change is flicker: the model changed its mind because more audio arrived. On a screen it is harmless. For an agent it is a bug, because the agent reasons about words nobody said. For a speech synthesizer it is worse: spoken audio cannot be taken back.
So a streaming recognizer returns two strings. The volatile part is the current guess, fine to show in grey. The stable prefix is a promise that these words never change. Only the stable prefix goes to the agent and the synthesizer.
LocalAgreement-n promotes a word to stable when the last n hypotheses agree on it. Whisper-Streaming (Macháček et al., 2023) wraps the offline Whisper with this policy and reports 3.3 seconds of latency on long-form speech. Here it is with n = 2 and an update every 200 ms:
| Time | Hypothesis | Agreed with the last one | New stable words |
|---|---|---|---|
| 0.2 s | i'd like to | none yet | none |
| 0.4 s | i'd like to prove | i'd like to | i'd like to |
| 0.6 s | i'd like to move my | i'd like to | none |
| 0.8 s | i'd like to move my flight | i'd like to move my | move my |
| 1.0 s | i'd like to move my flight to | i'd like to move my flight | flight |
"Prove" never became stable, so nothing was retracted. The model changed its mind inside the volatile zone.
Blue words are stable, yellow words are volatile, red words are ones the system showed and then took back. Change n and the update interval.
The five hypotheses are a scripted example, the same as the table.
Call the agreement count n and the update interval u. The extra wait before a word turns stable is d.
d equals n minus 1, times u.
A word must appear in n updates in a row. Its first sighting costs nothing extra; each of the other n minus 1 sightings costs one interval u.
With n = 2 and u = 200 ms, d = 200 ms. With n = 3, d = 400 ms. Keep n = 2 and update every 100 ms: d = 100 ms, for twice the decoder runs.
Emitting every word at once retracts "prove": 1 retraction in 7 words, a flicker rate of 14%. LocalAgreement-2 retracts nothing and pays 200 ms per word.
Symptom: a misheard name becomes stable and the agent acts on it.
Measure: the error rate of the stable text alone.
Fix: agreement guards against a model that hesitates, not one that is sure and wrong. Pass confidence or a list of alternatives to the agent.
Chapter 5
Cut the reply into chunks, make the first one small, and never let the audio run dry
The reply arrives as tokens. Say it has 20 words and the language model writes 10 words per second: the last word lands 1.9 seconds after the first. A synthesizer that waits for the full sentence throws that time away.
Incremental TTS cuts the text into chunks and synthesizes each chunk when it closes. The real-time factor (RTF) is compute seconds per second of audio, so 0.3 means one second of speech takes 0.3 seconds to make. With made-up numbers: 2.5 words per second of speech (one word is 0.4 s), RTF 0.3, and 60 ms of fixed cost per call.
| First chunk | Audio | Time to first audio |
|---|---|---|
| 3 words | 1.2 s | 60 + 0.3 × 1,200 = 420 ms |
| 8 words | 3.2 s | 60 + 960 = 1,020 ms |
| 20 words, whole sentence | 8.0 s | 60 + 2,400 = 2,460 ms |
Once playback starts, audio drains at real time. If chunk k is not ready when chunk k − 1 ends, the listener hears a buffer underrun: a hole in the middle of the reply. Call the audio length of chunk k Ak, the fixed cost per call o and the real-time factor r.
o plus r times A-k is at most A-k-minus-1.
Making chunk k takes o plus r times A-k. That must fit inside the playing time A-k-minus-1 of the chunk before it. Slack saved by earlier chunks adds room.
Chunks of 3, 8 and 16 words: A = 1.2, 3.2 and 6.4 s. With r = 0.3: 0.06 + 0.96 = 1.02 ≤ 1.2, safe by 0.18 s. With r = 0.9: 0.06 + 2.88 = 2.94 > 1.2, a 1.74 s hole, though r is below 1.
Pink bars are synthesis, purple bars are playback, red gaps are holes. Shrink the first chunk to start sooner; raise RTF to see the race fail.
Illustrative timing model: chunks of the first size, then 8 and 16 words, made back to back. Real RTF varies from call to call.
Seams can also be heard. A chunk made alone gets its own falling pitch, so the reply sounds like a list. Cut at clause boundaries, and give the synthesizer the previous text as context without speaking it again. Qwen2.5-Omni's speech decoder sees 2 blocks back and 1 block ahead of the block it renders.
Symptom: the reply stutters about a second in.
Measure: per chunk, log when synthesis ends and when playback of the previous chunk ends. Check the margin at the slow tail of RTF, not the median.
Fix: grow chunk sizes only as fast as the margin allows.
Chapter 6
Put every knob on one turn gap and find which ones move it
Every chapter so far gave you a knob. Here they meet in one number: the turn gap, from your last syllable to the first sound of the reply.
After you stop, two clocks start together. The endpoint hold is the silence timer that decides you are done. The recognizer's tail is the last chunk's wait, its compute and its stability delay. The reply waits for the later of the two. Call the hold E, the chunk wait Wc, the compute K and the stability delay d.
T-asr equals the max of E, and W-c plus K plus d.
Start both clocks at your silence. Add W-c, K and d for the recognizer. Take whichever of E and that sum is larger.
With made-up defaults: E = 250, Wc = (14 + 2 − 1) × 10 = 150, K = 60, d = 1 × 140 = 140. The recognizer needs 350 ms, so Tasr = max(250, 350) = 350 ms.
The rest is a plain sum, because each stage needs the one before it. Uplink 95, recognizer 350, three service hops 30, first token 375, first audio 180, downlink 95. Total: 1,125 ms.
The top bar is the turn gap, stage by stage. The two thin bars below race: the hatched one lost and costs nothing. Drag any slider.
Every stage time here is an illustrative model. It uses 10 ms frames and 60 ms of recognizer compute. Stability delay is (n − 1) × C × 10 ms; first audio is 60 + 120 ms per word. The 230 ms human gap and Moshi's 200 ms are published.
Symptom: you made the recognizer twice as fast and users noticed nothing.
Measure: log both clocks on every turn, and look at the slow tail (the 95th percentile), not the median.
Fix: work on the clock that finishes later, and on the serial stages after it.
Chapter 7
Delete the pipeline, turn sound into 80 ms tokens, and count the delay in frames
A cascade waits at every seam. The other route makes audio itself the token stream, so one model listens and speaks in the same step. Moshi (Défossez et al., 2024) takes this route.
A neural audio codec turns a waveform into a few discrete tokens per second, and back. Moshi's codec, Mimi, sends 24 kHz audio through causal convolutions with strides 4, 5, 6 and 8, then one more of stride 2. Each frame gets 8 tokens from 8 codebooks of 2,048 entries.
| Quantity | Arithmetic | Result |
|---|---|---|
| Downsampling | 4 × 5 × 6 × 8 × 2 | 1,920 |
| Frame rate | 24,000 / 1,920 | 12.5 per second |
| Frame length | 1 / 12.5 | 80 ms |
| Bitrate | 12.5 × 8 codebooks × 11 bits | 1.1 kbps |
Mimi distills WavLM, a self-supervised speech model, into its first codebook, so that codebook carries what was said. WavLM reads ahead, but it is used only in training, so the shipped codec stays causal.
A large temporal transformer steps once per frame; a small depth transformer predicts the 8 tokens inside each frame. Call the acoustic delay τ: codebooks 2 to 8 lag the first by τ frames. The latency is ℓ.
ell equals 1 plus tau, times 80 milliseconds.
Wait one frame to hear 80 ms of input. The acoustic tokens of a frame come tau frames after its first token. Count the frames and multiply by 80 ms.
Delay 0 gives 80 ms. Delay 1 gives 160 ms. Delay 2 gives 240 ms. A fully staggered pattern lags codebook 8 by 7 frames: 640 ms. Moshi pre-trains with τ = 2 and fine-tunes with τ = 1: 160 ms in theory, 200 ms in practice.
Columns are 80 ms steps, rows are codebooks. Teal is the first, semantic codebook; purple are acoustic ones. Frame 0's tokens have an outline. Press Play, then change the delay.
Moshi's paper tests delays of 0, 1 and 2 frames and a fully staggered pattern. Delays of 3 to 7 are shown for comparison.
Moshi models its own voice and the user's as two parallel token streams. It predicts its next 80 ms whether or not you speak, so there is no endpoint hold to tune. Its Inner Monologue also predicts text tokens aligned with its speech. Delay the text 2 s behind the audio and the model is a streaming recognizer: 5.7% WER on LibriSpeech test-clean. Delay the audio 2 s behind the text and it is a streaming synthesizer: 4.7%, against VALL-E's 5.9%.
Qwen2.5-Omni keeps separate modules and streams each one: its audio encoder attends in 2-second blocks, and its speech decoder uses that 4-block window.
Symptom: you cannot audit what the agent heard.
Measure: check whether a text transcript exists for each turn.
Fix: keep a text stream, or keep a cascade where review and redaction matter more than speed.
Chapter 8
Measure the error rate as the user saw it, and find where more lookahead stops paying
Lookahead buys accuracy. To budget it, you need a curve of error rate against lookahead. Compare the model's words with a reference. Count the S substituted words, the D deleted words and the I inserted words. The reference has N words.
WER equals S plus D plus I, over N.
Line up the two word lists with the fewest edits. Count S, D and I. Divide by N, the reference length.
Reference "i would like to move my flight", N = 7. Output "i would like to prove flight": S = 1 (prove), D = 1 (my), I = 0. WER = 2 / 7 = 28.6%.
Score the text the agent saw, each word frozen when it turned stable. Scoring the final transcript counts late fixes the agent never saw.
Published points show the shape. Emformer reports 3.01% WER on LibriSpeech test-clean at 80 ms average latency and 2.50% at about 960 ms: twelve times the lookahead for half a point. Moshi's recognizer gets 5.7% with 2 s of delay, and the paper notes a Streaming FastConformer gets 3.6% with similar lookahead.
Top: error rate against lookahead, your point marked. Bottom: what each extra 100 ms buys. Drag the lookahead past the knee, then stretch the scale.
Illustrative curve: the error falls from 11% with no lookahead toward a 5.5% floor, and each "scale" of lookahead removes about 63% of the gap left. Its shape matches the published points; its numbers are made up.
On this toy, the first 100 ms buys 1.56 points; the step from 900 to 1,000 ms buys 0.08. Past the knee, spend milliseconds on the endpoint hold or the first TTS chunk instead.
Symptom: accuracy falls off a cliff after the switch to streaming.
Measure: check the lookahead the model was trained with against the one it is served with.
Fix: train or fine-tune for each setting, or sample the chunk size at random during training so one model serves many.
Chapter 9
Keep the terms, the numbers, the checklist and the core code in one place
A streaming stack reads only a little ahead, does each frame's work once, and never takes back a word it promised. The recognizer commits through a forward-only decoder and a stable prefix. The synthesizer starts on a small first chunk and keeps its buffer full. The turn gap is a max of two clocks plus a serial sum. Frame-level models remove the seams.
| Term | Meaning | Number on this page |
|---|---|---|
| C, L | chunk size and lookahead, in frames | C 4, L 1: worst wait 40 ms |
| Receptive field | the inputs one output reads | five width-3 layers: 11 frames, 5 ahead |
| Blank | CTC's "nothing new" symbol | best CAT path 0.047 of 0.334 |
| Stable prefix | words promised never to change | LocalAgreement-2: 200 ms per word |
| RTF | compute seconds per audio second | 0.9 with chunks 3 then 8: a 1.74 s hole |
| Turn gap | silence from your last word to the reply | toy cascade 1,125 ms; Moshi 200 ms; people 230 ms |
| Mimi frame | one audio token step | 80 ms, 12.5 per second, 1.1 kbps |
| WER | (S + D + I) / N | Emformer 3.01% at 80 ms, 2.50% at 960 ms |
pythonimport numpy as np def chunk_mask(T, C, L): # (T, T) bool, True = query may read key m = np.zeros((T, T), dtype=bool) for t in range(T): edge = min(T - 1, C * (t // C + 1) - 1 + L) m[t, :edge + 1] = True return m # chunk_mask(12, 4, 1).sum() == 104 def ctc_greedy(probs, vocab): # probs: (T, V); vocab[0] is the blank out, prev = [], None for i in probs.argmax(axis=1): if i != prev and i != 0: out.append(vocab[i]) # emit once, never take back prev = i return ''.join(out) class LocalAgreement: def __init__(self, n=2): self.n, self.hist, self.stable = n, [], [] def update(self, words): # words: list[str], the newest hypothesis self.hist = (self.hist + [words])[-self.n:] if len(self.hist) == self.n: agree = min(len(h) for h in self.hist) for i in range(agree): if len({h[i] for h in self.hist}) > 1: agree = i; break if agree > len(self.stable): self.stable = words[:agree] # a ratchet: never shrinks return self.stable, words[len(self.stable):] # (stable, volatile) def turn_gap(up, E, Wc, K, d, hops, ttft, ttfa, down): # all in ms return up + max(E, Wc + K + d) + hops + ttft + ttfa + down # turn_gap(95, 250, 150, 60, 140, 30, 375, 180, 95) == 1125
Défossez et al., Moshi: a speech-text foundation model for real-time dialogue (2024). Qwen Team, Qwen2.5-Omni Technical Report (2025). Shi et al., Emformer (2020). Macháček, Dabre and Bojar, Turning Whisper into Real-Time Transcription System (2023). Graves, Sequence Transduction with Recurrent Neural Networks (2012). Graves et al., Connectionist Temporal Classification (ICML 2006).
Now press Present or Teach and explain, from memory, the chunk mask, the stable prefix and the two clocks. Then go back to the hero and say which chapter removes each part of the batch system's gap.