How does chunked attention make a speech encoder stream?

Authors
How does chunked attention make a speech encoder stream?

Chunked attention makes a speech encoder stream by cutting the incoming audio frames into small fixed-size groups called chunks, where each chunk looks only at itself and the chunks that came before it. This way, the encoder can work on the audio while the person is still speaking, without waiting for the full audio.

In this blog, we will learn about how chunked attention makes a speech encoder stream. We will also see why normal full attention cannot stream, why looking only at the past hurts accuracy, how an attention mask creates chunks, how caching keeps the work small, and how one model can be trained to work with many chunk sizes.

We will cover the following:

  • What is a speech encoder?
  • How does attention work inside a speech encoder?
  • Why full attention cannot stream
  • Approach 1: Causal attention
  • Approach 2: Chunked attention
  • How the attention mask creates chunks
  • Caching the past chunks
  • Limiting the left context
  • The convolution problem in Conformer
  • Dynamic chunk training
  • Choosing the chunk size

I am Amit Shekhar, Founder @ Outcome School, I have taught and mentored many developers, and their efforts landed them high-paying tech jobs, helped many tech companies in solving their unique problems, and created many open-source libraries being used by top companies. I am passionate about sharing knowledge through open-source, blogs, and videos.

I teach AI and Machine Learning at Outcome School.

Let's get started.

What is a speech encoder?

A speech encoder is the part of a speech recognition model that listens to the audio and turns it into a list of numbers that capture what was said.

A speech recognition model (also called ASR, Automatic Speech Recognition) has a simple job. It takes audio as input and gives text as output.

The model does this in two parts:

  • The encoder reads the audio and understands it.
  • The decoder reads what the encoder understood and writes the text.

We have a detailed blog on how the Token-and-Duration Transducer (TDT) speeds up speech recognition that walks through how one such decoder turns the encoder frames into text.

The encoder does not read the audio all at once. First, the audio is cut into very small time slices. For the sake of example, let's say each slice is 10 milliseconds long. Each slice is turned into a small list of numbers. We call each slice a frame.

Most speech encoders then combine these frames, so that, for example, every 4 frames of 10 milliseconds become 1 frame of 40 milliseconds. This makes the sequence shorter and faster to work with.

So, 1 second of audio becomes 25 frames of 40 milliseconds each. The encoder works on these frames.

Now, the question is: how does the encoder understand these frames? The answer is attention.

How does attention work inside a speech encoder?

A single frame of 40 milliseconds does not mean much on its own. It is just a tiny piece of a sound. To understand which word is being spoken, a frame must look at the frames around it.

Let's say a person says the word "cat". The sound "c" at the start only makes sense when the model also hears the "a" and the "t" that come after it.

Here comes the Self Attention into the picture. In Self Attention, every frame looks at the other frames and decides how much each of them matters to it. Then, it mixes in the useful information from those frames.

After attention, each frame does not only carry its own sound. It also carries an understanding of the sounds around it.

Modern speech encoders built on the Transformer or the Conformer architecture stack many layers of Self Attention, one on top of another. Each layer lets the frames share information again.

Now, let's see the problem.

Why full attention cannot stream

By default, Self Attention uses full attention. Means, every frame looks at every other frame in the whole audio, the past frames and the future frames.

This works very well for accuracy. Every frame knows the full sentence.

To let frame number 10 look at frame number 500, the model must already have frame number 500. So, the model must wait until the person has finished speaking before it can start.

Let's say a person speaks for 8 seconds. With full attention, the model waits 8 seconds, and only then starts to work. The person sees the text only after they have stopped talking.

Waiting is fine for transcribing a recorded meeting file. But it is not fine for live captions or a voice assistant. In those cases, we want the text to appear while the person is still speaking. We call this streaming.

Streaming means the model processes the audio piece by piece, as it arrives, and gives results without waiting for the full audio.

We have a detailed blog on how an ASR model produces partial and final transcripts that explains what a streaming model shows while the person is still speaking.

Now, the question is: why not simply run full attention again on all the audio received so far, every half a second? We can do that, but every new run repeats the work for all the old audio, so the work keeps growing. Also, the output for the old frames keeps changing, because they now see new future frames.

So, how can we make the encoder stream without these problems? Let's see the approaches one by one.

Approach 1: Causal attention

The simplest idea is to stop the frames from looking at the future.

