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
fp16 build of SAVA (voice activity + end of turn)
Browse filesFiles changed (9)
- .gitattributes+1
- fp16/LICENSEAdded+202
- fp16/NOTICEAdded+13
- fp16/config.jsonAdded+174
- fp16/device_chain.pyAdded+205
- fp16/pipeline.pyAdded+148
- fp16/pipeline_trt.pyAdded+81
- fp16/step.engineAdded+3
- fp16/trt_runner.pyAdded+98
32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textfp16/step.engine filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.12345678910111213Inworld SAVACopyright 2026 Inworld AI
The model weights were trained on Inworld first-party data, including datapurchased from vendors under private terms, and on these third-party datasets:
- pipecat smart-turn data v3.2, train split: CC BY 4.0, https://huggingface.co/datasets/pipecat-ai/smart-turn-data-v3.2-train- VoxConverse, dev split: CC BY 4.0, https://github.com/joonson/voxconverse- VocalSound: CC BY-SA 4.0, https://github.com/YuanGongND/vocalsound- Tatoeba (CC BY 2.0 FR, https://tatoeba.org), FineWeb-2 (ODC-BY 1.0, https://huggingface.co/datasets/HuggingFaceFW/fineweb-2) and C4 (ODC-BY 1.0, https://huggingface.co/datasets/allenai/c4), as text for synthetic speech123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174{
"sample_rate": 16000,
"frame_samples": 640,
"lookahead_frames": 3,
"turn_horizons_ms": [
0,
5,
10,
20
],
"state": [
[
"state.frontend",
[
1,
240
],
"float32"
],
[
"state.mixer.tail",
[
1,
1,
513
],
"float32"
],
[
"state.trunk.0.conv_tail",
[
1,
3,
1280
],
"float32"
],
[
"state.trunk.0.ssm",
[
1,
16,
64,
128
],
"float32"
],
[
"state.trunk.1.conv_tail",
[
1,
3,
1280
],
"float32"
],
[
"state.trunk.1.ssm",
[
1,
16,
64,
128
],
"float32"
],
[
"state.trunk.2.conv_tail",
[
1,
3,
1280
],
"float32"
],
[
"state.trunk.2.ssm",
[
1,
16,
64,
128
],
"float32"
],
[
"state.trunk.3.keys",
[
1,
512,
2,
64
],
"float32"
],
[
"state.trunk.3.values",
[
1,
512,
2,
64
],
"float32"
],
[
"state.trunk.3.offset",
[],
"int64"
],
[
"state.vad.keys",
[
1,
512,
2,
64
],
"float32"
],
[
"state.vad.values",
[
1,
512,
2,
64
],
"float32"
],
[
"state.vad.offset",
[],
"int64"
],
[
"state.turn.keys",
[
1,
512,
2,
64
],
"float32"
],
[
"state.turn.values",
[
1,
512,
2,
64
],
"float32"
],
[
"state.turn.offset",
[],
"int64"
],
[
"state.prev_speech",
[
1
],
"float32"
],
[
"state.frames",
[],
"int64"
]
]
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205"""TensorRT engines run on GPU buffers (Polygraphy's CUDA wrapper; no torch): a decoder's KV cache stays on the GPUbetween steps, and the activations between split engines (piecewise.py) never leave it.
from device_chain import Chain, Buffers step = Chain(folder, [{"engine": "gpt_step_0.engine"}, ...]) # or Chain.from_split(folder, "gpt_step") out = step({"token": np.array(...), "c_k0": cache_a["c_k0"], ...}, # numpy arrays are copied in, DeviceArrays used outputs={"n_k0": cache_b["n_k0"], ...}, # where these outputs go (else the chain's own) fetch=["logits"]) # -> {"logits": numpy array}
A tensor a call writes must not be one it reads: a cache is read from one set of buffers and written to another, andthe two sets swap after every step (Buffers.swap). Buffers are allocated at their largest shape once; a smaller shapereuses the allocation (DeviceArray.resize), so the steps allocate nothing."""from __future__ import annotations
import jsonfrom pathlib import Path
import numpy as np
def _cuda(): from polygraphy import cuda return cuda
def device_array(shape, dtype): """A DeviceArray of a numpy dtype (Polygraphy's DataType: numpy dtypes there are deprecated), which also keeps the numpy dtype (reading DeviceArray.dtype logs a deprecation warning on every call).""" from polygraphy.datatype import DataType a = _cuda().DeviceArray(shape=tuple(shape), dtype=DataType.from_dtype(np.dtype(dtype))) a.np_dtype = np.dtype(dtype) return a
def host_dtype(a) -> np.dtype: return a.np_dtype
class Engine: """One engine on device buffers. Its execution context holds device memory for the profile's largest shapes, or, with shared=True, none of its own: Chain gives all its engines one scratch buffer (they run one at a time on one stream), the size of the largest one's; with scratch="shapes" the scratch is sized for each call's input shapes instead (IExecutionContext.update_device_memory_size_for_shapes), for engines whose largest shapes need far more activation memory than the sizes they usually run at."""
def __init__(self, path, shared=False): import tensorrt as trt from trt_runner import lean_dlls lean_dlls() self.trt = trt runtime = trt.Runtime(trt.Logger(trt.Logger.WARNING)) runtime.engine_host_code_allowed = True # version-compatible engines carry their own lean runtime engine = runtime.deserialize_cuda_engine(Path(path).read_bytes()) if engine is None: raise RuntimeError(f"could not load {path} (TensorRT {trt.__version__}; the engine needs TensorRT 10.x " "and an RTX 30-series or newer GPU)") self.engine = engine if shared: self.context = engine.create_execution_context(trt.ExecutionContextAllocationStrategy.USER_MANAGED) self.scratch = engine.get_device_memory_size_for_profile_v2(0) else: self.context, self.scratch = engine.create_execution_context(), 0 names = [engine.get_tensor_name(i) for i in range(engine.num_io_tensors)] self.inputs = [n for n in names if engine.get_tensor_mode(n) == trt.TensorIOMode.INPUT] self.outputs = [n for n in names if engine.get_tensor_mode(n) == trt.TensorIOMode.OUTPUT] self.dtype = {n: np.dtype(trt.nptype(engine.get_tensor_dtype(n))) for n in names}
def enqueue(self, inputs: dict, outputs: dict, stream, scratch=None) -> None: """inputs / outputs: name -> DeviceArray. Each output is resized to its shape for these inputs. scratch: a function size -> DeviceArray of at least that many bytes, to size the scratch for these shapes.""" c = self.context for n in self.inputs: a = inputs[n] c.set_input_shape(n, tuple(a.shape)) c.set_tensor_address(n, a.ptr) if scratch is not None: need = c.update_device_memory_size_for_shapes() c.set_device_memory(scratch(need).ptr, need) for n in self.outputs: o = outputs[n] o.resize(tuple(c.get_tensor_shape(n))) c.set_tensor_address(n, o.ptr) if not c.execute_async_v3(stream.ptr): raise RuntimeError("TensorRT execution failed")
def use_memory(self, buf) -> None: self.context.set_device_memory(buf.ptr, self.scratch)
def close(self): self.context = self.engine = None
class Chain: """Engines run in order on one CUDA stream; each reads the call's inputs and earlier engines' outputs by name."""
def __init__(self, folder, plan: list[dict], shared_memory=True, scratch="profile"): self.folder, self.plan, self.engines = Path(folder), plan, [] self.by_shapes = scratch == "shapes" # shared scratch sized per call (Engine's docstring) self.pool = {} # the chain's own buffers, by tensor name self.stream = None self.shared = shared_memory # one scratch buffer for all the engines' activations
@classmethod def from_split(cls, folder, part: str, **kw): """<part>_split.json (the engines in order) if the part was split, else <part>.engine alone.""" f = Path(folder) / f"{part}_split.json" return cls(folder, json.loads(f.read_text()) if f.exists() else [{"engine": f"{part}.engine"}], **kw)
def load(self): if not self.engines: self.stream = _cuda().Stream() self.engines = [Engine(self.folder / p["engine"], self.shared or self.by_shapes) for p in self.plan] if self.shared and not self.by_shapes: scratch = self.pool["scratch"] = device_array((max(1, *(e.scratch for e in self.engines)),), np.uint8) for e in self.engines: e.use_memory(scratch) return self
def scratch(self, size: int): """The shared scratch, grown to at least size bytes (after the stream's queued work, which may use it).""" b = self.pool.get("scratch") if b is None or b.nbytes < size: if b is not None: self.stream.synchronize() b.free() b = self.pool["scratch"] = device_array((max(1, size),), np.uint8) return b
def buffer(self, name: str, dtype, shape=(1,)): """The chain's own buffer for a tensor (allocated on first use, at least one element).""" b = self.pool.get(name) if b is None: b = self.pool[name] = device_array(tuple(max(1, d) for d in shape) or (1,), dtype) return b
def __call__(self, feeds: dict, outputs: dict | None = None, fetch=()) -> dict: self.load() outputs = outputs or {} env, keep = {}, [] for n, v in feeds.items(): if isinstance(v, np.ndarray): # host -> a pooled device buffer of the engine's dtype want = next((e.dtype[n] for e in self.engines if n in e.dtype), v.dtype) h = np.ascontiguousarray(v, dtype=want) b = self.buffer("in:" + n, want, h.shape) b.resize(h.shape) b.copy_from(h, self.stream) keep.append(h) # alive until the stream has copied it env[n] = b else: env[n] = v for e in self.engines: outs = {n: outputs[n] if n in outputs else self.buffer(n, e.dtype[n]) for n in e.outputs} e.enqueue(env, outs, self.stream, self.scratch if self.by_shapes else None) env.update(outs) res = {} for n in fetch: a = env[n] res[n] = np.empty(tuple(a.shape), dtype=host_dtype(a)) a.copy_to(res[n], self.stream) self.stream.synchronize() return res
def close(self): for e in self.engines: e.close() for b in self.pool.values(): b.free() self.engines, self.pool = [], {}
class Buffers: """Two sets of device buffers for a decoder's caches, each allocated at the largest shape: step k reads set A and writes set B, then swap() exchanges them."""
def __init__(self, names_in: list[str], names_out: list[str], dtype, max_shape): self.names_in, self.names_out = names_in, names_out self.a = [device_array(max_shape, dtype) for _ in names_in] self.b = [device_array(max_shape, dtype) for _ in names_in]
def reads(self) -> dict: return dict(zip(self.names_in, self.a))
def writes(self) -> dict: return dict(zip(self.names_out, self.b))
def swap(self): self.a, self.b = self.b, self.a
def reset(self, shape): """Set A as an empty cache of this shape (e.g. [1, 0, 256] before a prefill): no copy, no allocation.""" for buf in self.a: buf.resize(tuple(shape))
def load(self, arrays, stream=None): """Fill set A from host arrays (the prompt's cache).""" for buf, x in zip(self.a, arrays): x = np.ascontiguousarray(x, dtype=host_dtype(buf)) buf.resize(x.shape) buf.copy_from(x, stream)
def free(self): for b in self.a + self.b: b.free() self.a = self.b = []123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148"""Inworld SAVA with ONNX Runtime: streaming voice activity and end-of-turn detection (16 kHz mono in, twoprobabilities every 40 ms out) as one graph, step.onnx (one 640-sample frame and the stream state in, the frame'slogits 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 lastreal frames get their verdicts. The end-of-turn probability is on time (horizon 0; `turns` holds all horizons)."""
from __future__ import annotations
import dataclassesimport jsonfrom 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.dataclassclass 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}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081"""SAVA (Inworld: streaming voice activity and end-of-turn detection) with a TensorRT engine: the same pipeline aspipeline.py (the package's streaming Session: 40 ms frames, the lookahead, the turn heads), with- step.engine: one 640-sample frame (16 kHz) and the stream state (mel front-end tail, the trunk's conv tails and SSM states, the attention caches) -> lookahead / speech / turn logits and the next state. All shapes are fixed.Built from the fp16 ONNX build, whose weights are stored in fp16 and read as fp32: the engine's math is fp32. Thestream state stays on the GPU (two sets of buffers per stream, read from one and written to the other each frame):only the frame goes in and the three logits come out. Needs numpy, tensorrt-cu12 / tensorrt-lean-cu12 10.x andpolygraphy; soundfile to read files.
python fp16/pipeline_trt.py speech_16k.wav"""
from __future__ import annotations
import jsonimport sysfrom pathlib import Path
import numpy as np
HERE = Path(__file__).resolve().parentsys.path.insert(0, str(HERE))from device_chain import Chain, device_array # noqa: E402from pipeline import _DT, Sava, Session, run # noqa: E402
HEADS = ["lookahead", "speech", "turn"]
class _State: """One stream's state on the GPU: set a is read by the next step, set b written by it."""
def __init__(self, spec, stream): self.names = [n for n, _, _ in spec] self.a, self.b = {}, {} for n, shape, dt in spec: for side in (self.a, self.b): buf = device_array(tuple(shape) or (1,), dt) buf.resize(tuple(shape)) side[n] = buf z = np.zeros(shape, dt) self.a[n].copy_from(z, stream)
def swap(self): self.a, self.b = self.b, self.a
def free(self): for buf in list(self.a.values()) + list(self.b.values()): buf.free() self.a = self.b = {}
class SavaTrt(Sava): def __init__(self, folder=HERE): folder = Path(folder) self.cfg = json.loads((folder / "config.json").read_text()) self.frame = self.cfg["frame_samples"] self.lag = self.cfg["lookahead_frames"] self.chain = Chain(folder, [{"engine": "step.engine"}]).load() e = self.chain.engines[0] want = {n: tuple(e.engine.get_tensor_shape(n)) for n in e.inputs} # config.json lists the scalar offsets as [1]; the engine takes [] self.spec = [(n, want[n], _DT[t]) for n, _, t in self.cfg["state"]] self.next = {n: "next." + n[len("state."):] for n, _, _ in self.spec}
def init_state(self): st = _State(self.spec, self.chain.stream) self.chain.stream.synchronize() return st
def step(self, frame, state): out = self.chain({"pcm": np.ascontiguousarray(frame.reshape(1, -1), np.float32), **state.a}, outputs={self.next[n]: state.b[n] for n in state.names}, fetch=HEADS) state.swap() return out["lookahead"].reshape(-1)[0], out["speech"].reshape(-1)[0], out["turn"].reshape(-1), state
if __name__ == "__main__": import soundfile as sf x, sr = sf.read(sys.argv[1], dtype="float32", always_2d=True) assert sr == 16000, "16 kHz audio" print(json.dumps(run(SavaTrt(), x.mean(1)))[:2000])123version https://git-lfs.github.com/spec/v1oid sha256:70f78d526207d2649447cec5596e43e29212e7ec861fa8033386745fb9a2d6e1size 1512682841234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798"""A minimal TensorRT engine runner: numpy in, numpy out (tensorrt-cu12 10.x and polygraphy; no torch).
from trt_runner import Engine e = Engine("model.engine") out = e({"input": x}) # dict of output name -> numpy array"""from __future__ import annotations
from pathlib import Path
import numpy as np
def lean_dlls(): """Version-compatible engines are built against and run on TensorRT's lean runtime (pip tensorrt-lean-cu12): put its DLL folder on the search path (Windows).""" import importlib.util import os spec = importlib.util.find_spec("tensorrt_lean_libs") if spec and spec.submodule_search_locations: d = list(spec.submodule_search_locations)[0] os.environ["PATH"] = d + os.pathsep + os.environ.get("PATH", "") if hasattr(os, "add_dll_directory"): os.add_dll_directory(d)
class Engine: """allocation: "static" (memory for the profiles' largest shapes, reserved once) or "runtime" (sized to each call's shapes: for pipelines of many engines with wide profiles, which would otherwise reserve every engine's maximum)."""
def __init__(self, path, allocation="static"): lean_dlls() import tensorrt as trt from polygraphy.backend.trt import TrtRunner self.trt = trt logger = trt.Logger(trt.Logger.WARNING) runtime = trt.Runtime(logger) runtime.engine_host_code_allowed = True # version-compatible engines carry their own lean runtime engine = runtime.deserialize_cuda_engine(Path(path).read_bytes()) if engine is None: raise RuntimeError(f"could not load {path} (TensorRT {trt.__version__}; the engine needs TensorRT 10.x " "and an RTX 30-series or newer GPU)") self.engine = engine self.runner = TrtRunner(engine, allocation_strategy=allocation) self.runner.activate() self.inputs = [engine.get_tensor_name(i) for i in range(engine.num_io_tensors) if engine.get_tensor_mode(engine.get_tensor_name(i)) == trt.TensorIOMode.INPUT]
def __call__(self, feed: dict) -> dict: feed = {k: np.require(v, requirements="C") for k, v in feed.items() if k in self.inputs} # 0-d stays 0-d out = self.runner.infer(feed, check_inputs=True) return {k: np.array(v) for k, v in out.items()}
def close(self): """Release the engine's device memory and weights now (deactivating the runner alone keeps the weights on the GPU until the engine object is collected).""" runner = getattr(self, "runner", None) if runner is not None and runner.is_active: runner.deactivate() self.runner = self.engine = None
def __del__(self): try: self.close() except Exception: pass
class OrtLike: """An engine behind onnxruntime's InferenceSession calls (run / get_inputs / get_outputs / get_providers), so a pipeline.py written for ONNX Runtime runs its graphs on TensorRT unchanged. Outputs come back in the order the ONNX graph listed them (pass `outputs`), else in the engine's order."""
def __init__(self, path, outputs=None, allocation="static"): self.e = Engine(path, allocation) eng = self.e.engine names = [eng.get_tensor_name(i) for i in range(eng.num_io_tensors)] self.outs = list(outputs) if outputs else [n for n in names if n not in self.e.inputs]
def get_inputs(self): """name, type ("tensor(float16)" etc., as onnxruntime spells it) and shape (-1 for dynamic dimensions).""" from types import SimpleNamespace eng, trt = self.e.engine, self.e.trt names = {trt.float16: "float16", trt.float32: "float", trt.int64: "int64", trt.int32: "int32", trt.bool: "bool", trt.int8: "int8", trt.bfloat16: "bfloat16"} return [SimpleNamespace(name=n, type=f"tensor({names.get(eng.get_tensor_dtype(n), 'float')})", shape=list(eng.get_tensor_shape(n))) for n in self.e.inputs]
def get_outputs(self): from types import SimpleNamespace return [SimpleNamespace(name=n) for n in self.outs]
def get_providers(self): return ["TensorRT"]
def run(self, names, feed, run_options=None): out = self.e(feed) return [out[n] for n in (names or self.outs)].gitattributes+1
fp16/LICENSEAdded+202
fp16/NOTICEAdded+13
fp16/config.jsonAdded+174
fp16/device_chain.pyAdded+205
fp16/pipeline.pyAdded+148
fp16/pipeline_trt.pyAdded+81
fp16/step.engineAdded+3
fp16/trt_runner.pyAdded+98