sava-onnx 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
sava_onnx-1.0.0/NOTICE ADDED
@@ -0,0 +1,29 @@
1
+ Inworld SAVA
2
+ Copyright 2026 Inworld AI
3
+
4
+ The model weights were trained on Inworld first-party data, including data
5
+ purchased from vendors under private terms, and on these third-party datasets:
6
+
7
+ - pipecat smart-turn data v3.2, train split: CC BY 4.0,
8
+ https://huggingface.co/datasets/pipecat-ai/smart-turn-data-v3.2-train
9
+ - VoxConverse, dev split: CC BY 4.0, https://github.com/joonson/voxconverse
10
+ - VocalSound: CC BY-SA 4.0, https://github.com/YuanGongND/vocalsound
11
+ - Tatoeba (CC BY 2.0 FR, https://tatoeba.org), FineWeb-2 (ODC-BY 1.0,
12
+ https://huggingface.co/datasets/HuggingFaceFW/fineweb-2) and C4 (ODC-BY 1.0,
13
+ https://huggingface.co/datasets/allenai/c4), as text for synthetic speech
14
+
15
+ ---
16
+
17
+ sava-onnx
18
+ ONNX conversions of Inworld SAVA, by github.com/Robinbinu (huggingface.co/Binu30).
19
+ Unofficial: not made, reviewed or endorsed by Inworld AI.
20
+
21
+ Changes from the original work (Apache License 2.0, section 4(b)):
22
+ - The SAVA weights (inworld/sava, sava.safetensors) are exported to ONNX as
23
+ offline and streaming graphs, unchanged except for numeric format: fp32, fp16
24
+ weight storage, and dynamic int8 quantization of some matrix multiplications.
25
+ - For export only, the mel frontend's strided unfold is computed as an
26
+ equivalent convolution, and sliding-window attention runs as one masked pass
27
+ instead of 512-frame chunks. Outputs match the original within 5e-6 (fp32).
28
+ - sava_onnx/__init__.py ports inworld/sava/segmenter.py and the Session/run API
29
+ to numpy and ONNX Runtime.
@@ -0,0 +1,158 @@
1
+ Metadata-Version: 2.4
2
+ Name: sava-onnx
3
+ Version: 1.0.0
4
+ Summary: Inworld SAVA voice activity + end-of-turn detection on ONNX Runtime: no PyTorch, CPU-friendly, streaming.
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Homepage, https://github.com/Robinbinu/sava-onnx
7
+ Project-URL: Models, https://huggingface.co/Binu30/sava-onnx
8
+ Project-URL: Original model, https://huggingface.co/inworld/sava
9
+ Keywords: vad,voice-activity-detection,turn-detection,end-of-turn,onnx,onnxruntime,speech,streaming,realtime,voice-agent,silero-alternative,sava
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Topic :: Multimedia :: Sound/Audio :: Speech
12
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
13
+ Requires-Python: >=3.9
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ License-File: NOTICE
17
+ Requires-Dist: numpy>=1.22
18
+ Requires-Dist: onnxruntime>=1.17
19
+ Provides-Extra: hub
20
+ Requires-Dist: huggingface_hub>=0.23; extra == "hub"
21
+ Dynamic: license-file
22
+
23
+ # sava-onnx
24
+
25
+ **Inworld SAVA voice activity detection and end-of-turn detection, as ONNX.** One small model answers both "is someone speaking?" and "have they finished their turn?" every 40 ms, on CPU, with no PyTorch.
26
+
27
+ [![Hugging Face](https://img.shields.io/badge/%F0%9F%A4%97-Binu30%2Fsava--onnx-yellow)](https://huggingface.co/Binu30/sava-onnx)
28
+ [![PyPI](https://img.shields.io/pypi/v/sava-onnx)](https://pypi.org/project/sava-onnx/)
29
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue)](https://github.com/Robinbinu/sava-onnx/blob/main/LICENSE)
30
+ [![Original model](https://img.shields.io/badge/original-inworld%2Fsava-black)](https://huggingface.co/inworld/sava)
31
+
32
+ [SAVA](https://huggingface.co/inworld/sava) (semantic acoustic voice activity) is Inworld AI's open model that combines streaming VAD with end-of-turn prediction. Inworld reports it ahead of Silero VAD on speech detection and on par with pipecat smart-turn on turn detection ([their benchmarks](https://github.com/inworld-ai/sava/blob/main/bench/README.md)). The official package runs on PyTorch. This repo exports the same weights to ONNX, so SAVA runs wherever ONNX Runtime does: Python, Node.js, the browser (onnxruntime-web), C/C++, C#, Java, Rust, Go, Android and iOS.
33
+
34
+ > Unofficial community conversion. Not made, reviewed or endorsed by Inworld AI. Weights, behaviour and credit are theirs; see [NOTICE](https://github.com/Robinbinu/sava-onnx/blob/main/NOTICE).
35
+
36
+ ## Models
37
+
38
+ Six graphs: **offline** (a whole recording in one call) or **streaming** (one 40 ms frame per call, state carried by you), each in three precisions. Download them from [Hugging Face](https://huggingface.co/Binu30/sava-onnx) or the [GitHub release](https://github.com/Robinbinu/sava-onnx/releases).
39
+
40
+ | File | Use | Size | Matches PyTorch |
41
+ |---|---|---|---|
42
+ | `sava.onnx` | offline, fp32 | 103 MB | within 5e-6 |
43
+ | `sava_fp16.onnx` | offline, fp16 weights | 52 MB | within 5e-6 |
44
+ | `sava_int8.onnx` | offline, int8 | **33 MB** | 99.8% of speech verdicts |
45
+ | `sava_streaming.onnx` | streaming, fp32 | 103 MB | within 5e-6 |
46
+ | `sava_streaming_fp16.onnx` | streaming, fp16 weights | 52 MB | within 5e-6 |
47
+ | `sava_streaming_int8.onnx` | streaming, int8 | **32 MB** | 99.8% of speech verdicts |
48
+
49
+ **Which one?** For a realtime voice agent, or audio arriving in pieces, use `sava_streaming_int8.onnx`. For files and batch jobs, use `sava_int8.onnx`. Choose fp16 for exactly the reference model at half the download (SAVA's checkpoint is bf16, so fp16 storage loses nothing measurable), or fp32 for a runtime without fp16 casts. Full numbers are in [PARITY.md](https://github.com/Robinbinu/sava-onnx/blob/main/PARITY.md).
50
+
51
+ Speed on one CPU thread (Apple M-series, onnxruntime 1.32): offline is about 16 ms per second of audio; streaming int8 is about 1.6 ms per 40 ms frame in Python and 2.8 ms in Node.js. Budget more on small cloud vCPUs.
52
+
53
+ ## Quick start (Python)
54
+
55
+ ```bash
56
+ pip install "sava-onnx[hub]"
57
+ ```
58
+
59
+ ```python
60
+ import sava_onnx as sava
61
+
62
+ audio = sava.load_wav("speech.wav") # float32, 16 kHz mono
63
+ model = sava.Sava.from_pretrained(variant="int8")
64
+ curves = model.run(audio) # one value per 40 ms frame
65
+
66
+ print(curves.speech) # P(speech) per frame
67
+ print(curves.turn) # P(turn has ended) per frame
68
+
69
+ for turn in sava.segment(curves, sava.Policy()):
70
+ if turn.kept:
71
+ print(f"{turn.start_seconds:.2f}s - {turn.end_seconds:.2f}s ({turn.reason})")
72
+ ```
73
+
74
+ Streaming, in pieces of any size:
75
+
76
+ ```python
77
+ stream = sava.Session.from_pretrained(variant="int8")
78
+ turns = sava.TurnSegmenter(sava.Policy())
79
+ for piece in audio_chunks(): # float32 16 kHz mono numpy arrays
80
+ frames = stream.push(piece)
81
+ for turn in turns.feed(frames):
82
+ print("end of turn", turn.end_seconds)
83
+ frames = stream.flush() # end of stream: last verdicts
84
+ ```
85
+
86
+ `sava_onnx` needs only `numpy` and `onnxruntime`. Its `run`, `Session`, `Policy` and `segment` mirror the official `inworld-sava` API, and its turns match the official segmenter exactly with fp32 and fp16 (int8: within one frame), tested in [tests/test_runtime.py](https://github.com/Robinbinu/sava-onnx/blob/main/tests/test_runtime.py). A live microphone demo is in [examples/microphone.py](https://github.com/Robinbinu/sava-onnx/blob/main/examples/microphone.py).
87
+
88
+ ## Quick start (Node.js / browser)
89
+
90
+ ```bash
91
+ cd examples/js && npm install
92
+ node sava.mjs sava_streaming_int8.onnx speech.wav
93
+ ```
94
+
95
+ [examples/js/sava.mjs](https://github.com/Robinbinu/sava-onnx/blob/main/examples/js/sava.mjs) is a dependency-free streaming loop on `onnxruntime-node`. The same calls run in the browser with `onnxruntime-web`.
96
+
97
+ ## Using the graphs directly
98
+
99
+ All audio is **16 kHz mono float32 in [-1, 1]**. One frame is 640 samples (40 ms). Speech verdicts use 3 frames (120 ms) of lookahead.
100
+
101
+ ### Offline (`sava*.onnx`)
102
+
103
+ | | Name | Shape | Meaning |
104
+ |---|---|---|---|
105
+ | in | `pcm` | `[1, samples]` | any length; the graph pads the last frame and the lookahead |
106
+ | out | `speech` | `[T]` | P(speech) for frame `t` (lookahead verdict) |
107
+ | out | `speech_on_time` | `[T]` | P(speech) for frame `t` without lookahead |
108
+ | out | `turn` | `[T, 4]` | P(the turn has ended) at frame `t`, horizons 0, 5, 10, 20 frames |
109
+ | out | `turn_flush` | `[3, 4]` | `turn` for the 3 lookahead steps after the end (the segmenter reads them) |
110
+
111
+ `T = ceil(samples / 640)`, and row `t` of every output is about samples `[640t, 640(t+1))`. Attention memory grows with the square of the clip length, so for recordings longer than a few minutes, use the streaming graph.
112
+
113
+ ### Streaming (`sava_streaming*.onnx`)
114
+
115
+ Call once per 40 ms frame. Feed `pcm [1, 640]` plus every state tensor, and pass each `next_<name>` output back as `<name>` on the next call. Start with every state tensor at zero. To end a stream, feed 3 frames of silence to get the last verdicts.
116
+
117
+ | Output | Shape | Meaning |
118
+ |---|---|---|
119
+ | `speech` | `[1]` | P(speech) for the frame fed **3 calls ago** |
120
+ | `turn` | `[1, 4]` | P(the turn has ended) at this frame, horizons 0, 5, 10, 20 frames |
121
+ | `next_*` | as below | the state for the next call |
122
+
123
+ | State | Shape | Type |
124
+ |---|---|---|
125
+ | `frontend` | `[1, 240]` | float32 |
126
+ | `mixer_tail` | `[1, 1, 513]` | float32 |
127
+ | `trunk{0,1,2}_conv` | `[1, 3, 1280]` | float32 |
128
+ | `trunk{0,1,2}_ssm` | `[1, 16, 64, 128]` | float32 |
129
+ | `trunk3_keys`, `trunk3_values`, `vad_keys`, `vad_values`, `turn_keys`, `turn_values` | `[1, 512, 2, 64]` | float32 |
130
+ | `trunk3_offset`, `vad_offset`, `turn_offset`, `frames` | `[]` | int64 |
131
+ | `prev_speech` | `[1]` | float32 |
132
+
133
+ The state is fixed-size (three Mamba-2 layers and 512-frame sliding-window attention, about 3.2 MB), so a stream can run indefinitely. Run one state set per audio stream.
134
+
135
+ ## How the export works
136
+
137
+ `export/export.py` rebuilds every file from the official checkpoint:
138
+
139
+ ```bash
140
+ pip install -r export/requirements.txt
141
+ python export/export.py --out models
142
+ python tests/parity.py --models models # writes PARITY.md
143
+ python -m unittest tests/test_runtime.py
144
+ ```
145
+
146
+ Two numerically identical rewrites make SAVA traceable, both in the export script only:
147
+ - **Mel frontend.** Its strided unfold and matmul is written as a 1-D convolution with the same DFT kernels; ONNX can't export an unfold over a dynamic length.
148
+ - **Sliding-window attention.** It runs as one masked pass instead of a Python loop over 512-frame chunks. Tracing froze that loop at the example's length and cut long clips off at 20.48 s.
149
+
150
+ **int8** is dynamic per-channel quantization of the attention, feed-forward and head matmuls. The mel frontend, the frame mixer and the Mamba projections stay out of it: quantizing everything cost up to 1.5% of frame verdicts, while leaving those three out cost 0.2%. The weights left out are stored as fp16. **fp16** stores every weight matmul in fp16 and computes in fp32. The usual onnxruntime fp16 converter broke this graph even with every node excluded, so the export does the conversion itself (`export/owners.py`).
151
+
152
+ Parity is measured on synthetic audio (macOS text-to-speech voices, noise, hum, silence, a 122 s clip past the attention window), so anyone can reproduce it.
153
+
154
+ ## License and credit
155
+
156
+ Apache License 2.0, the same as SAVA. The model, its weights and its design are by [Inworld AI](https://inworld.ai): see the [original model](https://huggingface.co/inworld/sava), the [code](https://github.com/inworld-ai/sava) and the [announcement](https://inworld.ai/blog/introducing-sava). Inworld's NOTICE, including the third-party datasets the weights were trained on, is carried unchanged in [NOTICE](https://github.com/Robinbinu/sava-onnx/blob/main/NOTICE), followed by what this repo changed.
157
+
158
+ If you use SAVA in research, cite Inworld's work; see the [original repository](https://github.com/inworld-ai/sava).
@@ -0,0 +1,136 @@
1
+ # sava-onnx
2
+
3
+ **Inworld SAVA voice activity detection and end-of-turn detection, as ONNX.** One small model answers both "is someone speaking?" and "have they finished their turn?" every 40 ms, on CPU, with no PyTorch.
4
+
5
+ [![Hugging Face](https://img.shields.io/badge/%F0%9F%A4%97-Binu30%2Fsava--onnx-yellow)](https://huggingface.co/Binu30/sava-onnx)
6
+ [![PyPI](https://img.shields.io/pypi/v/sava-onnx)](https://pypi.org/project/sava-onnx/)
7
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue)](https://github.com/Robinbinu/sava-onnx/blob/main/LICENSE)
8
+ [![Original model](https://img.shields.io/badge/original-inworld%2Fsava-black)](https://huggingface.co/inworld/sava)
9
+
10
+ [SAVA](https://huggingface.co/inworld/sava) (semantic acoustic voice activity) is Inworld AI's open model that combines streaming VAD with end-of-turn prediction. Inworld reports it ahead of Silero VAD on speech detection and on par with pipecat smart-turn on turn detection ([their benchmarks](https://github.com/inworld-ai/sava/blob/main/bench/README.md)). The official package runs on PyTorch. This repo exports the same weights to ONNX, so SAVA runs wherever ONNX Runtime does: Python, Node.js, the browser (onnxruntime-web), C/C++, C#, Java, Rust, Go, Android and iOS.
11
+
12
+ > Unofficial community conversion. Not made, reviewed or endorsed by Inworld AI. Weights, behaviour and credit are theirs; see [NOTICE](https://github.com/Robinbinu/sava-onnx/blob/main/NOTICE).
13
+
14
+ ## Models
15
+
16
+ Six graphs: **offline** (a whole recording in one call) or **streaming** (one 40 ms frame per call, state carried by you), each in three precisions. Download them from [Hugging Face](https://huggingface.co/Binu30/sava-onnx) or the [GitHub release](https://github.com/Robinbinu/sava-onnx/releases).
17
+
18
+ | File | Use | Size | Matches PyTorch |
19
+ |---|---|---|---|
20
+ | `sava.onnx` | offline, fp32 | 103 MB | within 5e-6 |
21
+ | `sava_fp16.onnx` | offline, fp16 weights | 52 MB | within 5e-6 |
22
+ | `sava_int8.onnx` | offline, int8 | **33 MB** | 99.8% of speech verdicts |
23
+ | `sava_streaming.onnx` | streaming, fp32 | 103 MB | within 5e-6 |
24
+ | `sava_streaming_fp16.onnx` | streaming, fp16 weights | 52 MB | within 5e-6 |
25
+ | `sava_streaming_int8.onnx` | streaming, int8 | **32 MB** | 99.8% of speech verdicts |
26
+
27
+ **Which one?** For a realtime voice agent, or audio arriving in pieces, use `sava_streaming_int8.onnx`. For files and batch jobs, use `sava_int8.onnx`. Choose fp16 for exactly the reference model at half the download (SAVA's checkpoint is bf16, so fp16 storage loses nothing measurable), or fp32 for a runtime without fp16 casts. Full numbers are in [PARITY.md](https://github.com/Robinbinu/sava-onnx/blob/main/PARITY.md).
28
+
29
+ Speed on one CPU thread (Apple M-series, onnxruntime 1.32): offline is about 16 ms per second of audio; streaming int8 is about 1.6 ms per 40 ms frame in Python and 2.8 ms in Node.js. Budget more on small cloud vCPUs.
30
+
31
+ ## Quick start (Python)
32
+
33
+ ```bash
34
+ pip install "sava-onnx[hub]"
35
+ ```
36
+
37
+ ```python
38
+ import sava_onnx as sava
39
+
40
+ audio = sava.load_wav("speech.wav") # float32, 16 kHz mono
41
+ model = sava.Sava.from_pretrained(variant="int8")
42
+ curves = model.run(audio) # one value per 40 ms frame
43
+
44
+ print(curves.speech) # P(speech) per frame
45
+ print(curves.turn) # P(turn has ended) per frame
46
+
47
+ for turn in sava.segment(curves, sava.Policy()):
48
+ if turn.kept:
49
+ print(f"{turn.start_seconds:.2f}s - {turn.end_seconds:.2f}s ({turn.reason})")
50
+ ```
51
+
52
+ Streaming, in pieces of any size:
53
+
54
+ ```python
55
+ stream = sava.Session.from_pretrained(variant="int8")
56
+ turns = sava.TurnSegmenter(sava.Policy())
57
+ for piece in audio_chunks(): # float32 16 kHz mono numpy arrays
58
+ frames = stream.push(piece)
59
+ for turn in turns.feed(frames):
60
+ print("end of turn", turn.end_seconds)
61
+ frames = stream.flush() # end of stream: last verdicts
62
+ ```
63
+
64
+ `sava_onnx` needs only `numpy` and `onnxruntime`. Its `run`, `Session`, `Policy` and `segment` mirror the official `inworld-sava` API, and its turns match the official segmenter exactly with fp32 and fp16 (int8: within one frame), tested in [tests/test_runtime.py](https://github.com/Robinbinu/sava-onnx/blob/main/tests/test_runtime.py). A live microphone demo is in [examples/microphone.py](https://github.com/Robinbinu/sava-onnx/blob/main/examples/microphone.py).
65
+
66
+ ## Quick start (Node.js / browser)
67
+
68
+ ```bash
69
+ cd examples/js && npm install
70
+ node sava.mjs sava_streaming_int8.onnx speech.wav
71
+ ```
72
+
73
+ [examples/js/sava.mjs](https://github.com/Robinbinu/sava-onnx/blob/main/examples/js/sava.mjs) is a dependency-free streaming loop on `onnxruntime-node`. The same calls run in the browser with `onnxruntime-web`.
74
+
75
+ ## Using the graphs directly
76
+
77
+ All audio is **16 kHz mono float32 in [-1, 1]**. One frame is 640 samples (40 ms). Speech verdicts use 3 frames (120 ms) of lookahead.
78
+
79
+ ### Offline (`sava*.onnx`)
80
+
81
+ | | Name | Shape | Meaning |
82
+ |---|---|---|---|
83
+ | in | `pcm` | `[1, samples]` | any length; the graph pads the last frame and the lookahead |
84
+ | out | `speech` | `[T]` | P(speech) for frame `t` (lookahead verdict) |
85
+ | out | `speech_on_time` | `[T]` | P(speech) for frame `t` without lookahead |
86
+ | out | `turn` | `[T, 4]` | P(the turn has ended) at frame `t`, horizons 0, 5, 10, 20 frames |
87
+ | out | `turn_flush` | `[3, 4]` | `turn` for the 3 lookahead steps after the end (the segmenter reads them) |
88
+
89
+ `T = ceil(samples / 640)`, and row `t` of every output is about samples `[640t, 640(t+1))`. Attention memory grows with the square of the clip length, so for recordings longer than a few minutes, use the streaming graph.
90
+
91
+ ### Streaming (`sava_streaming*.onnx`)
92
+
93
+ Call once per 40 ms frame. Feed `pcm [1, 640]` plus every state tensor, and pass each `next_<name>` output back as `<name>` on the next call. Start with every state tensor at zero. To end a stream, feed 3 frames of silence to get the last verdicts.
94
+
95
+ | Output | Shape | Meaning |
96
+ |---|---|---|
97
+ | `speech` | `[1]` | P(speech) for the frame fed **3 calls ago** |
98
+ | `turn` | `[1, 4]` | P(the turn has ended) at this frame, horizons 0, 5, 10, 20 frames |
99
+ | `next_*` | as below | the state for the next call |
100
+
101
+ | State | Shape | Type |
102
+ |---|---|---|
103
+ | `frontend` | `[1, 240]` | float32 |
104
+ | `mixer_tail` | `[1, 1, 513]` | float32 |
105
+ | `trunk{0,1,2}_conv` | `[1, 3, 1280]` | float32 |
106
+ | `trunk{0,1,2}_ssm` | `[1, 16, 64, 128]` | float32 |
107
+ | `trunk3_keys`, `trunk3_values`, `vad_keys`, `vad_values`, `turn_keys`, `turn_values` | `[1, 512, 2, 64]` | float32 |
108
+ | `trunk3_offset`, `vad_offset`, `turn_offset`, `frames` | `[]` | int64 |
109
+ | `prev_speech` | `[1]` | float32 |
110
+
111
+ The state is fixed-size (three Mamba-2 layers and 512-frame sliding-window attention, about 3.2 MB), so a stream can run indefinitely. Run one state set per audio stream.
112
+
113
+ ## How the export works
114
+
115
+ `export/export.py` rebuilds every file from the official checkpoint:
116
+
117
+ ```bash
118
+ pip install -r export/requirements.txt
119
+ python export/export.py --out models
120
+ python tests/parity.py --models models # writes PARITY.md
121
+ python -m unittest tests/test_runtime.py
122
+ ```
123
+
124
+ Two numerically identical rewrites make SAVA traceable, both in the export script only:
125
+ - **Mel frontend.** Its strided unfold and matmul is written as a 1-D convolution with the same DFT kernels; ONNX can't export an unfold over a dynamic length.
126
+ - **Sliding-window attention.** It runs as one masked pass instead of a Python loop over 512-frame chunks. Tracing froze that loop at the example's length and cut long clips off at 20.48 s.
127
+
128
+ **int8** is dynamic per-channel quantization of the attention, feed-forward and head matmuls. The mel frontend, the frame mixer and the Mamba projections stay out of it: quantizing everything cost up to 1.5% of frame verdicts, while leaving those three out cost 0.2%. The weights left out are stored as fp16. **fp16** stores every weight matmul in fp16 and computes in fp32. The usual onnxruntime fp16 converter broke this graph even with every node excluded, so the export does the conversion itself (`export/owners.py`).
129
+
130
+ Parity is measured on synthetic audio (macOS text-to-speech voices, noise, hum, silence, a 122 s clip past the attention window), so anyone can reproduce it.
131
+
132
+ ## License and credit
133
+
134
+ Apache License 2.0, the same as SAVA. The model, its weights and its design are by [Inworld AI](https://inworld.ai): see the [original model](https://huggingface.co/inworld/sava), the [code](https://github.com/inworld-ai/sava) and the [announcement](https://inworld.ai/blog/introducing-sava). Inworld's NOTICE, including the third-party datasets the weights were trained on, is carried unchanged in [NOTICE](https://github.com/Robinbinu/sava-onnx/blob/main/NOTICE), followed by what this repo changed.
135
+
136
+ If you use SAVA in research, cite Inworld's work; see the [original repository](https://github.com/inworld-ai/sava).
@@ -0,0 +1,31 @@
1
+ [build-system]
2
+ requires = ["setuptools>=69"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "sava-onnx"
7
+ version = "1.0.0"
8
+ description = "Inworld SAVA voice activity + end-of-turn detection on ONNX Runtime: no PyTorch, CPU-friendly, streaming."
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ license-files = ["LICENSE", "NOTICE"]
12
+ requires-python = ">=3.9"
13
+ dependencies = ["numpy>=1.22", "onnxruntime>=1.17"]
14
+ keywords = ["vad", "voice-activity-detection", "turn-detection", "end-of-turn", "onnx", "onnxruntime",
15
+ "speech", "streaming", "realtime", "voice-agent", "silero-alternative", "sava"]
16
+ classifiers = [
17
+ "Programming Language :: Python :: 3",
18
+ "Topic :: Multimedia :: Sound/Audio :: Speech",
19
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
20
+ ]
21
+
22
+ [project.optional-dependencies]
23
+ hub = ["huggingface_hub>=0.23"]
24
+
25
+ [project.urls]
26
+ Homepage = "https://github.com/Robinbinu/sava-onnx"
27
+ Models = "https://huggingface.co/Binu30/sava-onnx"
28
+ "Original model" = "https://huggingface.co/inworld/sava"
29
+
30
+ [tool.setuptools]
31
+ packages = ["sava_onnx"]
@@ -0,0 +1,294 @@
1
+ """SAVA voice activity and end-of-turn detection on ONNX Runtime.
2
+
3
+ No PyTorch: numpy and onnxruntime only. Mirrors the API of Inworld's
4
+ `inworld-sava` package (run / Session / segment), on the ONNX graphs:
5
+
6
+ import sava_onnx as sava
7
+
8
+ model = sava.Sava.from_pretrained(variant="int8") # or Sava("sava_int8.onnx")
9
+ curves = model.run(audio) # float32, 16 kHz mono
10
+ turns = sava.segment(curves, sava.Policy())
11
+
12
+ stream = sava.Session.from_pretrained(variant="int8")
13
+ for piece in microphone():
14
+ frames = stream.push(piece)
15
+ frames = stream.flush()
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import dataclasses
20
+ import wave
21
+
22
+ import numpy as np
23
+ import onnxruntime as ort
24
+
25
+ __version__ = "1.0.0"
26
+
27
+ SAMPLE_RATE = 16000
28
+ FRAME_SAMPLES = 640 # one 40 ms frame
29
+ FRAME_SECONDS = FRAME_SAMPLES / SAMPLE_RATE
30
+ LOOKAHEAD_FRAMES = 3 # a speech verdict arrives 120 ms after its audio
31
+ TURN_HORIZONS = (0, 5, 10, 20) # frames; column k of `turns` is P(turn ended by now + horizon)
32
+ REPO_ID = "Binu30/sava-onnx"
33
+ VARIANTS = ("fp32", "fp16", "int8")
34
+
35
+ __all__ = ["SAMPLE_RATE", "FRAME_SAMPLES", "FRAME_SECONDS", "LOOKAHEAD_FRAMES", "TURN_HORIZONS",
36
+ "Curves", "Frames", "Policy", "Turn", "TurnSegmenter", "Sava", "Session",
37
+ "segment", "load_wav", "download"]
38
+
39
+
40
+ def _filename(variant: str, streaming: bool) -> str:
41
+ if variant not in VARIANTS:
42
+ raise ValueError(f"variant must be one of {VARIANTS}, got {variant!r}")
43
+ base = "sava_streaming" if streaming else "sava"
44
+ return f"{base}.onnx" if variant == "fp32" else f"{base}_{variant}.onnx"
45
+
46
+
47
+ def download(variant: str = "int8", streaming: bool = False, repo_id: str = REPO_ID,
48
+ revision: str | None = None) -> str:
49
+ """Fetch a graph from the Hugging Face Hub (needs `pip install sava-onnx[hub]`)."""
50
+ from huggingface_hub import hf_hub_download
51
+ return hf_hub_download(repo_id, _filename(variant, streaming), revision=revision)
52
+
53
+
54
+ def _session(path, threads: int | None, providers) -> ort.InferenceSession:
55
+ opts = ort.SessionOptions()
56
+ if threads:
57
+ opts.intra_op_num_threads = threads
58
+ opts.inter_op_num_threads = 1
59
+ return ort.InferenceSession(str(path), opts, providers=providers or ["CPUExecutionProvider"])
60
+
61
+
62
+ def _mono_float(audio) -> np.ndarray:
63
+ audio = np.asarray(audio)
64
+ if audio.ndim != 1:
65
+ raise ValueError(f"audio must be one-dimensional 16 kHz mono, got shape {audio.shape}")
66
+ if audio.dtype == np.int16:
67
+ return audio.astype(np.float32) / 32768.0
68
+ return audio.astype(np.float32, copy=False)
69
+
70
+
71
+ def load_wav(path) -> np.ndarray:
72
+ """16-bit PCM 16 kHz mono WAV -> float32 in [-1, 1]. Resample anything else first,
73
+ e.g. `ffmpeg -i in.mp3 -ar 16000 -ac 1 out.wav`."""
74
+ with wave.open(str(path), "rb") as wf:
75
+ if (wf.getframerate(), wf.getnchannels(), wf.getsampwidth()) != (SAMPLE_RATE, 1, 2):
76
+ raise ValueError(f"{path}: need 16 kHz mono 16-bit PCM, got {wf.getframerate()} Hz, "
77
+ f"{wf.getnchannels()} channel(s), {8 * wf.getsampwidth()}-bit")
78
+ return np.frombuffer(wf.readframes(wf.getnframes()), np.int16).astype(np.float32) / 32768.0
79
+
80
+
81
+ @dataclasses.dataclass
82
+ class Curves:
83
+ """Per-frame probabilities of a whole recording; frame t covers samples
84
+ [640 t, 640 (t + 1)). `speech` is the lookahead verdict on frame t,
85
+ `speech_on_time` the verdict without lookahead, `turns [T, K]` P(the turn
86
+ has ended) at every horizon, `turn` its first column, and `flush_turns
87
+ [lag, K]` the end-of-turn outputs of the lookahead steps after the end."""
88
+ speech: np.ndarray
89
+ turn: np.ndarray
90
+ turns: np.ndarray
91
+ speech_on_time: np.ndarray
92
+ flush_turns: np.ndarray
93
+
94
+
95
+ @dataclasses.dataclass
96
+ class Frames:
97
+ """One push's outputs: value i of `speech` judges frame `first + i - lag`;
98
+ `turn`/`turns` are about frame `first + i` (on time)."""
99
+ first: int
100
+ speech: np.ndarray
101
+ turn: np.ndarray
102
+ turns: np.ndarray
103
+
104
+ def __len__(self) -> int:
105
+ return self.speech.size
106
+
107
+
108
+ class Sava:
109
+ """Offline: a whole recording in, aligned curves out (sava.onnx graphs)."""
110
+
111
+ def __init__(self, path, threads: int | None = 1, providers=None):
112
+ self.session = _session(path, threads, providers)
113
+
114
+ @classmethod
115
+ def from_pretrained(cls, variant: str = "int8", repo_id: str = REPO_ID, **kwargs) -> "Sava":
116
+ return cls(download(variant, False, repo_id), **kwargs)
117
+
118
+ def run(self, audio) -> Curves:
119
+ audio = _mono_float(audio)
120
+ if audio.size == 0:
121
+ empty = np.zeros(0, np.float32)
122
+ none = np.zeros((0, len(TURN_HORIZONS)), np.float32)
123
+ return Curves(empty, empty, none, empty, none)
124
+ speech, on_time, turns, flush = self.session.run(None, {"pcm": audio[None]})
125
+ return Curves(speech=speech, turn=turns[:, 0], turns=turns,
126
+ speech_on_time=on_time, flush_turns=flush)
127
+
128
+
129
+ class Session:
130
+ """Streaming: samples in pieces of any size, a verdict per whole 40 ms frame
131
+ (sava_streaming.onnx graphs). Not safe for concurrent pushes; one per stream."""
132
+
133
+ def __init__(self, path, threads: int | None = 1, providers=None):
134
+ self.session = _session(path, threads, providers)
135
+ self._names = [i.name for i in self.session.get_inputs() if i.name != "pcm"]
136
+ self.reset()
137
+
138
+ @classmethod
139
+ def from_pretrained(cls, variant: str = "int8", repo_id: str = REPO_ID, **kwargs) -> "Session":
140
+ return cls(download(variant, True, repo_id), **kwargs)
141
+
142
+ def reset(self) -> None:
143
+ """Start a new stream: zero caches, no pending samples."""
144
+ self._state = {i.name: np.zeros([d if isinstance(d, int) else 1 for d in i.shape],
145
+ np.int64 if "int64" in i.type else np.float32)
146
+ for i in self.session.get_inputs() if i.name != "pcm"}
147
+ self._pending = np.zeros(0, np.float32)
148
+ self._frames = 0
149
+ self._closed = False
150
+
151
+ @property
152
+ def frames(self) -> int:
153
+ return self._frames
154
+
155
+ def push(self, samples) -> Frames:
156
+ if self._closed:
157
+ raise RuntimeError("The session is flushed; call reset() for a new stream.")
158
+ self._pending = np.concatenate([self._pending, _mono_float(samples)])
159
+ whole = self._pending.size - self._pending.size % FRAME_SAMPLES
160
+ chunk, self._pending = self._pending[:whole], self._pending[whole:]
161
+ return self._step(chunk)
162
+
163
+ def flush(self) -> Frames:
164
+ """End the stream: pad the last partial frame and step `lag` silent frames
165
+ so the last real frames get their verdicts."""
166
+ if self._closed:
167
+ raise RuntimeError("The session is already flushed.")
168
+ tail = (-self._pending.size) % FRAME_SAMPLES if self._pending.size else 0
169
+ chunk = np.concatenate([self._pending, np.zeros(tail + LOOKAHEAD_FRAMES * FRAME_SAMPLES, np.float32)])
170
+ self._pending = np.zeros(0, np.float32)
171
+ self._closed = True
172
+ return self._step(chunk)
173
+
174
+ def _step(self, chunk: np.ndarray) -> Frames:
175
+ first = self._frames
176
+ speech, turns = [], []
177
+ for i in range(0, chunk.size, FRAME_SAMPLES):
178
+ out = self.session.run(None, {"pcm": chunk[None, i:i + FRAME_SAMPLES], **self._state})
179
+ speech.append(out[0][0])
180
+ turns.append(out[1][0])
181
+ self._state = dict(zip(self._names, out[2:]))
182
+ self._frames += len(speech)
183
+ turns = np.array(turns, np.float32).reshape(-1, len(TURN_HORIZONS))
184
+ return Frames(first, np.array(speech, np.float32), turns[:, 0], turns)
185
+
186
+
187
+ # The turn policy below is ported from inworld/sava/segmenter.py (Apache 2.0,
188
+ # Copyright 2026 Inworld AI), unchanged in behaviour, adapted to this module's
189
+ # Curves and Frames.
190
+
191
+ @dataclasses.dataclass(frozen=True)
192
+ class Policy:
193
+ """Speech gates and timing rules used to open and close turns."""
194
+ speech_threshold: float = 0.5
195
+ turn_threshold: float = 0.9
196
+ pre_roll_ms: int = 800
197
+ min_silence_before_check_ms: int = 0
198
+ max_silence_ms: int = 1600
199
+ min_speech_ms: int = 400
200
+ min_confident_speech_ms: int = 200
201
+ confident_speech_threshold: float = 0.9
202
+
203
+
204
+ @dataclasses.dataclass
205
+ class Turn:
206
+ """Frames [start, end) of the audio, pre-roll included; `reason` is how it
207
+ closed ("turn", "silence" or "end"); `kept` whether it passed the gate."""
208
+ start: int
209
+ end: int
210
+ speech_ms: int
211
+ reason: str
212
+ kept: bool
213
+
214
+ @property
215
+ def start_seconds(self) -> float:
216
+ return self.start * FRAME_SECONDS
217
+
218
+ @property
219
+ def end_seconds(self) -> float:
220
+ return self.end * FRAME_SECONDS
221
+
222
+
223
+ def _ms_to_frames(ms: int) -> int:
224
+ return round(ms / (1000 * FRAME_SECONDS))
225
+
226
+
227
+ class TurnSegmenter:
228
+ """Feed `Frames` in order; returns the turns they close."""
229
+
230
+ def __init__(self, policy: Policy | None = None, lag: int = LOOKAHEAD_FRAMES) -> None:
231
+ self.policy = policy or Policy()
232
+ self.lag = lag
233
+ self._start: int | None = None
234
+ self._speech_ms = self._confident_ms = self._pause_frames = 0
235
+ self._last_judged = -1
236
+
237
+ @property
238
+ def open(self) -> bool:
239
+ return self._start is not None
240
+
241
+ def feed(self, frames: Frames) -> list[Turn]:
242
+ closed = []
243
+ for i in range(len(frames)):
244
+ judged = frames.first + i - self.lag
245
+ if judged < 0:
246
+ continue
247
+ turn = self._frame(judged, frames.first + i, float(frames.speech[i]), float(frames.turn[i]))
248
+ if turn is not None:
249
+ closed.append(turn)
250
+ return closed
251
+
252
+ def finish(self) -> list[Turn]:
253
+ if self._start is None:
254
+ return []
255
+ return [self._close(self._last_judged + 1, "end")]
256
+
257
+ def _frame(self, judged: int, now: int, speech: float, turn: float) -> Turn | None:
258
+ p = self.policy
259
+ frame_ms = round(1000 * FRAME_SECONDS)
260
+ self._last_judged = judged
261
+ is_speech = speech >= p.speech_threshold
262
+ if self._start is None:
263
+ if not is_speech:
264
+ return None
265
+ self._start = max(0, judged - _ms_to_frames(p.pre_roll_ms))
266
+ self._speech_ms = self._confident_ms = self._pause_frames = 0
267
+ if is_speech:
268
+ self._pause_frames = 0
269
+ self._speech_ms += frame_ms
270
+ if speech >= p.confident_speech_threshold:
271
+ self._confident_ms += frame_ms
272
+ return None
273
+ self._pause_frames += 1
274
+ pause_ms = self._pause_frames * frame_ms
275
+ if pause_ms >= p.max_silence_ms:
276
+ return self._close(now + 1, "silence")
277
+ if pause_ms >= p.min_silence_before_check_ms and turn >= p.turn_threshold:
278
+ return self._close(now + 1, "turn")
279
+ return None
280
+
281
+ def _close(self, end: int, reason: str) -> Turn:
282
+ p = self.policy
283
+ kept = self._speech_ms >= p.min_speech_ms or self._confident_ms >= p.min_confident_speech_ms
284
+ turn = Turn(self._start, end, self._speech_ms, reason, kept)
285
+ self._start = None
286
+ return turn
287
+
288
+
289
+ def segment(curves: Curves, policy: Policy | None = None, lag: int = LOOKAHEAD_FRAMES) -> list[Turn]:
290
+ """The turns of a whole recording, as a stream would cut them."""
291
+ seg = TurnSegmenter(policy, lag)
292
+ steps = np.concatenate([curves.turns, curves.flush_turns])[lag:lag + len(curves.speech)]
293
+ frames = Frames(first=lag, speech=np.asarray(curves.speech), turn=steps[:, 0], turns=steps)
294
+ return seg.feed(frames) + seg.finish()
@@ -0,0 +1,158 @@
1
+ Metadata-Version: 2.4
2
+ Name: sava-onnx
3
+ Version: 1.0.0
4
+ Summary: Inworld SAVA voice activity + end-of-turn detection on ONNX Runtime: no PyTorch, CPU-friendly, streaming.
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Homepage, https://github.com/Robinbinu/sava-onnx
7
+ Project-URL: Models, https://huggingface.co/Binu30/sava-onnx
8
+ Project-URL: Original model, https://huggingface.co/inworld/sava
9
+ Keywords: vad,voice-activity-detection,turn-detection,end-of-turn,onnx,onnxruntime,speech,streaming,realtime,voice-agent,silero-alternative,sava
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Topic :: Multimedia :: Sound/Audio :: Speech
12
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
13
+ Requires-Python: >=3.9
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ License-File: NOTICE
17
+ Requires-Dist: numpy>=1.22
18
+ Requires-Dist: onnxruntime>=1.17
19
+ Provides-Extra: hub
20
+ Requires-Dist: huggingface_hub>=0.23; extra == "hub"
21
+ Dynamic: license-file
22
+
23
+ # sava-onnx
24
+
25
+ **Inworld SAVA voice activity detection and end-of-turn detection, as ONNX.** One small model answers both "is someone speaking?" and "have they finished their turn?" every 40 ms, on CPU, with no PyTorch.
26
+
27
+ [![Hugging Face](https://img.shields.io/badge/%F0%9F%A4%97-Binu30%2Fsava--onnx-yellow)](https://huggingface.co/Binu30/sava-onnx)
28
+ [![PyPI](https://img.shields.io/pypi/v/sava-onnx)](https://pypi.org/project/sava-onnx/)
29
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue)](https://github.com/Robinbinu/sava-onnx/blob/main/LICENSE)
30
+ [![Original model](https://img.shields.io/badge/original-inworld%2Fsava-black)](https://huggingface.co/inworld/sava)
31
+
32
+ [SAVA](https://huggingface.co/inworld/sava) (semantic acoustic voice activity) is Inworld AI's open model that combines streaming VAD with end-of-turn prediction. Inworld reports it ahead of Silero VAD on speech detection and on par with pipecat smart-turn on turn detection ([their benchmarks](https://github.com/inworld-ai/sava/blob/main/bench/README.md)). The official package runs on PyTorch. This repo exports the same weights to ONNX, so SAVA runs wherever ONNX Runtime does: Python, Node.js, the browser (onnxruntime-web), C/C++, C#, Java, Rust, Go, Android and iOS.
33
+
34
+ > Unofficial community conversion. Not made, reviewed or endorsed by Inworld AI. Weights, behaviour and credit are theirs; see [NOTICE](https://github.com/Robinbinu/sava-onnx/blob/main/NOTICE).
35
+
36
+ ## Models
37
+
38
+ Six graphs: **offline** (a whole recording in one call) or **streaming** (one 40 ms frame per call, state carried by you), each in three precisions. Download them from [Hugging Face](https://huggingface.co/Binu30/sava-onnx) or the [GitHub release](https://github.com/Robinbinu/sava-onnx/releases).
39
+
40
+ | File | Use | Size | Matches PyTorch |
41
+ |---|---|---|---|
42
+ | `sava.onnx` | offline, fp32 | 103 MB | within 5e-6 |
43
+ | `sava_fp16.onnx` | offline, fp16 weights | 52 MB | within 5e-6 |
44
+ | `sava_int8.onnx` | offline, int8 | **33 MB** | 99.8% of speech verdicts |
45
+ | `sava_streaming.onnx` | streaming, fp32 | 103 MB | within 5e-6 |
46
+ | `sava_streaming_fp16.onnx` | streaming, fp16 weights | 52 MB | within 5e-6 |
47
+ | `sava_streaming_int8.onnx` | streaming, int8 | **32 MB** | 99.8% of speech verdicts |
48
+
49
+ **Which one?** For a realtime voice agent, or audio arriving in pieces, use `sava_streaming_int8.onnx`. For files and batch jobs, use `sava_int8.onnx`. Choose fp16 for exactly the reference model at half the download (SAVA's checkpoint is bf16, so fp16 storage loses nothing measurable), or fp32 for a runtime without fp16 casts. Full numbers are in [PARITY.md](https://github.com/Robinbinu/sava-onnx/blob/main/PARITY.md).
50
+
51
+ Speed on one CPU thread (Apple M-series, onnxruntime 1.32): offline is about 16 ms per second of audio; streaming int8 is about 1.6 ms per 40 ms frame in Python and 2.8 ms in Node.js. Budget more on small cloud vCPUs.
52
+
53
+ ## Quick start (Python)
54
+
55
+ ```bash
56
+ pip install "sava-onnx[hub]"
57
+ ```
58
+
59
+ ```python
60
+ import sava_onnx as sava
61
+
62
+ audio = sava.load_wav("speech.wav") # float32, 16 kHz mono
63
+ model = sava.Sava.from_pretrained(variant="int8")
64
+ curves = model.run(audio) # one value per 40 ms frame
65
+
66
+ print(curves.speech) # P(speech) per frame
67
+ print(curves.turn) # P(turn has ended) per frame
68
+
69
+ for turn in sava.segment(curves, sava.Policy()):
70
+ if turn.kept:
71
+ print(f"{turn.start_seconds:.2f}s - {turn.end_seconds:.2f}s ({turn.reason})")
72
+ ```
73
+
74
+ Streaming, in pieces of any size:
75
+
76
+ ```python
77
+ stream = sava.Session.from_pretrained(variant="int8")
78
+ turns = sava.TurnSegmenter(sava.Policy())
79
+ for piece in audio_chunks(): # float32 16 kHz mono numpy arrays
80
+ frames = stream.push(piece)
81
+ for turn in turns.feed(frames):
82
+ print("end of turn", turn.end_seconds)
83
+ frames = stream.flush() # end of stream: last verdicts
84
+ ```
85
+
86
+ `sava_onnx` needs only `numpy` and `onnxruntime`. Its `run`, `Session`, `Policy` and `segment` mirror the official `inworld-sava` API, and its turns match the official segmenter exactly with fp32 and fp16 (int8: within one frame), tested in [tests/test_runtime.py](https://github.com/Robinbinu/sava-onnx/blob/main/tests/test_runtime.py). A live microphone demo is in [examples/microphone.py](https://github.com/Robinbinu/sava-onnx/blob/main/examples/microphone.py).
87
+
88
+ ## Quick start (Node.js / browser)
89
+
90
+ ```bash
91
+ cd examples/js && npm install
92
+ node sava.mjs sava_streaming_int8.onnx speech.wav
93
+ ```
94
+
95
+ [examples/js/sava.mjs](https://github.com/Robinbinu/sava-onnx/blob/main/examples/js/sava.mjs) is a dependency-free streaming loop on `onnxruntime-node`. The same calls run in the browser with `onnxruntime-web`.
96
+
97
+ ## Using the graphs directly
98
+
99
+ All audio is **16 kHz mono float32 in [-1, 1]**. One frame is 640 samples (40 ms). Speech verdicts use 3 frames (120 ms) of lookahead.
100
+
101
+ ### Offline (`sava*.onnx`)
102
+
103
+ | | Name | Shape | Meaning |
104
+ |---|---|---|---|
105
+ | in | `pcm` | `[1, samples]` | any length; the graph pads the last frame and the lookahead |
106
+ | out | `speech` | `[T]` | P(speech) for frame `t` (lookahead verdict) |
107
+ | out | `speech_on_time` | `[T]` | P(speech) for frame `t` without lookahead |
108
+ | out | `turn` | `[T, 4]` | P(the turn has ended) at frame `t`, horizons 0, 5, 10, 20 frames |
109
+ | out | `turn_flush` | `[3, 4]` | `turn` for the 3 lookahead steps after the end (the segmenter reads them) |
110
+
111
+ `T = ceil(samples / 640)`, and row `t` of every output is about samples `[640t, 640(t+1))`. Attention memory grows with the square of the clip length, so for recordings longer than a few minutes, use the streaming graph.
112
+
113
+ ### Streaming (`sava_streaming*.onnx`)
114
+
115
+ Call once per 40 ms frame. Feed `pcm [1, 640]` plus every state tensor, and pass each `next_<name>` output back as `<name>` on the next call. Start with every state tensor at zero. To end a stream, feed 3 frames of silence to get the last verdicts.
116
+
117
+ | Output | Shape | Meaning |
118
+ |---|---|---|
119
+ | `speech` | `[1]` | P(speech) for the frame fed **3 calls ago** |
120
+ | `turn` | `[1, 4]` | P(the turn has ended) at this frame, horizons 0, 5, 10, 20 frames |
121
+ | `next_*` | as below | the state for the next call |
122
+
123
+ | State | Shape | Type |
124
+ |---|---|---|
125
+ | `frontend` | `[1, 240]` | float32 |
126
+ | `mixer_tail` | `[1, 1, 513]` | float32 |
127
+ | `trunk{0,1,2}_conv` | `[1, 3, 1280]` | float32 |
128
+ | `trunk{0,1,2}_ssm` | `[1, 16, 64, 128]` | float32 |
129
+ | `trunk3_keys`, `trunk3_values`, `vad_keys`, `vad_values`, `turn_keys`, `turn_values` | `[1, 512, 2, 64]` | float32 |
130
+ | `trunk3_offset`, `vad_offset`, `turn_offset`, `frames` | `[]` | int64 |
131
+ | `prev_speech` | `[1]` | float32 |
132
+
133
+ The state is fixed-size (three Mamba-2 layers and 512-frame sliding-window attention, about 3.2 MB), so a stream can run indefinitely. Run one state set per audio stream.
134
+
135
+ ## How the export works
136
+
137
+ `export/export.py` rebuilds every file from the official checkpoint:
138
+
139
+ ```bash
140
+ pip install -r export/requirements.txt
141
+ python export/export.py --out models
142
+ python tests/parity.py --models models # writes PARITY.md
143
+ python -m unittest tests/test_runtime.py
144
+ ```
145
+
146
+ Two numerically identical rewrites make SAVA traceable, both in the export script only:
147
+ - **Mel frontend.** Its strided unfold and matmul is written as a 1-D convolution with the same DFT kernels; ONNX can't export an unfold over a dynamic length.
148
+ - **Sliding-window attention.** It runs as one masked pass instead of a Python loop over 512-frame chunks. Tracing froze that loop at the example's length and cut long clips off at 20.48 s.
149
+
150
+ **int8** is dynamic per-channel quantization of the attention, feed-forward and head matmuls. The mel frontend, the frame mixer and the Mamba projections stay out of it: quantizing everything cost up to 1.5% of frame verdicts, while leaving those three out cost 0.2%. The weights left out are stored as fp16. **fp16** stores every weight matmul in fp16 and computes in fp32. The usual onnxruntime fp16 converter broke this graph even with every node excluded, so the export does the conversion itself (`export/owners.py`).
151
+
152
+ Parity is measured on synthetic audio (macOS text-to-speech voices, noise, hum, silence, a 122 s clip past the attention window), so anyone can reproduce it.
153
+
154
+ ## License and credit
155
+
156
+ Apache License 2.0, the same as SAVA. The model, its weights and its design are by [Inworld AI](https://inworld.ai): see the [original model](https://huggingface.co/inworld/sava), the [code](https://github.com/inworld-ai/sava) and the [announcement](https://inworld.ai/blog/introducing-sava). Inworld's NOTICE, including the third-party datasets the weights were trained on, is carried unchanged in [NOTICE](https://github.com/Robinbinu/sava-onnx/blob/main/NOTICE), followed by what this repo changed.
157
+
158
+ If you use SAVA in research, cite Inworld's work; see the [original repository](https://github.com/inworld-ai/sava).
@@ -0,0 +1,11 @@
1
+ LICENSE
2
+ NOTICE
3
+ README.md
4
+ pyproject.toml
5
+ sava_onnx/__init__.py
6
+ sava_onnx.egg-info/PKG-INFO
7
+ sava_onnx.egg-info/SOURCES.txt
8
+ sava_onnx.egg-info/dependency_links.txt
9
+ sava_onnx.egg-info/requires.txt
10
+ sava_onnx.egg-info/top_level.txt
11
+ tests/test_runtime.py
@@ -0,0 +1,5 @@
1
+ numpy>=1.22
2
+ onnxruntime>=1.17
3
+
4
+ [hub]
5
+ huggingface_hub>=0.23
@@ -0,0 +1 @@
1
+ sava_onnx
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,72 @@
1
+ """sava_onnx (numpy + onnxruntime) against inworld-sava (PyTorch): same curves,
2
+ same streaming frames, same turns.
3
+
4
+ python -m unittest tests/test_runtime.py
5
+ """
6
+ import pathlib
7
+ import sys
8
+ import unittest
9
+
10
+ import numpy as np
11
+
12
+ ROOT = pathlib.Path(__file__).resolve().parents[1]
13
+ sys.path.insert(0, str(ROOT))
14
+ sys.path.insert(0, str(ROOT / "tests"))
15
+
16
+ import sava_onnx # noqa: E402
17
+ from parity import LINES, tts # noqa: E402
18
+
19
+ MODELS = ROOT / "models"
20
+
21
+
22
+ class RuntimeMatchesReference(unittest.TestCase):
23
+ @classmethod
24
+ def setUpClass(cls):
25
+ from inworld import sava
26
+ cls.sava = sava
27
+ cls.ref = sava.load("inworld/sava").eval()
28
+ gap = np.zeros(sava_onnx.SAMPLE_RATE, np.float32)
29
+ cls.audio = np.concatenate([x for v, t in LINES[:3] for x in (tts(v, t), gap)])
30
+
31
+ def test_offline_curves(self):
32
+ want = self.sava.run(self.ref, self.audio)
33
+ got = sava_onnx.Sava(MODELS / "sava.onnx").run(self.audio)
34
+ for field in ("speech", "speech_on_time", "turns", "flush_turns"):
35
+ np.testing.assert_allclose(getattr(got, field), getattr(want, field), atol=1e-4, err_msg=field)
36
+
37
+ def test_streaming_in_odd_pieces(self):
38
+ want = self.sava.Session(self.ref)
39
+ got = sava_onnx.Session(MODELS / "sava_streaming.onnx")
40
+ rng = np.random.default_rng(1)
41
+ cuts = np.sort(rng.integers(0, self.audio.size, 25))
42
+ ws, gs = [], []
43
+ for piece in np.split(self.audio, cuts):
44
+ ws.append(want.push(piece).speech)
45
+ gs.append(got.push(piece).speech)
46
+ ws.append(want.flush().speech)
47
+ gs.append(got.flush().speech)
48
+ np.testing.assert_allclose(np.concatenate(gs), np.concatenate(ws), atol=1e-4)
49
+
50
+ def test_turns_match_the_reference_segmenter(self):
51
+ want = self.sava.segment(self.sava.run(self.ref, self.audio), self.sava.Policy(),
52
+ self.ref.lookahead_frames)
53
+ for name in ("sava.onnx", "sava_fp16.onnx", "sava_int8.onnx"):
54
+ with self.subTest(name=name):
55
+ got = sava_onnx.segment(sava_onnx.Sava(MODELS / name).run(self.audio))
56
+ self.assertEqual([(t.reason, t.kept) for t in got], [(t.reason, t.kept) for t in want])
57
+ # int8 is an approximation: a turn may open or close one 40 ms frame apart.
58
+ slack = 1 if "int8" in name else 0
59
+ for g, w in zip(got, want):
60
+ self.assertLessEqual(abs(g.start - w.start), slack)
61
+ self.assertLessEqual(abs(g.end - w.end), slack)
62
+
63
+ def test_reset_starts_a_fresh_stream(self):
64
+ s = sava_onnx.Session(MODELS / "sava_streaming_int8.onnx")
65
+ a = np.concatenate([s.push(self.audio[:32000]).speech, s.flush().speech])
66
+ s.reset()
67
+ b = np.concatenate([s.push(self.audio[:32000]).speech, s.flush().speech])
68
+ np.testing.assert_array_equal(a, b)
69
+
70
+
71
+ if __name__ == "__main__":
72
+ unittest.main()