kollaikalrupesh0745 commited on
Commit
8d7c191
·
verified ·
1 Parent(s): e3c8bc7

turn-1-mini v2.0.0: multi-party end-of-turn, interruption output, p99turn 2.0.0

Browse files
NOTICE CHANGED
@@ -23,6 +23,9 @@ AMI Meeting Corpus. J. Carletta et al., "The AMI Meeting Corpus: A Pre-announcem
23
  https://groups.inf.ed.ac.uk/ami/corpus/
24
  ICSI Meeting Corpus. A. Janin et al., "The ICSI Meeting Corpus", ICASSP 2003. https://groups.inf.ed.ac.uk/ami/icsi/
25
 
 
 
 
26
  Evaluation (never trained or tuned on)
27
  eot-bench (code), LiveKit. Apache-2.0. https://github.com/livekit/eot-bench
28
  livekit/eot-bench-data, LiveKit. CC BY 4.0 per its dataset card. https://huggingface.co/datasets/livekit/eot-bench-data
 
23
  https://groups.inf.ed.ac.uk/ami/corpus/
24
  ICSI Meeting Corpus. A. Janin et al., "The ICSI Meeting Corpus", ICASSP 2003. https://groups.inf.ed.ac.uk/ami/icsi/
25
 
26
+ otoSpeech full-duplex (processed 141 h; task-oriented 20 h), otoearth. CC BY 4.0.
27
+ https://huggingface.co/otoearth
28
+
29
  Evaluation (never trained or tuned on)
30
  eot-bench (code), LiveKit. Apache-2.0. https://github.com/livekit/eot-bench
31
  livekit/eot-bench-data, LiveKit. CC BY 4.0 per its dataset card. https://huggingface.co/datasets/livekit/eot-bench-data
README.md CHANGED
@@ -2,209 +2,147 @@
2
  license: apache-2.0
3
  language: [en]
4
  pipeline_tag: voice-activity-detection
5
- tags: [turn-detection, end-of-turn, endpointing, turn-taking, voice-activity-detection, voice-agents, conversational-ai, real-time, streaming, on-device, edge, onnx, eot-bench]
6
- model-index:
7
- - name: turn-1-mini
8
- results:
9
- - task:
10
- type: audio-classification
11
- name: End-of-turn detection
12
- dataset:
13
- name: eot-bench (English)
14
- type: livekit/eot-bench-data
15
- config: en
16
- split: validation
17
- revision: ca9d98a
18
- metrics:
19
- - type: false_cutoff_rate_300ms
20
- name: False cut-offs at 300 ms (%)
21
- value: 22.6
22
- - type: false_cutoff_rate_600ms
23
- name: False cut-offs at 600 ms (%)
24
- value: 9.6
25
- - type: latency_at_5pct_false_cutoffs_ms
26
- name: Latency at 5% false cut-offs (ms)
27
- value: 849
28
- - type: latency_at_10pct_false_cutoffs_ms
29
- name: Latency at 10% false cut-offs (ms)
30
- value: 581
31
  ---
32
- # turn-1-mini
33
 
34
- **A 5.3M-parameter model that knows when you have finished talking.** Streaming, audio only, no transcript needed.
35
- 7 MB as an 8-bit ONNX file, 1.3 ms per 160 ms step on one laptop core, Apache-2.0.
36
 
37
- Ahead of every downloadable model on LiveKit's public eot-bench (English), on point estimates:
38
 
39
- | Model | False cut-offs @ 300 ms | Latency @ 5% cut-offs | Size |
40
- |---|---:|---:|---:|
41
- | **turn-1-mini** | **22.6%** | **849 ms** | 5.3M parameters |
42
- | ultraVAD | 27.7% | 899 ms | |
43
- | LiveKit Turn Detector v1-mini | 27.8% | 1,070 ms | |
44
- | Smart Turn v3.2 | 35.2% | 1,051 ms | 8M parameters |
45
-
46
- Lower is better. Full table, intervals and limits are below.
47
-
48
- ## Quick start
49
-
50
- No PyTorch needed:
51
-
52
- ```bash
53
- pip install "p99turn[onnx] @ https://huggingface.co/p99lab/turn-1-mini/resolve/main/dist/p99turn-1.2.3-py3-none-any.whl"
54
- ```
55
- ```python
56
- from p99turn.onnx_stream import Turn1MiniOnnx
57
 
58
- turn = Turn1MiniOnnx.from_pretrained() # downloads the 7 MB graph
59
- for chunk in microphone_chunks(): # 16 kHz mono float32, any chunk size
60
- probs = turn.push(chunk) # one P(end of turn) per finished 20 ms frame
61
- if len(probs) and probs[-1] > 0.5: # calibrate this threshold on your own audio
62
- respond()
63
- ```
64
-
65
- With PyTorch: install `p99turn[torch]` from the same link, then `from p99turn import Turn1Mini`.
66
-
67
- Made by p99lab (p99lab.com), which today works on turn-taking that runs on the device.
68
- Version 1.2.3, October 2026. Questions and issues: research@p99lab.com
69
-
70
- ## What it is
71
-
72
- turn-1-mini is p99lab's own model: the architecture, the weights and the training are ours. It contains no
73
- third-party weights and needs none at run time.
74
-
75
- | | |
76
- |---|---|
77
- | Parameters | 5,262,337 (trunk 5.0M + head 0.26M) |
78
- | Size | 21 MB (float32, `turn-1-mini.safetensors`) or 5.4 MB (8-bit, `turn-1-mini.int8.safetensors`, slightly lossy: see the evaluation section). ONNX streaming graphs of 21.8 MB and 7.0 MB are in `onnx/` |
79
- | Input | 16 kHz mono audio, **low-passed at 4 kHz**, 80-bin log-mel, 10 ms hop, causal framing |
80
- | Trunk | 2 causal convolutions (20 ms frames) + 6 transformer layers, width 256, 4 heads, causal attention limited to 1.2 s per layer, relative positions (ALiBi). No look-ahead |
81
- | Head | MLP on layers 2, 4, 6 at the current frame + the mean of layer 6 from 1.2 s to 0.2 s back |
82
- | Output | P(end of turn) per 20 ms frame; benchmarked read-out: any-time (the score can be read at any frame of a pause; no fixed score point) |
83
- | Streaming | 160 ms steps with cached attention state; equals the offline forward to 1e-4 (tested) |
84
-
85
- **The 4 kHz low-pass is required.** The model was trained on audio band-limited to 4 kHz. Feed it wideband
86
- microphone audio without the low-pass and it is out of distribution. `p99turn.audio.bandlimit_4k` is the filter
87
- behind the benchmark numbers. From version 1.2.0 the live stream (`model.stream()`) applies the same filter causally,
88
- so live scores follow the benchmarked path; earlier versions used a different live filter.
89
 
90
  ```bash
91
- pip install "p99turn[torch] @ https://huggingface.co/p99lab/turn-1-mini/resolve/main/dist/p99turn-1.2.3-py3-none-any.whl"
92
- ```
93
- ```python
94
- from p99turn import Turn1Mini
95
- model = Turn1Mini() # downloads p99lab/turn-1-mini; or set P99TURN_WEIGHTS=/local/dir
96
- p = model.score(audio_so_far) # as benchmarked: low-pass + run from a zero state
97
- s = model.stream() # live: probs = s.push(chunk) -> one value per finished 20 ms frame
98
  ```
99
 
100
- ## Training data
101
-
102
- turn-1-mini was trained on read, conversational and telephone speech in English. No training data is redistributed
103
- with this release. eot-bench data was used for evaluation only, never for training.
104
 
105
- ## Evaluation: eot-bench English
106
 
107
- `livekit/eot-bench-data`, config `en`, split `validation`, revision `ca9d98a`, harness commit `9ee21b5`: 400 turns,
108
- 705 scored mid-turn pauses. One run, any-time read-out. Lower is better.
109
 
110
- | | False cut-offs @ 300 ms | False cut-offs @ 600 ms | Latency @ 5% | Latency @ 10% | Score AUC (diagnostic) |
111
- |---|---:|---:|---:|---:|---:|
112
- | **turn-1-mini** (5.3M) | **22.6%** | **9.6%** | **849 ms** | **581 ms** | 0.970 |
113
- | 95% interval (turn-level bootstrap, 400 resamples) | 18.8 to 27.8% | 6.3 to 12.1% | 678 to 1,012 ms | 462 to 672 ms | |
114
- | ultraVAD (open weights) | 27.7% | 11.9% | 899 ms | 663 ms | |
115
- | LiveKit Turn Detector v1-mini (downloadable) | 27.8% | 12.1% | 1,070 ms | 698 ms | 0.890 |
116
- | Smart Turn v3.2 (open weights, 8M) | 35.2% | 14.8% | 1,051 ms | 739 ms | 0.845 |
117
- | *For scale: LiveKit Turn Detector v1 (hosted, board leader)* | *9.9%* | *4.5%* | *543 ms* | *295 ms* | *0.969* |
118
 
119
  What this supports, and what it does not:
120
 
121
- - On these four measures turn-1-mini is **ahead of every model on the board whose weights can be downloaded**
122
- (ultraVAD, LiveKit v1-mini, Smart Turn v3.2, VAP), on point estimates. No paired interval against them was
123
- computed, and its own interval at 300 ms (18.8 to 27.8%) overlaps LiveKit v1-mini's (20.7 to 32.9%).
124
- - Counted alone against the 13 rows of the board at that commit it would rank 4th / 4th / 4th / 5th.
125
- - It is behind the large hosted models (LiveKit v1, JoinIn Baton), which run in a data centre.
126
- - An 8-bit build of the same weights (5.4 MB, per-channel int8) scores 23.8% / 9.5% / 853 ms / 583 ms: about
127
- one point worse at 300 ms, unchanged on the other three measures. Load it with `Turn1Mini(variant="int8")`.
128
- - English only. No other language was run for this checkpoint and no multilingual number is claimed.
129
-
130
- Latency here is dead air chosen by the benchmark's policy sweep, not compute time. As for every model on the board,
131
- the sweep picks threshold, action delay and timeout on the same 400 turns it scores.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
 
133
- ## Evaluation discipline
 
134
 
135
- eot-bench audio and labels were never used to train, select or threshold this model. The checkpoint and its read-out
136
- were fixed beforehand on our own development data, and the checkpoint was scored on eot-bench English once. The
137
- released package reproduces the numbers above.
138
 
139
- ## Compute per decision
 
 
 
 
140
 
141
- About 0.57 GFLOP per second of audio; fixed memory. Streaming cost is constant per 160 ms step.
142
 
143
- Measured on a laptop CPU (Apple M4 Pro, one core, PyTorch 2.14, float32; 3,000 streaming steps after warm-up): one
144
- 160 ms step, including the low-pass and the log-mel, takes **1.29 ms at the median and 1.45 ms at the 95th
145
- percentile**, which is under 1% of one core. More threads do not help a model this small. The model loads in 17 ms.
146
- On a server GPU (NVIDIA GB10) a full-prefix decision takes about 8 ms.
147
 
148
- Not measured: an iPhone, a Core ML or ExecuTorch export, battery use, and end-to-end latency of a full voice
149
- pipeline. This is the model's compute only.
 
 
 
 
 
150
 
151
- ## ONNX (no PyTorch needed)
 
152
 
153
- `onnx/` holds one 160 ms streaming step of the model as an ONNX graph with fixed shapes: raw 16 kHz audio and the
154
- previous state in, 8 frame probabilities and the new state out. The low-pass and the log-mel are inside the graph. It
155
- runs with `onnxruntime` and `numpy` only. The float32 graph matches the PyTorch stream to 0.00004 on 337 s of audio. The
156
- 8-bit graph (7.0 MB) changes about 0.2% of decisions on our development audio and has not been run on eot-bench.
157
- Interface, state handling and an example: `onnx/README.md`. A Core ML build is not available yet.
158
 
159
- ## TurnBench
 
 
 
 
 
 
 
 
 
160
 
161
- turn-1-mini is also the model behind our entry on Sesame's TurnBench, submitted on 2026-10-05. Write-up:
162
- https://github.com/P99Lab/turn-1-mini
 
163
 
164
- ## Intended use
165
 
166
- On-device end-of-turn detection inside a voice SDK, as one signal in an endpointing policy (threshold + minimum
167
- silence + timeout), where a server model is not available or as a first stage before one.
168
 
169
- ## Limits
 
 
170
 
171
- - **English only measured.** Other languages are untested for this checkpoint.
172
- - **4 kHz band only** (see the low-pass requirement above).
173
- - **Scores are not calibrated.** The 300 ms operating point uses a threshold of 0.06. Calibrate thresholds on your
174
- own audio.
175
- - Audio only: it does not read words. At its 300 ms operating point it cuts off 27 of 126 pauses inside numbers,
176
- letters and email addresses, 36 of 119 after a finished sentence with more to come, 54 of 214 after a content word
177
- mid-sentence, and 40 of 68 pauses longer than 1 s.
178
- - No accent, age or gender breakdown; not evaluated with overlapping speech, far-field audio or agent echo.
179
 
180
- ## Responsible use
181
 
182
- turn-1-mini outputs one number about turn-taking. It does not identify speakers, transcribe, or infer emotion,
183
- health or identity. A false "end of turn" interrupts a person and a missed one makes them wait: keep a timeout
184
- fallback and do not rely on it alone where either could cause harm. Performance for accents, speech impairments
185
- and non-English speakers is unmeasured; test on your own users.
 
 
 
 
186
 
187
  ## How to credit
188
 
189
- If you use this model or build on it, please credit "turn-1-mini by p99lab" with a link to
190
- https://huggingface.co/p99lab/turn-1-mini. Redistributed copies and derived models must keep the `NOTICE` file
191
- (Apache-2.0, section 4). Please do not name a derived model "turn-1-mini".
192
-
193
- ## Licence
194
-
195
- Weights and code: Apache-2.0. Credits required by third-party licences: see `NOTICE`.
196
-
197
- Built by **Rupesh Kollaikal** at p99lab.
198
-
199
- ## Citation
200
-
201
- ```bibtex
202
- @misc{p99lab2026turn1mini,
203
- title = {turn-1-mini: a 5M-parameter streaming end-of-turn model},
204
- author = {Kollaikal, Rupesh},
205
- publisher = {p99lab},
206
- year = {2026},
207
- url = {https://p99lab.com}
208
- }
209
- ```
210
- Please also cite eot-bench (LiveKit) when reporting numbers.
 
2
  license: apache-2.0
3
  language: [en]
4
  pipeline_tag: voice-activity-detection