In causal attention, each frame can look only at itself and the frames before it. It can never look at a frame that comes after it.

Let's take 6 frames. In the diagram below, a 1 means "can look at" and a 0 means "cannot look at". Each row is a frame doing the looking.

          f1  f2  f3  f4  f5  f6
    f1     1   0   0   0   0   0
    f2     1   1   0   0   0   0
    f3     1   1   1   0   0   0
    f4     1   1   1   1   0   0
    f5     1   1   1   1   1   0
    f6     1   1   1   1   1   1

Here, we can see that frame f3 can look at f1, f2, and itself, but not at f4, f5, or f6.

Now, as soon as a new frame arrives, the model can process it. It does not need any future frame. So, the encoder can stream.

The issue with this approach is accuracy. Speech needs a little bit of the future. As we saw with the word "cat", the start of a sound often makes sense only after hearing what comes next. With zero future, each frame has less information, and the model makes more mistakes.

There is a second issue. The model runs once for every single frame of 40 milliseconds. That is 25 runs every second, and each run is small. Hardware like a GPU is much faster when it works on many frames together in one run.

Let's see how the next approach solves these issues.

Approach 2: Chunked attention

So, here comes the chunked attention to the rescue.

In chunked attention, we cut the frames into fixed-size groups called chunks. Each frame can look at every frame inside its own chunk, and at every frame in the chunks before it. It cannot look at any frame in the chunks after it.

Let's say the chunk size is 2 frames. Our 6 frames become 3 chunks:

  • Chunk A: f1, f2
  • Chunk B: f3, f4
  • Chunk C: f5, f6

Now, the "can look at" table becomes like below:

          f1  f2  f3  f4  f5  f6
    f1     1   1   0   0   0   0
    f2     1   1   0   0   0   0
    f3     1   1   1   1   0   0
    f4     1   1   1   1   0   0
    f5     1   1   1   1   1   1
    f6     1   1   1   1   1   1

Here, we can notice two things:

  • Frame f3 can now look at f4, which is in the future. This is because f3 and f4 are in the same chunk. So, each frame gets a small amount of future, which helps accuracy.
  • Frame f3 still cannot look at f5 or f6, because they belong to the next chunk. So, the future is limited to the end of the current chunk.

One more thing to notice: the last frame of a chunk, like f4, still sees no future at all. So, the frames near the end of a chunk get less help than the frames at the start. We will see a small fix for this at the end of this blog.

Now, the model works like below:

Audio keeps arriving
        ↓
Wait until one full chunk of frames is collected
        ↓
Run the encoder on this chunk (it also looks at the past chunks)
        ↓
Send the output to the decoder
        ↓
Repeat for the next chunk

The model only waits for one chunk, not for the full audio. And it processes a whole chunk in one run, which uses the hardware much better than one frame at a time.

This is how chunked attention makes a speech encoder stream. It gives a middle path between full attention (high accuracy, no streaming) and causal attention (streaming, lower accuracy).

Planning your move into AI?

No matter which tech domain you work in today, with your effort, you can transition to these roles:

  • AI Engineer
  • Forward Deployed Engineer
  • AI Agent Engineer
  • Harness Engineer
  • Voice AI Engineer
  • AI Architect
  • LLM Engineer
  • LLM Inference Engineer
  • Gen AI Engineer
  • MLOps Engineer
  • ML Engineer
  • Deep Learning Engineer

Our AI and Machine Learning Program at Outcome School takes you there.

How the attention mask creates chunks

Now, the question is: how do we actually stop a frame from looking at the next chunk?

The answer is an attention mask. An attention mask is a table of 1 and 0, exactly like the tables we drew above. Before attention mixes the frames, the model blocks every pair that has a 0 by giving it a very large negative score. So, a blocked frame gets zero importance, and its information is not mixed in.

The best part is that the rest of the encoder does not change at all. The same layers and the same weights are used. Only the mask changes.

Let's see the code for building a chunk mask as below:

