diff --git a/README.md b/README.md index c097acd..daf6f56 100644 --- a/README.md +++ b/README.md @@ -83,8 +83,15 @@ scriptrs = { version = "0.5", features = ["vad"] } `TranscriptionError::Control(TranscriptionControlError::Cancelled)` instead of `TranscriptionError::Cancelled`, and likewise for the other two. - `VadConfig` is gone. The speech threshold is now - `VadSegmentationConfig::threshold`, still 0.5 by default: set - `config.segmentation.threshold` instead of `config.vad.default_threshold`. + `VadSegmentationConfig::threshold`: set `config.segmentation.threshold` + instead of `config.vad.default_threshold`. +- VAD mode defaults to Silero fusion (`VadModel::SileroFusion`): it scores each + window with both Silero VAD v5 and v6 and keeps the higher probability, at a 0.6 threshold, in place of v5 alone at 0.5. Set + `config.segmentation = VadSegmentationConfig::for_model(VadModel::SileroV5)` + to keep v5-only planning. `VadSegmentationConfig` has a new `model` field, so + struct literals that list every field need it. VAD bundles need both models + (see [Local model layout](#local-model-layout)), and + `ModelBundle::validate_long_form` checks for both. - `Vocabulary` loads only through a deployment, with `Vocabulary::load(path, &deployment)` or `Vocabulary::from_bytes(bytes, &deployment)`. `load` takes the deployment in @@ -132,15 +139,16 @@ With the default `online` feature, `scriptrs` can resolve models automatically: - native CUDA weights come from [`avencera/parakeet-tdt-0.6b-v2-cuda`](https://huggingface.co/avencera/parakeet-tdt-0.6b-v2-cuda) and [`avencera/parakeet-tdt-0.6b-v3-cuda`](https://huggingface.co/avencera/parakeet-tdt-0.6b-v3-cuda), - and the native Silero VAD from + and the native Silero VAD models from [`avencera/silero-vad-v5-safetensors`](https://huggingface.co/avencera/silero-vad-v5-safetensors) + and [`avencera/silero-vad-v6-safetensors`](https://huggingface.co/avencera/silero-vad-v6-safetensors) You can force a local bundle when needed: - `SCRIPTRS_MODELS_DIR=/path/to/models` forces a local bundle Each download uses an immutable snapshot pinned in the release, such as -`63f6f9cbce43e5561c219229896f86f20c0eb660` of `avencera/scriptrs-models`. +`54f3f976b63bf5d5fe9927363d259cffa1c23a89` of `avencera/scriptrs-models`. ## Local model layout @@ -162,12 +170,13 @@ models/ Use `ParakeetDeployment::v2()` or `ParakeetDeployment::v3()` to select a layout. v2 remains the default for `from_dir` and `from_pretrained`. -With `vad`, add: +With `vad`, add both Silero VAD models: ```text models/ vad/ - silero-vad.mlmodelc/ + silero-vad.mlmodelc/ # Silero VAD 5.1.2 + silero-vad-v6.mlmodelc/ # Silero VAD 6.2.3 ``` @@ -193,7 +202,8 @@ let result = pipeline.run(&audio)?; With `vad`, `from_pretrained_native_long_form` also downloads the Silero VAD weights from -[`avencera/silero-vad-v5-safetensors`](https://huggingface.co/avencera/silero-vad-v5-safetensors). +[`avencera/silero-vad-v5-safetensors`](https://huggingface.co/avencera/silero-vad-v5-safetensors) +and [`avencera/silero-vad-v6-safetensors`](https://huggingface.co/avencera/silero-vad-v6-safetensors). To manage the files yourself, `dev-tools/nemo/export_native.py` writes them from the NeMo checkpoints in this layout, and `from_native_dir` loads them: @@ -207,6 +217,7 @@ models/ parakeet_vocab.json vad/ silero-vad-v5.safetensors # with `vad` + silero-vad-v6.safetensors # with `vad` ``` ```rust,ignore @@ -279,27 +290,49 @@ normalizer. Speed is x real time for transcription alone on one RTX 5090, with models loaded and audio in memory; WhisperX runs its VAD with batch size 16. The last row's speed is over all 114 hours. -With `vad`, Silero VAD v5 runs on the CPU, at about 0.3 s per hour of audio. On a -GPU each step of its recurrence costs more in launches than the whole step costs on -the CPU. VAD planning helps when most of a recording is not speech, and costs -accuracy and speed on dense or far-field speech: +With `vad`, Silero VAD runs on the CPU, at about 0.5 s per hour of audio. On a GPU +each step of its recurrence costs more in launches than the whole step costs on the +CPU. The scan runs alongside transcription: each speech region goes to the model as +soon as the scan has passed it, and the transcript is the same as scanning first. +VAD planning wins when most of a recording is not speech, and helps a little on +close-talk speech, but costs accuracy on far-field speech and runs at about two +thirds of overlap speed on recordings that are mostly speech: | Set | Overlap WER | VAD WER | Overlap speed | VAD speed | |---|---:|---:|---:|---:| -| Sparse speech, 24 % speech (4.2 h) | 14.8 % | **2.3 %** | 3430x | **3990x** | -| Earnings-21 earnings calls | **8.2 %** | 8.4 % | **3630x** | 2030x | -| AMI meetings, headset mix | 21.5 % | **21.1 %** | **3480x** | 1800x | -| AMI meetings, far-field microphone | **23.2 %** | 26.0 % | **3480x** | 1790x | -| CHiME-6 dinner parties | **44.0 %** | 54.0 % | **3490x** | 1970x | +| Sparse speech, 24 % speech (4.2 h) | 14.8 % | **2.3 %** | 3906x | **4509x** | +| Earnings-21 earnings calls | 8.2 % | **8.0 %** | **4049x** | 2994x | +| AMI meetings, headset mix | 21.5 % | **20.8 %** | **3946x** | 2589x | +| AMI meetings, far-field microphone | **23.2 %** | 25.3 % | **3940x** | 2485x | +| CHiME-6 dinner parties | **44.0 %** | 53.4 % | **3994x** | 2918x | The sparse set is LibriSpeech test-clean utterances separated by 15 to 75 s of -film music, effects, ambience and low-level noise. VAD runs use the default 0.5 -speech threshold and pad each speech region by 0.2 s on both sides, including both -sides of a split inside a region longer than the model window. Silero is slow to -react to a soft first word, such as the "a" in "a cold", and 0.1 s of padding cut -it off. 0.2 s lowered WER on every set; larger padding cost AMI headset accuracy. -The speed columns were measured with 0.1 s padding; in the padding sweep, 0.2 s -was no slower. +film music, effects, ambience and low-level noise. Speeds are the best of two or +three runs. + +The default, Silero fusion, takes each window's speech probability as the higher +of Silero VAD v5's and v6's, and windows at 0.6 or above count as speech. Either +model alone misses speech the other finds: v6 separates speech from non-speech +better on most audio but misses more of the sparse set's speech at its threshold, +and v5 holds up better on noisy dinner-party audio. Taking the higher probability +scores at or below v5 alone on every set, and the 0.6 threshold keeps the sparse +set at v5's error rate (it rises to 2.8 % at 0.5). Running both models adds about +6 % to the scan's CPU time. VAD WER by model, each alone at its default 0.5 +threshold: + +| Set | v5 | v6 | Silero fusion (default) | +|---|---:|---:|---:| +| Sparse speech | **2.3 %** | 3.0 % | **2.3 %** | +| Earnings-21 earnings calls | 8.4 % | **8.0 %** | **8.0 %** | +| AMI meetings, headset mix | 21.1 % | **20.7 %** | 20.8 % | +| AMI meetings, far-field microphone | 26.0 % | 25.6 % | **25.3 %** | +| CHiME-6 dinner parties | 54.0 % | 61.9 % | **53.4 %** | + +Each speech region is padded by 0.2 s on both sides, including both sides of a +split inside a region longer than the model window. Silero is slow to react to a +soft first word, such as the "a" in "a cold", and 0.1 s of padding cut it off. In +a padding sweep with v5, 0.2 s lowered WER on every set; larger padding cost AMI +headset accuracy. By default the encoder layers' linear weights are stored in FP16, which has TF32's 10-bit mantissa, and their matrix multiplies run on FP16 tensor cores with FP32 @@ -436,7 +469,7 @@ fn load_mono_16khz_audio() -> Vec { } ``` -Enable `vad` when you want VAD-backed speech region planning for sparse speech, long silences, or recordings with a lot of non-speech audio. Windows with a speech probability of at least `config.segmentation.threshold` (0.5 by default) count as speech: +Enable `vad` when you want VAD-backed speech region planning for sparse speech, long silences, or recordings with a lot of non-speech audio. Windows with a speech probability of at least `config.segmentation.threshold` count as speech. By default that is Silero fusion, the higher of Silero VAD v5's and v6's probabilities, with a 0.6 threshold: ```rust use scriptrs::{LongFormConfig, LongFormMode, LongFormTranscriptionPipeline}; @@ -459,6 +492,14 @@ fn load_mono_16khz_audio() -> Vec { } ``` +`VadSegmentationConfig::for_model` runs one model instead, with that model's default threshold, 0.5 for either alone: + +```rust,ignore +use scriptrs::{VadModel, VadSegmentationConfig}; + +config.segmentation = VadSegmentationConfig::for_model(VadModel::SileroV5); +``` + ### Streaming (CUDA) `StreamingModel` runs NVIDIA's cache-aware [Nemotron Speech Streaming EN @@ -692,7 +733,7 @@ The example expects mono 16kHz WAV input. - The public API is still moving - `scriptrs` currently targets the exact file layout and model I/O shipped in `avencera/scriptrs-models`; if you swap in a different CoreML Parakeet export, you may need runtime code changes - Use `long-form` for the fastest path on clean, dense speech -- Add `vad` when you need better robustness on sparse-speech or non-speech-heavy recordings; on dense or far-field speech it costs accuracy +- Add `vad` when you need better robustness on sparse-speech or non-speech-heavy recordings; on far-field speech it costs accuracy, and on dense speech about a third of the speed ## License diff --git a/crates/scriptrs-python/python/scriptrs/__init__.py b/crates/scriptrs-python/python/scriptrs/__init__.py index 3932281..fe64fbd 100644 --- a/crates/scriptrs-python/python/scriptrs/__init__.py +++ b/crates/scriptrs-python/python/scriptrs/__init__.py @@ -137,9 +137,10 @@ def from_pretrained( ``~/.cache/huggingface/hub``; later calls load from the cache. Setting ``SCRIPTRS_MODELS_DIR`` loads a local directory instead, as :meth:`from_dir` does. - With ``vad``, the Silero VAD model is downloaded too, and long recordings - are split at detected speech instead of at fixed intervals, which helps - when most of a recording is silence or noise. + With ``vad``, the Silero VAD v5 and v6 models are downloaded too, and long + recordings are split at speech instead of at fixed intervals, which helps + when most of a recording is silence or noise. Each window counts as speech + when the higher of its v5 and v6 speech probabilities is at least 0.6. Raises :class:`ScriptrsError` with code ``model_download`` when a download fails, or ``cuda`` when Linux has no NVIDIA driver. diff --git a/dev-tools/nemo/.gitignore b/dev-tools/nemo/.gitignore index 21d0b89..0fea4f7 100644 --- a/dev-tools/nemo/.gitignore +++ b/dev-tools/nemo/.gitignore @@ -1 +1,2 @@ .venv/ +.cache/ diff --git a/dev-tools/nemo/README.md b/dev-tools/nemo/README.md index cd1dd29..66a2091 100644 --- a/dev-tools/nemo/README.md +++ b/dev-tools/nemo/README.md @@ -1,8 +1,10 @@ # NeMo parity oracle NeMo PyTorch is the reference for the native backends. This uv project pins the -stack the 2026-10-23 Parakeet profile measured (NeMo 3.0.0, torch 2.14.1+cu130) -and Silero VAD 5.1.2, whose weights match the published Core ML VAD. +stack the 2026-10-23 Parakeet profile measured (NeMo 3.0.0, torch 2.14.1+cu130). +`silero.py` fetches the two Silero VAD TorchScript models scriptrs ships, 5.1.2 and +6.2.3, from Silero's release tags and checks each against its pinned SHA-256; their +weights match the published Core ML VAD models. ```sh uv sync @@ -12,14 +14,14 @@ just nemo-refs v2 /shared/datasets/parakeet-ref/v2 ## `export_native.py` -Writes the native model layout from the `.nemo` checkpoints and the Silero package: +Writes the native model layout from the `.nemo` checkpoints and the Silero models: ```text parakeet-v2/model.safetensors parakeet-v2/vocab.txt parakeet-v3/model.safetensors parakeet-v3/parakeet_vocab.json nemotron-speech-streaming-en-0.6b/model.safetensors .../vocab.txt nemotron-3.5-asr-streaming-0.6b/model.safetensors .../vocab.txt -vad/silero-vad-v5.safetensors +vad/silero-vad-v5.safetensors vad/silero-vad-v6.safetensors ``` `--only` (repeatable: `v2`, `v3`, `nemotron-en`, `nemotron-3.5`, `vad`) exports a @@ -44,7 +46,7 @@ layers 0 and 23, every layer output, the encoder output, a per-step greedy TDT trace, and a bf16-autocast encoder output for tolerance scale. The trace follows NeMo's label-looping frame advance (the same rules as `HostLoop`), and generation fails unless its tokens and timestamps equal NeMo's batched decode. `--vad-audio` -adds Silero v5 per-window probabilities. `--long-audio ` writes only +adds Silero v5 and v6 per-window probabilities, in `silero-v5/` and `silero-v6/`. `--long-audio ` writes only `long-full` and `long-local`: one 120 s excerpt (from 300 s by default) with full attention, then with NeMo's long-form recipe (`rel_pos_local_attn` [256, 256]), the only sets where the two attention modes differ. Each is about 3.5 GB. NeMo runs on the GPU in fp32 with TF32 @@ -52,7 +54,7 @@ off, so run it through the homebased `gpu0` queue. The v3 sets at `/shared/datasets/parakeet-ref/` came from the profile's original script, which this one ports with an unchanged key layout; v2 sets are in `v2/` -and Silero's in `silero-v5/`. `just parity` in the repository root checks the +and Silero's in `silero-v5/` and `silero-v6/`. `just parity` in the repository root checks the Rust side against them. ## `stream_ref.py` diff --git a/dev-tools/nemo/dump_ref.py b/dev-tools/nemo/dump_ref.py index aae8055..5d47aa5 100644 --- a/dev-tools/nemo/dump_ref.py +++ b/dev-tools/nemo/dump_ref.py @@ -1,9 +1,10 @@ -"""Dump NeMo reference activations for Parakeet TDT 0.6B v2/v3 and Silero VAD v5 +"""Dump NeMo reference activations for Parakeet TDT 0.6B v2/v3 and Silero VAD v5 and v6 Writes /b1.safetensors and /b8.safetensors (plus .json metadata): per-stage encoder activations (fp32, TF32 off), a step-by-step greedy TDT decode trace per utterance, and a bf16-autocast encoder output for tolerance scale. With --vad-audio it -also writes /vad.safetensors from the Silero v5 TorchScript model. With --long-audio +also writes /silero-v5/vad.safetensors and /silero-v6/vad.safetensors from Silero's +TorchScript models. With --long-audio it writes long-full and long-local sets for one long excerpt, the second with NeMo's long-form recipe (rel_pos_local_attn [256, 256]) @@ -247,17 +248,17 @@ def run_set(model, rows, device, audios=None): @torch.no_grad() -def dump_vad(out, audio_path): - """Silero v5 probabilities for every 512-sample window of one file, plus window 0's stages +def dump_vad(out, audio_path, version): + """One Silero version's probabilities for every 512-sample window of one file, plus window 0's stages Mirrors scriptrs `process_windows`: zero state per recording, 64 context samples from the previous chunk, and a short final chunk padded with its last sample """ - import importlib.resources + import silero - jit = torch.jit.load( - str(importlib.resources.files("silero_vad").joinpath("data/silero_vad.jit")), map_location="cpu" - ) + out = out / f"silero-{version}" + out.mkdir(parents=True, exist_ok=True) + jit = torch.jit.load(str(silero.jit_path(version)), map_location="cpu") model = jit._model audio = torch.from_numpy(sf.read(audio_path, dtype="float32")[0]) window, context_len = 512, 64 @@ -288,7 +289,7 @@ def dump_vad(out, audio_path): save_file({k: v.contiguous() for k, v in tensors.items()}, str(out / "vad.safetensors")) meta = {"audio": audio_path, "windows": len(probs), "keys": {k: list(v.shape) for k, v in tensors.items()}} (out / "vad.json").write_text(json.dumps(meta, indent=1)) - print("vad", meta) + print(f"vad {version}", meta) # NeMo's long-form recipe, as the 2026-10-23 profile ran it on the 1 h Earnings-21 file @@ -332,7 +333,7 @@ def main(): ap = argparse.ArgumentParser() ap.add_argument("--version", choices=sorted(NEMO_PATHS), required=True) ap.add_argument("--out", type=Path, required=True) - ap.add_argument("--vad-audio", help="also dump Silero v5 references for this 16 kHz wav") + ap.add_argument("--vad-audio", help="also dump Silero v5 and v6 references for this 16 kHz wav") ap.add_argument("--long-audio", help="dump only the long-full and long-local sets from this 16 kHz wav") ap.add_argument("--long-offset", type=float, default=300.0, help="excerpt start in seconds") ap.add_argument("--long-seconds", type=float, default=120.0, help="excerpt length in seconds") @@ -344,7 +345,8 @@ def main(): out = args.out out.mkdir(parents=True, exist_ok=True) if args.vad_audio: - dump_vad(out, args.vad_audio) + for version in ("v5", "v6"): + dump_vad(out, args.vad_audio, version) model = load_model(args.version, device) if args.long_audio: dump_long(model, out, args.long_audio, args.long_offset, args.long_seconds, device) diff --git a/dev-tools/nemo/export_native.py b/dev-tools/nemo/export_native.py index 5a25d9e..2cec01a 100644 --- a/dev-tools/nemo/export_native.py +++ b/dev-tools/nemo/export_native.py @@ -1,5 +1,5 @@ -"""Export Parakeet TDT and Nemotron streaming `.nemo` checkpoints and Silero VAD v5 to -scriptrs native weights +"""Export Parakeet TDT and Nemotron streaming `.nemo` checkpoints and Silero VAD v5 +and v6 to scriptrs native weights Writes, under --out: @@ -7,7 +7,7 @@ parakeet-v3/model.safetensors, parakeet-v3/parakeet_vocab.json nemotron-speech-streaming-en-0.6b/model.safetensors, .../vocab.txt nemotron-3.5-asr-streaming-0.6b/model.safetensors, .../vocab.txt - vad/silero-vad-v5.safetensors + vad/silero-vad-v5.safetensors, vad/silero-vad-v6.safetensors Tensors keep their NeMo (or Silero) names and stay fp32, so the file is the parity oracle's own weights. Layout changes such as BatchNorm folding or transposes happen @@ -22,7 +22,6 @@ import importlib import importlib.metadata import inspect -import importlib.resources import json import tarfile from pathlib import Path @@ -32,6 +31,8 @@ import yaml from safetensors.torch import save_file +import silero + FORMAT = "scriptrs-native" FORMAT_VERSION = "2" @@ -360,14 +361,10 @@ def write_vocab(version: str, tokenizer_model: bytes, vocab_size: int, path: Pat print(f"[{version}] wrote {vocab_size} tokens to {path}") -def export_silero(out: Path) -> None: +def export_silero(version: str, out: Path) -> None: target = out / "vad" target.mkdir(parents=True, exist_ok=True) - package_version = importlib.metadata.version("silero-vad") - if not package_version.startswith("5."): - raise SystemExit(f"silero-vad {package_version} does not ship the v5 weights") - - jit_path = importlib.resources.files("silero_vad").joinpath("data/silero_vad.jit") + jit_path = silero.jit_path(version) model = torch.jit.load(str(jit_path), map_location="cpu") # `_model` is the 16 kHz branch; `_model_8k` is not used by scriptrs tensors = { @@ -375,18 +372,19 @@ def export_silero(out: Path) -> None: for name, tensor in model.state_dict().items() if name.startswith("_model.") } + name = f"silero-vad-{version}" metadata = { "format": FORMAT, "format_version": FORMAT_VERSION, - "model": "silero-vad-v5", - "source": f"silero-vad {package_version} (16 kHz branch)", - "source_sha256": sha256_file(Path(str(jit_path))), + "model": name, + "source": silero.source(version), + "source_sha256": sha256_file(jit_path), "config": json.dumps( {"sample_rate": 16000, "window": 512, "context": 64, "state": 128}, sort_keys=True ), } - save_file(tensors, target / "silero-vad-v5.safetensors", metadata=metadata) - print(f"[vad] wrote {len(tensors)} tensors to {target / 'silero-vad-v5.safetensors'}") + save_file(tensors, target / f"{name}.safetensors", metadata=metadata) + print(f"[vad] wrote {len(tensors)} tensors to {target / f'{name}.safetensors'}") def main() -> None: @@ -400,7 +398,8 @@ def main() -> None: if key in only: export_streaming(key, getattr(args, f"{key}_nemo"), args.out) if "vad" in only: - export_silero(args.out) + for version in silero.VERSIONS: + export_silero(version, args.out) if __name__ == "__main__": diff --git a/dev-tools/nemo/pyproject.toml b/dev-tools/nemo/pyproject.toml index 41ec54f..aca4ed4 100644 --- a/dev-tools/nemo/pyproject.toml +++ b/dev-tools/nemo/pyproject.toml @@ -15,7 +15,6 @@ dependencies = [ "numpy", "jiwer", "whisper-normalizer", - "silero-vad==5.1.2", "huggingface-hub", ] diff --git a/dev-tools/nemo/silero.py b/dev-tools/nemo/silero.py new file mode 100644 index 0000000..cbe1304 --- /dev/null +++ b/dev-tools/nemo/silero.py @@ -0,0 +1,44 @@ +"""Silero VAD TorchScript models scriptrs ships, fetched from Silero's release tags + +Both versions ship, so neither can come from the `silero-vad` pip package, which +installs one. Each file is pinned by SHA-256, the hash the exported weights record +as `source_sha256` +""" + +from __future__ import annotations + +import hashlib +import urllib.request +from pathlib import Path + +# version: (release tag, SHA-256 of `src/silero_vad/data/silero_vad.jit` at that tag) +VERSIONS = { + "v5": ("v5.1.2", "85c48e1f0ecb604e5d2a268f3ccfb912d4f7e935acdc86af5a3fc5b0aea7b29a"), + # 6.2.1 to 6.2.3 ship the same weights; 6.0 and 6.1 ship older v6 weights + "v6": ("v6.2.3", "e1122837f4154c511485fe0b9c64455f7b929c96fbb8d79fbdb336383ebd3720"), +} + +CACHE = Path(__file__).resolve().parent / ".cache" / "silero" + + +def jit_path(version: str) -> Path: + """The version's TorchScript file, downloaded once and checked against its pin""" + tag, sha256 = VERSIONS[version] + path = CACHE / tag / "silero_vad.jit" + if not path.exists(): + path.parent.mkdir(parents=True, exist_ok=True) + url = f"https://github.com/snakers4/silero-vad/raw/{tag}/src/silero_vad/data/silero_vad.jit" + partial = path.with_suffix(".part") + urllib.request.urlretrieve(url, partial) + partial.rename(path) + found = hashlib.sha256(path.read_bytes()).hexdigest() + if found != sha256: + # a bad file left in the cache would fail every later run the same way + path.unlink() + raise SystemExit(f"{path} has SHA-256 {found}, expected {sha256} for Silero {tag}") + return path + + +def source(version: str) -> str: + """`source` metadata of the exported weights, the pip release the file matches""" + return f"silero-vad {VERSIONS[version][0].removeprefix('v')} (16 kHz branch)" diff --git a/dev-tools/nemo/uv.lock b/dev-tools/nemo/uv.lock index 7676818..a4e3cd7 100644 --- a/dev-tools/nemo/uv.lock +++ b/dev-tools/nemo/uv.lock @@ -456,14 +456,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/e0/1b/5e74289a1878e666bb4b65fe5805a04cafcac2aa5f519ef1ead67ef91c56/filelock-4.2.4-py3-none-any.whl", hash = "sha256:301241438c57936ef93f4243a94f2559022268bfcf9b375a9a72eb0f8db8358e", size = 162475, upload-time = "2026-10-19T01:57:49.419Z" }, ] -[[package]] -name = "flatbuffers" -version = "25.12.19" -source = { registry = "https://pypi.org/simple" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/e8/2d/d2a548598be01649e2d46231d151a6c56d10b964d94043a335ae56ea2d92/flatbuffers-25.12.19-py2.py3-none-any.whl", hash = "sha256:7634f50c427838bb021c2d66a3d1168e9d199b0607e6329399f04846d42e20b4", size = 26661, upload-time = "2025-12-19T23:16:13.622Z" }, -] - [[package]] name = "frozenlist" version = "1.8.0" @@ -1386,24 +1378,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/bd/1d/37f2c7f821f79ceed3c976bd087d16abdd2b0bba6c19475322e7a31bae59/onnx-1.23.2-cp312-abi3-win_arm64.whl", hash = "sha256:80cef0fad59524d02c21ec93f4fbccdcc6223f1c33339d597519a2d27cac19a7", size = 8047076, upload-time = "2026-10-06T04:25:46.93Z" }, ] -[[package]] -name = "onnxruntime" -version = "1.31.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "flatbuffers" }, - { name = "numpy" }, - { name = "packaging" }, - { name = "protobuf" }, -] -wheels = [ - { url = "https://files.pythonhosted.org/packages/0e/f7/cecc0efeeea83bff2f7789ae1b80f27fa0f0210d6d9d66d1f0031a6b5e47/onnxruntime-1.31.1-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:96dd2564b10ea7153ad9c207e7cd8e5917cb3ba521e0e0a62ac03486fdc8d56c", size = 20882125, upload-time = "2026-10-26T19:26:16.256Z" }, - { url = "https://files.pythonhosted.org/packages/ba/e4/1ed1a7a5f4702d899091fa2b976d377995250c307326ec8dc9ae6378aa13/onnxruntime-1.31.1-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:0b9a492176886992e0e875f06bc0367e333f5fff11711a2d642e18b02f3009cc", size = 21420803, upload-time = "2026-10-26T19:26:19.487Z" }, - { url = "https://files.pythonhosted.org/packages/eb/27/c6a823bac55b2977bea2027c3ec9393a2c1002cb9a09eb40354563e02730/onnxruntime-1.31.1-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:1f3dea47f2f0e5117c2404cea7d21fd253ae7836a3bf167a501cdfbb2600d536", size = 23760988, upload-time = "2026-10-26T19:26:23.153Z" }, - { url = "https://files.pythonhosted.org/packages/45/b2/793b4051d8dc6acb379ead9b72050f0ffa283ca49a6904add2e218b83e2e/onnxruntime-1.31.1-cp312-cp312-win_amd64.whl", hash = "sha256:ae8a9a351efda685cc59a66226cdefaa37a126c1d66872ca23a2de9425326130", size = 14888466, upload-time = "2026-10-26T19:26:25.816Z" }, - { url = "https://files.pythonhosted.org/packages/ed/72/09d635ab4b6137d8ac63d4911a37dad8b1ef15a77d20b65d7ed40fdca012/onnxruntime-1.31.1-cp312-cp312-win_arm64.whl", hash = "sha256:fe8b9ac1ae8e894e12c47ee82e4f6dfc1835768133687257866469fda80d0bf1", size = 14740724, upload-time = "2026-10-26T19:26:28.682Z" }, -] - [[package]] name = "opentelemetry-api" version = "1.45.1" @@ -1947,7 +1921,6 @@ dependencies = [ { name = "nemo-toolkit", extra = ["asr"] }, { name = "numpy" }, { name = "safetensors" }, - { name = "silero-vad" }, { name = "soundfile" }, { name = "torch" }, { name = "torchaudio" }, @@ -1961,7 +1934,6 @@ requires-dist = [ { name = "nemo-toolkit", extras = ["asr"], specifier = "==3.0.0" }, { name = "numpy" }, { name = "safetensors" }, - { name = "silero-vad", specifier = "==5.1.2" }, { name = "soundfile" }, { name = "torch", specifier = "==2.14.1", index = "https://download.pytorch.org/whl/cu130" }, { name = "torchaudio", index = "https://download.pytorch.org/whl/cu130" }, @@ -2001,20 +1973,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/e0/f9/0595336914c5619e5f28a1fb793285925a8cd4b432c9da0a987836c7f822/shellingham-1.5.4-py2.py3-none-any.whl", hash = "sha256:7ecfff8f2fd72616f7481040475a65b2bf8af90a56c89140852d1120324e8686", size = 9755, upload-time = "2023-10-24T04:13:38.866Z" }, ] -[[package]] -name = "silero-vad" -version = "5.1.2" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "onnxruntime" }, - { name = "torch" }, - { name = "torchaudio" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/b1/b4/d0311b2e6220a11f8f4699f4a278cb088131573286cdfe804c87c7eb5123/silero_vad-5.1.2.tar.gz", hash = "sha256:c442971160026d2d7aa0ad83f0c7ee86c89797a65289fe625c8ea59fc6fb828d", size = 5098526, upload-time = "2024-10-09T09:50:47.019Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/98/f7/5ae11d13fbb733cd3bfd7ff1c3a3902e6f55437df4b72307c1f168146268/silero_vad-5.1.2-py3-none-any.whl", hash = "sha256:93b41953d7774b165407fda6b533c119c5803864e367d5034dc626c82cfdf661", size = 5026737, upload-time = "2024-10-09T09:50:44.355Z" }, -] - [[package]] name = "six" version = "1.17.0" diff --git a/dev-tools/python/export_models.py b/dev-tools/python/export_models.py index d67d247..a206936 100644 --- a/dev-tools/python/export_models.py +++ b/dev-tools/python/export_models.py @@ -17,7 +17,15 @@ REPO_ROOT = Path(__file__).resolve().parents[2] PARAKEET_COREML_REPO = "FluidInference/parakeet-tdt-0.6b-v2-coreml" PARAKEET_VOCAB_REPO = "istupakov/parakeet-tdt-0.6b-v2-onnx" -SILERO_VAD_REPO = "aufklarer/Silero-VAD-v5-CoreML" +# staged directory: (repo, revision); both builds share one Core ML graph and I/O, +# v6.2.1 has the same weights as Silero 6.2.3 +SILERO_VAD_REPOS = { + "silero-vad.mlmodelc": ("aufklarer/Silero-VAD-v5-CoreML", None), + "silero-vad-v6.mlmodelc": ( + "aufklarer/Silero-VAD-v6.2.1-CoreML", + "523876545a57961474fee9df913e833e130560b8", + ), +} def parse_args() -> argparse.Namespace: @@ -60,22 +68,26 @@ def main() -> None: ], ) - print("Downloading Silero VAD CoreML bundle...") - vad_dir = download_snapshot( - SILERO_VAD_REPO, - ["silero_vad.mlmodelc/*"], - ) + print("Downloading Silero VAD CoreML bundles...") + vad_dirs = { + name: download_snapshot(repo, ["silero_vad.mlmodelc/*"], revision) + for name, (repo, revision) in SILERO_VAD_REPOS.items() + } stage_parakeet(parakeet_coreml_dir, parakeet_onnx_dir, output_dir) - stage_vad(vad_dir, output_dir) + for name, vad_dir in vad_dirs.items(): + copy_bundle(vad_dir / "silero_vad.mlmodelc", output_dir / "vad" / name) print(f"Staged models in {output_dir}") -def download_snapshot(repo_id: str, allow_patterns: list[str]) -> Path: +def download_snapshot( + repo_id: str, allow_patterns: list[str], revision: str | None = None +) -> Path: return Path( snapshot_download( repo_id=repo_id, allow_patterns=allow_patterns, + revision=revision, ) ) @@ -103,10 +115,6 @@ def stage_parakeet(coreml_dir: Path, onnx_dir: Path, output_dir: Path) -> None: ) -def stage_vad(vad_dir: Path, output_dir: Path) -> None: - copy_bundle(vad_dir / "silero_vad.mlmodelc", output_dir / "vad/silero-vad.mlmodelc") - - def copy_bundle(source: Path, destination: Path) -> None: if destination.exists(): shutil.rmtree(destination) diff --git a/examples/cuda_bench.rs b/examples/cuda_bench.rs index 57d9581..36e86a2 100644 --- a/examples/cuda_bench.rs +++ b/examples/cuda_bench.rs @@ -24,8 +24,9 @@ //! `--tf32` or `--fp32` runs the encoder GEMMs in that precision instead of FP16, //! as do `--fp8`, `--int8` and `--nvfp4` with the `low-precision` feature, //! and `--vad` (with the `vad` feature) plans long recordings from Silero speech -//! regions instead of overlap windows over the whole recording, at -//! `--vad-threshold

` and with `--vad-padding ` around each region if +//! regions instead of overlap windows over the whole recording, scored by +//! `--vad-model v5|v6|fusion` (fusion by default) at the model's threshold or +//! `--vad-threshold

`, and with `--vad-padding ` around each region if //! given //! //! ```sh @@ -65,7 +66,11 @@ struct Args { language: LanguageSelection, precision: Precision, vad: bool, + #[cfg(feature = "vad")] + vad_model: Option, + #[cfg(feature = "vad")] vad_threshold: Option, + #[cfg(feature = "vad")] vad_padding: Option, scheduler: bool, } @@ -114,14 +119,16 @@ fn run() -> Result<()> { let mut sorted = walls.clone(); sorted.sort_by(f64::total_cmp); - let summary = json!({ + #[cfg_attr( + not(feature = "vad"), + expect(unused_mut, reason = "only VAD runs add fields") + )] + let mut summary = json!({ "backend": format!("scriptrs-cuda-{}", precision_name(args.precision)), "version": version, "bs": batch, "long": !args.long.is_empty(), "vad": args.vad, - "vad_threshold": args.vad_threshold, - "vad_padding": args.vad_padding, "scheduler": args.scheduler, "n_utts": texts.len(), "audio_s": audio_s, @@ -129,6 +136,14 @@ fn run() -> Result<()> { "rtfx_best": audio_s / sorted[0], "rtfx_median": audio_s / median(&sorted), }); + // the settings the run used rather than the flags, so a run on the defaults + // still records which model and threshold scored it + #[cfg(feature = "vad")] + if let Some(segmentation) = vad_segmentation(&args)? { + summary["vad_model"] = json!(format!("{:?}", segmentation.model)); + summary["vad_threshold"] = json!(segmentation.threshold); + summary["vad_padding"] = json!(segmentation.speech_padding); + } if let Some(parent) = args.out.parent() { fs::create_dir_all(parent)?; } @@ -217,6 +232,31 @@ fn bench_manifest( )) } +/// Segmentation of a `--vad` run: the `--vad-model` defaults, then the overrides +#[cfg(feature = "vad")] +fn vad_segmentation(args: &Args) -> Result> { + if !args.vad { + return Ok(None); + } + + let mut segmentation = match args.vad_model.as_deref() { + None => scriptrs::VadSegmentationConfig::default(), + Some(model) => scriptrs::VadSegmentationConfig::for_model(match model { + "v5" => scriptrs::VadModel::SileroV5, + "v6" => scriptrs::VadModel::SileroV6, + "fusion" => scriptrs::VadModel::SileroFusion, + other => bail!("unknown VAD model {other}; expected v5, v6 or fusion"), + }), + }; + if let Some(threshold) = args.vad_threshold { + segmentation.threshold = threshold; + } + if let Some(padding) = args.vad_padding { + segmentation.speech_padding = padding; + } + Ok(Some(segmentation)) +} + fn bench_long(bundle: ModelBundle, paths: &[PathBuf], args: &Args) -> Result { let mut config = LongFormConfig::for_bundle(&bundle); config.transcription.language = args.language; @@ -234,14 +274,9 @@ fn bench_long(bundle: ModelBundle, paths: &[PathBuf], args: &Args) -> Result Result { let mut language = LanguageSelection::Auto; let mut precision = Precision::default(); let mut vad = false; + #[cfg(feature = "vad")] + let mut vad_model = None; + #[cfg(feature = "vad")] let mut vad_threshold = None; + #[cfg(feature = "vad")] let mut vad_padding = None; let mut scheduler = false; let mut args = env::args().skip(1); @@ -364,7 +403,11 @@ fn parse_args() -> Result { "--nvfp4" => precision = Precision::Nvfp4, "--vad" if cfg!(feature = "vad") => vad = true, "--vad" => return Err(eyre!("--vad needs the `vad` feature")), + #[cfg(feature = "vad")] + "--vad-model" => vad_model = Some(value()?), + #[cfg(feature = "vad")] "--vad-threshold" => vad_threshold = Some(value()?.parse()?), + #[cfg(feature = "vad")] "--vad-padding" => vad_padding = Some(value()?.parse()?), "--scheduler" => scheduler = true, other => return Err(eyre!("unknown argument {other}")), @@ -374,11 +417,16 @@ fn parse_args() -> Result { if vad && long.is_empty() { return Err(eyre!("--vad only applies to --long recordings")); } - if vad_threshold.is_some() && !vad { - return Err(eyre!("--vad-threshold needs --vad")); - } - if vad_padding.is_some() && !vad { - return Err(eyre!("--vad-padding needs --vad")); + #[cfg(feature = "vad")] + if !vad { + let flags = [ + ("--vad-model", vad_model.is_some()), + ("--vad-threshold", vad_threshold.is_some()), + ("--vad-padding", vad_padding.is_some()), + ]; + if let Some((flag, _)) = flags.into_iter().find(|(_, given)| *given) { + return Err(eyre!("{flag} needs --vad")); + } } Ok(Args { @@ -394,7 +442,11 @@ fn parse_args() -> Result { language, precision, vad, + #[cfg(feature = "vad")] + vad_model, + #[cfg(feature = "vad")] vad_threshold, + #[cfg(feature = "vad")] vad_padding, scheduler, }) diff --git a/examples/inspect_coreml_compute/macos.rs b/examples/inspect_coreml_compute/macos.rs index 26905eb..94736f7 100644 --- a/examples/inspect_coreml_compute/macos.rs +++ b/examples/inspect_coreml_compute/macos.rs @@ -19,8 +19,12 @@ use scriptrs::ModelBundle; const ENCODER_DIR: &str = "parakeet-v2/encoder.mlmodelc"; const DECODER_DIR: &str = "parakeet-v2/decoder.mlmodelc"; const JOINT_DECISION_DIR: &str = "parakeet-v2/joint-decision.mlmodelc"; +/// Silero VAD 5.1.2 and 6.2.3, the two models Silero fusion runs #[cfg(feature = "vad")] -const VAD_DIR: &str = "vad/silero-vad.mlmodelc"; +const VAD_DIRS: [(&str, &str); 2] = [ + ("vad v5", "vad/silero-vad.mlmodelc"), + ("vad v6", "vad/silero-vad-v6.mlmodelc"), +]; pub fn main() -> ExitCode { match run() { @@ -64,12 +68,14 @@ fn run() -> Result<()> { #[cfg(feature = "vad")] if args.long_form { - inspect_model( - "vad", - &bundle.root().join(VAD_DIR), - args.compute_units, - args.show_ops, - )?; + for (name, dir) in VAD_DIRS { + inspect_model( + name, + &bundle.root().join(dir), + args.compute_units, + args.show_ops, + )?; + } } #[cfg(not(feature = "vad"))] @@ -150,7 +156,7 @@ fn print_usage() { Options: --models-dir

local scriptrs model bundle directory --pretrained download models via the online feature - --long-form include the Silero VAD model + --long-form include the Silero VAD models --compute-units cpu_only | cpu_and_gpu | all | cpu_and_neural_engine --show-ops print the first n ML Program operations" ); diff --git a/src/lib.rs b/src/lib.rs index 4cc1dd0..856e048 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -63,12 +63,13 @@ //! //! Select a version with [`ParakeetDeployment::v2`] or [`ParakeetDeployment::v3`] //! -//! With `vad`, add: +//! With `vad`, add both Silero VAD models: //! //! ```text //! models/ //! vad/ -//! silero-vad.mlmodelc/ +//! silero-vad.mlmodelc/ # Silero VAD 5.1.2 +//! silero-vad-v6.mlmodelc/ # Silero VAD 6.2.3 //! ``` //! //! You can force local model resolution with an environment variable: @@ -189,12 +190,12 @@ pub use language::{ FilteredToken, LanguageSelection, ParakeetLanguage, Script, TopKCandidates, TopKPair, V3_LANGUAGES, detect_language_from_tokens, filter_top_k_language, select_language_from_logits, }; -#[cfg(feature = "vad")] -pub use long_form::VadSegmentationConfig; #[cfg(feature = "long-form")] pub use long_form::{ LongFormConfig, LongFormMode, LongFormTranscriptionPipeline, OverlapChunkConfig, }; +#[cfg(feature = "vad")] +pub use long_form::{VadModel, VadSegmentationConfig}; pub use model_io::{DecodedJointStep, EncoderOutputs, JointOutputs, decode_joint_outputs}; pub use models::ModelBundle; #[cfg(feature = "online")] diff --git a/src/long_form.rs b/src/long_form.rs index f051c5e..8af58b0 100644 --- a/src/long_form.rs +++ b/src/long_form.rs @@ -28,13 +28,15 @@ const NATIVE_OVERLAP_SECONDS: f64 = 8.0; #[cfg(feature = "cuda")] const NATIVE_BATCH_SIZE: usize = 16; #[cfg(feature = "vad")] -pub use planner::VadSegmentationConfig; +pub use planner::{VadModel, VadSegmentationConfig}; -use self::execute::{RunRequest, execute_plan, transcribe_task}; +use self::execute::{RunRequest, TaskStream, execute_plan, transcribe_task}; +#[cfg(feature = "vad")] +use self::execute::{execute_scoped_plan, is_interruption}; use self::merge::merge_overlapping_windows; use self::planner::{ChunkTask, LongFormExecutionPlan, RegionTaskKind, build_fast_execution_plan}; #[cfg(feature = "vad")] -use self::planner::{build_vad_execution_plan, detect_speech_regions}; +use self::planner::{SpeechRegions, VadPlan, build_vad_execution_plan, detect_speech_regions}; #[cfg(feature = "vad")] use self::vad::SileroVad; @@ -56,7 +58,7 @@ use self::vad::SileroVad; pub struct LongFormTranscriptionPipeline { inner: TranscriptionPipeline, #[cfg(feature = "vad")] - vad: Option, + vad: SileroVad, default_config: LongFormConfig, } @@ -175,9 +177,12 @@ pub enum LongFormMode { /// Skip VAD and chunk the full recording with overlap windows #[default] Fast, - /// Detect speech with VAD before chunk planning + /// Detect speech with VAD and transcribe only the speech /// - /// Audio that fits one window is transcribed whole without a VAD scan + /// Each speech region is transcribed as soon as the scan has passed it, while + /// the scan goes on; the windows and transcript are those of scanning the + /// whole recording first. Audio that fits one window is transcribed whole + /// without a VAD scan #[cfg(feature = "vad")] Vad, } @@ -261,6 +266,10 @@ impl LongFormTranscriptionPipeline { } /// Transcribe audio while preprocessing each planned ASR window once + /// + /// The plan is checked against `control`'s window limit before any window is + /// preprocessed. In VAD mode that means scanning the whole recording first, so + /// with a limit below `usize::MAX` the scan no longer overlaps transcription pub fn run_with_preprocessor( &self, audio: &[f32], @@ -327,6 +336,13 @@ impl LongFormTranscriptionPipeline { &self.default_config } + /// Transcribes each speech region's windows as soon as the VAD scan has + /// planned them + /// + /// The scan runs ahead on the CPU while the model works through the windows + /// planned so far, and plans the windows planning the whole recording first + /// would. A window limit is checked against the whole plan before any window + /// runs, so a run with one scans first #[cfg(feature = "vad")] fn run_vad_long_form( &self, @@ -339,19 +355,71 @@ impl LongFormTranscriptionPipeline { .. } = request; control.check()?; - let vad = self - .vad - .as_ref() - .ok_or_else(|| self.inner.bundle().missing_vad_error()) - .map_err(PreprocessedTranscriptionError::from)?; - let probabilities = vad - .process(audio, control) - .map_err(PreprocessedTranscriptionError::from)?; - control.check()?; - let regions = detect_speech_regions(&probabilities, audio.len(), &config.segmentation); - let execution_plan = build_vad_execution_plan(®ions, &probabilities, config); - control.check_plan(execution_plan.tasks.len())?; - self.run_plan(request, execution_plan) + if control.max_windows() < usize::MAX { + // a failing scan stops its run, which must not stop the caller's control + let probabilities = self + .vad + .process(audio, config.segmentation.model, &control.run_scope()) + .map_err(PreprocessedTranscriptionError::from)?; + control.check()?; + let regions = detect_speech_regions(&probabilities, audio.len(), &config.segmentation); + let execution_plan = build_vad_execution_plan(®ions, &probabilities, config); + control.check_plan(execution_plan.tasks.len())?; + return self.run_plan(request, execution_plan); + } + + // the scan and the windows stop each other through the run's own signal + let run_control = control.run_scope(); + let request = RunRequest { + control: &run_control, + ..request + }; + let tasks = TaskStream::open(); + let (planned, raw_tasks) = std::thread::scope(|scope| { + let (run_control, tasks) = (&run_control, &tasks); + // the pipeline is not `Sync`, so the scan gets its own handle on the + // VAD models + let vad = self.vad.clone(); + let planner = scope.spawn(move || { + let _close = ClosePlan(tasks, run_control); + let planned = plan_while_scanning(&vad, audio, config, run_control, tasks); + if planned.is_err() { + run_control.stop_run(); + } + planned + }); + + let _stop = StopRunOnPanic(run_control); + let raw_tasks = execute_scoped_plan(&self.inner, request, tasks); + if raw_tasks.is_err() { + run_control.stop_run(); + } + let planned = planner + .join() + .unwrap_or_else(|panic| std::panic::resume_unwind(panic)); + (planned, raw_tasks) + }); + + // whichever side failed stopped the other, which reports only the stop + let raw_tasks = match raw_tasks { + Err(error) if !is_interruption(&error) => return Err(error), + raw_tasks => raw_tasks, + }; + let execution_plan = match planned { + Ok(execution_plan) => execution_plan, + // a side that saw the other's stop reports it as a cancellation, so the + // caller's control says whether it was a cancellation or the deadline + Err(error @ TranscriptionError::Control(_)) => { + control.check()?; + return Err(raw_tasks.err().unwrap_or_else(|| error.into())); + } + Err(error) => return Err(error.into()), + }; + let raw_tasks = raw_tasks?; + if execution_plan.tasks.is_empty() { + return Ok(TranscriptionResult::empty(duration_seconds(audio.len()))); + } + Ok(self.build_plan_result(audio.len(), execution_plan, raw_tasks)?) } fn run_fast_long_form( @@ -397,7 +465,8 @@ impl LongFormTranscriptionPipeline { return Ok(TranscriptionResult::empty(duration_seconds(audio_len))); } - let raw_tasks = execute_plan(&self.inner, request, &execution_plan.tasks)?; + let tasks = TaskStream::complete(&execution_plan.tasks); + let raw_tasks = execute_plan(&self.inner, request, &tasks)?; Ok(self.build_plan_result(audio_len, execution_plan, raw_tasks)?) } @@ -528,11 +597,9 @@ impl LongFormTranscriptionPipeline { #[cfg(feature = "vad")] RunPath::Planned(LongFormMode::Vad) => { let control = TranscriptionControl::internal_unbounded(); - let vad = self + let probabilities = self .vad - .as_ref() - .ok_or_else(|| self.inner.bundle().missing_vad_error())?; - let probabilities = vad.process(audio, &control)?; + .process(audio, config.segmentation.model, &control)?; let regions = detect_speech_regions(&probabilities, audio.len(), &config.segmentation); build_vad_execution_plan(®ions, &probabilities, config) @@ -585,6 +652,59 @@ fn validate_finite_samples( }) } +/// Scans `audio` for speech, adding each region's windows to `tasks` as soon as +/// the region is final, and returns the whole plan +#[cfg(feature = "vad")] +fn plan_while_scanning( + vad: &SileroVad, + audio: &[f32], + config: &LongFormConfig, + control: &TranscriptionControl, + tasks: &TaskStream, +) -> Result { + let mut regions = SpeechRegions::new(audio.len(), &config.segmentation); + let mut plan = VadPlan::new(config); + let probabilities = vad.scan(audio, config.segmentation.model, control, |probabilities| { + for region in regions.push(probabilities) { + plan.add_region(region, probabilities); + } + tasks.extend(plan.tasks()); + })?; + for region in regions.finish() { + plan.add_region(region, &probabilities); + } + tasks.extend(plan.tasks()); + Ok(plan.finish()) +} + +/// Ends the plan when the planning thread finishes, also by panicking, so a +/// window executor waiting on the next window never hangs +#[cfg(feature = "vad")] +struct ClosePlan<'a>(&'a TaskStream, &'a TranscriptionControl); + +#[cfg(feature = "vad")] +impl Drop for ClosePlan<'_> { + fn drop(&mut self) { + if std::thread::panicking() { + self.1.stop_run(); + } + self.0.close(); + } +} + +/// Stops the run when the code holding it unwinds, so the scan stops at its next +/// block rather than running to the end of the recording before the panic +/// surfaces +struct StopRunOnPanic<'a>(&'a TranscriptionControl); + +impl Drop for StopRunOnPanic<'_> { + fn drop(&mut self) { + if std::thread::panicking() { + self.0.stop_run(); + } + } +} + fn identity_error( error: PreprocessedTranscriptionError, ) -> TranscriptionError { @@ -685,6 +805,8 @@ mod tests { use super::{ LongFormConfig, LongFormMode, RunPath, WindowPreprocessor, build_fast_execution_plan, }; + #[cfg(all(feature = "cuda", feature = "vad"))] + use super::{VadModel, VadSegmentationConfig}; #[cfg(feature = "vad")] use super::{detect_speech_regions, merge_overlap_region}; #[cfg(all(feature = "cuda", feature = "vad"))] @@ -700,6 +822,8 @@ mod tests { use crate::deployment::ParakeetDeployment; #[cfg(feature = "cuda")] use crate::error::TranscriptionError; + #[cfg(all(feature = "cuda", feature = "vad"))] + use crate::models::SileroVersion; #[cfg(feature = "cuda")] use crate::preprocessing::PreprocessedTranscriptionError; use crate::preprocessing::{AudioWindowMut, TranscriptionControl}; @@ -1225,6 +1349,29 @@ mod tests { } } + /// Fails window 1 only, so the other workers keep succeeding and must be + /// stopped by the run; on the batched path they would otherwise park at the + /// look-ahead gate and hang the join + #[cfg(feature = "cuda")] + struct FailingHook(RecordingHook); + + #[cfg(feature = "cuda")] + impl WindowPreprocessor for FailingHook { + type Error = HookError; + + fn process( + &self, + window: &mut AudioWindowMut<'_>, + control: &TranscriptionControl, + ) -> Result<(), Self::Error> { + self.0.process(window, control)?; + if window.index().get() == 1 { + return Err(HookError); + } + Ok(()) + } + } + /// A preprocessor error stops the parallel and batched workers, which join and /// return that error rather than finishing the plan, and leaves the caller's /// control uncancelled @@ -1232,27 +1379,6 @@ mod tests { #[test] #[ignore = "needs a CUDA GPU and the native weights; `just gpu-parity` runs it on gpu0"] fn gpu_workers_join_after_the_first_preprocessor_error() { - /// Fails window 1 only, so the other workers keep succeeding and must be - /// stopped by the run; on the batched path they would otherwise park at the - /// look-ahead gate and hang the join - struct FailingHook(RecordingHook); - - impl WindowPreprocessor for FailingHook { - type Error = HookError; - - fn process( - &self, - window: &mut AudioWindowMut<'_>, - control: &TranscriptionControl, - ) -> Result<(), Self::Error> { - self.0.process(window, control)?; - if window.index().get() == 1 { - return Err(HookError); - } - Ok(()) - } - } - let (pipeline, base) = native_pipeline(); let audio = vec![0.0; LONG_AUDIO_SAMPLES]; @@ -1338,24 +1464,35 @@ mod tests { assert!(panicked, "the batched run should raise the worker's panic"); } - /// Speech probabilities of the reference recording, from the native VAD and - /// from Silero itself + /// Speech probabilities of the reference recording under `model`, from the + /// native VAD and from Silero itself; fusion takes each window's higher Silero + /// probability #[cfg(all(feature = "cuda", feature = "vad"))] - fn reference_probabilities() -> (Vec, Vec, usize) { - let reference = NemoReference::silero(); - let audio = reference.f32("audio"); + fn reference_probabilities(model: VadModel) -> (Vec, Vec, usize) { + let silero = |version| -> Vec { + NemoReference::silero(version) + .f32("probs") + .into_iter() + .collect() + }; + let expected = match model { + VadModel::SileroV5 => silero(SileroVersion::V5), + VadModel::SileroV6 => silero(SileroVersion::V6), + VadModel::SileroFusion => silero(SileroVersion::V5) + .into_iter() + .zip(silero(SileroVersion::V6)) + .map(|(v5, v6)| v5.max(v6)) + .collect(), + }; + + let audio = NemoReference::silero(SileroVersion::V6).f32("audio"); let audio = audio.as_slice().expect("contiguous audio"); let vad = SileroVad::from_bundle(&nemo_parity_bundle(ParakeetDeployment::v3())) - .expect("native VAD should load") - .expect("the native bundle should have a VAD model"); + .expect("native VAD should load"); let ours = vad - .process(audio, &TranscriptionControl::internal_unbounded()) + .process(audio, model, &TranscriptionControl::internal_unbounded()) .expect("VAD scan"); - ( - ours, - reference.f32("probs").into_iter().collect(), - audio.len(), - ) + (ours, expected, audio.len()) } /// Regions and planned ASR windows `(start, end)` for one set of probabilities @@ -1374,22 +1511,38 @@ mod tests { (regions, windows) } - /// The native VAD's probabilities plan the same speech regions and ASR windows - /// as Silero's own on the reference recording, with the native defaults and with - /// 3 s windows that make the planner split the region on its probabilities + /// For each VAD model, the native VAD's probabilities plan the same speech + /// regions and ASR windows as Silero's own on the reference recording, with the + /// model's defaults and with 3 s windows that make the planner split the region + /// on its probabilities #[cfg(all(feature = "cuda", feature = "vad"))] #[test] #[ignore = "reads Silero references from /shared/datasets/parakeet-ref"] fn nemo_parity_native_vad_plans_the_reference_windows() { - let (ours, expected, audio_len) = reference_probabilities(); - let defaults = LongFormConfig::for_bundle(&nemo_parity_bundle(ParakeetDeployment::v3())); - let mut short_windows = defaults.clone(); - short_windows.overlap.max_model_samples = 48_000; - - for config in [defaults, short_windows] { - let plan = speech_plan(&ours, audio_len, &config); - assert!(!plan.0.is_empty(), "the reference recording is speech"); - assert_eq!(plan, speech_plan(&expected, audio_len, &config)); + for model in [ + VadModel::SileroV5, + VadModel::SileroV6, + VadModel::SileroFusion, + ] { + let (ours, expected, audio_len) = reference_probabilities(model); + let mut defaults = + LongFormConfig::for_bundle(&nemo_parity_bundle(ParakeetDeployment::v3())); + defaults.segmentation = VadSegmentationConfig::for_model(model); + let mut short_windows = defaults.clone(); + short_windows.overlap.max_model_samples = 48_000; + + for config in [defaults, short_windows] { + let plan = speech_plan(&ours, audio_len, &config); + assert!( + !plan.0.is_empty(), + "{model:?}: the reference recording is speech" + ); + assert_eq!( + plan, + speech_plan(&expected, audio_len, &config), + "{model:?}" + ); + } } } @@ -1397,7 +1550,7 @@ mod tests { /// single-input limit, with gaps the VAD must leave out #[cfg(all(feature = "cuda", feature = "vad"))] fn sparse_speech() -> (Vec, Vec) { - let speech = NemoReference::silero().f32("audio"); + let speech = NemoReference::silero(SileroVersion::V6).f32("audio"); let speech = speech.as_slice().expect("contiguous audio"); let gap = vec![0.0; 20 * SAMPLE_RATE]; let audio = [speech, &gap, speech, &gap, speech].concat(); @@ -1425,12 +1578,13 @@ mod tests { audio: &[f32], config: &LongFormConfig, ) -> Vec<(usize, usize, usize)> { - let vad = pipeline + let probabilities = pipeline .vad - .as_ref() - .expect("the native bundle has a VAD model"); - let probabilities = vad - .process(audio, &TranscriptionControl::internal_unbounded()) + .process( + audio, + config.segmentation.model, + &TranscriptionControl::internal_unbounded(), + ) .expect("VAD scan"); let (_, windows) = speech_plan(&probabilities, audio.len(), config); windows @@ -1440,6 +1594,105 @@ mod tests { .collect() } + /// The reference speech and 20 s of silence, 40 times over: 20 minutes, long + /// enough that the native VAD scores it in several blocks and the run streams + #[cfg(all(feature = "cuda", feature = "vad"))] + fn long_sparse_speech() -> Vec { + let speech = NemoReference::silero(SileroVersion::V6).f32("audio"); + let speech = speech.as_slice().expect("contiguous audio"); + let gap = vec![0.0; 20 * SAMPLE_RATE]; + [speech, &gap].concat().repeat(40) + } + + /// Without a window limit, VAD runs transcribe windows while the scan goes on; + /// every path still preprocesses exactly the planned windows and returns the + /// transcript of scanning first + #[cfg(all(feature = "cuda", feature = "vad"))] + #[test] + #[ignore = "needs a CUDA GPU and the native weights; `just gpu-parity` runs it on gpu0"] + fn gpu_streamed_vad_matches_scanning_first() { + let (pipeline, base) = native_vad_pipeline(); + let audio = long_sparse_speech(); + + for path in [ + ExecutionPath::Serial, + ExecutionPath::Parallel, + ExecutionPath::Batched, + ] { + let config = path.config(&base); + let planned = planned_vad_windows(&pipeline, &audio, &config); + assert!( + planned.len() > config.batch_size, + "{path:?} planned {planned:?}" + ); + let scanned_first = pipeline + .run_with_preprocessor( + &audio, + &config, + &recording_control(planned.len()), + &super::IdentityPreprocessor, + ) + .unwrap_or_else(|error| panic!("{path:?} scan-first run failed: {error}")); + let hook = RecordingHook(Arc::new(Mutex::new(Vec::new()))); + + let streamed = pipeline + .run_with_preprocessor( + &audio, + &config, + &TranscriptionControl::internal_unbounded(), + &hook, + ) + .unwrap_or_else(|error| panic!("{path:?} streamed run failed: {error}")); + + let mut observed = observed_hooks(&hook); + if !matches!(path, ExecutionPath::Serial) { + observed.sort_unstable(); + } + assert_eq!(observed, planned, "{path:?} preprocessed windows"); + assert!(!streamed.text.is_empty(), "{path:?} transcribed no speech"); + assert_eq!(streamed, scanned_first, "{path:?} transcript"); + } + } + + /// A preprocessor error while the scan goes on stops the scan and every worker, + /// and the run reports the error rather than the stop + #[cfg(all(feature = "cuda", feature = "vad"))] + #[test] + #[ignore = "needs a CUDA GPU and the native weights; `just gpu-parity` runs it on gpu0"] + fn gpu_streamed_vad_reports_a_preprocessor_error() { + let (pipeline, base) = native_vad_pipeline(); + let audio = long_sparse_speech(); + + for path in [ + ExecutionPath::Serial, + ExecutionPath::Parallel, + ExecutionPath::Batched, + ] { + let config = path.config(&base); + let planned = planned_vad_windows(&pipeline, &audio, &config).len(); + let hook = FailingHook(RecordingHook(Arc::new(Mutex::new(Vec::new())))); + let control = TranscriptionControl::internal_unbounded(); + + let error = pipeline + .run_with_preprocessor(&audio, &config, &control, &hook) + .expect_err("a preprocessor failure should stop the run"); + + assert!( + matches!( + error, + PreprocessedTranscriptionError::Preprocessing(HookError) + ), + "{path:?} returned {error}" + ); + let observed = observed_hooks(&hook.0).len(); + assert!( + observed < planned, + "{path:?} preprocessed all {planned} windows after the first error" + ); + assert_eq!(control.check(), Ok(()), "{path:?} cancelled the caller"); + } + } + /// In VAD mode every path preprocesses exactly the planned speech windows, and /// none of them reaches into the middle of a silent gap #[cfg(all(feature = "cuda", feature = "vad"))] diff --git a/src/long_form/execute.rs b/src/long_form/execute.rs index 4d5e052..8c7a839 100644 --- a/src/long_form/execute.rs +++ b/src/long_form/execute.rs @@ -7,7 +7,7 @@ use std::sync::{Condvar, Mutex, PoisonError}; use std::thread; use super::planner::ChunkTask; -use super::{LongFormConfig, validate_finite_samples}; +use super::{LongFormConfig, StopRunOnPanic, validate_finite_samples}; use crate::decode::RawTranscription; use crate::error::TranscriptionError; use crate::pipeline::{ChunkPreparer, PreparedWindow, TranscriptionPipeline}; @@ -47,27 +47,137 @@ impl<'a, P: ?Sized> RunRequest<'a, P> { } } +/// A plan's windows, all known up front or added while the VAD scan finds more +/// +/// Executors take windows by index and wait for one not planned yet, so the model +/// can start on a recording's first speech while the rest is still scanned +pub(super) struct TaskStream { + state: Mutex, + changed: Condvar, +} + +struct TaskStreamState { + tasks: Vec, + /// Whether the plan is complete + closed: bool, +} + +impl TaskStream { + /// A plan whose windows are all known + pub(super) fn complete(tasks: &[ChunkTask]) -> Self { + Self::with_state(tasks.to_vec(), true) + } + + /// A plan still being built, until [`Self::close`] + #[cfg(feature = "vad")] + pub(super) fn open() -> Self { + Self::with_state(Vec::new(), false) + } + + fn with_state(tasks: Vec, closed: bool) -> Self { + Self { + state: Mutex::new(TaskStreamState { tasks, closed }), + changed: Condvar::new(), + } + } + + /// Adds the windows planned since the last call, `planned` being every window + /// planned so far + #[cfg(feature = "vad")] + pub(super) fn extend(&self, planned: &[ChunkTask]) { + let mut state = self.lock(); + let known = state.tasks.len(); + if planned.len() > known { + state.tasks.extend_from_slice(&planned[known..]); + self.changed.notify_all(); + } + } + + /// Ends the plan, also when planning failed; executors stop at its last window + #[cfg(feature = "vad")] + pub(super) fn close(&self) { + self.lock().closed = true; + self.changed.notify_all(); + } + + /// Window `index`, once planned; `None` once the plan ends without it + fn get(&self, index: usize) -> Option { + let mut state = self.lock(); + loop { + if let Some(task) = state.tasks.get(index) { + return Some(*task); + } + if state.closed { + return None; + } + state = self + .changed + .wait(state) + .unwrap_or_else(PoisonError::into_inner); + } + } + + /// Windows planned so far + fn planned(&self) -> usize { + self.lock().tasks.len() + } + + /// Workers for `requested`, no more than a complete plan has windows + /// + /// A plan still being built first waits for its second window or its end, so a + /// plan of one window runs serially on the caller's model rather than on a + /// parallel worker that loads another. The scan plans the next window long + /// before a worker could load its model, and at worst this waits out the + /// scan, as a run that plans the whole recording first does + fn worker_count(&self, requested: usize) -> usize { + self.get(1); + let state = self.lock(); + if state.closed { + parallel_worker_count(state.tasks.len(), requested) + } else { + requested.max(1) + } + } + + fn lock(&self) -> std::sync::MutexGuard<'_, TaskStreamState> { + self.state.lock().unwrap_or_else(PoisonError::into_inner) + } +} + /// Runs the plan's windows on the path the config and backend select /// /// Returns each window's raw transcription in plan order pub(super) fn execute_plan( pipeline: &TranscriptionPipeline, request: RunRequest<'_, P>, - tasks: &[ChunkTask], + tasks: &TaskStream, ) -> Result>, PreprocessedTranscriptionError> { // workers stop each other on this run's own signal, so a failed run leaves // the caller's control usable for its next run let control = request.control.run_scope(); - let request = RunRequest { - control: &control, - ..request - }; + execute_scoped_plan( + pipeline, + RunRequest { + control: &control, + ..request + }, + tasks, + ) +} + +/// [`execute_plan`] for a request whose control is already the run's own +/// [`TranscriptionControl::run_scope`], shared with whatever else the run does +pub(super) fn execute_scoped_plan( + pipeline: &TranscriptionPipeline, + request: RunRequest<'_, P>, + tasks: &TaskStream, +) -> Result>, PreprocessedTranscriptionError> { // a host-loop backend runs a batch one window at a time with no control // checks between them, so it stays on the per-window paths if request.config.batch_size > 1 && pipeline.batches_on_device() { return run_batched_plan(pipeline, request, tasks); } - let worker_count = parallel_worker_count(tasks.len(), request.config.worker_count); + let worker_count = tasks.worker_count(request.config.worker_count); if worker_count <= 1 { return run_serial_plan(pipeline, request, tasks); } @@ -78,13 +188,14 @@ pub(super) fn execute_plan( fn run_serial_plan( pipeline: &TranscriptionPipeline, request: RunRequest<'_, P>, - tasks: &[ChunkTask], + tasks: &TaskStream, ) -> Result>, PreprocessedTranscriptionError> { let context = request.task_context(pipeline); - let mut raw_tasks = vec![None; tasks.len()]; - for (task_idx, task) in tasks.iter().enumerate() { + let mut raw_tasks = Vec::new(); + while let Some(task) = tasks.get(raw_tasks.len()) { request.control.check()?; - raw_tasks[task_idx] = Some(transcribe_task(&context, task, WindowIndex::new(task_idx))?); + let index = WindowIndex::new(raw_tasks.len()); + raw_tasks.push(Some(transcribe_task(&context, &task, index)?)); } request.control.check()?; Ok(raw_tasks) @@ -100,13 +211,13 @@ fn run_serial_plan( fn run_batched_plan( pipeline: &TranscriptionPipeline, request: RunRequest<'_, P>, - tasks: &[ChunkTask], + tasks: &TaskStream, ) -> Result>, PreprocessedTranscriptionError> { let RunRequest { config, control, .. } = request; let batch_size = config.batch_size; - let worker_count = parallel_worker_count(tasks.len(), config.worker_count); + let worker_count = tasks.worker_count(config.worker_count); let next_task = AtomicUsize::new(0); let lookahead = Lookahead::new(batch_size); // the pipeline is not `Sync`, so each worker builds its preparer from this @@ -121,8 +232,12 @@ fn run_batched_plan( scope.spawn(move || { // a panicking worker closes the gate, so the others stop and // drop their senders, the model side sees the channel close, - // and the scope's join raises the panic instead of hanging + // and the scope's join raises the panic instead of hanging. + // Stopping the run also stops the scan, which closes the plan + // and wakes workers waiting in `TaskStream::get` for windows + // the scan has not found yet let _stop_on_panic = StopOnPanic(lookahead); + let _stop_run_on_panic = StopRunOnPanic(control); let preparer = chunk.preparer(); loop { let task_idx = next_task.fetch_add(1, Ordering::Relaxed); @@ -132,7 +247,7 @@ fn run_batched_plan( if !lookahead.wait_for(task_idx) { break; } - let window = prepare_window(&request, &preparer, task, task_idx); + let window = prepare_window(&request, &preparer, &task, task_idx); let failed = window.is_err(); // a closed channel means the model side has stopped if sender.send((task_idx, window)).is_err() || failed { @@ -143,18 +258,25 @@ fn run_batched_plan( } drop(sender); // a panic in the model call unwinds past the cleanup below, and the - // scope would then wait on workers parked at the gate + // scope would then wait on workers parked at the gate or in + // `TaskStream::get` until the scan ends let _stop_on_panic = StopOnPanic(&lookahead); + let _stop_run_on_panic = StopRunOnPanic(control); - // windows arrive in any order; batches are cut in plan order, and an - // error surfaces when its window is reached, as on the serial path + // windows arrive in any order; batches are cut in plan order, each + // full unless it holds the plan's last window, so a plan still being + // built batches as it would complete, and an error surfaces when its + // window is reached, as on the serial path let consume = || -> Result, PreprocessedTranscriptionError> { let mut ready = BTreeMap::new(); - let mut raw_tasks = Vec::with_capacity(tasks.len()); - for batch_start in (0..tasks.len()).step_by(batch_size) { - let batch_end = (batch_start + batch_size).min(tasks.len()); - let mut windows = Vec::with_capacity(batch_end - batch_start); - for task_idx in batch_start..batch_end { + let mut raw_tasks = Vec::new(); + loop { + let batch_start = raw_tasks.len(); + let mut windows = Vec::with_capacity(batch_size); + for task_idx in batch_start..batch_start + batch_size { + if tasks.get(task_idx).is_none() { + break; + } while !ready.contains_key(&task_idx) { let (done_idx, window) = receiver.recv().map_err(|_| { TranscriptionError::InvalidModelOutput(format!( @@ -170,7 +292,14 @@ fn run_batched_plan( })?; windows.push(window?); } + if windows.is_empty() { + // a run stopped after the last window must not return as a + // finished, empty transcription, as on the serial path + control.check()?; + break; + } // the next batch prepares while this one runs + let batch_end = batch_start + windows.len(); lookahead.allow(batch_end + batch_size); control.check()?; @@ -178,6 +307,9 @@ fn run_batched_plan( .transcribe_prepared_batch(&windows, config.transcription.language)?; raw_tasks.extend(raws.into_iter().map(Some)); control.check()?; + if windows.len() < batch_size { + break; + } } Ok(raw_tasks) }; @@ -201,7 +333,7 @@ fn run_batched_plan( fn run_parallel_plan( pipeline: &TranscriptionPipeline, request: RunRequest<'_, P>, - tasks: &[ChunkTask], + tasks: &TaskStream, worker_count: usize, ) -> Result>, PreprocessedTranscriptionError> { let control = request.control; @@ -220,6 +352,15 @@ fn run_parallel_plan( // own from the bundle let bundle = pipeline.bundle().clone(); scope.spawn(move || { + // the other workers and the scan stop instead of running the plan + // out before the panic surfaces at the scope's join + let _stop = StopRunOnPanic(control); + // a worker loads its model once it has a window, so a plan still + // being built loads none it turns out not to need + let mut task_idx = next_task.fetch_add(1, Ordering::Relaxed); + if tasks.get(task_idx).is_none() { + return; + } let pipeline = match TranscriptionPipeline::from_bundle(bundle) { Ok(pipeline) => pipeline, Err(error) => { @@ -229,18 +370,12 @@ fn run_parallel_plan( } }; let context = request.task_context(&pipeline); - loop { - let task_idx = next_task.fetch_add(1, Ordering::Relaxed); - if task_idx >= tasks.len() { - break; - } - + while let Some(task) = tasks.get(task_idx) { if control.check().is_err() { break; } - let result = - transcribe_task(&context, &tasks[task_idx], WindowIndex::new(task_idx)) - .map(|raw| CompletedTask { task_idx, raw }); + let result = transcribe_task(&context, &task, WindowIndex::new(task_idx)) + .map(|raw| CompletedTask { task_idx, raw }); if let Err(error) = &result && !is_interruption(error) { @@ -249,34 +384,43 @@ fn run_parallel_plan( if sender.send(result).is_err() { break; } + task_idx = next_task.fetch_add(1, Ordering::Relaxed); } }); } drop(sender); - collect_completed_tasks(tasks.len(), receiver, control) + collect_completed_tasks(tasks, receiver, control) }) } /// Gathers the parallel workers' windows into plan order, or the error that /// stopped them fn collect_completed_tasks( - task_count: usize, + tasks: &TaskStream, receiver: Receiver>>, control: &TranscriptionControl, ) -> Result>, PreprocessedTranscriptionError> where E: std::error::Error + Send + Sync + 'static, { - let mut raw_tasks = vec![None; task_count]; + let mut raw_tasks = Vec::new(); let mut first_error = None; while let Ok(message) = receiver.recv() { match message { - Ok(completed) => raw_tasks[completed.task_idx] = Some(completed.raw), + Ok(completed) => { + if raw_tasks.len() <= completed.task_idx { + raw_tasks.resize(completed.task_idx + 1, None); + } + raw_tasks[completed.task_idx] = Some(completed.raw); + } Err(error) => remember_parallel_error(&mut first_error, error), } } + // every worker has stopped, so the plan is complete unless the run stopped + // first, which the checks below report + raw_tasks.resize(tasks.planned().max(raw_tasks.len()), None); if let Some(error) = first_error { return Err(error); @@ -437,7 +581,7 @@ fn prepare_window_samples( /// Whether the error only reports that the run was cancelled or ran out of time, /// rather than a failure that should stop the other workers -fn is_interruption(error: &PreprocessedTranscriptionError) -> bool +pub(super) fn is_interruption(error: &PreprocessedTranscriptionError) -> bool where E: std::error::Error + Send + Sync + 'static, { @@ -495,6 +639,40 @@ mod tests { assert_eq!(parallel_worker_count(3, 8), 3); } + /// A plan still being built picks its workers once it has a second window or + /// ends with one, so a one-window plan takes the serial path on the caller's + /// model + #[cfg(feature = "vad")] + #[test] + fn open_plan_picks_workers_once_it_has_two_windows_or_ends() { + use super::TaskStream; + + let mut config = LongFormConfig::default(); + config.overlap.max_model_samples = 48_000; + let plan = build_fast_execution_plan(96_000, &config); + assert!( + plan.tasks.len() >= 2, + "the plan should have several windows" + ); + + let one_window = TaskStream::open(); + let two_windows = TaskStream::open(); + let (one, two) = std::thread::scope(|scope| { + let one = scope.spawn(|| one_window.worker_count(4)); + let two = scope.spawn(|| two_windows.worker_count(4)); + one_window.extend(&plan.tasks[..1]); + two_windows.extend(&plan.tasks[..1]); + two_windows.extend(&plan.tasks[..2]); + let two = two.join().expect("worker count should not panic"); + one_window.close(); + two_windows.close(); + (one.join().expect("worker count should not panic"), two) + }); + + assert_eq!(one, 1); + assert_eq!(two, 4); + } + #[test] fn preparation_hook_runs_once_for_each_planned_window_with_source_coordinates() { let mut config = LongFormConfig::default(); diff --git a/src/long_form/planner.rs b/src/long_form/planner.rs index fc70669..bd9f266 100644 --- a/src/long_form/planner.rs +++ b/src/long_form/planner.rs @@ -11,6 +11,44 @@ pub(crate) struct SampleRange { pub end: usize, } +/// Silero VAD model that scores each window's speech probability +/// +/// The default, Silero fusion, is the most accurate or within 0.1 WER points of it on +/// every set measured (README). Silero +/// v6 alone beats v5 on calls and meetings but loses on sparse speech, where it +/// takes more music and effects for speech, and on far-field conversation, where it +/// misses distant speakers +#[cfg(feature = "vad")] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)] +pub enum VadModel { + /// Silero VAD 5.1.2 + SileroV5, + /// Silero VAD 6.2.3 + SileroV6, + /// Both Silero models, keeping each window's higher speech probability + /// + /// Speech either model finds counts, which recovers what v6 misses on far-field + /// audio. The two run at once, so it costs little more than one model + #[default] + SileroFusion, +} + +#[cfg(feature = "vad")] +impl VadModel { + /// Speech threshold this model was measured at, and the one + /// [`VadSegmentationConfig::for_model`] sets + pub fn default_threshold(self) -> f32 { + match self { + // Silero's own default; 0.85 dropped low-confidence phone and far-field + // speech, raising long-form WER on every set measured (README) + Self::SileroV5 | Self::SileroV6 => 0.5, + // fusion raises every window's probability, so 0.5 let in more non-speech + // and lost accuracy on sparse speech; 0.6 matched or beat v5 everywhere + Self::SileroFusion => 0.6, + } + } +} + /// Segmentation parameters for converting VAD probabilities into speech regions /// /// The model hard sample maximum is not stored here. Pass @@ -18,6 +56,9 @@ pub(crate) struct SampleRange { #[cfg(feature = "vad")] #[derive(Debug, Clone)] pub struct VadSegmentationConfig { + /// VAD model that scores speech; build the config with [`Self::for_model`] to + /// also take the model's threshold + pub model: VadModel, /// Speech probability at or above which a VAD window counts as speech pub threshold: f32, /// Minimum speech span kept in the output @@ -39,13 +80,20 @@ pub struct VadSegmentationConfig { #[cfg(feature = "vad")] impl Default for VadSegmentationConfig { fn default() -> Self { + Self::for_model(VadModel::default()) + } +} + +#[cfg(feature = "vad")] +impl VadSegmentationConfig { + /// Default segmentation for a VAD model, at its [`VadModel::default_threshold`] + pub fn for_model(model: VadModel) -> Self { Self { - // Silero's own default; 0.85 dropped low-confidence phone and far-field - // speech, raising long-form WER on every set measured (README) - threshold: 0.5, + model, + threshold: model.default_threshold(), min_speech_duration: 0.15, min_silence_duration: 0.75, - // Silero crosses the threshold up to ~220 ms into a soft onset, so 0.1 s + // Silero v5 crosses the threshold up to ~220 ms into a soft onset, so 0.1 s // clipped short first words ("a cold" became "cold"); 0.2 s lowered // long-form WER on every set measured, larger values cost AMI headset // accuracy (README) @@ -56,10 +104,7 @@ impl Default for VadSegmentationConfig { min_silence_at_max_speech: 0.098, } } -} -#[cfg(feature = "vad")] -impl VadSegmentationConfig { pub(crate) fn validate(&self) -> Result<(), TranscriptionError> { validate_probability("vad.threshold", self.threshold)?; validate_positive_duration("vad.min_speech_duration", self.min_speech_duration)?; @@ -260,97 +305,161 @@ fn validate_positive_duration(field: &str, value: f64) -> Result<(), Transcripti ))) } +/// Speech regions of a recording from its VAD window probabilities #[cfg(feature = "vad")] pub(crate) fn detect_speech_regions( probabilities: &[f32], audio_length_samples: usize, config: &VadSegmentationConfig, ) -> Vec { - if probabilities.is_empty() || audio_length_samples == 0 { - return Vec::new(); + let mut detector = SpeechRegions::new(audio_length_samples, config); + let mut regions = detector.push(probabilities); + regions.extend(detector.finish()); + regions +} + +/// Finds the speech regions of a recording as its VAD probabilities arrive +/// +/// Speech starts at a window at or above the threshold and ends after +/// `min_silence_duration` below the negative threshold; speech shorter than +/// `min_speech_duration` is dropped. Each region is padded by `speech_padding`, +/// or by half the gap when the next region is closer than twice that. A region is +/// returned once no later probability can change it: when the next region is +/// found, or once the scan is twice the padding past its end with no speech +/// started. Pushing the probabilities in any number of pieces gives the same +/// regions +#[cfg(feature = "vad")] +pub(crate) struct SpeechRegions { + audio_len: usize, + threshold: f32, + negative_threshold: f32, + min_speech_samples: usize, + min_silence_samples: usize, + speech_pad_samples: usize, + /// Probabilities scanned so far + scanned: usize, + triggered: bool, + speech_start: usize, + silence_start: Option, + /// The last speech found, its start padded and its end not yet + open: Option, +} + +#[cfg(feature = "vad")] +impl SpeechRegions { + pub(crate) fn new(audio_len: usize, config: &VadSegmentationConfig) -> Self { + let samples = |seconds: f64| (seconds * SAMPLE_RATE as f64) as usize; + Self { + audio_len, + threshold: config.threshold, + negative_threshold: config.effective_negative_threshold(), + min_speech_samples: samples(config.min_speech_duration), + min_silence_samples: samples(config.min_silence_duration), + speech_pad_samples: samples(config.speech_padding), + scanned: 0, + triggered: false, + speech_start: 0, + silence_start: None, + open: None, + } } - let hop_size = VAD_WINDOW_SAMPLES; - let min_speech_samples = (config.min_speech_duration * SAMPLE_RATE as f64) as usize; - let min_silence_samples = (config.min_silence_duration * SAMPLE_RATE as f64) as usize; - let speech_pad_samples = (config.speech_padding * SAMPLE_RATE as f64) as usize; - let threshold = config.threshold; - let negative_threshold = config.effective_negative_threshold(); - - let mut triggered = false; - let mut current_speech_start = 0usize; - let mut temp_end = None; - let mut speeches = Vec::new(); - - for (index, probability) in probabilities.iter().copied().enumerate() { - let frame_start = index * hop_size; - if probability >= threshold { - temp_end = None; - if !triggered { - triggered = true; - current_speech_start = frame_start; - } - continue; + /// Scans the probabilities not seen yet, `probabilities` being every one so + /// far, and returns the regions that became final + /// + /// A returned region's probabilities all lie in `probabilities` + pub(crate) fn push(&mut self, probabilities: &[f32]) -> Vec { + let mut regions = Vec::new(); + if self.audio_len == 0 { + return regions; } - if probability < negative_threshold && triggered { - if temp_end.is_none() { - temp_end = Some(frame_start); + for (index, probability) in probabilities.iter().copied().enumerate().skip(self.scanned) { + let frame_start = index * VAD_WINDOW_SAMPLES; + if probability >= self.threshold { + self.silence_start = None; + if !self.triggered { + self.triggered = true; + self.speech_start = frame_start; + } + continue; } - if let Some(start_silence) = temp_end - && frame_start.saturating_sub(start_silence) >= min_silence_samples - { - if start_silence.saturating_sub(current_speech_start) >= min_speech_samples { - speeches.push(SampleRange { - start: current_speech_start, - end: start_silence, - }); + + if probability < self.negative_threshold && self.triggered { + let silence_start = *self.silence_start.get_or_insert(frame_start); + if frame_start.saturating_sub(silence_start) >= self.min_silence_samples { + if silence_start.saturating_sub(self.speech_start) >= self.min_speech_samples { + self.speech(self.speech_start, silence_start, &mut regions); + } + self.triggered = false; + self.silence_start = None; } - triggered = false; - temp_end = None; } } - } + self.scanned = self.scanned.max(probabilities.len()); - if triggered && audio_length_samples.saturating_sub(current_speech_start) >= min_speech_samples - { - speeches.push(SampleRange { - start: current_speech_start, - end: audio_length_samples, - }); + // no later speech starts before this, so an open region this far behind + // keeps its full padding whatever comes next + let next_start = if self.triggered { + self.speech_start + } else { + self.scanned * VAD_WINDOW_SAMPLES + }; + if let Some(open) = self.open + && next_start.saturating_sub(open.end) >= 2 * self.speech_pad_samples + { + self.open = None; + self.emit(open.start, open.end + self.speech_pad_samples, &mut regions); + } + regions } - if speeches.is_empty() { - return Vec::new(); - } + /// The regions left once every probability has been pushed + pub(crate) fn finish(mut self) -> Vec { + let mut regions = Vec::new(); + if self.scanned == 0 || self.audio_len == 0 { + return regions; + } - let mut adjusted = speeches; - for index in 0..adjusted.len() { - if index == 0 { - adjusted[index].start = adjusted[index].start.saturating_sub(speech_pad_samples); + if self.triggered + && self.audio_len.saturating_sub(self.speech_start) >= self.min_speech_samples + { + self.speech(self.speech_start, self.audio_len, &mut regions); } - if index < adjusted.len() - 1 { - let silence = adjusted[index + 1] - .start - .saturating_sub(adjusted[index].end); - if silence < 2 * speech_pad_samples { - let half = silence / 2; - adjusted[index].end = (adjusted[index].end + half).min(audio_length_samples); - adjusted[index + 1].start = adjusted[index + 1].start.saturating_sub(half); - } else { - adjusted[index].end = - (adjusted[index].end + speech_pad_samples).min(audio_length_samples); - adjusted[index + 1].start = - adjusted[index + 1].start.saturating_sub(speech_pad_samples); - } - } else { - adjusted[index].end = - (adjusted[index].end + speech_pad_samples).min(audio_length_samples); + if let Some(open) = self.open.take() { + self.emit(open.start, open.end + self.speech_pad_samples, &mut regions); } + regions + } + + /// Records speech from `start` to `end`, which fixes the padding between it + /// and the open region + fn speech(&mut self, start: usize, end: usize, regions: &mut Vec) { + let pad = match self.open.take() { + Some(open) => { + let silence = start.saturating_sub(open.end); + let pad = if silence < 2 * self.speech_pad_samples { + silence / 2 + } else { + self.speech_pad_samples + }; + self.emit(open.start, open.end + pad, regions); + pad + } + None => self.speech_pad_samples, + }; + self.open = Some(SampleRange { + start: start.saturating_sub(pad), + end, + }); } - adjusted.retain(|range| range.end > range.start); - adjusted + fn emit(&self, start: usize, end: usize, regions: &mut Vec) { + let end = end.min(self.audio_len); + if end > start { + regions.push(SampleRange { start, end }); + } + } } #[cfg(feature = "vad")] @@ -454,22 +563,54 @@ pub(super) fn build_vad_execution_plan( probabilities: &[f32], config: &LongFormConfig, ) -> LongFormExecutionPlan { - let mut tasks = Vec::new(); - let mut region_tasks = Vec::with_capacity(regions.len()); - let mut previous_end = 0; + let mut plan = VadPlan::new(config); for region in regions.iter().copied() { - region_tasks.push(build_region_plan( + plan.add_region(region, probabilities); + } + plan.finish() +} + +/// A VAD plan built a region at a time, in recording order +#[cfg(feature = "vad")] +pub(super) struct VadPlan<'a> { + config: &'a LongFormConfig, + plan: LongFormExecutionPlan, + previous_end: usize, +} + +#[cfg(feature = "vad")] +impl<'a> VadPlan<'a> { + pub(super) fn new(config: &'a LongFormConfig) -> Self { + Self { + config, + plan: LongFormExecutionPlan { + tasks: Vec::new(), + regions: Vec::new(), + }, + previous_end: 0, + } + } + + /// Plans the windows of `region`, whose probabilities lie in `probabilities` + pub(super) fn add_region(&mut self, region: SampleRange, probabilities: &[f32]) { + let region_task = build_region_plan( region, - previous_end, + self.previous_end, probabilities, - config, - &mut tasks, - )); - previous_end = region.end; + self.config, + &mut self.plan.tasks, + ); + self.plan.regions.push(region_task); + self.previous_end = region.end; + } + + /// Every window planned so far, in plan order + pub(super) fn tasks(&self) -> &[ChunkTask] { + &self.plan.tasks } - LongFormExecutionPlan { - tasks, - regions: region_tasks, + + pub(super) fn finish(self) -> LongFormExecutionPlan { + self.plan } } @@ -616,7 +757,8 @@ mod tests { use super::{OverlapChunkConfig, RegionTaskKind, SampleRange, build_fast_execution_plan}; #[cfg(feature = "vad")] use super::{ - VadSegmentationConfig, build_region_plan, detect_speech_regions, plan_region_subsegments, + SpeechRegions, VadModel, VadSegmentationConfig, build_region_plan, detect_speech_regions, + plan_region_subsegments, }; use crate::constants::SAMPLES_PER_ENCODER_FRAME; #[cfg(feature = "vad")] @@ -635,11 +777,188 @@ mod tests { } } + /// Speech regions as the planner found them before it streamed: every + /// probability scanned first, then each region padded against its neighbours + #[cfg(feature = "vad")] + fn whole_recording_regions( + probabilities: &[f32], + audio_length_samples: usize, + config: &VadSegmentationConfig, + ) -> Vec { + use crate::constants::SAMPLE_RATE; + + if probabilities.is_empty() || audio_length_samples == 0 { + return Vec::new(); + } + + let hop_size = VAD_WINDOW_SAMPLES; + let min_speech_samples = (config.min_speech_duration * SAMPLE_RATE as f64) as usize; + let min_silence_samples = (config.min_silence_duration * SAMPLE_RATE as f64) as usize; + let speech_pad_samples = (config.speech_padding * SAMPLE_RATE as f64) as usize; + let threshold = config.threshold; + let negative_threshold = config.effective_negative_threshold(); + + let mut triggered = false; + let mut current_speech_start = 0usize; + let mut temp_end = None; + let mut speeches = Vec::new(); + + for (index, probability) in probabilities.iter().copied().enumerate() { + let frame_start = index * hop_size; + if probability >= threshold { + temp_end = None; + if !triggered { + triggered = true; + current_speech_start = frame_start; + } + continue; + } + + if probability < negative_threshold && triggered { + if temp_end.is_none() { + temp_end = Some(frame_start); + } + if let Some(start_silence) = temp_end + && frame_start.saturating_sub(start_silence) >= min_silence_samples + { + if start_silence.saturating_sub(current_speech_start) >= min_speech_samples { + speeches.push(SampleRange { + start: current_speech_start, + end: start_silence, + }); + } + triggered = false; + temp_end = None; + } + } + } + + if triggered + && audio_length_samples.saturating_sub(current_speech_start) >= min_speech_samples + { + speeches.push(SampleRange { + start: current_speech_start, + end: audio_length_samples, + }); + } + + let mut adjusted = speeches; + for index in 0..adjusted.len() { + if index == 0 { + adjusted[index].start = adjusted[index].start.saturating_sub(speech_pad_samples); + } + if index < adjusted.len() - 1 { + let silence = adjusted[index + 1] + .start + .saturating_sub(adjusted[index].end); + if silence < 2 * speech_pad_samples { + let half = silence / 2; + adjusted[index].end = (adjusted[index].end + half).min(audio_length_samples); + adjusted[index + 1].start = adjusted[index + 1].start.saturating_sub(half); + } else { + adjusted[index].end = + (adjusted[index].end + speech_pad_samples).min(audio_length_samples); + adjusted[index + 1].start = + adjusted[index + 1].start.saturating_sub(speech_pad_samples); + } + } else { + adjusted[index].end = + (adjusted[index].end + speech_pad_samples).min(audio_length_samples); + } + } + + adjusted.retain(|range| range.end > range.start); + adjusted + } + + /// xorshift64, so the generated recordings are the same on every run + #[cfg(feature = "vad")] + struct Rng(u64); + + #[cfg(feature = "vad")] + impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + + /// Uniform in `0..bound` + fn below(&mut self, bound: usize) -> usize { + (self.next() % bound as u64) as usize + } + + fn unit(&mut self) -> f32 { + (self.next() >> 40) as f32 / (1u64 << 24) as f32 + } + } + + /// Streaming the probabilities in random pieces finds exactly the regions the + /// whole-recording planner found, each returned only once its probabilities + /// have arrived + #[cfg(feature = "vad")] + #[test] + fn streamed_regions_match_the_whole_recording() { + let mut rng = Rng(0x5eed_cafe_f00d_d00d); + for case in 0..2_000 { + // runs of speech, silence and in-between scores, of lengths around the + // silence and padding durations, so gaps land on both sides of them + let windows = 1 + rng.below(1_500); + let mut probabilities = Vec::with_capacity(windows); + while probabilities.len() < windows { + let level = match rng.below(3) { + 0 => 0.6 + 0.4 * rng.unit(), + 1 => 0.3 * rng.unit(), + _ => 0.3 + 0.4 * rng.unit(), + }; + let run = 1 + rng.below(60); + probabilities.extend((0..run).map(|_| level + 0.05 * (rng.unit() - 0.5))); + } + probabilities.truncate(windows); + let audio_len = windows * VAD_WINDOW_SAMPLES - rng.below(VAD_WINDOW_SAMPLES); + + let config = VadSegmentationConfig { + min_speech_duration: 0.05 + 0.3 * rng.unit() as f64, + min_silence_duration: 0.05 + 1.0 * rng.unit() as f64, + speech_padding: 0.6 * rng.unit() as f64, + ..segmentation_at(0.4 + 0.3 * rng.unit()) + }; + let expected = whole_recording_regions(&probabilities, audio_len, &config); + assert_eq!( + detect_speech_regions(&probabilities, audio_len, &config), + expected, + "case {case} in one piece" + ); + + let mut detector = SpeechRegions::new(audio_len, &config); + let mut streamed = Vec::new(); + let mut arrived = 0; + while arrived < windows { + arrived = (arrived + 1 + rng.below(200)).min(windows); + let found = detector.push(&probabilities[..arrived]); + for region in &found { + assert!( + region.end.div_ceil(VAD_WINDOW_SAMPLES) <= arrived, + "case {case}: {region:?} returned with {arrived} windows scored" + ); + } + streamed.extend(found); + } + streamed.extend(detector.finish()); + assert_eq!(streamed, expected, "case {case} streamed"); + } + } + #[cfg(feature = "vad")] #[test] fn vad_defaults_lock_threshold_and_segmentation() { let segmentation = VadSegmentationConfig::default(); - assert_eq!(segmentation.threshold, 0.5); + assert_eq!(segmentation.model, VadModel::SileroFusion); + assert_eq!(segmentation.threshold, 0.6); + for (model, threshold) in [(VadModel::SileroV5, 0.5), (VadModel::SileroV6, 0.5)] { + assert_eq!(VadSegmentationConfig::for_model(model).threshold, threshold); + } assert_eq!(segmentation.min_speech_duration, 0.15); assert_eq!(segmentation.min_silence_duration, 0.75); assert_eq!(segmentation.speech_padding, 0.2); diff --git a/src/long_form/vad.rs b/src/long_form/vad.rs index 6930530..53b65e4 100644 --- a/src/long_form/vad.rs +++ b/src/long_form/vad.rs @@ -5,33 +5,184 @@ use crate::constants::{VAD_CONTEXT_SAMPLES, VAD_WINDOW_SAMPLES}; #[cfg(target_os = "macos")] use crate::coreml::SileroVadCoreMlModel; use crate::error::TranscriptionError; -use crate::models::{ModelBundle, RuntimeBundle}; +use crate::long_form::{StopRunOnPanic, VadModel}; +use crate::models::{ModelBundle, RuntimeBundle, SileroVersion}; #[cfg(feature = "cuda")] use crate::native::silero::{SileroModel, SileroState}; -use crate::preprocessing::TranscriptionControl; +use crate::preprocessing::{TranscriptionControl, TranscriptionControlError}; +use std::path::PathBuf; +use std::sync::mpsc; /// Silero VAD owner: window chunking, context carry-over, tail padding, and /// per-recording recurrent state reset /// -/// Runtimes only classify prepared windows and advance the opaque state +/// Holds every Silero model the bundle provides and runs the ones a +/// [`VadModel`] names. Runtimes only classify prepared windows and advance the +/// opaque state #[derive(Debug, Clone)] pub(crate) struct SileroVad { - model: VadModelInner, + v5: Slot, + v6: Slot, +} + +/// One Silero version: its model, or where the bundle expected it +#[derive(Debug, Clone)] +enum Slot { + Loaded(VadModelInner), + Missing(PathBuf), } impl SileroVad { - /// Load the VAD model a bundle provides, if it provides one - pub(crate) fn from_bundle(bundle: &ModelBundle) -> Result, TranscriptionError> { - VadModelInner::from_bundle(bundle).map(|model| model.map(|model| Self { model })) + /// Load every Silero model the bundle provides; a missing one fails only the + /// runs that need it + pub(crate) fn from_bundle(bundle: &ModelBundle) -> Result { + let slot = |version| { + let path = bundle.runtime().vad_paths().get(version); + if !path.exists() { + return Ok(Slot::Missing(path.to_path_buf())); + } + VadModelInner::load(bundle.runtime(), version, path).map(Slot::Loaded) + }; + Ok(Self { + v5: slot(SileroVersion::V5)?, + v6: slot(SileroVersion::V6)?, + }) } + /// Speech probability of each window of `audio` under `model` + /// + /// A model failure stops `control`'s run, as in [`Self::scan`] pub(crate) fn process( &self, audio: &[f32], + model: VadModel, + control: &TranscriptionControl, + ) -> Result, TranscriptionError> { + self.scan(audio, model, control, |_| {}) + } + + /// [`Self::process`], calling `progress` with every probability so far each time + /// more are ready, so the caller can act on the start of a recording while the + /// rest is scanned + /// + /// A model failure stops `control`'s run, so pass a run scope + /// ([`TranscriptionControl::run_scope`]) rather than a caller's own control + pub(crate) fn scan( + &self, + audio: &[f32], + model: VadModel, control: &TranscriptionControl, + mut progress: impl FnMut(&[f32]), ) -> Result, TranscriptionError> { - self.model.process(audio, control) + let models = match model { + VadModel::SileroV5 => vec![self.model(SileroVersion::V5)?], + VadModel::SileroV6 => vec![self.model(SileroVersion::V6)?], + VadModel::SileroFusion => vec![ + self.model(SileroVersion::V5)?, + self.model(SileroVersion::V6)?, + ], + }; + + // each model's recurrence is one thread's critical path, so running both at + // once costs little more than running one. Core ML models are `Send` but not + // `Sync`, so each thread gets its own clone, which shares the weights + // + // a scan that fails or panics stops the run, so the other scan and the + // run's windows stop instead of running to the end of the recording before + // the error surfaces. An interruption stops nothing: the other scan shares + // the same cancellation and deadline, and reports them itself + std::thread::scope(|scope| { + let (sender, receiver) = mpsc::channel(); + let scans: Vec<_> = models + .into_iter() + .enumerate() + .map(|(slot, model)| { + let model = model.clone(); + let sender = sender.clone(); + scope.spawn(move || { + let _stop = StopRunOnPanic(control); + // the receiver outlives every scan, so a send cannot fail + let scanned = model.process(audio, control, |block| { + let _ = sender.send((slot, block.to_vec())); + }); + if let Err(error) = &scanned + && !is_interruption(error) + { + control.stop_run(); + } + scanned + }) + }) + .collect(); + drop(sender); + + // fusion keeps each window's higher probability, once both models have + // scored it + let mut scores = vec![Vec::new(); scans.len()]; + let mut probabilities = Vec::new(); + for (slot, block) in receiver { + scores[slot].extend(block); + let ready = scores.iter().map(Vec::len).min().unwrap_or(0); + if ready == probabilities.len() { + continue; + } + // every model has scored a window below `ready` + probabilities.extend((probabilities.len()..ready).map(|index| { + scores + .iter() + .map(|model_scores| model_scores[index]) + .reduce(f32::max) + .unwrap_or_default() + })); + progress(&probabilities); + } + + // a model's own failure wins over the interruption it caused in the + // other scan; otherwise the first model's error wins + let mut first_error = None; + for scan in scans { + let scanned = scan + .join() + .unwrap_or_else(|panic| std::panic::resume_unwind(panic)); + if let Err(error) = scanned { + match &first_error { + None => first_error = Some(error), + Some(existing) if is_interruption(existing) && !is_interruption(&error) => { + first_error = Some(error); + } + Some(_) => {} + } + } + } + match first_error { + Some(error) => Err(error), + None => Ok(probabilities), + } + }) } + + fn model(&self, version: SileroVersion) -> Result<&VadModelInner, TranscriptionError> { + let slot = match version { + SileroVersion::V5 => &self.v5, + SileroVersion::V6 => &self.v6, + }; + match slot { + Slot::Loaded(model) => Ok(model), + Slot::Missing(path) => { + Err(TranscriptionError::MissingModelAsset { path: path.clone() }) + } + } + } +} + +/// Whether `error` only reports that the scan was stopped, rather than a failure +fn is_interruption(error: &TranscriptionError) -> bool { + matches!( + error, + TranscriptionError::Control( + TranscriptionControlError::Cancelled | TranscriptionControlError::DeadlineExpired + ) + ) } #[derive(Debug, Clone)] @@ -43,49 +194,48 @@ enum VadModelInner { // no VAD runtime without Core ML or the native weights; keeps the matches // below compiling #[cfg(not(any(target_os = "macos", feature = "cuda")))] - #[expect(dead_code, reason = "from_bundle never builds a VAD model here")] + #[expect(dead_code, reason = "load never builds a VAD model here")] Unsupported, } impl VadModelInner { - fn from_bundle(bundle: &ModelBundle) -> Result, TranscriptionError> { - match bundle.runtime() { - RuntimeBundle::CoreMl(layout) => { - if !layout.vad_dir().exists() { - return Ok(None); - } - + fn load( + runtime: &RuntimeBundle, + version: SileroVersion, + path: &std::path::Path, + ) -> Result { + match runtime { + RuntimeBundle::CoreMl(_) => { + // every Silero version takes the same Core ML inputs and outputs + let _ = version; #[cfg(target_os = "macos")] { - Ok(Some(Self::CoreMl(SileroVadCoreMlModel::new( - layout.vad_dir(), - )?))) + Ok(Self::CoreMl(SileroVadCoreMlModel::new(path)?)) } #[cfg(not(target_os = "macos"))] { + let _ = path; Err(TranscriptionError::UnsupportedPlatform) } } #[cfg(feature = "cuda")] - RuntimeBundle::Native(layout) => { - if !layout.vad_path().exists() { - return Ok(None); - } - Ok(Some(Self::Native(SileroModel::open(layout.vad_path())?))) - } + RuntimeBundle::Native(_) => Ok(Self::Native(SileroModel::open(path, version)?)), } } + /// Speech probability of each window of `audio`, also passed to `report` in + /// order as they are scored fn process( &self, audio: &[f32], control: &TranscriptionControl, + report: impl FnMut(&[f32]), ) -> Result, TranscriptionError> { match self { #[cfg(target_os = "macos")] Self::CoreMl(model) => { let mut state = vec![0.0f32; 2 * VAD_STATE_SIZE]; - process_blocks(audio, control, 1, |window, probabilities| { + process_blocks(audio, control, 1, report, |window, probabilities| { let (hidden_state, cell_state) = state.split_at_mut(VAD_STATE_SIZE); let outputs = model.run(window, hidden_state, cell_state)?; copy_state_vec(&outputs.hidden_state, hidden_state)?; @@ -101,6 +251,7 @@ impl VadModelInner { audio, control, model.block_windows(), + report, |windows, probabilities| { model.classify(windows, &mut state, probabilities); Ok(()) @@ -109,8 +260,7 @@ impl VadModelInner { } #[cfg(not(any(target_os = "macos", feature = "cuda")))] Self::Unsupported => { - let _ = audio; - let _ = control; + let _ = (audio, control, report); Err(TranscriptionError::UnsupportedPlatform) } } @@ -121,24 +271,32 @@ impl VadModelInner { #[cfg(any(target_os = "macos", feature = "cuda", test))] const WINDOW_INPUT_SAMPLES: usize = VAD_CONTEXT_SAMPLES + VAD_WINDOW_SAMPLES; +/// Probabilities scored between reports, about 8 s of audio; a Core ML block is one +/// window, and reporting each would cost a channel send per 32 ms of audio +#[cfg(any(target_os = "macos", feature = "cuda", test))] +const REPORT_WINDOWS: usize = 256; + /// Run one classifier over every window of a recording, `block_windows` at a time /// /// The caller starts the recurrent state at zero for each recording, and /// `classify` pushes one probability per window, in order. Each window is /// `VAD_CONTEXT_SAMPLES` from the previous chunk (zeros for the first) followed by /// one chunk of `VAD_WINDOW_SAMPLES`; a short final chunk is padded with its last -/// sample. Cancellation is checked before each block +/// sample. `report` gets the new probabilities after any block that brings them to +/// [`REPORT_WINDOWS`], and after the last. Cancellation is checked before each block #[cfg(any(target_os = "macos", feature = "cuda", test))] fn process_blocks( audio: &[f32], control: &TranscriptionControl, block_windows: usize, + mut report: impl FnMut(&[f32]), mut classify: impl FnMut(&[f32], &mut Vec) -> Result<(), TranscriptionError>, ) -> Result, TranscriptionError> { let count = audio.len().div_ceil(VAD_WINDOW_SAMPLES); let block_windows = block_windows.max(1); let mut probabilities = Vec::with_capacity(count); let mut inputs = vec![0.0f32; block_windows.min(count) * WINDOW_INPUT_SAMPLES]; + let mut reported = 0; for first in (0..count).step_by(block_windows) { control.check()?; @@ -156,6 +314,10 @@ fn process_blocks( let before = probabilities.len(); classify(inputs, &mut probabilities)?; debug_assert_eq!(probabilities.len(), before + windows); + if probabilities.len() - reported >= REPORT_WINDOWS || probabilities.len() == count { + report(&probabilities[reported..]); + reported = probabilities.len(); + } } Ok(probabilities) @@ -194,7 +356,7 @@ fn copy_state_vec(values: &[f32], state: &mut [f32]) -> Result<(), Transcription #[cfg(test)] mod tests { - use super::{WINDOW_INPUT_SAMPLES, process_blocks}; + use super::{REPORT_WINDOWS, WINDOW_INPUT_SAMPLES, process_blocks}; use crate::constants::{VAD_CONTEXT_SAMPLES, VAD_WINDOW_SAMPLES}; use crate::preprocessing::TranscriptionControl; @@ -203,18 +365,32 @@ mod tests { } /// Every window the classifier sees, in order, with `block_windows` per call + /// + /// Also checks the reports: they add up to the probabilities, and every one but + /// the last holds at least `REPORT_WINDOWS` fn windows_seen(audio: &[f32], block_windows: usize) -> Vec> { let mut seen = Vec::new(); - let probabilities = process_blocks(audio, &control(), block_windows, |inputs, out| { - assert!(inputs.len() <= block_windows * WINDOW_INPUT_SAMPLES); - for input in inputs.as_chunks::().0 { - seen.push(input.to_vec()); - out.push(seen.len() as f32); - } - Ok(()) - }) + let mut reports = Vec::new(); + let probabilities = process_blocks( + audio, + &control(), + block_windows, + |block| reports.push(block.to_vec()), + |inputs, out| { + assert!(inputs.len() <= block_windows * WINDOW_INPUT_SAMPLES); + for input in inputs.as_chunks::().0 { + seen.push(input.to_vec()); + out.push(seen.len() as f32); + } + Ok(()) + }, + ) .unwrap(); assert_eq!(probabilities.len(), seen.len()); + assert_eq!(reports.concat(), probabilities); + if let Some((_, earlier)) = reports.split_last() { + assert!(earlier.iter().all(|report| report.len() >= REPORT_WINDOWS)); + } seen } @@ -255,10 +431,27 @@ mod tests { assert_eq!(windows_seen(&audio, 64), one_at_a_time); } + #[test] + fn reports_cover_every_window_in_order() { + let audio = vec![0.25f32; VAD_WINDOW_SAMPLES * (2 * REPORT_WINDOWS + 7)]; + + // one window per block reports every `REPORT_WINDOWS`, larger blocks after + // the block that crosses it + for block_windows in [1, 100, 3 * REPORT_WINDOWS] { + windows_seen(&audio, block_windows); + } + } + #[test] fn empty_audio_never_invokes_the_classifier() { - let probabilities = - process_blocks(&[], &control(), 4, |_, _| panic!("classifier must not run")).unwrap(); + let probabilities = process_blocks( + &[], + &control(), + 4, + |_| panic!("nothing to report"), + |_, _| panic!("classifier must not run"), + ) + .unwrap(); assert!(probabilities.is_empty()); } @@ -267,20 +460,26 @@ mod tests { let audio = vec![0.0f32; VAD_WINDOW_SAMPLES * 6]; let control = control(); let mut calls = 0; - let error = process_blocks(&audio, &control, 2, |inputs, out| { - calls += 1; - if calls == 1 { - control.cancel(); - } - out.extend( - inputs - .as_chunks::() - .0 - .iter() - .map(|_| 0.1), - ); - Ok(()) - }) + let error = process_blocks( + &audio, + &control, + 2, + |_| {}, + |inputs, out| { + calls += 1; + if calls == 1 { + control.cancel(); + } + out.extend( + inputs + .as_chunks::() + .0 + .iter() + .map(|_| 0.1), + ); + Ok(()) + }, + ) .expect_err("cancelled scan"); assert_eq!(calls, 1); diff --git a/src/models.rs b/src/models.rs index 3b09f14..e5132cd 100644 --- a/src/models.rs +++ b/src/models.rs @@ -12,12 +12,73 @@ use crate::vocab::Vocabulary; #[cfg(feature = "online")] pub use hub::ModelManager; +/// One of the Silero VAD models a bundle holds #[cfg(feature = "vad")] -const VAD_DIR: &str = "vad/silero-vad.mlmodelc"; -/// Silero v5 weights in a native bundle, as `dev-tools/nemo/export_native.py` -/// writes them next to the Parakeet directories -#[cfg(all(feature = "cuda", feature = "vad"))] -const NATIVE_VAD_PATH: &str = "vad/silero-vad-v5.safetensors"; +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum SileroVersion { + /// Silero VAD 5.1.2 + V5, + /// Silero VAD 6.2.3 + V6, +} + +#[cfg(feature = "vad")] +impl SileroVersion { + pub(crate) const ALL: [Self; 2] = [Self::V5, Self::V6]; + + /// Compiled Core ML model in a Core ML bundle; v5 keeps the unversioned name + /// published bundles and local layouts already use + pub(crate) fn coreml_dir(self) -> &'static str { + match self { + Self::V5 => "vad/silero-vad.mlmodelc", + Self::V6 => "vad/silero-vad-v6.mlmodelc", + } + } + + /// Weights in a native bundle, as `dev-tools/nemo/export_native.py` writes them + /// next to the Parakeet directories + #[cfg(feature = "cuda")] + pub(crate) fn native_path(self) -> &'static str { + match self { + Self::V5 => "vad/silero-vad-v5.safetensors", + Self::V6 => "vad/silero-vad-v6.safetensors", + } + } + + /// `model` metadata of the native weights + #[cfg(feature = "cuda")] + pub(crate) fn model_name(self) -> &'static str { + match self { + Self::V5 => "silero-vad-v5", + Self::V6 => "silero-vad-v6", + } + } +} + +/// Where each Silero VAD model is in a bundle, whether or not it is there +#[cfg(feature = "vad")] +#[derive(Debug, Clone)] +pub(crate) struct VadPaths { + v5: PathBuf, + v6: PathBuf, +} + +#[cfg(feature = "vad")] +impl VadPaths { + fn resolve(root: &Path, relative: impl Fn(SileroVersion) -> &'static str) -> Self { + Self { + v5: root.join(relative(SileroVersion::V5)), + v6: root.join(relative(SileroVersion::V6)), + } + } + + pub(crate) fn get(&self, version: SileroVersion) -> &Path { + match version { + SileroVersion::V5 => &self.v5, + SileroVersion::V6 => &self.v6, + } + } +} /// Longest single input for native bundles, 40 s at 16 kHz; the CUDA encoder has no /// fixed input width, and full attention over 40 s still fits easily in memory #[cfg(feature = "cuda")] @@ -57,13 +118,13 @@ impl RuntimeBundle { } } - /// Where the bundle's VAD model is, whether or not it is there + /// Where the bundle's Silero VAD models are, whether or not they are there #[cfg(feature = "vad")] - fn vad_path(&self) -> &Path { + pub(crate) fn vad_paths(&self) -> &VadPaths { match self { - Self::CoreMl(layout) => &layout.vad_dir, + Self::CoreMl(layout) => &layout.vad_paths, #[cfg(feature = "cuda")] - Self::Native(layout) => &layout.vad_path, + Self::Native(layout) => &layout.vad_paths, } } } @@ -203,7 +264,7 @@ pub(crate) struct NativeLayout { weights_path: PathBuf, vocab_path: PathBuf, #[cfg(feature = "vad")] - vad_path: PathBuf, + vad_paths: VadPaths, precision: Precision, } @@ -214,7 +275,7 @@ impl NativeLayout { weights_path: root.join(deployment.native_weights_path()), vocab_path: root.join(deployment.layout().vocab()), #[cfg(feature = "vad")] - vad_path: root.join(NATIVE_VAD_PATH), + vad_paths: VadPaths::resolve(root, SileroVersion::native_path), precision: Precision::default(), } } @@ -254,11 +315,6 @@ impl NativeLayout { own.exists().then_some(own) } - #[cfg(feature = "vad")] - pub(crate) fn vad_path(&self) -> &Path { - &self.vad_path - } - pub(crate) fn precision(&self) -> Precision { self.precision } @@ -272,7 +328,7 @@ pub(crate) struct CoreMlLayout { joint_decision_dir: PathBuf, vocab_path: PathBuf, #[cfg(feature = "vad")] - vad_dir: PathBuf, + vad_paths: VadPaths, } impl CoreMlLayout { @@ -284,7 +340,7 @@ impl CoreMlLayout { joint_decision_dir: root.join(layout.joint_decision()), vocab_path: root.join(layout.vocab()), #[cfg(feature = "vad")] - vad_dir: root.join(VAD_DIR), + vad_paths: VadPaths::resolve(root, SileroVersion::coreml_dir), } } @@ -330,11 +386,6 @@ impl CoreMlLayout { pub(crate) fn joint_decision_dir(&self) -> &Path { &self.joint_decision_dir } - - #[cfg(feature = "vad")] - pub(crate) fn vad_dir(&self) -> &Path { - &self.vad_dir - } } impl ModelBundle { @@ -364,8 +415,8 @@ impl ModelBundle { /// /// The directory holds `parakeet-v2/` or `parakeet-v3/` with `model.safetensors` /// and the vocabulary, as `dev-tools/nemo/export_native.py` writes them. With - /// `vad`, the Silero VAD weights are `vad/silero-vad-v5.safetensors` in the same - /// directory. This only resolves paths; [`Self::validate_base`] checks they + /// `vad`, the Silero VAD weights are `vad/silero-vad-v5.safetensors` and + /// `vad/silero-vad-v6.safetensors` in the same directory. This only resolves paths; [`Self::validate_base`] checks they /// exist, and loading checks the weights against the deployment /// /// The CUDA encoder takes inputs of any length, so a native bundle raises the @@ -386,14 +437,14 @@ impl ModelBundle { /// Native bundle from files resolved one at a time, such as snapshots of the /// separate Hugging Face repositories for Parakeet and Silero VAD /// - /// The root is the weights' directory. Without `vad_path`, the VAD path keeps - /// the [`Self::from_native_dir`] layout under that root, so a long-form run - /// reports it missing + /// The root is the weights' directory. Without `vad_paths`, the VAD paths keep + /// the [`Self::from_native_dir`] layout under that root, so a VAD run reports + /// them missing #[cfg(all(feature = "online", feature = "cuda"))] fn from_native_files( weights_path: PathBuf, vocab_path: PathBuf, - vad_path: Option, + #[cfg(feature = "vad")] vad_paths: Option, deployment: ParakeetDeployment, ) -> Self { let root = weights_path @@ -401,14 +452,13 @@ impl ModelBundle { .map(Path::to_path_buf) .unwrap_or_default(); #[cfg(feature = "vad")] - let vad_path = vad_path.unwrap_or_else(|| root.join(NATIVE_VAD_PATH)); - #[cfg(not(feature = "vad"))] - let _ = vad_path; + let vad_paths = + vad_paths.unwrap_or_else(|| VadPaths::resolve(&root, SileroVersion::native_path)); let runtime = RuntimeBundle::Native(NativeLayout { weights_path, vocab_path, #[cfg(feature = "vad")] - vad_path, + vad_paths, precision: Precision::default(), }); Self { @@ -452,14 +502,21 @@ impl ModelBundle { } } - /// Validate that the Parakeet and VAD model assets are present + /// Validate that the Parakeet assets and both Silero VAD models are present #[cfg(feature = "vad")] pub fn validate_long_form(&self) -> Result<(), TranscriptionError> { self.validate_base()?; - if !self.runtime.vad_path().exists() { - return Err(self.missing_vad_error()); + let paths = self.runtime.vad_paths(); + let missing = SileroVersion::ALL + .into_iter() + .map(|version| paths.get(version)) + .find(|path| !path.exists()); + match missing { + Some(path) => Err(TranscriptionError::MissingModelAsset { + path: path.to_path_buf(), + }), + None => Ok(()), } - Ok(()) } pub(crate) fn runtime(&self) -> &RuntimeBundle { @@ -470,14 +527,6 @@ impl ModelBundle { Vocabulary::load(self.runtime.vocab_path(), &self.deployment) } - /// Error to return when a VAD run is requested but the bundle has no VAD model - #[cfg(feature = "vad")] - pub(crate) fn missing_vad_error(&self) -> TranscriptionError { - TranscriptionError::MissingModelAsset { - path: self.runtime.vad_path().to_path_buf(), - } - } - /// Return the root directory that contains the model bundle pub fn root(&self) -> &Path { &self.root diff --git a/src/models/hub.rs b/src/models/hub.rs index ff4ad87..1da01da 100644 --- a/src/models/hub.rs +++ b/src/models/hub.rs @@ -4,7 +4,9 @@ use std::path::{Path, PathBuf}; use super::ModelBundle; #[cfg(feature = "vad")] -use super::VAD_DIR; +use super::SileroVersion; +#[cfg(all(feature = "cuda", feature = "vad"))] +use super::VadPaths; use crate::deployment::ParakeetDeployment; #[cfg(feature = "cuda")] use crate::deployment::ParakeetVersion; @@ -68,9 +70,9 @@ impl ModelBundle { /// Download native CUDA weights and the native Silero VAD weights /// - /// The VAD weights come from a pinned snapshot of - /// `avencera/silero-vad-v5-safetensors`. Set `SCRIPTRS_MODELS_DIR` to force a - /// local native bundle + /// The VAD weights come from pinned snapshots of + /// `avencera/silero-vad-v5-safetensors` and `avencera/silero-vad-v6-safetensors`. + /// Set `SCRIPTRS_MODELS_DIR` to force a local native bundle #[cfg(all(feature = "cuda", feature = "vad"))] pub fn from_pretrained_native_long_form( deployment: ParakeetDeployment, @@ -84,7 +86,7 @@ impl ModelBundle { const HF_REPO: HuggingFaceRepository = HuggingFaceRepository("avencera/scriptrs-models"); const HF_REVISION: HuggingFaceRevision = - HuggingFaceRevision("63f6f9cbce43e5561c219229896f86f20c0eb660"); + HuggingFaceRevision("54f3f976b63bf5d5fe9927363d259cffa1c23a89"); // native CUDA weights live in one repository per model, named after the model, so // each is listed under its base model on Hugging Face and found by searching for it @@ -99,10 +101,15 @@ const NATIVE_V3_SOURCE: HuggingFaceModelSource = HuggingFaceModelSource { revision: HuggingFaceRevision("01ffcdb65d1e0087f4f12bbe87f5413f9b429626"), }; #[cfg(all(feature = "cuda", feature = "vad"))] -const NATIVE_VAD_SOURCE: HuggingFaceModelSource = HuggingFaceModelSource { +const NATIVE_VAD_V5_SOURCE: HuggingFaceModelSource = HuggingFaceModelSource { repository: HuggingFaceRepository("avencera/silero-vad-v5-safetensors"), revision: HuggingFaceRevision("bc58b9e061a5cb07bc3ec839df301647753dcc59"), }; +#[cfg(all(feature = "cuda", feature = "vad"))] +const NATIVE_VAD_V6_SOURCE: HuggingFaceModelSource = HuggingFaceModelSource { + repository: HuggingFaceRepository("avencera/silero-vad-v6-safetensors"), + revision: HuggingFaceRevision("10e0013ed989abfc4491003a03dab3a38839029a"), +}; /// Weight file name in each native model repository #[cfg(feature = "cuda")] const NATIVE_HUB_WEIGHTS: &str = "model.safetensors"; @@ -135,6 +142,14 @@ impl HuggingFaceModelSource { } } + #[cfg(all(feature = "cuda", feature = "vad"))] + fn native_vad(version: SileroVersion) -> Self { + match version { + SileroVersion::V5 => NATIVE_VAD_V5_SOURCE, + SileroVersion::V6 => NATIVE_VAD_V6_SOURCE, + } + } + fn pinned_repo(self, hub: &Hub) -> HubRepo { hub.model(self.repository.0, self.revision.0) } @@ -204,7 +219,9 @@ impl ModelManager { let files = repo_files(&deployment); #[cfg(feature = "vad")] if include_vad { - files.extend(mlmodelc_files(VAD_DIR)); + for version in SileroVersion::ALL { + files.extend(mlmodelc_files(version.coreml_dir())); + } } #[cfg(not(feature = "vad"))] let _ = include_vad; @@ -216,7 +233,8 @@ impl ModelManager { /// /// The weights come from the deployment's model repository, such as /// `avencera/parakeet-tdt-0.6b-v3-cuda`, and with `include_vad` the Silero VAD - /// weights from `avencera/silero-vad-v5-safetensors`, each at a pinned revision. + /// weights from `avencera/silero-vad-v5-safetensors` and + /// `avencera/silero-vad-v6-safetensors`, each at a pinned revision. /// The returned [`ModelBundle`] is a native bundle rooted at the Parakeet /// snapshot directory #[cfg(feature = "cuda")] @@ -230,24 +248,28 @@ impl ModelManager { let vocab_path = repo.get(native_hub_vocab(&deployment))?; #[cfg(feature = "vad")] - let vad_path = match include_vad { - true => Some( - NATIVE_VAD_SOURCE - .pinned_repo(&self.hub) - .get(NATIVE_HUB_WEIGHTS)?, - ), + let vad_paths = match include_vad { + true => { + let get = |version| { + HuggingFaceModelSource::native_vad(version) + .pinned_repo(&self.hub) + .get(NATIVE_HUB_WEIGHTS) + }; + Some(VadPaths { + v5: get(SileroVersion::V5)?, + v6: get(SileroVersion::V6)?, + }) + } false => None, }; #[cfg(not(feature = "vad"))] - let vad_path = { - let _ = include_vad; - None - }; + let _ = include_vad; Ok(ModelBundle::from_native_files( weights_path, vocab_path, - vad_path, + #[cfg(feature = "vad")] + vad_paths, deployment, )) } diff --git a/src/native/silero.rs b/src/native/silero.rs index 0ab3bb9..f4dcc35 100644 --- a/src/native/silero.rs +++ b/src/native/silero.rs @@ -1,4 +1,5 @@ -//! Silero VAD v5 (16 kHz branch) in plain Rust on the CPU +//! Silero VAD v5 and v6 (16 kHz branch) in plain Rust on the CPU; the two share +//! one architecture and differ only in their weights //! //! Everything before the LSTM sees one window and no recurrent state, so the STFT, //! the four convolutions and the LSTM input gates run as matrix multiplies over @@ -19,12 +20,12 @@ use ndarray::{ArrayView2, ArrayViewMut2}; use crate::constants::{VAD_CONTEXT_SAMPLES, VAD_STATE_SIZE, VAD_WINDOW_SAMPLES}; use crate::error::TranscriptionError; +use crate::models::SileroVersion; use crate::native::weights::WeightFile; /// Samples in one model input: the carried context plus one chunk pub(crate) const VAD_INPUT_SAMPLES: usize = VAD_CONTEXT_SAMPLES + VAD_WINDOW_SAMPLES; -const MODEL: &str = "silero-vad-v5"; const SAMPLE_RATE: u64 = 16_000; /// STFT as Silero runs it: a conv1d over a reflect-padded window with a DFT basis @@ -55,7 +56,7 @@ const TASKS_PER_WORKER: usize = 4; /// path, and a few workers already encode faster than it consumes const MAX_WORKERS: usize = 6; -/// Silero VAD v5 weights, shared by clones +/// One Silero VAD version's weights, shared by clones #[derive(Debug, Clone)] pub(crate) struct SileroModel(Arc); @@ -106,10 +107,11 @@ impl SileroState { } impl SileroModel { - /// Load `silero-vad-v5.safetensors` as `dev-tools/nemo/export_native.py` writes it - pub(crate) fn open(path: &Path) -> Result { + /// Load one version's weights, such as `silero-vad-v6.safetensors`, as + /// `dev-tools/nemo/export_native.py` writes them + pub(crate) fn open(path: &Path, version: SileroVersion) -> Result { let file = WeightFile::open(path)?; - file.expect_metadata("model", MODEL)?; + file.expect_metadata("model", version.model_name())?; check_config(&file)?; let basis = file.tensor("stft.forward_basis_buffer", &[2 * BINS, 1, FILTER])?; @@ -566,10 +568,11 @@ mod tests { #[cfg(target_arch = "x86_64")] use super::{GATES, lstm_step, lstm_step_avx}; use crate::cuda::test_support::native_root; + use crate::models::SileroVersion; use crate::test_support::NemoReference; - fn model() -> SileroModel { - SileroModel::open(&native_root().join("vad/silero-vad-v5.safetensors")) + fn model(version: SileroVersion) -> SileroModel { + SileroModel::open(&native_root().join(version.native_path()), version) .expect("exported Silero weights") } @@ -647,15 +650,22 @@ mod tests { assert!(baseline_state.h.iter().any(|h| *h != 0.0)); } - /// Window 0's STFT magnitude and encoder output match Silero's own modules + /// Window 0's STFT magnitude and encoder output match Silero's own modules, for + /// each version #[test] #[ignore = "reads Silero references from /shared/datasets/parakeet-ref"] fn nemo_parity_silero_encoder_stages() { - let reference = NemoReference::silero(); + SileroVersion::ALL + .into_iter() + .for_each(encoder_stages_match); + } + + fn encoder_stages_match(version: SileroVersion) { + let reference = NemoReference::silero(version); let window = reference.f32("window0.in"); let window = window.as_slice().expect("contiguous window"); assert_eq!(window.len(), VAD_INPUT_SAMPLES); - let model = model(); + let model = model(version); // the reference is `[1, BINS, FRAMES]`; ours is frames first let stft = reference.f32("window0.stft"); @@ -669,26 +679,31 @@ mod tests { let scale = stft.iter().copied().fold(0.0, f32::max); assert!( diff <= 1e-5 * scale.max(1.0), - "STFT max diff {diff} (peak {scale})" + "{version:?} STFT max diff {diff} (peak {scale})" ); let encoder = reference.f32("window0.encoder"); let features = model.0.encode(window); assert_eq!(features.len(), HIDDEN); let diff = max_abs_diff(features, encoder.iter().copied()); - assert!(diff <= 1e-4, "encoder max diff {diff}"); + assert!(diff <= 1e-4, "{version:?} encoder max diff {diff}"); } - /// Per-window probabilities over a whole file stay within 1e-4 of Silero's, and - /// the block size used for the batched encoder does not change them + /// For each version, per-window probabilities over a whole file stay within + /// 1e-5 of Silero's, and the block size used for the batched encoder does not + /// change them #[test] #[ignore = "reads Silero references from /shared/datasets/parakeet-ref"] fn nemo_parity_silero_probabilities() { - let reference = NemoReference::silero(); + SileroVersion::ALL.into_iter().for_each(probabilities_match); + } + + fn probabilities_match(version: SileroVersion) { + let reference = NemoReference::silero(version); let windows = reference.f32("windows"); let windows = windows.as_slice().expect("contiguous windows"); let expected = reference.f32("probs"); - let model = model(); + let model = model(version); let run = |block: usize| { let mut state = SileroState::new(); @@ -702,10 +717,14 @@ mod tests { assert_eq!(whole.len(), expected.len()); let diff = max_abs_diff(whole.iter().copied(), expected.iter().copied()); eprintln!( - "silero probability max abs diff {diff:e} over {} windows", + "silero {version:?} probability max abs diff {diff:e} over {} windows", whole.len() ); - assert!(diff <= 1e-5, "probability max diff {diff}"); - assert_eq!(run(7), whole, "block size changed the probabilities"); + assert!(diff <= 1e-5, "{version:?} probability max diff {diff}"); + assert_eq!( + run(7), + whole, + "{version:?}: block size changed the probabilities" + ); } } diff --git a/src/test_support.rs b/src/test_support.rs index 00c2a54..23a274d 100644 --- a/src/test_support.rs +++ b/src/test_support.rs @@ -53,10 +53,15 @@ impl NemoReference { Self::open_in(dir, set) } - /// Silero VAD v5 probabilities for one LibriSpeech file (`silero-v5/vad`) + /// One Silero VAD version's probabilities for one LibriSpeech file + /// (`silero-v5/vad` or `silero-v6/vad`) #[cfg(all(feature = "cuda", feature = "vad"))] - pub(crate) fn silero() -> Self { - Self::open_in(reference_root().join("silero-v5"), "vad") + pub(crate) fn silero(version: crate::models::SileroVersion) -> Self { + let dir = match version { + crate::models::SileroVersion::V5 => "silero-v5", + crate::models::SileroVersion::V6 => "silero-v6", + }; + Self::open_in(reference_root().join(dir), "vad") } /// The tensor dump of NeMo's streaming run of `model` (`nemotron-en` or