5
+ tags: [turn-detection, end-of-turn, endpointing, turn-taking, interruption, barge-in, multi-party, voice-activity-detection, voice-agents, streaming, cpu, eot-bench, turnbench, multipartyturnbench]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  ---
7
+ # turn-1-mini (v2)
8
 
9
+ **A 5.4M-parameter model that knows when someone has finished talking, and when someone is cutting in.**
10
+ Streaming, audio only, no transcript, CPU real time. Apache-2.0. Built by Rupesh Kollaikal at p99lab.
11
 
12
+ Version 2 keeps v1's size class and cost and adds:
13
 
14
+ - **Fast, multi-party end-of-turn**: give it every speaker's channel and it decides that a turn is over when its own speaker has
15
+ stopped AND someone else has just started to take the floor. Single-channel end-of-turn scores are exactly v1's.
16
+ - **An interruption output (INT)**: P(this speaker is taking the floor), as opposed to a backchannel ("yeah", "mm-hm") or a laugh.
17
+ - **Speech-activity (VAD) and floor-claim outputs** per channel, shared with the other channels as the REST input.
18
+ - **An optional REST input**: the other channels of a call, or your agent's own playback. Leave it out and the model runs
19
+ single-channel, like v1.
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
+ ## Install
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
  ```bash
24
+ pip install "p99turn[torch] @ https://huggingface.co/p99lab/turn-1-mini/resolve/main/dist/p99turn-2.0.0-py3-none-any.whl"
 
 
 
 
 
 
25
  ```
26
 
27
+ v2 runs with PyTorch on CPU (`turn-1-mini-v2.safetensors`, 21 MB). The v1 files in this repo (`turn-1-mini.safetensors`, the 8-bit
28
+ copy, the ONNX streaming graphs and the 1.2.3 wheel) are unchanged, and `Turn1Mini` / `Turn1MiniOnnx` from the 2.0.0 package load
29
+ them exactly as before. v1's model card: [revision e3c8bc7](https://huggingface.co/p99lab/turn-1-mini/blob/e3c8bc794a00ebe58c3649ca236078fef4d7b9aa/README.md).
 
30
 
31
+ ## Results
32
 
33
+ Every number below was measured by the benchmark's own scorer, with thresholds chosen on the benchmark's dev split where the
34
+ protocol says so. v1 is the released turn-1-mini 1.2.3, run by us through the same code.
35
 
36
+ | Benchmark | Measure | v1 (1.2.3; INT rows: v1 TurnBench interruption head, not released) | v2 |
37
+ |---|---|---:|---:|
38
+ | MultiPartyTurnBench test (2-5 speakers) | EOT | 86.9% recall, 25.3% FPR, p50 1087 ms | **92.2% recall, 3.8% FPR, p50 210 ms** |
39
+ | MultiPartyTurnBench test (2-5 speakers) | INT | 31.3% recall, 9.5% FPR, p50 777 ms | 28.5% recall, 5.5% FPR, p50 1021 ms (same output at the earlier threshold: 40.9%, 9.0%, 810 ms) |
40
+ | TurnBench dev (2 speakers) | EOT | 54.6% recall, 9.9% FPR, p50 811 ms | 82.1% recall, 10.0% FPR, p50 525 ms with REST (single channel: 54.6%, 9.9%, 811 ms) |
41
+ | TurnBench dev (2 speakers) | INT | 96.0% recall, 4.2% FPR, p50 688 ms | 96.8% recall, 5.4% FPR, p50 850 ms with REST (single channel: 96.0%, 3.6%, 1083 ms) |
42
+ | eot-bench English (single channel) | false cut-offs @ 300 / 600 ms | 22.6% / 9.6% | 22.6% / 9.6% (unchanged by construction) |
43
+ | eot-bench English (single channel) | latency @ 5% / 10% cut-offs | 849 / 581 ms | 849 / 581 ms (unchanged by construction) |
44
 
45
  What this supports, and what it does not:
46
 
47
+ - **MultiPartyTurnBench EOT** (192 test conversations; conversation-clustered bootstrap, B = 10,000): recall 92.2% [91.6%, 92.8%],
48
+ false alarms on mid-turn holds 3.8% [1.2%, 6.7%], median latency 210 ms [200, 221]. Against v1: recall +4.1 to +6.5 points, false
49
+ alarms -14.4 to -28.6 points. The paper reports VAP at 92.6% recall, 7.5% false alarms and 143 ms: v2's recall is level with VAP's
50
+ (the intervals overlap), its false-alarm rate is lower, and VAP decides about 70 ms earlier. v2 does not beat VAP on latency.
51
+ - **How the operating point was chosen**: thresholds were selected on the benchmark's dev split with a dev false-alarm budget of 5.5%,
52
+ stricter than the benchmark's standard 10%. The end-of-turn read-out used with several channels ("fast-onset", below) was designed
53
+ after inspecting false alarms on that dev split. It was then confirmed on TurnBench dev before the test split was scored. This v2
54
+ family has been scored on the MultiPartyTurnBench test split four times during development; this table is the fourth look.
55
+ - **INT on MultiPartyTurnBench** is not a strength: the same INT output gives 28.5% recall at 5.5% false alarms at the threshold chosen
56
+ with the 5.5% budget, and 40.9% at 9.0% at the threshold chosen in an earlier round. The paper's best in-budget INT system, Kyutai's
57
+ semantic VAD, reports 56.2% at 6.6%. On TurnBench dev, INT matches our earlier TurnBench interruption head on recall without needing
58
+ a separate voice-activity model.
59
+ - **TurnBench** numbers are on its public dev set (test labels are withheld). With REST, end-of-turn decides 290 ms earlier than v1 at
60
+ a much higher recall. Its false-alarm rate (10.0%) sits at the 10% budget of that benchmark's sweep. v2's previous REST read-out had
61
+ 3.8% false alarms at 719 ms there; use read-out 0 if false alarms matter more than speed.
62
+ - **Real meetings (report-only)**: on MultiPartyTurnBench's real-speech AMI slice (15 four-person meetings, 7.1 h; thresholds selected
63
+ inside the slice, as the paper does), end-of-turn reaches 82.4% recall at 9.3% false alarms (p50 800 ms) and INT 86.2% at 8.7%.
64
+ The paper reports VAP at 52.1% / 8.2% (EOT) and 35.9% / 5.3% (INT) on that slice. Caveats: the slice has no dev/test split, so
65
+ in-slice numbers are optimistic. Two of its meetings (TS3004a-b) are in our own development set. Five of its meeting series were in
66
+ an earlier p99lab training set whose relation to v1's trunk is not re-verified. All eight of its series were excluded from v2's
67
+ training. Without TS3004 the numbers are 81.2% / 9.7%.
68
+ - **eot-bench** is single-channel, where v2 is v1 by design (the frozen v1 path; checked on real audio, max difference 1.5e-7).
69
+ - The multi-party gains need the REST input: run all channels together.
70
+
71
+ ## Cost
72
+
73
+ | | v1 | v2 single channel | v2 per channel, 2-channel group |
74
+ |---|---:|---:|---:|
75
+ | CPU per 160 ms step, 1 thread, 1 stream (3 interleaved runs, same core) | 2.65-2.66 ms | 2.63-2.65 ms | 2.68-2.69 ms |
76
 
77
+ No GPU needed. Single channel, v2 costs no more than v1. Per channel in a multi-channel group it costs about 1% more than v1, because
78
+ each channel shares its speech-activity and floor-claim values with the others. 5,369,033 parameters (v1: 5,262,337).
79
 
