Skip to content

funasr_onnx streaming Paraformer: a final chunk under 960 samples leaves the frontend caches, so the next stream starts with the end of the previous one #3926

Closed

Description

@tanishqbaweja

Paraformer.__call__ in runtime/python/onnxruntime/funasr_onnx/paraformer_online_bin.py has a shortcut for a final chunk with fewer than 960 samples (60 ms) once the stream has produced features (:142-147):

if waveforms.shape[1] < 16 * 60 and is_final and len(cache) > 0:
    cache["last_chunk"] = True
    feats = cache["feats"]
    feats_len = np.array([feats.shape[1]]).astype(np.int32)
    asr_res = self.infer(feats, feats_len, cache)
    return asr_res

It decodes the cached overlap frames and returns without calling extract_feat. But extract_feat is what resets the online frontend at the end of a stream: WavFrontendOnline.extract_fbank calls cache_reset() on every final call (utils/frontend.py:377-378), which clears input_cache, lfr_splice_cache and reserve_waveforms (:384-388). After this shortcut the frontend keeps them.

The frontend belongs to the model (self.frontend), not to the caller's cache, so a new cache does not help. The next stream decoded with the same model is framed as a continuation of the previous one:

  • the 240-399 samples left in input_cache are put in front of its audio, and
  • its first LFR frame is built from the previous stream's last fbank frame(s) in lfr_splice_cache instead of copies of its own first frame.

So its first 60 ms feature frame comes from the end of the previous stream, and when the left-over sample count is not a multiple of 160, every later 25 ms window is moved too.

This happens after any stream that has produced features and then ends with an empty final call, a common way to end a stream (test_empty_final_still_decodes_existing_overlap_cache covers this call). It also happens with the chunking of demo_paraformer_online.py (600 ms chunks) whenever the audio ends with a last chunk of 2 to 959 samples, about one audio length in ten. A final chunk of 960 samples or more goes through extract_feat and resets the frontend, so the next stream is unaffected.

The C++ runtime resets the frontend in the same branch: ParaformerOnline::Forward calls ResetCache() (which clears reserve_waveforms_, input_cache_ and lfr_splice_cache_) and Reset() before returning (runtime/onnxruntime/src/paraformer-online.cpp:532-539, :391-395). The PyTorch model keeps the frontend state in cache["frontend"] and re-initializes the cache on every final call (funasr/models/paraformer_streaming/model.py:753-754, :547).

Reproduction

main (aa3d789), no model files: the real __call__, WavFrontendOnline, positional encoding and overlap cache run, and only infer (the two ONNX sessions) is replaced by a function that records the encoder input. It decodes 0.6 s of a tone as stream 2 on a fresh model, then on a model that first decoded stream 1 (0.6 s, then a final chunk of 0-4000 samples), and compares the first encoder input of stream 2:

import numpy as np

from funasr_onnx.paraformer_online_bin import Paraformer
from funasr_onnx.utils.frontend import SinusoidalPositionEncoderOnline, WavFrontendOnline


def make_model():
    # Real __call__, frontend, positions and overlap cache; only the ONNX sessions are replaced.
    model = Paraformer.__new__(Paraformer)
    model.chunk_size = [5, 10, 5]
    model.encoder_output_size = 512
    model.feats_dims = 80 * 7
    model.fsmn_layer = 0
    model.frontend = WavFrontendOnline(
        fs=16000, window="hamming", n_mels=80, frame_length=25, frame_shift=10,
        lfr_m=7, lfr_n=6, dither=0.0, cmvn_file=None,
    )
    model.pe = SinusoidalPositionEncoderOnline()
    model.encoder_inputs = []
    model.infer = lambda feats, feats_len, cache: model.encoder_inputs.append(feats.copy()) or []
    return model


t = np.arange(16000 * 3) / 16000
first = (0.3 * np.sin(2 * np.pi * 300 * t)).astype(np.float32)  # stream 1
second = (0.05 * np.sin(2 * np.pi * 800 * t[:9600])).astype(np.float32)  # stream 2

alone = make_model()
alone(second, param_dict={"cache": {}})
expected = alone.encoder_inputs[0]

for last in (0, 500, 959, 960, 4000):
    model = make_model()
    cache = {}
    model(first[:9600], param_dict={"cache": cache})
    model(first[9600 : 9600 + last], param_dict={"cache": cache, "is_final": True})
    frontend = model.frontend
    kept = 0 if frontend.input_cache is None else frontend.input_cache.shape[1]
    spliced = frontend.lfr_splice_cache[0].shape[0] if frontend.lfr_splice_cache else 0
    model.encoder_inputs.clear()
    model(second, param_dict={"cache": {}})  # next stream, new cache, same model
    got = model.encoder_inputs[0]
    if got.shape == expected.shape and np.array_equal(got, expected):
        verdict = "same as stream 2 alone"
    else:
        verdict = f"differs from stream 2 alone (max abs diff {np.abs(got - expected).max():.1f})"
    print(
        f"final chunk {last:4d} samples: frontend keeps {kept} samples, {spliced} fbank frame(s); "
        f"stream 2 encoder input {verdict}"
    )

Output:

final chunk    0 samples: frontend keeps 320 samples, 1 fbank frame(s); stream 2 encoder input differs from stream 2 alone (max abs diff 351.5)
final chunk  500 samples: frontend keeps 320 samples, 1 fbank frame(s); stream 2 encoder input differs from stream 2 alone (max abs diff 351.5)
final chunk  959 samples: frontend keeps 320 samples, 1 fbank frame(s); stream 2 encoder input differs from stream 2 alone (max abs diff 351.5)
final chunk  960 samples: frontend keeps 0 samples, 0 fbank frame(s); stream 2 encoder input same as stream 2 alone
final chunk 4000 samples: frontend keeps 0 samples, 0 fbank frame(s); stream 2 encoder input same as stream 2 alone

Here the difference is the first LFR frame of stream 2 (index 10 of the 20 encoder frames; the first 10 are the zero overlap cache). With a first chunk of 9650 samples instead of 9600, 370 samples are left over, and with a 437 Hz tone as stream 2 all 10 of its frames differ.

Expected behavior

After a final call, the next stream on the same model gives the same features as on a fresh model, whatever the size of the final chunk: same as stream 2 alone on every line, as for final chunks of 960 samples or more.

Environment

  • OS: Windows 11
  • Python: 3.12.15
  • funasr-onnx: 0.4.11, built from runtime/python/onnxruntime at main (aa3d789)
  • numpy 1.26.4, onnxruntime 1.32.0, kaldi-native-fbank 1.23.3, librosa 0.11.0
  • Device: CPU (the ONNX sessions are not called)

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions