Cache-aware streaming skips a final chunk shorter than sampling_frames, so a stream's last word depends on its batch
Describe the bug
CacheAwareStreamingAudioBuffer stops iterating as soon as the next chunk is narrower than the pre-encoder's sampling_frames. The check is in __iter__ (L1629-L1639) and, copied, in _iter_with_right_context (L1827-L1837):
audio_chunk = self.buffer[:, :, self.buffer_idx : self.buffer_idx + chunk_size]
if self.sampling_frames is not None:
# checking to make sure the audio chunk has enough frames to produce at least one output after
# downsampling
...
if audio_chunk.size(-1) < cur_sampling_frames:
return
Two things go wrong here:
self.bufferis zero-padded to the longest stream in the batch (append_processed_signal, L1950 and L1957). Soaudio_chunk.size(-1)is the remaining width of the longest stream, and one decision is made for the whole batch.- The check counts only the new frames. The chunk is then fed together with the pre-encode cache, so a short tail still produces output. With the FastConformer streaming settings (
dw_striding, subsampling factor 8,causal_downsampling: true), the 9-frame cache plus a 1-7 frame tail leaves 1 encoder frame afterdrop_extra_pre_encoded=2. The offline forward produces that frame too.
As a result:
- Streamed alone, a stream whose last chunk is 1-7 feature frames (
sampling_frames == [1, 8]) never has those frames fed, and its output ends one encoder frame short of offline. - In a batch, the same frames are fed unless the longest stream in the batch also has fewer than 8 frames left at that step. The short stream's transcript then depends on its neighbours.
With stt_en_fastconformer_hybrid_large_streaming_multi at its default att_context_size=[70, 13], streaming each LibriSpeech test-other utterance on its own truncates the end of 38 of the 2939 transcripts with the RNNT decoder and 65 with the CTC decoder. One example (RNNT) is lady graham looked ghast instead of ghastly. Details are below.
Scope, as far as I checked:
sampling_framesis set frompre_encode.get_sampling_frames()(L1594), andConvSubsamplingreturns[1, subsampling_factor](subsampling.pyL498-L499). All cache-aware Conformer and FastConformer configs underexamples/asr/confusestridingordw_stridingwithcausal_downsampling: true. I reproduced the effect with small random models of both shapes: FastConformer (factor 8, tails of 1-7 frames) and Conformer (striding, factor 4,[140, 27], tails of 1-3 frames).- Every user of this buffer on main goes through the check:
speech_to_text_cache_aware_streaming_infer.py(repro A),transcribe_simulate_cache_aware_streaming(CTC models, measured below) andspeech_to_text_multitalker_streaming_infer.py(through_iter_with_right_context, checked at the unit level only). - The tests in
tests/collections/asr/utils/test_streaming_utils.pybuild the buffer withsampling_frames = None, so they never reach this code.
Steps/Code to reproduce bug
A. The shipped example script, on a released checkpoint
I ran this on CPU (cuda=-1), with model_path pointing at the .nemo file of nvidia/stt_en_fastconformer_hybrid_large_streaming_multi. decoder_type is left unset, so the hybrid model decodes with RNNT (the script logs "Changed decoding strategy of the RNNT decoder"). The manifest holds two LibriSpeech test-other utterances, with the short one first:
{"audio_filepath": ".../7902-96595-0024.wav", "duration": 2.2, "text": "lady graeme looked ghastly"}
{"audio_filepath": ".../7902-96592-0014.wav", "duration": 18.91, "text": "oh those bars he mentally exclaimed ..."}
python examples/asr/asr_cache_aware_streaming/speech_to_text_cache_aware_streaming_infer.py \
model_path=stt_en_fastconformer_hybrid_large_streaming_multi.nemo \
dataset_manifest=pair.json batch_size=1 compare_vs_offline=true cuda=-1
batch_size |
streaming transcript of 7902-96595-0024 | WER% streaming (both utterances) | WER% offline (both utterances) |
|---|---|---|---|
| 1 | lady graham looked ghast |
8.82 | 7.35 |
| 2 | lady graham looked ghastly |
7.35 | 7.35 |
At batch_size=1 the script also logs its own check for that utterance:
The shape of the outputs of the model in streaming mode (torch.Size([12])) is different from offline mode (torch.Size([13])).
B. CPU only, no download
This builds a small, randomly initialised cache-aware FastConformer from the shipped char config. Run it from the repo root:
import torch
from omegaconf import OmegaConf, open_dict
from nemo.collections.asr.models import EncDecCTCModel
from nemo.collections.asr.parts.utils.streaming_utils import CacheAwareStreamingAudioBuffer
# Small, randomly initialised cache-aware FastConformer built from the shipped example config (CPU, no download).
torch.manual_seed(0)
cfg = OmegaConf.load("examples/asr/conf/fastconformer/cache_aware_streaming/fastconformer_ctc_char_streaming.yaml")
cfg = cfg.model
with open_dict(cfg):
cfg.train_ds = cfg.validation_ds = cfg.test_ds = None
cfg.encoder.n_layers, cfg.encoder.d_model, cfg.encoder.n_heads = 2, 64, 2
cfg.encoder.subsampling_conv_channels = 32
cfg.decoder.feat_in, cfg.decoder.num_classes, cfg.decoder.vocabulary = 64, len(cfg.labels), list(cfg.labels)
model = EncDecCTCModel(cfg=cfg).eval()
streaming_cfg = model.encoder.streaming_cfg
def stream(streams, process_tail=False):
"""Frames of greedy output per stream, driven like transcribe_simulate_cache_aware_streaming."""
buffer = CacheAwareStreamingAudioBuffer(model=model)
if process_tail:
buffer.sampling_frames = None # its only use is the check in question
for features in streams:
buffer.append_processed_signal(features.unsqueeze(0).clone())
cache = model.encoder.get_initial_cache_state(batch_size=len(streams))
pred = None
for step, (chunk, lengths) in enumerate(buffer):
with torch.inference_mode():
pred, _, *cache, _ = model.conformer_stream_step(
processed_signal=chunk,
processed_signal_length=lengths,
cache_last_channel=cache[0],
cache_last_time=cache[1],
cache_last_channel_len=cache[2],
keep_all_outputs=buffer.is_buffer_empty(),
previous_pred_out=pred,
drop_extra_pre_encoded=0 if step == 0 else streaming_cfg.drop_extra_pre_encoded,
)
return [len(p) for p in pred]
first, later = streaming_cfg.chunk_size # [105, 112] for att_context_size=[70, 13]
short = torch.randn(80, first + later + 2) # last chunk has 2 frames, fewer than sampling_frames[1] == 8
longer = torch.randn(80, first + 3 * later)
with torch.inference_mode():
offline_pred = model.conformer_stream_step(
processed_signal=short.unsqueeze(0), processed_signal_length=torch.tensor([short.shape[-1]])
)[0]
print("output frames for the short stream")
print(" offline :", len(offline_pred[0]))
print(" streamed alone :", stream([short])[0])
print(" streamed next to a longer stream :", stream([short, longer])[0])
print(" streamed alone, tail processed :", stream([short], process_tail=True)[0])
output frames for the short stream
offline : 29
streamed alone : 28
streamed next to a longer stream : 29
streamed alone, tail processed : 29
In a variant that compares log-probs, the extra frame from the batched run differs from the offline frame only by fp32 rounding. Over tails of 1-7 frames and three random inputs, the maximum absolute difference was 9.5e-07 with 8 threads, and 0 with torch.set_num_threads(1).
More measurements with the random models, and at the unit level
- Length sweep (FastConformer shape,
[70, 13]). I tried the 112 stream lengths from 217 to 328. Streaming alone differs from offline in frame count for exactly the 7 lengths whose last chunk is 1-7 frames (218-224: 28 frames instead of 29). Streaming next to a longer stream matches offline for all 112. At[70, 0], over the 16 lengths from 201 to 216, the same holds for the 14 lengths with a 1-7 frame tail. - Conformer shape. I built the same random model with
subsampling: striding,subsampling_factor: 4,att_context_size: [140, 27]andcausal_downsampling: true, which givessampling_frames == [1, 4], a 5-frame pre-encode cache anddrop_extra_pre_encoded=2. For tails of 1-3 frames: offline 57, alone 56, batched 57, alone with the tail processed 57. With a tail of 4 frames all four give 57, and with no tail all four give 56. transcribe_simulate_cache_aware_streaming. With the model from B and a noise wav whose last chunk is 2 frames: offline 29 log-prob frames. The method returns 28 atbatch_size=1and 29 atbatch_size=2next to a longer file.- Unit level, with the helper from
test_streaming_utils.py. I used_make_streaming_buffer(chunk and shift 14, cache 3) withsampling_frames = 8instead ofNone. A 16-frame stream alone stops after one step. Frames 15-16 are never fed as central frames in either iterator; initer_with_right_context(8)they appear only as right context of the diarization view at step 0. Batched with a 40-frame stream, a second step feeds them in both views with length 5. - Which batched streams lose the tail. With the same helper, a stream whose last chunk has
rframes (1 ≤ r ≤ 7) loses it exactly when the longest stream in its batch is fewer than8 - rframes longer. I checked this in both iterators for last chunks of 1-14 frames, each alone and next to a stream 1-9 frames longer (140 cases), with no exception. Last chunks of 8 or more frames were always fed.
How often, on a trained model
Setup: stt_en_fastconformer_hybrid_large_streaming_multi, att_context_size=[70, 13], all 2939 LibriSpeech test-other utterances, CPU. Each utterance is streamed on its own, with the same conformer_stream_step loop as the example script. To process the tail I set buffer.sampling_frames = None, which only disables this check. The offline reference is the one compare_vs_offline uses. Frame counts are the buffer's own stream lengths. append_processed_signal stores processed_signal.size(-1), which for every one of these files is one frame more than the length the preprocessor returns.
| RNNT | CTC | |
|---|---|---|
| utterances whose last chunk is 1-7 frames | 186 | 186 |
| of those, streaming alone (current code) == offline | 148 | 121 |
| of those, streaming alone with the tail processed == offline | 186 | 186 |
| transcripts that differ between the two | 38 | 65 |
| ...where the current output is a strict prefix of the other | 38 | 65 |
| ...last word cut / 1 whole word missing / 2 whole words missing | 22 / 15 / 1 | 53 / 12 / 0 |
| ...batched with a longer utterance (6070-86744-0018), current code, gives the tail-processed transcript | 38 | 65 |
For the other utterances the check never fires, so disabling it cannot change their output. As a spot check, the 57 such utterances among the first 60 (RNNT) gave identical transcripts and token ids with and without the check.
These numbers are for streaming one utterance at a time. At batch_size > 1 fewer streams are exposed: a stream with an r-frame tail loses it only when the longest stream in its batch is fewer than 8 - r frames longer (the unit-level condition above). Which streams those are depends on how the manifest is batched.
The lowest-latency lookahead, att_context_size=[70, 0]
This setting uses 8-frame chunks after a 1-frame first chunk, so any stream length that is not 1 mod 8 leaves a short last chunk. On the first 100 test-other utterances (RNNT, CPU):
- 86 have a last chunk of 1-7 frames.
- 36 of those change when the tail is processed. In every case the current output is a strict prefix: 16 end mid-word, 19 miss 1 word and 1 misses 2 words.
- With the tail processed, 83 of the 86 match offline. The other three differ from offline in an earlier word (
i am/i'm,turn/return,gerr/gurr), and their endings match offline. - All 36 get the tail-processed transcript when batched, with the current code, with a longer utterance (7902-96592-0014).
Expected behavior
A stream's output should not depend on the other streams in its batch. The example script's own offline comparison also says (L303): "Normally they should be exactly the same predictions for streaming models". Whether to get there by processing the tail everywhere or by dropping it everywhere is your decision, so I tried both on cf724ac33.
Option A: process the final partial chunk everywhere. Delete the two check blocks, which is equivalent to sampling_frames = None.
- Pair above:
ghastlyat batch size 1 and 2, streaming WER 7.35 = offline WER 7.35. - Random models: streaming alone now gives the offline frame count (29 in B, 57 for the Conformer shape).
- Caveat: a bare deletion crashes a non-causal pre-encoder. I rebuilt the random model from B with
causal_downsampling: false. There, the 9 cache frames plus a 1-7 frame tail leave 0 frames afterdrop_extra_pre_encoded=2, and the stream step raisesRuntimeError: cannot reshape tensor of 0 elements into shape [1, 2, -1, 0] .... The current check prevents that at batch size 1, and offline has no frame for the tail in that setup either. None of the cache-aware configs underexamples/asr/confuse a non-causal convolutional pre-encoder, but the buffer accepts anyStreamingEncoder. - So option A needs a narrower check. The current one is meant to make sure the chunk "has enough frames to produce at least one output after downsampling", but it ignores the pre-encode cache that is prepended right after it. A check on the pre-encoder's output length for cache plus chunk, minus
drop_extra_pre_encoded, separates the two cases above: 1 frame left withcausal_downsampling: true, 0 withfalse. ForConvSubsamplingthat length iscalc_length(...)(subsampling.pyL714, whichforwarduses at L518). The open #15689 addsget_streaming_drop_size(cache_size)to the subsamplers, which forConvSubsamplingwraps the same helper.FeatureStackingalready hascompute_num_out_frames.
Option B: drop the final partial chunk everywhere, per row. Keep the check, and also zero a row's chunk length when its own remaining frames are between 1 and cur_sampling_frames - 1:
remaining = (self.streams_length - self.buffer_idx).clamp(min=0, max=chunk_size)
chunk_lengths = chunk_lengths.masked_fill((remaining > 0) & (remaining < cur_sampling_frames), 0)
(the same for both views in _iter_with_right_context)
- Pair above:
ghastat batch size 1 and 2, streaming WER 8.82 vs offline 7.35. - Random models: streaming next to a longer stream now gives the truncated count (28 in B, 56 for the Conformer shape).
- This makes batching consistent but keeps every truncation in the table above.
Neither option breaks the 12 existing tests in test_streaming_utils.py, but those tests do not reach this check, so they do not tell the options apart. Each option also applies cleanly on top of #16287, and its tests pass (16 passed).
From the numbers above I would lean towards A with a narrower check. I'm happy to open a PR in whichever direction you prefer. Its tests would set sampling_frames in _make_streaming_buffer instead of None, cover both iterators (including the diarization view's lengths), and include a tail of exactly sampling_frames[1] frames.
Environment overview
- Bare metal, NeMo installed from source at
cf724ac33 - Everything above ran on CPU
Environment details
- Ubuntu 22.04.5 LTS
- PyTorch 2.11.0+cu128
- Python 3.12.13
Additional context
- The check in
__iter__has been there since #4920. #16070 copied it into_iter_with_right_context, whichspeech_to_text_multitalker_streaming_infer.pyuses. I checked that iterator only at the unit level (above), not end to end. - Related to #12840, which reported that cache-aware streaming results change with batch size for the same checkpoint. The stale bot closed it as not planned. This is one mechanism for that which is still present on main; I have not checked how much of that report it explains.
- #15482 and #15689 are about the same pre-encoder length arithmetic, for
drop_extra_pre_encoded. - #16287 (mine) is about online-normalization lengths in the same class. It is independent of this issue.
It sounds like the CacheAwareStreamingAudioBuffer might be skipping over the last chunk of audio if it's shorter than the sampling_frames. I'd check how this impacts the final output when streaming next to longer streams.
Hi @kzos, thanks for the detailed investigation and comparison of options A and B. I’d like to help move this forward.
Are you currently working on a fix? If not, I’m happy to take on the implementation, starting with reproducing the issue on current main and investigating option A with the narrower output-length check you outlined. I’d include regression coverage for both iterators, mixed-length batches, and the non-causal case.
Thanks for offering to help, Qing. I'm working on the fix now and will share an update when I have a PR ready.