File size: 16,427 Bytes
d9bc3e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
377037a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
"""Streaming ASR: family matching, decoder helpers, the streaming board and the board switch."""

from __future__ import annotations

import csv
import io
import re

import numpy as np
import pandas as pd
import pytest

import init
import job_queue
import leaderboard_view as lv
import streaming_config as sc
import streaming_results
from backends import streaming as bs
from diarization_config import TASK_STREAMING, normalize_task
from storage import RESULTS_PATH, STREAMING_RESULTS_PATH
from utils_display import make_clickable_model, model_id_from_leaderboard_cell, split_streaming_key, streaming_key

# ---------------------------------------------------------------------------
# Family matching (Hub metadata -> decoder)
# ---------------------------------------------------------------------------


@pytest.mark.parametrize(
    "model_id, model_type, library, files, family",
    [
        ("nvidia/nemotron-speech-streaming-en-0.6b", "nemotron_asr_streaming", "nemo", ["config.json", "m.nemo"], sc.TRANSFORMERS_RNNT),
        ("nvidia/nemotron-3.5-asr-streaming-0.6b", "nemotron3_5_asr", "nemo", ["config.json", "m.nemo"], sc.TRANSFORMERS_RNNT),
        ("nvidia/parakeet_realtime_eou_120m-v1", "", "nemo", ["parakeet.nemo"], sc.NEMO_CACHE_AWARE),
        ("nvidia/stt_en_fastconformer_hybrid_large_streaming_multi", "", "", ["x.nemo"], sc.NEMO_CACHE_AWARE),
        ("kyutai/stt-2.6b-en", "stt", "moshi", ["config.json"], sc.MOSHI),
        ("kyutai/stt-1b-en_fr-trfs", "kyutai_speech_to_text", "transformers", ["config.json"], sc.CAUSAL),
        ("mistralai/Voxtral-Mini-4B-Realtime-2602", "voxtral_realtime", "vllm", ["config.json"], sc.CAUSAL),
        ("moonshine-ai/moonshine-streaming-small", "moonshine_streaming", "transformers", ["config.json"], sc.CAUSAL),
        (
            "csukuangfj/sherpa-onnx-streaming-zipformer-en-2023-06-26",
            "",
            "",
            ["tokens.txt", "encoder-epoch-99-avg-1-chunk-16-left-128.onnx"],
            sc.SHERPA_ONNX,
        ),
        ("openai/whisper-tiny", "whisper", "transformers", ["config.json"], None),
    ],
)
def test_classify(model_id, model_type, library, files, family):
    assert sc.classify(model_id, model_type=model_type, library=library, files=files) == family


def test_right_context_env(monkeypatch):
    monkeypatch.delenv("FFASR_STREAM_RIGHT_CONTEXT", raising=False)
    assert sc.right_context() == 6
    monkeypatch.setenv("FFASR_STREAM_RIGHT_CONTEXT", "13")
    assert sc.right_context() == 13
    monkeypatch.setenv("FFASR_STREAM_RIGHT_CONTEXT", "junk")
    assert sc.right_context() == 6


def test_streaming_task_is_a_task():
    assert normalize_task("streaming") == TASK_STREAMING
    assert normalize_task("nonsense") == "asr"


# ---------------------------------------------------------------------------
# Decoder helpers (no torch / NeMo / moshi needed)
# ---------------------------------------------------------------------------


def test_pick_att_context_prefers_the_wanted_lookahead():
    opts = [[70, 13], [70, 6], [70, 1], [70, 0]]
    assert bs.pick_att_context(opts, [70, 13], 6) == [70, 6]
    assert bs.pick_att_context(opts, [70, 13], 3) == [70, 13]  # not offered: model default
    assert bs.pick_att_context(None, [70, 0], 6) == [70, 0]
    assert bs.pick_att_context([], None, 6) is None


def test_nemo_chunk_ms():
    class Cfg:
        class preprocessor:
            window_stride = 0.01

    class Model:
        cfg = Cfg

        class encoder:
            subsampling_factor = 8

    assert bs.nemo_chunk_ms(Model, [70, 6]) == pytest.approx(560.0)
    assert bs.nemo_chunk_ms(Model, [70, 0]) == pytest.approx(80.0)


