""" Streaming ASR decoders for the streaming board (family id ``streaming``). Each builder returns ``(transcribe, cleanup)`` like the other backends. ``transcribe(audio_np, sampling_rate)`` takes the whole 16 kHz utterance, but the incremental decoders hand it to the model in short chunks through the model's own streaming API and return what the model emitted by the end of the stream. ``transcribe._stream_meta`` carries the fields the leaderboard stores (``streaming_config.STREAM_FIELDS``). Evaluation runs one utterance at a time, as for every backend. See ``streaming_config`` for how a model is matched to a decoder. """ from __future__ import annotations import re import sys from collections.abc import Callable import numpy as np import streaming_config as sc Transcriber = tuple[Callable[..., str], Callable[[], None]] def _log(msg: str) -> None: print(f"[streaming] {msg}", file=sys.stderr, flush=True) def _meta(family: str, latency_ms: float | int | None) -> dict: return { "stream_family": family, "stream_mode": sc.mode_for(family), "stream_latency_ms": "" if latency_ms is None else int(round(float(latency_ms))), } def _to_device(model, device_str: str): import torch if (device_str or "").lower() == "cuda" and torch.cuda.is_available(): return model.to("cuda"), "cuda" return model.to("cpu"), "cpu" # --------------------------------------------------------------------------- # NeMo cache-aware FastConformer (stt_*_streaming_*, parakeet_realtime_eou, …) # --------------------------------------------------------------------------- def pick_att_context(options, default, wanted_right: int): """The ``[left, right]`` attention context to stream with. Multi-lookahead checkpoints list several; take the one whose right context is ``wanted_right`` (else the default). Single-latency checkpoints keep their default. """ opts = [list(o) for o in (options or []) if o is not None and len(o) == 2] for o in opts: if int(o[1]) == int(wanted_right): return o return list(default) if default is not None else (opts[0] if opts else None) def nemo_chunk_ms(model, att_context) -> float | None: """Algorithmic latency of a cache-aware chunk: (right context + 1) encoder frames.""" try: sub = int(getattr(model.encoder, "subsampling_factor", 8) or 8) stride = float(model.cfg.preprocessor.window_stride) return (int(att_context[1]) + 1) * sub * stride * 1000.0 except Exception: return None def _hyp_text(h) -> str: if h is None: return "" if hasattr(h, "text"): return str(h.text or "") return str(h) def _use_streaming_rnnt_decoding(model) -> None: """Plain greedy RNNT decoding, which carries the hypothesis from chunk to chunk. The batched greedy decoders (label/frame looping, CUDA graphs) reject the ``partial_hypotheses`` that ``conformer_stream_step`` passes in (NotImplementedError), so switch to ``strategy="greedy"`` as NeMo's cache-aware streaming example does. CTC-only models (no joint) keep their decoding. """ if not hasattr(model, "joint"): return import copy from omegaconf import open_dict cfg = copy.deepcopy(model.cfg.decoding) with open_dict(cfg): cfg.strategy = "greedy" cfg.preserve_alignments = False cfg.fused_batch_size = -1 if cfg.get("greedy") is not None: cfg.greedy.max_symbols = 10 # Hybrid RNNT/CTC models: no decoder_type keeps the RNNT decoder, which is what streams here. model.change_decoding_strategy(cfg) def build_nemo_cache_aware(model_id: str, device_str: str) -> Transcriber: import torch import nemo.collections.asr as nemo_asr from nemo.collections.asr.parts.utils.streaming_utils import CacheAwareStreamingAudioBuffer from ._model_utils import attach_params model = nemo_asr.models.ASRModel.from_pretrained(model_name=model_id) model, actual = _to_device(model, device_str) model.eval() enc = model.encoder if not hasattr(enc, "streaming_cfg") or not hasattr(model, "conformer_stream_step"): raise RuntimeError(f"{model_id} is a NeMo model without a cache-aware streaming encoder.") att = pick_att_context( getattr(enc, "att_context_size_all", None), getattr(enc, "att_context_size", None), sc.right_context() ) if att is not None and hasattr(enc, "set_default_att_context_size"): enc.set_default_att_context_size(att) enc.setup_streaming_params() _use_streaming_rnnt_decoding(model) latency = nemo_chunk_ms(model, att) if att is not None else None _log(f"nemo cache-aware: device={actual} att_context_size={att} chunk={latency} ms") def _drop_extra(step: int) -> int: # ``pad_and_drop_preencoded=False``: the first chunk keeps its pre-encoded frames. return 0 if step == 0 else int(enc.streaming_cfg.drop_extra_pre_encoded) def transcribe(audio_np, sampling_rate: int = 16000) -> str: audio = np.asarray(audio_np, dtype=np.float32).reshape(-1) buffer = CacheAwareStreamingAudioBuffer(model=model, online_normalization=False, pad_and_drop_preencoded=False) buffer.append_audio(audio, stream_id=-1) cache_ch, cache_t, cache_len = enc.get_initial_cache_state(batch_size=1) prev_hyps = None prev_out = None texts = None with torch.inference_mode(): for step, (chunk, chunk_len) in enumerate(iter(buffer)): prev_out, texts, cache_ch, cache_t, cache_len, prev_hyps = model.conformer_stream_step( processed_signal=chunk, processed_signal_length=chunk_len, cache_last_channel=cache_ch, cache_last_time=cache_t, cache_last_channel_len=cache_len, keep_all_outputs=buffer.is_buffer_empty(), previous_hypotheses=prev_hyps, previous_pred_out=prev_out, drop_extra_pre_encoded=_drop_extra(step), return_transcription=True, ) return _hyp_text(texts[0]) if texts else "" attach_params(transcribe, model) transcribe._stream_meta = _meta(sc.NEMO_CACHE_AWARE, latency) def cleanup() -> None: nonlocal model del model return transcribe, cleanup # --------------------------------------------------------------------------- # Nemotron ASR streaming in Transformers (nemotron-speech-streaming, nemotron-3.5-asr-streaming) # --------------------------------------------------------------------------- def stream_feature_chunks(processor, audio: np.ndarray, *, sampling_rate: int, extra: dict): """Yield ``(first_inputs, input_features generator)`` the way the model card streams. The first chunk has its own size; after that every chunk is ``num_samples_per_audio_chunk`` samples, overlapping by half an FFT window so the mel frames line up. Trailing silence lets the last real chunk through the lookahead. """ tail = int(processor.num_samples_per_audio_chunk) * 2 + int(processor.feature_extractor.n_fft) audio = np.concatenate([audio, np.zeros(tail, dtype=np.float32)]) first = processor( audio[: processor.num_samples_first_audio_chunk], sampling_rate=sampling_rate, is_streaming=True, is_first_audio_chunk=True, return_tensors="pt", **extra, ) def features(to_model: Callable): yield to_model(first).input_features[:, : processor.num_mel_frames_first_audio_chunk, :] hop = int(processor.feature_extractor.hop_length) n_fft = int(processor.feature_extractor.n_fft) mel_idx = int(processor.num_mel_frames_first_audio_chunk) start = mel_idx * hop - n_fft // 2 while (end := start + int(processor.num_samples_per_audio_chunk)) < audio.shape[0]: chunk = processor( audio[start:end], sampling_rate=sampling_rate, is_streaming=True, is_first_audio_chunk=False, return_tensors="pt", **extra, ) yield to_model(chunk).input_features mel_idx += int(processor.num_mel_frames_per_audio_chunk) start = mel_idx * hop - n_fft // 2 return first, features def build_transformers_rnnt(model_id: str, device_str: str) -> Transcriber: import torch from transformers import AutoModelForRNNT, AutoProcessor from ._model_utils import attach_params from .family_resolve import infer_model_type processor = AutoProcessor.from_pretrained(model_id) model = AutoModelForRNNT.from_pretrained(model_id) model, actual = _to_device(model, device_str) model.eval() if hasattr(processor, "set_num_lookahead_tokens"): processor.set_num_lookahead_tokens(sc.right_context()) latency = getattr(processor, "streaming_latency_ms", None) # The multilingual model takes a language prompt with every chunk; the test set is English. extra = {"language": "en-US"} if infer_model_type(model_id) == "nemotron3_5_asr" else {} sr = int(processor.feature_extractor.sampling_rate) _log(f"transformers rnnt: device={actual} latency={latency} ms extra={extra}") def to_model(inputs): return inputs.to(model.device, dtype=model.dtype) def transcribe(audio_np, sampling_rate: int = 16000) -> str: audio = np.asarray(audio_np, dtype=np.float32).reshape(-1) if int(sampling_rate) != sr: import librosa audio = librosa.resample(audio, orig_sr=int(sampling_rate), target_sr=sr).astype(np.float32) first, features = stream_feature_chunks(processor, audio, sampling_rate=sr, extra=extra) kwargs = {**to_model(first), "input_features": features(to_model)} with torch.inference_mode(): out = model.generate(**kwargs, return_dict_in_generate=True) seqs = getattr(out, "sequences", out) return str(processor.batch_decode(seqs, skip_special_tokens=True)[0]).strip() attach_params(transcribe, model) transcribe._stream_meta = _meta(sc.TRANSFORMERS_RNNT, latency) def cleanup() -> None: nonlocal model del model return transcribe, cleanup # --------------------------------------------------------------------------- # Kyutai STT (delayed streams) through moshi # --------------------------------------------------------------------------- def decode_moshi_tokens(tokenizer, ids: list[int], skip: set[int]) -> str: keep = [int(i) for i in ids if int(i) not in skip] if not keep: return "" try: return str(tokenizer.decode(keep)).strip() except Exception: return "".join(tokenizer.id_to_piece(i) for i in keep).replace("▁", " ").strip() def build_moshi(model_id: str, device_str: str) -> Transcriber: import itertools import math import torch import torchaudio from moshi.models import LMGen, loaders from ._model_utils import attach_params device = "cuda" if (device_str or "").lower() == "cuda" and torch.cuda.is_available() else "cpu" info = loaders.CheckpointInfo.from_hf_repo(model_id) mimi = info.get_mimi(device=device) tokenizer = info.get_text_tokenizer() lm = info.get_moshi(device=device, dtype=torch.bfloat16 if device == "cuda" else torch.float32) lm_gen = LMGen(lm, temp=0, temp_text=0.0) stt = getattr(info, "stt_config", None) or {} prefix_s = float(stt.get("audio_silence_prefix_seconds", 1.0)) delay_s = float(stt.get("audio_delay_seconds", 0.5)) pad_id = int((getattr(info, "raw_config", None) or {}).get("text_padding_token_id", 3)) skip = {0, pad_id} frame = int(mimi.frame_size) _log(f"moshi: device={device} delay={delay_s}s frame={frame} samples @ {mimi.sample_rate} Hz") def transcribe(audio_np, sampling_rate: int = 16000) -> str: audio = torch.from_numpy(np.asarray(audio_np, dtype=np.float32).reshape(1, -1)).to(device) audio = torchaudio.functional.resample(audio, int(sampling_rate), int(mimi.sample_rate)) if audio.shape[-1] % frame: audio = torch.nn.functional.pad(audio, (0, frame - audio.shape[-1] % frame)) silence = torch.zeros((1, 1, frame), dtype=torch.float32, device=device) chunks = itertools.chain( itertools.repeat(silence, math.ceil(prefix_s * mimi.frame_rate)), torch.split(audio[:, None], frame, dim=-1), # The text runs ``delay_s`` behind the audio; flush it with silence. itertools.repeat(silence, math.ceil(delay_s * mimi.frame_rate) + 1), ) ids: list[int] = [] with torch.inference_mode(), mimi.streaming(1), lm_gen.streaming(1): for chunk in chunks: tokens = lm_gen.step(mimi.encode(chunk)) if tokens is not None: ids.append(int(tokens[0, 0, 0].item())) return decode_moshi_tokens(tokenizer, ids, skip) attach_params(transcribe, lm) transcribe._stream_meta = _meta(sc.MOSHI, delay_s * 1000.0) def cleanup() -> None: nonlocal lm, mimi, lm_gen del lm_gen, lm, mimi return transcribe, cleanup # --------------------------------------------------------------------------- # sherpa-onnx online transducer (k2 streaming Zipformer) # --------------------------------------------------------------------------- def pick_sherpa_files(files: list[str]) -> dict[str, str]: """encoder / decoder / joiner / tokens for one export: fp32 first, then the widest left context.""" def rank(name: str) -> tuple[int, int]: left = 0 for part in name.replace(".", "-").split("-"): if part.isdigit(): left = max(left, int(part)) return (1 if ".int8." in name else 0, -left) out: dict[str, str] = {} tokens = [f for f in files if f.rsplit("/", 1)[-1] == "tokens.txt"] if tokens: out["tokens"] = tokens[0] encoders = sorted((f for f in files if f.endswith(".onnx") and "encoder" in f.rsplit("/", 1)[-1]), key=rank) if not encoders: return out enc = encoders[0] out["encoder"] = enc for part in ("decoder", "joiner"): twin = enc.replace("encoder", part) if twin in files: out[part] = twin else: cands = sorted((f for f in files if f.endswith(".onnx") and part in f.rsplit("/", 1)[-1]), key=rank) if cands: out[part] = cands[0] return out def build_sherpa_onnx(model_id: str, device_str: str) -> Transcriber: import os import sherpa_onnx from huggingface_hub import HfApi, snapshot_download token = os.environ.get("HF_TOKEN") or None files = [s.rfilename for s in (HfApi(token=token).model_info(model_id).siblings or [])] picked = pick_sherpa_files(files) missing = {"tokens", "encoder", "decoder", "joiner"} - set(picked) if missing: raise RuntimeError(f"{model_id}: no sherpa-onnx online transducer files ({', '.join(sorted(missing))} missing).") root = snapshot_download(model_id, allow_patterns=list(picked.values()), token=token) paths = {k: os.path.join(root, v) for k, v in picked.items()} recognizer = sherpa_onnx.OnlineRecognizer.from_transducer( tokens=paths["tokens"], encoder=paths["encoder"], decoder=paths["decoder"], joiner=paths["joiner"], num_threads=int(os.environ.get("FFASR_SHERPA_THREADS", "4") or 4), sample_rate=16000, feature_dim=80, decoding_method="greedy_search", provider="cpu", ) latency = sc.sherpa_chunk_ms(picked["encoder"]) step = int(16000 * sc.FEED_CHUNK_MS / 1000) _log(f"sherpa-onnx: encoder={picked['encoder']} chunk={latency} ms (CPU)") def transcribe(audio_np, sampling_rate: int = 16000) -> str: audio = np.asarray(audio_np, dtype=np.float32).reshape(-1) stream = recognizer.create_stream() for start in range(0, audio.shape[0], step): stream.accept_waveform(int(sampling_rate), audio[start : start + step]) while recognizer.is_ready(stream): recognizer.decode_stream(stream) # Trailing silence pushes the last frames through the encoder's right context. stream.accept_waveform(int(sampling_rate), np.zeros(int(0.66 * int(sampling_rate)), dtype=np.float32)) stream.input_finished() while recognizer.is_ready(stream): recognizer.decode_stream(stream) res = recognizer.get_result(stream) return str(getattr(res, "text", res)).strip() transcribe._num_params = 0 transcribe._stream_meta = _meta(sc.SHERPA_ONNX, latency) def cleanup() -> None: nonlocal recognizer del recognizer return transcribe, cleanup # --------------------------------------------------------------------------- # VibeVoice-ASR-Streaming (microsoft/VibeVoice, ``streaming_generate``) # --------------------------------------------------------------------------- _VV_SPEAKER_RE = re.compile(r"Speaker\s+\d+\s*:") _VV_TAG_RE = re.compile(r"\[[^\[\]]*\]") # non-speech events: [Noise], [Laughter], [Silence] def vibevoice_stream_text(chunk_texts: list[str]) -> str: """Plain transcript from VibeVoice's per-chunk ``Speaker N: …`` blocks. Chunks join with no separator (their text carries its own spacing), as in VibeVoice's own ``vllm_plugin.asr_streaming.chunk_segments``; speaker labels and event tags are not words. """ text = _VV_TAG_RE.sub(" ", _VV_SPEAKER_RE.sub(" ", "".join(chunk_texts))) return re.sub(r"\s+", " ", text).strip() def vibevoice_frame_config(model_id: str) -> dict: """Chunk and lookahead the checkpoint was trained on (its ``preprocessor_config.json``).""" import json import os from huggingface_hub import hf_hub_download path = hf_hub_download(model_id, "preprocessor_config.json", token=os.environ.get("HF_TOKEN") or None) with open(path, encoding="utf-8") as f: cfg = json.load(f) missing = [k for k in ("chunk_frames", "lookahead_frames") if k not in cfg] if missing: raise RuntimeError(f"{model_id} is not a VibeVoice streaming checkpoint (no {', '.join(missing)}).") sr = int(cfg.get("target_sample_rate", 24000)) frame_s = float(cfg["speech_tok_compress_ratio"]) / sr return { "sample_rate": sr, "chunk_duration": cfg["chunk_frames"] * frame_s, "text_audio_delay": cfg["lookahead_frames"] * frame_s, } def build_vibevoice(model_id: str, device_str: str) -> Transcriber: import torch from vibevoice.modular.modeling_vibevoice_asr import VibeVoiceASRForConditionalGeneration from vibevoice.processor.vibevoice_asr_processor import VibeVoiceASRProcessor from ._model_utils import attach_params frames = vibevoice_frame_config(model_id) processor = VibeVoiceASRProcessor.from_pretrained(model_id) if getattr(processor.tokenizer, "text_chunk_end_id", None) is None: raise RuntimeError(f"{model_id} has no <|text_chunk_end|> token, so it is not a streaming checkpoint.") device = "cuda" if (device_str or "").lower() == "cuda" and torch.cuda.is_available() else "cpu" model = ( VibeVoiceASRForConditionalGeneration.from_pretrained( model_id, dtype=torch.bfloat16 if device == "cuda" else torch.float32, attn_implementation="sdpa", ) .to(device) .eval() ) sr = int(frames["sample_rate"]) # Text for a chunk comes out once the chunk and its lookahead have arrived. latency = (frames["chunk_duration"] + frames["text_audio_delay"]) * 1000.0 _log( f"vibevoice: device={device} chunk={frames['chunk_duration']:.3f}s " f"lookahead={frames['text_audio_delay']:.3f}s @ {sr} Hz" ) def transcribe(audio_np, sampling_rate: int = 16000) -> str: audio = np.asarray(audio_np, dtype=np.float32).reshape(-1) if int(sampling_rate) != sr: import librosa audio = librosa.resample(audio, orig_sr=int(sampling_rate), target_sr=sr).astype(np.float32) chunks: list[str] = [] with torch.inference_mode(): for _idx, _total, chunk_text in model.streaming_generate( audio_tensor=torch.from_numpy(audio), tokenizer=processor.tokenizer, chunk_duration=frames["chunk_duration"], text_audio_delay=frames["text_audio_delay"], sample_rate=sr, max_new_tokens_per_chunk=256, temperature=0.0, ): chunks.append(chunk_text) return vibevoice_stream_text(chunks) attach_params(transcribe, model) transcribe._stream_meta = _meta(sc.VIBEVOICE, latency) def cleanup() -> None: nonlocal model del model return transcribe, cleanup # --------------------------------------------------------------------------- # Causal-by-design models (whole-utterance pass) # --------------------------------------------------------------------------- def causal_latency_ms(model_id: str) -> float | None: """Text delay declared in the checkpoint config, when it declares one.""" from .family_resolve import load_hub_config cfg = load_hub_config(model_id) if cfg.get("default_num_delay_tokens") is not None: # Voxtral Realtime: 80 ms per token try: return float(cfg["default_num_delay_tokens"]) * sc.FRAME_MS except (TypeError, ValueError): return None stt = cfg.get("stt_config") or {} if stt.get("audio_delay_seconds") is not None: try: return float(stt["audio_delay_seconds"]) * 1000.0 except (TypeError, ValueError): return None return None def build_causal(model_id: str, device_str: str, device_int: int) -> Transcriber: from . import auto transcribe, cleanup = auto.build_transcriber(model_id, device_str, device_int) transcribe._stream_meta = _meta(sc.CAUSAL, causal_latency_ms(model_id)) return transcribe, cleanup # --------------------------------------------------------------------------- def build_transcriber(model_id: str, device_str: str, device_int: int = -1) -> Transcriber: family = sc.resolve_family(model_id) _log(f"{model_id}: streaming family={family!r}") if family == sc.NEMO_CACHE_AWARE: return build_nemo_cache_aware(model_id, device_str) if family == sc.TRANSFORMERS_RNNT: return build_transformers_rnnt(model_id, device_str) if family == sc.MOSHI: return build_moshi(model_id, device_str) if family == sc.SHERPA_ONNX: return build_sherpa_onnx(model_id, device_str) if family == sc.VIBEVOICE: return build_vibevoice(model_id, device_str) if family == sc.CAUSAL: return build_causal(model_id, device_str, device_int) raise RuntimeError( f"{model_id} has no streaming decoder. The streaming board runs NeMo cache-aware models, " "Nemotron ASR streaming, Kyutai STT, sherpa-onnx online transducers, VibeVoice-ASR-Streaming " "and causal streaming " "models (Voxtral Realtime, Moonshine Streaming). For anything else, submit a custom " "evaluate() that streams the audio." )