Voice Activity Detection
TensorRT
moonbox
inworld
sava
vad
end-of-turn
turn-detection
streaming
realtime
Run this model with HF Jobs
Run moonbox-dev/sava-TensorRT on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/moonbox-dev/sava-TensorRT. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/moonbox-dev/sava-TensorRT on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use moonbox-dev/sava-TensorRT with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- TensorRT
How to use moonbox-dev/sava-TensorRT with TensorRT:
# No code snippets available yet for this library. # To use this model, check the repository files and the library's documentation. # Want to help? PRs adding snippets are welcome at: # https://github.com/huggingface/huggingface.js
- Notebooks
- Google Colab
- Kaggle
File size: 6,310 Bytes
d45acc0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 | """Inworld SAVA with ONNX Runtime: streaming voice activity and end-of-turn detection (16 kHz mono in, two
probabilities every 40 ms out) as one graph, step.onnx (one 640-sample frame and the stream state in, the frame's
logits and the next state out), and this file: a numpy port of the sava package's Session (push / flush) and run.
Needs numpy and onnxruntime; soundfile and soxr for files at other rates.
python fp32/pipeline.py recording.wav # per-frame speech and end-of-turn probabilities
import pipeline
model = pipeline.Sava("fp32")
session = pipeline.Session(model)
for piece in pieces_of_16k_audio: # any length
frames = session.push(piece) # frames.speech, frames.turn for every whole 40 ms frame
frames = session.flush()
As in the original, the speech probability emitted at frame t judges frame t - lookahead_frames (3 frames, 120 ms):
the first three values of a stream are the no-speech floor, and flush() steps three frames of silence so the last
real frames get their verdicts. The end-of-turn probability is on time (horizon 0; `turns` holds all horizons).
"""
from __future__ import annotations
import dataclasses
import json
from pathlib import Path
import numpy as np
_DT = {"float32": np.float32, "int64": np.int64, "float16": np.float16}
def _sigmoid(x):
return 1.0 / (1.0 + np.exp(-x.astype(np.float64)))
@dataclasses.dataclass
class Frames:
first: int # index of the first stepped frame in the stream
speech: np.ndarray # [n] P(speech) as emitted: value i judges frame first + i - lag
turn: np.ndarray # [n] P(the turn has ended by frame first + i)
turns: np.ndarray # [n, K] every horizon
def __len__(self):
return self.speech.size
class Sava:
def __init__(self, folder, provider="cpu", threads=1):
import onnxruntime as ort
folder = Path(folder)
self.cfg = json.loads((folder / "config.json").read_text())
self.frame = self.cfg["frame_samples"]
self.lag = self.cfg["lookahead_frames"]
so = ort.SessionOptions()
so.intra_op_num_threads = threads
prov = ["CPUExecutionProvider"] if provider == "cpu" else ["CUDAExecutionProvider", "CPUExecutionProvider"]
self.s = ort.InferenceSession(str(folder / "step.onnx"), so, providers=prov)
self.state_names = [n for n, _, _ in self.cfg["state"]]
self.out_names = [o.name for o in self.s.get_outputs()]
def init_state(self) -> dict:
"""The stream state as ONNX Runtime values: each step's outputs feed the next step without numpy copies of
the attention caches."""
import onnxruntime as ort
return {n: ort.OrtValue.ortvalue_from_numpy(np.zeros(shape, _DT[t])) for n, shape, t in self.cfg["state"]}
def step(self, frame: np.ndarray, state: dict):
"""One 640-sample frame -> (lookahead logit, on-time speech logit, turn logits [K], next state)."""
import onnxruntime as ort
feeds = {"pcm": ort.OrtValue.ortvalue_from_numpy(np.ascontiguousarray(frame.reshape(1, -1), np.float32)),
**state}
out = self.s.run_with_ort_values(self.out_names, feeds)
nxt = dict(zip(self.state_names, out[3:]))
return (out[0].numpy().reshape(-1)[0], out[1].numpy().reshape(-1)[0], out[2].numpy().reshape(-1), nxt)
class Session:
"""A stream through one model, as sava.Session: samples in pieces of any size."""
def __init__(self, model: Sava):
self.model = model
self.lag = model.lag
self._state = model.init_state()
self._pending = np.zeros(0, np.float32)
self._frames = 0
self._closed = False
@property
def frames(self):
return self._frames
def push(self, samples) -> Frames:
if self._closed:
raise RuntimeError("The session is flushed; start a new one.")
samples = np.asarray(samples, np.float32).reshape(-1)
self._pending = np.concatenate([self._pending, samples])
f = self.model.frame
whole = self._pending.size - self._pending.size % f
chunk, self._pending = self._pending[:whole], self._pending[whole:]
return self._step(chunk)
def flush(self) -> Frames:
if self._closed:
raise RuntimeError("The session is already flushed.")
f = self.model.frame
tail = (-self._pending.size) % f if self._pending.size else 0
chunk = np.concatenate([self._pending, np.zeros(tail + self.lag * f, np.float32)])
self._pending = np.zeros(0, np.float32)
self._closed = True
return self._step(chunk)
def _step(self, chunk: np.ndarray) -> Frames:
first, f = self._frames, self.model.frame
speech, turns = [], []
for i in range(chunk.size // f):
la, _, turn, self._state = self.model.step(chunk[i * f:(i + 1) * f], self._state)
speech.append(_sigmoid(la))
turns.append(_sigmoid(turn))
self._frames += len(speech)
k = len(self.model.cfg["turn_horizons_ms"])
turns = np.array(turns, np.float32).reshape(-1, k)
return Frames(first, np.array(speech, np.float32), turns[:, 0].copy(), turns)
def run(model: Sava, audio: np.ndarray) -> dict:
"""Whole-recording curves, frame t covering samples [640 t, 640 (t + 1)): speech (the lookahead verdict on t),
turn (horizon 0) and turns [T, K], as sava.run."""
s = Session(model)
a, b = s.push(audio), s.flush()
speech = np.concatenate([a.speech, b.speech])[model.lag:]
turns = np.concatenate([a.turns, b.turns])
n = speech.size
return {"speech": speech, "turn": turns[:n, 0], "turns": turns[:n], "flush_turns": turns[n:]}
if __name__ == "__main__":
import argparse
import soundfile as sf
ap = argparse.ArgumentParser()
ap.add_argument("audio")
a = ap.parse_args()
x, sr = sf.read(a.audio, dtype="float32", always_2d=True)
x = x.mean(1)
if sr != 16000:
import soxr
x = soxr.resample(x, sr, 16000)
c = run(Sava(Path(__file__).resolve().parent), x)
for t in range(c["speech"].size):
print(f"{t * 0.04:7.2f} s speech {c['speech'][t]:.3f} turn {c['turn'][t]:.3f}")
|