Jr23xd23 commited on
Commit
f730521
·
verified ·
1 Parent(s): 1a39499

RightNow Duplex v0

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
.gitattributes CHANGED
@@ -33,3 +33,9 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ assets/prompt_af_heart.wav filter=lfs diff=lfs merge=lfs -text
37
+ assets/prompt_af_heart_short.wav filter=lfs diff=lfs merge=lfs -text
38
+ samples/formal_fallacies.wav filter=lfs diff=lfs merge=lfs -text
39
+ samples/navigate.wav filter=lfs diff=lfs merge=lfs -text
40
+ samples/object_counting.wav filter=lfs diff=lfs merge=lfs -text
41
+ samples/web_of_lies.wav filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -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.
NOTICE ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ RightNow Duplex v0
2
+ Copyright 2026 RightNow AI
3
+
4
+ Licensed under the Apache License, Version 2.0 (see LICENSE).
5
+
6
+ This work builds on the following. None of it is included in this repository
7
+ except the files named below.
8
+
9
+ Step-Audio R1.1 (stepfun-ai/Step-Audio-R1.1), by StepFun. Apache-2.0.
10
+ The speech model this layer serves. Used unchanged. Not included.
11
+ serving/chat_template.jinja is the chat template of its model card, unchanged.
12
+
13
+ Step-Audio R1 (github.com/stepfun-ai/Step-Audio-R1), by StepFun. Apache-2.0.
14
+ controller/encoder/teacher.py contains its AudioEncoder and log-mel code,
15
+ changed to use scaled dot-product attention and a padding mask.
16
+ serving/baseline_client.py follows its released client.
17
+
18
+ Step-Audio 2 (github.com/stepfun-ai/Step-Audio2) and the token2wav weights of
19
+ stepfun-ai/Step-Audio-2-mini, by StepFun. Apache-2.0.
20
+ Turn audio tokens into sound. Imported unchanged. Not included.
21
+ serving/speech_out.py contains the warm-up token list of its streaming example.
22
+
23
+ Kokoro-82M (hexgrad/Kokoro-82M). Apache-2.0.
24
+ Made the voices of the training dialogues, and the two recordings in assets/
25
+ (voice pack af_heart). Not included.
26
+
27
+ Qwen3-32B (Qwen/Qwen3-32B). Apache-2.0.
28
+ Wrote the text of the training dialogues. Not included.
29
+
30
+ Big Bench Audio (ArtificialAnalysis/big_bench_audio). MIT.
31
+ The test questions. Not included.
32
+
33
+ Whisper large-v3 (openai/whisper-large-v3). Apache-2.0.
34
+ Transcribed the reply audio for the "as heard" scores. Not included.
README.md ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - en
5
+ pipeline_tag: audio-to-audio
6
+ tags:
7
+ - speech
8
+ - speech-to-speech
9
+ - full-duplex
10
+ - turn-taking
11
+ - voice-agent
12
+ ---
13
+
14
+ # RightNow Duplex v0
15
+
16
+ **It listens while you talk. It thinks before it answers. You hear it one second after you stop.**
17
+
18
+ RightNow Duplex is an open, full-duplex speech layer with reasoning. One live audio connection and no push to talk: it knows when you have finished, it lets you interrupt, and it runs on your own GPUs.
19
+
20
+ <sub>Preview release by RightNow AI. Apache-2.0. Runs on the open model Step-Audio R1.1 by StepFun.</sub>
21
+
22
+ ## Hear it
23
+
24
+ Four replies to spoken reasoning questions, exactly as the test caller recorded them. You hear the lead-in first, then the answer.
25
+
26
+ | Question type | Reply |
27
+ |---|---|
28
+ | Is the argument valid? | <audio controls src="https://huggingface.co/RightNowAI/duplex-v0/resolve/main/samples/formal_fallacies.wav"></audio> |
29
+ | Do you return to the starting point? | <audio controls src="https://huggingface.co/RightNowAI/duplex-v0/resolve/main/samples/navigate.wav"></audio> |
30
+ | How many are there? | <audio controls src="https://huggingface.co/RightNowAI/duplex-v0/resolve/main/samples/object_counting.wav"></audio> |
31
+ | Who tells the truth? | <audio controls src="https://huggingface.co/RightNowAI/duplex-v0/resolve/main/samples/web_of_lies.wav"></audio> |
32
+
33
+ ## What it does
34
+
35
+ - **Knows when you have finished.** After 240 ms of quiet the speech model itself is asked, and answers with one token: yes or no. No extra model, no training.
36
+ - **Never talks over you by mistake.** A reply starts silently at once. If you go on speaking, it is withdrawn and you never hear it.
37
+ - **Reasons, then speaks.** Each reply thinks first, as text, and the speech opens with that reasoning already in it.
38
+ - **Fills the silence.** While it reasons it says one short sentence, such as "Let me check if the argument is valid."
39
+ - **Lets you interrupt.** 240 ms of your speech stops a reply. An optional small controller tells an "mm-hm" from an interruption.
40
+
41
+ ## Measured
42
+
43
+ Measured on 2026-11-30 on 100 questions of Big Bench Audio, four callers at a time per copy of the model, one GPU per copy. The caller sends audio in real time, as a microphone would, and every time is counted from the moment the question ends. Scoring is our own parser, not the leaderboard's judge, so these figures cannot be set beside leaderboard figures.
44
+
45
+ | | Result |
46
+ |---|---|
47
+ | Answers right, read from the reply's text | 96 of 100 |
48
+ | Answers right, as heard: Whisper large-v3 transcribes the reply audio | 86 of 100 |
49
+ | First audio after the caller stops | median 1.0 s, 90th percentile 1.3 s |
50
+ | The answer itself after the caller stops | median 9.2 s |
51
+ | Questions where the caller heard a false start | 2 of 100 |
52
+ | Word errors in the spoken reply, by Whisper | 1.4% of 1,396 words |
53
+ | The same test with no reasoning before the speech (text score) | 65 of 100 |
54
+
55
+ The optional controller, on held-out synthetic dialogues with voices and scenarios it did not see in training:
56
+
57
+ | | Result |
58
+ |---|---|
59
+ | An "mm-hm" not treated as an interruption | 871 of 989 |
60
+ | Interruption caught | 507 of 566 |
61
+
62
+ Every number, with what failed, is in [RESULTS.md](RESULTS.md).
63
+
64
+ ## Run it
65
+
66
+ You need the Step-Audio R1.1 weights (`stepfun-ai/Step-Audio-R1.1`), StepFun's released vLLM image, and the Step-Audio 2 audio decoder (`stepfun-ai/Step-Audio2`, `stepfun-ai/Step-Audio-2-mini`).
67
+
68
+ ```bash
69
+ pip install -r requirements.txt
70
+
71
+ # 1. the speech model behind its released vLLM image (the flags, and the reason for each, are in the script)
72
+ MODEL_DIR=/path/to/Step-Audio-R1.1 bash serving/launch_vllm.sh
73
+
74
+ # 2. the duplex endpoint, in the configuration measured above
75
+ python -m serving.server --reply-prefix '<tts_start>' --think-first \
76
+ --judge-prompt v1 --lead-in --lead-in-after-ms 1200 --lead-in-max-tokens 300 \
77
+ --step-audio2-dir /path/to/Step-Audio2 \
78
+ --token2wav-dir /path/to/Step-Audio-2-mini/token2wav \
79
+ --prompt-wav assets/prompt_af_heart.wav
80
+
81
+ # optional: the controller, for backchannels
82
+ # --encoder-ckpt checkpoints/encoder.safetensors --controller-ckpt checkpoints/controller.safetensors
83
+ ```
84
+
85
+ Then talk to it: open `ws://127.0.0.1:8765/ws`, send `{"type": "session.start", "endpointing": "judge"}`, then 80 ms frames of 16 kHz 16-bit mono audio. Audio comes back at 24 kHz with transcript events. `eval/ws_client.py` is a complete caller.
86
+
87
+ No GPU at hand? `python -m tests.test_listen_think` runs the endpoint's logic against a fake model.
88
+
89
+ ## In this repository
90
+
91
+ | Path | What |
92
+ |---|---|
93
+ | `serving/` | The WebSocket endpoint |
94
+ | `checkpoints/` | Two small models trained by RightNow AI, as safetensors: a streaming audio encoder (38.7M parameters) and a turn controller (89.0M parameters) |
95
+ | `controller/`, `data/` | Their training code, and the recipe for the synthetic dialogue data |
96
+ | `eval/`, `tools/`, `tests/` | The measurements and the scripts that produced them |
97
+ | `samples/`, `assets/` | The four replies above, and two synthetic voice prompts |
98
+
99
+ ## Limits
100
+
101
+ This is a preview. Know these before you build on it.
102
+
103
+ - **The answer itself takes about 9 s.** You hear the lead-in after one second. Then there is a silence until the reasoning is done.
104
+ - **One-word answers are thin in the audio.** The model gives a lone word such as "ten" very little sound. That is the gap between 96 and 86 above.
105
+ - **One caller per GPU at this latency.** Two streams had one audible gap, four streams stuttered.
106
+ - **English and synthetic callers only.** One person has listened to a sample of the replies.
107
+ - **The 1.2 s wait before the lead-in was set from this test's own pauses.** Other speech may need another value (`--lead-in-after-ms`).
108
+ - **The controller cannot decide when to start.** It starts inside 258 of 580 mid-sentence pauses, so the endpoint asks the speech model instead.
109
+ - Written and not measured: keeping an interrupted reply in the conversation (`--keep-interrupted`).
110
+ - Tried and switched off: reasoning while the caller is still speaking. Without training it cost accuracy.
111
+
112
+ The voice of the replies comes from a prompt recording. The two in `assets/` are synthetic voices. Do not use a recording of a real person without their consent.
113
+
114
+ ## Licence and credit
115
+
116
+ Apache-2.0. RightNow Duplex runs on Step-Audio R1.1 by StepFun, used unchanged and not included here. `NOTICE` lists everything this work builds on, all of it Apache-2.0 or MIT. The methods have published authors: reasoning in a speech model and speaking while reasoning (StepFun), speculative end-of-turn detection, and reasoning while listening (SHANKS, Chronological Thinking). This repository is an open implementation with its measurements.
117
+
118
+ ## About RightNow AI
119
+
120
+ Bring any Hugging Face model. RightNow AI tunes it down to the GPU kernel and hosts it on private infrastructure, with zero data retention by default. RightNow AI is a YC-backed GPU research lab.
121
+
122
+ https://www.rightnowai.co
RESULTS.md ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Results
2
+
3
+ Everything here was measured on 2026-11-30 (UTC) on one server with eight GPUs, one copy of Step-Audio R1.1 per GPU. Nothing is estimated. What failed is listed as plainly as what worked.
4
+
5
+ How to read the benchmark figures: the test is 100 questions of Big Bench Audio (ArtificialAnalysis/big_bench_audio, MIT), 25 per category. The caller sends the question in real time and waits. The reply is scored by our own parser (the last valid or invalid, yes or no, or number in the reply), not by the leaderboard's judge, so these figures cannot be set beside leaderboard figures. "Text" means the parser read the reply's text. "As heard" means Whisper large-v3 transcribed the reply's audio and the parser read that transcript. Whisper makes errors of its own, most of all on a lone short word, so "as heard" is a lower bound on what a person hears.
6
+
7
+ ## The duplex layer
8
+
9
+ Four callers at a time per copy of the model. Times are counted from the end of the question on the caller's clock.
10
+
11
+ | Configuration | Right, text | Right, as heard | First audio, median / p90 | Answer itself, median | Questions with an audible false start |
12
+ |---|---|---|---|---|---|
13
+ | Reply opened for speech directly, turn committed by the caller at the end of the question | 65 | not measured | not measured | not measured | not applicable |
14
+ | The model decides the end of turn, speech directly | 65 | not measured | not measured | not measured | 35 |
15
+ | The model decides, reasoning then speech | 95 | 74 | 11.2 / 31.4 s | 11.2 s | 1 |
16
+ | The same, with a lead-in played at once | 95 | not measured | 1.0 / 1.2 s | 12.9 s | 25 |
17
+ | The same, lead-in played only after 1.2 s of quiet, up to 150 tokens | 96 | 69 | 1.0 / 1.2 s | 11.7 s | 2 |
18
+ | **The same, lead-in up to 300 tokens (the configuration in the README)** | **96** | **86** | **1.0 / 1.3 s** | 9.2 s | 2 |
19
+
20
+ - The lead-in does not change how often the answer is right. It changes when the caller first hears the model.
21
+ - Played at once, the lead-in is heard in the pauses inside a question. The pauses of the 100 questions were measured: 788 pauses of 240 ms or more, median 480 ms, 90th percentile 960 ms, longest 1,440 ms, six of 1.2 s or more. So the lead-in waits for 1.2 s of quiet. That value comes from this test's own pauses.
22
+ - With 150 tokens the audio of longer lead-ins was cut off. 300 tokens fixed that: word errors in the whole spoken reply fell from 12.8% to 1.4% (1,396 words, 82 of 100 clips without an error).
23
+ - All 100 replies had a lead-in, 13 words at the median. None states an answer.
24
+ - The gap between "text" and "as heard" is the answer word. The model gives a lone word very little audio, down to 0.16 s. It is not the audio decoder: the same short token runs decoded two ways give audio of the same length.
25
+
26
+ ## The model as its own end-of-turn judge
27
+
28
+ 100 held-out caller turns of our synthetic dialogues, three at a time. "Clean" turns are those where the caller did not hear the model before finishing.
29
+
30
+ | Who decides when to answer | Clean turns | First audio, median / p90 | Turns where the caller heard the model early |
31
+ |---|---|---|---|
32
+ | A fixed 640 ms of silence | 96 | 1,523 / 1,709 ms | 4 |
33
+ | The small controller | 44 | 1,258 / 1,737 ms | 55 |
34
+ | The speech model, asked yes or no (prompt v1) | 95 | 1,178 / 1,639 ms | 5 |
35
+ | The speech model, stricter wording (prompt v2) | 98 | 1,353 / 1,699 ms | 2 |
36
+
37
+ Asked offline on held-out audio, the model holds back in 85% (v1) to 92% (v2) of pauses that cut a sentence off, and releases 84% (v1) or 54% (v2) of finished turns at once. One answer takes about 0.15 s.
38
+
39
+ ## Tried and switched off: reasoning while the caller is still speaking
40
+
41
+ The model's reasoning block was re-opened on more audio every 2.4 s of caller speech, opened with what it had already worked out. No training. Two rounds were stopped early once the result was clear.
42
+
43
+ | Arm | Questions | Right, text | Answer itself, median |
44
+ |---|---|---|---|
45
+ | Nothing carried (reference) | 100 | 95 | 11.2 s |
46
+ | A withdrawn reply keeps its reasoning | 70 | 62 | 6.6 s |
47
+ | Also reasons while listening | 64 | 50 | 7.7 s |
48
+ | Told at the end to check its work | 20 | 8 | 1.0 s |
49
+ | Told to take notes | 46 | 32 | 7.9 s |
50
+
51
+ Reasoning made on an unfinished question holds early conclusions, and the model trusts them. Published work on reasoning while listening trains the model for it. The code stays in the repository behind flags that are off.
52
+
53
+ ## How much reasoning the spoken answer needs
54
+
55
+ One caller at a time, reasoning limited to a number of tokens before the speech starts (text score).
56
+
57
+ | Reasoning tokens allowed | 0 | 64 | 128 | 256 | 512 | 2,048 |
58
+ |---|---|---|---|---|---|---|
59
+ | Right of 100 | 67 | 46 | 45 | 66 | 79 | 95 |
60
+
61
+ Reasoning that is cut short is worse than none.
62
+
63
+ ## Streams on one GPU
64
+
65
+ Without the lead-in. First audio is counted from the commit of the turn. An underrun is an 80 ms frame that was due and not ready.
66
+
67
+ | Audio settings | 1 stream | 2 streams | 4 streams |
68
+ |---|---|---|---|
69
+ | Released recipe: 25 tokens per chunk, one decoder | 880 ms, 0 underruns | 840 ms, 0 | 960 ms, 3 |
70
+ | First chunk of 12 tokens, small chunks while the buffer is low, four decoders | 561 ms, 0 | 640 ms, 1 | 721 ms, 91 |
71
+
72
+ A reply is generated at about 62 tokens per second for one stream. Speech needs about 31.
73
+
74
+ ## The two small models
75
+
76
+ Trained on 76.4 hours of synthetic two-speaker dialogue and tested on 8.3 hours with voices and scenarios kept out of training (340 dialogues, 372,632 frames of 80 ms).
77
+
78
+ | | |
79
+ |---|---|
80
+ | Streaming audio encoder | 38.7M parameters. Distilled from the audio encoder of Step-Audio R1.1 (637M). Cosine similarity to it on held-out voices: 0.676 |
81
+ | Turn controller | 89.0M parameters. One step for both, frame by frame: 12.4 ms on average per 80 ms frame |
82
+ | Frame labels, precision / recall | WAIT 0.985 / 0.977 · START 0.566 / 0.676 · STOP 0.793 / 0.834 · BACKCHANNEL 0.887 / 0.892 |
83
+ | Backchannel not treated as an interruption | 871 of 989 (a plain loudness rule: 0 of 989) |
84
+ | Interruption caught | 507 of 566 |
85
+ | No start inside a mid-sentence pause | 322 of 580 |
86
+ | Turn end caught in its window | 1,567 of 2,015 |
87
+
88
+ The controller is not good enough to decide when to start. The endpoint uses it only to tell a backchannel from an interruption.
89
+
90
+ ## The training data
91
+
92
+ Not included. `data/` holds the recipe: 3,400 dialogues written by Qwen3-32B, voiced with Kokoro-82M (23 voices for training, 4 held out), laid on a shared 80 ms timeline with interruptions, backchannels, pauses and self-corrections, with generated noise, room and line effects. No recording of a person is in it. Writing took 303 s, voicing 193 s and the timeline 36 s.
93
+
94
+ ## Step-Audio R1.1 through its released image, on the GPUs used here
95
+
96
+ - The engine does not start with its compiled kernels on this GPU generation (compute target sm_103a). `serving/launch_vllm.sh` turns that code generation off.
97
+ - A request for token probabilities stops the engine, so the end-of-turn judge reads a plain yes or no.
98
+ - The first reply longer than one token after a first start waits about 80 s. After a restart soon after it waits about 9 s.
99
+ - The weights take 62.4 GiB.
100
+
101
+ ## Not measured
102
+
103
+ - The leaderboard's own scoring of Big Bench Audio.
104
+ - Real callers. Every test caller was synthetic speech. One person has listened to a sample of the replies.
105
+ - Any public test of turn-taking or of reasoning under interruption. The ones found are not under Apache-2.0 or MIT.
106
+ - Keeping an interrupted reply in the conversation (`--keep-interrupted`).
assets/prompt_af_heart.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ea63ce9066d51935cba843c657af9a823ffed86f3197c6928f2d935f052eb915
3
+ size 494444
assets/prompt_af_heart_short.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:382f1b76802c795ac88a7eb362ab4ef7516f19d6670480cb7f8a3dd9a594accc
3
+ size 174044
checkpoints/controller.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cfg": {
3
+ "feat_dim": 1280,
4
+ "dim": 768,
5
+ "layers": 12,
6
+ "heads": 12,
7
+ "window": 375
8
+ },
9
+ "training_step": 25180,
10
+ "tensor_values": 88992772
11
+ }
checkpoints/controller.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b3db116d71d645410abaa5357dbc0fea319b63458d54fbee2994228c87b7722c
3
+ size 355985120
checkpoints/encoder.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cfg": {
3
+ "dim": 512,
4
+ "layers": 12,
5
+ "heads": 8,
6
+ "window": 250,
7
+ "out_dim": 1280
8
+ },
9
+ "training_step": 16900,
10
+ "tensor_values": 38775056
11
+ }
checkpoints/encoder.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8be66a92e105b0903dd6fc10f03f09df8aa0dc46e511aed986baa5aaf2394bc9
3
+ size 155114112
controller/__init__.py ADDED
File without changes
controller/encoder/__init__.py ADDED
File without changes
controller/encoder/distill.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Distil the baseline audio encoder into the causal streaming student.
2
+
3
+ Loss: L1 + (1 - cosine) between student and teacher features, frame by frame at 25 Hz.
4
+ Both channels of every crop are used (noisy caller audio and clean agent audio).
5
+
6
+ torchrun --nproc_per_node=3 -m controller.encoder.distill \
7
+ --data data/out/dataset --baseline-dir /models/Step-Audio-R1.1 --out runs/encoder --max-hours 1.5
8
+ """
9
+ import argparse
10
+ from pathlib import Path
11
+
12
+ import torch
13
+ import torch.nn.functional as F
14
+ from torch.nn.parallel import DistributedDataParallel
15
+ from torch.utils.data import DataLoader
16
+
17
+ from controller.encoder.student import StudentEncoder, mel_filterbank, save_student
18
+ from controller.encoder.teacher import Teacher
19
+ from data.dataset import Crops
20
+ from duplex.spec import FRAME_MS
21
+ from duplex.streaming import cosine_by_time, count_params
22
+ from duplex.train_utils import Budget, log_row, setup_ddp
23
+
24
+
25
+ def losses(pred, target):
26
+ l1 = F.l1_loss(pred, target)
27
+ cos = 1.0 - F.cosine_similarity(pred, target, dim=-1).mean()
28
+ return l1, cos
29
+
30
+
31
+ def main():
32
+ ap = argparse.ArgumentParser()
33
+ ap.add_argument("--data", required=True)
34
+ ap.add_argument("--baseline-dir", required=True, help="local folder of stepfun-ai/Step-Audio-R1.1")
35
+ ap.add_argument("--out", required=True)
36
+ ap.add_argument("--max-hours", type=float, default=1.5)
37
+ ap.add_argument("--batch", type=int, default=16, help="crops per GPU; each crop gives two clips (caller, agent)")
38
+ ap.add_argument("--crop-s", type=float, default=20.0, help="at most 29 s: the teacher's context")
39
+ ap.add_argument("--lr", type=float, default=4e-4)
40
+ ap.add_argument("--dim", type=int, default=512)
41
+ ap.add_argument("--layers", type=int, default=12)
42
+ ap.add_argument("--heads", type=int, default=8)
43
+ ap.add_argument("--window", type=int, default=250, help="attention window in 40 ms tokens (250 = 10 s)")
44
+ ap.add_argument("--workers", type=int, default=6)
45
+ ap.add_argument("--eval-every", type=int, default=500)
46
+ ap.add_argument("--ckpt-minutes", type=float, default=60.0, help="a checkpoint this often (the plan: hourly)")
47
+ args = ap.parse_args()
48
+
49
+ rank, world, device = setup_ddp()
50
+ out = Path(args.out)
51
+ out.mkdir(parents=True, exist_ok=True)
52
+ crop_frames = int(args.crop_s * 1000 / FRAME_MS)
53
+
54
+ teacher = Teacher(args.baseline_dir).to(device)
55
+ student = StudentEncoder(args.dim, args.layers, args.heads, args.window, fb=mel_filterbank()).to(device)
56
+ model = DistributedDataParallel(student, device_ids=[device.index]) if world > 1 else student
57
+ opt = torch.optim.AdamW(student.parameters(), lr=args.lr, betas=(0.9, 0.98), weight_decay=0.01)
58
+
59
+ loader = DataLoader(Crops(args.data, "train", crop_frames, seed=1000 + rank), batch_size=args.batch, num_workers=args.workers)
60
+ eval_set = list(DataLoader(Crops(args.data, "test", crop_frames, seed=7, limit=8 * args.batch), batch_size=args.batch)) if rank == 0 else []
61
+ log = str(out / "log.jsonl") if rank == 0 else None
62
+ if rank == 0:
63
+ log_row(log, event="start", student_params=count_params(student), teacher_params=count_params(teacher.encoder),
64
+ world=world, batch_per_gpu=args.batch, crop_s=args.crop_s, max_hours=args.max_hours)
65
+
66
+ budget = Budget(args.max_hours, rank, world, device, args.ckpt_minutes)
67
+ frac = 0.0
68
+ for step, (wav, _) in enumerate(loader):
69
+ if step % 20 == 0:
70
+ frac = budget.sync()
71
+ if frac >= 1.0:
72
+ break
73
+ n_ckpt = budget.checkpoint_due()
74
+ if n_ckpt and rank == 0:
75
+ save_student(out / f"ckpt_{n_ckpt:02d}.pt", student, {"step": step, "elapsed_s": budget.elapsed})
76
+ log_row(log, event="checkpoint", number=n_ckpt, step=step, elapsed_s=budget.elapsed)
77
+ for g in opt.param_groups:
78
+ g["lr"] = args.lr * cosine_by_time(frac)
79
+
80
+ wav = wav.to(device, non_blocking=True).flatten(0, 1) # [B*2, T]
81
+ target = teacher(wav)
82
+ with torch.autocast(device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):
83
+ pred = model(wav)
84
+ l1, cos = losses(pred.float(), target)
85
+ opt.zero_grad(set_to_none=True)
86
+ (l1 + cos).backward()
87
+ torch.nn.utils.clip_grad_norm_(student.parameters(), 1.0)
88
+ opt.step()
89
+
90
+ if rank == 0 and step % 50 == 0:
91
+ log_row(log, event="train", step=step, elapsed_s=budget.elapsed, l1=l1.item(), cos_dist=cos.item(), lr=opt.param_groups[0]["lr"])
92
+ if rank == 0 and step and step % args.eval_every == 0:
93
+ evaluate(student, teacher, eval_set, device, log, step)
94
+
95
+ if rank == 0:
96
+ evaluate(student, teacher, eval_set, device, log, step)
97
+ save_student(out / "final.pt", student, {"step": step, "elapsed_s": budget.elapsed})
98
+ log_row(log, event="done", step=step, elapsed_s=budget.elapsed)
99
+
100
+
101
+ @torch.no_grad()
102
+ def evaluate(student, teacher, eval_set, device, log, step):
103
+ student.eval()
104
+ l1s, coss = [], []
105
+ for wav, _ in eval_set:
106
+ wav = wav.to(device).flatten(0, 1)
107
+ with torch.autocast(device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):
108
+ pred = student(wav)
109
+ l1, cos = losses(pred.float(), teacher(wav))
110
+ l1s.append(l1.item())
111
+ coss.append(cos.item())
112
+ student.train()
113
+ log_row(log, event="eval", step=step, heldout_l1=sum(l1s) / len(l1s), heldout_cos_sim=1.0 - sum(coss) / len(coss))
114
+
115
+
116
+ if __name__ == "__main__":
117
+ main()
controller/encoder/student.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Causal streaming student of the baseline audio encoder.
2
+
3
+ Input: 16 kHz mono audio. Output: one 1280-d vector every 40 ms (25 Hz), the rate and
4
+ width of the baseline AudioEncoder, so two vectors per 80 ms frame.
5
+
6
+ Nothing here looks ahead: the mel frame for hop k uses samples up to the end of hop k
7
+ (the baseline's STFT is centred and its log-mel is clamped by the whole clip's
8
+ maximum, which a streaming front end cannot do), and attention is causal with a
9
+ bounded window. `forward` (whole crop) and `step` (80 ms at a time) are the same
10
+ function.
11
+ """
12
+ import torch
13
+ import torch.nn as nn
14
+
15
+ from duplex.spec import HOP, N_FFT, N_MELS, PATCH, SR, TEACHER_DIM
16
+ from duplex.streaming import CausalTransformer
17
+
18
+ TAIL = N_FFT - HOP # 240 samples of history each new mel frame needs
19
+
20
+
21
+ def mel_filterbank():
22
+ """The baseline's filterbank (librosa, Slaney), built once at training time and then
23
+ carried inside the checkpoint, so serving does not need librosa."""
24
+ import librosa
25
+ return torch.from_numpy(librosa.filters.mel(sr=SR, n_fft=N_FFT, n_mels=N_MELS)).float()
26
+
27
+
28
+ class StreamingMel(nn.Module):
29
+ def __init__(self, fb=None):
30
+ super().__init__()
31
+ self.register_buffer("window", torch.hann_window(N_FFT))
32
+ self.register_buffer("fb", fb if fb is not None else torch.zeros(N_MELS, N_FFT // 2 + 1))
33
+
34
+ def forward(self, wav, tail=None):
35
+ """wav [B, T], T a multiple of HOP -> log-mel [B, T/HOP, N_MELS], new tail [B, 240]."""
36
+ assert wav.shape[1] % HOP == 0
37
+ with torch.autocast(wav.device.type, enabled=False):
38
+ wav = wav.float()
39
+ if tail is None:
40
+ tail = wav.new_zeros(wav.shape[0], TAIL)
41
+ x = torch.cat([tail, wav], dim=1)
42
+ frames = x.unfold(1, N_FFT, HOP) # [B, T/HOP, 400]
43
+ power = torch.fft.rfft(frames * self.window, dim=-1).abs() ** 2
44
+ mel = power @ self.fb.T
45
+ logmel = (torch.clamp(mel, min=1e-6).log10() + 4.0) / 4.0 # fixed floor, no clip-level max
46
+ return logmel, x[:, -TAIL:]
47
+
48
+
49
+ class StudentEncoder(nn.Module):
50
+ def __init__(self, dim=512, layers=12, heads=8, window=250, out_dim=TEACHER_DIM, fb=None):
51
+ super().__init__()
52
+ self.cfg = dict(dim=dim, layers=layers, heads=heads, window=window, out_dim=out_dim)
53
+ self.mel = StreamingMel(fb)
54
+ self.inp = nn.Linear(PATCH * N_MELS, dim)
55
+ self.tf = CausalTransformer(dim, layers, heads, window)
56
+ self.ln = nn.LayerNorm(dim)
57
+ self.head = nn.Linear(dim, out_dim)
58
+
59
+ def _tokens(self, logmel):
60
+ B, N, M = logmel.shape
61
+ return self.inp(logmel.reshape(B, N // PATCH, PATCH * M).to(self.inp.weight.dtype))
62
+
63
+ def forward(self, wav):
64
+ """wav [B, T], T a multiple of 640 -> features [B, T/640, out_dim]."""
65
+ logmel, _ = self.mel(wav)
66
+ return self.head(self.ln(self.tf(self._tokens(logmel))))
67
+
68
+ def init_state(self, batch, device):
69
+ return {"tail": torch.zeros(batch, TAIL, device=device), "tf": self.tf.init_state()}
70
+
71
+ def step(self, wav, state):
72
+ """wav [B, t], t a multiple of 640 (one 80 ms frame is 1280) -> [B, t/640, out_dim]."""
73
+ logmel, tail = self.mel(wav, state["tail"])
74
+ x, tf = self.tf.step(self._tokens(logmel), state["tf"])
75
+ return self.head(self.ln(x)), {"tail": tail, "tf": tf}
76
+
77
+
78
+ def save_student(path, model, extra=None):
79
+ torch.save({"cfg": model.cfg, "model": model.state_dict(), "extra": extra or {}}, path)
80
+
81
+
82
+ def load_student(path, device="cpu"):
83
+ from duplex.streaming import read_checkpoint
84
+ cfg, state = read_checkpoint(path)
85
+ model = StudentEncoder(**cfg)
86
+ model.load_state_dict(state)
87
+ return model.to(device).eval()
controller/encoder/teacher.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The baseline's audio encoder, loaded alone (about 0.6B of the 33B), as the frozen teacher.
2
+
3
+ `AudioEncoder`, `log_mel` and the length arithmetic follow
4
+ modeling_step_audio_2.py / utils.py of stepfun-ai/Step-Audio-R1.1
5
+ (Copyright StepFun, Apache-2.0). Parameter names are kept identical so the released
6
+ weights load with strict=True. Only the `encoder.*` tensors are read from the
7
+ checkpoint shards; the LLM is never loaded.
8
+ """
9
+ import json
10
+ from pathlib import Path
11
+
12
+ import torch
13
+ import torch.nn as nn
14
+ import torch.nn.functional as F
15
+
16
+ from duplex.spec import N_FFT, N_MELS, SR
17
+
18
+
19
+ class MultiHeadAttention(nn.Module):
20
+ def __init__(self, n_state, n_head):
21
+ super().__init__()
22
+ self.n_head = n_head
23
+ self.query = nn.Linear(n_state, n_state)
24
+ self.key = nn.Linear(n_state, n_state, bias=False)
25
+ self.value = nn.Linear(n_state, n_state)
26
+ self.out = nn.Linear(n_state, n_state)
27
+
28
+ def forward(self, x, bias):
29
+ # Same attention as the released code (q and k each scaled by d_head ** -0.25, i.e. the usual
30
+ # 1 / sqrt(d_head)), computed with PyTorch's fused routine: the released explicit float32
31
+ # softmax over batch x heads x T x T made a distillation step several times slower.
32
+ B, T, _ = x.shape
33
+ q, k, v = (m(x).view(B, T, self.n_head, -1).transpose(1, 2) for m in (self.query, self.key, self.value))
34
+ a = F.scaled_dot_product_attention(q, k, v, attn_mask=bias.to(q.dtype))
35
+ return self.out(a.transpose(1, 2).flatten(start_dim=2))
36
+
37
+
38
+ class ResidualAttentionBlock(nn.Module):
39
+ def __init__(self, n_state, n_head):
40
+ super().__init__()
41
+ self.attn = MultiHeadAttention(n_state, n_head)
42
+ self.attn_ln = nn.LayerNorm(n_state)
43
+ self.mlp = nn.Sequential(nn.Linear(n_state, n_state * 4), nn.GELU(), nn.Linear(n_state * 4, n_state))
44
+ self.mlp_ln = nn.LayerNorm(n_state)
45
+
46
+ def forward(self, x, bias):
47
+ x = x + self.attn(self.attn_ln(x), bias)
48
+ return x + self.mlp(self.mlp_ln(x))
49
+
50
+
51
+ class AudioEncoder(nn.Module):
52
+ """Every clip in a batch has the same length here (fixed crops). The released code
53
+ still hides the two mel frames that come from its 479-sample padding
54
+ (feats_lengths = frames - 2); the same key mask is applied here."""
55
+
56
+ def __init__(self, n_mels=128, n_ctx=1500, n_state=1280, n_head=20, n_layer=32):
57
+ super().__init__()
58
+ self.conv1 = nn.Conv1d(n_mels, n_state, kernel_size=3, padding=1)
59
+ self.conv2 = nn.Conv1d(n_state, n_state, kernel_size=3, stride=2, padding=1)
60
+ self.positional_embedding = nn.Embedding(n_ctx, n_state)
61
+ self.blocks = nn.ModuleList([ResidualAttentionBlock(n_state, n_head) for _ in range(n_layer)])
62
+ self.avg_pooler = nn.AvgPool1d(2, stride=2)
63
+ self.after_norm = nn.LayerNorm(n_state)
64
+
65
+ def forward(self, mel):
66
+ T = mel.size(-1)
67
+ x = F.gelu(self.conv1(mel))
68
+ x = F.gelu(self.conv2(x)).permute(0, 2, 1)
69
+ assert x.shape[1] <= self.positional_embedding.num_embeddings, "clip longer than the encoder context (about 29.9 s)"
70
+ valid = (torch.arange(T, device=mel.device) < T - 2)[(T + 1) % 2::2] # released make_non_pad_mask + subsampling
71
+ bias = ((~valid).to(x.dtype) * -1.0e10)[None, None, None, :]
72
+ x = x + self.positional_embedding.weight[: x.shape[1]]
73
+ for block in self.blocks:
74
+ x = block(x, bias)
75
+ x = self.avg_pooler(x.permute(0, 2, 1)).permute(0, 2, 1)
76
+ return self.after_norm(x)
77
+
78
+
79
+ def log_mel(audio, filters):
80
+ """Released log_mel_spectrogram (padding=479), batched over equal-length clips [B, T]."""
81
+ audio = F.pad(audio, (0, 479))
82
+ window = torch.hann_window(N_FFT, device=audio.device)
83
+ stft = torch.stft(audio, N_FFT, 160, window=window, return_complex=True)
84
+ mel = filters @ (stft[..., :-1].abs() ** 2)
85
+ log_spec = torch.clamp(mel, min=1e-10).log10()
86
+ log_spec = torch.maximum(log_spec, log_spec.amax(dim=(1, 2), keepdim=True) - 8.0) # per clip, as released
87
+ return (log_spec + 4.0) / 4.0
88
+
89
+
90
+ class Teacher(nn.Module):
91
+ def __init__(self, model_dir):
92
+ super().__init__()
93
+ import librosa
94
+ self.register_buffer("filters", torch.from_numpy(librosa.filters.mel(sr=SR, n_fft=N_FFT, n_mels=N_MELS)).float())
95
+ model_dir = Path(model_dir)
96
+ cfg = json.loads((model_dir / "config.json").read_text())["audio_encoder_config"]
97
+ self.encoder = AudioEncoder(cfg["n_mels"], cfg["n_audio_ctx"], cfg["n_audio_state"], cfg["n_audio_head"], cfg["n_audio_layer"])
98
+ self.encoder.load_state_dict(_encoder_weights(model_dir), strict=True)
99
+ self.requires_grad_(False).eval()
100
+
101
+ @torch.no_grad()
102
+ def forward(self, wav):
103
+ """wav [B, T] at 16 kHz, T a multiple of 640 -> [B, T/640, 1280] (25 Hz)."""
104
+ with torch.autocast(wav.device.type, enabled=False):
105
+ mel = log_mel(wav.float(), self.filters)
106
+ with torch.autocast(wav.device.type, dtype=torch.bfloat16, enabled=wav.is_cuda):
107
+ out = self.encoder(mel)
108
+ n = wav.shape[1] // 640
109
+ assert out.shape[1] == n, f"teacher gave {out.shape[1]} frames for {n} expected"
110
+ return out.float()
111
+
112
+
113
+ def _encoder_weights(model_dir):
114
+ from safetensors import safe_open
115
+ weight_map = json.loads((model_dir / "model.safetensors.index.json").read_text())["weight_map"]
116
+ keys = [k for k in weight_map if k.startswith("encoder.")]
117
+ if not keys:
118
+ prefixes = sorted({k.split(".")[0] for k in weight_map})
119
+ raise RuntimeError(f"no 'encoder.*' tensors in the checkpoint index; top-level names are {prefixes}")
120
+ sd = {}
121
+ for shard in sorted({weight_map[k] for k in keys}):
122
+ with safe_open(str(model_dir / shard), framework="pt") as f:
123
+ for k in f.keys():
124
+ if k.startswith("encoder."):
125
+ sd[k[len("encoder."):]] = f.get_tensor(k).float()
126
+ return sd
controller/model/__init__.py ADDED
File without changes
controller/model/model.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The duplex controller: a small causal transformer that reads, per 80 ms frame, the
2
+ streaming encoder features of the caller's audio and of the model's own output audio,
3
+ and predicts one of WAIT, START, STOP, BACKCHANNEL.
4
+
5
+ Default size is about 90M parameters (dim 768, 12 layers); the plan's ceiling is 1B.
6
+ """
7
+ import torch
8
+ import torch.nn as nn
9
+
10
+ from duplex.spec import LABELS, TEACHER_DIM, TOK_PER_FRAME
11
+ from duplex.streaming import CausalTransformer
12
+
13
+
14
+ class Controller(nn.Module):
15
+ def __init__(self, feat_dim=TEACHER_DIM, dim=768, layers=12, heads=12, window=375):
16
+ super().__init__()
17
+ self.cfg = dict(feat_dim=feat_dim, dim=dim, layers=layers, heads=heads, window=window)
18
+ self.in_caller = nn.Linear(TOK_PER_FRAME * feat_dim, dim)
19
+ self.in_self = nn.Linear(TOK_PER_FRAME * feat_dim, dim)
20
+ self.tf = CausalTransformer(dim, layers, heads, window) # window in 80 ms frames (375 = 30 s)
21
+ self.ln = nn.LayerNorm(dim)
22
+ self.head = nn.Linear(dim, len(LABELS))
23
+
24
+ def _embed(self, caller, own):
25
+ """caller, own: [B, 2T, feat_dim] at 25 Hz -> [B, T, dim] at 12.5 Hz."""
26
+ B, N, Fd = caller.shape
27
+ shape = (B, N // TOK_PER_FRAME, TOK_PER_FRAME * Fd)
28
+ return self.in_caller(caller.reshape(shape)) + self.in_self(own.reshape(shape))
29
+
30
+ def forward(self, caller, own):
31
+ return self.head(self.ln(self.tf(self._embed(caller, own))))
32
+
33
+ def init_state(self):
34
+ return self.tf.init_state()
35
+
36
+ def step(self, caller, own, state):
37
+ x, state = self.tf.step(self._embed(caller, own), state)
38
+ return self.head(self.ln(x)), state
39
+
40
+
41
+ def save_controller(path, model, extra=None):
42
+ torch.save({"cfg": model.cfg, "model": model.state_dict(), "extra": extra or {}}, path)
43
+
44
+
45
+ def load_controller(path, device="cpu"):
46
+ from duplex.streaming import read_checkpoint
47
+ cfg, state = read_checkpoint(path)
48
+ model = Controller(**cfg)
49
+ model.load_state_dict(state)
50
+ return model.to(device).eval()
controller/model/train.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Train the duplex controller on frozen student-encoder features.
2
+
3
+ One run, time-budgeted (default 3.75 h so it ends inside 4 h), a checkpoint every hour.
4
+ The loss is cross-entropy weighted toward START / STOP / BACKCHANNEL and away from WAIT.
5
+
6
+ torchrun --nproc_per_node=3 -m controller.model.train \
7
+ --data data/out/dataset --encoder runs/encoder/final.pt --out runs/controller
8
+ """
9
+ import argparse
10
+ from pathlib import Path
11
+
12
+ import numpy as np
13
+ import torch
14
+ import torch.nn.functional as F
15
+ from torch.nn.parallel import DistributedDataParallel
16
+ from torch.utils.data import DataLoader
17
+
18
+ from controller.encoder.student import load_student
19
+ from controller.model.model import Controller, save_controller
20
+ from data.dataset import Crops
21
+ from duplex.spec import FRAME_MS, LABELS
22
+ from duplex.streaming import cosine_by_time, count_params
23
+ from duplex.train_utils import Budget, confusion, log_row, precision_recall, setup_ddp
24
+
25
+
26
+ @torch.no_grad()
27
+ def features(encoder, wav, device):
28
+ """wav [B, 2, T] -> caller feats, own feats, each [B, T/640, 1280]."""
29
+ B = wav.shape[0]
30
+ with torch.autocast(device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):
31
+ f = encoder(wav.flatten(0, 1))
32
+ f = f.view(B, 2, f.shape[1], f.shape[2])
33
+ return f[:, 0], f[:, 1]
34
+
35
+
36
+ def main():
37
+ ap = argparse.ArgumentParser()
38
+ ap.add_argument("--data", required=True)
39
+ ap.add_argument("--encoder", required=True, help="student encoder checkpoint from controller.encoder.distill")
40
+ ap.add_argument("--out", required=True)
41
+ ap.add_argument("--max-hours", type=float, default=3.75)
42
+ ap.add_argument("--batch", type=int, default=24, help="crops per GPU")
43
+ ap.add_argument("--crop-s", type=float, default=30.0)
44
+ ap.add_argument("--lr", type=float, default=3e-4)
45
+ ap.add_argument("--dim", type=int, default=768)
46
+ ap.add_argument("--layers", type=int, default=12)
47
+ ap.add_argument("--heads", type=int, default=12)
48
+ ap.add_argument("--window", type=int, default=375, help="attention window in 80 ms frames (375 = 30 s)")
49
+ ap.add_argument("--class-weights", default="0.2,1,1,1", help="loss weight for " + ",".join(LABELS))
50
+ ap.add_argument("--workers", type=int, default=6)
51
+ ap.add_argument("--eval-every", type=int, default=500)
52
+ ap.add_argument("--ckpt-minutes", type=float, default=60.0, help="a checkpoint this often (the plan: hourly)")
53
+ args = ap.parse_args()
54
+
55
+ rank, world, device = setup_ddp()
56
+ out = Path(args.out)
57
+ out.mkdir(parents=True, exist_ok=True)
58
+ crop_frames = int(args.crop_s * 1000 / FRAME_MS)
59
+ weights = torch.tensor([float(w) for w in args.class_weights.split(",")], device=device)
60
+ assert len(weights) == len(LABELS)
61
+
62
+ encoder = load_student(args.encoder, device).requires_grad_(False)
63
+ ctl = Controller(encoder.cfg["out_dim"], args.dim, args.layers, args.heads, args.window).to(device)
64
+ assert count_params(ctl) < 1_000_000_000
65
+ model = DistributedDataParallel(ctl, device_ids=[device.index]) if world > 1 else ctl
66
+ opt = torch.optim.AdamW(ctl.parameters(), lr=args.lr, betas=(0.9, 0.98), weight_decay=0.01)
67
+
68
+ loader = DataLoader(Crops(args.data, "train", crop_frames, seed=2000 + rank), batch_size=args.batch, num_workers=args.workers)
69
+ eval_set = list(DataLoader(Crops(args.data, "test", crop_frames, seed=7, limit=16 * args.batch), batch_size=args.batch)) if rank == 0 else []
70
+ log = str(out / "log.jsonl") if rank == 0 else None
71
+ if rank == 0:
72
+ log_row(log, event="start", controller_params=count_params(ctl), encoder_params=count_params(encoder), world=world,
73
+ batch_per_gpu=args.batch, crop_s=args.crop_s, max_hours=args.max_hours, class_weights=args.class_weights)
74
+
75
+ budget = Budget(args.max_hours, rank, world, device, args.ckpt_minutes)
76
+ frac = 0.0
77
+ for step, (wav, labels) in enumerate(loader):
78
+ if step % 20 == 0:
79
+ frac = budget.sync()
80
+ if frac >= 1.0:
81
+ break
82
+ n_ckpt = budget.checkpoint_due()
83
+ if n_ckpt and rank == 0:
84
+ save_controller(out / f"ckpt_{n_ckpt:02d}.pt", ctl, {"step": step, "elapsed_s": budget.elapsed})
85
+ log_row(log, event="checkpoint", number=n_ckpt, step=step, elapsed_s=budget.elapsed)
86
+ for g in opt.param_groups:
87
+ g["lr"] = args.lr * cosine_by_time(frac)
88
+
89
+ wav, labels = wav.to(device, non_blocking=True), labels.to(device, non_blocking=True)
90
+ caller, own = features(encoder, wav, device)
91
+ with torch.autocast(device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):
92
+ logits = model(caller, own)
93
+ loss = F.cross_entropy(logits.float().flatten(0, 1), labels.flatten(), weight=weights, ignore_index=-100)
94
+ opt.zero_grad(set_to_none=True)
95
+ loss.backward()
96
+ torch.nn.utils.clip_grad_norm_(ctl.parameters(), 1.0)
97
+ opt.step()
98
+
99
+ if rank == 0 and step % 50 == 0:
100
+ log_row(log, event="train", step=step, elapsed_s=budget.elapsed, loss=loss.item(), lr=opt.param_groups[0]["lr"])
101
+ if rank == 0 and step and step % args.eval_every == 0:
102
+ evaluate(encoder, ctl, eval_set, device, log, step)
103
+
104
+ if rank == 0:
105
+ evaluate(encoder, ctl, eval_set, device, log, step)
106
+ save_controller(out / "final.pt", ctl, {"step": step, "elapsed_s": budget.elapsed})
107
+ log_row(log, event="done", step=step, elapsed_s=budget.elapsed)
108
+
109
+
110
+ @torch.no_grad()
111
+ def evaluate(encoder, ctl, eval_set, device, log, step):
112
+ ctl.eval()
113
+ conf = np.zeros((len(LABELS), len(LABELS)), dtype=np.int64)
114
+ for wav, labels in eval_set:
115
+ caller, own = features(encoder, wav.to(device), device)
116
+ with torch.autocast(device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):
117
+ pred = ctl(caller, own).argmax(-1)
118
+ conf += confusion(pred.cpu().numpy(), labels.numpy())
119
+ ctl.train()
120
+ log_row(log, event="eval", step=step, heldout=precision_recall(conf))
121
+
122
+
123
+ if __name__ == "__main__":
124
+ main()
controller/runtime.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Frame-by-frame controller for the server: one call per 80 ms frame, per session."""
2
+ import numpy as np
3
+ import torch
4
+
5
+ from controller.encoder.student import load_student
6
+ from controller.model.model import load_controller
7
+ from duplex.spec import FRAME
8
+
9
+
10
+ class DuplexController:
11
+ def __init__(self, encoder_ckpt, controller_ckpt, device="cuda:1"):
12
+ self.device = torch.device(device)
13
+ self.encoder = load_student(encoder_ckpt, self.device)
14
+ self.ctl = load_controller(controller_ckpt, self.device)
15
+ warm = self.new_session() # first calls pay one-time GPU set-up; do it before a caller arrives
16
+ for _ in range(30):
17
+ self.step(warm, np.zeros(FRAME, np.float32), np.zeros(FRAME, np.float32))
18
+
19
+ def new_session(self):
20
+ # batch of 2 in the encoder: row 0 is the caller's audio, row 1 the model's own output
21
+ return {"enc": self.encoder.init_state(2, self.device), "ctl": self.ctl.init_state()}
22
+
23
+ @torch.inference_mode()
24
+ def step(self, sess, caller_frame, own_frame):
25
+ """caller_frame, own_frame: float32 [1280] at 16 kHz. Returns probabilities over LABELS."""
26
+ assert len(caller_frame) == FRAME and len(own_frame) == FRAME
27
+ wav = torch.from_numpy(np.stack([caller_frame, own_frame]).astype(np.float32)).to(self.device)
28
+ with torch.autocast(self.device.type, dtype=torch.bfloat16, enabled=self.device.type == "cuda"):
29
+ feats, sess["enc"] = self.encoder.step(wav, sess["enc"])
30
+ logits, sess["ctl"] = self.ctl.step(feats[0:1], feats[1:2], sess["ctl"])
31
+ return torch.softmax(logits[0, -1].float(), dim=-1).cpu().numpy()
data/__init__.py ADDED
File without changes
data/build_timeline.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Put both speakers of each dialogue on one shared timeline and label every 80 ms frame.
2
+
3
+ Channel 0 is the caller as the model hears them (room, line and noise effects, and
4
+ sometimes the model's own voice leaking back). Channel 1 is the model's own output
5
+ audio, clean, exactly what a server would have sent.
6
+
7
+ Labels are the action the model (the agent) should take in that frame:
8
+ START the caller's turn is over and the agent has not begun yet. The agent's
9
+ audio starts in the frame right after the last START frame, so the label
10
+ can never be read off the agent's own channel.
11
+ STOP the caller is truly interrupting; from one frame after the caller's onset
12
+ until the agent's audio is cut.
13
+ BACKCHANNEL the caller says "mm-hm" over the agent; the agent keeps talking.
14
+ WAIT everything else, including mid-sentence pauses of the caller.
15
+
16
+ All noise, room responses and line effects are generated here (no third-party audio),
17
+ so the licence of the dataset is the licence of this code and of the TTS output.
18
+
19
+ python -m data.build_timeline --dialogues data/out/dialogues.jsonl --tts data/out/tts \
20
+ --out data/out/dataset --workers 32
21
+ """
22
+ import argparse
23
+ import json
24
+ import zlib
25
+ from collections import Counter
26
+ from multiprocessing import Pool
27
+ from pathlib import Path
28
+
29
+ import numpy as np
30
+
31
+ from duplex.spec import AGENT, BACKCHANNEL, CALLER, FRAME, LABELS, SR, START, STOP, read_jsonl, write_json, write_wav
32
+
33
+
34
+ def trim(x, rel=0.01, margin=160):
35
+ """Cut leading and trailing silence, keeping 10 ms each side."""
36
+ x = x.astype(np.float32) / 32768.0
37
+ if not len(x):
38
+ return x
39
+ loud = np.nonzero(np.abs(x) > rel * max(float(np.abs(x).max()), 1e-6))[0]
40
+ return x[max(0, loud[0] - margin): loud[-1] + margin] if len(loud) else x[:0]
41
+
42
+
43
+ def lay_out(d, clips, bank, rng, barge_prob=0.0):
44
+ """Returns (placements, events, end_sample) or None when a turn could not be voiced."""
45
+ turns = []
46
+ for ti, turn in enumerate(d["turns"]):
47
+ parts, si = [], 0
48
+ while f"t{ti}_s{si}" in clips:
49
+ part = trim(clips[f"t{ti}_s{si}"])
50
+ if len(part) < SR // 20:
51
+ return None
52
+ parts.append(part)
53
+ si += 1
54
+ if not parts:
55
+ return None
56
+ turns.append((turn["spk"], parts, turn.get("interrupts", False)))
57
+
58
+ cg, ag = 10 ** (rng.uniform(-6, 0) / 20), 10 ** (rng.uniform(-3, 0) / 20)
59
+ place, events = [], []
60
+ t = int(rng.uniform(0.3, 1.0) * SR)
61
+ for k, (spk, parts, _) in enumerate(turns):
62
+ nxt = turns[k + 1] if k + 1 < len(turns) else None
63
+ if spk == "caller":
64
+ start = t
65
+ for pi, part in enumerate(parts):
66
+ place.append((CALLER, t, part * cg))
67
+ t += len(part)
68
+ if pi < len(parts) - 1: # mid-sentence pause: stays WAIT
69
+ pause = int(rng.uniform(0.5, 2.0) * SR)
70
+ events.append({"type": "pause", "start": t, "end": t + pause, "f0": -(-t // FRAME), "f1": (t + pause) // FRAME})
71
+ t += pause
72
+ events.append({"type": "caller_turn", "start": start, "end": t})
73
+ if nxt: # the agent answers: START until its audio begins
74
+ f0 = -(-t // FRAME)
75
+ f1 = f0 + int(rng.integers(2, 13)) # 160 ms to 960 ms
76
+ events.append({"type": "start", "caller_end": t, "f0": f0, "f1": f1})
77
+ t = f1 * FRAME
78
+ else:
79
+ seg = np.concatenate(parts) * ag
80
+ start = t
81
+ # the caller cuts in: where the dialogue says so, and at random elsewhere (barge_prob), so that
82
+ # true interruptions are not vastly outnumbered by backchannels
83
+ if nxt and len(seg) > 2.5 * SR and (nxt[2] or rng.random() < barge_prob):
84
+ react = int(rng.integers(3, 8)) # the agent stops 240 ms to 560 ms after noticing
85
+ onset = start + int(rng.uniform(0.35, 0.8) * (len(seg) - (react + 2) * FRAME))
86
+ f_cut = onset // FRAME + 1 + react
87
+ seg = seg[: f_cut * FRAME - start].copy()
88
+ seg[-320:] *= np.linspace(1.0, 0.0, 320, dtype=np.float32)
89
+ place.append((AGENT, start, seg))
90
+ events.append({"type": "interrupt", "onset": onset, "f0": onset // FRAME + 1, "f1": f_cut})
91
+ t = onset # the caller's next turn starts here, over the agent
92
+ else:
93
+ place.append((AGENT, start, seg))
94
+ taken = []
95
+ if bank and len(seg) > 4 * SR and rng.random() < 0.5:
96
+ for _ in range(int(rng.integers(1, 3))):
97
+ bc = bank[int(rng.integers(len(bank)))] * cg * rng.uniform(0.5, 1.0)
98
+ pos = start + int(rng.uniform(1.0 * SR, len(seg) - 1.0 * SR - len(bc)))
99
+ if any(pos < e and s < pos + len(bc) + SR for s, e in taken):
100
+ continue
101
+ taken.append((pos, pos + len(bc)))
102
+ place.append((CALLER, pos, bc))
103
+ events.append({"type": "backchannel", "start": pos, "end": pos + len(bc),
104
+ "f0": pos // FRAME + 1, "f1": -(-(pos + len(bc)) // FRAME)})
105
+ t = start + len(seg) + int(rng.uniform(0.2, 1.2) * SR)
106
+ return place, events, t + int(0.5 * SR)
107
+
108
+
109
+ def fft_conv(x, h):
110
+ n = 1 << (len(x) + len(h) - 1).bit_length()
111
+ return np.fft.irfft(np.fft.rfft(x, n) * np.fft.rfft(h, n), n)[: len(x)].astype(np.float32)
112
+
113
+
114
+ def room(rng):
115
+ """Synthetic room response: direct path plus exponentially decaying noise."""
116
+ rt60 = rng.uniform(0.15, 0.7)
117
+ n = int(rt60 * SR)
118
+ h = rng.standard_normal(n) * np.exp(-6.908 * np.arange(n) / SR / rt60)
119
+ h[: int(0.002 * SR)] = 0.0
120
+ h *= 10 ** (-rng.uniform(3, 15) / 20) / np.sqrt(np.sum(h ** 2) + 1e-9) # direct-to-reverberant ratio 3 to 15 dB
121
+ h[0] = 1.0
122
+ return h.astype(np.float32)
123
+
124
+
125
+ def colored_noise(rng, n):
126
+ """Noise with a random spectral tilt between white and brown, unit RMS."""
127
+ spec = np.fft.rfft(rng.standard_normal(n))
128
+ f = np.fft.rfftfreq(n, 1.0 / SR)
129
+ f[0] = f[1]
130
+ x = np.fft.irfft(spec / f ** (rng.uniform(0.0, 2.0) / 2.0), n)
131
+ return (x / (np.sqrt(np.mean(x ** 2)) + 1e-9)).astype(np.float32)
132
+
133
+
134
+ def degrade_caller(caller, agent, rng):
135
+ """What the model's microphone side would hear: room, echo of itself, line, noise."""
136
+ active = caller[np.abs(caller) > 1e-4]
137
+ speech_rms = float(np.sqrt(np.mean(active ** 2))) if len(active) else 0.05
138
+ n, fx = len(caller), []
139
+ if rng.random() < 0.6:
140
+ caller = fft_conv(caller, room(rng))
141
+ fx.append("room")
142
+ if rng.random() < 0.3: # the agent's voice leaking back, delayed and quiet
143
+ delay = int(rng.uniform(0.04, 0.2) * SR)
144
+ echo = fft_conv(np.concatenate([np.zeros(delay, np.float32), agent[: n - delay]]), room(rng))
145
+ caller = caller + echo * 10 ** (-rng.uniform(18, 35) / 20)
146
+ fx.append("echo")
147
+ if rng.random() < 0.3: # narrow telephone band
148
+ spec = np.fft.rfft(caller)
149
+ f = np.fft.rfftfreq(n, 1.0 / SR)
150
+ spec[(f < 300) | (f > 3400)] = 0
151
+ caller = np.fft.irfft(spec, n).astype(np.float32)
152
+ fx.append("phone_band")
153
+ if rng.random() < 0.85:
154
+ noise = colored_noise(rng, n)
155
+ if rng.random() < 0.2:
156
+ tt = np.arange(n) / SR
157
+ f0 = float(rng.choice([50.0, 60.0]))
158
+ noise = noise + 2.0 * sum(np.sin(2 * np.pi * f0 * h * tt + rng.uniform(0, 6.28)) / h for h in (1, 2, 3)).astype(np.float32)
159
+ noise /= np.sqrt(np.mean(noise ** 2)) + 1e-9
160
+ snr = rng.uniform(5, 35)
161
+ caller = caller + noise * speech_rms * 10 ** (-snr / 20)
162
+ fx.append(f"noise_snr{snr:.0f}")
163
+ if rng.random() < 0.3: # short bangs: not speech, must not trigger anything
164
+ for _ in range(int(rng.integers(1, 4))):
165
+ m = int(rng.uniform(0.1, 0.4) * SR)
166
+ pos = int(rng.integers(0, max(1, n - m)))
167
+ caller[pos: pos + m] += colored_noise(rng, m) * np.hanning(m).astype(np.float32) * speech_rms * rng.uniform(0.5, 1.5)
168
+ fx.append("bursts")
169
+ return caller, fx
170
+
171
+
172
+ def build(job):
173
+ d, tts_dir, out_dir, seed, barge_prob = job
174
+ try:
175
+ z = np.load(Path(tts_dir) / f"{d['id']}.npz")
176
+ clips = {k: z[k] for k in z.files}
177
+ except FileNotFoundError:
178
+ return None
179
+ bank_file = Path(tts_dir) / f"_bank_{d['caller_voice']}.npz"
180
+ bank = []
181
+ if bank_file.exists():
182
+ z = np.load(bank_file)
183
+ bank = [b for b in (trim(z[k]) for k in z.files) if len(b) > SR // 20]
184
+ rng = np.random.default_rng([seed, zlib.crc32(d["id"].encode())])
185
+ laid = lay_out(d, clips, bank, rng, barge_prob)
186
+ if laid is None:
187
+ return None
188
+ place, events, end = laid
189
+ n_frames = -(-end // FRAME)
190
+ audio = np.zeros((n_frames * FRAME, 2), dtype=np.float32)
191
+ for ch, start, x in place:
192
+ x = x[: len(audio) - start]
193
+ audio[start: start + len(x), ch] += x
194
+ audio[:, CALLER], fx = degrade_caller(audio[:, CALLER], audio[:, AGENT], rng)
195
+ peak = float(np.abs(audio).max())
196
+ if peak > 0.99:
197
+ audio *= 0.99 / peak
198
+
199
+ labels = np.zeros(n_frames, dtype=np.uint8)
200
+ for e in events:
201
+ code = {"start": START, "interrupt": STOP, "backchannel": BACKCHANNEL}.get(e["type"])
202
+ if code is not None:
203
+ labels[e["f0"]: e["f1"]] = code
204
+
205
+ out = Path(out_dir)
206
+ write_wav(out / "audio" / f"{d['id']}.wav", audio, SR)
207
+ np.save(out / "labels" / f"{d['id']}.npy", labels)
208
+ meta = {k: d[k] for k in ("id", "split", "domain", "task", "caller_voice", "agent_voice")}
209
+ meta.update(n_frames=int(n_frames), effects=fx, events=[{k: (int(v) if k != "type" else v) for k, v in e.items()} for e in events],
210
+ self_corrections=sum(t.get("self_correction", False) for t in d["turns"]))
211
+ write_json(out / "meta" / f"{d['id']}.json", meta)
212
+ return {"id": d["id"], "split": d["split"], "n_frames": int(n_frames), "labels": np.bincount(labels, minlength=len(LABELS)).tolist(),
213
+ "events": dict(Counter(e["type"] for e in events)), "self_corrections": meta["self_corrections"]}
214
+
215
+
216
+ def main():
217
+ ap = argparse.ArgumentParser()
218
+ ap.add_argument("--dialogues", required=True)
219
+ ap.add_argument("--tts", required=True)
220
+ ap.add_argument("--out", required=True)
221
+ ap.add_argument("--workers", type=int, default=16)
222
+ ap.add_argument("--seed", type=int, default=0)
223
+ ap.add_argument("--barge-prob", type=float, default=0.25, help="chance that a caller turn not marked as an interruption still starts over the agent")
224
+ args = ap.parse_args()
225
+
226
+ out = Path(args.out)
227
+ for sub in ("audio", "labels", "meta"):
228
+ (out / sub).mkdir(parents=True, exist_ok=True)
229
+ dialogues = read_jsonl(args.dialogues)
230
+ with Pool(args.workers) as pool:
231
+ rows = [r for r in pool.imap_unordered(build, [(d, args.tts, args.out, args.seed, args.barge_prob) for d in dialogues], chunksize=4) if r]
232
+
233
+ stats = {"dialogues_in": len(dialogues), "dialogues_built": len(rows), "frame_ms": 80, "labels": LABELS}
234
+ for split in ("train", "test"):
235
+ part = sorted((r for r in rows if r["split"] == split), key=lambda r: r["id"])
236
+ write_json(out / f"index_{split}.json", [{"id": r["id"], "n_frames": r["n_frames"]} for r in part])
237
+ counts = np.sum([r["labels"] for r in part], axis=0) if part else np.zeros(len(LABELS))
238
+ events = Counter()
239
+ for r in part:
240
+ events.update(r["events"])
241
+ stats[split] = {
242
+ "dialogues": len(part), "hours": round(sum(r["n_frames"] for r in part) * 0.08 / 3600, 3),
243
+ "label_frames": dict(zip(LABELS, (int(c) for c in counts))), "events": dict(events),
244
+ "self_corrections": sum(r["self_corrections"] for r in part),
245
+ }
246
+ write_json(out / "stats.json", stats)
247
+ print(json.dumps(stats, indent=2))
248
+
249
+
250
+ if __name__ == "__main__":
251
+ main()
data/dataset.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Random fixed-length crops of the built dialogues: stereo audio (caller, agent) and
2
+ one label per 80 ms frame. Used by both trainers."""
3
+ import json
4
+ from pathlib import Path
5
+
6
+ import numpy as np
7
+ import torch
8
+ from torch.utils.data import IterableDataset, get_worker_info
9
+
10
+ from duplex.spec import FRAME, read_wav
11
+
12
+
13
+ class Crops(IterableDataset):
14
+ def __init__(self, root, split, crop_frames, seed=0, limit=None):
15
+ self.root, self.crop, self.seed, self.limit = Path(root), crop_frames, seed, limit
16
+ self.items = json.loads((self.root / f"index_{split}.json").read_text())
17
+ assert self.items, f"no dialogues in split {split}"
18
+
19
+ def __iter__(self):
20
+ info = get_worker_info()
21
+ rng = np.random.default_rng([self.seed, info.id if info else 0])
22
+ length = np.array([it["n_frames"] for it in self.items], dtype=np.float64)
23
+ p = length / length.sum()
24
+ count = 0
25
+ while self.limit is None or count < self.limit:
26
+ it = self.items[int(rng.choice(len(self.items), p=p))]
27
+ start = int(rng.integers(0, max(1, it["n_frames"] - self.crop + 1)))
28
+ wav, _ = read_wav(self.root / "audio" / f"{it['id']}.wav", start * FRAME, self.crop * FRAME)
29
+ labels = np.load(self.root / "labels" / f"{it['id']}.npy")[start:start + self.crop].astype(np.int64)
30
+ if wav.shape[0] < self.crop * FRAME: # dialogue shorter than the crop: pad, and ignore padded frames
31
+ wav = np.pad(wav, ((0, self.crop * FRAME - wav.shape[0]), (0, 0)))
32
+ labels = np.pad(labels, (0, self.crop - len(labels)), constant_values=-100)
33
+ yield torch.from_numpy(np.ascontiguousarray(wav.T)), torch.from_numpy(labels)
34
+ count += 1
data/gen_dialogues.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Write two-speaker phone dialogues as text with an open LLM behind any
2
+ OpenAI-compatible endpoint (the runbook serves an Apache-2.0 model with vLLM on GPU 1).
3
+
4
+ Each line of the output is one dialogue with its cast (voices, speeds, split) and turns.
5
+ Markers the later steps rely on:
6
+ [pause] inside a caller turn: the caller stops mid-sentence, then goes on
7
+ "interrupts": true on a caller turn: spoken over the agent's previous turn
8
+ "self_correction" on a caller turn: kept for the statistics
9
+
10
+ python -m data.gen_dialogues --base-url http://localhost:8001/v1 --model Qwen/Qwen3-32B \
11
+ --num-dialogues 3000 --out data/out/dialogues.jsonl
12
+ """
13
+ import argparse
14
+ import asyncio
15
+ import json
16
+ import random
17
+ import re
18
+ from pathlib import Path
19
+
20
+ import aiohttp
21
+
22
+ from data.scenarios import STYLES, TEST_VOICES, TRAIN_VOICES, split_scenarios
23
+
24
+ PROMPT = """Write one phone conversation between a CALLER and an AGENT (a helpful voice assistant).
25
+
26
+ Scenario: {domain}: the caller wants to {task}.
27
+ Caller style: {style}.
28
+ Length: {n_turns} turns. The {first} speaks first. Speakers strictly alternate.
29
+
30
+ Rules:
31
+ - Natural spoken English, the way people really talk on the phone. Mix short and long turns.
32
+ - No stage directions, no emojis, no markdown. No names of real people or real companies.
33
+ - Spell out every number and symbol in words ("twenty five dollars", never "$25").
34
+ - In {k_pause} caller turns, put the marker [pause] where the caller stops in the middle of a sentence to think and then continues the same sentence. The words before [pause] must not sound finished.
35
+ - In {k_corr} caller turns, the caller corrects themselves mid-sentence ("on Tuesday, no, sorry, Wednesday"). Set "self_correction": true on those turns.
36
+ - In {k_int} caller turns, the caller cuts in while the agent is still talking. Set "interrupts": true on those turns. The agent turn right before it must be long (at least thirty words), the caller's words must make sense as an interruption, and the agent's next turn responds to it.
37
+ - Agent turns that explain something run twenty to sixty words.
38
+
39
+ Return only JSON:
40
+ {{"turns": [{{"spk": "caller", "text": "...", "interrupts": false, "self_correction": false}}, {{"spk": "agent", "text": "..."}}]}}"""
41
+
42
+
43
+ def make_cast(i, n_total, seed):
44
+ """Everything about dialogue i that is decided before the LLM writes it."""
45
+ rng = random.Random(f"{seed}-{i}")
46
+ train_s, test_s = split_scenarios(seed)
47
+ split = "test" if i < round(n_total * 0.1) else "train"
48
+ domain, task = rng.choice(test_s if split == "test" else train_s)
49
+ caller, agent = rng.sample(TEST_VOICES if split == "test" else TRAIN_VOICES, 2)
50
+ return {
51
+ "id": f"{split}_{i:06d}", "split": split, "domain": domain, "task": task, "style": rng.choice(STYLES),
52
+ "caller_voice": caller, "agent_voice": agent,
53
+ "caller_speed": round(rng.uniform(0.9, 1.15), 2), "agent_speed": round(rng.uniform(0.95, 1.1), 2),
54
+ "n_turns": rng.randint(8, 18), "first": rng.choice(["AGENT", "AGENT", "CALLER"]),
55
+ "k_pause": rng.randint(1, 3), "k_corr": rng.randint(0, 1), "k_int": rng.randint(0, 2),
56
+ }
57
+
58
+
59
+ def clean(raw):
60
+ """Parse and validate the model's JSON. Returns the turn list, or None to retry."""
61
+ raw = re.sub(r"<think>.*?</think>", "", raw, flags=re.S)
62
+ m = re.search(r"\{.*\}", raw, flags=re.S)
63
+ if not m:
64
+ return None
65
+ try:
66
+ turns = json.loads(m.group(0))["turns"]
67
+ except (ValueError, KeyError, TypeError):
68
+ return None
69
+ out = []
70
+ for t in turns if isinstance(turns, list) else []:
71
+ if not isinstance(t, dict) or t.get("spk") not in ("caller", "agent") or not isinstance(t.get("text"), str):
72
+ return None
73
+ text = re.sub(r"\((.*?)\)|\[(?!pause\])[^\]]*\]|[*_#`]", " ", t["text"])
74
+ text = re.sub(r"\s+", " ", text).strip()
75
+ if not text or re.search(r"\d", text) or len(text) > 900:
76
+ return None
77
+ if out and out[-1]["spk"] == t["spk"]:
78
+ return None # speakers must alternate
79
+ if t["spk"] == "agent":
80
+ text = text.replace("[pause]", " ").strip()
81
+ else:
82
+ parts = [p.strip() for p in text.split("[pause]")]
83
+ if any(len(p.split()) < 2 for p in parts): # a fragment too short to voice: drop the markers
84
+ text = " ".join(p for p in parts if p)
85
+ out.append({
86
+ "spk": t["spk"], "text": text,
87
+ "interrupts": bool(t.get("interrupts")) and t["spk"] == "caller" and bool(out),
88
+ "self_correction": bool(t.get("self_correction")) and t["spk"] == "caller",
89
+ })
90
+ return out if len(out) >= 6 else None
91
+
92
+
93
+ async def one(session, args, cast, sem, extra):
94
+ body = {
95
+ "model": args.model, "temperature": 0.9, "max_tokens": 3000, "response_format": {"type": "json_object"},
96
+ "messages": [
97
+ {"role": "system", "content": "You write realistic two-speaker phone conversations and return strict JSON."},
98
+ {"role": "user", "content": PROMPT.format(**cast)},
99
+ ], **extra,
100
+ }
101
+ async with sem:
102
+ for _ in range(4):
103
+ try:
104
+ async with session.post(args.base_url.rstrip("/") + "/chat/completions", json=body) as r:
105
+ r.raise_for_status()
106
+ raw = (await r.json())["choices"][0]["message"]["content"] or ""
107
+ except (aiohttp.ClientError, asyncio.TimeoutError, KeyError, ValueError) as e:
108
+ print(f"{cast['id']}: request failed: {e!r}")
109
+ continue
110
+ turns = clean(raw)
111
+ if turns:
112
+ return {**cast, "turns": turns}
113
+ return None
114
+
115
+
116
+ async def main():
117
+ ap = argparse.ArgumentParser()
118
+ ap.add_argument("--base-url", required=True)
119
+ ap.add_argument("--model", required=True)
120
+ ap.add_argument("--out", required=True)
121
+ ap.add_argument("--num-dialogues", type=int, default=3000, help="set from the measured mean dialogue length to land on 50 to 100 hours")
122
+ ap.add_argument("--concurrency", type=int, default=64)
123
+ ap.add_argument("--seed", type=int, default=0)
124
+ ap.add_argument("--shard", type=int, default=0, help="write only dialogues with index % num-shards == shard (one process per LLM replica)")
125
+ ap.add_argument("--num-shards", type=int, default=1)
126
+ ap.add_argument("--api-key", default="none")
127
+ ap.add_argument("--extra-body", default='{"chat_template_kwargs": {"enable_thinking": false}}')
128
+ args = ap.parse_args()
129
+
130
+ out = Path(args.out)
131
+ out.parent.mkdir(parents=True, exist_ok=True)
132
+ done = {json.loads(line)["id"] for line in out.open(encoding="utf-8")} if out.exists() else set()
133
+ casts = [c for c in (make_cast(i, args.num_dialogues, args.seed) for i in range(args.num_dialogues) if i % args.num_shards == args.shard)
134
+ if c["id"] not in done]
135
+ print(f"{len(done)} already written, {len(casts)} to write")
136
+
137
+ sem, ok, failed = asyncio.Semaphore(args.concurrency), 0, 0
138
+ timeout = aiohttp.ClientTimeout(total=600)
139
+ async with aiohttp.ClientSession(timeout=timeout, headers={"Authorization": f"Bearer {args.api_key}"}) as session:
140
+ with out.open("a", encoding="utf-8") as f:
141
+ for fut in asyncio.as_completed([one(session, args, c, sem, json.loads(args.extra_body)) for c in casts]):
142
+ d = await fut
143
+ if d:
144
+ f.write(json.dumps(d, ensure_ascii=False) + "\n")
145
+ f.flush()
146
+ ok += 1
147
+ else:
148
+ failed += 1
149
+ if (ok + failed) % 100 == 0:
150
+ print(f"written {ok}, failed {failed}")
151
+ print(f"done: written {ok}, failed after retries {failed}")
152
+
153
+
154
+ if __name__ == "__main__":
155
+ asyncio.run(main())
data/scenarios.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """What the dialogues are about, who voices them, and the held-out split.
2
+
3
+ The test set is held out by voice AND by scenario: a test dialogue uses only test
4
+ scenarios and only test voices; a train dialogue uses neither.
5
+ """
6
+ import random
7
+
8
+ DOMAINS = {
9
+ "bank": ["dispute a card charge", "raise a transfer limit", "report a lost card", "ask about a loan payoff", "set up a travel notice"],
10
+ "airline": ["rebook a cancelled flight", "add a checked bag", "ask about a refund", "change a seat", "track delayed luggage"],
11
+ "hotel": ["extend a stay", "request a late checkout", "fix a billing error", "book an airport shuttle", "ask about parking"],
12
+ "pharmacy": ["refill a prescription", "ask when an order is ready", "transfer a prescription", "ask about pickup hours", "update insurance details"],
13
+ "internet provider": ["report an outage", "upgrade a plan", "schedule a technician", "question a bill", "return a router"],
14
+ "it helpdesk": ["reset a password", "set up a laptop", "fix a printer", "request software access", "report a phishing email"],
15
+ "restaurant": ["book a table", "change a reservation", "ask about allergens", "order catering", "ask about a private room"],
16
+ "doctor's office": ["book an appointment", "reschedule a visit", "ask for test results timing", "request a referral", "update contact details"],
17
+ "car service": ["book an oil change", "ask about a repair quote", "arrange a loaner car", "check on a repair", "ask about a recall"],
18
+ "online store": ["return an item", "track a package", "change a delivery address", "use a gift card", "report a damaged item"],
19
+ "insurance": ["start a claim", "add a driver", "ask what a policy covers", "update an address", "ask why a premium went up"],
20
+ "utility company": ["report a power cut", "set up a payment plan", "start service at a new home", "submit a meter reading", "question a high bill"],
21
+ "gym": ["freeze a membership", "book a class", "cancel a membership", "ask about personal training", "update a payment card"],
22
+ "university office": ["ask about enrolment dates", "request a transcript", "ask about a tuition payment", "change a course", "book an advising slot"],
23
+ "travel agency": ["plan a weekend trip", "change a tour date", "ask about travel insurance", "add a rental car", "ask about visa paperwork"],
24
+ "mobile carrier": ["add a line", "ask about roaming", "replace a broken phone", "dispute a data charge", "port a number"],
25
+ "property manager": ["report a leak", "ask about a lease renewal", "request a parking permit", "book the shared room", "report a noisy neighbour"],
26
+ "delivery service": ["reschedule a delivery", "report a missing parcel", "arrange a pickup", "ask about customs fees", "change delivery instructions"],
27
+ "voice assistant at home": ["plan dinner for guests", "work out a monthly budget", "compare two phone plans", "plan a study schedule", "troubleshoot a smart light"],
28
+ "tutor": ["explain compound interest", "practice a job interview", "walk through a logic puzzle", "explain how tides work", "review a short essay plan"],
29
+ "event venue": ["book a hall", "ask about catering options", "change a guest count", "ask about sound equipment", "arrange accessibility access"],
30
+ "tax helpline": ["ask about a filing deadline", "ask about a deduction", "correct a filed form", "set up instalments", "ask about a refund status"],
31
+ "vet clinic": ["book a vaccination", "ask about a sick pet", "refill pet medication", "ask about boarding", "arrange a follow-up"],
32
+ "library": ["renew a loan", "reserve a study room", "ask about a late fee", "find a book", "sign up for a workshop"],
33
+ }
34
+
35
+ STYLES = ["calm and brief", "chatty and friendly", "hurried and a little impatient", "unsure and hesitant",
36
+ "precise and detail-minded", "tired and distracted", "cheerful", "frustrated but polite"]
37
+
38
+ # Kokoro-82M English voice packs (am_santa is left out: it is a character voice).
39
+ VOICES = [
40
+ "af_alloy", "af_aoede", "af_bella", "af_heart", "af_jessica", "af_kore", "af_nicole", "af_nova", "af_river", "af_sarah", "af_sky",
41
+ "am_adam", "am_echo", "am_eric", "am_fenrir", "am_liam", "am_michael", "am_onyx", "am_puck",
42
+ "bf_alice", "bf_emma", "bf_isabella", "bf_lily",
43
+ "bm_daniel", "bm_fable", "bm_george", "bm_lewis",
44
+ ]
45
+ TEST_VOICES = ["af_river", "am_liam", "bf_lily", "bm_lewis"] # one per group, never used in training
46
+ TRAIN_VOICES = [v for v in VOICES if v not in TEST_VOICES]
47
+
48
+ BACKCHANNELS = ["mm-hm", "uh-huh", "yeah", "right", "okay", "I see", "mhm", "sure", "got it", "oh, okay"]
49
+
50
+
51
+ def split_scenarios(seed=0, test_fraction=0.1):
52
+ all_s = [(d, t) for d, tasks in DOMAINS.items() for t in tasks]
53
+ random.Random(seed).shuffle(all_s)
54
+ n_test = max(1, round(len(all_s) * test_fraction))
55
+ return all_s[n_test:], all_s[:n_test] # train, test
data/synth_tts.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Voice every dialogue turn with Kokoro-82M (Apache-2.0) preset voice packs.
2
+
3
+ No voice is cloned: only the voice packs shipped with the model are used. Each turn is
4
+ voiced as one clip, or as several when the caller pauses mid-sentence ([pause]).
5
+ Output: one .npz per dialogue (16 kHz int16 clips named t<turn>_s<segment>), plus one
6
+ bank of backchannels ("mm-hm" ...) per voice.
7
+
8
+ Run one process per shard, several per GPU:
9
+ CUDA_VISIBLE_DEVICES=1 python -m data.synth_tts --dialogues data/out/dialogues.jsonl \
10
+ --out data/out/tts --shard 0 --num-shards 12
11
+ """
12
+ import argparse
13
+ import os
14
+ from pathlib import Path
15
+
16
+ import numpy as np
17
+ import torch
18
+ import torchaudio
19
+
20
+ from data.scenarios import BACKCHANNELS, VOICES
21
+ from duplex.spec import SR, read_jsonl
22
+
23
+ KOKORO_SR = 24000
24
+
25
+
26
+ class Voicer:
27
+ def __init__(self, device):
28
+ from kokoro import KPipeline
29
+ # 'a' = American English, 'b' = British English: the language code must match the voice prefix
30
+ self.pipes = {code: KPipeline(lang_code=code, repo_id="hexgrad/Kokoro-82M", device=device) for code in "ab"}
31
+
32
+ def say(self, text, voice, speed):
33
+ chunks = []
34
+ for _, _, audio in self.pipes[voice[0]](text, voice=voice, speed=speed):
35
+ if audio is not None:
36
+ chunks.append(torch.as_tensor(audio).float().flatten().cpu())
37
+ if not chunks:
38
+ return np.zeros(0, dtype=np.int16)
39
+ wav = torchaudio.functional.resample(torch.cat(chunks), KOKORO_SR, SR)
40
+ return (wav.clamp(-1, 1) * 32767).numpy().astype(np.int16)
41
+
42
+
43
+ def save(path, clips):
44
+ tmp = path.with_suffix(".tmp.npz")
45
+ np.savez(tmp, **clips)
46
+ os.replace(tmp, path)
47
+
48
+
49
+ def main():
50
+ ap = argparse.ArgumentParser()
51
+ ap.add_argument("--dialogues", required=True)
52
+ ap.add_argument("--out", required=True)
53
+ ap.add_argument("--shard", type=int, default=0)
54
+ ap.add_argument("--num-shards", type=int, default=1)
55
+ ap.add_argument("--limit", type=int, default=None, help="voice only the first N dialogues of this shard (smoke test)")
56
+ ap.add_argument("--pause-suffix", default=",", help="appended to the words before a [pause] so they do not sound finished")
57
+ args = ap.parse_args()
58
+
59
+ out = Path(args.out)
60
+ out.mkdir(parents=True, exist_ok=True)
61
+ voicer = Voicer("cuda" if torch.cuda.is_available() else "cpu")
62
+
63
+ for i, voice in enumerate(VOICES):
64
+ path = out / f"_bank_{voice}.npz"
65
+ if i % args.num_shards == args.shard and not path.exists():
66
+ save(path, {f"b{k}": voicer.say(text, voice, 1.0) for k, text in enumerate(BACKCHANNELS)})
67
+
68
+ todo = [d for i, d in enumerate(read_jsonl(args.dialogues)) if i % args.num_shards == args.shard][: args.limit]
69
+ seconds = 0.0
70
+ for n, d in enumerate(todo):
71
+ path = out / f"{d['id']}.npz"
72
+ if path.exists():
73
+ continue
74
+ clips = {}
75
+ for ti, turn in enumerate(d["turns"]):
76
+ voice, speed = (d["caller_voice"], d["caller_speed"]) if turn["spk"] == "caller" else (d["agent_voice"], d["agent_speed"])
77
+ parts = [p.strip() for p in turn["text"].split("[pause]") if p.strip()]
78
+ for si, text in enumerate(parts):
79
+ if si < len(parts) - 1 and text[-1].isalnum():
80
+ text += args.pause_suffix
81
+ clips[f"t{ti}_s{si}"] = voicer.say(text, voice, speed)
82
+ seconds += len(clips[f"t{ti}_s{si}"]) / SR
83
+ save(path, clips)
84
+ if n % 50 == 0:
85
+ print(f"shard {args.shard}: {n + 1}/{len(todo)} dialogues, {seconds / 3600:.2f} h of speech", flush=True)
86
+ print(f"shard {args.shard} done: {seconds / 3600:.3f} h of speech voiced in this run")
87
+
88
+
89
+ if __name__ == "__main__":
90
+ main()
duplex/__init__.py ADDED
File without changes
duplex/spec.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared constants and tiny I/O helpers. Every other module imports these, so the
2
+ frame grid, label ids and file layout are defined exactly once."""
3
+ import json
4
+ import wave
5
+ from pathlib import Path
6
+
7
+ import numpy as np
8
+
9
+ SR = 16000 # input sample rate (caller audio, and self audio as the controller sees it)
10
+ FRAME_MS = 80
11
+ FRAME = SR * FRAME_MS // 1000 # 1280 samples per 80 ms frame
12
+ HOP = 160 # 10 ms mel hop (same as the baseline encoder's front end)
13
+ N_FFT = 400
14
+ N_MELS = 128
15
+ PATCH = 4 # mel frames per encoder token: 40 ms, 25 Hz (the baseline encoder's output rate)
16
+ TOK_PER_FRAME = FRAME // (HOP * PATCH) # 2 encoder tokens per 80 ms frame
17
+ TEACHER_DIM = 1280 # baseline AudioEncoder n_audio_state (config.json of Step-Audio-R1.1)
18
+
19
+ OUT_SR = 24000 # reply audio sample rate (Step-Audio 2 token2wav and Kokoro both emit 24 kHz)
20
+ OUT_FRAME = OUT_SR * FRAME_MS // 1000 # 1920 samples
21
+
22
+ LABELS = ["WAIT", "START", "STOP", "BACKCHANNEL"]
23
+ WAIT, START, STOP, BACKCHANNEL = range(4)
24
+
25
+ CALLER, AGENT = 0, 1 # channel order in every dataset wav
26
+
27
+
28
+ def read_wav(path, start=0, frames=None):
29
+ """PCM16 wav -> float32 [T, C] in [-1, 1], sample rate. Reads only the requested slice."""
30
+ with wave.open(str(path), "rb") as w:
31
+ assert w.getsampwidth() == 2, f"{path}: expected 16-bit PCM"
32
+ n = w.getnframes()
33
+ start = min(start, n)
34
+ frames = n - start if frames is None else min(frames, n - start)
35
+ w.setpos(start)
36
+ x = np.frombuffer(w.readframes(frames), dtype="<i2").reshape(-1, w.getnchannels())
37
+ return x.astype(np.float32) / 32768.0, w.getframerate()
38
+
39
+
40
+ def wav_len(path):
41
+ with wave.open(str(path), "rb") as w:
42
+ return w.getnframes()
43
+
44
+
45
+ def write_wav(path, x, sr):
46
+ """float [T] or [T, C] in [-1, 1] -> PCM16 wav."""
47
+ x = np.asarray(x, dtype=np.float32)
48
+ if x.ndim == 1:
49
+ x = x[:, None]
50
+ pcm = (np.clip(x, -1.0, 1.0) * 32767.0).astype("<i2")
51
+ Path(path).parent.mkdir(parents=True, exist_ok=True)
52
+ with wave.open(str(path), "wb") as w:
53
+ w.setnchannels(pcm.shape[1])
54
+ w.setsampwidth(2)
55
+ w.setframerate(sr)
56
+ w.writeframes(pcm.tobytes())
57
+
58
+
59
+ def read_jsonl(path):
60
+ with open(path, encoding="utf-8") as f:
61
+ return [json.loads(line) for line in f if line.strip()]
62
+
63
+
64
+ def write_json(path, obj):
65
+ Path(path).parent.mkdir(parents=True, exist_ok=True)
66
+ with open(path, "w", encoding="utf-8") as f:
67
+ json.dump(obj, f, indent=2, ensure_ascii=False)
duplex/streaming.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A causal transformer that gives the same output offline and frame by frame.
2
+
3
+ Offline (training): `forward(x)` uses a banded causal mask: token i attends to the
4
+ `window` tokens ending at i. Streaming (serving): `step(x, state)` keeps, per layer,
5
+ the keys and values of the last `window - 1` tokens. The two are the same function
6
+ (tests/test_streaming.py checks it), so a model trained on whole crops can be
7
+ served one 80 ms frame at a time without drift.
8
+
9
+ Positions are rotary, so only distances matter and a session can run for hours.
10
+ """
11
+ import math
12
+
13
+ import torch
14
+ import torch.nn as nn
15
+ import torch.nn.functional as F
16
+
17
+
18
+ def _rope(pos, dim, device):
19
+ """cos/sin tables [T, dim/2] for integer positions `pos` [T]. float64 angles so
20
+ long sessions keep precision."""
21
+ inv = 1.0 / (10000.0 ** (torch.arange(0, dim, 2, device=device, dtype=torch.float64) / dim))
22
+ ang = pos.to(torch.float64)[:, None] * inv[None, :]
23
+ return ang.cos().float(), ang.sin().float()
24
+
25
+
26
+ def _rotate(x, cos, sin):
27
+ """x [B, H, T, Dh]; rotate pairs (even, odd) by the position angle."""
28
+ x1, x2 = x[..., 0::2], x[..., 1::2]
29
+ cos, sin = cos.to(x.dtype), sin.to(x.dtype)
30
+ return torch.stack((x1 * cos - x2 * sin, x1 * sin + x2 * cos), dim=-1).flatten(-2)
31
+
32
+
33
+ class Block(nn.Module):
34
+ def __init__(self, dim, heads, mlp_ratio=4):
35
+ super().__init__()
36
+ assert dim % heads == 0 and (dim // heads) % 2 == 0
37
+ self.heads = heads
38
+ self.ln1 = nn.LayerNorm(dim)
39
+ self.qkv = nn.Linear(dim, 3 * dim)
40
+ self.out = nn.Linear(dim, dim)
41
+ self.ln2 = nn.LayerNorm(dim)
42
+ self.mlp = nn.Sequential(nn.Linear(dim, mlp_ratio * dim), nn.GELU(), nn.Linear(mlp_ratio * dim, dim))
43
+
44
+ def _qkv(self, x, cos, sin):
45
+ B, T, D = x.shape
46
+ q, k, v = self.qkv(self.ln1(x)).view(B, T, 3, self.heads, D // self.heads).permute(2, 0, 3, 1, 4)
47
+ return _rotate(q, cos, sin), _rotate(k, cos, sin), v
48
+
49
+ def forward(self, x, cos, sin, mask):
50
+ q, k, v = self._qkv(x, cos, sin)
51
+ a = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)
52
+ x = x + self.out(a.transpose(1, 2).flatten(2))
53
+ return x + self.mlp(self.ln2(x))
54
+
55
+ def step(self, x, cos, sin, cache, window, seen):
56
+ """x [B, t, D] new tokens; cache = (k, v) of the last window-1 tokens; seen = tokens before this step.
57
+
58
+ The cache has its full size from the first step (zeros, masked out until real tokens
59
+ arrive), so every step has the same tensor shapes. Measured: with a cache that grew step
60
+ by step, a controller step took 53 ms until the window was full and 13 ms after."""
61
+ q, k, v = self._qkv(x, cos, sin)
62
+ keep = window - 1
63
+ if cache is None:
64
+ cache = (k.new_zeros(k.shape[0], k.shape[1], keep, k.shape[3]), v.new_zeros(v.shape[0], v.shape[1], keep, v.shape[3]))
65
+ k = torch.cat([cache[0], k], dim=2)
66
+ v = torch.cat([cache[1], v], dim=2)
67
+ t, S = q.shape[2], k.shape[2]
68
+ # key j (0..S-1) sits at distance (S - t + i) - j behind new token i; the first keys are empty slots
69
+ j = torch.arange(S, device=x.device)
70
+ dist = (S - t + torch.arange(t, device=x.device))[:, None] - j[None, :]
71
+ mask = (dist >= 0) & (dist < window) & (j[None, :] >= keep - min(seen, keep))
72
+ a = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)
73
+ x = x + self.out(a.transpose(1, 2).flatten(2))
74
+ return x + self.mlp(self.ln2(x)), (k[:, :, t:], v[:, :, t:])
75
+
76
+
77
+ class CausalTransformer(nn.Module):
78
+ def __init__(self, dim, layers, heads, window):
79
+ super().__init__()
80
+ self.dim, self.heads, self.window = dim, heads, window
81
+ self.blocks = nn.ModuleList([Block(dim, heads) for _ in range(layers)])
82
+
83
+ def forward(self, x):
84
+ T = x.shape[1]
85
+ idx = torch.arange(T, device=x.device)
86
+ cos, sin = _rope(idx, self.dim // self.heads, x.device)
87
+ dist = idx[:, None] - idx[None, :]
88
+ mask = (dist >= 0) & (dist < self.window)
89
+ for b in self.blocks:
90
+ x = b(x, cos, sin, mask)
91
+ return x
92
+
93
+ def init_state(self):
94
+ return {"pos": 0, "cache": [None] * len(self.blocks)}
95
+
96
+ def step(self, x, state):
97
+ t = x.shape[1]
98
+ pos = torch.arange(state["pos"], state["pos"] + t, device=x.device)
99
+ cos, sin = _rope(pos, self.dim // self.heads, x.device)
100
+ cache = []
101
+ for b, c in zip(self.blocks, state["cache"]):
102
+ x, c = b.step(x, cos, sin, c, self.window, state["pos"])
103
+ cache.append(c)
104
+ return x, {"pos": state["pos"] + t, "cache": cache}
105
+
106
+
107
+ def count_params(m):
108
+ return sum(p.numel() for p in m.parameters())
109
+
110
+
111
+ def cosine_by_time(frac, warmup=0.02, floor=0.05):
112
+ """LR multiplier as a function of elapsed wall-clock fraction (runs are time-budgeted)."""
113
+ if frac < warmup:
114
+ return frac / warmup
115
+ return floor + (1 - floor) * 0.5 * (1 + math.cos(math.pi * min(1.0, (frac - warmup) / (1 - warmup))))
116
+
117
+
118
+ def read_checkpoint(path):
119
+ """(cfg, state dict) of a model of this repository, from a training checkpoint (.pt) or from the
120
+ published form: <name>.safetensors with <name>.json (the cfg) beside it."""
121
+ import json
122
+ from pathlib import Path
123
+ path = Path(path)
124
+ if path.suffix == ".safetensors":
125
+ from safetensors.torch import load_file
126
+ return json.loads(path.with_suffix(".json").read_text(encoding="utf-8"))["cfg"], load_file(str(path))
127
+ ck = torch.load(path, map_location="cpu", weights_only=True)
128
+ return ck["cfg"], ck["model"]
duplex/train_utils.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Small helpers shared by the two trainers: DDP setup, a wall-clock budget that all
2
+ ranks agree on, hourly checkpoints, a JSONL log, label metrics."""
3
+ import json
4
+ import os
5
+ import time
6
+
7
+ import numpy as np
8
+ import torch
9
+ import torch.distributed as dist
10
+
11
+ from duplex.spec import LABELS
12
+
13
+
14
+ def setup_ddp():
15
+ world = int(os.environ.get("WORLD_SIZE", "1"))
16
+ rank = int(os.environ.get("RANK", "0"))
17
+ local = int(os.environ.get("LOCAL_RANK", "0"))
18
+ if world > 1:
19
+ torch.cuda.set_device(local)
20
+ dist.init_process_group("nccl")
21
+ device = torch.device("cuda", local) if torch.cuda.is_available() else torch.device("cpu")
22
+ torch.backends.cuda.matmul.allow_tf32 = True
23
+ torch.backends.cudnn.allow_tf32 = True
24
+ return rank, world, device
25
+
26
+
27
+ class Budget:
28
+ """Rank 0's clock is the only clock: every rank reads the same elapsed time, so they
29
+ use the same learning rate and stop on the same step."""
30
+
31
+ def __init__(self, max_hours, rank, world, device, ckpt_minutes=60.0):
32
+ self.t0, self.max_s = time.time(), max_hours * 3600.0
33
+ self.rank, self.world, self.device = rank, world, device
34
+ self.elapsed, self.every_s, self.next_ckpt = 0.0, ckpt_minutes * 60.0, 1
35
+
36
+ def sync(self):
37
+ t = torch.tensor([time.time() - self.t0 if self.rank == 0 else 0.0], device=self.device, dtype=torch.float64)
38
+ if self.world > 1:
39
+ dist.all_reduce(t)
40
+ self.elapsed = float(t.item())
41
+ return self.elapsed / self.max_s
42
+
43
+ def checkpoint_due(self):
44
+ """Returns the checkpoint number once, right after each full interval."""
45
+ if self.elapsed >= self.next_ckpt * self.every_s:
46
+ self.next_ckpt += 1
47
+ return self.next_ckpt - 1
48
+ return None
49
+
50
+
51
+ def log_row(path, **row):
52
+ row = {k: (round(v, 6) if isinstance(v, float) else v) for k, v in row.items()}
53
+ print(json.dumps(row), flush=True)
54
+ if path:
55
+ with open(path, "a", encoding="utf-8") as f:
56
+ f.write(json.dumps(row) + "\n")
57
+
58
+
59
+ def confusion(pred, gold, n=len(LABELS)):
60
+ """Rows are the true label, columns the predicted one. Frames with gold < 0 are skipped."""
61
+ pred, gold = np.asarray(pred).reshape(-1), np.asarray(gold).reshape(-1)
62
+ keep = gold >= 0
63
+ return np.bincount(gold[keep] * n + pred[keep], minlength=n * n).reshape(n, n)
64
+
65
+
66
+ def precision_recall(conf):
67
+ out = {}
68
+ for i, name in enumerate(LABELS):
69
+ tp, pred_n, gold_n = int(conf[i, i]), int(conf[:, i].sum()), int(conf[i, :].sum())
70
+ out[name] = {
71
+ "precision": tp / pred_n if pred_n else None,
72
+ "recall": tp / gold_n if gold_n else None,
73
+ "frames": gold_n,
74
+ "predicted": pred_n,
75
+ }
76
+ return out
eval/__init__.py ADDED
File without changes
eval/eval_bba.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """100 Big Bench Audio questions through the endpoint, with and without the controller.
2
+
3
+ without endpointing "manual": the question is committed the instant its audio ends,
4
+ so nothing but the model decides the answer.
5
+ with endpointing "controller": the controller alone decides when to answer. If it
6
+ starts early, the model answers a cut-off question and that shows up here.
7
+
8
+ Scoring is ours, not Artificial Analysis's judge model: the reply text after the last
9
+ "</think>" is searched for the last valid/invalid, yes/no or number, and compared with
10
+ the official answer. Scores are comparable between the two modes of this run, not with
11
+ the public leaderboard. Raw replies (text and audio) are saved so they can be re-scored.
12
+
13
+ python -m eval.eval_bba --data eval/data/bba --out eval/results/bba --modes manual,controller
14
+ """
15
+ import argparse
16
+ import asyncio
17
+ import json
18
+ import re
19
+ from collections import defaultdict
20
+ from pathlib import Path
21
+
22
+ import aiohttp
23
+ import numpy as np
24
+
25
+ from duplex.spec import OUT_SR, write_json, write_wav
26
+ from eval.ws_client import load_16k, open_session, percentiles, run_turn
27
+
28
+ SYSTEM = ('Listen to the question and answer it. Reply with only "valid" or "invalid", "yes" or "no", '
29
+ "or a number. Do not add anything else.")
30
+
31
+ # Third run: Whisper recognised only 71 of 94 one-word spoken answers (the model gives a lone word very little
32
+ # audio, down to 0.16 s). "sentence" asks for the answer inside one short sentence instead.
33
+ SYSTEMS = {"word": SYSTEM,
34
+ "sentence": ('Listen to the question and answer it in one short spoken sentence that states the answer: "valid" or "invalid", '
35
+ '"yes" or "no", or the number. Do not add anything else.')}
36
+
37
+ UNITS = "zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen".split()
38
+ TENS = "twenty thirty forty fifty sixty seventy eighty ninety".split()
39
+ # digits, "twenty", "twenty one" / "twenty-one", or a single word from zero to nineteen
40
+ NUMBER = rf"\d+|(?:{'|'.join(TENS)})(?:[\s-](?:{'|'.join(UNITS[1:10])}))?|(?:{'|'.join(UNITS)})"
41
+
42
+
43
+ def to_number(s):
44
+ words = re.split(r"[\s-]+", s.strip().lower())
45
+ if len(words) == 1 and words[0].isdigit():
46
+ return int(words[0])
47
+ if len(words) == 1 and words[0] in UNITS:
48
+ return UNITS.index(words[0])
49
+ if words[0] in TENS and (len(words) == 1 or (len(words) == 2 and words[1] in UNITS[1:10])):
50
+ return 10 * (TENS.index(words[0]) + 2) + (UNITS.index(words[1]) if len(words) == 2 else 0)
51
+ return None
52
+
53
+
54
+ def parse_answer(text, official):
55
+ """The last answer of the right kind in the spoken part of the reply, or None."""
56
+ say = re.sub(r"<[^>]+>", " ", text.split("</think>")[-1]).lower()
57
+ official = official.strip().lower()
58
+ if official in ("valid", "invalid"):
59
+ found = re.findall(r"\b(invalid|valid)\b", say)
60
+ elif official in ("yes", "no"):
61
+ found = re.findall(r"\b(yes|no)\b", say)
62
+ else:
63
+ found = [str(n) for n in (to_number(m) for m in re.findall(rf"\b({NUMBER})\b", say)) if n is not None]
64
+ official = str(to_number(official)) if to_number(official) is not None else official
65
+ return (found[-1] if found else None), official
66
+
67
+
68
+ async def ask(http, args, q, mode, sem, out):
69
+ async with sem:
70
+ pcm = load_16k(Path(args.data) / f"q_{q['id']}.wav")
71
+ ws = await open_session(http, args.url, SYSTEMS[args.system], mode)
72
+ try:
73
+ r = await run_turn(ws, pcm, commit=(mode == "manual"), until="done_after_audio", max_wait_s=args.max_wait_s)
74
+ finally:
75
+ await ws.close()
76
+ answer, official = parse_answer(r["text"], q["official_answer"])
77
+ row = {
78
+ "id": q["id"], "category": q["category"], "official_answer": official, "answer": answer,
79
+ "correct": answer is not None and answer == official, "replied": r["done"] is not None and r["done"]["reason"] == "done",
80
+ "started_early": r["started_early"], "replies_cut_off": sum(1 for d in r["replies"] if d["reason"] != "done"),
81
+ "latency_ms": r["latency_ms"], "question_s": len(pcm) / 16000, "text": r["text"], "error": r["error"],
82
+ "events": [e for e in r["events"] if e["type"] != "transcript.delta"],
83
+ }
84
+ write_json(out / f"q_{q['id']}.json", row)
85
+ if r["audio"]:
86
+ write_wav(out / f"q_{q['id']}.wav", np.frombuffer(r["audio"], dtype="<i2").astype(np.float32) / 32768, OUT_SR)
87
+ return row
88
+
89
+
90
+ async def main():
91
+ ap = argparse.ArgumentParser()
92
+ ap.add_argument("--url", default="http://localhost:8765/ws")
93
+ ap.add_argument("--data", default="eval/data/bba")
94
+ ap.add_argument("--out", default="eval/results/bba")
95
+ ap.add_argument("--modes", default="manual,controller")
96
+ ap.add_argument("--concurrency", type=int, default=4)
97
+ ap.add_argument("--max-wait-s", type=float, default=90.0)
98
+ ap.add_argument("--system", default="word", choices=list(SYSTEMS), help="how the answer is asked for")
99
+ ap.add_argument("--shard", type=int, default=0, help="ask only questions with index % num-shards == shard (an arm split over several baseline copies)")
100
+ ap.add_argument("--num-shards", type=int, default=1)
101
+ args = ap.parse_args()
102
+
103
+ subset = [q for i, q in enumerate(json.loads((Path(args.data) / "subset.json").read_text())) if i % args.num_shards == args.shard]
104
+ summary = {"questions": len(subset), "scoring": "last valid/invalid, yes/no or number in the reply text; not the leaderboard's judge"}
105
+ async with aiohttp.ClientSession() as http:
106
+ for mode in args.modes.split(","):
107
+ out = Path(args.out) / mode
108
+ out.mkdir(parents=True, exist_ok=True)
109
+ sem = asyncio.Semaphore(args.concurrency)
110
+ rows = await asyncio.gather(*[ask(http, args, q, mode, sem, out) for q in subset])
111
+ by_cat = defaultdict(list)
112
+ for row in rows:
113
+ by_cat[row["category"]].append(row["correct"])
114
+ summary[mode] = {
115
+ "accuracy": sum(r["correct"] for r in rows) / len(rows),
116
+ "accuracy_by_category": {c: sum(v) / len(v) for c, v in sorted(by_cat.items())},
117
+ "replied": sum(r["replied"] for r in rows), "no_answer_found": sum(r["answer"] is None for r in rows),
118
+ "started_early": sum(r["started_early"] for r in rows), "replies_cut_off": sum(r["replies_cut_off"] for r in rows),
119
+ "errors": sum(bool(r["error"]) for r in rows), "latency_ms": percentiles([r["latency_ms"] for r in rows if r["replied"]]),
120
+ }
121
+ print(mode, json.dumps(summary[mode]))
122
+ write_json(Path(args.out) / f"summary_{args.modes.replace(',', '_')}{f'_shard{args.shard}' if args.num_shards > 1 else ''}.json", summary)
123
+
124
+
125
+ if __name__ == "__main__":
126
+ asyncio.run(main())
eval/eval_bba_budget.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """How much thinking does the spoken answer need? One arm per thinking budget.
2
+
3
+ For each of the 100 benchmark questions: the baseline reasons as text for at most
4
+ `--budget` tokens (the reasoning is cut there if it has not closed itself), then the reply
5
+ is opened for speech with that reasoning in it, exactly as the endpoint's think-then-speak
6
+ does. Budget 0 is the plain speech path. The spoken words are scored by the same parser as
7
+ every other arm. Audio tokens are generated but not decoded here (the speech decoder adds
8
+ nothing to the answer), so "seconds to answer" is the time until the spoken answer's first
9
+ audio tokens exist, with one question at a time on a baseline copy of its own.
10
+
11
+ python -m eval.eval_bba_budget --budget 128 --api-url http://127.0.0.1:9992/v1/chat/completions
12
+ """
13
+ import argparse
14
+ import asyncio
15
+ import json
16
+ import time
17
+ from collections import defaultdict
18
+ from pathlib import Path
19
+
20
+ import aiohttp
21
+
22
+ from duplex.spec import write_json
23
+ from eval.eval_bba import SYSTEM, parse_answer
24
+ from eval.ws_client import load_16k, percentiles
25
+ from serving.baseline_client import human_turn, stream_chat
26
+
27
+ NL = chr(10)
28
+ THINK_OPEN, THINK_CLOSE, SPEAK = "<think>" + NL, "</think>", "<tts_start>"
29
+ BRIEF = " Before you answer, think it through in a few short steps."
30
+
31
+
32
+ async def ask(http, args, q, sem, out):
33
+ pcm = load_16k(Path(args.data) / f"q_{q['id']}.wav")
34
+ base = [{"role": "system", "content": SYSTEM + (BRIEF if args.brief else "")}, human_turn(pcm)]
35
+ row = {"id": q["id"], "category": q["category"], "think_tokens": 0, "closed_itself": None, "error": None}
36
+ async with sem:
37
+ t0 = time.perf_counter()
38
+ try:
39
+ thought = ""
40
+ if args.budget > 0:
41
+ n = 0
42
+ async for _, text, _ in stream_chat(http, args.api_url, args.model, base + [{"role": "assistant", "content": THINK_OPEN, "eot": False}],
43
+ max_tokens=args.budget, temperature=0.7, repetition_penalty=1.0, stop_token_ids=[151665],
44
+ stop=[THINK_CLOSE]):
45
+ thought += text
46
+ n += 1
47
+ row["think_tokens"], row["closed_itself"] = n, n < args.budget
48
+ if thought and not thought.endswith(NL):
49
+ thought += NL # cut mid-sentence by the budget: close the block on a new line
50
+ row["think_s"] = time.perf_counter() - t0
51
+ opener = (THINK_OPEN + thought + THINK_CLOSE + NL if args.budget > 0 else "") + SPEAK
52
+ spoken, first_audio = "", None
53
+ async for _, text, tokens in stream_chat(http, args.api_url, args.model, base + [{"role": "assistant", "content": opener, "eot": False}],
54
+ max_tokens=512, temperature=0.7, top_p=0.9, repetition_penalty=1.05, stop_token_ids=[151665]):
55
+ spoken += text
56
+ if tokens and first_audio is None:
57
+ first_audio = time.perf_counter() - t0
58
+ row["answer_s"], row["total_s"] = first_audio, time.perf_counter() - t0
59
+ except Exception as e:
60
+ row["error"], spoken, thought = repr(e), "", ""
61
+ answer, official = parse_answer(spoken, q["official_answer"])
62
+ row.update(official_answer=official, answer=answer, correct=answer is not None and answer == official, spoken=spoken, thought=thought)
63
+ write_json(out / f"q_{q['id']}.json", row)
64
+ return row
65
+
66
+
67
+ async def main():
68
+ ap = argparse.ArgumentParser()
69
+ ap.add_argument("--api-url", required=True)
70
+ ap.add_argument("--model", default="Step-Audio-R1.1")
71
+ ap.add_argument("--data", default="eval/data/bba")
72
+ ap.add_argument("--out", default="eval/results/bba_budget")
73
+ ap.add_argument("--budget", type=int, required=True, help="most reasoning tokens before the speech; 0 = no reasoning")
74
+ ap.add_argument("--brief", action="store_true", help="also ask, in the system prompt, for a few short steps")
75
+ ap.add_argument("--concurrency", type=int, default=1)
76
+ args = ap.parse_args()
77
+
78
+ name = f"budget_{args.budget}" + ("_brief" if args.brief else "")
79
+ out = Path(args.out) / name
80
+ out.mkdir(parents=True, exist_ok=True)
81
+ subset = json.loads((Path(args.data) / "subset.json").read_text())
82
+ sem = asyncio.Semaphore(args.concurrency)
83
+ async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=None)) as http:
84
+ rows = await asyncio.gather(*[ask(http, args, q, sem, out) for q in subset])
85
+ by_cat = defaultdict(list)
86
+ for r in rows:
87
+ by_cat[r["category"]].append(r["correct"])
88
+ summary = {
89
+ "arm": name, "budget": args.budget, "brief": args.brief, "concurrency": args.concurrency, "questions": len(rows),
90
+ "accuracy": sum(r["correct"] for r in rows) / len(rows), "accuracy_by_category": {c: sum(v) / len(v) for c, v in sorted(by_cat.items())},
91
+ "no_answer_found": sum(r["answer"] is None for r in rows), "errors": sum(bool(r["error"]) for r in rows),
92
+ "reasoning_closed_itself": sum(bool(r["closed_itself"]) for r in rows), "think_tokens": percentiles([r["think_tokens"] for r in rows]),
93
+ "seconds_to_spoken_answer": percentiles([r.get("answer_s") for r in rows]),
94
+ }
95
+ write_json(Path(args.out) / f"summary_{name}.json", summary)
96
+ print(json.dumps(summary))
97
+
98
+
99
+ if __name__ == "__main__":
100
+ asyncio.run(main())
eval/eval_bba_text.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reference arm for the benchmark: the same 100 questions sent straight to the baseline
2
+ with the reply opened by "<think>\\n" (the released reasoning examples), text out, no speech.
3
+
4
+ It answers one question the endpoint arms cannot: how much of the reasoning score is lost
5
+ when the model is asked to speak ("<tts_start>") instead of think. Same system prompt and
6
+ same scorer as eval/eval_bba.py, so the three arms compare with each other only.
7
+
8
+ python -m eval.eval_bba_text --data eval/data/bba --out eval/results/bba
9
+ """
10
+ import argparse
11
+ import asyncio
12
+ import json
13
+ import time
14
+ from collections import defaultdict
15
+ from pathlib import Path
16
+
17
+ import aiohttp
18
+
19
+ from duplex.spec import write_json
20
+ from eval.eval_bba import SYSTEM, parse_answer
21
+ from eval.ws_client import load_16k, percentiles
22
+ from serving.baseline_client import human_turn, stream_chat
23
+
24
+
25
+ async def ask(http, args, q, sem, out):
26
+ pcm = load_16k(Path(args.data) / f"q_{q['id']}.wav")
27
+ messages = [{"role": "system", "content": SYSTEM}, human_turn(pcm), {"role": "assistant", "content": "<think>\n", "eot": False}]
28
+ text, error = "", None
29
+ async with sem:
30
+ t0 = time.perf_counter()
31
+ try:
32
+ async for _, t, _ in stream_chat(http, args.api_url, args.model, messages, max_tokens=args.max_tokens, temperature=0.7,
33
+ repetition_penalty=1.0, stop_token_ids=[151665]):
34
+ text += t
35
+ except Exception as e:
36
+ error = repr(e)
37
+ seconds = time.perf_counter() - t0
38
+ answer, official = parse_answer(text, q["official_answer"]) if "</think>" in text else (None, q["official_answer"].strip().lower())
39
+ row = {"id": q["id"], "category": q["category"], "official_answer": official, "answer": answer, "correct": answer is not None and answer == official,
40
+ "finished_thinking": "</think>" in text, "seconds": seconds, "text": text, "error": error}
41
+ write_json(out / f"q_{q['id']}.json", row)
42
+ return row
43
+
44
+
45
+ async def main():
46
+ ap = argparse.ArgumentParser()
47
+ ap.add_argument("--api-url", default="http://127.0.0.1:9999/v1/chat/completions")
48
+ ap.add_argument("--model", default="Step-Audio-R1.1")
49
+ ap.add_argument("--data", default="eval/data/bba")
50
+ ap.add_argument("--out", default="eval/results/bba")
51
+ ap.add_argument("--concurrency", type=int, default=8)
52
+ ap.add_argument("--max-tokens", type=int, default=8192)
53
+ args = ap.parse_args()
54
+
55
+ subset = json.loads((Path(args.data) / "subset.json").read_text())
56
+ out = Path(args.out) / "think_text"
57
+ out.mkdir(parents=True, exist_ok=True)
58
+ sem = asyncio.Semaphore(args.concurrency)
59
+ async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=None)) as http:
60
+ rows = await asyncio.gather(*[ask(http, args, q, sem, out) for q in subset])
61
+ by_cat = defaultdict(list)
62
+ for r in rows:
63
+ by_cat[r["category"]].append(r["correct"])
64
+ summary = {"questions": len(rows), "think_text": {
65
+ "accuracy": sum(r["correct"] for r in rows) / len(rows),
66
+ "accuracy_by_category": {c: sum(v) / len(v) for c, v in sorted(by_cat.items())},
67
+ "finished_thinking": sum(r["finished_thinking"] for r in rows), "no_answer_found": sum(r["answer"] is None for r in rows),
68
+ "errors": sum(bool(r["error"]) for r in rows), "seconds_to_full_answer": percentiles([r["seconds"] for r in rows]),
69
+ }}
70
+ write_json(Path(args.out) / "summary_think_text.json", summary)
71
+ print(json.dumps(summary))
72
+
73
+
74
+ if __name__ == "__main__":
75
+ asyncio.run(main())
eval/eval_controller.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The controller on the held-out set (unseen voices, unseen scenarios).
2
+
3
+ Frame level: precision and recall per label.
4
+ Event level, from the events the data builder recorded:
5
+ pause handling a mid-sentence pause is handled when no START is predicted in it
6
+ turn ends a turn end is caught when START is predicted inside its START window;
7
+ the delay is counted from the caller's last frame
8
+ interruptions caught when STOP is predicted inside the STOP window
9
+ backchannels survived when no STOP is predicted while the caller says "mm-hm"
10
+
11
+ Whole dialogues are run offline with the banded causal mask, which is the same function
12
+ as frame-by-frame serving (tests/test_streaming.py). Raw per-frame predictions are saved.
13
+
14
+ python -m eval.eval_controller --data data/out/dataset --encoder runs/encoder/final.pt \
15
+ --controller runs/controller/final.pt --out eval/results/controller
16
+ """
17
+ import argparse
18
+ import json
19
+ from pathlib import Path
20
+
21
+ import numpy as np
22
+ import torch
23
+
24
+ from controller.encoder.student import load_student
25
+ from controller.model.model import load_controller
26
+ from duplex.spec import FRAME, LABELS, START, STOP, read_wav, write_json
27
+ from duplex.train_utils import confusion, precision_recall
28
+
29
+
30
+ def rate(hits, total):
31
+ return {"correct": int(hits), "total": int(total), "accuracy": hits / total if total else None}
32
+
33
+
34
+ @torch.inference_mode()
35
+ def main():
36
+ ap = argparse.ArgumentParser()
37
+ ap.add_argument("--data", required=True)
38
+ ap.add_argument("--encoder", required=True)
39
+ ap.add_argument("--controller", required=True)
40
+ ap.add_argument("--out", default="eval/results/controller")
41
+ ap.add_argument("--device", default="cuda:1")
42
+ ap.add_argument("--limit", type=int, default=None, help="only the first N held-out dialogues (smoke test)")
43
+ args = ap.parse_args()
44
+
45
+ data, out, device = Path(args.data), Path(args.out), torch.device(args.device)
46
+ (out / "pred").mkdir(parents=True, exist_ok=True)
47
+ encoder, ctl = load_student(args.encoder, device), load_controller(args.controller, device)
48
+
49
+ conf = np.zeros((len(LABELS), len(LABELS)), dtype=np.int64)
50
+ pauses, turn_ends, stops, backchannels = (np.zeros(2, dtype=np.int64) for _ in range(4)) # [hits, total]
51
+ delays, pause_len_ok, pause_len_bad = [], [], []
52
+ items = json.loads((data / "index_test.json").read_text())[: args.limit]
53
+ for it in items:
54
+ wav, _ = read_wav(data / "audio" / f"{it['id']}.wav")
55
+ wav = torch.from_numpy(wav[: it["n_frames"] * FRAME].T.copy()).to(device) # [2, T]
56
+ with torch.autocast(device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):
57
+ feats = encoder(wav)
58
+ probs = torch.softmax(ctl(feats[0:1], feats[1:2])[0].float(), dim=-1).cpu().numpy()
59
+ pred = probs.argmax(-1)
60
+ gold = np.load(data / "labels" / f"{it['id']}.npy")
61
+ conf += confusion(pred, gold)
62
+ np.savez_compressed(out / "pred" / f"{it['id']}.npz", pred=pred.astype(np.uint8), probs=probs.astype(np.float16))
63
+
64
+ for e in json.loads((data / "meta" / f"{it['id']}.json").read_text())["events"]:
65
+ window = pred[e["f0"]: e["f1"]] if "f0" in e else None
66
+ if e["type"] == "pause" and len(window):
67
+ quiet = not (window == START).any()
68
+ pauses = pauses + [quiet, 1]
69
+ (pause_len_ok if quiet else pause_len_bad).append((e["end"] - e["start"]) / 16000)
70
+ elif e["type"] == "start":
71
+ hit = np.nonzero(window == START)[0]
72
+ turn_ends = turn_ends + [len(hit) > 0, 1]
73
+ if len(hit):
74
+ delays.append(float(hit[0] + 1) * 80.0) # ms from the caller's last frame to the first START
75
+ elif e["type"] == "interrupt" and len(window):
76
+ stops = stops + [(window == STOP).any(), 1]
77
+ elif e["type"] == "backchannel" and len(window):
78
+ backchannels = backchannels + [not (window == STOP).any(), 1]
79
+
80
+ result = {
81
+ "dialogues": len(items), "frames": int(conf.sum()), "per_label": precision_recall(conf), "confusion_rows_true_cols_pred": conf.tolist(),
82
+ "pause_handling": rate(*pauses),
83
+ "pause_seconds_mean": {"handled": float(np.mean(pause_len_ok)) if pause_len_ok else None,
84
+ "started_in_pause": float(np.mean(pause_len_bad)) if pause_len_bad else None},
85
+ "turn_end_caught": rate(*turn_ends),
86
+ "start_delay_ms": {"p50": float(np.percentile(delays, 50)), "p90": float(np.percentile(delays, 90))} if delays else None,
87
+ "interruption_caught": rate(*stops), "backchannel_not_interrupted": rate(*backchannels),
88
+ }
89
+ write_json(out / "controller.json", result)
90
+ print(json.dumps(result, indent=2))
91
+
92
+
93
+ if __name__ == "__main__":
94
+ main()
eval/eval_judge.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The baseline as end-of-turn judge (serving/judge.py), measured offline.
2
+
3
+ Cases, all cut from the caller's channel (with its noise), each ending 240 ms into the silence:
4
+ finished a caller turn up to its end (the turns that were answered in the data)
5
+ pause the same kind of turn, cut at a mid-sentence pause
6
+ question Big Bench Audio questions (voices and style nothing here was tuned on):
7
+ cut at every inner silence of 400 ms or more (not finished), and at the end (finished)
8
+
9
+ About half of the data's "pauses" follow a complete sentence ("Thanks for the email.
10
+ [pause] I want to make sure ..."): nobody can know from the words that more is coming.
11
+ So pauses are also reported in two groups by the words before them:
12
+ cut off the last word is a function word (and, but, to, the, my, I ...): clearly unfinished
13
+ other everything else, complete-sounding or not
14
+
15
+ Several variants of the judge (prompt, optional short reasoning) are run on a sample of
16
+ TRAIN-split cases and on all held-out cases. The variant to use is the one with the best
17
+ balanced accuracy on the TRAIN sample; the held-out numbers of every variant are reported.
18
+
19
+ python -m eval.eval_judge --data data/out/dataset --dialogues data/out/dialogues.jsonl --bba eval/data/bba --out eval/results/judge
20
+ """
21
+ import argparse
22
+ import asyncio
23
+ import json
24
+ import random
25
+ import re
26
+ import time
27
+ from pathlib import Path
28
+
29
+ import aiohttp
30
+ import numpy as np
31
+
32
+ from duplex.spec import CALLER, FRAME, SR, read_jsonl, read_wav, write_json
33
+ from eval.ws_client import load_16k, percentiles
34
+ from serving.judge import judge_finished
35
+
36
+ TAIL = int(0.24 * SR) # the judge is asked 240 ms into the silence
37
+ LEAD = int(0.3 * SR)
38
+ FUNCTION_WORDS = set("""and but or so because if that which who when while although though unless until
39
+ to of in on at for with from by about into onto over under between through during before after
40
+ the a an my your our their his her its this these those some any every each no
41
+ i we you they he she it there
42
+ is are was were am be been being have has had do does did can could will would should might may must
43
+ not just than as""".split())
44
+
45
+
46
+ def pause_prefixes(dialogue):
47
+ """The words before each pause of a dialogue, in the order the data builder created the pauses."""
48
+ out = []
49
+ for turn in dialogue["turns"]:
50
+ if turn["spk"] == "caller":
51
+ parts = [p.strip() for p in turn["text"].split("[pause]") if p.strip()]
52
+ out += [" ".join(parts[: i + 1]) for i in range(len(parts) - 1)]
53
+ return out
54
+
55
+
56
+ def cut_off(prefix):
57
+ words = re.findall(r"[a-z']+", prefix.lower())
58
+ return bool(words) and words[-1] in FUNCTION_WORDS and prefix.rstrip()[-1] not in ".?!"
59
+
60
+
61
+ def dialogue_cases(data, split, limit, seed, dialogues=None):
62
+ data, cases = Path(data), []
63
+ for it in json.loads((data / f"index_{split}.json").read_text()):
64
+ events = json.loads((data / "meta" / f"{it['id']}.json").read_text())["events"]
65
+ cuts = {e["onset"] for e in events if e["type"] == "interrupt"}
66
+ answered = {e["caller_end"] for e in events if e["type"] == "start"}
67
+ pauses = [e for e in events if e["type"] == "pause"]
68
+ prefixes = pause_prefixes(dialogues[it["id"]]) if dialogues else []
69
+ for e in events:
70
+ if e["type"] != "caller_turn" or e["start"] in cuts or not 1.0 * SR <= e["end"] - e["start"] <= 25 * SR:
71
+ continue
72
+ if e["end"] in answered:
73
+ cases.append({"kind": "finished", "id": it["id"], "start": e["start"], "cut": e["end"]})
74
+ for k, p in enumerate(pauses):
75
+ if e["start"] < p["start"] < e["end"] and p["end"] - p["start"] >= TAIL + FRAME:
76
+ c = {"kind": "pause", "id": it["id"], "start": e["start"], "cut": p["start"], "pause_index": k}
77
+ if len(prefixes) == len(pauses):
78
+ c["before"], c["cut_off"] = prefixes[k][-80:], cut_off(prefixes[k])
79
+ cases.append(c)
80
+ random.Random(seed).shuffle(cases)
81
+ return cases[:limit] if limit else cases
82
+
83
+
84
+ def question_cases(bba_dir, db=-45.0, min_gap_s=0.4):
85
+ cases = []
86
+ for q in json.loads((Path(bba_dir) / "subset.json").read_text()):
87
+ pcm = load_16k(Path(bba_dir) / f"q_{q['id']}.wav")
88
+ n = len(pcm) // FRAME
89
+ rms = np.sqrt(np.mean((pcm[: n * FRAME].reshape(n, FRAME).astype(np.float32) / 32768) ** 2, axis=1))
90
+ voiced = 20 * np.log10(rms + 1e-9) > db
91
+ last = int(np.nonzero(voiced)[0][-1])
92
+ i = 0
93
+ while i < last:
94
+ if not voiced[i]:
95
+ j = i
96
+ while j < last and not voiced[j]:
97
+ j += 1
98
+ if (j - i) * 0.08 >= min_gap_s and voiced[:i].sum() >= 3:
99
+ cases.append({"kind": "question_inner", "id": q["id"], "cut": i * FRAME})
100
+ i = j
101
+ else:
102
+ i += 1
103
+ cases.append({"kind": "question_end", "id": q["id"], "cut": (last + 1) * FRAME})
104
+ return cases
105
+
106
+
107
+ def audio_of(case, data, bba_dir):
108
+ if case["kind"].startswith("question"):
109
+ pcm = load_16k(Path(bba_dir) / f"q_{case['id']}.wav")[: case["cut"]]
110
+ return np.concatenate([pcm, np.zeros(TAIL, np.int16)]) # clean recordings: silence after the cut
111
+ a = max(0, case["start"] - LEAD)
112
+ x, _ = read_wav(Path(data) / "audio" / f"{case['id']}.wav", a, case["cut"] + TAIL - a)
113
+ return (x[:, CALLER] * 32767).astype(np.int16) # the real channel, noise included
114
+
115
+
116
+ async def run(http, args, cases, sem, variant):
117
+ prompt, think = variant.split("+")
118
+
119
+ async def one(c):
120
+ pcm = audio_of(c, args.data, args.bba)
121
+ async with sem:
122
+ t0 = time.perf_counter()
123
+ try:
124
+ said = await judge_finished(http, args.api_url, args.model, pcm, prompt=prompt, think_tokens=int(think))
125
+ except Exception as e:
126
+ said, c["error"] = None, repr(e)
127
+ c.setdefault("said", {})[variant] = said
128
+ c.setdefault("ms", {})[variant] = (time.perf_counter() - t0) * 1000
129
+ c["audio_s"] = len(pcm) / SR
130
+ await asyncio.gather(*[one(c) for c in cases])
131
+
132
+
133
+ def rate(cases, variant, want, keep=lambda c: True):
134
+ rows = [c for c in cases if keep(c) and c["said"][variant] is not None]
135
+ hits = sum(c["said"][variant] == want for c in rows)
136
+ return {"correct": hits, "total": len(rows), "rate": hits / len(rows) if rows else None}
137
+
138
+
139
+ async def main():
140
+ ap = argparse.ArgumentParser()
141
+ ap.add_argument("--api-url", default="http://127.0.0.1:9991/v1/chat/completions")
142
+ ap.add_argument("--model", default="Step-Audio-R1.1")
143
+ ap.add_argument("--data", required=True)
144
+ ap.add_argument("--dialogues", required=True)
145
+ ap.add_argument("--bba", default="eval/data/bba")
146
+ ap.add_argument("--out", default="eval/results/judge")
147
+ ap.add_argument("--variants", default="v1+0,v2+0,v2+32", help="prompt+reasoning tokens, comma separated")
148
+ ap.add_argument("--train-cases", type=int, default=500)
149
+ ap.add_argument("--concurrency", type=int, default=12)
150
+ args = ap.parse_args()
151
+
152
+ dialogues = {d["id"]: d for d in read_jsonl(args.dialogues)}
153
+ train = dialogue_cases(args.data, "train", args.train_cases, 0, dialogues)
154
+ test = dialogue_cases(args.data, "test", None, 0, dialogues)
155
+ quest = question_cases(args.bba)
156
+ sem, variants = asyncio.Semaphore(args.concurrency), args.variants.split(",")
157
+ async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=300)) as http:
158
+ for v in variants:
159
+ for cases in (train, test, quest):
160
+ await run(http, args, cases, sem, v)
161
+
162
+ is_kind = lambda k: (lambda c: c["kind"] == k)
163
+ result = {"cases": {"train": len(train), "held_out": len(test), "question_cuts": len(quest)},
164
+ "held_out_pauses": {"all": sum(c["kind"] == "pause" for c in test), "cut_off": sum(c.get("cut_off") is True for c in test)},
165
+ "concurrency": args.concurrency, "variants": {}}
166
+ for v in variants:
167
+ tr_end, tr_pause = rate(train, v, True, is_kind("finished")), rate(train, v, False, is_kind("pause"))
168
+ result["variants"][v] = {
169
+ "train_balanced_accuracy": (tr_end["rate"] + tr_pause["rate"]) / 2,
170
+ "held_out": {
171
+ "turn_end_released": rate(test, v, True, is_kind("finished")),
172
+ "pause_held_all": rate(test, v, False, is_kind("pause")),
173
+ "pause_held_cut_off": rate(test, v, False, lambda c: c.get("cut_off") is True),
174
+ "pause_held_other": rate(test, v, False, lambda c: c.get("cut_off") is False),
175
+ },
176
+ "benchmark_questions": {
177
+ "inner_silence_held": rate(quest, v, False, is_kind("question_inner")),
178
+ "end_released": rate(quest, v, True, is_kind("question_end")),
179
+ "questions_never_released_early": sum(all(c["said"][v] is not True for c in quest if c["id"] == q and c["kind"] == "question_inner")
180
+ for q in {c["id"] for c in quest}),
181
+ },
182
+ "no_answer_word": sum(c["said"][v] is None for c in train + test + quest),
183
+ "judge_ms_held_out": percentiles([c["ms"][v] for c in test]),
184
+ }
185
+ result["chosen_on_train"] = max(variants, key=lambda v: result["variants"][v]["train_balanced_accuracy"])
186
+ out = Path(args.out)
187
+ write_json(out / "cases.json", {"train": train, "test": test, "questions": quest})
188
+ write_json(out / "judge.json", result)
189
+ print(json.dumps(result, indent=1))
190
+
191
+
192
+ if __name__ == "__main__":
193
+ asyncio.run(main())
eval/eval_latency.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Turn-taking latency: time from the caller finishing to the first reply audio.
2
+
3
+ Held-out caller turns (test voices, test scenarios, with their noise) are cut out of
4
+ the test dialogues and spoken to the endpoint one per fresh session, once with the
5
+ controller deciding and once with the fixed-silence baseline ("vad"). Reported per mode:
6
+ the latency of the reply that finally answers the turn, in how many turns the caller
7
+ heard the model before they had finished (the audible false starts), how many replies
8
+ were withdrawn before a single frame played (inaudible), and how often no reply came.
9
+
10
+ Only turns that end a caller's say are used (the turn's whole audio, pauses included),
11
+ so a mid-sentence pause that triggers a reply counts as "started early".
12
+
13
+ python -m eval.eval_latency --data data/out/dataset --out eval/results/latency --modes controller,vad
14
+ """
15
+ import argparse
16
+ import asyncio
17
+ import json
18
+ import random
19
+ from pathlib import Path
20
+
21
+ import aiohttp
22
+ import numpy as np
23
+
24
+ from duplex.spec import CALLER, SR, read_wav, write_json
25
+ from eval.ws_client import open_session, percentiles, run_turn
26
+
27
+
28
+ def held_out_turns(data, n, seed):
29
+ data = Path(data)
30
+ turns = []
31
+ for it in json.loads((data / "index_test.json").read_text()):
32
+ meta = json.loads((data / "meta" / f"{it['id']}.json").read_text())
33
+ cuts = [e["onset"] for e in meta["events"] if e["type"] == "interrupt"]
34
+ for e in meta["events"]:
35
+ # skip turns that begin as an interruption: their first words overlap the agent
36
+ if e["type"] == "caller_turn" and e["start"] not in cuts and 1.0 * SR <= e["end"] - e["start"] <= 25 * SR:
37
+ turns.append((it["id"], e["start"], e["end"]))
38
+ random.Random(seed).shuffle(turns)
39
+ return turns[:n]
40
+
41
+
42
+ async def one(http, args, data, turn, mode, sem):
43
+ did, start, end = turn
44
+ lead = int(0.3 * SR)
45
+ x, _ = read_wav(Path(data) / "audio" / f"{did}.wav", max(0, start - lead), end - max(0, start - lead))
46
+ pcm = (x[:, CALLER] * 32767).astype(np.int16)
47
+ async with sem:
48
+ ws = await open_session(http, args.url, args.system, mode)
49
+ try:
50
+ r = await run_turn(ws, pcm, until="done_after_audio", max_wait_s=args.max_wait_s)
51
+ finally:
52
+ await ws.close()
53
+ lag = [e.get("lag_ms") for e in r["events"] if e["type"] == "reply.start"]
54
+ return {"dialogue": did, "start": start, "end": end, "turn_s": len(pcm) / SR, "latency_ms": r["latency_ms"], "server_lag_ms": lag[0] if lag else None,
55
+ "started_early": r["started_early"], "replied": r["t_first_audio"] is not None, "error": r["error"],
56
+ "heard_early_ms": r["audio_ms_before_caller_end"], "replies_cut_off": sum(1 for d in r["replies"] if d["reason"] != "done"),
57
+ "withdrawn_unheard": sum(1 for e in r["events"] if e["type"] == "reply.withdrawn")}
58
+
59
+
60
+ async def main():
61
+ ap = argparse.ArgumentParser()
62
+ ap.add_argument("--url", default="http://localhost:8765/ws")
63
+ ap.add_argument("--data", required=True)
64
+ ap.add_argument("--out", default="eval/results/latency")
65
+ ap.add_argument("--modes", default="controller,vad")
66
+ ap.add_argument("--turns", type=int, default=100)
67
+ ap.add_argument("--concurrency", type=int, default=4)
68
+ ap.add_argument("--max-wait-s", type=float, default=30.0)
69
+ ap.add_argument("--system", default="You are a helpful assistant on a phone call. Keep answers short.")
70
+ ap.add_argument("--seed", type=int, default=0)
71
+ args = ap.parse_args()
72
+
73
+ turns = held_out_turns(args.data, args.turns, args.seed)
74
+ summary = {"turns": len(turns)}
75
+ async with aiohttp.ClientSession() as http:
76
+ for mode in args.modes.split(","):
77
+ sem = asyncio.Semaphore(args.concurrency)
78
+ rows = await asyncio.gather(*[one(http, args, args.data, t, mode, sem) for t in turns])
79
+ write_json(Path(args.out) / f"{mode}.json", rows)
80
+ clean = [r for r in rows if r["replied"] and r["heard_early_ms"] == 0 and r["latency_ms"] is not None and r["latency_ms"] >= 0]
81
+ summary[mode] = {
82
+ # the caller never heard the model before finishing, and the reply came after: the clean turns
83
+ "latency_ms_clean_turns": percentiles([r["latency_ms"] for r in clean]),
84
+ "turns_where_caller_heard_the_model_early": sum(r["heard_early_ms"] > 0 for r in rows),
85
+ "replies_cut_off_after_being_heard": sum(r["replies_cut_off"] for r in rows),
86
+ "replies_withdrawn_unheard": sum(r["withdrawn_unheard"] for r in rows),
87
+ "no_reply": sum(not r["replied"] for r in rows),
88
+ "errors": sum(bool(r["error"]) for r in rows),
89
+ "server_lag_ms": percentiles([r["server_lag_ms"] for r in rows]), # how far behind real time the server was when it decided
90
+ }
91
+ print(mode, json.dumps(summary[mode]))
92
+ write_json(Path(args.out) / f"summary_{args.modes.replace(',', '_')}.json", summary)
93
+
94
+
95
+ if __name__ == "__main__":
96
+ asyncio.run(main())
eval/eval_wer.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Nobody has listened to the audio, so a speech recogniser does: Whisper large-v3 (Apache-2.0)
2
+ transcribes it and the transcript is compared with the words the audio was meant to say.
3
+
4
+ --pairs DIR ... folders of <name>.wav + <name>.txt (reply audio and the reply's own text,
5
+ saved by serving/loadtest.py --save-audio)
6
+ --tts-sample N N random clips of the training speech (data/out/tts) against the dialogue text
7
+
8
+ Reported per group: word error rate (all errors / all reference words), and how often the
9
+ first three words came out right (the first words are what a smaller first audio chunk
10
+ could damage). Whisper makes errors of its own, so these are upper bounds on the audio's.
11
+
12
+ CUDA_VISIBLE_DEVICES=7 python -m eval.eval_wer --pairs eval/results/loadtest_fc25/audio --tts-sample 300 --out eval/results/wer
13
+ """
14
+ import argparse
15
+ import json
16
+ import random
17
+ import re
18
+ from pathlib import Path
19
+
20
+ import numpy as np
21
+ import torch
22
+ from scipy.signal import resample_poly
23
+
24
+ from duplex.spec import SR, read_jsonl, read_wav, write_json
25
+
26
+ UNITS = "zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen".split()
27
+ TENS = "twenty thirty forty fifty sixty seventy eighty ninety".split()
28
+
29
+
30
+ def spell(m):
31
+ n = int(m.group(0))
32
+ if n < 20:
33
+ return UNITS[n]
34
+ if n < 100:
35
+ return TENS[n // 10 - 2] + ("" if n % 10 == 0 else " " + UNITS[n % 10])
36
+ return m.group(0)
37
+
38
+
39
+ def words(text):
40
+ text = re.sub(r"<[^>]+>", " ", text.split("</think>")[-1]).lower().replace("-", " ")
41
+ text = re.sub(r"\d+", spell, text)
42
+ return re.sub(r"[^a-z0-9' ]+", " ", text).replace("'", "").split()
43
+
44
+
45
+ def errors(ref, hyp):
46
+ """Word-level edit distance."""
47
+ d = list(range(len(hyp) + 1))
48
+ for i, r in enumerate(ref, 1):
49
+ prev, d[0] = d[0], i
50
+ for j, h in enumerate(hyp, 1):
51
+ prev, d[j] = d[j], min(d[j] + 1, d[j - 1] + 1, prev + (r != h))
52
+ return d[-1]
53
+
54
+
55
+ def score(rows):
56
+ rows = [r for r in rows if r["ref"]]
57
+ if not rows:
58
+ return {"clips": 0}
59
+ return {
60
+ "clips": len(rows), "reference_words": sum(len(r["ref"]) for r in rows),
61
+ "word_error_rate": sum(r["errors"] for r in rows) / sum(len(r["ref"]) for r in rows),
62
+ "clips_with_no_error": sum(r["errors"] == 0 for r in rows),
63
+ "first_three_words_right": sum(r["ref"][:3] == r["hyp"][:3] for r in rows) / len(rows),
64
+ }
65
+
66
+
67
+ def main():
68
+ ap = argparse.ArgumentParser()
69
+ ap.add_argument("--pairs", nargs="*", default=[])
70
+ ap.add_argument("--tts-sample", type=int, default=0)
71
+ ap.add_argument("--tts", default="data/out/tts")
72
+ ap.add_argument("--dialogues", default="data/out/dialogues.jsonl")
73
+ ap.add_argument("--out", default="eval/results/wer")
74
+ ap.add_argument("--seed", type=int, default=0)
75
+ args = ap.parse_args()
76
+
77
+ from transformers import pipeline
78
+ asr = pipeline("automatic-speech-recognition", model="openai/whisper-large-v3", torch_dtype=torch.float16, device=0, chunk_length_s=30)
79
+
80
+ def transcribe(x, sr):
81
+ if sr != SR:
82
+ x = resample_poly(x, SR, sr)
83
+ return asr({"raw": np.asarray(x, dtype=np.float32), "sampling_rate": SR}, generate_kwargs={"language": "english", "task": "transcribe"})["text"]
84
+
85
+ groups = {}
86
+ for d in args.pairs:
87
+ rows = []
88
+ for wav in sorted(Path(d).glob("*.wav")):
89
+ x, sr = read_wav(wav)
90
+ ref, hyp = words(wav.with_suffix(".txt").read_text(encoding="utf-8")), None
91
+ hyp = words(transcribe(x[:, 0], sr))
92
+ rows.append({"clip": wav.name, "ref": ref, "hyp": hyp, "errors": errors(ref, hyp)})
93
+ groups[str(d)] = rows
94
+
95
+ if args.tts_sample:
96
+ rng = random.Random(args.seed)
97
+ dialogues = read_jsonl(args.dialogues)
98
+ rows = []
99
+ for d in rng.sample(dialogues, min(args.tts_sample, len(dialogues))):
100
+ clips = np.load(Path(args.tts) / f"{d['id']}.npz")
101
+ ti = rng.randrange(len(d["turns"]))
102
+ parts = [p.strip() for p in d["turns"][ti]["text"].split("[pause]") if p.strip()]
103
+ si = rng.randrange(len(parts))
104
+ ref = words(parts[si])
105
+ hyp = words(transcribe(clips[f"t{ti}_s{si}"].astype(np.float32) / 32768, SR))
106
+ rows.append({"clip": f"{d['id']} t{ti}_s{si}", "voice": d["caller_voice"] if d["turns"][ti]["spk"] == "caller" else d["agent_voice"],
107
+ "ref": ref, "hyp": hyp, "errors": errors(ref, hyp)})
108
+ groups["training_speech"] = rows
109
+
110
+ summary = {name: score(rows) for name, rows in groups.items()}
111
+ out = Path(args.out)
112
+ write_json(out / "clips.json", groups)
113
+ write_json(out / "wer.json", summary)
114
+ print(json.dumps(summary, indent=1))
115
+
116
+
117
+ if __name__ == "__main__":
118
+ main()
eval/prep_bba.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fetch a fixed 100-question subset of Big Bench Audio (ArtificialAnalysis/big_bench_audio,
2
+ MIT): 25 questions per category, chosen with a fixed seed, decoded to 16 kHz wav.
3
+
4
+ The dataset ships mp3. It is decoded with the soundfile package (libsndfile), or with the
5
+ ffmpeg program when soundfile is not installed.
6
+
7
+ python -m eval.prep_bba --out eval/data/bba
8
+ """
9
+ import argparse
10
+ import json
11
+ import random
12
+ import subprocess
13
+ from collections import defaultdict
14
+ from pathlib import Path
15
+
16
+ from huggingface_hub import hf_hub_download
17
+
18
+ from duplex.spec import SR, write_json, write_wav
19
+
20
+ REPO = "ArtificialAnalysis/big_bench_audio"
21
+
22
+
23
+ def decode(mp3, wav):
24
+ """mp3 -> 16 kHz mono wav. Uses the soundfile package (its bundled libsndfile reads mp3) when
25
+ present, so nothing has to be installed on the host; otherwise the ffmpeg program."""
26
+ try:
27
+ import soundfile as sf
28
+ except ImportError:
29
+ subprocess.run(["ffmpeg", "-loglevel", "error", "-y", "-i", mp3, "-ac", "1", "-ar", "16000", "-c:a", "pcm_s16le", str(wav)], check=True)
30
+ return
31
+ from scipy.signal import resample_poly
32
+ x, sr = sf.read(mp3, dtype="float32", always_2d=True)
33
+ x = x.mean(axis=1)
34
+ write_wav(wav, x if sr == SR else resample_poly(x, SR, sr), SR)
35
+
36
+
37
+ def main():
38
+ ap = argparse.ArgumentParser()
39
+ ap.add_argument("--out", default="eval/data/bba")
40
+ ap.add_argument("--per-category", type=int, default=25)
41
+ ap.add_argument("--seed", type=int, default=0)
42
+ args = ap.parse_args()
43
+
44
+ out = Path(args.out)
45
+ out.mkdir(parents=True, exist_ok=True)
46
+ meta = [json.loads(line) for line in open(hf_hub_download(REPO, "metadata.jsonl", repo_type="dataset"), encoding="utf-8")]
47
+ by_cat = defaultdict(list)
48
+ for row in meta:
49
+ by_cat[row["category"]].append(row)
50
+ rng = random.Random(args.seed)
51
+ subset = [q for cat in sorted(by_cat) for q in rng.sample(sorted(by_cat[cat], key=lambda r: r["id"]), args.per_category)]
52
+
53
+ for q in subset:
54
+ wav = out / f"q_{q['id']}.wav"
55
+ if not wav.exists():
56
+ mp3 = hf_hub_download(REPO, q["file_name"].replace("\\", "/"), repo_type="dataset")
57
+ decode(mp3, wav)
58
+ write_json(out / "subset.json", [{"id": q["id"], "category": q["category"], "official_answer": q["official_answer"]} for q in subset])
59
+ print(f"{len(subset)} questions in {out}: " + ", ".join(f"{c}={args.per_category}" for c in sorted(by_cat)))
60
+
61
+
62
+ if __name__ == "__main__":
63
+ main()
eval/ws_client.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A caller for the duplex endpoint, shared by the load test and the evaluations.
2
+
3
+ Audio is sent the way a live microphone would send it: the frame holding samples
4
+ [i*80 ms, (i+1)*80 ms) leaves at (i+1)*80 ms. "The caller finished" is therefore
5
+ t_start + len(audio)/16000, and every latency below is measured from that instant
6
+ on the client's own clock.
7
+ """
8
+ import asyncio
9
+ import json
10
+ import time
11
+
12
+ import aiohttp
13
+ import numpy as np
14
+
15
+ from duplex.spec import FRAME, SR, read_wav
16
+
17
+ FRAME_S = FRAME / SR
18
+
19
+
20
+ def load_16k(path):
21
+ x, sr = read_wav(path)
22
+ x = x.mean(axis=1)
23
+ if sr != SR:
24
+ from scipy.signal import resample_poly
25
+ x = resample_poly(x, SR, sr)
26
+ return (np.clip(x, -1, 1) * 32767).astype(np.int16)
27
+
28
+
29
+ async def open_session(http, url, system_prompt, endpointing):
30
+ ws = await http.ws_connect(url, max_msg_size=1 << 20)
31
+ await ws.send_str(json.dumps({"type": "session.start", "system_prompt": system_prompt, "endpointing": endpointing}))
32
+ msg = json.loads((await ws.receive()).data)
33
+ if msg.get("type") != "session.started":
34
+ raise RuntimeError(f"session did not start: {msg}")
35
+ return ws
36
+
37
+
38
+ async def run_turn(ws, pcm, commit=False, until="first_done", max_wait_s=60.0):
39
+ """Speak `pcm` (int16, 16 kHz) to the server in real time, then stay silent until the reply is over.
40
+
41
+ commit=True sends input.commit right after the last frame (manual endpointing).
42
+ until="first_done": return at the first reply.done.
43
+ until="done_after_audio": return at the first reply that ran to its end after the caller
44
+ finished (earlier replies that were cut off are kept in res["replies"]).
45
+ """
46
+ n = -(-len(pcm) // FRAME)
47
+ frames = np.concatenate([pcm, np.zeros(n * FRAME - len(pcm), np.int16)]).astype("<i2").reshape(n, FRAME)
48
+ silence = np.zeros(FRAME, "<i2").tobytes()
49
+ res = {"audio": bytearray(), "text": "", "events": [], "replies": [], "t_first_audio": None, "t_reply_start": None,
50
+ "max_gap_ms": 0.0, "error": None, "audio_ms_before_caller_end": 0}
51
+ t_start = time.perf_counter()
52
+ t_end = t_start + len(pcm) / SR
53
+ res["t_caller_end"] = t_end
54
+ finished = asyncio.Event()
55
+
56
+ async def receive():
57
+ last = None
58
+ async for msg in ws:
59
+ now = time.perf_counter()
60
+ if msg.type == aiohttp.WSMsgType.BINARY:
61
+ if last is not None:
62
+ res["max_gap_ms"] = max(res["max_gap_ms"], (now - last) * 1000)
63
+ last = now
64
+ res["t_first_audio"] = res["t_first_audio"] or now
65
+ if now < t_end:
66
+ res["audio_ms_before_caller_end"] += 80 # the caller hears the model while still speaking
67
+ res["audio"] += msg.data
68
+ elif msg.type == aiohttp.WSMsgType.TEXT:
69
+ ev = json.loads(msg.data)
70
+ ev["t_client"] = now - t_start
71
+ res["events"].append(ev)
72
+ if ev["type"] == "reply.start": # a new reply: timings, text and audio are per reply
73
+ res["t_reply_start"] = res["t_reply_start"] or now
74
+ res["text"], res["audio"], res["t_first_audio"], last = "", bytearray(), None, None
75
+ elif ev["type"] == "transcript.delta":
76
+ res["text"] += ev["text"]
77
+ elif ev["type"] == "error":
78
+ res["error"] = ev.get("message")
79
+ elif ev["type"] == "reply.done":
80
+ res["replies"].append(ev)
81
+ if until == "first_done" or (ev["reason"] == "done" and now >= t_end):
82
+ break
83
+ else:
84
+ res["error"] = res["error"] or f"socket closed: {msg.type}"
85
+ break
86
+ finished.set()
87
+
88
+ task = asyncio.create_task(receive())
89
+ i = 0
90
+ while not finished.is_set():
91
+ due = t_start + (i + 1) * FRAME_S
92
+ if due > t_end + max_wait_s:
93
+ res["error"] = res["error"] or "timeout: no finished reply"
94
+ break
95
+ await asyncio.sleep(max(0.0, due - time.perf_counter()))
96
+ try:
97
+ await ws.send_bytes(frames[i].tobytes() if i < n else silence)
98
+ if i == n - 1 and commit:
99
+ res["t_commit"] = time.perf_counter()
100
+ await ws.send_str(json.dumps({"type": "input.commit"}))
101
+ except (ConnectionError, RuntimeError) as e:
102
+ res["error"] = res["error"] or f"send failed: {e!r}"
103
+ break
104
+ i += 1
105
+ task.cancel()
106
+
107
+ done = res["replies"][-1] if res["replies"] else None
108
+ res["done"] = done
109
+ # caller finished -> first audio of the last reply (negative when that reply began before the caller finished)
110
+ res["latency_ms"] = (res["t_first_audio"] - t_end) * 1000 if res["t_first_audio"] else None
111
+ res["started_early"] = bool(res["t_reply_start"] and res["t_reply_start"] < t_end) # any reply began while the caller spoke
112
+ res["audio"] = bytes(res["audio"])
113
+ return res
114
+
115
+
116
+ def percentiles(values):
117
+ v = [x for x in values if x is not None]
118
+ if not v:
119
+ return {"n": 0}
120
+ return {"n": len(v), "min": float(np.min(v)), "p50": float(np.percentile(v, 50)), "p90": float(np.percentile(v, 90)),
121
+ "p95": float(np.percentile(v, 95)), "max": float(np.max(v))}
requirements.txt ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # our code
2
+ torch
3
+ torchaudio
4
+ numpy
5
+ scipy
6
+ aiohttp
7
+ librosa
8
+ safetensors
9
+ huggingface_hub
10
+ # data generation (read docs/licenses.md item 1 before installing kokoro's English front end)
11
+ kokoro
12
+ # needed by the released token2wav decoder (stepfun-ai/Step-Audio2); see that repository's README for the rest
13
+ s3tokenizer
14
+ onnxruntime
15
+ hyperpyyaml
samples/README.md ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Samples
2
+
3
+ Replies of the configuration in the README to four Big Bench Audio questions, as the test caller recorded them
4
+ (24 kHz). Each is the lead-in, then the answer. The questions are not included.
5
+
6
+ | File | Category | What it says | Right answer |
7
+ |---|---|---|---|
8
+ | `formal_fallacies.wav` | formal fallacies | Let me just check the validity of the argument based on the given premises. valid | valid |
9
+ | `navigate.wav` | navigate | Let me figure out if following those instructions gets you back to the starting point. no | no |
10
+ | `object_counting.wav` | object counting | Let me count all the fruits you mentioned to give you the total number. Fourteen | 14 |
11
+ | `web_of_lies.wav` | web of lies | Let me think for a moment about who is telling the truth. Yes | yes |
samples/formal_fallacies.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a63d06068516e730b8866e58359218115c71584e4559dfe603f4eb257595a45a
3
+ size 311084
samples/navigate.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:95eba09ae02c1cb876aec61b1bc648be393c24e286168738da29a08e49ac122a
3
+ size 261164
samples/object_counting.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:50e5f1d790385378219f3edfbbbe77e5d87b9c6b65fde7a9c927112e549e814c
3
+ size 261164
samples/web_of_lies.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9edcc62b4323977809e5ed6caa3756c6bf09fd9c25425af8e368ab448ee7ba01
3
+ size 238124
serving/__init__.py ADDED
File without changes
serving/baseline_client.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Async client for the baseline's released vLLM endpoint.
2
+
3
+ The request and response handling mirror the released clients
4
+ (stepaudior1vllm.py in stepfun-ai/Step-Audio-R1, stepaudio2vllm.py in stepfun-ai/Step-Audio2):
5
+ role "human", audio as `input_audio` wav parts of at most 25 s, skip_special_tokens false,
6
+ the assistant prefix sent as an unfinished last message, text read from
7
+ tts_content.tts_text or content, audio tokens read from tts_content.tts_audio.
8
+ Nothing here is guessed; where the released code is silent (how R1.1 is asked to
9
+ speak), serving/probe_baseline.py tries the released prefixes and records what comes back.
10
+ """
11
+ import base64
12
+ import io
13
+ import json
14
+ import re
15
+ import wave
16
+
17
+ import numpy as np
18
+
19
+ from duplex.spec import SR
20
+
21
+ AUDIO_TOKEN = re.compile(r"<audio_(\d+)>")
22
+ SPEECH_MARKUP = re.compile(r"<audio_\d+>|<tts_(?:start|end|pad)>")
23
+ MAX_CLIP_S = 25.0 # the released client splits longer audio into 25 s parts
24
+
25
+
26
+ def wav_bytes(pcm16, sr=SR):
27
+ buf = io.BytesIO()
28
+ with wave.open(buf, "wb") as w:
29
+ w.setnchannels(1)
30
+ w.setsampwidth(2)
31
+ w.setframerate(sr)
32
+ w.writeframes(np.asarray(pcm16, dtype="<i2").tobytes())
33
+ return buf.getvalue()
34
+
35
+
36
+ def human_turn(pcm16):
37
+ """One caller turn (int16, 16 kHz mono) as a released-format message."""
38
+ step = int(MAX_CLIP_S * SR)
39
+ parts = [pcm16[i: i + step] for i in range(0, len(pcm16), step)]
40
+ return {"role": "human", "content": [
41
+ {"type": "input_audio", "input_audio": {"data": base64.b64encode(wav_bytes(p)).decode(), "format": "wav"}} for p in parts
42
+ ]}
43
+
44
+
45
+ async def stream_chat(http, api_url, model, messages, info=None, **params):
46
+ """Yields (delta, text, audio_tokens) per streamed chunk, as the released client does.
47
+ info: a dict that receives "finish_reason" ("stop": the model or a stop string ended it; "length": the token limit)."""
48
+ payload = dict(params, model=model, stream=True, skip_special_tokens=False)
49
+ last = messages[-1]
50
+ if last.get("role") == "assistant" and last.get("content") is None:
51
+ messages = messages[:-1]
52
+ payload.update(continue_final_message=False, add_generation_prompt=True)
53
+ elif last.get("eot", True):
54
+ payload.update(continue_final_message=False, add_generation_prompt=True)
55
+ else:
56
+ payload.update(continue_final_message=True, add_generation_prompt=False)
57
+ payload["messages"] = messages
58
+
59
+ async with http.post(api_url, json=payload) as r:
60
+ if r.status != 200:
61
+ raise RuntimeError(f"vLLM answered {r.status}: {(await r.text())[:500]}")
62
+ async for raw in r.content:
63
+ line = raw.decode("utf-8").strip()
64
+ if not line.startswith("data: "):
65
+ continue
66
+ line = line[6:]
67
+ if line == "[DONE]":
68
+ break
69
+ try:
70
+ choice = json.loads(line)["choices"][0]
71
+ if info is not None and choice.get("finish_reason"):
72
+ info["finish_reason"] = choice["finish_reason"]
73
+ delta = choice["delta"]
74
+ except (ValueError, KeyError, IndexError):
75
+ continue
76
+ tts = delta.get("tts_content") or {}
77
+ content = delta.get("content") or ""
78
+ text = tts.get("tts_text")
79
+ text = text if text is not None else content
80
+ # Measured on 2026-11-30 with the released image and R1.1: tts_content stays empty and the
81
+ # audio tokens arrive inside `content`, interleaved with the words (one word piece, four
82
+ # audio tokens, with <tts_pad> and <tts_end> markers). So audio is read from both places.
83
+ audio = [int(i) for i in AUDIO_TOKEN.findall(tts.get("tts_audio") or content)]
84
+ yield delta, SPEECH_MARKUP.sub("", text), audio
serving/chat_template.jinja ADDED
@@ -0,0 +1 @@
 
 
1
+ {%- macro render_content(content) -%}{%- if content is string -%}{{- content.replace("<audio_patch>\n", "<audio_patch>") -}}{%- elif content is mapping -%}{{- content['value'] if 'value' in content else content['text'] -}}{%- elif content is iterable -%}{%- for item in content -%}{%- if item.type == 'text' -%}{{- item['value'] if 'value' in item else item['text'] -}}{%- elif item.type == 'audio' -%}<audio_patch>{%- endif -%}{%- endfor -%}{%- endif -%}{%- endmacro -%}{%- if tools -%}{{- '<|BOT|>system\n' -}}{%- if messages[0]['role'] == 'system' -%}{{- render_content(messages[0]['content']) + '<|EOT|>' -}}{%- endif -%}{{- '<|BOT|>tool_json_schemas\n' + tools|tojson + '<|EOT|>' -}}{%- else -%}{%- if messages[0]['role'] == 'system' -%}{{- '<|BOT|>system\n' + render_content(messages[0]['content']) + '<|EOT|>' -}}{%- endif -%}{%- endif -%}{%- for message in messages -%}{%- if message["role"] == "user" -%}{{- '<|BOT|>human\n' + render_content(message["content"]) + '<|EOT|>' -}}{%- elif message["role"] == "assistant" -%}{{- '<|BOT|>assistant\n' + (render_content(message["content"]) if message["content"] else '') -}}{%- set is_last_assistant = true -%}{%- for m in messages[loop.index:] -%}{%- if m["role"] == "assistant" -%}{%- set is_last_assistant = false -%}{%- endif -%}{%- endfor -%}{%- if not is_last_assistant -%}{{- '<|EOT|>' -}}{%- endif -%}{%- elif message["role"] == "function_output" -%}{%- else -%}{%- if not (loop.first and message["role"] == "system") -%}{{- '<|BOT|>' + message["role"] + '\n' + render_content(message["content"]) + '<|EOT|>' -}}{%- endif -%}{%- endif -%}{%- endfor -%}{%- if add_generation_prompt -%}{{- '<|BOT|>assistant\n<think>\n' -}}{%- endif -%}
serving/judge.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Has the caller finished? Asked of the baseline itself.
2
+
3
+ The small controller could not tell a thinking pause from a finished turn: that needs the
4
+ meaning of the words, and the 33B model has it. So at a silence the audio heard so far is
5
+ sent to the baseline with one question, the reply is opened past its reasoning block, and
6
+ only the first token is read: "yes" or "no". One prefill and one token, so the answer
7
+ comes back in about 0.15 s. No training is involved.
8
+
9
+ The answer is the model's single most likely word. Its probability would be better (a
10
+ threshold could be tuned), but asking this vLLM image for logprobs kills its engine on a
11
+ this GPU (see serving/launch_vllm.sh).
12
+ """
13
+ from serving.baseline_client import human_turn
14
+
15
+ NL = chr(10)
16
+ PROMPTS = {
17
+ # v1: the first wording tried (measured: 49% of pauses held, 82% of turn ends released)
18
+ "v1": ("You are listening to one side of a phone call. The caller has just gone quiet. Decide whether the caller has "
19
+ "finished what they wanted to say and is now waiting for a reply, or has only paused and will go on speaking. "
20
+ "Answer with one word: yes if the caller has finished, no if the caller will go on."),
21
+ # v2: says what "finished" means, so that a complete sentence that asks for nothing is not an invitation to reply
22
+ "v2": ("You are the listener on a phone call. The caller has just gone quiet for a moment. Should you start replying now? "
23
+ "Answer no if the caller's last words stop in the middle of a sentence (for example they end on a word like "
24
+ "and, but, to, the, my, on, or a half-said phrase), or if the caller is still setting out information and has "
25
+ "not yet asked their question or made their request. Answer yes only if the caller has finished a question, "
26
+ "a request, or a remark that calls for your reply. Answer with one word: yes or no."),
27
+ }
28
+ EMPTY_THOUGHT = "<think>" + NL + NL + "</think>" + NL # an empty reasoning block: the next token is the answer
29
+
30
+
31
+ async def _post(http, api_url, payload):
32
+ async with http.post(api_url, json=payload) as r:
33
+ if r.status != 200:
34
+ raise RuntimeError(f"vLLM answered {r.status}: {(await r.text())[:300]}")
35
+ return (await r.json())["choices"][0]["message"].get("content") or ""
36
+
37
+
38
+ async def judge_finished(http, api_url, model, pcm16, prompt="v2", think_tokens=0):
39
+ """pcm16: the caller's audio so far (int16, 16 kHz). Returns True (finished), False (will go on) or None.
40
+
41
+ With think_tokens > 0 the model may reason for up to that many tokens before it answers,
42
+ which costs think_tokens / (tokens per second) of extra time."""
43
+ base = {"model": model, "stream": False, "skip_special_tokens": False, "temperature": 0.0,
44
+ "continue_final_message": True, "add_generation_prompt": False}
45
+ head = [{"role": "system", "content": PROMPTS[prompt]}, human_turn(pcm16)]
46
+ prefix = EMPTY_THOUGHT
47
+ if think_tokens:
48
+ thought = await _post(http, api_url, dict(base, max_tokens=think_tokens, stop=["</think>"],
49
+ messages=head + [{"role": "assistant", "content": "<think>" + NL}]))
50
+ prefix = "<think>" + NL + thought.rstrip() + NL + "</think>" + NL
51
+ word = (await _post(http, api_url, dict(base, max_tokens=1, messages=head + [{"role": "assistant", "content": prefix}]))).strip().lower()
52
+ return True if word.startswith("yes") else False if word.startswith("no") else None