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.
sava-TensorRT / fp16 /pipeline.py
jennyxue's picture
fp16 build of SAVA (voice activity + end of turn)
d45acc0 verified
Raw History Blame Contribute Delete
6.31 kB
"""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}")