def chunk_mask(num_frames, chunk_size):
    mask = [[0] * num_frames for _ in range(num_frames)]
    for i in range(num_frames):
        # index right after the end of the chunk of frame i
        chunk_end = (i // chunk_size + 1) * chunk_size
        for j in range(min(chunk_end, num_frames)):
            mask[i][j] = 1  # frame i can look at frame j
    return mask

for row in chunk_mask(6, 2):
    print(row)

Here, we have:

  • i // chunk_size gives the chunk number of frame i. The counting starts from 0, so frame index 2 is f3, and with a chunk size of 2, it is in chunk number 1, which is Chunk B.
  • chunk_end is the index right after the end of that chunk.
  • Frame i can look at every frame from the start up to, but not including, chunk_end. So, it sees all past chunks and its own chunk, and nothing after.

This will print the following:

[1, 1, 0, 0, 0, 0]
[1, 1, 0, 0, 0, 0]
[1, 1, 1, 1, 0, 0]
[1, 1, 1, 1, 0, 0]
[1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1]

It matches the chunk table we drew earlier.

Note: If we set chunk_size to 1, we get causal attention. If we set chunk_size to the full length of the audio, we get full attention. So, chunked attention covers both of them as the two extreme cases.

To learn Self-Attention, Causal Masked Attention, and the Transformer Architecture in depth, check out our AI and Machine Learning Program at Outcome School.

Caching the past chunks

There is one more problem to solve.

Each new chunk looks at all the past chunks. If the model had to run the encoder again on all the past chunks every time a new chunk arrives, the work would keep growing with every chunk. After a minute of speech, the model would be doing a huge amount of repeated work.

The past chunks never look at the new chunk. Their mask rows have 0 for every future chunk. So, the output of a past chunk never changes when a new chunk arrives.

Hence, we can compute each chunk only once and save what the future chunks need from it. We call this saved data a cache. Now, the question is: what exactly do the future chunks need?

In attention, every frame produces two lists of numbers called the key and the value. The key says "what kind of information I have", and the value is "the actual information I carry". A frame also produces a third list called the query, which says "what I am looking for". When a new frame looks at a past frame, it compares its own query with that past frame's key, and then takes in that past frame's value. So, from the past frames, it needs only their keys and values.

So, for each layer, the model saves the keys and values of the past chunks. When a new chunk arrives, it works like below:

New chunk arrives
        ↓
Compute keys and values only for the new chunk
        ↓
Join them with the saved keys and values of the past chunks
        ↓
New chunk attends to all of them
        ↓
Save the new chunk's keys and values in the cache

This is the same idea as the KV Cache used in LLMs (Large Language Models). The work for each new chunk stays small, because the old chunks are never computed again.

A quick note for you

No matter which tech domain you work in, get familiar with these topics:

  • LLM
  • RAG
  • MCP
  • Agent
  • Fine-tuning
  • Quantization

We put it all together in one video:

AI Engineering Explained: LLM, RAG, MCP, Agent, Fine-Tuning, and Quantization

No need to stop reading - bookmark it and watch later when you get time. Future you will thank you.

Now, let's get back to the topic.

Limiting the left context

Even with a cache, one issue remains. The cache keeps growing. After 10 minutes of speech, each new chunk must look at 10 minutes of past frames. This uses more memory and more time with every chunk.

We limit how far back a chunk can look. This past window is called the left context.

Let's say we keep a left context of 4 chunks. Then, a new chunk looks at its own frames and only the 4 chunks before it. Anything older is dropped from the cache.

We have a detailed blog on Sliding Window Attention that covers this idea of a fixed look-back window step by step.

For the sake of understanding, let's take a smaller example with 4 chunks of 1 frame each, and a left context of only 1 chunk. The mask looks like below:

          c1  c2  c3  c4
    c1     1   0   0   0
    c2     1   1   0   0
    c3     0   1   1   0
    c4     0   0   1   1

Here, we can see that c3 looks at c2 and itself, but no longer at c1.

Now, the memory and the work per chunk stay fixed, no matter how long the person speaks. The model can run on a live stream for as long as needed.

In practice, the speech for a word rarely depends on audio from many seconds ago. So, a few seconds of left context often keeps the accuracy close to what we get with the full past.

The convolution problem in Conformer

Many modern speech encoders use the Conformer. The Conformer is an encoder architecture that uses both Self Attention and convolution in each layer.

A convolution looks at a small window of nearby frames, for example a few frames on the left and a few frames on the right, and mixes them. It is good at catching short sound patterns.

The attention mask controls only attention. It does not control convolution. A normal convolution looks at frames on the right side too, and those frames can be in the next chunk, which has not arrived yet.

So, if we only add the chunk mask, the convolution still needs future audio. The encoder still cannot stream properly.

The solution is a causal convolution. In a causal convolution, the window looks only at the current frame and the frames on its left. It never looks to the right.

Since the convolution also needs a few frames from the left, the model saves the last few frames of the previous chunk in a small convolution cache too.

Now, both attention and convolution respect the chunk boundary. The Conformer can stream.

Stay updated: Subscribe to our newsletter to get our latest AI and Machine Learning blogs straight to your inbox.

Dynamic chunk training

Now, the next big question is: how do we train such a model?

The model must be trained with the same mask that it will use while streaming. If we train with full attention and then use chunked attention at run time, the model loses the future frames it learned to depend on, and the accuracy drops a lot.

So, we train with the chunk mask applied.

But this creates a new problem. If we train with a chunk size of 16 frames, the model works best with 16 frames. If we later want a lower delay with 4 frames, the accuracy drops, and we often need to train a new model.

Here comes the dynamic chunk training into the picture. This idea was introduced with the U2 model, which is part of the WeNet speech recognition toolkit.

In dynamic chunk training, the chunk size is not fixed during training. For each training batch, the training code picks a random chunk size. Sometimes it is small, sometimes it is large, and sometimes it is the full audio, which means full attention.

Hence, the model learns to work well with many different chunk sizes. After training, we pick the chunk size at run time:

  • A small chunk size when we want the text to appear very fast.
  • A larger chunk size when we want better accuracy and can wait a little longer.
  • Full attention when we transcribe a complete recorded file.

So, one trained model can be used for streaming and for non-streaming, and we choose the speed and accuracy we want depending on our use case.

Choosing the chunk size

The chunk size controls the trade-off between delay and accuracy.

Let's say each frame is 40 milliseconds, like in our earlier example:

  • A chunk of 4 frames is 160 milliseconds.
  • A chunk of 16 frames is 640 milliseconds.

With a chunk of 640 milliseconds, the model must wait for 640 milliseconds of audio before it can process that chunk. So, the first frame of the chunk waits the longest, while the last frame barely waits. Hence, chunking adds a delay of up to one chunk length. On top of this, the model needs some time to run.

Let me tabulate the differences between small chunks and large chunks for your better understanding.

PropertySmall chunkLarge chunk
Delay before text appearsLowHigh
Future each frame can seeVery littleMore
AccuracyLowerHigher
Runs per secondManyFew
Good forVoice assistants, live captionsNear-live transcription

Some streaming encoders also add a small right context, which means a few extra frames from the next chunk that the current chunk can also look at. This gives a bit more future without making the chunk itself bigger, and it helps the last frames of a chunk, which otherwise see no future at all. The cost is a small extra delay, because the model must wait for those extra frames too.

Now we must have understood how chunked attention makes a speech encoder stream, how the attention mask creates chunks, how caching and left context keep the work small, and how dynamic chunk training lets one model work with many chunk sizes.

Frequently Asked Questions

Does chunked attention need a new model architecture?

No. Chunked attention does not change the layers or the weights of the encoder. It only changes the attention mask, which blocks every frame from looking at the frames in the chunks after its own chunk. For a Conformer, the convolution must also become a causal convolution, so that it does not need future audio.

What is the difference between chunked attention and causal attention?

In causal attention, each frame looks only at itself and the frames before it, so it sees no future at all. In chunked attention, a frame also sees the later frames inside its own chunk, which helps accuracy, and the model processes a whole chunk in one run. Causal attention is simply chunked attention with a chunk size of 1.

Can one speech encoder work for both streaming and non-streaming transcription?

Yes. With dynamic chunk training, the model is trained with a random chunk size for each batch, sometimes small, sometimes large, and sometimes the full audio. After training, we pick a small chunk size for fast text, a larger one for better accuracy, or full attention for a complete recorded file.

What is right context in a streaming speech encoder?

Right context is a few extra frames from the next chunk that the current chunk can also look at. It gives a bit more future without making the chunk itself bigger, and it helps the last frames of a chunk, which otherwise see no future. The cost is a small extra delay, because the model must wait for those extra frames.

That's it for now.

Thanks

Amit Shekhar
Founder @ Outcome School

You can connect with me on:

Follow Outcome School on:

Read all of our high-quality blogs here.