def test_pick_sherpa_files_prefers_fp32_and_widest_context():
    files = [
        "tokens.txt",
        "decoder-epoch-99-avg-1-chunk-16-left-128.int8.onnx",
        "decoder-epoch-99-avg-1-chunk-16-left-128.onnx",
        "decoder-epoch-99-avg-1-chunk-16-left-64.onnx",
        "encoder-epoch-99-avg-1-chunk-16-left-128.int8.onnx",
        "encoder-epoch-99-avg-1-chunk-16-left-128.onnx",
        "encoder-epoch-99-avg-1-chunk-16-left-64.onnx",
        "joiner-epoch-99-avg-1-chunk-16-left-128.onnx",
        "joiner-epoch-99-avg-1-chunk-16-left-64.onnx",
    ]
    picked = bs.pick_sherpa_files(files)
    assert picked == {
        "tokens": "tokens.txt",
        "encoder": "encoder-epoch-99-avg-1-chunk-16-left-128.onnx",
        "decoder": "decoder-epoch-99-avg-1-chunk-16-left-128.onnx",
        "joiner": "joiner-epoch-99-avg-1-chunk-16-left-128.onnx",
    }
    assert sc.sherpa_chunk_ms(picked["encoder"]) == 320


def test_decode_moshi_tokens_drops_padding():
    class Tok:
        def decode(self, ids):
            return " ".join(str(i) for i in ids)

    assert bs.decode_moshi_tokens(Tok(), [0, 3, 11, 3, 12, 0], {0, 3}) == "11 12"
    assert bs.decode_moshi_tokens(Tok(), [3, 3], {0, 3}) == ""


class _FakeInputs(dict):
    def __getattr__(self, k):
        return self[k]