80
+ ## End-of-turn read-outs
 
 
81
 
82
+ | Read-out | When | What it is |
83
+ |---|---|---|
84
+ | 3, "fast-onset" (default with 2 or more human channels) | every speaker has a channel | (1 - P_speech(own)) x max over the others of P_claim(now) x (1 - max over the others of P_claim 1 s ago): this speaker has stopped and someone else has just started to take the floor |
85
+ | 0, trained correction (default with one channel + `rest_activity`) | one human channel + your agent's playback activity | v1's score plus a learned correction from the REST input, Platt-calibrated |
86
+ | single channel (no REST) | one channel, nothing else | exactly v1's score |
87
 
88
+ Choose with `m.stream(n_channels, readout=0 or 3)`. Read-out 3 is a score, not a calibrated probability.
89
 
90
+ ## Outputs and default thresholds
 
 
 
91
 
92
+ | Output | Meaning | Default threshold | How it was set |
93
+ |---|---|---:|---|
94
+ | `eot`, 2+ channels (read-out 3) | the turn is over | 0.32 | highest recall at a 10% false-alarm rate on mid-turn holds, p99lab dev data (AMI / ICSI / otoSpeech held out). The MultiPartyTurnBench rows above use 0.25 (its dev split, 5.5% budget) |
95
+ | `eot`, one channel + agent playback (read-out 0) | same | 0.82 | same rule |
96
+ | `eot`, single channel | v1's score, unchanged | 0.36 | same rule, single-channel mode |
97
+ | `int` | this speaker's new vocalisation is a floor-taking interruption | 0.70 (with REST), 0.74 (single channel) | highest recall at a 10% false-alarm rate on backchannels and laughter, same dev data |
98
+ | `vad` | this speaker is speaking | 0.5 | |
99
 
100
+ Commit rule used for these thresholds and on all three benchmarks: fire on the rising edge above the threshold, then wait 2 s
101
+ before firing again. Re-tune on your own audio when you can.
102
 
103
+ ## Quick start
 
 
 
 
104
 
105
+ ```python
106
+ from p99turn import Turn1MiniV2
107
+ m = Turn1MiniV2() # 16 kHz mono float32 in; 4 kHz low-pass applied inside the stream
108
+ s = m.stream() # one human channel
109
+ for chunk in mic_chunks():
110
+ out = s.push([chunk]) # one value per finished 20 ms frame
111
+ if len(out["eot"][0]) and out["eot"][0][-1] > 0.36:
112
+ respond()
113
+ if len(out["int"][0]) and out["int"][0][-1] > 0.74 and agent_is_speaking:
114
+ stop_talking() # barge-in
115
 
116
+ s = m.stream(n_channels=4) # four people, one channel each (read-out 3): every channel's REST = the other three
117
+ out = s.push([c1, c2, c3, c4]) # end of turn on channel k: out["eot"][k] > 0.32
118
+ ```
119
 
120
+ ## Training data
121
 
122
+ All training audio is ours to use and licensed for commercial use (CC BY 4.0):
 
123
 
124
+ - AMI Meeting Corpus, headset channels (AMI Consortium; Carletta et al. 2005).
125
+ - ICSI Meeting Corpus, close-talk channels (Janin et al. 2003).
126
+ - otoSpeech full-duplex processed 141 h and task-oriented 20 h (otoearth).
127
 
128
+ Labels were derived by p99lab from each speaker's activity and word timings, following TurnBench's published annotation scheme.
129
+ No benchmark audio or labels were used for training or calibration: not eot-bench, TurnBench (dev or test, or its
130
+ otoSpeech-turn-104h training set), or MultiPartyTurnBench. MultiPartyTurnBench's dev split was used to choose among candidate models and
131
+ end-of-turn read-outs (see Results). The AMI meetings in MultiPartyTurnBench's real-speech table
132
+ (series ES2002, ES2003, ES2004, ES2005, IS1000, IS1001, TS3003, TS3004) were excluded. An audio-level check of all 154 TurnBench dev and test conversations against every otoSpeech session found 0 duplicates (the same check finds 15 of 40 known overlapping sessions between the two otoSpeech releases). The trunk is unchanged from v1.
 
 
 
133
 
134
+ ## Limits
135
 
136
+ - English only.
137
+ - The 4 kHz band limit of v1 still applies (the stream applies it).
138
+ - The INT output decides between "taking the floor" and "backchannel or laugh". It does not judge whether an interruption is
139
+ polite, and it does not remove echo of your agent's own voice: use acoustic echo cancellation in front of it.
140
+ - Read-out 3 needs a channel per speaker; it cannot see a speaker who has no channel. On noisy channels its speech-activity output is
141
+ less reliable (this release's activity module was trained without noise augmentation; a noise-augmented variant is more robust on our
142
+ noisy dev set but was not faster on MultiPartyTurnBench).
143
+ - Single-channel end-of-turn detection is unchanged from v1 (same score, same limits: pauses inside numbers, letters and email addresses remain the hardest case).
144
 
145
  ## How to credit
146
 
147
+ "turn-1-mini by p99lab", with a link to https://huggingface.co/p99lab/turn-1-mini. Keep the `NOTICE` file (Apache-2.0, section 4),
148
+ which carries the AMI, ICSI and otoSpeech attributions.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
SHA256SUMS CHANGED
@@ -4,3 +4,6 @@ a59a5b627190e7bf52a46dd25026ec8d4d0b01e1b0146643bb39161808c0619e onnx/turn-1-mi
4
  aab623c3df7a494710a9bf650df29b292b76ee2fe0e85b616a57c871d0b993b4 onnx/turn-1-mini.step.int8.onnx
5
  aacf7c34683776d8de46053aefba5516bea2117cd173be2292924a80bd2d1ac9 onnx/turn-1-mini.step.nolp.onnx
6
  e747b182d685c7db489a3ea2e12bdcd65bac506fcddec00ed3cd0bf9f209fd11 onnx/turn-1-mini.step.onnx
 
 
 
 
4
  aab623c3df7a494710a9bf650df29b292b76ee2fe0e85b616a57c871d0b993b4 onnx/turn-1-mini.step.int8.onnx
5
  aacf7c34683776d8de46053aefba5516bea2117cd173be2292924a80bd2d1ac9 onnx/turn-1-mini.step.nolp.onnx
6
  e747b182d685c7db489a3ea2e12bdcd65bac506fcddec00ed3cd0bf9f209fd11 onnx/turn-1-mini.step.onnx