class _FakeProcessor:
    """Shape-only stand-in for the Nemotron streaming processor (mel frames == samples / hop)."""

    num_samples_first_audio_chunk = 1000
    num_mel_frames_first_audio_chunk = 10
    num_samples_per_audio_chunk = 800
    num_mel_frames_per_audio_chunk = 8

    class feature_extractor:
        hop_length = 100
        n_fft = 400

    def __init__(self):
        self.calls = []

    def __call__(self, audio, **kw):
        self.calls.append((len(audio), kw))
        frames = max(1, len(audio) // 100)
        return _FakeInputs(input_features=np.zeros((1, frames, 4)))


def test_stream_feature_chunks_cover_the_whole_utterance():
    proc = _FakeProcessor()
    audio = np.ones(5000, dtype=np.float32)
    first, features = bs.stream_feature_chunks(proc, audio, sampling_rate=16000, extra={"language": "en-US"})
    chunks = list(features(lambda x: x))
    assert chunks[0].shape[1] == proc.num_mel_frames_first_audio_chunk
    mel_frames = proc.num_mel_frames_first_audio_chunk + proc.num_mel_frames_per_audio_chunk * (len(chunks) - 1)
    # Every real sample (plus the lookahead tail) reached the model.
    assert mel_frames * proc.feature_extractor.hop_length >= len(audio)
    assert all(kw.get("is_streaming") and kw.get("language") == "en-US" for _, kw in proc.calls)
    assert [kw["is_first_audio_chunk"] for _, kw in proc.calls] == [True] + [False] * (len(proc.calls) - 1)


# ---------------------------------------------------------------------------
# Streaming board storage and queue routing
# ---------------------------------------------------------------------------


def _fake_storage(monkeypatch):
    files: dict[str, bytes] = {}

    def fake_download(path, **kwargs):
        blob = files.get(path)
        if blob is None:
            raise FileNotFoundError(path)
        import tempfile

        f = tempfile.NamedTemporaryFile("w", suffix=".csv", delete=False, encoding="utf-8")
        f.write(blob.decode("utf-8"))
        f.close()
        return f.name

    def fake_upload(bucket, *, add=None, **kwargs):
        for src, dst in add or []:
            files[dst] = bytes(src)

    for mod in (init, streaming_results):
        monkeypatch.setattr(mod, "download_bucket_file", fake_download)
        monkeypatch.setattr(mod, "upload_to_bucket", fake_upload)
    monkeypatch.setattr("storage.append_private_submission", lambda **kwargs: None)
    init.invalidate_results_cache()
    streaming_results.invalidate_cache()
    return files


STREAM_RESULT = {
    "model_id": "nvidia/nemotron-speech-streaming-en-0.6b",
    "eval_family": "Streaming",
    "task": "streaming",
    # Wire keys, as the evaluation emits them (benchmark.dataset.wer_result_key).
    "wer_clean": 0.05,
    "wer_high": 0.08,
    "wer_mid": 0.1,
    "wer_low": 0.2,
    "eval_rtf": 40.0,
    "stream_family": sc.TRANSFORMERS_RNNT,
    "stream_mode": "incremental",
    "stream_latency_ms": 560,
}


def test_streaming_result_goes_to_its_own_board(monkeypatch):
    files = _fake_storage(monkeypatch)
    job_queue._merge_eval_result_to_leaderboard(dict(STREAM_RESULT), "2026-11-13T00:00:00Z", "")
    assert RESULTS_PATH not in files  # offline board untouched
    rows = list(csv.DictReader(io.StringIO(files[STREAMING_RESULTS_PATH].decode("utf-8"))))
    assert len(rows) == 1
    row = rows[0]
    assert row["model_id"] == STREAM_RESULT["model_id"]
    assert row["wer_realistic_low_snr"] == "0.2"
    assert row["stream_latency_ms"] == "560" and row["stream_family"] == sc.TRANSFORMERS_RNNT
    assert job_queue._task_has_model(TASK_STREAMING, STREAM_RESULT["model_id"])
    assert not job_queue._task_has_model("asr", STREAM_RESULT["model_id"])

    with pytest.raises(RuntimeError, match="already on the streaming leaderboard"):
        streaming_results.merge_eval_result(dict(STREAM_RESULT), "2026-11-14T00:00:00Z")
    streaming_results.merge_eval_result(
        {**STREAM_RESULT, "wer_low": 0.3}, "2026-11-14T00:00:00Z", replace_existing=True
    )
    assert streaming_results.row_for_model(STREAM_RESULT["model_id"])["wer_realistic_low_snr"] == "0.3"


def test_enqueue_streaming_uses_the_streaming_family_and_no_recipe(monkeypatch):
    monkeypatch.setattr(job_queue, "MODERATION_ENABLED", True)
    monkeypatch.setattr(job_queue, "MODERATOR_SECRET", "s")
    monkeypatch.setattr(job_queue, "_ensure_worker", lambda: None)
    monkeypatch.setattr(job_queue, "_persist_jobs", lambda: None)
    monkeypatch.setattr(job_queue, "_task_has_model", lambda *a, **k: False)
    monkeypatch.setattr(job_queue, "_record_submission_pii", lambda **kwargs: None)
    monkeypatch.setattr("remote_jobs.remote_jobs_enabled", lambda: True)
    job_queue._jobs.clear()
    job_queue._submit_hits.clear()

    # A model on the offline board can still be queued for streaming, and vice versa.
    jid, _pos, err, awaiting = job_queue.enqueue(
        "zhifeixie/Mega-ASR", "auto", contact_email="a@b.co", task=TASK_STREAMING
    )
    assert err is None and awaiting
    job = job_queue._jobs[jid]
    assert job.task == TASK_STREAMING and job.family_id == "streaming" and job.recipe_id == ""
    assert "streaming" in job_queue.task_badge_html(job.task)
    assert not job_queue._model_in_flight("zhifeixie/Mega-ASR", "asr")
    assert job_queue._model_in_flight("zhifeixie/Mega-ASR", TASK_STREAMING)
    job_queue._jobs.clear()


def test_streaming_deps_follow_the_family(monkeypatch):
    import remote_jobs

    for family, needle in (
        (sc.NEMO_CACHE_AWARE, "nemo_toolkit"),
        (sc.MOSHI, "moshi"),
        (sc.SHERPA_ONNX, "sherpa-onnx"),
        (sc.TRANSFORMERS_RNNT, "transformers @ git+"),
        (sc.CAUSAL, "transformers @ git+"),
    ):
        monkeypatch.setattr(sc, "resolve_family", lambda mid, f=family: f)
        deps = remote_jobs._select_deps("org/model", "streaming", task="streaming")
        assert any(d.startswith(needle) for d in deps), (family, deps)
        assert "torch<2.11" in deps


# ---------------------------------------------------------------------------
# Board: streaming keys, tags and the switch
# ---------------------------------------------------------------------------


def test_streaming_key_round_trip_and_link():
    key = streaming_key("org/m")
    assert split_streaming_key(key) == ("org/m", True)
    assert split_streaming_key("org/m") == ("org/m", False)
    cell = make_clickable_model(key)
    assert 'href="https://huggingface.co/org/m"' in cell
    assert model_id_from_leaderboard_cell(cell) == key


def _frame(rows):
    return pd.DataFrame(rows, columns=[lv.RANK_COL, lv.MODEL_COL, lv.AutoEvalColumn.avg_wer_core.name])


def test_switch_replaces_the_changes_summary():
    df = _frame([[1, make_clickable_model("org/a"), 5.0], [2, make_clickable_model("org/b"), 6.0]])
    html = lv.render_asr_table(df, {}, newest="org/b", moves={"org/a": 1}, stream_switch={"on": False, "count": 3})
    assert "changed position" not in html and "was added:" not in html
    assert "data-streaming aria-checked='false'" in html and ">3</span>" in html
    assert "ff-stream'" not in html  # no streaming rows while off

    off = lv.render_asr_table(df, {}, stream_switch={"on": False, "count": 0})
    assert " disabled" in off and "No streaming model has results yet" in off
    assert "data-streaming" not in lv.render_asr_table(df, {}, version="v1", stream_switch=None)


def test_streaming_rows_are_tagged_and_keyed_apart():
    key = streaming_key("org/a")
    df = _frame([[1, make_clickable_model(key), 4.0], [2, make_clickable_model("org/a"), 5.0]])
    info = {key: {"latency_ms": 560.0, "mode": "incremental", "family": "NeMo cache-aware streaming"}}
    html = lv.render_asr_table(df, {}, streaming=info, stream_switch={"on": True, "count": 1})
    assert re.findall(r"<tr data-model='([^']+)'", html) == [key, "org/a"]
    assert html.count("data-streaming=1") == 1
    assert "Streaming · 560 ms" in html
    assert "aria-checked='true'" in html
    assert "1 streaming model is ranked with the offline models" in html
    # The name shown is the Hub id, without the key suffix.
    assert "(streaming)</span>" not in html.split("<tbody>")[1].split("ff-sr")[0]

    chart = lv.render_wer_chart(df, {}, {}, streaming=info)
    assert "ff-col is-stream" in chart and "data-latency='560'" in chart
    assert "Striped bars are streaming models." in chart
    assert ", streaming'" in chart


def test_board_combines_streaming_rows_when_switched_on(monkeypatch):
    import app

    offline = [
        {"model_id": "org/off", "wer_anechoic_speech": "0.10", "wer_realistic_high_snr": "0.10",
         "wer_realistic_mid_snr": "0.10", "wer_realistic_low_snr": "0.10", "submitted_at": "2026-01-01"},
    ]
    stream = [{
        "model_id": "org/off", "wer_anechoic_speech": "0.05", "wer_realistic_high_snr": "0.05",
        "wer_realistic_mid_snr": "0.05", "wer_realistic_low_snr": "0.05",
        "stream_family": sc.NEMO_CACHE_AWARE, "stream_mode": "incremental", "stream_latency_ms": "560",
    }]
    monkeypatch.setattr(app, "load_raw_results", lambda *a, **k: [dict(r) for r in offline])
    monkeypatch.setattr(app, "load_results", lambda *a, **k: app._display_df_from_raw_rows(offline))
    monkeypatch.setattr(app.streaming_results, "load_rows", lambda *a, **k: [dict(r) for r in stream])
    monkeypatch.setattr(app, "_lineage_chains", lambda snap: {})

    html_off, _ = app._leaderboard_table_update("", app.DEFAULT_VISIBLE_COLS, None, False)
    assert "(streaming)'" not in html_off and "aria-checked='false'" in html_off

    html_on, _ = app._leaderboard_table_update("", app.DEFAULT_VISIBLE_COLS, None, True)
    keys = re.findall(r"<tr data-model='([^']+)'", html_on)
    # Same model, both rows; the streaming run (lower WER here) ranks first.
    assert keys == ["org/off (streaming)", "org/off"]
    assert "Streaming · 560 ms" in html_on and "aria-checked='true'" in html_on


# ---------------------------------------------------------------------------
# VibeVoice
# ---------------------------------------------------------------------------


def test_vibevoice_routing_and_hardware():
    import remote_jobs
    from recipes.registry import resolve_recipe_id

    assert sc.classify("microsoft/VibeVoice-ASR-Streaming-7B", model_type="vibevoice") == sc.VIBEVOICE
    assert resolve_recipe_id("microsoft/VibeVoice-ASR") == "vibevoice_asr"
    for other in ("microsoft/VibeVoice-ASR-Streaming-7B", "microsoft/VibeVoice-ASR-HF", "microsoft/VibeVoice-ASR-BitNet"):
        assert resolve_recipe_id(other) is None
    assert remote_jobs._flavor_for_submission("l4x1", "microsoft/VibeVoice-ASR-Streaming-7B", None) == "l40sx1"
    assert remote_jobs._flavor_for_submission("l4x1", "microsoft/VibeVoice-ASR-Streaming-1.5B", None) == "l4x1"
    assert remote_jobs._flavor_for_submission("a100-large", "microsoft/VibeVoice-ASR", "vibevoice_asr") == "a100-large"


def test_vibevoice_text_cleanup():
    from recipes.vibevoice_asr.evaluate import transcript_text

    chunks = ["Speaker 0: Hello the", "re, how are", " you? [Noise] Speaker 1: Fine."]
    assert bs.vibevoice_stream_text(chunks) == "Hello there, how are you? Fine."
    segs = [{"speaker_id": 0, "text": "Hello there."}, {"speaker_id": 1, "text": "[Laughter] Fine."}]
    assert transcript_text("ignored", segs) == "Hello there. Fine."
    raw = '[{"Start time": 0.0, "End time": 1.2, "Speaker ID": 0, "Content": "Hi all."}]'
    assert transcript_text(raw, []) == "Hi all."