7
+ 020f1d22f5199a007064c269acfbbe6e4707399735b02216915b496a67c6cc03 turn-1-mini-v2.safetensors
8
+ b65a350137d627d4d6532be41f51194d736db40648d8cf6c505aa95a3f981eb7 config.json
9
+ fa7a8d5a1f32aad517cd3eb6ba056d846d389190510bee9b1c0f5f93b507165f dist/p99turn-2.0.0-py3-none-any.whl
config.json CHANGED
@@ -1,15 +1,58 @@
1
  {
2
- "model_type": "turn-1-mini",
3
- "library": "p99turn",
4
- "version": "1.2.3",
5
- "task": "end-of-turn detection",
6
- "language": "en",
7
- "parameters": 5262337,
8
- "sample_rate_hz": 16000,
9
- "bandlimit_hz": 4000,
10
- "frame_s": 0.02,
11
- "step_s": 0.16,
12
- "left_context_frames": 60,
13
- "readout": "any-time",
14
- "weights_file": "turn-1-mini.safetensors"
15
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  {
2
+ "model_type": "turn-1-mini",
3
+ "version": "2.0.0",
4
+ "parameters": 5369033,
5
+ "sample_rate_hz": 16000,
6
+ "bandlimit_hz": 4000,
7
+ "frame_s": 0.02,
8
+ "step_s": 0.16,
9
+ "left_context_frames": 60,
10
+ "outputs": {
11
+ "eot": "P(the speaker's turn is over), per 20 ms frame (read-out 3: a score, not a calibrated probability)",
12
+ "int": "P(this speaker's vocalisation is a floor-taking interruption)",
13
+ "vad": "P(this speaker is speaking)"
14
+ },
15
+ "rest_input": {
16
+ "lags_frames": [
17
+ 0,
18
+ 1,
19
+ 2,
20
+ 3,
21
+ 5,
22
+ 8,
23
+ 12,
24
+ 18,
25
+ 25,
26
+ 35,
27
+ 50
28
+ ],
29
+ "flag": "1 when a REST track is given (other channels, or the agent's playback); 0 = single channel"
30
+ },
31
+ "default_thresholds": {
32
+ "rest_eot": 0.32,
33
+ "rest_eot_readout0": 0.82,
34
+ "single_eot": 0.36,
35
+ "rest_int": 0.7,
36
+ "single_int": 0.74,
37
+ "mptb_dev_selected": {
38
+ "eot_readout3": 0.25,
39
+ "int": 0.8,
40
+ "rule": "MPTB harness, dev FPR budget 0.055 (round 6)"
41
+ },
42
+ "rule": "highest recall at FPR <= 0.10 on p99lab dev (D-MP + D-2P pooled), rising edge + 2 s refractory; rest_eot = head (R6c_cal) read-out 3; rest_eot_readout0 = read-out 0 (one channel + agent playback); single_eot = v1; INT from head_int (R4_cal)"
43
+ },
44
+ "source_checkpoint_sha256": {
45
+ "R6c_cal.pt": "6fbf9ccf1d1be28892667b4b46f1b2aa70f6bbb9b073efd25063e2adeed35300",
46
+ "R4_cal.pt": "a0e56837fabceaa3251528d40afb65b618615e4c4f66180793ba95c370e91553"
47
+ },
48
+ "heads": {
49
+ "head": "R6c_cal (EOT with REST read-out 3 'fast-onset', VAD, own claim)",
50
+ "head_int": "R4_cal (INT, own claim)"
51
+ },
52
+ "rest_eot_readout": {
53
+ "default": 3,
54
+ "3": "fast-onset: (1 - P_speech(own)) x max_other P_claim(now) x (1 - max_other P_claim(now - 1 s)); >= 2 human channels",
55
+ "0": "trained REST correction (Platt-calibrated); used automatically with ONE channel + rest_activity (agent playback)",
56
+ "select": "Turn1MiniV2().stream(n_channels, readout=0|3)"
57
+ }
58
+ }
dist/p99turn-2.0.0-py3-none-any.whl ADDED
Binary file (31.5 kB). View file
 
p99turn/__init__.py CHANGED
@@ -6,8 +6,8 @@ Inference only: no training code lives here.
6
  """
7
  from .audio import SR, agent_context, bandlimit_4k # noqa: F401
8
 
9
- __version__ = "1.2.3"
10
- __all__ = ["Turn1Mini", "Turn1MiniStream", "SR", "bandlimit_4k"]
11
 
12
 
13
  def __getattr__(name): # lazy: importing `p99turn` must not import torch
@@ -15,4 +15,8 @@ def __getattr__(name): # lazy: importing `p99turn` must not
15
  from . import mini
16
 
17
  return getattr(mini, name)
 
 
 
 
18
  raise AttributeError(name)
 
6
  """
7
  from .audio import SR, agent_context, bandlimit_4k # noqa: F401
8
 
9
+ __version__ = "2.0.0"
10
+ __all__ = ["Turn1Mini", "Turn1MiniStream", "Turn1MiniV2", "SR", "bandlimit_4k"]
11
 
12
 
13
  def __getattr__(name): # lazy: importing `p99turn` must not import torch
 
15
  from . import mini
16
 
17
  return getattr(mini, name)
18
+ if name in ("Turn1MiniV2", "GroupStream"):
19
+ from . import mini2
20
+
21
+ return getattr(mini2, name)
22
  raise AttributeError(name)
p99turn/mini2.py ADDED
@@ -0,0 +1,375 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """turn-1-mini v2 (p99turn 2.0, DRAFT, not released; round-6 head supported): the v1 trunk (unchanged) + a v2 head with three outputs per 20 ms frame:
2
+ eot P(this speaker's turn is over) (calibrated on p99lab dev data; see the model card for default thresholds)
3
+ int P(this speaker's new vocalisation is a floor-taking interruption, not a backchannel / laugh)
4
+ vad P(this speaker is speaking)
5
+ and an optional REST input: the activity of everyone else (other channels of the same call, or the agent's own playback).
6
+ Without it (single channel) the model runs exactly like v1 in cost. Audio only, causal, 160 ms steps, no look-ahead.
7
+
8
+ from p99turn import Turn1MiniV2
9
+ m = Turn1MiniV2() # P99TURN_WEIGHTS=/local/dir or the Hugging Face repo
10
+ s = m.stream() # one channel: out = s.push([chunk]) -> out["eot"][0], out["int"][0]
11
+ s = m.stream(n_channels=3) # three speakers: out = s.push([c1, c2, c3]); each channel's REST = the others
12
+ s.push([chunk], rest_activity=agent_playing) # one human channel + the agent's playback activity per 20 ms frame
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import math
17
+
18
+ import numpy as np
19
+ import torch
20
+ import torch.nn as nn
21
+ import torch.nn.functional as F
22
+
23
+ from . import weights as W
24
+ from .audio import bandlimit_4k
25
+ from .mini import CHUNK_MEL, HOP, N_FFT, N_MELS, Trunk, _pooled_h6
26
+
27
+ V2_FILE = "turn-1-mini-v2.safetensors"
28
+
29
+ LAGS = (0, 1, 2, 3, 5, 8, 12, 18, 25, 35, 50)
30
+ R = len(LAGS) + 1
31
+ R_CLAIM = len(LAGS) # round 4: + max over the other channels of their own-only floor-claim probability at the same lags
32
+
33
+
34
+ class HeadV2(nn.Module):
35
+ def __init__(self, hid=256, zdim=128, n_proj=0, claim_rest=False):
36
+ super().__init__()
37
+ self.n_proj, self.claim_rest = n_proj, claim_rest
38
+ self.ln = nn.LayerNorm(1024)
39
+ self.fc1 = nn.Linear(1024, hid)
40
+ self.eot = nn.Linear(hid, 1)
41
+ self.vad = nn.Linear(hid, 1)
42
+ self.fc2 = nn.Linear(hid + R + (R_CLAIM if claim_rest else 0), zdim)
43
+ if claim_rest:
44
+ self.claim = nn.Linear(hid, 1) # own-only floor-claim logit (shared with the other channels)
45
+ self.fc3 = nn.Linear(zdim, 2 + n_proj)
46
+ nn.init.zeros_(self.fc3.weight); nn.init.zeros_(self.fc3.bias)
47
+ self.register_buffer("cal", torch.tensor([1.0, 0.0, 1.0, 0.0])) # a_e, b_e, a_i, b_i
48
+ self.register_buffer("readout", torch.tensor(0.0)) # REST-mode EOT: 0 = eot0 + d, 1 = logit(p_shift) (round 3)
49
+
50
+ def own(self, x):
51
+ h = F.gelu(self.fc1(self.ln(x)))
52
+ return h, self.vad(h).squeeze(-1)
53
+
54
+ def fuse(self, h, r):
55
+ """EOT: v1's score when no REST input is given (flag 0: exactly v1, uncalibrated); with REST (flag 1) the v2 correction d is added
56
+ and the calibration (a_e, b_e) applies. INT: calibrated in both modes."""
57
+ eot, it, _ = self.fuse_all(h, r)
58
+ return eot, it
59
+
60
+ def fuse_all(self, h, r):
61
+ o = self.fc3(F.gelu(self.fc2(torch.cat([h, r], -1))))
62
+ eot0 = self.eot(h).squeeze(-1)
63
+ flag = r[..., -1]
64
+ proj = o[..., 2:]
65
+ rest_eot = eot0 + o[..., 0]
66
+ if self.n_proj:
67
+ pp = torch.sigmoid(proj)
68
+ shift = pp[..., 5:8].mean(-1) * (1 - pp[..., 0:4]).mean(-1)
69
+ rest_eot = torch.where(self.readout > 0.5, torch.logit(shift.clamp(1e-6, 1 - 1e-6)), rest_eot)
70
+ eot = (1 - flag) * eot0 + flag * (self.cal[0] * rest_eot + self.cal[1])
71
+ return eot, self.cal[2] * o[..., 1] + self.cal[3], proj
72
+
73
+
74
+ class _Pick(nn.Module):
75
+ def __init__(self, k):
76
+ super().__init__()
77
+ self.k = k
78
+
79
+ def forward(self, haug):
80
+ return haug[..., self.k:self.k + 1]
81
+
82
+
83
+ class HeadV6(HeadV2):
84
+ """Round-6 EOT / VAD head: v1's frozen first layer and EOT output (single channel = v1 exactly), a per-frame activity module
85
+ LN([h2 | h]) -> 64 -> GELU -> (P(speech), P(claim)), and the REST correction / INT layers. own() returns haug = [h | vad | claim logits].
86
+ REST-mode EOT read-out (buffer `readout`): 0 = trained correction (Platt-calibrated); 2 = fast = (1 - P_speech(own)) x max_other P_claim;
87
+ 3 = fast-onset = fast x (1 - max_other P_claim 1.0 s ago) (the release default with >= 2 human channels)."""
88
+
89
+ def __init__(self, hid=256, zdim=128):
90
+ super().__init__(hid=hid, zdim=zdim, n_proj=0, claim_rest=True)
91
+ del self.vad, self.claim
92
+ self.aln = nn.LayerNorm(512)
93
+ self.a1 = nn.Linear(512, 64)
94
+ self.a2 = nn.Linear(64, 2)
95
+ self.vad, self.claim = _Pick(hid), _Pick(hid + 1)
96
+ self.hid = hid
97
+
98
+ def own(self, x):
99
+ h = F.gelu(self.fc1(self.ln(x)))
100
+ z = self.a2(F.gelu(self.a1(self.aln(torch.cat([x[..., :256], h], -1)))))
101
+ return torch.cat([h, z], -1), z[..., 0]
102
+
103
+ def fuse_all(self, haug, r):
104
+ h = haug[..., :self.hid]
105
+ o = self.fc3(F.gelu(self.fc2(torch.cat([h, r], -1))))
106
+ eot0 = self.eot(h).squeeze(-1)
107
+ flag = r[..., -1]
108
+ if float(self.readout) in (2.0, 3.0):
109
+ fast = (1 - torch.sigmoid(haug[..., self.hid])) * r[..., len(LAGS)]
110
+ if float(self.readout) == 3.0:
111
+ fast = fast * (1 - r[..., len(LAGS) + LAGS.index(50)])
112
+ eot = (1 - flag) * eot0 + flag * torch.logit(fast.clamp(1e-6, 1 - 1e-6))
113
+ else:
114
+ eot = (1 - flag) * eot0 + flag * (self.cal[0] * (eot0 + o[..., 0]) + self.cal[1])
115
+ return eot, self.cal[2] * o[..., 1] + self.cal[3], o[..., 2:]
116
+
117
+
118
+ class _Slice256(nn.Module):
119
+ """A 256-input head (the INT head) used behind a HeadV6 that passes haug (h + 2 logits)."""
120
+
121
+ def __init__(self, hd):
122
+ super().__init__()
123
+ self.hd = hd
124
+ self.claim_rest = hd.claim_rest
125
+
126
+ def vad(self, haug):
127
+ return self.hd.vad(haug[..., :256])
128
+
129
+ def claim(self, haug):
130
+ return self.hd.claim(haug[..., :256])
131
+
132
+ def fuse(self, haug, r):
133
+ return self.hd.fuse(haug[..., :256], r)
134
+
135
+
136
+ def _rest_max(x):
137
+ K, T = x.shape
138
+ top2 = x.topk(2, dim=0)
139
+ is_max = x >= top2.values[0:1]
140
+ return torch.where(is_max, top2.values[1:2].expand(K, T), top2.values[0:1].expand(K, T))
141
+
142
+
143
+ def rest_features(vad_p: torch.Tensor, flag: torch.Tensor | None = None, claim_p: torch.Tensor | None = None):
144
+ """vad_p [K, T] (probabilities of the K channels of one recording) -> r [K, T, R (+ R_CLAIM)]. Channel k's rest = max over j != k.
145
+ The flag stays the LAST column."""
146
+ K, T = vad_p.shape
147
+ if K < 2:
148
+ return vad_p.new_zeros(K, T, R + (R_CLAIM if claim_p is not None else 0))
149
+ if claim_p is not None:
150
+ rc = _rest_max(claim_p)
151
+ fc = [F.pad(rc, (L, 0))[:, :T] for L in LAGS]
152
+ top2 = vad_p.topk(2, dim=0)
153
+ is_max = vad_p >= top2.values[0:1]
154
+ rest = torch.where(is_max, top2.values[1:2].expand(K, T), top2.values[0:1].expand(K, T))
155
+ feats = []
156
+ for L in LAGS:
157
+ feats.append(F.pad(rest, (L, 0))[:, :T])
158
+ r = torch.stack(feats + (fc if claim_p is not None else []) + [torch.ones_like(rest)], -1)
159
+ if flag is not None:
160
+ r = r * flag.view(K, 1, 1)
161
+ return r
162
+
163
+
164
+ class TurnV2(nn.Module):
165
+ def __init__(self, n_proj=0, claim_rest=False):
166
+ super().__init__()
167
+ self.trunk = Trunk()
168
+ self.head = HeadV2(n_proj=n_proj, claim_rest=claim_rest)
169
+
170
+ def readout(self, wav=None, mel=None):
171
+ """-> x [B, T20, 1024]. mel: [B, 80, T10] already normalised (LogMel output)."""
172
+ t = self.trunk
173
+ m = t.mel(wav) if mel is None else mel
174
+ x = t.sub(m).transpose(1, 2)
175
+ B, T = x.shape[:2]
176
+ i = torch.arange(T, device=x.device)
177
+ dist = (i[:, None] - i[None, :]).float()
178
+ allowed = (dist >= 0) & (dist < t.left_ctx)
179
+ mask = (-t.slopes[:, None, None] * dist[None]).masked_fill(~allowed[None], float("-inf")).repeat(B, 1, 1).to(x.dtype)
180
+ hs = []
181
+ for b in t.blocks:
182
+ x = b(x, mask)
183
+ hs.append(x)
184
+ hs[-1] = t.norm(hs[-1])
185
+ return torch.cat([hs[1], hs[3], hs[5], _pooled_h6(hs[5])], -1)
186
+
187
+ def group_forward(self, xs, flag=None):
188
+ """xs [K, T, 1024] (the K channels of one recording, same frames) -> eot, int, vad logits [K, T]."""
189
+ eot, it, vad, _ = self.group_forward_all(xs, flag)
190
+ return eot, it, vad
191
+
192
+ def group_forward_all(self, xs, flag=None, return_claim=False):
193
+ h, vad = self.head.own(xs)
194
+ cl = self.head.claim(h).squeeze(-1) if self.head.claim_rest else None
195
+ r = rest_features(torch.sigmoid(vad).detach(), flag, torch.sigmoid(cl).detach() if cl is not None else None)
196
+ eot, it, proj = self.head.fuse_all(h, r)
197
+ if return_claim:
198
+ return eot, it, vad, proj, cl
199
+ return eot, it, vad, proj
200
+
201
+
202
+
203
+ class Turn1MiniV2(nn.Module):
204
+ """Release model: one trunk, head `head` (EOT, VAD) and head `head_int` (INT, own-only claim shared as REST). The two heads' first layer
205
+ (v1's LayerNorm + Linear) is the same frozen v1 layer; it is stored once and shared."""
206
+
207
+ def __init__(self, weights=None, *, revision=None, device=None) -> None:
208
+ super().__init__()
209
+ from safetensors.torch import load_file
210
+ sd = load_file(str(W.resolve(V2_FILE, weights, revision)))
211
+ self.trunk = Trunk()
212
+ self.r6 = "head.a1.weight" in sd # round-6 EOT / VAD head
213
+ self.head = HeadV6() if self.r6 else HeadV2(n_proj=sd["head.fc3.weight"].shape[0] - 2, claim_rest="head.claim.weight" in sd)
214
+ self.head_int = HeadV2(n_proj=sd["head_int.fc3.weight"].shape[0] - 2, claim_rest="head_int.claim.weight" in sd)
215
+ self.head_int.ln, self.head_int.fc1, self.head_int.eot = self.head.ln, self.head.fc1, self.head.eot # shared v1 layer
216
+ for k in list(sd):
217
+ if k.startswith("head_int.") and k.split(".")[1] in ("ln", "fc1", "eot"):
218
+ sd.pop(k)
219
+ self.load_state_dict(sd, strict=False)
220
+ missing = [k for k in self.state_dict() if k not in sd and not (k.startswith("head_int.") and k.split(".")[1] in ("ln", "fc1", "eot"))]
221
+ assert not missing, missing
222
+ self.heads = [self.head, _Slice256(self.head_int) if self.r6 else self.head_int]
223
+ self.default_readout = float(self.head.readout) # stored in the weights file (3 = fast-onset)
224
+ self.to(torch.device(device or "cpu")).eval()
225
+
226
+ def stream(self, n_channels: int = 1, lowpass: bool = True, readout: float | None = None) -> "GroupStream":
227
+ """readout: REST-mode EOT read-out. Default: the file's (fast-onset, 3) with >= 2 human channels. With ONE channel plus
228
+ rest_activity (the agent's playback) the fast read-outs have no claim input, so the trained correction (0) is used."""
229
+ if readout is None:
230
+ readout = self.default_readout if n_channels >= 2 else 0.0
231
+ return GroupStream(self, n_channels, lowpass, readout)
232
+
233
+
234
+ STEP = CHUNK_MEL * HOP
235
+ HIST = N_FFT - HOP + 64
236
+ MAXLAG = max(LAGS)
237
+
238
+
239
+ class _Chan:
240
+ def __init__(self, m: TurnV2):
241
+ t = m.trunk
242
+ L, d, H, W = len(t.blocks), t.norm.normalized_shape[0], t.heads_n, t.left_ctx
243
+ z = torch.zeros
244
+ self.pending = np.zeros(0, np.float32)
245
+ self.tail = np.zeros(HIST, np.float32)
246
+ self.conv1, self.conv2 = z(1, N_MELS, 2), z(1, d, 2)
247
+ self.k, self.v = z(L, H, W, d // H), z(L, H, W, d // H)
248
+ self.k_pos = torch.full((W,), -1e9)
249
+ self.h6 = z(60, d)
250
+ self.t0 = 0.0
251
+ self.vad_hist = torch.zeros(MAXLAG + 8)
252
+ self.claim_hist = torch.zeros(MAXLAG + 8)
253
+ self.rest_hist = np.zeros(MAXLAG + 8, np.float32)
254
+
255
+
256
+ class GroupStream:
257
+ def __init__(self, model: TurnV2, n_channels: int = 1, lowpass: bool = True, readout: float | None = None):
258
+ self.m, self.K, self.lp = model.eval(), n_channels, lowpass
259
+ self.readout = readout
260
+ t = model.trunk
261
+ self.L, self.d, self.H, self.W = len(t.blocks), t.norm.normalized_shape[0], t.heads_n, t.left_ctx
262
+ self.dh = self.d // self.H
263
+ self.reset()
264
+
265
+ def reset(self):
266
+ self.ch = [_Chan(self.m) for _ in range(self.K)]
267
+ n = CHUNK_MEL // 2
268
+ Hh = MAXLAG + 8
269
+ self.idx = torch.from_numpy((Hh - n + np.arange(n))[:, None] - np.array(LAGS)[None, :]) # [8, 11] into the history
270
+ self.cr = bool(getattr(self.m.head, "claim_rest", False))
271
+ self.r0 = torch.zeros(n, R + (R_CLAIM if self.cr else 0))
272
+ # steady-state attention bias (all W cached positions valid and contiguous): constant, computed once
273
+ t = self.m.trunk
274
+ q_pos = torch.arange(n, dtype=torch.float32) + self.W
275
+ all_pos = torch.arange(self.W + n, dtype=torch.float32)
276
+ dist = q_pos[:, None] - all_pos[None, :]
277
+ allowed = (dist >= 0) & (dist < self.W)
278
+ self.bias_ss = (-t.slopes[:, None, None] * dist[None]).masked_fill(~allowed[None], float("-inf"))[None]
279
+
280
+ def _readout(self, c: _Chan, mel): # mel [1, 80, 16] -> x [8, 1024]
281
+ t = self.m.trunk
282
+ c1, c2 = t.sub[0], t.sub[2]
283
+ x1 = torch.cat([c.conv1, mel], -1)
284
+ y1 = F.gelu(F.conv1d(x1, c1.weight, c1.bias))
285
+ x2 = torch.cat([c.conv2, y1], -1)
286
+ x = F.gelu(F.conv1d(x2, c2.weight, c2.bias, stride=2)).transpose(1, 2)
287
+ n = x.shape[1]
288
+ q_pos = c.t0 + torch.arange(n, dtype=torch.float32)
289
+ all_pos = torch.cat([c.k_pos, q_pos])
290
+ if c.t0 >= self.W and n == self.bias_ss.shape[2]:
291
+ bias = self.bias_ss
292
+ else:
293
+ dist = q_pos[:, None] - all_pos[None, :]
294
+ allowed = (dist >= 0) & (dist < self.W)
295
+ bias = (-t.slopes[:, None, None] * dist[None]).masked_fill(~allowed[None], float("-inf"))[None]
296
+ nk, nv, taps = [], [], []
297
+ for li, blk in enumerate(t.blocks):
298
+ y = blk.n1(x)
299
+ qkv = F.linear(y, blk.attn.in_proj_weight, blk.attn.in_proj_bias).view(1, n, 3, self.H, self.dh).permute(2, 0, 3, 1, 4)
300
+ q, k, v = qkv[0], qkv[1], qkv[2]
301
+ K_, V_ = torch.cat([c.k[li][None], k], 2), torch.cat([c.v[li][None], v], 2)
302
+ o = F.scaled_dot_product_attention(q, K_, V_, attn_mask=bias).transpose(1, 2).reshape(1, n, self.d)
303
+ x = x + blk.attn.out_proj(o)
304
+ x = x + blk.ff(blk.n2(x))
305
+ if li == self.L - 1:
306
+ x = t.norm(x)
307
+ taps.append(x)
308
+ nk.append(K_[0, :, -self.W:]); nv.append(V_[0, :, -self.W:])
309
+ h2, h4, h6 = taps[1][0], taps[3][0], taps[5][0]
310
+ buf = torch.cat([c.h6, h6], 0) # [60 + n, d]; frame i of the step uses rows 1+i .. 50+i
311
+ cs = torch.cumsum(buf, 0)
312
+ pooled = (cs[50:50 + n] - cs[0:n]) / 50 # sum of rows 1+i .. 50+i
313
+ c.conv1, c.conv2 = x1[..., -2:], x2[..., -2:]
314
+ c.k, c.v, c.k_pos, c.h6, c.t0 = torch.stack(nk), torch.stack(nv), all_pos[-self.W:], buf[-60:], c.t0 + n
315
+ return torch.cat([h2, h4, h6, pooled], -1)
316
+
317
+ @torch.inference_mode()
318
+ def push(self, chunks, rest_activity=None):
319
+ """chunks: list of K float32 arrays (16 kHz). rest_activity (single channel only): optional per-20-ms-frame activity of the
320
+ other party (e.g. the agent's own playback, 0..1) for the frames this call finishes; None = no REST input.
321
+ Models with two heads (EOT/VAD head + INT head, `heads`) share one trunk read-out per channel and step."""
322
+ for c, x in zip(self.ch, chunks):
323
+ c.pending = np.concatenate([c.pending, np.asarray(x, np.float32)])
324
+ out = {"eot": [[] for _ in range(self.K)], "int": [[] for _ in range(self.K)], "vad": [[] for _ in range(self.K)]}
325
+ heads = getattr(self.m, "heads", [self.m.head])
326
+ nH = len(heads)
327
+ if self.readout is not None:
328
+ self.m.head.readout.fill_(float(self.readout))
329
+ for c in self.ch:
330
+ if not hasattr(c, "vh"):
331
+ c.vh = [torch.zeros(MAXLAG + 8) for _ in heads]; c.chh = [torch.zeros(MAXLAG + 8) for _ in heads]
332
+ nstep = min(len(c.pending) for c in self.ch) // STEP
333
+ for s in range(nstep):
334
+ H = [[None] * nH for _ in self.ch]; VP = [[None] * nH for _ in self.ch]
335
+ for ci, c in enumerate(self.ch):
336
+ seg, c.pending = c.pending[:STEP], c.pending[STEP:]
337
+ win = np.concatenate([c.tail, seg]); c.tail = win[-HIST:]
338
+ win = bandlimit_4k(win)[-(N_FFT - HOP + STEP):] if self.lp else win[-(N_FFT - HOP + STEP):]
339
+ mel = self.m.trunk.mel(torch.from_numpy(np.ascontiguousarray(win))[None], pad=False)
340
+ x = self._readout(c, mel)
341
+ for q, hd in enumerate(heads):
342
+ if q == 0:
343
+ h, vad = hd.own(x) # the heads share v1's frozen first layer: computed once
344
+ else:
345
+ vad = hd.vad(h).squeeze(-1)
346
+ H[ci][q] = h; VP[ci][q] = torch.sigmoid(vad)
347
+ if self.K > 1:
348
+ c.vh[q] = torch.cat([c.vh[q][len(vad):], VP[ci][q]])
349
+ if getattr(hd, "claim_rest", False):
350
+ c.chh[q] = torch.cat([c.chh[q][len(vad):], torch.sigmoid(hd.claim(h).squeeze(-1))])
351
+ for k, c in enumerate(self.ch):
352
+ res = []
353
+ for q, hd in enumerate(heads):
354
+ cr = getattr(hd, "claim_rest", False)
355
+ n = len(VP[k][q])
356
+ if self.K > 1:
357
+ parts = [torch.stack([o.vh[q] for j, o in enumerate(self.ch) if j != k]).amax(0)[self.idx]]
358
+ if cr:
359
+ parts.append(torch.stack([o.chh[q] for j, o in enumerate(self.ch) if j != k]).amax(0)[self.idx])
360
+ r = torch.cat(parts + [torch.ones(len(self.idx), 1)], 1)
361
+ elif rest_activity is not None:
362
+ if q == 0:
363
+ ra = np.asarray(rest_activity, np.float32)[8 * s: 8 * s + n]
364
+ ra = np.concatenate([ra, np.full(n - len(ra), ra[-1] if len(ra) else 0.0, np.float32)])
365
+ c.rest_hist = np.concatenate([c.rest_hist[n:], ra])
366
+ parts = [torch.from_numpy(c.rest_hist)[self.idx]]
367
+ if cr:
368
+ parts.append(torch.zeros(len(self.idx), R_CLAIM))
369
+ r = torch.cat(parts + [torch.ones(len(self.idx), 1)], 1)
370
+ else:
371
+ r = torch.zeros(n, R + (R_CLAIM if cr else 0))
372
+ res.append(hd.fuse(H[k][q], r))
373
+ out["eot"][k].append(torch.sigmoid(res[0][0])); out["int"][k].append(torch.sigmoid(res[-1][1])); out["vad"][k].append(VP[k][0])
374
+ cat = lambda L: torch.cat(L).numpy() if L else np.zeros(0, np.float32) # noqa: E731
375
+ return {k: [cat(v) for v in out[k]] for k in out}
pyproject.toml CHANGED
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
 
5
  [project]
6
  name = "p99turn"
7
- version = "1.2.3"
8
  description = "p99lab turn-1-mini: a small streaming end-of-turn detection model (inference only)."
9
  readme = "README.md"
10
  license = { file = "LICENSE" }
 
4
 
5
  [project]
6
  name = "p99turn"
7
+ version = "2.0.0"
8
  description = "p99lab turn-1-mini: a small streaming end-of-turn detection model (inference only)."
9
  readme = "README.md"
10
  license = { file = "LICENSE" }
turn-1-mini-v2.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:020f1d22f5199a007064c269acfbbe6e4707399735b02216915b496a67c6cc03
3
+ size 21485844