diff --git a/.gitattributes b/.gitattributes
index a6344aac8c09253b3b630fb776ae94478aa0275b..0bdcbb0454c919d246be204a9ceaa62cd5c26f16 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -33,3 +33,9 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
*.zip filter=lfs diff=lfs merge=lfs -text
*.zst filter=lfs diff=lfs merge=lfs -text
*tfevents* filter=lfs diff=lfs merge=lfs -text
+assets/prompt_af_heart.wav filter=lfs diff=lfs merge=lfs -text
+assets/prompt_af_heart_short.wav filter=lfs diff=lfs merge=lfs -text
+samples/formal_fallacies.wav filter=lfs diff=lfs merge=lfs -text
+samples/navigate.wav filter=lfs diff=lfs merge=lfs -text
+samples/object_counting.wav filter=lfs diff=lfs merge=lfs -text
+samples/web_of_lies.wav filter=lfs diff=lfs merge=lfs -text
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/NOTICE b/NOTICE
new file mode 100644
index 0000000000000000000000000000000000000000..d489ce2b3090811bc3cd4f93afb6777aa7ae7803
--- /dev/null
+++ b/NOTICE
@@ -0,0 +1,34 @@
+RightNow Duplex v0
+Copyright 2026 RightNow AI
+
+Licensed under the Apache License, Version 2.0 (see LICENSE).
+
+This work builds on the following. None of it is included in this repository
+except the files named below.
+
+Step-Audio R1.1 (stepfun-ai/Step-Audio-R1.1), by StepFun. Apache-2.0.
+ The speech model this layer serves. Used unchanged. Not included.
+ serving/chat_template.jinja is the chat template of its model card, unchanged.
+
+Step-Audio R1 (github.com/stepfun-ai/Step-Audio-R1), by StepFun. Apache-2.0.
+ controller/encoder/teacher.py contains its AudioEncoder and log-mel code,
+ changed to use scaled dot-product attention and a padding mask.
+ serving/baseline_client.py follows its released client.
+
+Step-Audio 2 (github.com/stepfun-ai/Step-Audio2) and the token2wav weights of
+stepfun-ai/Step-Audio-2-mini, by StepFun. Apache-2.0.
+ Turn audio tokens into sound. Imported unchanged. Not included.
+ serving/speech_out.py contains the warm-up token list of its streaming example.
+
+Kokoro-82M (hexgrad/Kokoro-82M). Apache-2.0.
+ Made the voices of the training dialogues, and the two recordings in assets/
+ (voice pack af_heart). Not included.
+
+Qwen3-32B (Qwen/Qwen3-32B). Apache-2.0.
+ Wrote the text of the training dialogues. Not included.
+
+Big Bench Audio (ArtificialAnalysis/big_bench_audio). MIT.
+ The test questions. Not included.
+
+Whisper large-v3 (openai/whisper-large-v3). Apache-2.0.
+ Transcribed the reply audio for the "as heard" scores. Not included.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..8a2997572b08c3162bdc8b17f1ed78547c848438
--- /dev/null
+++ b/README.md
@@ -0,0 +1,122 @@
+---
+license: apache-2.0
+language:
+- en
+pipeline_tag: audio-to-audio
+tags:
+- speech
+- speech-to-speech
+- full-duplex
+- turn-taking
+- voice-agent
+---
+
+# RightNow Duplex v0
+
+**It listens while you talk. It thinks before it answers. You hear it one second after you stop.**
+
+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.
+
+Preview release by RightNow AI. Apache-2.0. Runs on the open model Step-Audio R1.1 by StepFun.
+
+## Hear it
+
+Four replies to spoken reasoning questions, exactly as the test caller recorded them. You hear the lead-in first, then the answer.
+
+| Question type | Reply |
+|---|---|
+| Is the argument valid? | |
+| Do you return to the starting point? | |
+| How many are there? | |
+| Who tells the truth? | |
+
+## What it does
+
+- **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.
+- **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.
+- **Reasons, then speaks.** Each reply thinks first, as text, and the speech opens with that reasoning already in it.
+- **Fills the silence.** While it reasons it says one short sentence, such as "Let me check if the argument is valid."
+- **Lets you interrupt.** 240 ms of your speech stops a reply. An optional small controller tells an "mm-hm" from an interruption.
+
+## Measured
+
+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.
+
+| | Result |
+|---|---|
+| Answers right, read from the reply's text | 96 of 100 |
+| Answers right, as heard: Whisper large-v3 transcribes the reply audio | 86 of 100 |
+| First audio after the caller stops | median 1.0 s, 90th percentile 1.3 s |
+| The answer itself after the caller stops | median 9.2 s |
+| Questions where the caller heard a false start | 2 of 100 |
+| Word errors in the spoken reply, by Whisper | 1.4% of 1,396 words |
+| The same test with no reasoning before the speech (text score) | 65 of 100 |
+
+The optional controller, on held-out synthetic dialogues with voices and scenarios it did not see in training:
+
+| | Result |
+|---|---|
+| An "mm-hm" not treated as an interruption | 871 of 989 |
+| Interruption caught | 507 of 566 |
+
+Every number, with what failed, is in [RESULTS.md](RESULTS.md).
+
+## Run it
+
+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`).
+
+```bash
+pip install -r requirements.txt
+
+# 1. the speech model behind its released vLLM image (the flags, and the reason for each, are in the script)
+MODEL_DIR=/path/to/Step-Audio-R1.1 bash serving/launch_vllm.sh
+
+# 2. the duplex endpoint, in the configuration measured above
+python -m serving.server --reply-prefix '' --think-first \
+ --judge-prompt v1 --lead-in --lead-in-after-ms 1200 --lead-in-max-tokens 300 \
+ --step-audio2-dir /path/to/Step-Audio2 \
+ --token2wav-dir /path/to/Step-Audio-2-mini/token2wav \
+ --prompt-wav assets/prompt_af_heart.wav
+
+# optional: the controller, for backchannels
+# --encoder-ckpt checkpoints/encoder.safetensors --controller-ckpt checkpoints/controller.safetensors
+```
+
+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.
+
+No GPU at hand? `python -m tests.test_listen_think` runs the endpoint's logic against a fake model.
+
+## In this repository
+
+| Path | What |
+|---|---|
+| `serving/` | The WebSocket endpoint |
+| `checkpoints/` | Two small models trained by RightNow AI, as safetensors: a streaming audio encoder (38.7M parameters) and a turn controller (89.0M parameters) |
+| `controller/`, `data/` | Their training code, and the recipe for the synthetic dialogue data |
+| `eval/`, `tools/`, `tests/` | The measurements and the scripts that produced them |
+| `samples/`, `assets/` | The four replies above, and two synthetic voice prompts |
+
+## Limits
+
+This is a preview. Know these before you build on it.
+
+- **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.
+- **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.
+- **One caller per GPU at this latency.** Two streams had one audible gap, four streams stuttered.
+- **English and synthetic callers only.** One person has listened to a sample of the replies.
+- **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`).
+- **The controller cannot decide when to start.** It starts inside 258 of 580 mid-sentence pauses, so the endpoint asks the speech model instead.
+- Written and not measured: keeping an interrupted reply in the conversation (`--keep-interrupted`).
+- Tried and switched off: reasoning while the caller is still speaking. Without training it cost accuracy.
+
+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.
+
+## Licence and credit
+
+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.
+
+## About RightNow AI
+
+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.
+
+https://www.rightnowai.co
diff --git a/RESULTS.md b/RESULTS.md
new file mode 100644
index 0000000000000000000000000000000000000000..b7810da3407ddaa939b08aabb72a452018c8a222
--- /dev/null
+++ b/RESULTS.md
@@ -0,0 +1,106 @@
+# Results
+
+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.
+
+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.
+
+## The duplex layer
+
+Four callers at a time per copy of the model. Times are counted from the end of the question on the caller's clock.
+
+| Configuration | Right, text | Right, as heard | First audio, median / p90 | Answer itself, median | Questions with an audible false start |
+|---|---|---|---|---|---|
+| 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 |
+| The model decides the end of turn, speech directly | 65 | not measured | not measured | not measured | 35 |
+| The model decides, reasoning then speech | 95 | 74 | 11.2 / 31.4 s | 11.2 s | 1 |
+| The same, with a lead-in played at once | 95 | not measured | 1.0 / 1.2 s | 12.9 s | 25 |
+| 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 |
+| **The same, lead-in up to 300 tokens (the configuration in the README)** | **96** | **86** | **1.0 / 1.3 s** | 9.2 s | 2 |
+
+- The lead-in does not change how often the answer is right. It changes when the caller first hears the model.
+- 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.
+- 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).
+- All 100 replies had a lead-in, 13 words at the median. None states an answer.
+- 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.
+
+## The model as its own end-of-turn judge
+
+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.
+
+| Who decides when to answer | Clean turns | First audio, median / p90 | Turns where the caller heard the model early |
+|---|---|---|---|
+| A fixed 640 ms of silence | 96 | 1,523 / 1,709 ms | 4 |
+| The small controller | 44 | 1,258 / 1,737 ms | 55 |
+| The speech model, asked yes or no (prompt v1) | 95 | 1,178 / 1,639 ms | 5 |
+| The speech model, stricter wording (prompt v2) | 98 | 1,353 / 1,699 ms | 2 |
+
+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.
+
+## Tried and switched off: reasoning while the caller is still speaking
+
+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.
+
+| Arm | Questions | Right, text | Answer itself, median |
+|---|---|---|---|
+| Nothing carried (reference) | 100 | 95 | 11.2 s |
+| A withdrawn reply keeps its reasoning | 70 | 62 | 6.6 s |
+| Also reasons while listening | 64 | 50 | 7.7 s |
+| Told at the end to check its work | 20 | 8 | 1.0 s |
+| Told to take notes | 46 | 32 | 7.9 s |
+
+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.
+
+## How much reasoning the spoken answer needs
+
+One caller at a time, reasoning limited to a number of tokens before the speech starts (text score).
+
+| Reasoning tokens allowed | 0 | 64 | 128 | 256 | 512 | 2,048 |
+|---|---|---|---|---|---|---|
+| Right of 100 | 67 | 46 | 45 | 66 | 79 | 95 |
+
+Reasoning that is cut short is worse than none.
+
+## Streams on one GPU
+
+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.
+
+| Audio settings | 1 stream | 2 streams | 4 streams |
+|---|---|---|---|
+| Released recipe: 25 tokens per chunk, one decoder | 880 ms, 0 underruns | 840 ms, 0 | 960 ms, 3 |
+| First chunk of 12 tokens, small chunks while the buffer is low, four decoders | 561 ms, 0 | 640 ms, 1 | 721 ms, 91 |
+
+A reply is generated at about 62 tokens per second for one stream. Speech needs about 31.
+
+## The two small models
+
+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).
+
+| | |
+|---|---|
+| 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 |
+| Turn controller | 89.0M parameters. One step for both, frame by frame: 12.4 ms on average per 80 ms frame |
+| Frame labels, precision / recall | WAIT 0.985 / 0.977 · START 0.566 / 0.676 · STOP 0.793 / 0.834 · BACKCHANNEL 0.887 / 0.892 |
+| Backchannel not treated as an interruption | 871 of 989 (a plain loudness rule: 0 of 989) |
+| Interruption caught | 507 of 566 |
+| No start inside a mid-sentence pause | 322 of 580 |
+| Turn end caught in its window | 1,567 of 2,015 |
+
+The controller is not good enough to decide when to start. The endpoint uses it only to tell a backchannel from an interruption.
+
+## The training data
+
+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.
+
+## Step-Audio R1.1 through its released image, on the GPUs used here
+
+- 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.
+- A request for token probabilities stops the engine, so the end-of-turn judge reads a plain yes or no.
+- 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.
+- The weights take 62.4 GiB.
+
+## Not measured
+
+- The leaderboard's own scoring of Big Bench Audio.
+- Real callers. Every test caller was synthetic speech. One person has listened to a sample of the replies.
+- Any public test of turn-taking or of reasoning under interruption. The ones found are not under Apache-2.0 or MIT.
+- Keeping an interrupted reply in the conversation (`--keep-interrupted`).
diff --git a/assets/prompt_af_heart.wav b/assets/prompt_af_heart.wav
new file mode 100644
index 0000000000000000000000000000000000000000..ed05baa955a50dd96f7f1728a9549083e2b388f8
--- /dev/null
+++ b/assets/prompt_af_heart.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:ea63ce9066d51935cba843c657af9a823ffed86f3197c6928f2d935f052eb915
+size 494444
diff --git a/assets/prompt_af_heart_short.wav b/assets/prompt_af_heart_short.wav
new file mode 100644
index 0000000000000000000000000000000000000000..db001e0603d3d356357ce5453c5c68603a5870c6
--- /dev/null
+++ b/assets/prompt_af_heart_short.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:382f1b76802c795ac88a7eb362ab4ef7516f19d6670480cb7f8a3dd9a594accc
+size 174044
diff --git a/checkpoints/controller.json b/checkpoints/controller.json
new file mode 100644
index 0000000000000000000000000000000000000000..9fcf1055a5d328652bf80d17ad1e9f56a8c079ec
--- /dev/null
+++ b/checkpoints/controller.json
@@ -0,0 +1,11 @@
+{
+ "cfg": {
+ "feat_dim": 1280,
+ "dim": 768,
+ "layers": 12,
+ "heads": 12,
+ "window": 375
+ },
+ "training_step": 25180,
+ "tensor_values": 88992772
+}
diff --git a/checkpoints/controller.safetensors b/checkpoints/controller.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..bfffc0b292a75d8f8245c5558cc99a0705f7b42f
--- /dev/null
+++ b/checkpoints/controller.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:b3db116d71d645410abaa5357dbc0fea319b63458d54fbee2994228c87b7722c
+size 355985120
diff --git a/checkpoints/encoder.json b/checkpoints/encoder.json
new file mode 100644
index 0000000000000000000000000000000000000000..6b6d0c3045a1c8cda1d3945641df01a97ae481a3
--- /dev/null
+++ b/checkpoints/encoder.json
@@ -0,0 +1,11 @@
+{
+ "cfg": {
+ "dim": 512,
+ "layers": 12,
+ "heads": 8,
+ "window": 250,
+ "out_dim": 1280
+ },
+ "training_step": 16900,
+ "tensor_values": 38775056
+}
diff --git a/checkpoints/encoder.safetensors b/checkpoints/encoder.safetensors
new file mode 100644
index 0000000000000000000000000000000000000000..4279f566d2c3d752463595c54405013df312254d
--- /dev/null
+++ b/checkpoints/encoder.safetensors
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:8be66a92e105b0903dd6fc10f03f09df8aa0dc46e511aed986baa5aaf2394bc9
+size 155114112
diff --git a/controller/__init__.py b/controller/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/controller/encoder/__init__.py b/controller/encoder/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/controller/encoder/distill.py b/controller/encoder/distill.py
new file mode 100644
index 0000000000000000000000000000000000000000..36eb34e21d88c823c019c041b02817c33249fdd6
--- /dev/null
+++ b/controller/encoder/distill.py
@@ -0,0 +1,117 @@
+"""Distil the baseline audio encoder into the causal streaming student.
+
+Loss: L1 + (1 - cosine) between student and teacher features, frame by frame at 25 Hz.
+Both channels of every crop are used (noisy caller audio and clean agent audio).
+
+ torchrun --nproc_per_node=3 -m controller.encoder.distill \
+ --data data/out/dataset --baseline-dir /models/Step-Audio-R1.1 --out runs/encoder --max-hours 1.5
+"""
+import argparse
+from pathlib import Path
+
+import torch
+import torch.nn.functional as F
+from torch.nn.parallel import DistributedDataParallel
+from torch.utils.data import DataLoader
+
+from controller.encoder.student import StudentEncoder, mel_filterbank, save_student
+from controller.encoder.teacher import Teacher
+from data.dataset import Crops
+from duplex.spec import FRAME_MS
+from duplex.streaming import cosine_by_time, count_params
+from duplex.train_utils import Budget, log_row, setup_ddp
+
+
+def losses(pred, target):
+ l1 = F.l1_loss(pred, target)
+ cos = 1.0 - F.cosine_similarity(pred, target, dim=-1).mean()
+ return l1, cos
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--data", required=True)
+ ap.add_argument("--baseline-dir", required=True, help="local folder of stepfun-ai/Step-Audio-R1.1")
+ ap.add_argument("--out", required=True)
+ ap.add_argument("--max-hours", type=float, default=1.5)
+ ap.add_argument("--batch", type=int, default=16, help="crops per GPU; each crop gives two clips (caller, agent)")
+ ap.add_argument("--crop-s", type=float, default=20.0, help="at most 29 s: the teacher's context")
+ ap.add_argument("--lr", type=float, default=4e-4)
+ ap.add_argument("--dim", type=int, default=512)
+ ap.add_argument("--layers", type=int, default=12)
+ ap.add_argument("--heads", type=int, default=8)
+ ap.add_argument("--window", type=int, default=250, help="attention window in 40 ms tokens (250 = 10 s)")
+ ap.add_argument("--workers", type=int, default=6)
+ ap.add_argument("--eval-every", type=int, default=500)
+ ap.add_argument("--ckpt-minutes", type=float, default=60.0, help="a checkpoint this often (the plan: hourly)")
+ args = ap.parse_args()
+
+ rank, world, device = setup_ddp()
+ out = Path(args.out)
+ out.mkdir(parents=True, exist_ok=True)
+ crop_frames = int(args.crop_s * 1000 / FRAME_MS)
+
+ teacher = Teacher(args.baseline_dir).to(device)
+ student = StudentEncoder(args.dim, args.layers, args.heads, args.window, fb=mel_filterbank()).to(device)
+ model = DistributedDataParallel(student, device_ids=[device.index]) if world > 1 else student
+ opt = torch.optim.AdamW(student.parameters(), lr=args.lr, betas=(0.9, 0.98), weight_decay=0.01)
+
+ loader = DataLoader(Crops(args.data, "train", crop_frames, seed=1000 + rank), batch_size=args.batch, num_workers=args.workers)
+ eval_set = list(DataLoader(Crops(args.data, "test", crop_frames, seed=7, limit=8 * args.batch), batch_size=args.batch)) if rank == 0 else []
+ log = str(out / "log.jsonl") if rank == 0 else None
+ if rank == 0:
+ log_row(log, event="start", student_params=count_params(student), teacher_params=count_params(teacher.encoder),
+ world=world, batch_per_gpu=args.batch, crop_s=args.crop_s, max_hours=args.max_hours)
+
+ budget = Budget(args.max_hours, rank, world, device, args.ckpt_minutes)
+ frac = 0.0
+ for step, (wav, _) in enumerate(loader):
+ if step % 20 == 0:
+ frac = budget.sync()
+ if frac >= 1.0:
+ break
+ n_ckpt = budget.checkpoint_due()
+ if n_ckpt and rank == 0:
+ save_student(out / f"ckpt_{n_ckpt:02d}.pt", student, {"step": step, "elapsed_s": budget.elapsed})
+ log_row(log, event="checkpoint", number=n_ckpt, step=step, elapsed_s=budget.elapsed)
+ for g in opt.param_groups:
+ g["lr"] = args.lr * cosine_by_time(frac)
+
+ wav = wav.to(device, non_blocking=True).flatten(0, 1) # [B*2, T]
+ target = teacher(wav)
+ with torch.autocast(device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):
+ pred = model(wav)
+ l1, cos = losses(pred.float(), target)
+ opt.zero_grad(set_to_none=True)
+ (l1 + cos).backward()
+ torch.nn.utils.clip_grad_norm_(student.parameters(), 1.0)
+ opt.step()
+
+ if rank == 0 and step % 50 == 0:
+ log_row(log, event="train", step=step, elapsed_s=budget.elapsed, l1=l1.item(), cos_dist=cos.item(), lr=opt.param_groups[0]["lr"])
+ if rank == 0 and step and step % args.eval_every == 0:
+ evaluate(student, teacher, eval_set, device, log, step)
+
+ if rank == 0:
+ evaluate(student, teacher, eval_set, device, log, step)
+ save_student(out / "final.pt", student, {"step": step, "elapsed_s": budget.elapsed})
+ log_row(log, event="done", step=step, elapsed_s=budget.elapsed)
+
+
+@torch.no_grad()
+def evaluate(student, teacher, eval_set, device, log, step):
+ student.eval()
+ l1s, coss = [], []
+ for wav, _ in eval_set:
+ wav = wav.to(device).flatten(0, 1)
+ with torch.autocast(device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):
+ pred = student(wav)
+ l1, cos = losses(pred.float(), teacher(wav))
+ l1s.append(l1.item())
+ coss.append(cos.item())
+ student.train()
+ log_row(log, event="eval", step=step, heldout_l1=sum(l1s) / len(l1s), heldout_cos_sim=1.0 - sum(coss) / len(coss))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/controller/encoder/student.py b/controller/encoder/student.py
new file mode 100644
index 0000000000000000000000000000000000000000..f689e7b5c60e155566eeeaec72fe6a84a9029ba7
--- /dev/null
+++ b/controller/encoder/student.py
@@ -0,0 +1,87 @@
+"""Causal streaming student of the baseline audio encoder.
+
+Input: 16 kHz mono audio. Output: one 1280-d vector every 40 ms (25 Hz), the rate and
+width of the baseline AudioEncoder, so two vectors per 80 ms frame.
+
+Nothing here looks ahead: the mel frame for hop k uses samples up to the end of hop k
+(the baseline's STFT is centred and its log-mel is clamped by the whole clip's
+maximum, which a streaming front end cannot do), and attention is causal with a
+bounded window. `forward` (whole crop) and `step` (80 ms at a time) are the same
+function.
+"""
+import torch
+import torch.nn as nn
+
+from duplex.spec import HOP, N_FFT, N_MELS, PATCH, SR, TEACHER_DIM
+from duplex.streaming import CausalTransformer
+
+TAIL = N_FFT - HOP # 240 samples of history each new mel frame needs
+
+
+def mel_filterbank():
+ """The baseline's filterbank (librosa, Slaney), built once at training time and then
+ carried inside the checkpoint, so serving does not need librosa."""
+ import librosa
+ return torch.from_numpy(librosa.filters.mel(sr=SR, n_fft=N_FFT, n_mels=N_MELS)).float()
+
+
+class StreamingMel(nn.Module):
+ def __init__(self, fb=None):
+ super().__init__()
+ self.register_buffer("window", torch.hann_window(N_FFT))
+ self.register_buffer("fb", fb if fb is not None else torch.zeros(N_MELS, N_FFT // 2 + 1))
+
+ def forward(self, wav, tail=None):
+ """wav [B, T], T a multiple of HOP -> log-mel [B, T/HOP, N_MELS], new tail [B, 240]."""
+ assert wav.shape[1] % HOP == 0
+ with torch.autocast(wav.device.type, enabled=False):
+ wav = wav.float()
+ if tail is None:
+ tail = wav.new_zeros(wav.shape[0], TAIL)
+ x = torch.cat([tail, wav], dim=1)
+ frames = x.unfold(1, N_FFT, HOP) # [B, T/HOP, 400]
+ power = torch.fft.rfft(frames * self.window, dim=-1).abs() ** 2
+ mel = power @ self.fb.T
+ logmel = (torch.clamp(mel, min=1e-6).log10() + 4.0) / 4.0 # fixed floor, no clip-level max
+ return logmel, x[:, -TAIL:]
+
+
+class StudentEncoder(nn.Module):
+ def __init__(self, dim=512, layers=12, heads=8, window=250, out_dim=TEACHER_DIM, fb=None):
+ super().__init__()
+ self.cfg = dict(dim=dim, layers=layers, heads=heads, window=window, out_dim=out_dim)
+ self.mel = StreamingMel(fb)
+ self.inp = nn.Linear(PATCH * N_MELS, dim)
+ self.tf = CausalTransformer(dim, layers, heads, window)
+ self.ln = nn.LayerNorm(dim)
+ self.head = nn.Linear(dim, out_dim)
+
+ def _tokens(self, logmel):
+ B, N, M = logmel.shape
+ return self.inp(logmel.reshape(B, N // PATCH, PATCH * M).to(self.inp.weight.dtype))
+
+ def forward(self, wav):
+ """wav [B, T], T a multiple of 640 -> features [B, T/640, out_dim]."""
+ logmel, _ = self.mel(wav)
+ return self.head(self.ln(self.tf(self._tokens(logmel))))
+
+ def init_state(self, batch, device):
+ return {"tail": torch.zeros(batch, TAIL, device=device), "tf": self.tf.init_state()}
+
+ def step(self, wav, state):
+ """wav [B, t], t a multiple of 640 (one 80 ms frame is 1280) -> [B, t/640, out_dim]."""
+ logmel, tail = self.mel(wav, state["tail"])
+ x, tf = self.tf.step(self._tokens(logmel), state["tf"])
+ return self.head(self.ln(x)), {"tail": tail, "tf": tf}
+
+
+def save_student(path, model, extra=None):
+ torch.save({"cfg": model.cfg, "model": model.state_dict(), "extra": extra or {}}, path)
+
+
+def load_student(path, device="cpu"):
+ from duplex.streaming import read_checkpoint
+ cfg, state = read_checkpoint(path)
+ model = StudentEncoder(**cfg)
+ model.load_state_dict(state)
+ return model.to(device).eval()
diff --git a/controller/encoder/teacher.py b/controller/encoder/teacher.py
new file mode 100644
index 0000000000000000000000000000000000000000..842cb879d822eb90b47c6369c8456214b6225e95
--- /dev/null
+++ b/controller/encoder/teacher.py
@@ -0,0 +1,126 @@
+"""The baseline's audio encoder, loaded alone (about 0.6B of the 33B), as the frozen teacher.
+
+`AudioEncoder`, `log_mel` and the length arithmetic follow
+modeling_step_audio_2.py / utils.py of stepfun-ai/Step-Audio-R1.1
+(Copyright StepFun, Apache-2.0). Parameter names are kept identical so the released
+weights load with strict=True. Only the `encoder.*` tensors are read from the
+checkpoint shards; the LLM is never loaded.
+"""
+import json
+from pathlib import Path
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+from duplex.spec import N_FFT, N_MELS, SR
+
+
+class MultiHeadAttention(nn.Module):
+ def __init__(self, n_state, n_head):
+ super().__init__()
+ self.n_head = n_head
+ self.query = nn.Linear(n_state, n_state)
+ self.key = nn.Linear(n_state, n_state, bias=False)
+ self.value = nn.Linear(n_state, n_state)
+ self.out = nn.Linear(n_state, n_state)
+
+ def forward(self, x, bias):
+ # Same attention as the released code (q and k each scaled by d_head ** -0.25, i.e. the usual
+ # 1 / sqrt(d_head)), computed with PyTorch's fused routine: the released explicit float32
+ # softmax over batch x heads x T x T made a distillation step several times slower.
+ B, T, _ = x.shape
+ q, k, v = (m(x).view(B, T, self.n_head, -1).transpose(1, 2) for m in (self.query, self.key, self.value))
+ a = F.scaled_dot_product_attention(q, k, v, attn_mask=bias.to(q.dtype))
+ return self.out(a.transpose(1, 2).flatten(start_dim=2))
+
+
+class ResidualAttentionBlock(nn.Module):
+ def __init__(self, n_state, n_head):
+ super().__init__()
+ self.attn = MultiHeadAttention(n_state, n_head)
+ self.attn_ln = nn.LayerNorm(n_state)
+ self.mlp = nn.Sequential(nn.Linear(n_state, n_state * 4), nn.GELU(), nn.Linear(n_state * 4, n_state))
+ self.mlp_ln = nn.LayerNorm(n_state)
+
+ def forward(self, x, bias):
+ x = x + self.attn(self.attn_ln(x), bias)
+ return x + self.mlp(self.mlp_ln(x))
+
+
+class AudioEncoder(nn.Module):
+ """Every clip in a batch has the same length here (fixed crops). The released code
+ still hides the two mel frames that come from its 479-sample padding
+ (feats_lengths = frames - 2); the same key mask is applied here."""
+
+ def __init__(self, n_mels=128, n_ctx=1500, n_state=1280, n_head=20, n_layer=32):
+ super().__init__()
+ self.conv1 = nn.Conv1d(n_mels, n_state, kernel_size=3, padding=1)
+ self.conv2 = nn.Conv1d(n_state, n_state, kernel_size=3, stride=2, padding=1)
+ self.positional_embedding = nn.Embedding(n_ctx, n_state)
+ self.blocks = nn.ModuleList([ResidualAttentionBlock(n_state, n_head) for _ in range(n_layer)])
+ self.avg_pooler = nn.AvgPool1d(2, stride=2)
+ self.after_norm = nn.LayerNorm(n_state)
+
+ def forward(self, mel):
+ T = mel.size(-1)
+ x = F.gelu(self.conv1(mel))
+ x = F.gelu(self.conv2(x)).permute(0, 2, 1)
+ assert x.shape[1] <= self.positional_embedding.num_embeddings, "clip longer than the encoder context (about 29.9 s)"
+ valid = (torch.arange(T, device=mel.device) < T - 2)[(T + 1) % 2::2] # released make_non_pad_mask + subsampling
+ bias = ((~valid).to(x.dtype) * -1.0e10)[None, None, None, :]
+ x = x + self.positional_embedding.weight[: x.shape[1]]
+ for block in self.blocks:
+ x = block(x, bias)
+ x = self.avg_pooler(x.permute(0, 2, 1)).permute(0, 2, 1)
+ return self.after_norm(x)
+
+
+def log_mel(audio, filters):
+ """Released log_mel_spectrogram (padding=479), batched over equal-length clips [B, T]."""
+ audio = F.pad(audio, (0, 479))
+ window = torch.hann_window(N_FFT, device=audio.device)
+ stft = torch.stft(audio, N_FFT, 160, window=window, return_complex=True)
+ mel = filters @ (stft[..., :-1].abs() ** 2)
+ log_spec = torch.clamp(mel, min=1e-10).log10()
+ log_spec = torch.maximum(log_spec, log_spec.amax(dim=(1, 2), keepdim=True) - 8.0) # per clip, as released
+ return (log_spec + 4.0) / 4.0
+
+
+class Teacher(nn.Module):
+ def __init__(self, model_dir):
+ super().__init__()
+ import librosa
+ self.register_buffer("filters", torch.from_numpy(librosa.filters.mel(sr=SR, n_fft=N_FFT, n_mels=N_MELS)).float())
+ model_dir = Path(model_dir)
+ cfg = json.loads((model_dir / "config.json").read_text())["audio_encoder_config"]
+ self.encoder = AudioEncoder(cfg["n_mels"], cfg["n_audio_ctx"], cfg["n_audio_state"], cfg["n_audio_head"], cfg["n_audio_layer"])
+ self.encoder.load_state_dict(_encoder_weights(model_dir), strict=True)
+ self.requires_grad_(False).eval()
+
+ @torch.no_grad()
+ def forward(self, wav):
+ """wav [B, T] at 16 kHz, T a multiple of 640 -> [B, T/640, 1280] (25 Hz)."""
+ with torch.autocast(wav.device.type, enabled=False):
+ mel = log_mel(wav.float(), self.filters)
+ with torch.autocast(wav.device.type, dtype=torch.bfloat16, enabled=wav.is_cuda):
+ out = self.encoder(mel)
+ n = wav.shape[1] // 640
+ assert out.shape[1] == n, f"teacher gave {out.shape[1]} frames for {n} expected"
+ return out.float()
+
+
+def _encoder_weights(model_dir):
+ from safetensors import safe_open
+ weight_map = json.loads((model_dir / "model.safetensors.index.json").read_text())["weight_map"]
+ keys = [k for k in weight_map if k.startswith("encoder.")]
+ if not keys:
+ prefixes = sorted({k.split(".")[0] for k in weight_map})
+ raise RuntimeError(f"no 'encoder.*' tensors in the checkpoint index; top-level names are {prefixes}")
+ sd = {}
+ for shard in sorted({weight_map[k] for k in keys}):
+ with safe_open(str(model_dir / shard), framework="pt") as f:
+ for k in f.keys():
+ if k.startswith("encoder."):
+ sd[k[len("encoder."):]] = f.get_tensor(k).float()
+ return sd
diff --git a/controller/model/__init__.py b/controller/model/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/controller/model/model.py b/controller/model/model.py
new file mode 100644
index 0000000000000000000000000000000000000000..6d7d15151ab872bc60da29696221e6693310c1b6
--- /dev/null
+++ b/controller/model/model.py
@@ -0,0 +1,50 @@
+"""The duplex controller: a small causal transformer that reads, per 80 ms frame, the
+streaming encoder features of the caller's audio and of the model's own output audio,
+and predicts one of WAIT, START, STOP, BACKCHANNEL.
+
+Default size is about 90M parameters (dim 768, 12 layers); the plan's ceiling is 1B.
+"""
+import torch
+import torch.nn as nn
+
+from duplex.spec import LABELS, TEACHER_DIM, TOK_PER_FRAME
+from duplex.streaming import CausalTransformer
+
+
+class Controller(nn.Module):
+ def __init__(self, feat_dim=TEACHER_DIM, dim=768, layers=12, heads=12, window=375):
+ super().__init__()
+ self.cfg = dict(feat_dim=feat_dim, dim=dim, layers=layers, heads=heads, window=window)
+ self.in_caller = nn.Linear(TOK_PER_FRAME * feat_dim, dim)
+ self.in_self = nn.Linear(TOK_PER_FRAME * feat_dim, dim)
+ self.tf = CausalTransformer(dim, layers, heads, window) # window in 80 ms frames (375 = 30 s)
+ self.ln = nn.LayerNorm(dim)
+ self.head = nn.Linear(dim, len(LABELS))
+
+ def _embed(self, caller, own):
+ """caller, own: [B, 2T, feat_dim] at 25 Hz -> [B, T, dim] at 12.5 Hz."""
+ B, N, Fd = caller.shape
+ shape = (B, N // TOK_PER_FRAME, TOK_PER_FRAME * Fd)
+ return self.in_caller(caller.reshape(shape)) + self.in_self(own.reshape(shape))
+
+ def forward(self, caller, own):
+ return self.head(self.ln(self.tf(self._embed(caller, own))))
+
+ def init_state(self):
+ return self.tf.init_state()
+
+ def step(self, caller, own, state):
+ x, state = self.tf.step(self._embed(caller, own), state)
+ return self.head(self.ln(x)), state
+
+
+def save_controller(path, model, extra=None):
+ torch.save({"cfg": model.cfg, "model": model.state_dict(), "extra": extra or {}}, path)
+
+
+def load_controller(path, device="cpu"):
+ from duplex.streaming import read_checkpoint
+ cfg, state = read_checkpoint(path)
+ model = Controller(**cfg)
+ model.load_state_dict(state)
+ return model.to(device).eval()
diff --git a/controller/model/train.py b/controller/model/train.py
new file mode 100644
index 0000000000000000000000000000000000000000..4784f3075cbb3748f4cbbd6c28eb47f3f486aa3f
--- /dev/null
+++ b/controller/model/train.py
@@ -0,0 +1,124 @@
+"""Train the duplex controller on frozen student-encoder features.
+
+One run, time-budgeted (default 3.75 h so it ends inside 4 h), a checkpoint every hour.
+The loss is cross-entropy weighted toward START / STOP / BACKCHANNEL and away from WAIT.
+
+ torchrun --nproc_per_node=3 -m controller.model.train \
+ --data data/out/dataset --encoder runs/encoder/final.pt --out runs/controller
+"""
+import argparse
+from pathlib import Path
+
+import numpy as np
+import torch
+import torch.nn.functional as F
+from torch.nn.parallel import DistributedDataParallel
+from torch.utils.data import DataLoader
+
+from controller.encoder.student import load_student
+from controller.model.model import Controller, save_controller
+from data.dataset import Crops
+from duplex.spec import FRAME_MS, LABELS
+from duplex.streaming import cosine_by_time, count_params
+from duplex.train_utils import Budget, confusion, log_row, precision_recall, setup_ddp
+
+
+@torch.no_grad()
+def features(encoder, wav, device):
+ """wav [B, 2, T] -> caller feats, own feats, each [B, T/640, 1280]."""
+ B = wav.shape[0]
+ with torch.autocast(device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):
+ f = encoder(wav.flatten(0, 1))
+ f = f.view(B, 2, f.shape[1], f.shape[2])
+ return f[:, 0], f[:, 1]
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--data", required=True)
+ ap.add_argument("--encoder", required=True, help="student encoder checkpoint from controller.encoder.distill")
+ ap.add_argument("--out", required=True)
+ ap.add_argument("--max-hours", type=float, default=3.75)
+ ap.add_argument("--batch", type=int, default=24, help="crops per GPU")
+ ap.add_argument("--crop-s", type=float, default=30.0)
+ ap.add_argument("--lr", type=float, default=3e-4)
+ ap.add_argument("--dim", type=int, default=768)
+ ap.add_argument("--layers", type=int, default=12)
+ ap.add_argument("--heads", type=int, default=12)
+ ap.add_argument("--window", type=int, default=375, help="attention window in 80 ms frames (375 = 30 s)")
+ ap.add_argument("--class-weights", default="0.2,1,1,1", help="loss weight for " + ",".join(LABELS))
+ ap.add_argument("--workers", type=int, default=6)
+ ap.add_argument("--eval-every", type=int, default=500)
+ ap.add_argument("--ckpt-minutes", type=float, default=60.0, help="a checkpoint this often (the plan: hourly)")
+ args = ap.parse_args()
+
+ rank, world, device = setup_ddp()
+ out = Path(args.out)
+ out.mkdir(parents=True, exist_ok=True)
+ crop_frames = int(args.crop_s * 1000 / FRAME_MS)
+ weights = torch.tensor([float(w) for w in args.class_weights.split(",")], device=device)
+ assert len(weights) == len(LABELS)
+
+ encoder = load_student(args.encoder, device).requires_grad_(False)
+ ctl = Controller(encoder.cfg["out_dim"], args.dim, args.layers, args.heads, args.window).to(device)
+ assert count_params(ctl) < 1_000_000_000
+ model = DistributedDataParallel(ctl, device_ids=[device.index]) if world > 1 else ctl
+ opt = torch.optim.AdamW(ctl.parameters(), lr=args.lr, betas=(0.9, 0.98), weight_decay=0.01)
+
+ loader = DataLoader(Crops(args.data, "train", crop_frames, seed=2000 + rank), batch_size=args.batch, num_workers=args.workers)
+ eval_set = list(DataLoader(Crops(args.data, "test", crop_frames, seed=7, limit=16 * args.batch), batch_size=args.batch)) if rank == 0 else []
+ log = str(out / "log.jsonl") if rank == 0 else None
+ if rank == 0:
+ log_row(log, event="start", controller_params=count_params(ctl), encoder_params=count_params(encoder), world=world,
+ batch_per_gpu=args.batch, crop_s=args.crop_s, max_hours=args.max_hours, class_weights=args.class_weights)
+
+ budget = Budget(args.max_hours, rank, world, device, args.ckpt_minutes)
+ frac = 0.0
+ for step, (wav, labels) in enumerate(loader):
+ if step % 20 == 0:
+ frac = budget.sync()
+ if frac >= 1.0:
+ break
+ n_ckpt = budget.checkpoint_due()
+ if n_ckpt and rank == 0:
+ save_controller(out / f"ckpt_{n_ckpt:02d}.pt", ctl, {"step": step, "elapsed_s": budget.elapsed})
+ log_row(log, event="checkpoint", number=n_ckpt, step=step, elapsed_s=budget.elapsed)
+ for g in opt.param_groups:
+ g["lr"] = args.lr * cosine_by_time(frac)
+
+ wav, labels = wav.to(device, non_blocking=True), labels.to(device, non_blocking=True)
+ caller, own = features(encoder, wav, device)
+ with torch.autocast(device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):
+ logits = model(caller, own)
+ loss = F.cross_entropy(logits.float().flatten(0, 1), labels.flatten(), weight=weights, ignore_index=-100)
+ opt.zero_grad(set_to_none=True)
+ loss.backward()
+ torch.nn.utils.clip_grad_norm_(ctl.parameters(), 1.0)
+ opt.step()
+
+ if rank == 0 and step % 50 == 0:
+ log_row(log, event="train", step=step, elapsed_s=budget.elapsed, loss=loss.item(), lr=opt.param_groups[0]["lr"])
+ if rank == 0 and step and step % args.eval_every == 0:
+ evaluate(encoder, ctl, eval_set, device, log, step)
+
+ if rank == 0:
+ evaluate(encoder, ctl, eval_set, device, log, step)
+ save_controller(out / "final.pt", ctl, {"step": step, "elapsed_s": budget.elapsed})
+ log_row(log, event="done", step=step, elapsed_s=budget.elapsed)
+
+
+@torch.no_grad()
+def evaluate(encoder, ctl, eval_set, device, log, step):
+ ctl.eval()
+ conf = np.zeros((len(LABELS), len(LABELS)), dtype=np.int64)
+ for wav, labels in eval_set:
+ caller, own = features(encoder, wav.to(device), device)
+ with torch.autocast(device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):
+ pred = ctl(caller, own).argmax(-1)
+ conf += confusion(pred.cpu().numpy(), labels.numpy())
+ ctl.train()
+ log_row(log, event="eval", step=step, heldout=precision_recall(conf))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/controller/runtime.py b/controller/runtime.py
new file mode 100644
index 0000000000000000000000000000000000000000..77b685bcecc25e975b975afaf26d432120997eab
--- /dev/null
+++ b/controller/runtime.py
@@ -0,0 +1,31 @@
+"""Frame-by-frame controller for the server: one call per 80 ms frame, per session."""
+import numpy as np
+import torch
+
+from controller.encoder.student import load_student
+from controller.model.model import load_controller
+from duplex.spec import FRAME
+
+
+class DuplexController:
+ def __init__(self, encoder_ckpt, controller_ckpt, device="cuda:1"):
+ self.device = torch.device(device)
+ self.encoder = load_student(encoder_ckpt, self.device)
+ self.ctl = load_controller(controller_ckpt, self.device)
+ warm = self.new_session() # first calls pay one-time GPU set-up; do it before a caller arrives
+ for _ in range(30):
+ self.step(warm, np.zeros(FRAME, np.float32), np.zeros(FRAME, np.float32))
+
+ def new_session(self):
+ # batch of 2 in the encoder: row 0 is the caller's audio, row 1 the model's own output
+ return {"enc": self.encoder.init_state(2, self.device), "ctl": self.ctl.init_state()}
+
+ @torch.inference_mode()
+ def step(self, sess, caller_frame, own_frame):
+ """caller_frame, own_frame: float32 [1280] at 16 kHz. Returns probabilities over LABELS."""
+ assert len(caller_frame) == FRAME and len(own_frame) == FRAME
+ wav = torch.from_numpy(np.stack([caller_frame, own_frame]).astype(np.float32)).to(self.device)
+ with torch.autocast(self.device.type, dtype=torch.bfloat16, enabled=self.device.type == "cuda"):
+ feats, sess["enc"] = self.encoder.step(wav, sess["enc"])
+ logits, sess["ctl"] = self.ctl.step(feats[0:1], feats[1:2], sess["ctl"])
+ return torch.softmax(logits[0, -1].float(), dim=-1).cpu().numpy()
diff --git a/data/__init__.py b/data/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/data/build_timeline.py b/data/build_timeline.py
new file mode 100644
index 0000000000000000000000000000000000000000..d366e4d3547ada69594c0cfc3a56062e13fbf9e1
--- /dev/null
+++ b/data/build_timeline.py
@@ -0,0 +1,251 @@
+"""Put both speakers of each dialogue on one shared timeline and label every 80 ms frame.
+
+Channel 0 is the caller as the model hears them (room, line and noise effects, and
+sometimes the model's own voice leaking back). Channel 1 is the model's own output
+audio, clean, exactly what a server would have sent.
+
+Labels are the action the model (the agent) should take in that frame:
+ START the caller's turn is over and the agent has not begun yet. The agent's
+ audio starts in the frame right after the last START frame, so the label
+ can never be read off the agent's own channel.
+ STOP the caller is truly interrupting; from one frame after the caller's onset
+ until the agent's audio is cut.
+ BACKCHANNEL the caller says "mm-hm" over the agent; the agent keeps talking.
+ WAIT everything else, including mid-sentence pauses of the caller.
+
+All noise, room responses and line effects are generated here (no third-party audio),
+so the licence of the dataset is the licence of this code and of the TTS output.
+
+ python -m data.build_timeline --dialogues data/out/dialogues.jsonl --tts data/out/tts \
+ --out data/out/dataset --workers 32
+"""
+import argparse
+import json
+import zlib
+from collections import Counter
+from multiprocessing import Pool
+from pathlib import Path
+
+import numpy as np
+
+from duplex.spec import AGENT, BACKCHANNEL, CALLER, FRAME, LABELS, SR, START, STOP, read_jsonl, write_json, write_wav
+
+
+def trim(x, rel=0.01, margin=160):
+ """Cut leading and trailing silence, keeping 10 ms each side."""
+ x = x.astype(np.float32) / 32768.0
+ if not len(x):
+ return x
+ loud = np.nonzero(np.abs(x) > rel * max(float(np.abs(x).max()), 1e-6))[0]
+ return x[max(0, loud[0] - margin): loud[-1] + margin] if len(loud) else x[:0]
+
+
+def lay_out(d, clips, bank, rng, barge_prob=0.0):
+ """Returns (placements, events, end_sample) or None when a turn could not be voiced."""
+ turns = []
+ for ti, turn in enumerate(d["turns"]):
+ parts, si = [], 0
+ while f"t{ti}_s{si}" in clips:
+ part = trim(clips[f"t{ti}_s{si}"])
+ if len(part) < SR // 20:
+ return None
+ parts.append(part)
+ si += 1
+ if not parts:
+ return None
+ turns.append((turn["spk"], parts, turn.get("interrupts", False)))
+
+ cg, ag = 10 ** (rng.uniform(-6, 0) / 20), 10 ** (rng.uniform(-3, 0) / 20)
+ place, events = [], []
+ t = int(rng.uniform(0.3, 1.0) * SR)
+ for k, (spk, parts, _) in enumerate(turns):
+ nxt = turns[k + 1] if k + 1 < len(turns) else None
+ if spk == "caller":
+ start = t
+ for pi, part in enumerate(parts):
+ place.append((CALLER, t, part * cg))
+ t += len(part)
+ if pi < len(parts) - 1: # mid-sentence pause: stays WAIT
+ pause = int(rng.uniform(0.5, 2.0) * SR)
+ events.append({"type": "pause", "start": t, "end": t + pause, "f0": -(-t // FRAME), "f1": (t + pause) // FRAME})
+ t += pause
+ events.append({"type": "caller_turn", "start": start, "end": t})
+ if nxt: # the agent answers: START until its audio begins
+ f0 = -(-t // FRAME)
+ f1 = f0 + int(rng.integers(2, 13)) # 160 ms to 960 ms
+ events.append({"type": "start", "caller_end": t, "f0": f0, "f1": f1})
+ t = f1 * FRAME
+ else:
+ seg = np.concatenate(parts) * ag
+ start = t
+ # the caller cuts in: where the dialogue says so, and at random elsewhere (barge_prob), so that
+ # true interruptions are not vastly outnumbered by backchannels
+ if nxt and len(seg) > 2.5 * SR and (nxt[2] or rng.random() < barge_prob):
+ react = int(rng.integers(3, 8)) # the agent stops 240 ms to 560 ms after noticing
+ onset = start + int(rng.uniform(0.35, 0.8) * (len(seg) - (react + 2) * FRAME))
+ f_cut = onset // FRAME + 1 + react
+ seg = seg[: f_cut * FRAME - start].copy()
+ seg[-320:] *= np.linspace(1.0, 0.0, 320, dtype=np.float32)
+ place.append((AGENT, start, seg))
+ events.append({"type": "interrupt", "onset": onset, "f0": onset // FRAME + 1, "f1": f_cut})
+ t = onset # the caller's next turn starts here, over the agent
+ else:
+ place.append((AGENT, start, seg))
+ taken = []
+ if bank and len(seg) > 4 * SR and rng.random() < 0.5:
+ for _ in range(int(rng.integers(1, 3))):
+ bc = bank[int(rng.integers(len(bank)))] * cg * rng.uniform(0.5, 1.0)
+ pos = start + int(rng.uniform(1.0 * SR, len(seg) - 1.0 * SR - len(bc)))
+ if any(pos < e and s < pos + len(bc) + SR for s, e in taken):
+ continue
+ taken.append((pos, pos + len(bc)))
+ place.append((CALLER, pos, bc))
+ events.append({"type": "backchannel", "start": pos, "end": pos + len(bc),
+ "f0": pos // FRAME + 1, "f1": -(-(pos + len(bc)) // FRAME)})
+ t = start + len(seg) + int(rng.uniform(0.2, 1.2) * SR)
+ return place, events, t + int(0.5 * SR)
+
+
+def fft_conv(x, h):
+ n = 1 << (len(x) + len(h) - 1).bit_length()
+ return np.fft.irfft(np.fft.rfft(x, n) * np.fft.rfft(h, n), n)[: len(x)].astype(np.float32)
+
+
+def room(rng):
+ """Synthetic room response: direct path plus exponentially decaying noise."""
+ rt60 = rng.uniform(0.15, 0.7)
+ n = int(rt60 * SR)
+ h = rng.standard_normal(n) * np.exp(-6.908 * np.arange(n) / SR / rt60)
+ h[: int(0.002 * SR)] = 0.0
+ h *= 10 ** (-rng.uniform(3, 15) / 20) / np.sqrt(np.sum(h ** 2) + 1e-9) # direct-to-reverberant ratio 3 to 15 dB
+ h[0] = 1.0
+ return h.astype(np.float32)
+
+
+def colored_noise(rng, n):
+ """Noise with a random spectral tilt between white and brown, unit RMS."""
+ spec = np.fft.rfft(rng.standard_normal(n))
+ f = np.fft.rfftfreq(n, 1.0 / SR)
+ f[0] = f[1]
+ x = np.fft.irfft(spec / f ** (rng.uniform(0.0, 2.0) / 2.0), n)
+ return (x / (np.sqrt(np.mean(x ** 2)) + 1e-9)).astype(np.float32)
+
+
+def degrade_caller(caller, agent, rng):
+ """What the model's microphone side would hear: room, echo of itself, line, noise."""
+ active = caller[np.abs(caller) > 1e-4]
+ speech_rms = float(np.sqrt(np.mean(active ** 2))) if len(active) else 0.05
+ n, fx = len(caller), []
+ if rng.random() < 0.6:
+ caller = fft_conv(caller, room(rng))
+ fx.append("room")
+ if rng.random() < 0.3: # the agent's voice leaking back, delayed and quiet
+ delay = int(rng.uniform(0.04, 0.2) * SR)
+ echo = fft_conv(np.concatenate([np.zeros(delay, np.float32), agent[: n - delay]]), room(rng))
+ caller = caller + echo * 10 ** (-rng.uniform(18, 35) / 20)
+ fx.append("echo")
+ if rng.random() < 0.3: # narrow telephone band
+ spec = np.fft.rfft(caller)
+ f = np.fft.rfftfreq(n, 1.0 / SR)
+ spec[(f < 300) | (f > 3400)] = 0
+ caller = np.fft.irfft(spec, n).astype(np.float32)
+ fx.append("phone_band")
+ if rng.random() < 0.85:
+ noise = colored_noise(rng, n)
+ if rng.random() < 0.2:
+ tt = np.arange(n) / SR
+ f0 = float(rng.choice([50.0, 60.0]))
+ 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)
+ noise /= np.sqrt(np.mean(noise ** 2)) + 1e-9
+ snr = rng.uniform(5, 35)
+ caller = caller + noise * speech_rms * 10 ** (-snr / 20)
+ fx.append(f"noise_snr{snr:.0f}")
+ if rng.random() < 0.3: # short bangs: not speech, must not trigger anything
+ for _ in range(int(rng.integers(1, 4))):
+ m = int(rng.uniform(0.1, 0.4) * SR)
+ pos = int(rng.integers(0, max(1, n - m)))
+ caller[pos: pos + m] += colored_noise(rng, m) * np.hanning(m).astype(np.float32) * speech_rms * rng.uniform(0.5, 1.5)
+ fx.append("bursts")
+ return caller, fx
+
+
+def build(job):
+ d, tts_dir, out_dir, seed, barge_prob = job
+ try:
+ z = np.load(Path(tts_dir) / f"{d['id']}.npz")
+ clips = {k: z[k] for k in z.files}
+ except FileNotFoundError:
+ return None
+ bank_file = Path(tts_dir) / f"_bank_{d['caller_voice']}.npz"
+ bank = []
+ if bank_file.exists():
+ z = np.load(bank_file)
+ bank = [b for b in (trim(z[k]) for k in z.files) if len(b) > SR // 20]
+ rng = np.random.default_rng([seed, zlib.crc32(d["id"].encode())])
+ laid = lay_out(d, clips, bank, rng, barge_prob)
+ if laid is None:
+ return None
+ place, events, end = laid
+ n_frames = -(-end // FRAME)
+ audio = np.zeros((n_frames * FRAME, 2), dtype=np.float32)
+ for ch, start, x in place:
+ x = x[: len(audio) - start]
+ audio[start: start + len(x), ch] += x
+ audio[:, CALLER], fx = degrade_caller(audio[:, CALLER], audio[:, AGENT], rng)
+ peak = float(np.abs(audio).max())
+ if peak > 0.99:
+ audio *= 0.99 / peak
+
+ labels = np.zeros(n_frames, dtype=np.uint8)
+ for e in events:
+ code = {"start": START, "interrupt": STOP, "backchannel": BACKCHANNEL}.get(e["type"])
+ if code is not None:
+ labels[e["f0"]: e["f1"]] = code
+
+ out = Path(out_dir)
+ write_wav(out / "audio" / f"{d['id']}.wav", audio, SR)
+ np.save(out / "labels" / f"{d['id']}.npy", labels)
+ meta = {k: d[k] for k in ("id", "split", "domain", "task", "caller_voice", "agent_voice")}
+ 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],
+ self_corrections=sum(t.get("self_correction", False) for t in d["turns"]))
+ write_json(out / "meta" / f"{d['id']}.json", meta)
+ return {"id": d["id"], "split": d["split"], "n_frames": int(n_frames), "labels": np.bincount(labels, minlength=len(LABELS)).tolist(),
+ "events": dict(Counter(e["type"] for e in events)), "self_corrections": meta["self_corrections"]}
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--dialogues", required=True)
+ ap.add_argument("--tts", required=True)
+ ap.add_argument("--out", required=True)
+ ap.add_argument("--workers", type=int, default=16)
+ ap.add_argument("--seed", type=int, default=0)
+ 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")
+ args = ap.parse_args()
+
+ out = Path(args.out)
+ for sub in ("audio", "labels", "meta"):
+ (out / sub).mkdir(parents=True, exist_ok=True)
+ dialogues = read_jsonl(args.dialogues)
+ with Pool(args.workers) as pool:
+ 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]
+
+ stats = {"dialogues_in": len(dialogues), "dialogues_built": len(rows), "frame_ms": 80, "labels": LABELS}
+ for split in ("train", "test"):
+ part = sorted((r for r in rows if r["split"] == split), key=lambda r: r["id"])
+ write_json(out / f"index_{split}.json", [{"id": r["id"], "n_frames": r["n_frames"]} for r in part])
+ counts = np.sum([r["labels"] for r in part], axis=0) if part else np.zeros(len(LABELS))
+ events = Counter()
+ for r in part:
+ events.update(r["events"])
+ stats[split] = {
+ "dialogues": len(part), "hours": round(sum(r["n_frames"] for r in part) * 0.08 / 3600, 3),
+ "label_frames": dict(zip(LABELS, (int(c) for c in counts))), "events": dict(events),
+ "self_corrections": sum(r["self_corrections"] for r in part),
+ }
+ write_json(out / "stats.json", stats)
+ print(json.dumps(stats, indent=2))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/data/dataset.py b/data/dataset.py
new file mode 100644
index 0000000000000000000000000000000000000000..9cf13443fe1ece19384fdead7d701e39640d8011
--- /dev/null
+++ b/data/dataset.py
@@ -0,0 +1,34 @@
+"""Random fixed-length crops of the built dialogues: stereo audio (caller, agent) and
+one label per 80 ms frame. Used by both trainers."""
+import json
+from pathlib import Path
+
+import numpy as np
+import torch
+from torch.utils.data import IterableDataset, get_worker_info
+
+from duplex.spec import FRAME, read_wav
+
+
+class Crops(IterableDataset):
+ def __init__(self, root, split, crop_frames, seed=0, limit=None):
+ self.root, self.crop, self.seed, self.limit = Path(root), crop_frames, seed, limit
+ self.items = json.loads((self.root / f"index_{split}.json").read_text())
+ assert self.items, f"no dialogues in split {split}"
+
+ def __iter__(self):
+ info = get_worker_info()
+ rng = np.random.default_rng([self.seed, info.id if info else 0])
+ length = np.array([it["n_frames"] for it in self.items], dtype=np.float64)
+ p = length / length.sum()
+ count = 0
+ while self.limit is None or count < self.limit:
+ it = self.items[int(rng.choice(len(self.items), p=p))]
+ start = int(rng.integers(0, max(1, it["n_frames"] - self.crop + 1)))
+ wav, _ = read_wav(self.root / "audio" / f"{it['id']}.wav", start * FRAME, self.crop * FRAME)
+ labels = np.load(self.root / "labels" / f"{it['id']}.npy")[start:start + self.crop].astype(np.int64)
+ if wav.shape[0] < self.crop * FRAME: # dialogue shorter than the crop: pad, and ignore padded frames
+ wav = np.pad(wav, ((0, self.crop * FRAME - wav.shape[0]), (0, 0)))
+ labels = np.pad(labels, (0, self.crop - len(labels)), constant_values=-100)
+ yield torch.from_numpy(np.ascontiguousarray(wav.T)), torch.from_numpy(labels)
+ count += 1
diff --git a/data/gen_dialogues.py b/data/gen_dialogues.py
new file mode 100644
index 0000000000000000000000000000000000000000..57020676cff0ce483ad6ba9c094895ce321e2819
--- /dev/null
+++ b/data/gen_dialogues.py
@@ -0,0 +1,155 @@
+"""Write two-speaker phone dialogues as text with an open LLM behind any
+OpenAI-compatible endpoint (the runbook serves an Apache-2.0 model with vLLM on GPU 1).
+
+Each line of the output is one dialogue with its cast (voices, speeds, split) and turns.
+Markers the later steps rely on:
+ [pause] inside a caller turn: the caller stops mid-sentence, then goes on
+ "interrupts": true on a caller turn: spoken over the agent's previous turn
+ "self_correction" on a caller turn: kept for the statistics
+
+ python -m data.gen_dialogues --base-url http://localhost:8001/v1 --model Qwen/Qwen3-32B \
+ --num-dialogues 3000 --out data/out/dialogues.jsonl
+"""
+import argparse
+import asyncio
+import json
+import random
+import re
+from pathlib import Path
+
+import aiohttp
+
+from data.scenarios import STYLES, TEST_VOICES, TRAIN_VOICES, split_scenarios
+
+PROMPT = """Write one phone conversation between a CALLER and an AGENT (a helpful voice assistant).
+
+Scenario: {domain}: the caller wants to {task}.
+Caller style: {style}.
+Length: {n_turns} turns. The {first} speaks first. Speakers strictly alternate.
+
+Rules:
+- Natural spoken English, the way people really talk on the phone. Mix short and long turns.
+- No stage directions, no emojis, no markdown. No names of real people or real companies.
+- Spell out every number and symbol in words ("twenty five dollars", never "$25").
+- 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.
+- In {k_corr} caller turns, the caller corrects themselves mid-sentence ("on Tuesday, no, sorry, Wednesday"). Set "self_correction": true on those turns.
+- 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.
+- Agent turns that explain something run twenty to sixty words.
+
+Return only JSON:
+{{"turns": [{{"spk": "caller", "text": "...", "interrupts": false, "self_correction": false}}, {{"spk": "agent", "text": "..."}}]}}"""
+
+
+def make_cast(i, n_total, seed):
+ """Everything about dialogue i that is decided before the LLM writes it."""
+ rng = random.Random(f"{seed}-{i}")
+ train_s, test_s = split_scenarios(seed)
+ split = "test" if i < round(n_total * 0.1) else "train"
+ domain, task = rng.choice(test_s if split == "test" else train_s)
+ caller, agent = rng.sample(TEST_VOICES if split == "test" else TRAIN_VOICES, 2)
+ return {
+ "id": f"{split}_{i:06d}", "split": split, "domain": domain, "task": task, "style": rng.choice(STYLES),
+ "caller_voice": caller, "agent_voice": agent,
+ "caller_speed": round(rng.uniform(0.9, 1.15), 2), "agent_speed": round(rng.uniform(0.95, 1.1), 2),
+ "n_turns": rng.randint(8, 18), "first": rng.choice(["AGENT", "AGENT", "CALLER"]),
+ "k_pause": rng.randint(1, 3), "k_corr": rng.randint(0, 1), "k_int": rng.randint(0, 2),
+ }
+
+
+def clean(raw):
+ """Parse and validate the model's JSON. Returns the turn list, or None to retry."""
+ raw = re.sub(r".*?", "", raw, flags=re.S)
+ m = re.search(r"\{.*\}", raw, flags=re.S)
+ if not m:
+ return None
+ try:
+ turns = json.loads(m.group(0))["turns"]
+ except (ValueError, KeyError, TypeError):
+ return None
+ out = []
+ for t in turns if isinstance(turns, list) else []:
+ if not isinstance(t, dict) or t.get("spk") not in ("caller", "agent") or not isinstance(t.get("text"), str):
+ return None
+ text = re.sub(r"\((.*?)\)|\[(?!pause\])[^\]]*\]|[*_#`]", " ", t["text"])
+ text = re.sub(r"\s+", " ", text).strip()
+ if not text or re.search(r"\d", text) or len(text) > 900:
+ return None
+ if out and out[-1]["spk"] == t["spk"]:
+ return None # speakers must alternate
+ if t["spk"] == "agent":
+ text = text.replace("[pause]", " ").strip()
+ else:
+ parts = [p.strip() for p in text.split("[pause]")]
+ if any(len(p.split()) < 2 for p in parts): # a fragment too short to voice: drop the markers
+ text = " ".join(p for p in parts if p)
+ out.append({
+ "spk": t["spk"], "text": text,
+ "interrupts": bool(t.get("interrupts")) and t["spk"] == "caller" and bool(out),
+ "self_correction": bool(t.get("self_correction")) and t["spk"] == "caller",
+ })
+ return out if len(out) >= 6 else None
+
+
+async def one(session, args, cast, sem, extra):
+ body = {
+ "model": args.model, "temperature": 0.9, "max_tokens": 3000, "response_format": {"type": "json_object"},
+ "messages": [
+ {"role": "system", "content": "You write realistic two-speaker phone conversations and return strict JSON."},
+ {"role": "user", "content": PROMPT.format(**cast)},
+ ], **extra,
+ }
+ async with sem:
+ for _ in range(4):
+ try:
+ async with session.post(args.base_url.rstrip("/") + "/chat/completions", json=body) as r:
+ r.raise_for_status()
+ raw = (await r.json())["choices"][0]["message"]["content"] or ""
+ except (aiohttp.ClientError, asyncio.TimeoutError, KeyError, ValueError) as e:
+ print(f"{cast['id']}: request failed: {e!r}")
+ continue
+ turns = clean(raw)
+ if turns:
+ return {**cast, "turns": turns}
+ return None
+
+
+async def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--base-url", required=True)
+ ap.add_argument("--model", required=True)
+ ap.add_argument("--out", required=True)
+ ap.add_argument("--num-dialogues", type=int, default=3000, help="set from the measured mean dialogue length to land on 50 to 100 hours")
+ ap.add_argument("--concurrency", type=int, default=64)
+ ap.add_argument("--seed", type=int, default=0)
+ ap.add_argument("--shard", type=int, default=0, help="write only dialogues with index % num-shards == shard (one process per LLM replica)")
+ ap.add_argument("--num-shards", type=int, default=1)
+ ap.add_argument("--api-key", default="none")
+ ap.add_argument("--extra-body", default='{"chat_template_kwargs": {"enable_thinking": false}}')
+ args = ap.parse_args()
+
+ out = Path(args.out)
+ out.parent.mkdir(parents=True, exist_ok=True)
+ done = {json.loads(line)["id"] for line in out.open(encoding="utf-8")} if out.exists() else set()
+ 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)
+ if c["id"] not in done]
+ print(f"{len(done)} already written, {len(casts)} to write")
+
+ sem, ok, failed = asyncio.Semaphore(args.concurrency), 0, 0
+ timeout = aiohttp.ClientTimeout(total=600)
+ async with aiohttp.ClientSession(timeout=timeout, headers={"Authorization": f"Bearer {args.api_key}"}) as session:
+ with out.open("a", encoding="utf-8") as f:
+ for fut in asyncio.as_completed([one(session, args, c, sem, json.loads(args.extra_body)) for c in casts]):
+ d = await fut
+ if d:
+ f.write(json.dumps(d, ensure_ascii=False) + "\n")
+ f.flush()
+ ok += 1
+ else:
+ failed += 1
+ if (ok + failed) % 100 == 0:
+ print(f"written {ok}, failed {failed}")
+ print(f"done: written {ok}, failed after retries {failed}")
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/data/scenarios.py b/data/scenarios.py
new file mode 100644
index 0000000000000000000000000000000000000000..f160fb3008ede189bcbf5a3682be2e6787fda1ec
--- /dev/null
+++ b/data/scenarios.py
@@ -0,0 +1,55 @@
+"""What the dialogues are about, who voices them, and the held-out split.
+
+The test set is held out by voice AND by scenario: a test dialogue uses only test
+scenarios and only test voices; a train dialogue uses neither.
+"""
+import random
+
+DOMAINS = {
+ "bank": ["dispute a card charge", "raise a transfer limit", "report a lost card", "ask about a loan payoff", "set up a travel notice"],
+ "airline": ["rebook a cancelled flight", "add a checked bag", "ask about a refund", "change a seat", "track delayed luggage"],
+ "hotel": ["extend a stay", "request a late checkout", "fix a billing error", "book an airport shuttle", "ask about parking"],
+ "pharmacy": ["refill a prescription", "ask when an order is ready", "transfer a prescription", "ask about pickup hours", "update insurance details"],
+ "internet provider": ["report an outage", "upgrade a plan", "schedule a technician", "question a bill", "return a router"],
+ "it helpdesk": ["reset a password", "set up a laptop", "fix a printer", "request software access", "report a phishing email"],
+ "restaurant": ["book a table", "change a reservation", "ask about allergens", "order catering", "ask about a private room"],
+ "doctor's office": ["book an appointment", "reschedule a visit", "ask for test results timing", "request a referral", "update contact details"],
+ "car service": ["book an oil change", "ask about a repair quote", "arrange a loaner car", "check on a repair", "ask about a recall"],
+ "online store": ["return an item", "track a package", "change a delivery address", "use a gift card", "report a damaged item"],
+ "insurance": ["start a claim", "add a driver", "ask what a policy covers", "update an address", "ask why a premium went up"],
+ "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"],
+ "gym": ["freeze a membership", "book a class", "cancel a membership", "ask about personal training", "update a payment card"],
+ "university office": ["ask about enrolment dates", "request a transcript", "ask about a tuition payment", "change a course", "book an advising slot"],
+ "travel agency": ["plan a weekend trip", "change a tour date", "ask about travel insurance", "add a rental car", "ask about visa paperwork"],
+ "mobile carrier": ["add a line", "ask about roaming", "replace a broken phone", "dispute a data charge", "port a number"],
+ "property manager": ["report a leak", "ask about a lease renewal", "request a parking permit", "book the shared room", "report a noisy neighbour"],
+ "delivery service": ["reschedule a delivery", "report a missing parcel", "arrange a pickup", "ask about customs fees", "change delivery instructions"],
+ "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"],
+ "tutor": ["explain compound interest", "practice a job interview", "walk through a logic puzzle", "explain how tides work", "review a short essay plan"],
+ "event venue": ["book a hall", "ask about catering options", "change a guest count", "ask about sound equipment", "arrange accessibility access"],
+ "tax helpline": ["ask about a filing deadline", "ask about a deduction", "correct a filed form", "set up instalments", "ask about a refund status"],
+ "vet clinic": ["book a vaccination", "ask about a sick pet", "refill pet medication", "ask about boarding", "arrange a follow-up"],
+ "library": ["renew a loan", "reserve a study room", "ask about a late fee", "find a book", "sign up for a workshop"],
+}
+
+STYLES = ["calm and brief", "chatty and friendly", "hurried and a little impatient", "unsure and hesitant",
+ "precise and detail-minded", "tired and distracted", "cheerful", "frustrated but polite"]
+
+# Kokoro-82M English voice packs (am_santa is left out: it is a character voice).
+VOICES = [
+ "af_alloy", "af_aoede", "af_bella", "af_heart", "af_jessica", "af_kore", "af_nicole", "af_nova", "af_river", "af_sarah", "af_sky",
+ "am_adam", "am_echo", "am_eric", "am_fenrir", "am_liam", "am_michael", "am_onyx", "am_puck",
+ "bf_alice", "bf_emma", "bf_isabella", "bf_lily",
+ "bm_daniel", "bm_fable", "bm_george", "bm_lewis",
+]
+TEST_VOICES = ["af_river", "am_liam", "bf_lily", "bm_lewis"] # one per group, never used in training
+TRAIN_VOICES = [v for v in VOICES if v not in TEST_VOICES]
+
+BACKCHANNELS = ["mm-hm", "uh-huh", "yeah", "right", "okay", "I see", "mhm", "sure", "got it", "oh, okay"]
+
+
+def split_scenarios(seed=0, test_fraction=0.1):
+ all_s = [(d, t) for d, tasks in DOMAINS.items() for t in tasks]
+ random.Random(seed).shuffle(all_s)
+ n_test = max(1, round(len(all_s) * test_fraction))
+ return all_s[n_test:], all_s[:n_test] # train, test
diff --git a/data/synth_tts.py b/data/synth_tts.py
new file mode 100644
index 0000000000000000000000000000000000000000..d86e97ae2ce9771a833eeb287854ebb693388214
--- /dev/null
+++ b/data/synth_tts.py
@@ -0,0 +1,90 @@
+"""Voice every dialogue turn with Kokoro-82M (Apache-2.0) preset voice packs.
+
+No voice is cloned: only the voice packs shipped with the model are used. Each turn is
+voiced as one clip, or as several when the caller pauses mid-sentence ([pause]).
+Output: one .npz per dialogue (16 kHz int16 clips named t_s), plus one
+bank of backchannels ("mm-hm" ...) per voice.
+
+Run one process per shard, several per GPU:
+ CUDA_VISIBLE_DEVICES=1 python -m data.synth_tts --dialogues data/out/dialogues.jsonl \
+ --out data/out/tts --shard 0 --num-shards 12
+"""
+import argparse
+import os
+from pathlib import Path
+
+import numpy as np
+import torch
+import torchaudio
+
+from data.scenarios import BACKCHANNELS, VOICES
+from duplex.spec import SR, read_jsonl
+
+KOKORO_SR = 24000
+
+
+class Voicer:
+ def __init__(self, device):
+ from kokoro import KPipeline
+ # 'a' = American English, 'b' = British English: the language code must match the voice prefix
+ self.pipes = {code: KPipeline(lang_code=code, repo_id="hexgrad/Kokoro-82M", device=device) for code in "ab"}
+
+ def say(self, text, voice, speed):
+ chunks = []
+ for _, _, audio in self.pipes[voice[0]](text, voice=voice, speed=speed):
+ if audio is not None:
+ chunks.append(torch.as_tensor(audio).float().flatten().cpu())
+ if not chunks:
+ return np.zeros(0, dtype=np.int16)
+ wav = torchaudio.functional.resample(torch.cat(chunks), KOKORO_SR, SR)
+ return (wav.clamp(-1, 1) * 32767).numpy().astype(np.int16)
+
+
+def save(path, clips):
+ tmp = path.with_suffix(".tmp.npz")
+ np.savez(tmp, **clips)
+ os.replace(tmp, path)
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--dialogues", required=True)
+ ap.add_argument("--out", required=True)
+ ap.add_argument("--shard", type=int, default=0)
+ ap.add_argument("--num-shards", type=int, default=1)
+ ap.add_argument("--limit", type=int, default=None, help="voice only the first N dialogues of this shard (smoke test)")
+ ap.add_argument("--pause-suffix", default=",", help="appended to the words before a [pause] so they do not sound finished")
+ args = ap.parse_args()
+
+ out = Path(args.out)
+ out.mkdir(parents=True, exist_ok=True)
+ voicer = Voicer("cuda" if torch.cuda.is_available() else "cpu")
+
+ for i, voice in enumerate(VOICES):
+ path = out / f"_bank_{voice}.npz"
+ if i % args.num_shards == args.shard and not path.exists():
+ save(path, {f"b{k}": voicer.say(text, voice, 1.0) for k, text in enumerate(BACKCHANNELS)})
+
+ todo = [d for i, d in enumerate(read_jsonl(args.dialogues)) if i % args.num_shards == args.shard][: args.limit]
+ seconds = 0.0
+ for n, d in enumerate(todo):
+ path = out / f"{d['id']}.npz"
+ if path.exists():
+ continue
+ clips = {}
+ for ti, turn in enumerate(d["turns"]):
+ voice, speed = (d["caller_voice"], d["caller_speed"]) if turn["spk"] == "caller" else (d["agent_voice"], d["agent_speed"])
+ parts = [p.strip() for p in turn["text"].split("[pause]") if p.strip()]
+ for si, text in enumerate(parts):
+ if si < len(parts) - 1 and text[-1].isalnum():
+ text += args.pause_suffix
+ clips[f"t{ti}_s{si}"] = voicer.say(text, voice, speed)
+ seconds += len(clips[f"t{ti}_s{si}"]) / SR
+ save(path, clips)
+ if n % 50 == 0:
+ print(f"shard {args.shard}: {n + 1}/{len(todo)} dialogues, {seconds / 3600:.2f} h of speech", flush=True)
+ print(f"shard {args.shard} done: {seconds / 3600:.3f} h of speech voiced in this run")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/duplex/__init__.py b/duplex/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/duplex/spec.py b/duplex/spec.py
new file mode 100644
index 0000000000000000000000000000000000000000..413b5187ba3c016458760fb320c527eb60d134ec
--- /dev/null
+++ b/duplex/spec.py
@@ -0,0 +1,67 @@
+"""Shared constants and tiny I/O helpers. Every other module imports these, so the
+frame grid, label ids and file layout are defined exactly once."""
+import json
+import wave
+from pathlib import Path
+
+import numpy as np
+
+SR = 16000 # input sample rate (caller audio, and self audio as the controller sees it)
+FRAME_MS = 80
+FRAME = SR * FRAME_MS // 1000 # 1280 samples per 80 ms frame
+HOP = 160 # 10 ms mel hop (same as the baseline encoder's front end)
+N_FFT = 400
+N_MELS = 128
+PATCH = 4 # mel frames per encoder token: 40 ms, 25 Hz (the baseline encoder's output rate)
+TOK_PER_FRAME = FRAME // (HOP * PATCH) # 2 encoder tokens per 80 ms frame
+TEACHER_DIM = 1280 # baseline AudioEncoder n_audio_state (config.json of Step-Audio-R1.1)
+
+OUT_SR = 24000 # reply audio sample rate (Step-Audio 2 token2wav and Kokoro both emit 24 kHz)
+OUT_FRAME = OUT_SR * FRAME_MS // 1000 # 1920 samples
+
+LABELS = ["WAIT", "START", "STOP", "BACKCHANNEL"]
+WAIT, START, STOP, BACKCHANNEL = range(4)
+
+CALLER, AGENT = 0, 1 # channel order in every dataset wav
+
+
+def read_wav(path, start=0, frames=None):
+ """PCM16 wav -> float32 [T, C] in [-1, 1], sample rate. Reads only the requested slice."""
+ with wave.open(str(path), "rb") as w:
+ assert w.getsampwidth() == 2, f"{path}: expected 16-bit PCM"
+ n = w.getnframes()
+ start = min(start, n)
+ frames = n - start if frames is None else min(frames, n - start)
+ w.setpos(start)
+ x = np.frombuffer(w.readframes(frames), dtype=" PCM16 wav."""
+ x = np.asarray(x, dtype=np.float32)
+ if x.ndim == 1:
+ x = x[:, None]
+ pcm = (np.clip(x, -1.0, 1.0) * 32767.0).astype("= 0) & (dist < window) & (j[None, :] >= keep - min(seen, keep))
+ a = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)
+ x = x + self.out(a.transpose(1, 2).flatten(2))
+ return x + self.mlp(self.ln2(x)), (k[:, :, t:], v[:, :, t:])
+
+
+class CausalTransformer(nn.Module):
+ def __init__(self, dim, layers, heads, window):
+ super().__init__()
+ self.dim, self.heads, self.window = dim, heads, window
+ self.blocks = nn.ModuleList([Block(dim, heads) for _ in range(layers)])
+
+ def forward(self, x):
+ T = x.shape[1]
+ idx = torch.arange(T, device=x.device)
+ cos, sin = _rope(idx, self.dim // self.heads, x.device)
+ dist = idx[:, None] - idx[None, :]
+ mask = (dist >= 0) & (dist < self.window)
+ for b in self.blocks:
+ x = b(x, cos, sin, mask)
+ return x
+
+ def init_state(self):
+ return {"pos": 0, "cache": [None] * len(self.blocks)}
+
+ def step(self, x, state):
+ t = x.shape[1]
+ pos = torch.arange(state["pos"], state["pos"] + t, device=x.device)
+ cos, sin = _rope(pos, self.dim // self.heads, x.device)
+ cache = []
+ for b, c in zip(self.blocks, state["cache"]):
+ x, c = b.step(x, cos, sin, c, self.window, state["pos"])
+ cache.append(c)
+ return x, {"pos": state["pos"] + t, "cache": cache}
+
+
+def count_params(m):
+ return sum(p.numel() for p in m.parameters())
+
+
+def cosine_by_time(frac, warmup=0.02, floor=0.05):
+ """LR multiplier as a function of elapsed wall-clock fraction (runs are time-budgeted)."""
+ if frac < warmup:
+ return frac / warmup
+ return floor + (1 - floor) * 0.5 * (1 + math.cos(math.pi * min(1.0, (frac - warmup) / (1 - warmup))))
+
+
+def read_checkpoint(path):
+ """(cfg, state dict) of a model of this repository, from a training checkpoint (.pt) or from the
+ published form: .safetensors with .json (the cfg) beside it."""
+ import json
+ from pathlib import Path
+ path = Path(path)
+ if path.suffix == ".safetensors":
+ from safetensors.torch import load_file
+ return json.loads(path.with_suffix(".json").read_text(encoding="utf-8"))["cfg"], load_file(str(path))
+ ck = torch.load(path, map_location="cpu", weights_only=True)
+ return ck["cfg"], ck["model"]
diff --git a/duplex/train_utils.py b/duplex/train_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..b1194c0c6d31dae828d19e58a02f957a8cc60595
--- /dev/null
+++ b/duplex/train_utils.py
@@ -0,0 +1,76 @@
+"""Small helpers shared by the two trainers: DDP setup, a wall-clock budget that all
+ranks agree on, hourly checkpoints, a JSONL log, label metrics."""
+import json
+import os
+import time
+
+import numpy as np
+import torch
+import torch.distributed as dist
+
+from duplex.spec import LABELS
+
+
+def setup_ddp():
+ world = int(os.environ.get("WORLD_SIZE", "1"))
+ rank = int(os.environ.get("RANK", "0"))
+ local = int(os.environ.get("LOCAL_RANK", "0"))
+ if world > 1:
+ torch.cuda.set_device(local)
+ dist.init_process_group("nccl")
+ device = torch.device("cuda", local) if torch.cuda.is_available() else torch.device("cpu")
+ torch.backends.cuda.matmul.allow_tf32 = True
+ torch.backends.cudnn.allow_tf32 = True
+ return rank, world, device
+
+
+class Budget:
+ """Rank 0's clock is the only clock: every rank reads the same elapsed time, so they
+ use the same learning rate and stop on the same step."""
+
+ def __init__(self, max_hours, rank, world, device, ckpt_minutes=60.0):
+ self.t0, self.max_s = time.time(), max_hours * 3600.0
+ self.rank, self.world, self.device = rank, world, device
+ self.elapsed, self.every_s, self.next_ckpt = 0.0, ckpt_minutes * 60.0, 1
+
+ def sync(self):
+ t = torch.tensor([time.time() - self.t0 if self.rank == 0 else 0.0], device=self.device, dtype=torch.float64)
+ if self.world > 1:
+ dist.all_reduce(t)
+ self.elapsed = float(t.item())
+ return self.elapsed / self.max_s
+
+ def checkpoint_due(self):
+ """Returns the checkpoint number once, right after each full interval."""
+ if self.elapsed >= self.next_ckpt * self.every_s:
+ self.next_ckpt += 1
+ return self.next_ckpt - 1
+ return None
+
+
+def log_row(path, **row):
+ row = {k: (round(v, 6) if isinstance(v, float) else v) for k, v in row.items()}
+ print(json.dumps(row), flush=True)
+ if path:
+ with open(path, "a", encoding="utf-8") as f:
+ f.write(json.dumps(row) + "\n")
+
+
+def confusion(pred, gold, n=len(LABELS)):
+ """Rows are the true label, columns the predicted one. Frames with gold < 0 are skipped."""
+ pred, gold = np.asarray(pred).reshape(-1), np.asarray(gold).reshape(-1)
+ keep = gold >= 0
+ return np.bincount(gold[keep] * n + pred[keep], minlength=n * n).reshape(n, n)
+
+
+def precision_recall(conf):
+ out = {}
+ for i, name in enumerate(LABELS):
+ tp, pred_n, gold_n = int(conf[i, i]), int(conf[:, i].sum()), int(conf[i, :].sum())
+ out[name] = {
+ "precision": tp / pred_n if pred_n else None,
+ "recall": tp / gold_n if gold_n else None,
+ "frames": gold_n,
+ "predicted": pred_n,
+ }
+ return out
diff --git a/eval/__init__.py b/eval/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/eval/eval_bba.py b/eval/eval_bba.py
new file mode 100644
index 0000000000000000000000000000000000000000..acc69bdc07f2fc4001156226cab7873afab193c2
--- /dev/null
+++ b/eval/eval_bba.py
@@ -0,0 +1,126 @@
+"""100 Big Bench Audio questions through the endpoint, with and without the controller.
+
+ without endpointing "manual": the question is committed the instant its audio ends,
+ so nothing but the model decides the answer.
+ with endpointing "controller": the controller alone decides when to answer. If it
+ starts early, the model answers a cut-off question and that shows up here.
+
+Scoring is ours, not Artificial Analysis's judge model: the reply text after the last
+"" is searched for the last valid/invalid, yes/no or number, and compared with
+the official answer. Scores are comparable between the two modes of this run, not with
+the public leaderboard. Raw replies (text and audio) are saved so they can be re-scored.
+
+ python -m eval.eval_bba --data eval/data/bba --out eval/results/bba --modes manual,controller
+"""
+import argparse
+import asyncio
+import json
+import re
+from collections import defaultdict
+from pathlib import Path
+
+import aiohttp
+import numpy as np
+
+from duplex.spec import OUT_SR, write_json, write_wav
+from eval.ws_client import load_16k, open_session, percentiles, run_turn
+
+SYSTEM = ('Listen to the question and answer it. Reply with only "valid" or "invalid", "yes" or "no", '
+ "or a number. Do not add anything else.")
+
+# Third run: Whisper recognised only 71 of 94 one-word spoken answers (the model gives a lone word very little
+# audio, down to 0.16 s). "sentence" asks for the answer inside one short sentence instead.
+SYSTEMS = {"word": SYSTEM,
+ "sentence": ('Listen to the question and answer it in one short spoken sentence that states the answer: "valid" or "invalid", '
+ '"yes" or "no", or the number. Do not add anything else.')}
+
+UNITS = "zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen".split()
+TENS = "twenty thirty forty fifty sixty seventy eighty ninety".split()
+# digits, "twenty", "twenty one" / "twenty-one", or a single word from zero to nineteen
+NUMBER = rf"\d+|(?:{'|'.join(TENS)})(?:[\s-](?:{'|'.join(UNITS[1:10])}))?|(?:{'|'.join(UNITS)})"
+
+
+def to_number(s):
+ words = re.split(r"[\s-]+", s.strip().lower())
+ if len(words) == 1 and words[0].isdigit():
+ return int(words[0])
+ if len(words) == 1 and words[0] in UNITS:
+ return UNITS.index(words[0])
+ if words[0] in TENS and (len(words) == 1 or (len(words) == 2 and words[1] in UNITS[1:10])):
+ return 10 * (TENS.index(words[0]) + 2) + (UNITS.index(words[1]) if len(words) == 2 else 0)
+ return None
+
+
+def parse_answer(text, official):
+ """The last answer of the right kind in the spoken part of the reply, or None."""
+ say = re.sub(r"<[^>]+>", " ", text.split("")[-1]).lower()
+ official = official.strip().lower()
+ if official in ("valid", "invalid"):
+ found = re.findall(r"\b(invalid|valid)\b", say)
+ elif official in ("yes", "no"):
+ found = re.findall(r"\b(yes|no)\b", say)
+ else:
+ found = [str(n) for n in (to_number(m) for m in re.findall(rf"\b({NUMBER})\b", say)) if n is not None]
+ official = str(to_number(official)) if to_number(official) is not None else official
+ return (found[-1] if found else None), official
+
+
+async def ask(http, args, q, mode, sem, out):
+ async with sem:
+ pcm = load_16k(Path(args.data) / f"q_{q['id']}.wav")
+ ws = await open_session(http, args.url, SYSTEMS[args.system], mode)
+ try:
+ r = await run_turn(ws, pcm, commit=(mode == "manual"), until="done_after_audio", max_wait_s=args.max_wait_s)
+ finally:
+ await ws.close()
+ answer, official = parse_answer(r["text"], q["official_answer"])
+ row = {
+ "id": q["id"], "category": q["category"], "official_answer": official, "answer": answer,
+ "correct": answer is not None and answer == official, "replied": r["done"] is not None and r["done"]["reason"] == "done",
+ "started_early": r["started_early"], "replies_cut_off": sum(1 for d in r["replies"] if d["reason"] != "done"),
+ "latency_ms": r["latency_ms"], "question_s": len(pcm) / 16000, "text": r["text"], "error": r["error"],
+ "events": [e for e in r["events"] if e["type"] != "transcript.delta"],
+ }
+ write_json(out / f"q_{q['id']}.json", row)
+ if r["audio"]:
+ write_wav(out / f"q_{q['id']}.wav", np.frombuffer(r["audio"], dtype=" 1 else ''}.json", summary)
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/eval/eval_bba_budget.py b/eval/eval_bba_budget.py
new file mode 100644
index 0000000000000000000000000000000000000000..2271134859e5d9803354867cdaaf239d7738f786
--- /dev/null
+++ b/eval/eval_bba_budget.py
@@ -0,0 +1,100 @@
+"""How much thinking does the spoken answer need? One arm per thinking budget.
+
+For each of the 100 benchmark questions: the baseline reasons as text for at most
+`--budget` tokens (the reasoning is cut there if it has not closed itself), then the reply
+is opened for speech with that reasoning in it, exactly as the endpoint's think-then-speak
+does. Budget 0 is the plain speech path. The spoken words are scored by the same parser as
+every other arm. Audio tokens are generated but not decoded here (the speech decoder adds
+nothing to the answer), so "seconds to answer" is the time until the spoken answer's first
+audio tokens exist, with one question at a time on a baseline copy of its own.
+
+ python -m eval.eval_bba_budget --budget 128 --api-url http://127.0.0.1:9992/v1/chat/completions
+"""
+import argparse
+import asyncio
+import json
+import time
+from collections import defaultdict
+from pathlib import Path
+
+import aiohttp
+
+from duplex.spec import write_json
+from eval.eval_bba import SYSTEM, parse_answer
+from eval.ws_client import load_16k, percentiles
+from serving.baseline_client import human_turn, stream_chat
+
+NL = chr(10)
+THINK_OPEN, THINK_CLOSE, SPEAK = "" + NL, "", ""
+BRIEF = " Before you answer, think it through in a few short steps."
+
+
+async def ask(http, args, q, sem, out):
+ pcm = load_16k(Path(args.data) / f"q_{q['id']}.wav")
+ base = [{"role": "system", "content": SYSTEM + (BRIEF if args.brief else "")}, human_turn(pcm)]
+ row = {"id": q["id"], "category": q["category"], "think_tokens": 0, "closed_itself": None, "error": None}
+ async with sem:
+ t0 = time.perf_counter()
+ try:
+ thought = ""
+ if args.budget > 0:
+ n = 0
+ async for _, text, _ in stream_chat(http, args.api_url, args.model, base + [{"role": "assistant", "content": THINK_OPEN, "eot": False}],
+ max_tokens=args.budget, temperature=0.7, repetition_penalty=1.0, stop_token_ids=[151665],
+ stop=[THINK_CLOSE]):
+ thought += text
+ n += 1
+ row["think_tokens"], row["closed_itself"] = n, n < args.budget
+ if thought and not thought.endswith(NL):
+ thought += NL # cut mid-sentence by the budget: close the block on a new line
+ row["think_s"] = time.perf_counter() - t0
+ opener = (THINK_OPEN + thought + THINK_CLOSE + NL if args.budget > 0 else "") + SPEAK
+ spoken, first_audio = "", None
+ async for _, text, tokens in stream_chat(http, args.api_url, args.model, base + [{"role": "assistant", "content": opener, "eot": False}],
+ max_tokens=512, temperature=0.7, top_p=0.9, repetition_penalty=1.05, stop_token_ids=[151665]):
+ spoken += text
+ if tokens and first_audio is None:
+ first_audio = time.perf_counter() - t0
+ row["answer_s"], row["total_s"] = first_audio, time.perf_counter() - t0
+ except Exception as e:
+ row["error"], spoken, thought = repr(e), "", ""
+ answer, official = parse_answer(spoken, q["official_answer"])
+ row.update(official_answer=official, answer=answer, correct=answer is not None and answer == official, spoken=spoken, thought=thought)
+ write_json(out / f"q_{q['id']}.json", row)
+ return row
+
+
+async def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--api-url", required=True)
+ ap.add_argument("--model", default="Step-Audio-R1.1")
+ ap.add_argument("--data", default="eval/data/bba")
+ ap.add_argument("--out", default="eval/results/bba_budget")
+ ap.add_argument("--budget", type=int, required=True, help="most reasoning tokens before the speech; 0 = no reasoning")
+ ap.add_argument("--brief", action="store_true", help="also ask, in the system prompt, for a few short steps")
+ ap.add_argument("--concurrency", type=int, default=1)
+ args = ap.parse_args()
+
+ name = f"budget_{args.budget}" + ("_brief" if args.brief else "")
+ out = Path(args.out) / name
+ out.mkdir(parents=True, exist_ok=True)
+ subset = json.loads((Path(args.data) / "subset.json").read_text())
+ sem = asyncio.Semaphore(args.concurrency)
+ async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=None)) as http:
+ rows = await asyncio.gather(*[ask(http, args, q, sem, out) for q in subset])
+ by_cat = defaultdict(list)
+ for r in rows:
+ by_cat[r["category"]].append(r["correct"])
+ summary = {
+ "arm": name, "budget": args.budget, "brief": args.brief, "concurrency": args.concurrency, "questions": len(rows),
+ "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())},
+ "no_answer_found": sum(r["answer"] is None for r in rows), "errors": sum(bool(r["error"]) for r in rows),
+ "reasoning_closed_itself": sum(bool(r["closed_itself"]) for r in rows), "think_tokens": percentiles([r["think_tokens"] for r in rows]),
+ "seconds_to_spoken_answer": percentiles([r.get("answer_s") for r in rows]),
+ }
+ write_json(Path(args.out) / f"summary_{name}.json", summary)
+ print(json.dumps(summary))
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/eval/eval_bba_text.py b/eval/eval_bba_text.py
new file mode 100644
index 0000000000000000000000000000000000000000..23b0ed9f7003ea3d62c6c9965777e9072a807abb
--- /dev/null
+++ b/eval/eval_bba_text.py
@@ -0,0 +1,75 @@
+"""Reference arm for the benchmark: the same 100 questions sent straight to the baseline
+with the reply opened by "\\n" (the released reasoning examples), text out, no speech.
+
+It answers one question the endpoint arms cannot: how much of the reasoning score is lost
+when the model is asked to speak ("") instead of think. Same system prompt and
+same scorer as eval/eval_bba.py, so the three arms compare with each other only.
+
+ python -m eval.eval_bba_text --data eval/data/bba --out eval/results/bba
+"""
+import argparse
+import asyncio
+import json
+import time
+from collections import defaultdict
+from pathlib import Path
+
+import aiohttp
+
+from duplex.spec import write_json
+from eval.eval_bba import SYSTEM, parse_answer
+from eval.ws_client import load_16k, percentiles
+from serving.baseline_client import human_turn, stream_chat
+
+
+async def ask(http, args, q, sem, out):
+ pcm = load_16k(Path(args.data) / f"q_{q['id']}.wav")
+ messages = [{"role": "system", "content": SYSTEM}, human_turn(pcm), {"role": "assistant", "content": "\n", "eot": False}]
+ text, error = "", None
+ async with sem:
+ t0 = time.perf_counter()
+ try:
+ async for _, t, _ in stream_chat(http, args.api_url, args.model, messages, max_tokens=args.max_tokens, temperature=0.7,
+ repetition_penalty=1.0, stop_token_ids=[151665]):
+ text += t
+ except Exception as e:
+ error = repr(e)
+ seconds = time.perf_counter() - t0
+ answer, official = parse_answer(text, q["official_answer"]) if "" in text else (None, q["official_answer"].strip().lower())
+ row = {"id": q["id"], "category": q["category"], "official_answer": official, "answer": answer, "correct": answer is not None and answer == official,
+ "finished_thinking": "" in text, "seconds": seconds, "text": text, "error": error}
+ write_json(out / f"q_{q['id']}.json", row)
+ return row
+
+
+async def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--api-url", default="http://127.0.0.1:9999/v1/chat/completions")
+ ap.add_argument("--model", default="Step-Audio-R1.1")
+ ap.add_argument("--data", default="eval/data/bba")
+ ap.add_argument("--out", default="eval/results/bba")
+ ap.add_argument("--concurrency", type=int, default=8)
+ ap.add_argument("--max-tokens", type=int, default=8192)
+ args = ap.parse_args()
+
+ subset = json.loads((Path(args.data) / "subset.json").read_text())
+ out = Path(args.out) / "think_text"
+ out.mkdir(parents=True, exist_ok=True)
+ sem = asyncio.Semaphore(args.concurrency)
+ async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=None)) as http:
+ rows = await asyncio.gather(*[ask(http, args, q, sem, out) for q in subset])
+ by_cat = defaultdict(list)
+ for r in rows:
+ by_cat[r["category"]].append(r["correct"])
+ summary = {"questions": len(rows), "think_text": {
+ "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())},
+ "finished_thinking": sum(r["finished_thinking"] for r in rows), "no_answer_found": sum(r["answer"] is None for r in rows),
+ "errors": sum(bool(r["error"]) for r in rows), "seconds_to_full_answer": percentiles([r["seconds"] for r in rows]),
+ }}
+ write_json(Path(args.out) / "summary_think_text.json", summary)
+ print(json.dumps(summary))
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/eval/eval_controller.py b/eval/eval_controller.py
new file mode 100644
index 0000000000000000000000000000000000000000..e5abd560c9a2edd236eebf6f15b59cf0b100dec6
--- /dev/null
+++ b/eval/eval_controller.py
@@ -0,0 +1,94 @@
+"""The controller on the held-out set (unseen voices, unseen scenarios).
+
+Frame level: precision and recall per label.
+Event level, from the events the data builder recorded:
+ pause handling a mid-sentence pause is handled when no START is predicted in it
+ turn ends a turn end is caught when START is predicted inside its START window;
+ the delay is counted from the caller's last frame
+ interruptions caught when STOP is predicted inside the STOP window
+ backchannels survived when no STOP is predicted while the caller says "mm-hm"
+
+Whole dialogues are run offline with the banded causal mask, which is the same function
+as frame-by-frame serving (tests/test_streaming.py). Raw per-frame predictions are saved.
+
+ python -m eval.eval_controller --data data/out/dataset --encoder runs/encoder/final.pt \
+ --controller runs/controller/final.pt --out eval/results/controller
+"""
+import argparse
+import json
+from pathlib import Path
+
+import numpy as np
+import torch
+
+from controller.encoder.student import load_student
+from controller.model.model import load_controller
+from duplex.spec import FRAME, LABELS, START, STOP, read_wav, write_json
+from duplex.train_utils import confusion, precision_recall
+
+
+def rate(hits, total):
+ return {"correct": int(hits), "total": int(total), "accuracy": hits / total if total else None}
+
+
+@torch.inference_mode()
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--data", required=True)
+ ap.add_argument("--encoder", required=True)
+ ap.add_argument("--controller", required=True)
+ ap.add_argument("--out", default="eval/results/controller")
+ ap.add_argument("--device", default="cuda:1")
+ ap.add_argument("--limit", type=int, default=None, help="only the first N held-out dialogues (smoke test)")
+ args = ap.parse_args()
+
+ data, out, device = Path(args.data), Path(args.out), torch.device(args.device)
+ (out / "pred").mkdir(parents=True, exist_ok=True)
+ encoder, ctl = load_student(args.encoder, device), load_controller(args.controller, device)
+
+ conf = np.zeros((len(LABELS), len(LABELS)), dtype=np.int64)
+ pauses, turn_ends, stops, backchannels = (np.zeros(2, dtype=np.int64) for _ in range(4)) # [hits, total]
+ delays, pause_len_ok, pause_len_bad = [], [], []
+ items = json.loads((data / "index_test.json").read_text())[: args.limit]
+ for it in items:
+ wav, _ = read_wav(data / "audio" / f"{it['id']}.wav")
+ wav = torch.from_numpy(wav[: it["n_frames"] * FRAME].T.copy()).to(device) # [2, T]
+ with torch.autocast(device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):
+ feats = encoder(wav)
+ probs = torch.softmax(ctl(feats[0:1], feats[1:2])[0].float(), dim=-1).cpu().numpy()
+ pred = probs.argmax(-1)
+ gold = np.load(data / "labels" / f"{it['id']}.npy")
+ conf += confusion(pred, gold)
+ np.savez_compressed(out / "pred" / f"{it['id']}.npz", pred=pred.astype(np.uint8), probs=probs.astype(np.float16))
+
+ for e in json.loads((data / "meta" / f"{it['id']}.json").read_text())["events"]:
+ window = pred[e["f0"]: e["f1"]] if "f0" in e else None
+ if e["type"] == "pause" and len(window):
+ quiet = not (window == START).any()
+ pauses = pauses + [quiet, 1]
+ (pause_len_ok if quiet else pause_len_bad).append((e["end"] - e["start"]) / 16000)
+ elif e["type"] == "start":
+ hit = np.nonzero(window == START)[0]
+ turn_ends = turn_ends + [len(hit) > 0, 1]
+ if len(hit):
+ delays.append(float(hit[0] + 1) * 80.0) # ms from the caller's last frame to the first START
+ elif e["type"] == "interrupt" and len(window):
+ stops = stops + [(window == STOP).any(), 1]
+ elif e["type"] == "backchannel" and len(window):
+ backchannels = backchannels + [not (window == STOP).any(), 1]
+
+ result = {
+ "dialogues": len(items), "frames": int(conf.sum()), "per_label": precision_recall(conf), "confusion_rows_true_cols_pred": conf.tolist(),
+ "pause_handling": rate(*pauses),
+ "pause_seconds_mean": {"handled": float(np.mean(pause_len_ok)) if pause_len_ok else None,
+ "started_in_pause": float(np.mean(pause_len_bad)) if pause_len_bad else None},
+ "turn_end_caught": rate(*turn_ends),
+ "start_delay_ms": {"p50": float(np.percentile(delays, 50)), "p90": float(np.percentile(delays, 90))} if delays else None,
+ "interruption_caught": rate(*stops), "backchannel_not_interrupted": rate(*backchannels),
+ }
+ write_json(out / "controller.json", result)
+ print(json.dumps(result, indent=2))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/eval/eval_judge.py b/eval/eval_judge.py
new file mode 100644
index 0000000000000000000000000000000000000000..5aa6b3ec826a425468797779a66ca7613ff36b9e
--- /dev/null
+++ b/eval/eval_judge.py
@@ -0,0 +1,193 @@
+"""The baseline as end-of-turn judge (serving/judge.py), measured offline.
+
+Cases, all cut from the caller's channel (with its noise), each ending 240 ms into the silence:
+ finished a caller turn up to its end (the turns that were answered in the data)
+ pause the same kind of turn, cut at a mid-sentence pause
+ question Big Bench Audio questions (voices and style nothing here was tuned on):
+ cut at every inner silence of 400 ms or more (not finished), and at the end (finished)
+
+About half of the data's "pauses" follow a complete sentence ("Thanks for the email.
+[pause] I want to make sure ..."): nobody can know from the words that more is coming.
+So pauses are also reported in two groups by the words before them:
+ cut off the last word is a function word (and, but, to, the, my, I ...): clearly unfinished
+ other everything else, complete-sounding or not
+
+Several variants of the judge (prompt, optional short reasoning) are run on a sample of
+TRAIN-split cases and on all held-out cases. The variant to use is the one with the best
+balanced accuracy on the TRAIN sample; the held-out numbers of every variant are reported.
+
+ python -m eval.eval_judge --data data/out/dataset --dialogues data/out/dialogues.jsonl --bba eval/data/bba --out eval/results/judge
+"""
+import argparse
+import asyncio
+import json
+import random
+import re
+import time
+from pathlib import Path
+
+import aiohttp
+import numpy as np
+
+from duplex.spec import CALLER, FRAME, SR, read_jsonl, read_wav, write_json
+from eval.ws_client import load_16k, percentiles
+from serving.judge import judge_finished
+
+TAIL = int(0.24 * SR) # the judge is asked 240 ms into the silence
+LEAD = int(0.3 * SR)
+FUNCTION_WORDS = set("""and but or so because if that which who when while although though unless until
+to of in on at for with from by about into onto over under between through during before after
+the a an my your our their his her its this these those some any every each no
+i we you they he she it there
+is are was were am be been being have has had do does did can could will would should might may must
+not just than as""".split())
+
+
+def pause_prefixes(dialogue):
+ """The words before each pause of a dialogue, in the order the data builder created the pauses."""
+ out = []
+ for turn in dialogue["turns"]:
+ if turn["spk"] == "caller":
+ parts = [p.strip() for p in turn["text"].split("[pause]") if p.strip()]
+ out += [" ".join(parts[: i + 1]) for i in range(len(parts) - 1)]
+ return out
+
+
+def cut_off(prefix):
+ words = re.findall(r"[a-z']+", prefix.lower())
+ return bool(words) and words[-1] in FUNCTION_WORDS and prefix.rstrip()[-1] not in ".?!"
+
+
+def dialogue_cases(data, split, limit, seed, dialogues=None):
+ data, cases = Path(data), []
+ for it in json.loads((data / f"index_{split}.json").read_text()):
+ events = json.loads((data / "meta" / f"{it['id']}.json").read_text())["events"]
+ cuts = {e["onset"] for e in events if e["type"] == "interrupt"}
+ answered = {e["caller_end"] for e in events if e["type"] == "start"}
+ pauses = [e for e in events if e["type"] == "pause"]
+ prefixes = pause_prefixes(dialogues[it["id"]]) if dialogues else []
+ for e in events:
+ if e["type"] != "caller_turn" or e["start"] in cuts or not 1.0 * SR <= e["end"] - e["start"] <= 25 * SR:
+ continue
+ if e["end"] in answered:
+ cases.append({"kind": "finished", "id": it["id"], "start": e["start"], "cut": e["end"]})
+ for k, p in enumerate(pauses):
+ if e["start"] < p["start"] < e["end"] and p["end"] - p["start"] >= TAIL + FRAME:
+ c = {"kind": "pause", "id": it["id"], "start": e["start"], "cut": p["start"], "pause_index": k}
+ if len(prefixes) == len(pauses):
+ c["before"], c["cut_off"] = prefixes[k][-80:], cut_off(prefixes[k])
+ cases.append(c)
+ random.Random(seed).shuffle(cases)
+ return cases[:limit] if limit else cases
+
+
+def question_cases(bba_dir, db=-45.0, min_gap_s=0.4):
+ cases = []
+ for q in json.loads((Path(bba_dir) / "subset.json").read_text()):
+ pcm = load_16k(Path(bba_dir) / f"q_{q['id']}.wav")
+ n = len(pcm) // FRAME
+ rms = np.sqrt(np.mean((pcm[: n * FRAME].reshape(n, FRAME).astype(np.float32) / 32768) ** 2, axis=1))
+ voiced = 20 * np.log10(rms + 1e-9) > db
+ last = int(np.nonzero(voiced)[0][-1])
+ i = 0
+ while i < last:
+ if not voiced[i]:
+ j = i
+ while j < last and not voiced[j]:
+ j += 1
+ if (j - i) * 0.08 >= min_gap_s and voiced[:i].sum() >= 3:
+ cases.append({"kind": "question_inner", "id": q["id"], "cut": i * FRAME})
+ i = j
+ else:
+ i += 1
+ cases.append({"kind": "question_end", "id": q["id"], "cut": (last + 1) * FRAME})
+ return cases
+
+
+def audio_of(case, data, bba_dir):
+ if case["kind"].startswith("question"):
+ pcm = load_16k(Path(bba_dir) / f"q_{case['id']}.wav")[: case["cut"]]
+ return np.concatenate([pcm, np.zeros(TAIL, np.int16)]) # clean recordings: silence after the cut
+ a = max(0, case["start"] - LEAD)
+ x, _ = read_wav(Path(data) / "audio" / f"{case['id']}.wav", a, case["cut"] + TAIL - a)
+ return (x[:, CALLER] * 32767).astype(np.int16) # the real channel, noise included
+
+
+async def run(http, args, cases, sem, variant):
+ prompt, think = variant.split("+")
+
+ async def one(c):
+ pcm = audio_of(c, args.data, args.bba)
+ async with sem:
+ t0 = time.perf_counter()
+ try:
+ said = await judge_finished(http, args.api_url, args.model, pcm, prompt=prompt, think_tokens=int(think))
+ except Exception as e:
+ said, c["error"] = None, repr(e)
+ c.setdefault("said", {})[variant] = said
+ c.setdefault("ms", {})[variant] = (time.perf_counter() - t0) * 1000
+ c["audio_s"] = len(pcm) / SR
+ await asyncio.gather(*[one(c) for c in cases])
+
+
+def rate(cases, variant, want, keep=lambda c: True):
+ rows = [c for c in cases if keep(c) and c["said"][variant] is not None]
+ hits = sum(c["said"][variant] == want for c in rows)
+ return {"correct": hits, "total": len(rows), "rate": hits / len(rows) if rows else None}
+
+
+async def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--api-url", default="http://127.0.0.1:9991/v1/chat/completions")
+ ap.add_argument("--model", default="Step-Audio-R1.1")
+ ap.add_argument("--data", required=True)
+ ap.add_argument("--dialogues", required=True)
+ ap.add_argument("--bba", default="eval/data/bba")
+ ap.add_argument("--out", default="eval/results/judge")
+ ap.add_argument("--variants", default="v1+0,v2+0,v2+32", help="prompt+reasoning tokens, comma separated")
+ ap.add_argument("--train-cases", type=int, default=500)
+ ap.add_argument("--concurrency", type=int, default=12)
+ args = ap.parse_args()
+
+ dialogues = {d["id"]: d for d in read_jsonl(args.dialogues)}
+ train = dialogue_cases(args.data, "train", args.train_cases, 0, dialogues)
+ test = dialogue_cases(args.data, "test", None, 0, dialogues)
+ quest = question_cases(args.bba)
+ sem, variants = asyncio.Semaphore(args.concurrency), args.variants.split(",")
+ async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=300)) as http:
+ for v in variants:
+ for cases in (train, test, quest):
+ await run(http, args, cases, sem, v)
+
+ is_kind = lambda k: (lambda c: c["kind"] == k)
+ result = {"cases": {"train": len(train), "held_out": len(test), "question_cuts": len(quest)},
+ "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)},
+ "concurrency": args.concurrency, "variants": {}}
+ for v in variants:
+ tr_end, tr_pause = rate(train, v, True, is_kind("finished")), rate(train, v, False, is_kind("pause"))
+ result["variants"][v] = {
+ "train_balanced_accuracy": (tr_end["rate"] + tr_pause["rate"]) / 2,
+ "held_out": {
+ "turn_end_released": rate(test, v, True, is_kind("finished")),
+ "pause_held_all": rate(test, v, False, is_kind("pause")),
+ "pause_held_cut_off": rate(test, v, False, lambda c: c.get("cut_off") is True),
+ "pause_held_other": rate(test, v, False, lambda c: c.get("cut_off") is False),
+ },
+ "benchmark_questions": {
+ "inner_silence_held": rate(quest, v, False, is_kind("question_inner")),
+ "end_released": rate(quest, v, True, is_kind("question_end")),
+ "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")
+ for q in {c["id"] for c in quest}),
+ },
+ "no_answer_word": sum(c["said"][v] is None for c in train + test + quest),
+ "judge_ms_held_out": percentiles([c["ms"][v] for c in test]),
+ }
+ result["chosen_on_train"] = max(variants, key=lambda v: result["variants"][v]["train_balanced_accuracy"])
+ out = Path(args.out)
+ write_json(out / "cases.json", {"train": train, "test": test, "questions": quest})
+ write_json(out / "judge.json", result)
+ print(json.dumps(result, indent=1))
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/eval/eval_latency.py b/eval/eval_latency.py
new file mode 100644
index 0000000000000000000000000000000000000000..502ca055ec3c868adfd0b734e3608495dfed88bc
--- /dev/null
+++ b/eval/eval_latency.py
@@ -0,0 +1,96 @@
+"""Turn-taking latency: time from the caller finishing to the first reply audio.
+
+Held-out caller turns (test voices, test scenarios, with their noise) are cut out of
+the test dialogues and spoken to the endpoint one per fresh session, once with the
+controller deciding and once with the fixed-silence baseline ("vad"). Reported per mode:
+the latency of the reply that finally answers the turn, in how many turns the caller
+heard the model before they had finished (the audible false starts), how many replies
+were withdrawn before a single frame played (inaudible), and how often no reply came.
+
+Only turns that end a caller's say are used (the turn's whole audio, pauses included),
+so a mid-sentence pause that triggers a reply counts as "started early".
+
+ python -m eval.eval_latency --data data/out/dataset --out eval/results/latency --modes controller,vad
+"""
+import argparse
+import asyncio
+import json
+import random
+from pathlib import Path
+
+import aiohttp
+import numpy as np
+
+from duplex.spec import CALLER, SR, read_wav, write_json
+from eval.ws_client import open_session, percentiles, run_turn
+
+
+def held_out_turns(data, n, seed):
+ data = Path(data)
+ turns = []
+ for it in json.loads((data / "index_test.json").read_text()):
+ meta = json.loads((data / "meta" / f"{it['id']}.json").read_text())
+ cuts = [e["onset"] for e in meta["events"] if e["type"] == "interrupt"]
+ for e in meta["events"]:
+ # skip turns that begin as an interruption: their first words overlap the agent
+ if e["type"] == "caller_turn" and e["start"] not in cuts and 1.0 * SR <= e["end"] - e["start"] <= 25 * SR:
+ turns.append((it["id"], e["start"], e["end"]))
+ random.Random(seed).shuffle(turns)
+ return turns[:n]
+
+
+async def one(http, args, data, turn, mode, sem):
+ did, start, end = turn
+ lead = int(0.3 * SR)
+ x, _ = read_wav(Path(data) / "audio" / f"{did}.wav", max(0, start - lead), end - max(0, start - lead))
+ pcm = (x[:, CALLER] * 32767).astype(np.int16)
+ async with sem:
+ ws = await open_session(http, args.url, args.system, mode)
+ try:
+ r = await run_turn(ws, pcm, until="done_after_audio", max_wait_s=args.max_wait_s)
+ finally:
+ await ws.close()
+ lag = [e.get("lag_ms") for e in r["events"] if e["type"] == "reply.start"]
+ 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,
+ "started_early": r["started_early"], "replied": r["t_first_audio"] is not None, "error": r["error"],
+ "heard_early_ms": r["audio_ms_before_caller_end"], "replies_cut_off": sum(1 for d in r["replies"] if d["reason"] != "done"),
+ "withdrawn_unheard": sum(1 for e in r["events"] if e["type"] == "reply.withdrawn")}
+
+
+async def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--url", default="http://localhost:8765/ws")
+ ap.add_argument("--data", required=True)
+ ap.add_argument("--out", default="eval/results/latency")
+ ap.add_argument("--modes", default="controller,vad")
+ ap.add_argument("--turns", type=int, default=100)
+ ap.add_argument("--concurrency", type=int, default=4)
+ ap.add_argument("--max-wait-s", type=float, default=30.0)
+ ap.add_argument("--system", default="You are a helpful assistant on a phone call. Keep answers short.")
+ ap.add_argument("--seed", type=int, default=0)
+ args = ap.parse_args()
+
+ turns = held_out_turns(args.data, args.turns, args.seed)
+ summary = {"turns": len(turns)}
+ async with aiohttp.ClientSession() as http:
+ for mode in args.modes.split(","):
+ sem = asyncio.Semaphore(args.concurrency)
+ rows = await asyncio.gather(*[one(http, args, args.data, t, mode, sem) for t in turns])
+ write_json(Path(args.out) / f"{mode}.json", rows)
+ 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]
+ summary[mode] = {
+ # the caller never heard the model before finishing, and the reply came after: the clean turns
+ "latency_ms_clean_turns": percentiles([r["latency_ms"] for r in clean]),
+ "turns_where_caller_heard_the_model_early": sum(r["heard_early_ms"] > 0 for r in rows),
+ "replies_cut_off_after_being_heard": sum(r["replies_cut_off"] for r in rows),
+ "replies_withdrawn_unheard": sum(r["withdrawn_unheard"] for r in rows),
+ "no_reply": sum(not r["replied"] for r in rows),
+ "errors": sum(bool(r["error"]) for r in rows),
+ "server_lag_ms": percentiles([r["server_lag_ms"] for r in rows]), # how far behind real time the server was when it decided
+ }
+ print(mode, json.dumps(summary[mode]))
+ write_json(Path(args.out) / f"summary_{args.modes.replace(',', '_')}.json", summary)
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/eval/eval_wer.py b/eval/eval_wer.py
new file mode 100644
index 0000000000000000000000000000000000000000..646c60e113f80543c054ffc997c0b55f2b495a2c
--- /dev/null
+++ b/eval/eval_wer.py
@@ -0,0 +1,118 @@
+"""Nobody has listened to the audio, so a speech recogniser does: Whisper large-v3 (Apache-2.0)
+transcribes it and the transcript is compared with the words the audio was meant to say.
+
+ --pairs DIR ... folders of .wav + .txt (reply audio and the reply's own text,
+ saved by serving/loadtest.py --save-audio)
+ --tts-sample N N random clips of the training speech (data/out/tts) against the dialogue text
+
+Reported per group: word error rate (all errors / all reference words), and how often the
+first three words came out right (the first words are what a smaller first audio chunk
+could damage). Whisper makes errors of its own, so these are upper bounds on the audio's.
+
+ CUDA_VISIBLE_DEVICES=7 python -m eval.eval_wer --pairs eval/results/loadtest_fc25/audio --tts-sample 300 --out eval/results/wer
+"""
+import argparse
+import json
+import random
+import re
+from pathlib import Path
+
+import numpy as np
+import torch
+from scipy.signal import resample_poly
+
+from duplex.spec import SR, read_jsonl, read_wav, write_json
+
+UNITS = "zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen".split()
+TENS = "twenty thirty forty fifty sixty seventy eighty ninety".split()
+
+
+def spell(m):
+ n = int(m.group(0))
+ if n < 20:
+ return UNITS[n]
+ if n < 100:
+ return TENS[n // 10 - 2] + ("" if n % 10 == 0 else " " + UNITS[n % 10])
+ return m.group(0)
+
+
+def words(text):
+ text = re.sub(r"<[^>]+>", " ", text.split("")[-1]).lower().replace("-", " ")
+ text = re.sub(r"\d+", spell, text)
+ return re.sub(r"[^a-z0-9' ]+", " ", text).replace("'", "").split()
+
+
+def errors(ref, hyp):
+ """Word-level edit distance."""
+ d = list(range(len(hyp) + 1))
+ for i, r in enumerate(ref, 1):
+ prev, d[0] = d[0], i
+ for j, h in enumerate(hyp, 1):
+ prev, d[j] = d[j], min(d[j] + 1, d[j - 1] + 1, prev + (r != h))
+ return d[-1]
+
+
+def score(rows):
+ rows = [r for r in rows if r["ref"]]
+ if not rows:
+ return {"clips": 0}
+ return {
+ "clips": len(rows), "reference_words": sum(len(r["ref"]) for r in rows),
+ "word_error_rate": sum(r["errors"] for r in rows) / sum(len(r["ref"]) for r in rows),
+ "clips_with_no_error": sum(r["errors"] == 0 for r in rows),
+ "first_three_words_right": sum(r["ref"][:3] == r["hyp"][:3] for r in rows) / len(rows),
+ }
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--pairs", nargs="*", default=[])
+ ap.add_argument("--tts-sample", type=int, default=0)
+ ap.add_argument("--tts", default="data/out/tts")
+ ap.add_argument("--dialogues", default="data/out/dialogues.jsonl")
+ ap.add_argument("--out", default="eval/results/wer")
+ ap.add_argument("--seed", type=int, default=0)
+ args = ap.parse_args()
+
+ from transformers import pipeline
+ asr = pipeline("automatic-speech-recognition", model="openai/whisper-large-v3", torch_dtype=torch.float16, device=0, chunk_length_s=30)
+
+ def transcribe(x, sr):
+ if sr != SR:
+ x = resample_poly(x, SR, sr)
+ return asr({"raw": np.asarray(x, dtype=np.float32), "sampling_rate": SR}, generate_kwargs={"language": "english", "task": "transcribe"})["text"]
+
+ groups = {}
+ for d in args.pairs:
+ rows = []
+ for wav in sorted(Path(d).glob("*.wav")):
+ x, sr = read_wav(wav)
+ ref, hyp = words(wav.with_suffix(".txt").read_text(encoding="utf-8")), None
+ hyp = words(transcribe(x[:, 0], sr))
+ rows.append({"clip": wav.name, "ref": ref, "hyp": hyp, "errors": errors(ref, hyp)})
+ groups[str(d)] = rows
+
+ if args.tts_sample:
+ rng = random.Random(args.seed)
+ dialogues = read_jsonl(args.dialogues)
+ rows = []
+ for d in rng.sample(dialogues, min(args.tts_sample, len(dialogues))):
+ clips = np.load(Path(args.tts) / f"{d['id']}.npz")
+ ti = rng.randrange(len(d["turns"]))
+ parts = [p.strip() for p in d["turns"][ti]["text"].split("[pause]") if p.strip()]
+ si = rng.randrange(len(parts))
+ ref = words(parts[si])
+ hyp = words(transcribe(clips[f"t{ti}_s{si}"].astype(np.float32) / 32768, SR))
+ rows.append({"clip": f"{d['id']} t{ti}_s{si}", "voice": d["caller_voice"] if d["turns"][ti]["spk"] == "caller" else d["agent_voice"],
+ "ref": ref, "hyp": hyp, "errors": errors(ref, hyp)})
+ groups["training_speech"] = rows
+
+ summary = {name: score(rows) for name, rows in groups.items()}
+ out = Path(args.out)
+ write_json(out / "clips.json", groups)
+ write_json(out / "wer.json", summary)
+ print(json.dumps(summary, indent=1))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/eval/prep_bba.py b/eval/prep_bba.py
new file mode 100644
index 0000000000000000000000000000000000000000..7d032e7da8fbc67354f74a63a40d665af3873379
--- /dev/null
+++ b/eval/prep_bba.py
@@ -0,0 +1,63 @@
+"""Fetch a fixed 100-question subset of Big Bench Audio (ArtificialAnalysis/big_bench_audio,
+MIT): 25 questions per category, chosen with a fixed seed, decoded to 16 kHz wav.
+
+The dataset ships mp3. It is decoded with the soundfile package (libsndfile), or with the
+ffmpeg program when soundfile is not installed.
+
+ python -m eval.prep_bba --out eval/data/bba
+"""
+import argparse
+import json
+import random
+import subprocess
+from collections import defaultdict
+from pathlib import Path
+
+from huggingface_hub import hf_hub_download
+
+from duplex.spec import SR, write_json, write_wav
+
+REPO = "ArtificialAnalysis/big_bench_audio"
+
+
+def decode(mp3, wav):
+ """mp3 -> 16 kHz mono wav. Uses the soundfile package (its bundled libsndfile reads mp3) when
+ present, so nothing has to be installed on the host; otherwise the ffmpeg program."""
+ try:
+ import soundfile as sf
+ except ImportError:
+ subprocess.run(["ffmpeg", "-loglevel", "error", "-y", "-i", mp3, "-ac", "1", "-ar", "16000", "-c:a", "pcm_s16le", str(wav)], check=True)
+ return
+ from scipy.signal import resample_poly
+ x, sr = sf.read(mp3, dtype="float32", always_2d=True)
+ x = x.mean(axis=1)
+ write_wav(wav, x if sr == SR else resample_poly(x, SR, sr), SR)
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--out", default="eval/data/bba")
+ ap.add_argument("--per-category", type=int, default=25)
+ ap.add_argument("--seed", type=int, default=0)
+ args = ap.parse_args()
+
+ out = Path(args.out)
+ out.mkdir(parents=True, exist_ok=True)
+ meta = [json.loads(line) for line in open(hf_hub_download(REPO, "metadata.jsonl", repo_type="dataset"), encoding="utf-8")]
+ by_cat = defaultdict(list)
+ for row in meta:
+ by_cat[row["category"]].append(row)
+ rng = random.Random(args.seed)
+ 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)]
+
+ for q in subset:
+ wav = out / f"q_{q['id']}.wav"
+ if not wav.exists():
+ mp3 = hf_hub_download(REPO, q["file_name"].replace("\\", "/"), repo_type="dataset")
+ decode(mp3, wav)
+ write_json(out / "subset.json", [{"id": q["id"], "category": q["category"], "official_answer": q["official_answer"]} for q in subset])
+ print(f"{len(subset)} questions in {out}: " + ", ".join(f"{c}={args.per_category}" for c in sorted(by_cat)))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/eval/ws_client.py b/eval/ws_client.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a98df8be2ddd20e65bcac4512c906322e693ed0
--- /dev/null
+++ b/eval/ws_client.py
@@ -0,0 +1,121 @@
+"""A caller for the duplex endpoint, shared by the load test and the evaluations.
+
+Audio is sent the way a live microphone would send it: the frame holding samples
+[i*80 ms, (i+1)*80 ms) leaves at (i+1)*80 ms. "The caller finished" is therefore
+t_start + len(audio)/16000, and every latency below is measured from that instant
+on the client's own clock.
+"""
+import asyncio
+import json
+import time
+
+import aiohttp
+import numpy as np
+
+from duplex.spec import FRAME, SR, read_wav
+
+FRAME_S = FRAME / SR
+
+
+def load_16k(path):
+ x, sr = read_wav(path)
+ x = x.mean(axis=1)
+ if sr != SR:
+ from scipy.signal import resample_poly
+ x = resample_poly(x, SR, sr)
+ return (np.clip(x, -1, 1) * 32767).astype(np.int16)
+
+
+async def open_session(http, url, system_prompt, endpointing):
+ ws = await http.ws_connect(url, max_msg_size=1 << 20)
+ await ws.send_str(json.dumps({"type": "session.start", "system_prompt": system_prompt, "endpointing": endpointing}))
+ msg = json.loads((await ws.receive()).data)
+ if msg.get("type") != "session.started":
+ raise RuntimeError(f"session did not start: {msg}")
+ return ws
+
+
+async def run_turn(ws, pcm, commit=False, until="first_done", max_wait_s=60.0):
+ """Speak `pcm` (int16, 16 kHz) to the server in real time, then stay silent until the reply is over.
+
+ commit=True sends input.commit right after the last frame (manual endpointing).
+ until="first_done": return at the first reply.done.
+ until="done_after_audio": return at the first reply that ran to its end after the caller
+ finished (earlier replies that were cut off are kept in res["replies"]).
+ """
+ n = -(-len(pcm) // FRAME)
+ frames = np.concatenate([pcm, np.zeros(n * FRAME - len(pcm), np.int16)]).astype("= t_end):
+ break
+ else:
+ res["error"] = res["error"] or f"socket closed: {msg.type}"
+ break
+ finished.set()
+
+ task = asyncio.create_task(receive())
+ i = 0
+ while not finished.is_set():
+ due = t_start + (i + 1) * FRAME_S
+ if due > t_end + max_wait_s:
+ res["error"] = res["error"] or "timeout: no finished reply"
+ break
+ await asyncio.sleep(max(0.0, due - time.perf_counter()))
+ try:
+ await ws.send_bytes(frames[i].tobytes() if i < n else silence)
+ if i == n - 1 and commit:
+ res["t_commit"] = time.perf_counter()
+ await ws.send_str(json.dumps({"type": "input.commit"}))
+ except (ConnectionError, RuntimeError) as e:
+ res["error"] = res["error"] or f"send failed: {e!r}"
+ break
+ i += 1
+ task.cancel()
+
+ done = res["replies"][-1] if res["replies"] else None
+ res["done"] = done
+ # caller finished -> first audio of the last reply (negative when that reply began before the caller finished)
+ res["latency_ms"] = (res["t_first_audio"] - t_end) * 1000 if res["t_first_audio"] else None
+ res["started_early"] = bool(res["t_reply_start"] and res["t_reply_start"] < t_end) # any reply began while the caller spoke
+ res["audio"] = bytes(res["audio"])
+ return res
+
+
+def percentiles(values):
+ v = [x for x in values if x is not None]
+ if not v:
+ return {"n": 0}
+ return {"n": len(v), "min": float(np.min(v)), "p50": float(np.percentile(v, 50)), "p90": float(np.percentile(v, 90)),
+ "p95": float(np.percentile(v, 95)), "max": float(np.max(v))}
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..aaf194096c4bed5d9716cb91ddabcc1a90d4ac33
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1,15 @@
+# our code
+torch
+torchaudio
+numpy
+scipy
+aiohttp
+librosa
+safetensors
+huggingface_hub
+# data generation (read docs/licenses.md item 1 before installing kokoro's English front end)
+kokoro
+# needed by the released token2wav decoder (stepfun-ai/Step-Audio2); see that repository's README for the rest
+s3tokenizer
+onnxruntime
+hyperpyyaml
diff --git a/samples/README.md b/samples/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..033f753deeb1b7b65e7460d6fa709453263b774b
--- /dev/null
+++ b/samples/README.md
@@ -0,0 +1,11 @@
+# Samples
+
+Replies of the configuration in the README to four Big Bench Audio questions, as the test caller recorded them
+(24 kHz). Each is the lead-in, then the answer. The questions are not included.
+
+| File | Category | What it says | Right answer |
+|---|---|---|---|
+| `formal_fallacies.wav` | formal fallacies | Let me just check the validity of the argument based on the given premises. valid | valid |
+| `navigate.wav` | navigate | Let me figure out if following those instructions gets you back to the starting point. no | no |
+| `object_counting.wav` | object counting | Let me count all the fruits you mentioned to give you the total number. Fourteen | 14 |
+| `web_of_lies.wav` | web of lies | Let me think for a moment about who is telling the truth. Yes | yes |
diff --git a/samples/formal_fallacies.wav b/samples/formal_fallacies.wav
new file mode 100644
index 0000000000000000000000000000000000000000..d93832d30f83fe4a992921be1e809fc90a68e9c5
--- /dev/null
+++ b/samples/formal_fallacies.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:a63d06068516e730b8866e58359218115c71584e4559dfe603f4eb257595a45a
+size 311084
diff --git a/samples/navigate.wav b/samples/navigate.wav
new file mode 100644
index 0000000000000000000000000000000000000000..1311d0bb2c97bb6f922cf2c2fe8f51185883deff
--- /dev/null
+++ b/samples/navigate.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:95eba09ae02c1cb876aec61b1bc648be393c24e286168738da29a08e49ac122a
+size 261164
diff --git a/samples/object_counting.wav b/samples/object_counting.wav
new file mode 100644
index 0000000000000000000000000000000000000000..193361298124737ac453d1139c4986598f86b2de
--- /dev/null
+++ b/samples/object_counting.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:50e5f1d790385378219f3edfbbbe77e5d87b9c6b65fde7a9c927112e549e814c
+size 261164
diff --git a/samples/web_of_lies.wav b/samples/web_of_lies.wav
new file mode 100644
index 0000000000000000000000000000000000000000..ca23552632de1861585b29734fcafe0a27915bbe
--- /dev/null
+++ b/samples/web_of_lies.wav
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:9edcc62b4323977809e5ed6caa3756c6bf09fd9c25425af8e368ab448ee7ba01
+size 238124
diff --git a/serving/__init__.py b/serving/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/serving/baseline_client.py b/serving/baseline_client.py
new file mode 100644
index 0000000000000000000000000000000000000000..491776c7b71a31e3cb3fac2a5dc315737e94ec47
--- /dev/null
+++ b/serving/baseline_client.py
@@ -0,0 +1,84 @@
+"""Async client for the baseline's released vLLM endpoint.
+
+The request and response handling mirror the released clients
+(stepaudior1vllm.py in stepfun-ai/Step-Audio-R1, stepaudio2vllm.py in stepfun-ai/Step-Audio2):
+role "human", audio as `input_audio` wav parts of at most 25 s, skip_special_tokens false,
+the assistant prefix sent as an unfinished last message, text read from
+tts_content.tts_text or content, audio tokens read from tts_content.tts_audio.
+Nothing here is guessed; where the released code is silent (how R1.1 is asked to
+speak), serving/probe_baseline.py tries the released prefixes and records what comes back.
+"""
+import base64
+import io
+import json
+import re
+import wave
+
+import numpy as np
+
+from duplex.spec import SR
+
+AUDIO_TOKEN = re.compile(r"")
+SPEECH_MARKUP = re.compile(r"|")
+MAX_CLIP_S = 25.0 # the released client splits longer audio into 25 s parts
+
+
+def wav_bytes(pcm16, sr=SR):
+ buf = io.BytesIO()
+ with wave.open(buf, "wb") as w:
+ w.setnchannels(1)
+ w.setsampwidth(2)
+ w.setframerate(sr)
+ w.writeframes(np.asarray(pcm16, dtype=" and markers). So audio is read from both places.
+ audio = [int(i) for i in AUDIO_TOKEN.findall(tts.get("tts_audio") or content)]
+ yield delta, SPEECH_MARKUP.sub("", text), audio
diff --git a/serving/chat_template.jinja b/serving/chat_template.jinja
new file mode 100644
index 0000000000000000000000000000000000000000..96fac94b84123d7e4108b3e9fe271c16a2def3d2
--- /dev/null
+++ b/serving/chat_template.jinja
@@ -0,0 +1 @@
+{%- macro render_content(content) -%}{%- if content is string -%}{{- content.replace("\n", "") -}}{%- 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' -%}{%- 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\n' -}}{%- endif -%}
\ No newline at end of file
diff --git a/serving/judge.py b/serving/judge.py
new file mode 100644
index 0000000000000000000000000000000000000000..c92501d51b5073d4e89de376430445f2ec18c46b
--- /dev/null
+++ b/serving/judge.py
@@ -0,0 +1,52 @@
+"""Has the caller finished? Asked of the baseline itself.
+
+The small controller could not tell a thinking pause from a finished turn: that needs the
+meaning of the words, and the 33B model has it. So at a silence the audio heard so far is
+sent to the baseline with one question, the reply is opened past its reasoning block, and
+only the first token is read: "yes" or "no". One prefill and one token, so the answer
+comes back in about 0.15 s. No training is involved.
+
+The answer is the model's single most likely word. Its probability would be better (a
+threshold could be tuned), but asking this vLLM image for logprobs kills its engine on a
+this GPU (see serving/launch_vllm.sh).
+"""
+from serving.baseline_client import human_turn
+
+NL = chr(10)
+PROMPTS = {
+ # v1: the first wording tried (measured: 49% of pauses held, 82% of turn ends released)
+ "v1": ("You are listening to one side of a phone call. The caller has just gone quiet. Decide whether the caller has "
+ "finished what they wanted to say and is now waiting for a reply, or has only paused and will go on speaking. "
+ "Answer with one word: yes if the caller has finished, no if the caller will go on."),
+ # v2: says what "finished" means, so that a complete sentence that asks for nothing is not an invitation to reply
+ "v2": ("You are the listener on a phone call. The caller has just gone quiet for a moment. Should you start replying now? "
+ "Answer no if the caller's last words stop in the middle of a sentence (for example they end on a word like "
+ "and, but, to, the, my, on, or a half-said phrase), or if the caller is still setting out information and has "
+ "not yet asked their question or made their request. Answer yes only if the caller has finished a question, "
+ "a request, or a remark that calls for your reply. Answer with one word: yes or no."),
+}
+EMPTY_THOUGHT = "" + NL + NL + "" + NL # an empty reasoning block: the next token is the answer
+
+
+async def _post(http, api_url, payload):
+ async with http.post(api_url, json=payload) as r:
+ if r.status != 200:
+ raise RuntimeError(f"vLLM answered {r.status}: {(await r.text())[:300]}")
+ return (await r.json())["choices"][0]["message"].get("content") or ""
+
+
+async def judge_finished(http, api_url, model, pcm16, prompt="v2", think_tokens=0):
+ """pcm16: the caller's audio so far (int16, 16 kHz). Returns True (finished), False (will go on) or None.
+
+ With think_tokens > 0 the model may reason for up to that many tokens before it answers,
+ which costs think_tokens / (tokens per second) of extra time."""
+ base = {"model": model, "stream": False, "skip_special_tokens": False, "temperature": 0.0,
+ "continue_final_message": True, "add_generation_prompt": False}
+ head = [{"role": "system", "content": PROMPTS[prompt]}, human_turn(pcm16)]
+ prefix = EMPTY_THOUGHT
+ if think_tokens:
+ thought = await _post(http, api_url, dict(base, max_tokens=think_tokens, stop=[""],
+ messages=head + [{"role": "assistant", "content": "" + NL}]))
+ prefix = "" + NL + thought.rstrip() + NL + "" + NL
+ word = (await _post(http, api_url, dict(base, max_tokens=1, messages=head + [{"role": "assistant", "content": prefix}]))).strip().lower()
+ return True if word.startswith("yes") else False if word.startswith("no") else None
diff --git a/serving/launch_vllm.sh b/serving/launch_vllm.sh
new file mode 100644
index 0000000000000000000000000000000000000000..1e6744410e6cc7f726af763b27c1d2143ec42f9c
--- /dev/null
+++ b/serving/launch_vllm.sh
@@ -0,0 +1,52 @@
+#!/usr/bin/env bash
+# The released serving command (Docker method on the model card of stepfun-ai/Step-Audio-R1.1).
+# Changes, the first two required by the plan (Track A lives on GPU 0 alone):
+# --gpus device=0 (the card uses --gpus all)
+# --tensor-parallel-size 1 (the card uses 4)
+# -p 127.0.0.1:9999:9999 (the card publishes the port on every interface; this machine has a public address)
+# no -ti, a container name (runs in the background)
+# no "--" before "vllm serve" (this Docker hands "--" to the container as the program and fails)
+# --compilation-config '{"use_inductor": false}'
+# measured on this GPU, 2026-11-30: with the image's default (Inductor on) the engine dies at start with
+# "'sm_103a' is not a recognized processor" / "LLVM ERROR: Cannot select: intrinsic
+# %llvm.nvvm.shfl.sync.bfly.i32": the image's Triton 3.3.1 (torch 2.7.1+cu128) cannot generate
+# kernels for this GPU. Turning Inductor off keeps vLLM's CUDA graphs and skips that code generation.
+# -e VLLM_USE_FLASHINFER_SAMPLER=0
+# measured next: the FlashInfer top-p/top-k sampler builds itself at start and the image's torch
+# refuses with "Unknown CUDA arch (10.3+PTX) or GPU not supported". vLLM's own switch falls back
+# to its PyTorch sampler.
+# -v :/root/.nv
+# measured in the second run: after every start, the first reply longer than one token stalls for
+# about 90 s with the GPU idle (the engine waits in torch.cuda.Event.synchronize while the driver
+# builds kernels for this GPU; in the first run this was wrongly put down to CPU load). The driver
+# keeps the result in /root/.nv/ComputeCache; keeping that folder on the host is meant to spare
+# later starts the stall. Added after the measurements; not yet timed.
+# NOT set: TORCHDYNAMO_DISABLE=1. Measured in the second run: a request with "logprobs" kills the engine
+# with the same LLVM error (vLLM compiles a token-rank function on first use). Turning torch.compile
+# off for the container stops that crash but makes every reply hang after its first token. So this
+# image cannot return logprobs on this GPU, and nothing here asks for them.
+# The chat template is the card's own, byte for byte, read from a file instead of the command line.
+set -euo pipefail
+MODEL_DIR=${MODEL_DIR:?set MODEL_DIR to the downloaded Step-Audio-R1.1 folder}
+HERE=$(cd "$(dirname "$0")" && pwd)
+
+GPU=${GPU:-0} # extra copies (GPU=1 PORT=9991 ...) only run evaluation arms side by side
+PORT=${PORT:-9999}
+exec sudo docker run --rm --name "duplex-vllm-$GPU" --gpus "\"device=$GPU\"" \
+ -v "$MODEL_DIR":/Step-Audio-R1.1 \
+ -v "$HERE/chat_template.jinja":/chat_template.jinja:ro \
+ -p "127.0.0.1:$PORT:9999" \
+ -v "${NV_CACHE:-$HOME/.cache/duplex-nv}":/root/.nv \
+ -e VLLM_USE_FLASHINFER_SAMPLER=0 \
+ stepfun2025/vllm:step-audio-2-v20250909 \
+ vllm serve /Step-Audio-R1.1 \
+ --served-model-name Step-Audio-R1.1 \
+ --port 9999 \
+ --max-model-len 16384 \
+ --max-num-seqs 32 \
+ --tensor-parallel-size 1 \
+ --chat-template /chat_template.jinja \
+ --compilation-config '{"use_inductor": false}' \
+ --enable-log-requests \
+ --interleave-mm-strings \
+ --trust-remote-code
diff --git a/serving/listen_think.py b/serving/listen_think.py
new file mode 100644
index 0000000000000000000000000000000000000000..7f7d428a5f9ee177393342a7ab22f445f03f49e6
--- /dev/null
+++ b/serving/listen_think.py
@@ -0,0 +1,105 @@
+"""Reasoning that begins while the caller is still speaking, and survives a withdrawn reply.
+
+Measured in the second run: with its reasoning kept, the endpoint answers 97 of 100 Big
+Bench Audio questions, but the caller waits 9 to 11 s, because all of the reasoning starts
+when the caller stops. And at every pause inside a question a speculative reply reasons
+from nothing and is thrown away (about 8 per long question).
+
+So the reasoning of one caller turn is kept in one place, a `Thought`:
+ - while the caller speaks, the baseline is asked every few seconds to reason on the audio
+ heard so far, opened with what it has already worked out (serving/server.py, listen);
+ - a withdrawn reply leaves its reasoning here instead of dropping it;
+ - when the caller finishes, the reply's reasoning opens with all of that, so only the
+ last step is left to do; if the reasoning was already closed and the caller has said
+ nothing since, the reply speaks at once.
+
+The idea is not ours: reasoning while listening is published (SHANKS, arXiv 2510.06917;
+Chronological Thinking, arXiv 2510.05150), there with training. Here nothing is trained:
+the baseline's own reasoning block is re-opened on more audio.
+
+MEASURED IN THE THIRD RUN (docs/numbers.md): it costs accuracy. The best arm answered 62 of
+70 questions right against 95 of 100 without it; reasoning made on an unfinished question
+holds early conclusions and the model trusts them. So it is off by default and not part
+of the final configuration. Kept as the record of what was tried.
+"""
+import re
+
+NL = chr(10)
+FRESH = 3 # voiced frames (240 ms) of caller speech that count as "the caller said more"
+MAX_CHARS = 6000 # no more listening requests once the carried reasoning is this long
+# Measured in the third run's first round: a reply withdrawn at a pause had reasoned for a fraction of a
+# second ("Okay, let's see."), and each one left that and a remark behind. Ten remarks in a row and no
+# reasoning: the model then closed the block at once and answered without thinking, or went on writing
+# remarks for 30 s. So an addition shorter than this is not kept, and neither is the remark before it.
+MIN_KEEP = 60
+
+# How the carried reasoning is worded. It sits inside the model's own reasoning block, so it is
+# written in the model's voice. Three wordings are compared, because the baseline was never
+# trained to reason on a question that is still being asked.
+# open first words of the block while the caller is still speaking
+# more added when the block is re-opened and the caller has said more since
+# end added when the block is opened for the reply itself
+STANCES = {
+ # nothing added: the model's reasoning simply goes on
+ "bare": {"open": "", "more": NL, "end": ""},
+ # one short remark when more audio has arrived
+ "plain": {"open": "", "more": NL + "The caller has said more; I go on from here." + NL, "end": ""},
+ # told to take notes and not to answer until the caller has finished
+ # nothing added while listening; at the end, told to check its work against the whole question
+ "check": {"open": "", "more": NL,
+ "end": NL + "The caller has finished. I check what I worked out against the whole question, then give the answer." + NL},
+ "notes": {"open": "The caller is still speaking, so I only note what I have heard so far and do not answer yet." + NL,
+ "more": NL + "More from the caller:" + NL,
+ "end": NL + "The caller has finished. Now I use my notes and the whole question to work out the answer." + NL},
+}
+_SENTENCE_END = re.compile(r"[.!?:;][\"')\]]*(?:\s+|$)|" + NL)
+
+
+def finished_part(text):
+ """`text` cut back to its last finished sentence: a stream stopped in the middle of a word is not a thought."""
+ ends = [m.end() for m in _SENTENCE_END.finditer(text)]
+ return text[: ends[-1]] if ends else ""
+
+
+class Thought:
+ """The reasoning of one caller turn. `voiced` counts the caller's voiced frames, so silence adds nothing."""
+
+ def __init__(self, stance="plain", min_keep=MIN_KEEP):
+ self.stance, self.min_keep = STANCES[stance], min_keep
+ self.reset()
+
+ def reset(self):
+ self.text = "" # the reasoning so far (what follows the opening tag of the block)
+ self.voiced = 0 # voiced caller frames it was made on
+ self.closed = False # the model ended its reasoning on that audio
+ self.kept = 0 # requests whose reasoning was kept
+
+ def full(self):
+ return len(self.text) >= MAX_CHARS
+
+ def opening(self, voiced, final):
+ """How the reasoning block is opened for a request that has heard `voiced` frames.
+
+ final: the request is the reply itself (the caller seems to have finished).
+ Returns (text, ready). ready means the reasoning is closed and the caller has said
+ nothing since: no reasoning is left to do and the reply can speak at once."""
+ if not self.text:
+ return ("" if final else self.stance["open"]), False
+ more = voiced - self.voiced >= FRESH
+ if self.closed and not more:
+ return self.text, final
+ return self.text + (self.stance["more"] if more else "") + (self.stance["end"] if final else ""), False
+
+ def keep(self, opening, new, voiced, closed):
+ """Keep what a request added: `new` text after `opening`, made on `voiced` frames.
+ closed: the model ended its reasoning. Otherwise the request was cut (token limit, or
+ cancelled because the caller went on) and only its finished sentences are kept."""
+ if not closed:
+ new = finished_part(new)
+ if len(new.strip()) < max(self.min_keep, 1):
+ # too little to be a thought: keep neither it nor the remark in front of it
+ if closed and self.text:
+ self.voiced, self.closed = voiced, True # the model had nothing to add on this audio
+ return
+ self.text, self.voiced, self.closed = opening + new, voiced, closed
+ self.kept += 1
diff --git a/serving/loadtest.py b/serving/loadtest.py
new file mode 100644
index 0000000000000000000000000000000000000000..41f7f36843116ed90e6c0be827171630cd7313ff
--- /dev/null
+++ b/serving/loadtest.py
@@ -0,0 +1,96 @@
+"""Track A step 4: 1, 2, 4, 8, 16 concurrent streams against the endpoint.
+
+Every stream speaks a question in real time, ends its turn with input.commit (so the
+number is the model and the audio path, not an endpointing wait), and listens to the
+whole reply. Per turn:
+ ttfa_ms input.commit sent -> first reply audio frame received (client clock)
+ underruns frames that were due while the reply was playing but were not ready (server count)
+ max_gap_ms longest gap between two reply audio frames at the client (80 ms is nominal)
+
+A level PASSES when every turn has ttfa_ms < 800 and no turn has an underrun.
+Streams start within a random 2 s of each other; they are not artificially aligned.
+
+ python -m serving.loadtest --wav-dir eval/data/bba --out eval/results/loadtest
+"""
+import argparse
+import asyncio
+import random
+from pathlib import Path
+
+import aiohttp
+
+import numpy as np
+
+from duplex.spec import OUT_SR, write_json, write_wav
+from eval.ws_client import load_16k, open_session, percentiles, run_turn
+from serving.probe_baseline import gpu_memory
+
+
+async def stream(http, args, wavs, idx, level):
+ await asyncio.sleep(random.Random(f"{level}-{idx}").uniform(0, 2.0))
+ ws = await open_session(http, args.url, args.system, "manual")
+ turns = []
+ try:
+ for k in range(args.turns):
+ r = await run_turn(ws, wavs[(idx + k) % len(wavs)], commit=True, max_wait_s=args.max_wait_s)
+ done = r["done"] or {}
+ if args.save_audio and idx == 0 and r["audio"]: # one stream's replies, to check the audio with a recogniser
+ name = Path(args.save_audio) / f"level{level}_turn{k}"
+ write_wav(name.with_suffix(".wav"), np.frombuffer(r["audio"], dtype="\\n" (every
+Step-Audio-R1 example, text out) and "" (every Step-Audio 2 speech example).
+Which one makes R1.1 speak is not written down anywhere, so both are sent and the raw
+stream of each is saved. Nothing is assumed about the result.
+
+Saves to --out: question.wav, answer_.wav (when audio came back),
+raw__run.jsonl (every streamed chunk with its arrival time), probe.json.
+
+ python -m serving.probe_baseline --wav /src/Step-Audio2/assets/give_me_a_brief_introduction_to_the_great_wall.wav \
+ --step-audio2-dir /src/Step-Audio2 --token2wav-dir /models/Step-Audio-2-mini/token2wav \
+ --prompt-wav /src/Step-Audio2/assets/default_female.wav --out eval/results/probe
+"""
+import argparse
+import asyncio
+import json
+import subprocess
+import time
+from pathlib import Path
+
+import aiohttp
+import numpy as np
+
+from duplex.spec import OUT_SR, SR, read_wav, write_json, write_wav
+from serving.baseline_client import human_turn, stream_chat
+from serving.speech_out import NativeSpeechOut
+
+VARIANTS = {"think": "\n", "tts": ""}
+
+
+def gpu_memory():
+ """Per-GPU memory as nvidia-smi reports it (MiB). vLLM reserves a fixed share of the
+ card up front, so 'used' is the reservation, not what the model strictly needs."""
+ out = subprocess.run(["nvidia-smi", "--query-gpu=index,name,memory.used,memory.total", "--format=csv,noheader,nounits"],
+ capture_output=True, text=True, check=True).stdout
+ rows = [[c.strip() for c in line.split(",")] for line in out.strip().splitlines()]
+ return [{"gpu": int(r[0]), "name": r[1], "used_mib": int(r[2]), "total_mib": int(r[3])} for r in rows]
+
+
+async def run_once(http, args, speech, pcm, prefix, raw_path):
+ messages = [{"role": "system", "content": args.system}] if args.system else []
+ messages += [human_turn(pcm), {"role": "assistant", "content": prefix, "eot": False}]
+ st = speech.new_reply()
+ t0 = time.perf_counter()
+ m = {"first_chunk_s": None, "first_audio_token_s": None, "first_audio_s": None, "audio_tokens": 0}
+ text, audio = "", bytearray()
+ with open(raw_path, "w", encoding="utf-8") as raw:
+ async for delta, t, tokens in stream_chat(http, args.api_url, args.model, messages, max_tokens=args.max_tokens,
+ temperature=args.temperature, top_p=args.top_p,
+ repetition_penalty=args.repetition_penalty, stop_token_ids=[151665]):
+ now = time.perf_counter() - t0
+ raw.write(json.dumps({"t": round(now, 4), "delta": delta}, ensure_ascii=False) + "\n")
+ m["first_chunk_s"] = m["first_chunk_s"] or now
+ text += t
+ if tokens:
+ m["first_audio_token_s"] = m["first_audio_token_s"] or now
+ m["audio_tokens"] += len(tokens)
+ for chunk in await speech.feed(st, tokens):
+ m["first_audio_s"] = m["first_audio_s"] or time.perf_counter() - t0
+ audio += chunk
+ for chunk in await speech.finish(st):
+ m["first_audio_s"] = m["first_audio_s"] or time.perf_counter() - t0
+ audio += chunk
+ m["total_s"] = time.perf_counter() - t0
+ m["audio_s"] = len(audio) / 2 / OUT_SR
+ m["real_time_factor"] = m["total_s"] / m["audio_s"] if m["audio_s"] else None # below 1 is faster than real time
+ m["text"] = text
+ return m, bytes(audio)
+
+
+async def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--api-url", default="http://localhost:9999/v1/chat/completions")
+ ap.add_argument("--model", default="Step-Audio-R1.1")
+ ap.add_argument("--wav", required=True, help="the spoken question, 16-bit PCM wav")
+ ap.add_argument("--step-audio2-dir", required=True)
+ ap.add_argument("--token2wav-dir", required=True)
+ ap.add_argument("--prompt-wav", required=True, help="voice prompt for the released decoder")
+ ap.add_argument("--out", default="eval/results/probe")
+ ap.add_argument("--variants", default="think,tts")
+ ap.add_argument("--runs", type=int, default=3, help="per variant; run 0 includes warm-up")
+ ap.add_argument("--system", default="You are a helpful assistant.", help="as in the released multi-turn speech example")
+ ap.add_argument("--max-tokens", type=int, default=2048)
+ ap.add_argument("--temperature", type=float, default=0.7)
+ ap.add_argument("--top-p", type=float, default=0.9)
+ ap.add_argument("--repetition-penalty", type=float, default=1.05)
+ args = ap.parse_args()
+
+ out = Path(args.out)
+ out.mkdir(parents=True, exist_ok=True)
+ x, sr = read_wav(args.wav)
+ x = x.mean(axis=1)
+ if sr != SR:
+ from scipy.signal import resample_poly
+ x = resample_poly(x, SR, sr)
+ pcm = (np.clip(x, -1, 1) * 32767).astype(np.int16)
+ write_wav(out / "question.wav", pcm.astype(np.float32) / 32768, SR)
+
+ report = {"question_s": len(pcm) / SR, "args": vars(args), "gpu_before": gpu_memory(), "variants": {}}
+ speech = NativeSpeechOut(args.step_audio2_dir, args.token2wav_dir, args.prompt_wav)
+ report["gpu_after_decoder_load"] = gpu_memory()
+ async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=None)) as http:
+ for name in args.variants.split(","):
+ runs = []
+ for k in range(args.runs):
+ try:
+ m, audio = await run_once(http, args, speech, pcm, VARIANTS[name], out / f"raw_{name}_run{k}.jsonl")
+ except Exception as e: # keep the evidence, move to the next variant
+ runs.append({"error": repr(e)})
+ break
+ runs.append(m)
+ if audio:
+ write_wav(out / f"answer_{name}.wav", np.frombuffer(audio, dtype=" server
+ text {"type": "session.start", "system_prompt": "...", "endpointing": "controller" | "vad" | "manual"}
+ binary one 80 ms frame: 1280 samples, 16 kHz mono, 16-bit little-endian (2560 bytes)
+ text {"type": "input.commit"} end the caller's turn now (used with "manual")
+ text {"type": "session.end"}
+
+Server -> client
+ text session.started, reply.start, transcript.delta, reply.audio.first, reply.done, control, error
+ binary one 80 ms frame of reply audio: 1920 samples, 24 kHz mono, 16-bit little-endian
+
+The clock is the caller's audio: for every frame that comes in, at most one frame of
+reply audio goes out. So the reply plays in real time, a STOP cuts it within one frame,
+and the controller sees the model's own audio exactly as the caller hears it.
+
+Who decides when to speak ("endpointing"):
+ controller the trained controller: START begins the reply, STOP cuts it off, WAIT
+ holds, BACKCHANNEL does not interrupt.
+ vad no controller: energy threshold, START after a fixed silence, STOP on any
+ 240 ms of caller speech (the plain baseline to compare against).
+ manual only input.commit starts a reply (used to measure the model alone).
+ judge 240 ms into a silence the reply is started speculatively and kept silent, and
+ the baseline itself is asked whether the caller has finished (serving/judge.py).
+ "yes" lets the reply be heard; if the caller goes on, the reply is withdrawn
+ unheard; after --judge-timeout-ms of silence it is heard anyway. A loaded
+ controller is used for STOP against BACKCHANNEL only.
+
+Third run (docs/numbers.md), with --think-first. The first two cost accuracy and are off by default;
+--lead-in is part of the final configuration; --keep-interrupted was not measured.
+ --carry-thought a withdrawn reply leaves its reasoning for the next one;
+ --listen-think the baseline also reasons while the caller is still speaking;
+ --keep-interrupted a reply the caller cut in on stays in the conversation (their question
+ and the part of the answer that was played).
+ --lead-in once a reasoning reply may be heard, the baseline says one short sentence
+ ("let me work that out") while the reasoning goes on; the answer follows it.
+ reply.audio.first is then the lead-in, reply.answer.first the answer.
+
+ python -m serving.server --reply-prefix '' --step-audio2-dir /src/Step-Audio2 \
+ --token2wav-dir /models/Step-Audio-2-mini/token2wav --prompt-wav prompt.wav \
+ --encoder-ckpt runs/encoder/final.pt --controller-ckpt runs/controller/final.pt
+"""
+import argparse
+import asyncio
+import json
+import time
+from concurrent.futures import ThreadPoolExecutor
+
+import aiohttp
+import numpy as np
+from aiohttp import web
+from scipy.signal import resample_poly
+
+from duplex.spec import BACKCHANNEL, FRAME, LABELS, OUT_FRAME, OUT_SR, SR, START, STOP, WAIT
+from serving.baseline_client import human_turn, stream_chat
+from serving.judge import judge_finished
+from serving.listen_think import Thought
+
+IN_BYTES, OUT_BYTES = FRAME * 2, OUT_FRAME * 2
+SILENT = np.zeros(FRAME, dtype=np.float32)
+THINK_OPEN, THINK_CLOSE = "" + chr(10), "" # the baseline's reasoning block, as its chat template opens it
+JUDGE_AT = 3 # frames of quiet (240 ms) at which the judge is asked and a reply is started speculatively
+ONSET_GAP = 5 # frames of quiet (400 ms) after which caller speech counts as a new onset
+MIN_VOICED = 3 # frames of caller speech (240 ms) needed before a reply may start
+# --lead-in: what the baseline is told when it is asked to say something while the real reply is still reasoning
+LEAD_IN = ("The caller has just finished speaking and you need a moment to think before you answer. Say one short sentence "
+ "telling them you are working it out, and mention what they asked about. Do not give the answer or any part of it.")
+
+
+class Session:
+ def __init__(self, app, ws, cfg):
+ self.app, self.ws, self.args = app, ws, app["args"]
+ self.system_prompt = str(cfg.get("system_prompt", ""))
+ default = "controller" if app["ctl"] else "vad"
+ self.mode = cfg.get("endpointing", default)
+ if self.mode == "controller" and not app["ctl"]:
+ raise ValueError("this server was started without a controller")
+ if self.mode not in ("controller", "vad", "manual", "judge"):
+ raise ValueError(f"unknown endpointing {self.mode!r}")
+ # in "judge" mode a loaded controller is still used, but only for STOP against BACKCHANNEL
+ self.ctl_state = app["ctl"].new_session() if app["ctl"] and self.mode in ("controller", "judge") else None
+ self.t0 = time.perf_counter()
+ self.state = "listening" # listening | pending (reply asked, no audio yet) | speaking
+ self.turn = [] # caller frames of the turn being heard
+ self.turn_voiced = 0 # how many of them are voiced
+ self.barge = [] # caller frames since their last onset while a reply is in flight
+ self.silence = 0 # frames since the caller was last voiced
+ self.voiced_run = 0 # consecutive voiced frames
+ self.history = []
+ self.reply = None
+ self.frame = 0
+ self.out24, self.out16, self.n24, self.n16 = bytearray(), np.zeros(0, np.float32), 0, 0
+ a = self.args
+ # the reasoning of the caller's turn in progress (serving/listen_think.py)
+ self.thought = Thought(a.listen_stance, a.thought_min_chars) if a.think_first and (a.listen_think or a.carry_thought) else None
+ self.listener = None # the request that reasons while the caller speaks
+ self.listened = 0 # voiced frames the last such request had heard
+
+ # ---- plumbing -------------------------------------------------------------
+ def voiced(self, x):
+ rms = float(np.sqrt(np.mean((x.astype(np.float32) / 32768.0) ** 2)))
+ return bool(20 * np.log10(rms + 1e-9) > self.args.vad_db)
+
+ def context(self):
+ return ([{"role": "system", "content": self.system_prompt}] if self.system_prompt else []) + self.history
+
+ async def send(self, **event):
+ event["t_ms"] = round((time.perf_counter() - self.t0) * 1000, 1)
+ await self.ws.send_str(json.dumps(event, ensure_ascii=False))
+
+ def enqueue(self, pcm):
+ """Reply audio from the decoder (24 kHz bytes): queue it for the caller, and keep a
+ 16 kHz copy, sample-aligned, for the controller."""
+ self.out24 += pcm
+ x = np.frombuffer(pcm, dtype="= ONSET_GAP
+ self.silence = 0 if is_voiced else self.silence + 1
+ self.voiced_run = self.voiced_run + 1 if is_voiced else 0
+ if self.state == "listening":
+ self.turn_voiced += is_voiced
+ # before any speech keep only 400 ms of lead-in; never hold more than 60 s
+ self.turn = (self.turn + [x])[-(750 if self.turn_voiced else ONSET_GAP):]
+ th = self.thought
+ if (th is not None and self.args.listen_think and is_voiced and not th.full()
+ and (self.listener is None or self.listener.done())
+ and (self.turn_voiced - max(th.voiced, self.listened)) * 80 >= self.args.listen_every_ms):
+ self.listened = self.turn_voiced
+ self.listener = asyncio.create_task(self.listen())
+ else:
+ if new_onset:
+ self.barge = []
+ self.barge = (self.barge + [x])[-312:] # at most 25 s
+
+ label = WAIT
+ if self.ctl_state is not None:
+ probs = await asyncio.get_running_loop().run_in_executor(
+ self.app["ctl_pool"], self.app["ctl"].step, self.ctl_state, x.astype(np.float32) / 32768.0, own)
+ label = int(np.argmax(probs))
+ if self.mode == "judge" and label == START:
+ label = WAIT # the judge decides when to start
+ if label != WAIT:
+ await self.send(type="control", label=LABELS[label], frame=self.frame, probs=[round(float(p), 3) for p in probs])
+ if self.mode == "judge":
+ held = self.reply is not None and self.reply["held"]
+ if self.state == "listening" and self.silence == JUDGE_AT:
+ # Speculate: start the reply now, keep it silent, and ask the baseline whether the caller has finished.
+ await self.start_reply("judge", held=True)
+ elif held and self.voiced_run >= 2:
+ await self.end_reply("withdrawn") # the caller went on: nothing was heard, nothing is lost
+ elif held and self.silence * 80 >= self.args.judge_timeout_ms:
+ await self.release("timeout") # quiet this long: reply whatever the judge said
+ elif self.ctl_state is None and self.state != "listening" and not held and self.voiced_run >= MIN_VOICED:
+ label = STOP
+ elif self.mode == "vad":
+ if self.state == "listening" and self.silence * 80 >= self.args.vad_silence_ms:
+ label = START
+ elif self.state != "listening" and self.voiced_run >= MIN_VOICED:
+ label = STOP
+ self.frame += 1
+
+ if label == STOP and self.reply is not None and (self.reply["held"] or self.reply["frames"] == 0):
+ await self.end_reply("withdrawn") # a STOP against a reply nobody has heard yet
+ elif label == START and self.state == "listening":
+ await self.start_reply(self.mode)
+ elif label == STOP and self.state != "listening":
+ await self.end_reply("interrupted")
+ # WAIT holds. BACKCHANNEL does not interrupt: the reply keeps playing.
+
+ async def pump(self):
+ """Send one frame of reply audio if one is due. Returns that frame at 16 kHz."""
+ r = self.reply
+ if r is None or r["held"]:
+ return SILENT
+ if r["frames"] == 0 and r["lead_left"] > 0 and self.silence * 80 < self.args.lead_in_after_ms:
+ # The lead-in is ready but the caller has been quiet only briefly. Measured in the third run: played at
+ # once, it was heard in the pauses inside a question (4 of the first 8 questions). So it waits; if the
+ # caller goes on meanwhile, the reply is withdrawn unheard as before.
+ return SILENT
+ if len(self.out24) >= OUT_BYTES or (r["generated"] and self.out24):
+ chunk = bytes(self.out24[:OUT_BYTES]).ljust(OUT_BYTES, b"\0")
+ del self.out24[:OUT_BYTES]
+ own = np.concatenate([self.out16[:FRAME], SILENT])[:FRAME]
+ self.out16 = self.out16[FRAME:]
+ if r["first_audio"] is None:
+ r["first_audio"] = time.perf_counter()
+ self.state = "speaking"
+ await self.send(type="reply.audio.first", ttfa_ms=round((r["first_audio"] - r["t_commit"]) * 1000, 1))
+ if r["lead_left"] > 0:
+ r["lead_left"] -= OUT_BYTES
+ elif r["answer_audio"] is None:
+ r["answer_audio"] = time.perf_counter()
+ await self.send(type="reply.answer.first", answer_ms=round((r["answer_audio"] - r["t_commit"]) * 1000, 1))
+ await self.ws.send_bytes(chunk)
+ r["frames"] += 1
+ return own
+ if r["generated"]:
+ await self.end_reply("done")
+ elif r["first_audio"] is not None and r["answer_audio"] is None:
+ r["lead_gap"] += 1 # the lead-in has played and the answer is not ready: a silence, not a stutter
+ elif r["first_audio"] is not None:
+ r["underruns"] += 1 # a frame was due and none was ready: the caller hears a gap
+ return SILENT
+
+ # ---- reasoning while the caller speaks -------------------------------------
+ async def listen(self):
+ """Ask the baseline to reason on the audio heard so far, opened with what it has already worked out."""
+ a, th = self.args, self.thought
+ voiced, pcm, t0 = self.turn_voiced, np.concatenate(self.turn), time.perf_counter()
+ opening, _ = th.opening(voiced, final=False)
+ messages = self.context() + [human_turn(pcm), {"role": "assistant", "content": THINK_OPEN + opening, "eot": False}]
+ new, info, failed = "", {}, None
+ try:
+ async for _, text, _ in stream_chat(self.app["http"], a.vllm_url, a.model, messages, info=info, max_tokens=a.listen_max_tokens,
+ temperature=a.temperature, repetition_penalty=1.0, stop_token_ids=[151665],
+ stop=[THINK_CLOSE]):
+ new += text
+ except asyncio.CancelledError:
+ raise # the caller paused and a reply took over: what was streamed so far is kept below
+ except Exception as e:
+ failed = repr(e)
+ finally:
+ th.keep(opening, new, voiced, closed=info.get("finish_reason") == "stop")
+ if failed:
+ await self.send(type="error", message=f"listen: {failed}")
+ else:
+ await self.send(type="control", label="LISTEN", frame=self.frame, heard_voiced_ms=voiced * 80, chars=len(new),
+ closed=th.closed, ms=round((time.perf_counter() - t0) * 1000, 1))
+
+ async def stop_listening(self):
+ task, self.listener = self.listener, None
+ if task is not None and not task.done():
+ task.cancel()
+ await asyncio.gather(task, return_exceptions=True) # its partial reasoning is in self.thought once this returns
+
+ # ---- replies --------------------------------------------------------------
+ async def say(self, r, text, kind):
+ """Transcript text goes out at once, or waits with a held reply."""
+ if r["held"]:
+ r["backlog"].append((text, kind))
+ else:
+ await self.send(type="transcript.delta", text=text, kind=kind)
+
+ async def release(self, why):
+ """Let a held (speculative) reply be heard."""
+ r = self.reply
+ r["held"], r["released_by"] = False, why
+ lag = (time.perf_counter() - self.t_first_frame) * 1000 - (self.frame - 1) * 80
+ await self.send(type="reply.start", by=f"judge:{why}", frame=self.frame, heard_ms=len(r["heard"]) * 80, lag_ms=round(lag, 1),
+ speculated_ms=round((time.perf_counter() - r["t_commit"]) * 1000, 1))
+ for text, kind in r["backlog"]:
+ await self.send(type="transcript.delta", text=text, kind=kind)
+ r["backlog"] = []
+ self.maybe_lead_in(r)
+
+ def maybe_lead_in(self, r):
+ a = self.args
+ if a.lead_in and a.think_first and not r["think_done"] and "lead" not in r:
+ r["lead"] = asyncio.create_task(self.lead_in(r))
+
+ async def lead_in(self, r):
+ """One short spoken sentence while the reply is still reasoning. Its audio is queued ahead of the answer's."""
+ a, speech = self.args, self.app["speech"]
+ st = speech.new_reply()
+ messages = [{"role": "system", "content": LEAD_IN}] + self.history + [r["human"], {"role": "assistant", "content": a.reply_prefix, "eot": False}]
+
+ def queue(pcm):
+ if self.reply is r:
+ self.enqueue(pcm)
+ r["lead_left"] += len(pcm)
+ try:
+ async for _, text, tokens in stream_chat(self.app["http"], a.vllm_url, a.model, messages, max_tokens=a.lead_in_max_tokens,
+ temperature=a.temperature, top_p=a.top_p, repetition_penalty=a.repetition_penalty,
+ stop_token_ids=[151665]):
+ if text:
+ r["lead_text"] += text
+ await self.send(type="transcript.delta", text=text, kind="lead")
+ if tokens:
+ for pcm in await speech.feed(st, tokens):
+ queue(pcm)
+ for pcm in await speech.finish(st):
+ queue(pcm)
+ except asyncio.CancelledError:
+ raise
+ except Exception as e:
+ await self.send(type="error", message=f"lead-in: {e!r}")
+ finally:
+ st["cache"], st["buf"] = None, []
+
+ async def ask_judge(self, r, pcm):
+ a = self.args
+ try:
+ said = await judge_finished(self.app["http"], a.vllm_url, a.model, pcm, prompt=a.judge_prompt, think_tokens=a.judge_think_tokens)
+ except Exception as e:
+ said = None
+ await self.send(type="error", message=f"judge: {e!r}")
+ if self.reply is not r or not r["held"]:
+ return # withdrawn or already released meanwhile
+ await self.send(type="control", label="JUDGE", finished=said, frame=self.frame,
+ judge_ms=round((time.perf_counter() - r["t_commit"]) * 1000, 1))
+ if said is not False:
+ await self.release("finished") # "no" keeps it held until the caller goes on or the timeout
+
+ async def start_reply(self, by, held=False):
+ if self.turn_voiced < MIN_VOICED:
+ return
+ await self.stop_listening()
+ heard, voiced = self.turn, self.turn_voiced
+ pcm = np.concatenate(heard)
+ self.turn, self.turn_voiced = [], 0
+ human = human_turn(pcm)
+ messages = self.context() + [human, {"role": "assistant", "content": self.args.reply_prefix, "eot": False}]
+ r = {"t_commit": time.perf_counter(), "first_token": None, "first_audio": None, "t_generated": None, "generated": False,
+ "frames": 0, "underruns": 0, "text": "", "tts_audio": "", "human": human, "by": by, "heard": heard,
+ "voiced": voiced, "held": held, "backlog": [],
+ "think_done": False, "lead_left": 0, "lead_gap": 0, "lead_text": "", "answer_audio": None,
+ "thinking": self.args.reply_prefix.startswith("")}
+ self.reply, self.state = r, "pending"
+ self.out24, self.out16, self.n24, self.n16 = bytearray(), np.zeros(0, np.float32), 0, 0
+ r["task"] = asyncio.create_task(self.generate(r, messages))
+ if held:
+ r["judge"] = asyncio.create_task(self.ask_judge(r, pcm))
+ await self.send(type="reply.speculative", frame=self.frame, heard_ms=round(len(pcm) * 1000 / SR))
+ return
+ # lag_ms: how far this session's processing is behind the caller's audio clock (0 when the server keeps up)
+ lag = (time.perf_counter() - self.t_first_frame) * 1000 - (self.frame - 1) * 80 if self.frame else 0.0
+ await self.send(type="reply.start", by=by, frame=self.frame, heard_ms=round(len(pcm) * 1000 / SR), lag_ms=round(lag, 1))
+ self.maybe_lead_in(r)
+
+ async def generate(self, r, messages):
+ a, speech = self.args, self.app["speech"]
+ st = speech.new_reply()
+ try:
+ if a.think_first:
+ # Think, then speak. Measured on 100 Big Bench Audio questions: the baseline scores 97 when
+ # its reply is opened for reasoning (text out) and 65 when it is opened for speech: asked
+ # to speak, it does not reason. So it reasons first, as text, and the speech is then opened
+ # with that reasoning already in the reply.
+ # With a carried thought (serving/listen_think.py) the reasoning opens with what was worked out
+ # while the caller spoke, or by a reply that was withdrawn; `ready` means nothing is left to do.
+ th = self.thought
+ opening, ready = th.opening(r["voiced"], final=True) if th else ("", False)
+ r["carried_chars"], r["thought_ready"] = len(opening), ready
+ thought = ""
+ if opening:
+ await self.say(r, opening, "think")
+ if not ready:
+ think_msgs = messages[:-1] + [{"role": "assistant", "content": THINK_OPEN + opening, "eot": False}]
+ closed = False
+ try:
+ async for _, text, _ in stream_chat(self.app["http"], a.vllm_url, a.model, think_msgs, max_tokens=a.think_max_tokens,
+ temperature=a.temperature, repetition_penalty=1.0, stop_token_ids=[151665],
+ stop=[THINK_CLOSE]):
+ r["first_token"] = r["first_token"] or time.perf_counter()
+ if text:
+ thought += text
+ await self.say(r, text, "think")
+ closed = True
+ finally:
+ if th: # also when this reply is withdrawn in the middle of its reasoning
+ th.keep(opening, thought, r["voiced"], closed)
+ r["think_done"] = True
+ if "lead" in r:
+ await asyncio.gather(r["lead"], return_exceptions=True) # the answer's audio goes behind the lead-in's
+ await self.say(r, THINK_CLOSE, "think")
+ r["thought_ms"] = round((time.perf_counter() - r["t_commit"]) * 1000, 1)
+ spoken_open = THINK_OPEN + opening + thought + THINK_CLOSE + chr(10) + a.reply_prefix
+ messages = messages[:-1] + [{"role": "assistant", "content": spoken_open, "eot": False}]
+ async for _, text, tokens in stream_chat(self.app["http"], a.vllm_url, a.model, messages, max_tokens=a.max_tokens,
+ temperature=a.temperature, top_p=a.top_p,
+ repetition_penalty=a.repetition_penalty, stop_token_ids=[151665]):
+ r["first_token"] = r["first_token"] or time.perf_counter()
+ if text:
+ r["text"] += text
+ await self.say(r, text, "think" if r["thinking"] else "say")
+ if "" in r["text"]:
+ r["thinking"] = False
+ if tokens:
+ r["tts_audio"] += "".join(f"" for t in tokens)
+ playing = self.reply is r and not r["held"] and r["first_audio"] is not None
+ for pcm in await speech.feed(st, tokens, buffered_ms=len(self.out24) / 48 if playing else None):
+ if self.reply is r:
+ self.enqueue(pcm)
+ for pcm in await speech.finish(st):
+ if self.reply is r:
+ self.enqueue(pcm)
+ except asyncio.CancelledError:
+ raise
+ except Exception as e:
+ await self.send(type="error", message=repr(e))
+ finally:
+ r["generated"], r["t_generated"] = True, time.perf_counter()
+ r["decodes"], r["decode_ms"] = st["decodes"], round(st["decode_ms"], 1)
+ # Free the decoder caches now. The reply, its task and this coroutine refer to each other, so
+ # Python frees them only when its cycle collector runs, and it cannot see GPU memory: measured,
+ # the decoder process grew to 30.6 GiB and one load test died of CUDA out-of-memory.
+ st["cache"], st["buf"] = None, []
+
+ async def end_reply(self, reason):
+ r, self.reply, self.state = self.reply, None, "listening"
+ r["task"].cancel() # no effect when generation already finished
+ for extra in ("judge", "lead"):
+ if extra in r:
+ r[extra].cancel()
+ self.out24, self.out16 = bytearray(), np.zeros(0, np.float32)
+ turn_goes_on = reason != "done" and r["frames"] * 80 < self.args.false_start_ms
+ if self.thought is not None and not turn_goes_on:
+ self.thought.reset() # the caller's next words are a new turn
+ self.listened = 0
+ if reason == "done":
+ # history as in the released multi-turn text example: the assistant's words as plain content
+ # (the R1.1 chat template renders only `content`)
+ said = {"role": "assistant", "content": (r["lead_text"] + " " + r["text"]).strip()}
+ self.history = (self.history + [r["human"], said])[-2 * self.args.max_history_turns:] if self.args.max_history_turns else []
+ self.turn = list(self.barge) if self.silence < ONSET_GAP else [] # the caller already began their next turn
+ elif r["frames"] * 80 < self.args.false_start_ms:
+ # cut off before it had really begun: the caller was not finished. Keep what they had said, add what they said since.
+ self.turn = (r["heard"] + list(self.barge))[-750:]
+ else:
+ self.turn = list(self.barge) # what the caller said to cut in starts the new turn
+ if self.args.keep_interrupted and self.args.max_history_turns:
+ # The caller cut in on a reply they had been hearing. Without this their question and the answer
+ # are forgotten and "no, I meant four" has nothing to refer to. The words that were played are
+ # estimated from the share of the generated audio that was played.
+ share = min(1.0, r["frames"] * OUT_FRAME / max(self.n24, 1))
+ said = r["text"][: int(len(r["text"]) * share)].rsplit(" ", 1)[0].strip()
+ if said:
+ self.history = (self.history + [r["human"], {"role": "assistant", "content": said}])[-2 * self.args.max_history_turns:]
+ self.barge = []
+ self.turn_voiced = sum(self.voiced(f) for f in self.turn)
+ if reason == "withdrawn": # a speculative reply nobody heard
+ await self.send(type="reply.withdrawn", frame=self.frame)
+ return
+ ms = lambda t: round((t - r["t_commit"]) * 1000, 1) if t else None
+ await self.send(type="reply.done", reason=reason, by=r["by"], text=r["text"], audio_ms=r["frames"] * 80, underruns=r["underruns"],
+ ttfa_ms=ms(r["first_audio"]), first_token_ms=ms(r["first_token"]), generated_ms=ms(r["t_generated"]),
+ thought_ms=r.get("thought_ms"), answer_ms=ms(r["answer_audio"]), lead_gap_ms=r["lead_gap"] * 80, lead_text=r["lead_text"],
+ carried_chars=r.get("carried_chars"), thought_ready=r.get("thought_ready"),
+ decodes=r.get("decodes"), decode_ms=r.get("decode_ms"))
+
+
+async def handler(request):
+ ws = web.WebSocketResponse(max_msg_size=1 << 20)
+ await ws.prepare(request)
+ sess = None
+ try:
+ async for msg in ws:
+ if msg.type == web.WSMsgType.BINARY:
+ if sess is None or len(msg.data) != IN_BYTES:
+ await ws.send_str(json.dumps({"type": "error", "message": f"send session.start first, then {IN_BYTES}-byte frames"}))
+ continue
+ await sess.on_frame(msg.data)
+ elif msg.type == web.WSMsgType.TEXT:
+ m = json.loads(msg.data)
+ if m.get("type") == "session.start":
+ try:
+ sess = Session(request.app, ws, m)
+ except ValueError as e:
+ await ws.send_str(json.dumps({"type": "error", "message": str(e)}))
+ continue
+ await sess.send(type="session.started", endpointing=sess.mode, frame_ms=80, input_sample_rate=SR, output_sample_rate=OUT_SR)
+ elif sess and m.get("type") == "input.commit" and sess.state == "listening":
+ await sess.start_reply("manual")
+ elif m.get("type") == "session.end":
+ break
+ finally:
+ if sess and sess.reply:
+ sess.reply["task"].cancel()
+ if sess and sess.listener:
+ sess.listener.cancel()
+ return ws
+
+
+async def on_startup(app):
+ app["http"] = aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=None))
+
+
+async def on_cleanup(app):
+ await app["http"].close()
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--host", default="127.0.0.1", help="local only: the machine has a public address")
+ ap.add_argument("--port", type=int, default=8765)
+ ap.add_argument("--vllm-url", default="http://localhost:9999/v1/chat/completions")
+ ap.add_argument("--model", default="Step-Audio-R1.1")
+ ap.add_argument("--reply-prefix", required=True, help="how the assistant turn is opened; taken from what serving/probe_baseline.py measured")
+ ap.add_argument("--step-audio2-dir", required=True)
+ ap.add_argument("--token2wav-dir", required=True)
+ ap.add_argument("--prompt-wav", required=True)
+ ap.add_argument("--first-chunk", type=int, default=25, help="audio tokens in a reply's first decoded chunk (released recipe: 25, one second)")
+ ap.add_argument("--min-chunk", type=int, default=25, help="smallest later chunk, used while the play buffer is below --low-water-ms")
+ ap.add_argument("--low-water-ms", type=int, default=0)
+ ap.add_argument("--decoder-workers", type=int, default=1, help="independent audio decoders")
+ ap.add_argument("--decoder-fp16", action="store_true", help="run the released decoder in half precision (its own float16 option)")
+ ap.add_argument("--encoder-ckpt")
+ ap.add_argument("--controller-ckpt")
+ ap.add_argument("--controller-device", default="cuda:1")
+ ap.add_argument("--vad-db", type=float, default=-45.0)
+ ap.add_argument("--vad-silence-ms", type=int, default=640)
+ ap.add_argument("--max-history-turns", type=int, default=4)
+ ap.add_argument("--judge-prompt", default="v2", help="wording of the end-of-turn question (serving/judge.py)")
+ ap.add_argument("--judge-think-tokens", type=int, default=0, help="reasoning tokens the judge may use before it answers")
+ ap.add_argument("--judge-timeout-ms", type=int, default=1600, help="reply after this much silence even when the judge said the caller will go on")
+ ap.add_argument("--think-first", action="store_true", help="reason as text first, then speak with that reasoning in the reply")
+ ap.add_argument("--think-max-tokens", type=int, default=2048)
+ ap.add_argument("--carry-thought", action="store_true", help="with --think-first: a withdrawn reply leaves its reasoning for the next one")
+ ap.add_argument("--listen-think", action="store_true", help="with --think-first: reason while the caller is still speaking (implies --carry-thought)")
+ ap.add_argument("--listen-every-ms", type=int, default=2400, help="caller speech between two listening requests")
+ ap.add_argument("--listen-max-tokens", type=int, default=96, help="reasoning tokens one listening request may add")
+ ap.add_argument("--listen-stance", default="plain", choices=["bare", "plain", "check", "notes"], help="wording of the carried reasoning (serving/listen_think.py)")
+ ap.add_argument("--thought-min-chars", type=int, default=60, help="an addition to the carried reasoning shorter than this is dropped")
+ ap.add_argument("--lead-in", action="store_true", help="with --think-first: say one short sentence while the reply is still reasoning")
+ ap.add_argument("--lead-in-max-tokens", type=int, default=300, help="150 cut the audio of longer lead-ins short (third run)")
+ ap.add_argument("--short-whole", action="store_true", help="decode a reply shorter than one audio chunk in one piece (serving/speech_out.py)")
+ ap.add_argument("--lead-in-after-ms", type=int, default=1200, help="the lead-in is not played before the caller has been quiet this long")
+ ap.add_argument("--keep-interrupted", action="store_true", help="keep a reply the caller cut in on, as far as it was played, in the conversation")
+ ap.add_argument("--false-start-ms", type=int, default=2000, help="a reply cut off before it played this long counts as a false start: the caller's earlier words are kept")
+ ap.add_argument("--max-tokens", type=int, default=2048)
+ ap.add_argument("--temperature", type=float, default=0.7)
+ ap.add_argument("--top-p", type=float, default=0.9)
+ ap.add_argument("--repetition-penalty", type=float, default=1.05)
+ args = ap.parse_args()
+
+ from serving.speech_out import NativeSpeechOut
+ app = web.Application()
+ app["args"] = args
+ app["speech"] = NativeSpeechOut(args.step_audio2_dir, args.token2wav_dir, args.prompt_wav, first_chunk=args.first_chunk,
+ min_chunk=args.min_chunk, low_water_ms=args.low_water_ms, workers=args.decoder_workers,
+ float16=args.decoder_fp16, whole_short=args.short_whole)
+ app["ctl"], app["ctl_pool"] = None, ThreadPoolExecutor(max_workers=1)
+ if args.controller_ckpt:
+ from controller.runtime import DuplexController
+ app["ctl"] = DuplexController(args.encoder_ckpt, args.controller_ckpt, args.controller_device)
+ app.router.add_get("/ws", handler)
+ app.on_startup.append(on_startup)
+ app.on_cleanup.append(on_cleanup)
+ web.run_app(app, host=args.host, port=args.port)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/serving/speech_out.py b/serving/speech_out.py
new file mode 100644
index 0000000000000000000000000000000000000000..cc92f8590ef17d8306e33d0367fb64540239dfeb
--- /dev/null
+++ b/serving/speech_out.py
@@ -0,0 +1,155 @@
+"""Audio tokens -> 24 kHz waveform with the released Step-Audio 2 decoder (token2wav.py
+in stepfun-ai/Step-Audio2, weights in stepfun-ai/Step-Audio-2-mini/token2wav).
+
+The released streaming recipe is kept as is: 25 tokens per chunk plus the flow model's
+look-ahead, tokens >= 6561 dropped, last chunk flushed with last_chunk=True.
+
+The released Token2wav holds one stream's caches on the object. To serve many sessions,
+each reply owns a copy of the freshly primed caches, and they are swapped in for the
+duration of one call. Each decoder has one worker thread; several decoders can be loaded.
+"""
+import asyncio
+import copy
+import sys
+import time
+from concurrent.futures import ThreadPoolExecutor
+
+CHUNK = 25
+MAX_AUDIO_TOKEN = 6561
+# the token sequence the released example (examples-vllm-stream.py) uses to warm the decoder up
+WARMUP_TOKENS = [1493, 4299, 4218, 2049, 528, 2752, 4850, 4569, 4575, 6372, 2127, 4068, 2312, 4993, 4769, 2300, 226, 2175, 2160, 2152,
+ 6311, 6065, 4859, 5102, 4615, 6534, 6426, 1763, 2249, 2209, 5938, 1725, 6048, 3816, 6058, 958, 63, 4460, 5914, 2379,
+ 735, 5319, 4593, 2328, 890, 35, 751, 1483, 1484, 1483, 2112, 303, 4753, 2301, 5507, 5588, 5261, 5744, 5501, 2341,
+ 2001, 2252, 2344, 1860, 2031, 414, 4366, 4366, 6059, 5300, 4814, 5092, 5100, 1923, 3054, 4320, 4296, 2148, 4371, 5831,
+ 5084, 5027, 4946, 4946, 2678, 575, 575, 521, 518, 638, 1367, 2804, 3402, 4299]
+
+
+def _restore_torchaudio_load():
+ """The released decoder (and s3tokenizer) read the voice prompt with torchaudio.load.
+ Current torchaudio routes that through TorchCodec, which needs FFmpeg libraries on the
+ host. Reading the wav with soundfile gives the same samples and changes nothing on the host."""
+ import soundfile as sf
+ import torch
+ import torchaudio
+
+ def load(path, *args, **kwargs):
+ x, sr = sf.read(str(path), dtype="float32", always_2d=True)
+ return torch.from_numpy(x.T.copy()), sr
+
+ torchaudio.load = load
+
+
+class NativeSpeechOut:
+ """first_chunk audio tokens in a reply's first chunk (released recipe: 25, one second of speech).
+ min_chunk smallest later chunk, used only while the caller's play buffer is below low_water_ms.
+ workers independent decoders, each on its own thread; a reply stays on one of them.
+
+ Measured in the second run: a first chunk of 12 alone brought the first audio from 0.88 s to
+ 0.56 s for one stream and made it stutter (8 underruns in 3 turns), because the second chunk
+ of 25 was not ready when the short first one had played out. So later chunks are small only
+ while the buffer is low, and go back to 25 once it has filled."""
+
+ def __init__(self, step_audio2_dir, token2wav_dir, prompt_wav, float16=False, first_chunk=CHUNK, min_chunk=CHUNK,
+ low_water_ms=0, workers=1, whole_short=False):
+ _restore_torchaudio_load()
+ self.first_chunk, self.min_chunk, self.low_water_ms = first_chunk, min_chunk, low_water_ms
+ self.whole_short = whole_short
+ sys.path.insert(0, str(step_audio2_dir))
+ from token2wav import Token2wav # released code, imported unchanged
+ self.prompt = str(prompt_wav)
+ self.units, self._next = [], 0
+ for _ in range(workers):
+ t2w = Token2wav(str(token2wav_dir), float16=float16)
+ t2w.set_stream_cache(self.prompt)
+ self.units.append({"t2w": t2w, "fresh": copy.deepcopy((t2w.stream_cache, t2w.hift_cache_dict)),
+ "pool": ThreadPoolExecutor(max_workers=1)})
+ self.lookahead = int(self.units[0]["t2w"].flow.pre_lookahead_len)
+ # Warm up, as the released streaming example does: without it the first reply's first
+ # audio took 7.6 s (probe) and 8.3 s (server), against 0.76 s once warm.
+ for _ in self.units:
+ st = self.new_reply()
+ for i in range(0, 3 * CHUNK, CHUNK):
+ self._decode(st, WARMUP_TOKENS[i: i + CHUNK + self.lookahead], False)
+ self._decode(st, WARMUP_TOKENS[-CHUNK:], True)
+ # Every chunk length is a new tensor shape, and the first decode of a new shape can stall for
+ # seconds (measured: one 6 s call in the middle of a reply, 75 underruns). So every length this
+ # configuration can produce is decoded once here: each chunk size in use, and every possible
+ # length of a reply's last chunk.
+ sizes = sorted({first_chunk} | set(range(min(min_chunk, CHUNK), CHUNK + 1)))
+ for n in sizes:
+ st = self.new_reply()
+ self._decode(st, WARMUP_TOKENS[: n + self.lookahead], False)
+ self._decode(st, WARMUP_TOKENS[n: n + CHUNK + self.lookahead], False)
+ for n in range(1, CHUNK + self.lookahead + 1):
+ st = self.new_reply()
+ self._decode(st, WARMUP_TOKENS[: CHUNK + self.lookahead], False)
+ self._decode(st, WARMUP_TOKENS[CHUNK: CHUNK + n], True)
+
+ if whole_short:
+ for unit in range(len(self.units)):
+ for n in range(1, max(first_chunk, CHUNK) + self.lookahead + 1):
+ self._decode_whole({"unit": unit, "decodes": 0, "decode_ms": 0.0}, WARMUP_TOKENS[:n])
+
+ def _decode_whole(self, st, tokens):
+ """A reply shorter than one chunk, decoded in one piece: the body of the released Token2wav.__call__
+ (flow.inference, then the vocoder) without its wav-file wrapper.
+
+ Measured in the third run with Whisper: of the one-word answers ("valid", "ten") decoded by the
+ streaming path as a lone last chunk, only 71 of 94 were recognisable, and some clips lasted 0.16 s."""
+ import numpy as np
+ import torch
+ t2w, t0 = self.units[st["unit"]]["t2w"], time.perf_counter()
+ prompt_speech_tokens, prompt_speech_tokens_lens, spk_emb, prompt_mels, prompt_mels_lens = t2w.cache[self.prompt]
+ tok = torch.tensor([tokens], dtype=torch.int32, device="cuda")
+ lens = torch.tensor([tok.shape[1]], dtype=torch.int32, device="cuda")
+ with torch.inference_mode():
+ with torch.amp.autocast("cuda", dtype=torch.float16 if t2w.float16 else torch.float32):
+ mel = t2w.flow.inference(tok, lens, prompt_speech_tokens, prompt_speech_tokens_lens, prompt_mels, prompt_mels_lens, spk_emb, 10)
+ wav, _ = t2w.hift(speech_feat=mel)
+ st["decodes"] += 1
+ st["decode_ms"] += (time.perf_counter() - t0) * 1000
+ return (np.clip(wav.float().cpu().numpy(), -1.0, 1.0) * 32767.0).astype(" 0:
+ if n >= CFG["close_at"]:
+ if info is not None:
+ info["finish_reason"] = "stop"
+ return
+ n += 1
+ for piece in (f"S{n} is ", "done. "):
+ await asyncio.sleep(CFG["delay"])
+ yield {}, piece, []
+ budget -= 1
+ if info is not None:
+ info["finish_reason"] = "length"
+ else:
+ for _ in range(30):
+ await asyncio.sleep(CFG["delay"])
+ yield {}, "word ", [1, 2, 3, 4]
+
+
+async def fake_judge(http, url, model, pcm, prompt="v2", think_tokens=0):
+ return len(pcm) >= CFG["finished_after"] * FRAME
+
+
+class FakeSpeech:
+ def new_reply(self):
+ return {"buf": [], "decodes": 0, "decode_ms": 0.0, "cache": 1}
+
+ async def feed(self, st, tokens, buffered_ms=None):
+ st["buf"] += tokens
+ out = []
+ while len(st["buf"]) >= 25:
+ st["buf"] = st["buf"][25:]
+ st["decodes"] += 1
+ out.append(bytes(48000)) # one second at 24 kHz, 16 bit
+ return out
+
+ async def finish(self, st):
+ n, st["buf"] = len(st["buf"]), []
+ return [bytes(1920 * n)] if n else []
+
+
+class FakeSocket:
+ def __init__(self):
+ self.events, self.audio_frames = [], 0
+
+ async def send_str(self, s):
+ self.events.append(json.loads(s))
+
+ async def send_bytes(self, b):
+ self.audio_frames += 1
+
+
+def session(**over):
+ args = argparse.Namespace(
+ vad_db=-45.0, vad_silence_ms=640, judge_prompt="v1", judge_think_tokens=0, judge_timeout_ms=1600, vllm_url="", model="m",
+ reply_prefix="", think_first=True, think_max_tokens=2048, max_tokens=2048, temperature=0.7, top_p=0.9,
+ repetition_penalty=1.05, false_start_ms=2000, max_history_turns=4, carry_thought=False, listen_think=False,
+ listen_every_ms=2400, listen_max_tokens=96, listen_stance="plain", keep_interrupted=False, thought_min_chars=0, lead_in=False, lead_in_max_tokens=150, lead_in_after_ms=0)
+ vars(args).update(over)
+ ws = FakeSocket()
+ app = {"args": args, "ctl": None, "ctl_pool": None, "http": None, "speech": FakeSpeech()}
+ return server.Session(app, ws, {"endpointing": "judge"}), ws
+
+
+RNG = np.random.default_rng(0)
+QUIET = np.zeros(FRAME, "= 2, "nothing was carried over the pause"
+ done = await until_done(sess, ws)
+ spoken = [c for c in CALLS if not c["reasoning"]]
+ assert done["reason"] == "done" and done["carried_chars"] > 0 and len(spoken) == 1
+ prefix = spoken[0]["content"]
+ assert prefix.startswith("" + NL) and prefix.endswith("" + NL + "")
+ assert re.findall(r"S(\d+) is done\.", prefix) == [str(i) for i in range(1, 21)], "sentences lost, repeated or cut: " + prefix
+ assert prefix.count("S") == 20 and STANCES["plain"]["more"] in prefix
+ listens = [c for c in CALLS if c["reasoning"] and c["max_tokens"] == 96]
+ assert len(listens) >= 2, "no reasoning request while the caller spoke"
+ assert all(c["content"].startswith("" + NL) for c in CALLS)
+ assert sess.thought.text == "" and (sess.listener is None or sess.listener.done())
+ assert not [e for e in ws.events if e["type"] == "error"], [e for e in ws.events if e["type"] == "error"]
+ assert any(e["type"] == "reply.start" and e["by"] == "judge:finished" for e in ws.events)
+ print(f"ok listen and carry: {len(listens)} requests while listening, {sum(c['reasoning'] for c in CALLS)} reasoning requests, "
+ f"20 sentences once each in the spoken reply's reasoning")
+
+
+async def test_ready():
+ """The reasoning closes while the caller is still speaking and they add nothing: the reply needs no reasoning request."""
+ CALLS.clear()
+ CFG.update(close_at=2, delay=0.0, finished_after=0)
+ sess, ws = session(listen_think=True)
+ await feed(sess, [QUIET] * 5 + [loud() for _ in range(32)])
+ done = await until_done(sess, ws)
+ assert done["thought_ready"] is True and sum(c["reasoning"] for c in CALLS) == 1, CALLS
+ assert CALLS[-1]["content"] == "" + NL + "S1 is done. S2 is done. " + NL + ""
+ print("ok ready: reasoning closed while listening, the reply spoke without a reasoning request")
+
+
+async def test_without_and_interrupted():
+ """Flags off: the second run's path. And a reply the caller cuts in on stays in the conversation when asked to."""
+ CALLS.clear()
+ CFG.update(close_at=3, delay=0.0, finished_after=0)
+ sess, ws = session(keep_interrupted=True)
+ assert sess.thought is None
+ await feed(sess, [QUIET] * 5 + [loud() for _ in range(15)] + [QUIET] * 45)
+ assert ws.audio_frames >= 26, f"the reply should have played more than 2 s, played {ws.audio_frames} frames"
+ await feed(sess, [loud() for _ in range(5)])
+ done = next(e for e in ws.events if e["type"] == "reply.done")
+ assert done["reason"] == "interrupted" and len(sess.history) == 2, (done["reason"], len(sess.history))
+ said = sess.history[1]["content"]
+ assert said and len(said) < len(done["text"]) and said.split() == ["word"] * len(said.split())
+ assert [c["content"] for c in CALLS if c["reasoning"]] == ["" + NL]
+ print(f"ok flags off is the old path; interrupted reply kept: {len(said.split())} of {len(done['text'].split())} words")
+
+
+async def test_lead_in():
+ """While the reply reasons, one spoken sentence goes out first; the answer's audio follows it."""
+ CALLS.clear()
+ CFG.update(close_at=20, delay=0.01, finished_after=0)
+ sess, ws = session(lead_in=True)
+ await feed(sess, [QUIET] * 5 + [loud() for _ in range(15)])
+ done = await until_done(sess, ws)
+ kinds = [e["type"] for e in ws.events if e["type"] in ("reply.audio.first", "reply.answer.first")]
+ assert kinds == ["reply.audio.first", "reply.answer.first"], kinds
+ assert done["reason"] == "done" and done["answer_ms"] > done["ttfa_ms"] and done["lead_text"].split() == ["word"] * 30
+ lead = [c for c in CALLS if c["content"] == ""]
+ assert len(lead) == 1 and lead[0]["system"] == server.LEAD_IN and lead[0]["max_tokens"] == 150 # the test session sets 150
+ assert ws.audio_frames >= 115, ws.audio_frames # 4.8 s of lead-in and 4.8 s of answer
+ deltas = [e for e in ws.events if e["type"] == "transcript.delta"]
+ close = next(i for i, e in enumerate(deltas) if e["text"] == "")
+ assert all(e["kind"] != "lead" for e in deltas[close:]), "lead-in words after the reasoning closed"
+ assert sess.history[-1]["content"].split() == ["word"] * 60
+ print(f"ok lead-in: first audio after {done['ttfa_ms']:.0f} ms, the answer after {done['answer_ms']:.0f} ms, {ws.audio_frames} frames played")
+
+
+async def test_lead_in_gate():
+ """The lead-in is ready early but is not played before the caller has been quiet for 1.2 s; if they go on, nothing was heard."""
+ CALLS.clear()
+ CFG.update(close_at=40, delay=0.005, finished_after=0)
+ sess, ws = session(lead_in=True, lead_in_after_ms=1200)
+ await feed(sess, [QUIET] * 5 + [loud() for _ in range(15)] + [QUIET] * 14)
+ assert ws.audio_frames == 0 and sess.reply["lead_left"] > 0, (ws.audio_frames, sess.reply["lead_left"])
+ await feed(sess, [loud() for _ in range(4)])
+ assert ws.audio_frames == 0 and any(e["type"] == "reply.withdrawn" for e in ws.events), [e["type"] for e in ws.events][-6:]
+ await feed(sess, [loud() for _ in range(8)] + [QUIET] * 14)
+ assert ws.audio_frames == 0
+ await feed(sess, [QUIET] * 6)
+ assert ws.audio_frames > 0
+ done = await until_done(sess, ws)
+ assert done["reason"] == "done" and not [e for e in ws.events if e["type"] == "reply.done" and e["reason"] != "done"]
+ print("ok lead-in gate: nothing played in a 1.1 s pause, the reply was withdrawn unheard, then played after 1.2 s of quiet")
+
+
+async def main():
+ server.stream_chat, server.judge_finished = fake_stream, fake_judge
+ test_thought()
+ await test_listen_and_carry()
+ await test_ready()
+ await test_without_and_interrupted()
+ await test_lead_in()
+ await test_lead_in_gate()
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/tests/test_streaming.py b/tests/test_streaming.py
new file mode 100644
index 0000000000000000000000000000000000000000..7d03f1826d77107de0e5ef48595e1b9d62488397
--- /dev/null
+++ b/tests/test_streaming.py
@@ -0,0 +1,98 @@
+"""Checks that need no model weights and no GPU. Run first on the training machine:
+
+ python -m tests.test_streaming
+
+1. Frame-by-frame serving is the same function as whole-crop training, for the shared
+ transformer, the student encoder and the controller.
+2. The timeline builder's labels obey their definition on a synthetic dialogue.
+"""
+import numpy as np
+import torch
+
+from controller.encoder.student import StudentEncoder
+from controller.model.model import Controller
+from data.build_timeline import lay_out
+from duplex.spec import AGENT, CALLER, FRAME, SR, TEACHER_DIM
+from duplex.streaming import CausalTransformer
+
+
+def close(a, b, what, tol=1e-4):
+ err = (a - b).abs().max().item()
+ assert err < tol, f"{what}: streaming and offline differ by {err}"
+ print(f"ok {what}: max difference {err:.2e}")
+
+
+@torch.no_grad()
+def test_transformer():
+ torch.manual_seed(0)
+ tf = CausalTransformer(dim=64, layers=3, heads=4, window=16).eval()
+ x = torch.randn(2, 61, 64)
+ state, parts = tf.init_state(), []
+ for i in range(0, 61, 2): # longer than the window, odd length, 2 tokens at a time
+ y, state = tf.step(x[:, i: i + 2], state)
+ parts.append(y)
+ close(torch.cat(parts, 1), tf(x), "transformer")
+
+
+@torch.no_grad()
+def test_student():
+ torch.manual_seed(0)
+ fb = torch.rand(128, 201) * 0.01 # any filterbank: the check is about streaming, not about mel values
+ enc = StudentEncoder(dim=64, layers=2, heads=4, window=20, out_dim=32, fb=fb).eval()
+ wav = torch.randn(2, 40 * FRAME) * 0.1
+ state, parts = enc.init_state(2, wav.device), []
+ for i in range(40):
+ y, state = enc.step(wav[:, i * FRAME: (i + 1) * FRAME], state)
+ parts.append(y)
+ close(torch.cat(parts, 1), enc(wav), "student encoder")
+
+
+@torch.no_grad()
+def test_controller():
+ torch.manual_seed(0)
+ ctl = Controller(feat_dim=32, dim=64, layers=2, heads=4, window=12).eval()
+ caller, own = torch.randn(1, 60, 32), torch.randn(1, 60, 32)
+ state, parts = ctl.init_state(), []
+ for i in range(0, 60, 2):
+ y, state = ctl.step(caller[:, i: i + 2], own[:, i: i + 2], state)
+ parts.append(y)
+ close(torch.cat(parts, 1), ctl(caller, own), "controller")
+ assert Controller().cfg["feat_dim"] == TEACHER_DIM
+
+
+def test_labels():
+ rng = np.random.default_rng(0)
+ speech = lambda s: (rng.standard_normal(int(s * SR)) * 8000).astype(np.int16)
+ for trial in range(200):
+ d = {"turns": [
+ {"spk": "agent", "text": "", "interrupts": False}, {"spk": "caller", "text": "", "interrupts": False},
+ {"spk": "agent", "text": "", "interrupts": False}, {"spk": "caller", "text": "", "interrupts": True},
+ {"spk": "agent", "text": "", "interrupts": False}, {"spk": "caller", "text": "", "interrupts": False},
+ ]}
+ clips = {"t0_s0": speech(2), "t1_s0": speech(1.5), "t1_s1": speech(1), "t2_s0": speech(6), "t3_s0": speech(2),
+ "t4_s0": speech(7), "t5_s0": speech(1)}
+ place, events, end = lay_out(d, clips, [speech(0.4).astype(np.float32) / 32768], np.random.default_rng(trial))
+ audio = np.zeros((-(-end // FRAME) * FRAME, 2), dtype=np.float32)
+ for ch, start, x in place:
+ audio[start: start + len(x), ch] += x
+ loud = lambda ch, f0, f1: bool(np.abs(audio[f0 * FRAME: f1 * FRAME, ch]).max() > 0) if f1 > f0 else False
+ kinds = [e["type"] for e in events]
+ # two caller turns are answered (the last caller turn ends the call), one has a pause, one cuts in
+ assert kinds.count("pause") == 1 and kinds.count("interrupt") == 1 and kinds.count("start") == 2, kinds
+ for e in events:
+ if e["type"] == "start": # nobody speaks during START; the agent speaks right after it
+ assert not loud(CALLER, e["f0"], e["f1"]) and not loud(AGENT, e["f0"], e["f1"]) and loud(AGENT, e["f1"], e["f1"] + 1)
+ elif e["type"] == "pause": # the caller is silent in a pause and nothing was labelled there
+ assert not loud(CALLER, e["f0"], e["f1"])
+ elif e["type"] == "interrupt": # both speak during STOP; the agent is silent from the cut on
+ assert loud(CALLER, e["f0"], e["f1"]) and loud(AGENT, e["f0"], e["f1"]) and not loud(AGENT, e["f1"], e["f1"] + 3)
+ elif e["type"] == "backchannel": # the caller's "mm-hm" lies inside the agent's speech
+ assert loud(CALLER, e["f0"], e["f1"]) and loud(AGENT, e["f0"], e["f1"])
+ print("ok labels: 200 synthetic dialogues obey the label definitions")
+
+
+if __name__ == "__main__":
+ test_transformer()
+ test_student()
+ test_controller()
+ test_labels()
diff --git a/tools/README.md b/tools/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..0fe607021557145f9d881744bc168d76e4bbc62e
--- /dev/null
+++ b/tools/README.md
@@ -0,0 +1,2 @@
+These are the scripts as they ran on our machine. Paths under `/data/train` are that machine's layout:
+change them to yours. `serving/` and `eval/` take every path as an argument.
diff --git a/tools/__init__.py b/tools/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tools/bba_arm.sh b/tools/bba_arm.sh
new file mode 100644
index 0000000000000000000000000000000000000000..9116c2e429f46d18fd39c99df82722cbd1e79b02
--- /dev/null
+++ b/tools/bba_arm.sh
@@ -0,0 +1,16 @@
+#!/usr/bin/env bash
+# The benchmark through one endpoint on one baseline copy.
+# tools/bba_arm.sh [server_run.sh mode] [extra server args]
+# OUT = result folder under eval/results (default bba2); PROMPT = the reply voice prompt.
+# CONC = questions at a time; SHARD / NSHARDS split one arm over several copies (merge with tools/bba_merge.py).
+cd /data/train/duplex && . /data/train/venv/bin/activate
+export OMP_NUM_THREADS=8
+g=$1; name=$2; mode=$3; srv=${4:-}; extra=${5:-}
+[ "$srv" = "-" ] && srv=""
+port=878$g; vport=$([ "$g" = 0 ] && echo 9999 || echo 999$g)
+tmux kill-session -t bsrv$g 2>/dev/null; sleep 1
+tmux new-session -d -s bsrv$g "FIRST_CHUNK=${FIRST_CHUNK:-25} MIN_CHUNK=${MIN_CHUNK:-25} LOW_WATER=${LOW_WATER:-0} WORKERS=${WORKERS:-1} THINK_TOKENS=${THINK_TOKENS:-2048} PROMPT=${PROMPT:-runs/prompt_af_heart.wav} GPU=$g PORT=$port VLLM_PORT=$vport SERVER_ARGS='$extra' bash tools/server_run.sh $srv > /data/train/logs/server_bba_${name}_${SHARD:-0}.log 2>&1"
+for i in $(seq 1 120); do ss -ltn 2>/dev/null | grep -q ":$port " && break; sleep 2; done
+python -u -m eval.eval_bba --url http://127.0.0.1:$port/ws --data eval/data/bba --out eval/results/${OUT:-bba2}/$name --modes $mode --concurrency "${CONC:-6}" --max-wait-s 150 --shard "${SHARD:-0}" --num-shards "${NSHARDS:-1}" ${EVAL_ARGS:-} > /data/train/logs/${OUT:-bba2}_${name}_${SHARD:-0}.log 2>&1
+tmux kill-session -t bsrv$g 2>/dev/null
+date -u +%FT%TZ > runs/${OUT:-bba2}_${name}_${SHARD:-0}_end
diff --git a/tools/bba_merge.py b/tools/bba_merge.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd81e7ab410d035ecf0232d7faf100cad4a99eea
--- /dev/null
+++ b/tools/bba_merge.py
@@ -0,0 +1,36 @@
+"""Summary of a benchmark arm from its per-question files (used when an arm was split over several baseline copies).
+
+ python -m tools.bba_merge eval/results/bba2/judge_v1/judge
+"""
+import json
+import sys
+from collections import defaultdict
+from pathlib import Path
+
+from duplex.spec import write_json
+from eval.ws_client import percentiles
+
+d = Path(sys.argv[1])
+rows = [json.loads(p.read_text(encoding="utf-8")) for p in sorted(d.glob("q_*.json"))]
+by_cat = defaultdict(list)
+for r in rows:
+ by_cat[r["category"]].append(r["correct"])
+done = [[e for e in r["events"] if e["type"] == "reply.done"] for r in rows]
+summary = {
+ "questions": len(rows), "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())},
+ "replied": sum(r["replied"] for r in rows), "no_answer_found": sum(r["answer"] is None for r in rows),
+ "errors": sum(bool(r["error"]) for r in rows),
+ # audible: the caller heard part of a reply that was then cut off because the question went on
+ "replies_cut_off_after_being_heard": sum(r["replies_cut_off"] for r in rows),
+ "questions_with_a_reply_cut_off": sum(r["replies_cut_off"] > 0 for r in rows),
+ "replies_withdrawn_unheard": sum(sum(1 for e in r["events"] if e["type"] == "reply.withdrawn") for r in rows),
+ "latency_ms": percentiles([r["latency_ms"] for r in rows if r["replied"]]),
+ "thought_ms": percentiles([x[-1].get("thought_ms") for x in done if x]),
+ # third run (serving/listen_think.py): reasoning requests made while the caller spoke, and what the last reply began with
+ "listen_requests": sum(sum(1 for e in r["events"] if e.get("label") == "LISTEN") for r in rows),
+ "carried_chars": percentiles([x[-1].get("carried_chars") for x in done if x]),
+ "replies_that_needed_no_reasoning": sum(1 for x in done if x and x[-1].get("thought_ready")),
+}
+write_json(d.parent / "summary_merged.json", summary)
+print(json.dumps(summary))
diff --git a/tools/bench_controller.py b/tools/bench_controller.py
new file mode 100644
index 0000000000000000000000000000000000000000..0646ade8787329d0343e7dcdcf112957673c66ff
--- /dev/null
+++ b/tools/bench_controller.py
@@ -0,0 +1,45 @@
+"""How long one 80 ms controller step takes (student encoder on both audio streams plus the
+controller), frame by frame as the server runs it. A session needs 12.5 steps per second.
+
+ python -m tools.bench_controller --encoder runs/encoder/final.pt [--controller runs/controller/final.pt] --device cuda:0
+"""
+import argparse
+import time
+
+import numpy as np
+import torch
+
+from controller.encoder.student import load_student
+from controller.model.model import Controller, load_controller
+from controller.runtime import DuplexController
+from duplex.spec import FRAME
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--encoder", required=True)
+ ap.add_argument("--controller", default=None, help="omit to time a randomly initialised controller of the default size")
+ ap.add_argument("--device", default="cuda:0")
+ ap.add_argument("--frames", type=int, default=600)
+ args = ap.parse_args()
+
+ rt = DuplexController.__new__(DuplexController)
+ rt.device = torch.device(args.device)
+ rt.encoder = load_student(args.encoder, rt.device)
+ rt.ctl = load_controller(args.controller, rt.device) if args.controller else Controller(rt.encoder.cfg["out_dim"]).to(rt.device).eval()
+ sess = rt.new_session()
+ rng = np.random.default_rng(0)
+ times = []
+ for _ in range(args.frames):
+ a, b = (rng.standard_normal(FRAME).astype(np.float32) * 0.05 for _ in range(2))
+ t0 = time.perf_counter()
+ rt.step(sess, a, b)
+ times.append((time.perf_counter() - t0) * 1000)
+ steady = np.array(times[50:])
+ print(f"controller step over {len(steady)} frames: mean {steady.mean():.2f} ms, p50 {np.percentile(steady, 50):.2f} ms, "
+ f"p99 {np.percentile(steady, 99):.2f} ms; first 400 frames mean {np.mean(times[50:400]):.2f} ms, last 100 mean {np.mean(times[-100:]):.2f} ms")
+ print(f"one thread could carry about {1000 / steady.mean() / 12.5:.1f} sessions")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/box_setup.sh b/tools/box_setup.sh
new file mode 100644
index 0000000000000000000000000000000000000000..c99c0776433d37cef81adc8daeb202e7203a6a4b
--- /dev/null
+++ b/tools/box_setup.sh
@@ -0,0 +1,24 @@
+#!/usr/bin/env bash
+# One-time setup on the training machine. Everything lives under /data/train; the host
+# system is not changed (no apt, nothing outside /data/train except Docker's own image store).
+set -euo pipefail
+ROOT=/data/train
+export HF_HOME=$ROOT/hf PIP_CACHE_DIR=$ROOT/pipcache HF_HUB_DISABLE_TELEMETRY=1
+cd $ROOT
+[ -d venv ] || python3 -m venv venv
+. venv/bin/activate
+pip install -q --upgrade pip
+pip install -q torch torchaudio numpy scipy aiohttp librosa safetensors huggingface_hub soundfile s3tokenizer onnxruntime hyperpyyaml
+# Kokoro without its GPL / LGPL dependencies: tools/kokoro_stubs stands in for them
+pip install -q --no-deps kokoro misaki
+pip install -q spacy loguru addict regex transformers
+echo "$ROOT/duplex/tools/kokoro_stubs" > "$(python -c 'import sysconfig; print(sysconfig.get_paths()["purelib"])')/duplex_kokoro_stubs.pth"
+python -c 'import torch; print("torch", torch.__version__, "cuda", torch.version.cuda, torch.cuda.get_device_name(3)); x = torch.randn(2048, 2048, device="cuda:3"); print("gpu matmul ok", float((x @ x).abs().mean()))'
+[ -d src/Step-Audio2 ] || git clone -q https://github.com/stepfun-ai/Step-Audio2 src/Step-Audio2
+echo "Step-Audio2 commit $(git -C src/Step-Audio2 rev-parse HEAD)"
+hf download stepfun-ai/Step-Audio-2-mini --include 'token2wav/*' --local-dir models/Step-Audio-2-mini > /dev/null
+echo TOKEN2WAV_DONE
+hf download stepfun-ai/Step-Audio-R1.1 --local-dir models/Step-Audio-R1.1 > /dev/null &
+hf download Qwen/Qwen3-32B --local-dir models/Qwen3-32B > /dev/null &
+wait
+echo SETUP_DONE
diff --git a/tools/budget_arm.sh b/tools/budget_arm.sh
new file mode 100644
index 0000000000000000000000000000000000000000..a641fc648f1db83e2b02c7554d2874cb6a08a442
--- /dev/null
+++ b/tools/budget_arm.sh
@@ -0,0 +1,7 @@
+#!/usr/bin/env bash
+# One thinking-budget arm on one baseline copy: tools/budget_arm.sh [brief]
+cd /data/train/duplex && . /data/train/venv/bin/activate
+export OMP_NUM_THREADS=4
+g=$1; p=$([ "$g" = 0 ] && echo 9999 || echo 999$g)
+python -u -m eval.eval_bba_budget --api-url http://127.0.0.1:$p/v1/chat/completions --budget "$2" ${3:+--brief} \
+ > "/data/train/logs/budget_$2${3:+_brief}.log" 2>&1
diff --git a/tools/chain.sh b/tools/chain.sh
new file mode 100644
index 0000000000000000000000000000000000000000..ec47be73c61b51618a58f0e888fe8ec644352b71
--- /dev/null
+++ b/tools/chain.sh
@@ -0,0 +1,14 @@
+#!/usr/bin/env bash
+# Start the with-controller evaluations when controller training has ended and the
+# think-then-speak run no longer shares the baseline (or at 02:04Z at the latest: the
+# sign-in certificate ends at 02:51Z and the results must be copied off before then).
+cd /data/train/duplex
+until [ -f runs/ctl_run_end ] || [ -f runs/ctl_run_failed ]; do sleep 3; done
+[ -f runs/ctl_run_end ] || exit 1
+until [ -f runs/think_speak_end ] || [ "$(date -u +%H%M)" -ge 0204 ]; do sleep 3; done
+if [ ! -f runs/think_speak_end ]; then
+ tmux kill-session -t thinkeval 2>/dev/null
+ echo "stopped at $(date -u +%T) with $(ls eval/results/bba_think_speak/manual | grep -c json) of 100 questions done" > runs/think_speak_stopped
+fi
+tmux kill-session -t think 2>/dev/null
+bash tools/eval_run.sh
diff --git a/tools/check_licenses.py b/tools/check_licenses.py
new file mode 100644
index 0000000000000000000000000000000000000000..4fee629f9a7e429f5df2d1ae2fa054228819805f
--- /dev/null
+++ b/tools/check_licenses.py
@@ -0,0 +1,45 @@
+"""Re-read the licence of every model and dataset this repository uses from the Hugging Face
+API, and the licence of every installed Python package from its own metadata. Prints one
+line per item and exits 1 if a model or dataset is not Apache-2.0 or MIT.
+
+Packages are listed, not failed: docs/licenses.md says which non-Apache/MIT ones are
+tolerated and why. Copyleft ones are marked.
+
+ python -m tools.check_licenses
+"""
+import json
+import sys
+import urllib.request
+from importlib import metadata
+
+MODELS = ["stepfun-ai/Step-Audio-R1.1", "stepfun-ai/Step-Audio-2-mini", "hexgrad/Kokoro-82M", "Qwen/Qwen3-32B"]
+DATASETS = ["ArtificialAnalysis/big_bench_audio"]
+ALLOWED = {"apache-2.0", "mit"}
+
+
+def hf_license(kind, repo):
+ with urllib.request.urlopen(f"https://huggingface.co/api/{kind}/{repo}", timeout=30) as r:
+ tags = json.load(r).get("tags", [])
+ return next((t.split(":", 1)[1] for t in tags if t.startswith("license:")), None)
+
+
+def main():
+ bad = 0
+ for kind, repos in (("models", MODELS), ("datasets", DATASETS)):
+ for repo in repos:
+ lic = hf_license(kind, repo)
+ ok = lic in ALLOWED
+ bad += not ok
+ print(f"{'ok ' if ok else 'FAIL'} {kind[:-1]:8s} {repo:42s} {lic}")
+ print()
+ for dist in sorted(metadata.distributions(), key=lambda d: (d.metadata["Name"] or "").lower()):
+ m = dist.metadata
+ lic = m.get("License-Expression") or " / ".join(c.split(" :: ")[-1] for c in m.get_all("Classifier") or [] if c.startswith("License")) \
+ or " ".join((m.get("License") or "").split())[:60] or "not stated"
+ mark = "COPYLEFT" if any(w in lic.upper() for w in ("GPL", "AGPL")) else ""
+ print(f" package {m['Name']:42s} {lic} {mark}")
+ sys.exit(1 if bad else 0)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/decision_sweep.py b/tools/decision_sweep.py
new file mode 100644
index 0000000000000000000000000000000000000000..834d0850ad134b4e2c921a6404e153911fcf4272
--- /dev/null
+++ b/tools/decision_sweep.py
@@ -0,0 +1,66 @@
+"""Would a stricter decision rule fix the early starts? CPU only.
+
+Uses the saved per-frame probabilities of the held-out run (eval/results/controller/pred)
+and the recorded events. Rule: START fires in a frame when p(START) >= threshold
+("argmax" = START is the most likely label, which is what the endpoint used).
+
+The thresholds are compared on the same held-out set they would be chosen on, so the
+best row is optimistic. Frames after the labelled START window cannot be judged offline
+(the agent's own audio starts there), so a rule that needs several frames in a row is
+not evaluated.
+
+ python -m tools.decision_sweep --data data/out/dataset --pred eval/results/controller/pred --out eval/results/controller/decision_sweep.json
+"""
+import argparse
+import json
+from pathlib import Path
+
+import numpy as np
+
+from duplex.spec import FRAME, START, write_json
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--data", required=True)
+ ap.add_argument("--pred", required=True)
+ ap.add_argument("--out", required=True)
+ args = ap.parse_args()
+ data = Path(args.data)
+ rules = ["argmax", 0.5, 0.7, 0.9, 0.95, 0.99]
+ tally = {str(r): {"pause_quiet": 0, "pauses": 0, "turn_end_caught": 0, "turn_ends": 0, "turn_clean": 0, "turns": 0, "delays": []} for r in rules}
+ for it in json.loads((data / "index_test.json").read_text()):
+ probs = np.load(Path(args.pred) / f"{it['id']}.npz")["probs"].astype(np.float32)
+ events = json.loads((data / "meta" / f"{it['id']}.json").read_text())["events"]
+ for r in rules:
+ fire = probs.argmax(-1) == START if r == "argmax" else probs[:, START] >= r
+ t = tally[str(r)]
+ for e in events:
+ if e["type"] == "pause" and e["f1"] > e["f0"]:
+ t["pauses"] += 1
+ t["pause_quiet"] += not fire[e["f0"]: e["f1"]].any()
+ elif e["type"] == "start":
+ hit = np.nonzero(fire[e["f0"]: e["f1"]])[0]
+ t["turn_ends"] += 1
+ t["turn_end_caught"] += len(hit) > 0
+ if len(hit):
+ t["delays"].append((int(hit[0]) + 1) * 80)
+ elif e["type"] == "caller_turn": # the whole turn, pauses included: no START before the caller has finished
+ t["turns"] += 1
+ t["turn_clean"] += not fire[e["start"] // FRAME: e["end"] // FRAME].any()
+ out = {}
+ for r, t in tally.items():
+ out[r] = {
+ "pause_handling": t["pause_quiet"] / t["pauses"], "turn_end_caught": t["turn_end_caught"] / t["turn_ends"],
+ "caller_turns_with_no_start_before_their_end": t["turn_clean"] / t["turns"],
+ "start_delay_ms_p50": float(np.median(t["delays"])) if t["delays"] else None,
+ "counts": {k: t[k] for k in ("pause_quiet", "pauses", "turn_end_caught", "turn_ends", "turn_clean", "turns")},
+ }
+ print(f"p(START) >= {r:>6}: pauses kept quiet {t['pause_quiet']}/{t['pauses']} ({out[r]['pause_handling']:.3f}) | turn ends caught "
+ f"{t['turn_end_caught']}/{t['turn_ends']} ({out[r]['turn_end_caught']:.3f}) | whole caller turns with no early START "
+ f"{t['turn_clean']}/{t['turns']} ({out[r]['caller_turns_with_no_start_before_their_end']:.3f}) | delay p50 {out[r]['start_delay_ms_p50']} ms")
+ write_json(args.out, out)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/eval_run.sh b/tools/eval_run.sh
new file mode 100644
index 0000000000000000000000000000000000000000..e443fe3da09c5726cdcb564bec28d5c066bae2c7
--- /dev/null
+++ b/tools/eval_run.sh
@@ -0,0 +1,11 @@
+#!/usr/bin/env bash
+# After controller training: the endpoint with the controller, then the benchmark and the
+# latency test with the controller deciding.
+cd /data/train/duplex && . /data/train/venv/bin/activate
+export OMP_NUM_THREADS=8
+tmux kill-session -t server 2>/dev/null; sleep 2
+tmux new-session -d -s server "bash tools/server_run.sh controller > /data/train/logs/server_ctl.log 2>&1"
+for i in $(seq 1 60); do ss -ltn 2>/dev/null | grep -q ":8765 " && break; sleep 2; done
+python -u -m eval.eval_bba --url http://127.0.0.1:8765/ws --data eval/data/bba --out eval/results/bba --modes controller --concurrency 4 > /data/train/logs/bba_controller.log 2>&1
+python -u -m eval.eval_latency --url http://127.0.0.1:8765/ws --data data/out/dataset --out eval/results/latency --modes controller --turns 100 --concurrency 3 > /data/train/logs/latency_controller.log 2>&1
+date -u +%FT%TZ > runs/eval_run_end
diff --git a/tools/export_checkpoints.py b/tools/export_checkpoints.py
new file mode 100644
index 0000000000000000000000000000000000000000..693eea73a243fc0d147802479c10da9c58f41fec
--- /dev/null
+++ b/tools/export_checkpoints.py
@@ -0,0 +1,35 @@
+"""Training checkpoints (.pt) -> the published form: .safetensors and .json (cfg and training step).
+
+ python -m tools.export_checkpoints runs/encoder/final.pt=encoder runs/controller/final.pt=controller --out release/checkpoints
+"""
+import argparse
+import json
+from pathlib import Path
+
+import torch
+from safetensors.torch import save_file
+
+from duplex.streaming import read_checkpoint
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("pairs", nargs="+", help="=")
+ ap.add_argument("--out", required=True)
+ args = ap.parse_args()
+ out = Path(args.out)
+ out.mkdir(parents=True, exist_ok=True)
+ for pair in args.pairs:
+ src, name = pair.split("=")
+ ck = torch.load(src, map_location="cpu", weights_only=True)
+ save_file({k: v.contiguous() for k, v in ck["model"].items()}, str(out / f"{name}.safetensors"))
+ meta = {"cfg": ck["cfg"], "training_step": ck["extra"].get("step"), "tensor_values": sum(v.numel() for v in ck["model"].values())}
+ (out / f"{name}.json").write_text(json.dumps(meta, indent=1) + "\n", encoding="utf-8")
+ cfg, state = read_checkpoint(out / f"{name}.safetensors") # read it back: same cfg, same tensors
+ assert cfg == ck["cfg"] and state.keys() == ck["model"].keys()
+ assert all(torch.equal(state[k], ck["model"][k]) for k in state), name
+ print(f"{name}: {meta['tensor_values']:,} values in {len(state)} tensors, read back identical")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/finish_run3.sh b/tools/finish_run3.sh
new file mode 100644
index 0000000000000000000000000000000000000000..90815fdbec494e81775be8799e9d045760671c8d
--- /dev/null
+++ b/tools/finish_run3.sh
@@ -0,0 +1,17 @@
+#!/usr/bin/env bash
+# End of the third run: wait for round four, free seven GPUs, let Whisper check what was spoken on the
+# eighth, then free that one too.
+cd /data/train/duplex && . /data/train/venv/bin/activate
+while tmux has-session -t run3 2>/dev/null; do sleep 5; done
+date -u +%FT%TZ > runs/run3_round4_end
+for g in 0 1 2 3 4 5 6; do sudo docker stop duplex-vllm-$g > /dev/null & done; wait
+python -m tools.show_run3 eval/results/bba3 reference_again lead_gate reference_sentence lead_gate_sentence
+for a in reference_sentence lead_gate_sentence; do python -m tools.wer_pairs eval/results/bba3/$a/judge eval/results/wer_sentence/$a; done
+HF_HOME=/data/train/hf CUDA_VISIBLE_DEVICES=7 python -m eval.eval_wer --pairs eval/results/wer_sentence/reference_sentence eval/results/wer_sentence/lead_gate_sentence --out eval/results/wer_sentence 2>&1 | tail -16
+python -m tools.heard_accuracy eval/results/wer_sentence/clips.json eval/results/bba3/reference_sentence/judge=eval/results/wer_sentence/reference_sentence eval/results/bba3/lead_gate_sentence/judge=eval/results/wer_sentence/lead_gate_sentence
+sudo docker stop duplex-vllm-7 > /dev/null
+for s in $(tmux ls 2>/dev/null | cut -d: -f1 | grep -E "^(vllm|bsrv|srv|warm|lead|r3b)"); do tmux kill-session -t "$s" 2>/dev/null; done
+sleep 5
+date -u +%FT%TZ | tee runs/run3_end
+nvidia-smi --query-gpu=index,memory.used --format=csv,noheader | tr "\n" ";"; echo
+sudo docker ps -a --format "{{.Names}} {{.Status}}"
diff --git a/tools/heard_accuracy.py b/tools/heard_accuracy.py
new file mode 100644
index 0000000000000000000000000000000000000000..2307dda0b4fefb0a927072b507c89baa6808aadd
--- /dev/null
+++ b/tools/heard_accuracy.py
@@ -0,0 +1,35 @@
+"""How many answers are right as HEARD, not as written.
+
+The benchmark arms are scored on the reply's text (eval/eval_bba.py). Here Whisper's transcript of the
+reply's audio (eval/eval_wer.py, clips.json) is searched for the answer in the same way and compared
+with the official answer. Whisper makes errors of its own, most of all on a lone short word, so this
+is a lower bound on what a person would hear.
+
+ python -m tools.heard_accuracy eval/results/wer_answers/clips.json eval/results/bba3/reference_again/judge=eval/results/wer_answers/reference_again ...
+"""
+import json
+import sys
+from pathlib import Path
+
+from eval.eval_bba import parse_answer
+
+groups = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8"))
+print("| Arm | Replies with audio | Right in the text | Right as heard | Text right, not heard | Reply audio, median (s) |")
+print("|---|---|---|---|---|---|")
+for pair in sys.argv[2:]:
+ arm, key = pair.split("=")
+ heard = {c["clip"].replace(".wav", ""): " ".join(c["hyp"]) for c in groups[key]}
+ rows = [json.loads(p.read_text(encoding="utf-8")) for p in sorted(Path(arm).glob("q_*.json"))]
+ rows = [r for r in rows if f"q_{r['id']}" in heard]
+ ok_text = [r["correct"] for r in rows]
+ ok_heard = []
+ for r in rows:
+ answer, official = parse_answer(heard[f"q_{r['id']}"], r["official_answer"])
+ ok_heard.append(answer is not None and answer == official)
+ import wave
+ secs = []
+ for r in rows:
+ with wave.open(str(Path(arm) / f"q_{r['id']}.wav")) as w:
+ secs.append(w.getnframes() / w.getframerate())
+ secs.sort()
+ print(f"| {Path(arm).parent.name} | {len(rows)} | {sum(ok_text)} | {sum(ok_heard)} | {sum(t and not h for t, h in zip(ok_text, ok_heard))} | {secs[len(secs) // 2]:.2f} |")
diff --git a/tools/held_out_baselines.py b/tools/held_out_baselines.py
new file mode 100644
index 0000000000000000000000000000000000000000..1c57b442a4ffdd787b739bcf687328b9c86838a2
--- /dev/null
+++ b/tools/held_out_baselines.py
@@ -0,0 +1,89 @@
+"""Two CPU-only readings of the held-out set that put the controller's numbers in context.
+
+1. Pause handling by what came before the pause. About half of the data's pauses follow
+ a complete sentence, which nobody could tell from a finished turn. "Cut off" pauses
+ end on a function word (and, but, to, the, I ...): clearly unfinished.
+2. Overlap handling against the plain rule the endpoint uses without a controller:
+ 240 ms of caller speech while the reply plays means STOP. That rule catches every
+ interruption and also stops for every "mm-hm"; the controller is there to tell them apart.
+
+ python -m tools.held_out_baselines --data data/out/dataset --dialogues data/out/dialogues.jsonl \
+ --pred eval/results/controller/pred --out eval/results/controller/held_out_baselines.json
+"""
+import argparse
+import json
+from pathlib import Path
+
+import numpy as np
+
+from duplex.spec import CALLER, FRAME, START, STOP, read_jsonl, read_wav, write_json
+from eval.eval_judge import cut_off, pause_prefixes
+
+
+def rate(hits, total):
+ return {"correct": int(hits), "total": int(total), "rate": hits / total if total else None}
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--data", required=True)
+ ap.add_argument("--dialogues", required=True)
+ ap.add_argument("--pred", required=True)
+ ap.add_argument("--out", required=True)
+ ap.add_argument("--vad-db", type=float, default=-45.0)
+ args = ap.parse_args()
+
+ data = Path(args.data)
+ dialogues = {d["id"]: d for d in read_jsonl(args.dialogues)}
+ ctl = {"cut_off": [0, 0], "other": [0, 0]}
+ silence_rule = {"cut_off": [0, 0], "other": [0, 0]}
+ vad_int, vad_bc = [0, 0], [0, 0]
+ ctl_int, ctl_bc = [0, 0], [0, 0]
+ for it in json.loads((data / "index_test.json").read_text()):
+ events = json.loads((data / "meta" / f"{it['id']}.json").read_text())["events"]
+ pred = np.load(Path(args.pred) / f"{it['id']}.npz")["pred"]
+ pauses = [e for e in events if e["type"] == "pause"]
+ prefixes = pause_prefixes(dialogues[it["id"]])
+ assert len(prefixes) == len(pauses), it["id"]
+ for e, before in zip(pauses, prefixes):
+ if e["f1"] <= e["f0"]:
+ continue
+ group = "cut_off" if cut_off(before) else "other"
+ ctl[group][0] += not (pred[e["f0"]: e["f1"]] == START).any()
+ ctl[group][1] += 1
+ silence_rule[group][0] += (e["end"] - e["start"]) / 16000 < 0.64 # a perfect voice detector with a 640 ms rule
+ silence_rule[group][1] += 1
+
+ wav, _ = read_wav(data / "audio" / f"{it['id']}.wav")
+ x = wav[: it["n_frames"] * FRAME, CALLER].reshape(-1, FRAME)
+ voiced = 20 * np.log10(np.sqrt(np.mean(x ** 2, axis=1)) + 1e-9) > args.vad_db
+ run = np.zeros(len(voiced), dtype=np.int32)
+ for i, v in enumerate(voiced):
+ run[i] = (run[i - 1] + 1 if i else 1) if v else 0
+ for e in events:
+ if e["type"] not in ("interrupt", "backchannel") or e["f1"] <= e["f0"]:
+ continue
+ # the rule may fire up to two frames after the labelled window (it needs three voiced frames in a row)
+ fired = bool((run[e["f0"]: e["f1"] + 2] >= 3).any())
+ ctl_stop = bool((pred[e["f0"]: e["f1"]] == STOP).any())
+ if e["type"] == "interrupt":
+ vad_int[0] += fired; vad_int[1] += 1; ctl_int[0] += ctl_stop; ctl_int[1] += 1
+ else:
+ vad_bc[0] += not fired; vad_bc[1] += 1; ctl_bc[0] += not ctl_stop; ctl_bc[1] += 1
+
+ result = {
+ "pause_handling": {
+ "controller": {g: rate(*v) for g, v in ctl.items()},
+ "fixed_640ms_silence_rule_with_perfect_voice_detector": {g: rate(*v) for g, v in silence_rule.items()},
+ },
+ "overlaps": {
+ "interruption_caught": {"controller": rate(*ctl_int), "plain_rule_240ms_of_caller_speech": rate(*vad_int)},
+ "backchannel_not_interrupted": {"controller": rate(*ctl_bc), "plain_rule_240ms_of_caller_speech": rate(*vad_bc)},
+ },
+ }
+ write_json(args.out, result)
+ print(json.dumps(result, indent=1))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/judge_arm.sh b/tools/judge_arm.sh
new file mode 100644
index 0000000000000000000000000000000000000000..ae0a00cea9495bbc2706946607b185df69d8acea
--- /dev/null
+++ b/tools/judge_arm.sh
@@ -0,0 +1,15 @@
+#!/usr/bin/env bash
+# One endpoint with judge endpointing on one baseline copy, then the held-out latency test and the benchmark through it.
+# tools/judge_arm.sh [think budget] results under eval/results/judge_[_think]/
+cd /data/train/duplex && . /data/train/venv/bin/activate
+export OMP_NUM_THREADS=8
+g=$1; prompt=$2; think=${3:-}
+name=judge_${prompt}${think:+_think$think}
+port=877$g; vport=$([ "$g" = 0 ] && echo 9999 || echo 999$g)
+tmux kill-session -t srv$g 2>/dev/null; sleep 1
+tmux new-session -d -s srv$g "GPU=$g PORT=$port VLLM_PORT=$vport THINK_TOKENS=$think SERVER_ARGS='--judge-prompt $prompt' bash tools/server_run.sh ${think:+think} > /data/train/logs/server_$name.log 2>&1"
+for i in $(seq 1 60); do ss -ltn 2>/dev/null | grep -q ":$port " && break; sleep 2; done
+python -u -m eval.eval_latency --url http://127.0.0.1:$port/ws --data data/out/dataset --out eval/results/$name/latency --modes judge --turns 100 --concurrency 3 > /data/train/logs/latency_$name.log 2>&1
+python -u -m eval.eval_bba --url http://127.0.0.1:$port/ws --data eval/data/bba --out eval/results/$name/bba --modes judge --concurrency 3 --max-wait-s 120 > /data/train/logs/bba_$name.log 2>&1
+tmux kill-session -t srv$g 2>/dev/null
+date -u +%FT%TZ > runs/${name}_end
diff --git a/tools/kokoro_stubs/README.md b/tools/kokoro_stubs/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..570137ff2316908a7e785f424b2516b62c1a987d
--- /dev/null
+++ b/tools/kokoro_stubs/README.md
@@ -0,0 +1,6 @@
+Stand-ins for three packages that Kokoro's English text front end imports but that are
+not Apache-2.0 or MIT: num2words (LGPL-2.1), phonemizer-fork (GPL-3.0-or-later) and
+espeakng-loader (a wrapper around espeak-ng, GPL-3.0). With these stand-ins on the path,
+none of that code is installed. The effect: words outside Kokoro's own dictionary are
+skipped instead of being spelled out by espeak-ng, and a digit in the text raises an
+error (the dialogue writer rejects digits, so it does not happen).
diff --git a/tools/kokoro_stubs/espeakng_loader/__init__.py b/tools/kokoro_stubs/espeakng_loader/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..44e772a71a5faac510a91e62614ab4ee68b4b3de
--- /dev/null
+++ b/tools/kokoro_stubs/espeakng_loader/__init__.py
@@ -0,0 +1,9 @@
+"""Stand-in for espeakng-loader. espeak-ng (GPL-3.0) is not installed on purpose."""
+
+
+def get_library_path():
+ return ""
+
+
+def get_data_path():
+ return ""
diff --git a/tools/kokoro_stubs/num2words/__init__.py b/tools/kokoro_stubs/num2words/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2503ebc9f4e51eddf4c3cc4e8df8887094f40a40
--- /dev/null
+++ b/tools/kokoro_stubs/num2words/__init__.py
@@ -0,0 +1,5 @@
+"""Stand-in for num2words (LGPL-2.1). Never called: the dialogue text contains no digits."""
+
+
+def num2words(*args, **kwargs):
+ raise RuntimeError("num2words stand-in called: the text contains a digit, which data/gen_dialogues.py should have rejected")
diff --git a/tools/kokoro_stubs/phonemizer/__init__.py b/tools/kokoro_stubs/phonemizer/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..637c896be7759b282049124a34ef9c719c4883fa
--- /dev/null
+++ b/tools/kokoro_stubs/phonemizer/__init__.py
@@ -0,0 +1,2 @@
+"""Stand-in for phonemizer-fork (GPL-3.0-or-later), which is not installed on purpose."""
+from . import backend # noqa: F401
diff --git a/tools/kokoro_stubs/phonemizer/backend/__init__.py b/tools/kokoro_stubs/phonemizer/backend/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..7901d844377cd0436b6111ce79c2fa8a8668788d
--- /dev/null
+++ b/tools/kokoro_stubs/phonemizer/backend/__init__.py
@@ -0,0 +1,4 @@
+class EspeakBackend:
+ def __init__(self, *args, **kwargs):
+ # kokoro catches this and runs without the espeak fallback: unknown words are skipped
+ raise RuntimeError("espeak-ng is not installed on purpose (GPL-3.0)")
diff --git a/tools/kokoro_stubs/phonemizer/backend/espeak/__init__.py b/tools/kokoro_stubs/phonemizer/backend/espeak/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tools/kokoro_stubs/phonemizer/backend/espeak/wrapper.py b/tools/kokoro_stubs/phonemizer/backend/espeak/wrapper.py
new file mode 100644
index 0000000000000000000000000000000000000000..9e6ef791a1b3e9178e0701989093b358bb1d13a2
--- /dev/null
+++ b/tools/kokoro_stubs/phonemizer/backend/espeak/wrapper.py
@@ -0,0 +1,8 @@
+class EspeakWrapper:
+ @classmethod
+ def set_library(cls, *args, **kwargs):
+ pass
+
+ @classmethod
+ def set_data_path(cls, *args, **kwargs):
+ pass
diff --git a/tools/latency_arm.sh b/tools/latency_arm.sh
new file mode 100644
index 0000000000000000000000000000000000000000..1520734812f4dc13c6a3d8d3ea83cfb195f60d19
--- /dev/null
+++ b/tools/latency_arm.sh
@@ -0,0 +1,16 @@
+#!/usr/bin/env bash
+# One endpoint on one baseline copy and the held-out latency test through it.
+# tools/latency_arm.sh [server_run.sh mode] [extra server args]
+# Decoder settings come from the environment (FIRST_CHUNK MIN_CHUNK LOW_WATER WORKERS FP16 DECODER_GPU).
+cd /data/train/duplex && . /data/train/venv/bin/activate
+export OMP_NUM_THREADS=8
+g=$1; name=$2; mode=$3; srv=${4:-}; extra=${5:-}
+[ "$srv" = "-" ] && srv=""
+port=877$g; vport=$([ "$g" = 0 ] && echo 9999 || echo 999$g)
+tmux kill-session -t srv$g 2>/dev/null; sleep 1
+tmux new-session -d -s srv$g "FIRST_CHUNK=${FIRST_CHUNK:-25} MIN_CHUNK=${MIN_CHUNK:-25} LOW_WATER=${LOW_WATER:-0} WORKERS=${WORKERS:-1} THINK_TOKENS=${THINK_TOKENS:-2048} GPU=$g PORT=$port VLLM_PORT=$vport SERVER_ARGS='$extra' bash tools/server_run.sh $srv > /data/train/logs/server_lat_$name.log 2>&1"
+for i in $(seq 1 90); do ss -ltn 2>/dev/null | grep -q ":$port " && break; sleep 2; done
+python -u -m eval.eval_latency --url http://127.0.0.1:$port/ws --data data/out/dataset --out eval/results/${OUT:-latency2}/$name --modes $mode --turns "${TURNS:-100}" --concurrency "${CONC:-3}" > /data/train/logs/lat_$name.log 2>&1
+[ -n "${BBA:-}" ] && python -u -m eval.eval_bba --url http://127.0.0.1:$port/ws --data eval/data/bba --out eval/results/bba2/$name --modes $mode --concurrency 3 --max-wait-s 150 > /data/train/logs/bba2_$name.log 2>&1
+tmux kill-session -t srv$g 2>/dev/null
+date -u +%FT%TZ > runs/lat_${name}_end
diff --git a/tools/loadtest_cfg.sh b/tools/loadtest_cfg.sh
new file mode 100644
index 0000000000000000000000000000000000000000..50e049a8f7d083a3bfd181563306cad9e2ab0036
--- /dev/null
+++ b/tools/loadtest_cfg.sh
@@ -0,0 +1,14 @@
+#!/usr/bin/env bash
+# One load test of the endpoint on one GPU (its own baseline copy), decoder settings from the environment:
+# GPU (0) FIRST_CHUNK MIN_CHUNK LOW_WATER WORKERS (released recipe, one decoder) DECODER_GPU (= GPU) PROMPT (the 10 s prompt)
+# tools/loadtest_cfg.sh [levels] results in eval/results/loadtest_/
+cd /data/train/duplex && . /data/train/venv/bin/activate
+export OMP_NUM_THREADS=8
+g=${GPU:-0}; port=876$g; vport=$([ "$g" = 0 ] && echo 9999 || echo 999$g)
+tmux kill-session -t server$g 2>/dev/null; sleep 2
+tmux new-session -d -s server$g "GPU=$g PORT=$port VLLM_PORT=$vport FIRST_CHUNK=${FIRST_CHUNK:-25} MIN_CHUNK=${MIN_CHUNK:-25} LOW_WATER=${LOW_WATER:-0} WORKERS=${WORKERS:-1} DECODER_GPU=${DECODER_GPU:-$g} PROMPT=${PROMPT:-runs/prompt_af_heart.wav} bash tools/server_run.sh > /data/train/logs/server_$1.log 2>&1"
+for i in $(seq 1 90); do ss -ltn 2>/dev/null | grep -q ":$port " && break; sleep 2; done
+python -u -m serving.loadtest --url http://127.0.0.1:$port/ws --wav-dir eval/data/bba --out eval/results/loadtest_$1 \
+ --levels "${2:-1,2,4,8}" --turns 3 --save-audio eval/results/loadtest_$1/audio > /data/train/logs/loadtest_$1.log 2>&1
+tmux kill-session -t server$g 2>/dev/null
+date -u +%FT%TZ > runs/loadtest_$1_end
diff --git a/tools/loadtest_report.py b/tools/loadtest_report.py
new file mode 100644
index 0000000000000000000000000000000000000000..761457b0bc69584a485d74c41c3b67df9154b025
--- /dev/null
+++ b/tools/loadtest_report.py
@@ -0,0 +1,28 @@
+"""Per level of a load test: where the time goes (first token, first audio, generation speed).
+
+ python -m tools.loadtest_report eval/results/loadtest
+"""
+import json
+import sys
+from pathlib import Path
+
+import numpy as np
+
+
+def main():
+ for path in sorted(Path(sys.argv[1]).glob("level_*.json"), key=lambda p: int(p.stem.split("_")[1])):
+ d = json.loads(path.read_text())
+ turns = [t for t in d["turns"] if not t["error"] and t["ttfa_ms"] is not None]
+ if not turns:
+ print(path.stem, "no finished turns", d["summary"]["errors"][:2])
+ continue
+ col = lambda k: np.array([t[k] for t in turns if t[k] is not None], dtype=float)
+ s = d["summary"]
+ print(f"{path.stem:9s} turns {len(turns):2d}/{s['turns']:2d} | first token ms p50 {np.median(col('first_token_ms')):6.0f} max {col('first_token_ms').max():6.0f}"
+ f" | first audio ms p50 {np.median(col('ttfa_ms')):6.0f} max {col('ttfa_ms').max():6.0f}"
+ f" | generation/audio time p50 {np.median(col('real_time_factor')):.2f} max {col('real_time_factor').max():.2f}"
+ f" | underruns {int(col('underruns').sum())} | longest gap ms {col('max_gap_ms').max():.0f} | pass {s['pass']}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/make_prompt.py b/tools/make_prompt.py
new file mode 100644
index 0000000000000000000000000000000000000000..a48d0c3e916ed5d705942b1449ab620f55f2525a
--- /dev/null
+++ b/tools/make_prompt.py
@@ -0,0 +1,33 @@
+"""Make the voice prompt for the released token2wav decoder from a synthetic voice
+(a Kokoro voice pack), so the reply voice is not conditioned on a recording of a person.
+
+ python -m tools.make_prompt --voice af_heart --out runs/prompt_af_heart.wav
+"""
+import argparse
+
+import torch
+
+from duplex.spec import write_wav
+
+TEXT = ("Hello, and thanks for calling. I can help you with bookings, questions about your account, "
+ "and most everyday requests. Tell me what you need, and we will sort it out together.")
+
+
+SHORT_TEXT = "Hello, and thanks for calling. How can I help you today?"
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--voice", default="af_heart")
+ ap.add_argument("--short", action="store_true", help="one sentence (about 3.5 s): every decode call attends to the whole prompt")
+ ap.add_argument("--out", required=True)
+ args = ap.parse_args()
+ from kokoro import KPipeline
+ pipe = KPipeline(lang_code=args.voice[0], repo_id="hexgrad/Kokoro-82M", device="cpu")
+ audio = torch.cat([torch.as_tensor(a).float().flatten() for _, _, a in pipe(SHORT_TEXT if args.short else TEXT, voice=args.voice, speed=1.0) if a is not None])
+ write_wav(args.out, audio.numpy(), 24000)
+ print(f"{args.out}: {len(audio) / 24000:.1f} s, voice {args.voice}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/pick_subset.py b/tools/pick_subset.py
new file mode 100644
index 0000000000000000000000000000000000000000..b85ef208e687f573234b5d9eae4f102c1c7fcfd1
--- /dev/null
+++ b/tools/pick_subset.py
@@ -0,0 +1,17 @@
+"""Copy a few questions of the benchmark subset into another folder (smoke tests).
+
+ python -m tools.pick_subset eval/data/bba eval/data/bba4 0 30 55 80
+"""
+import json
+import shutil
+import sys
+from pathlib import Path
+
+src, dst = Path(sys.argv[1]), Path(sys.argv[2])
+dst.mkdir(parents=True, exist_ok=True)
+subset = json.loads((src / "subset.json").read_text())
+pick = [subset[int(i)] for i in sys.argv[3:]]
+(dst / "subset.json").write_text(json.dumps(pick))
+for q in pick:
+ shutil.copy(src / f"q_{q['id']}.wav", dst / f"q_{q['id']}.wav")
+print(len(pick), "questions in", dst)
diff --git a/tools/probe_report.py b/tools/probe_report.py
new file mode 100644
index 0000000000000000000000000000000000000000..bfb3caac7c6127d990ead06fb57d9fe36a86a26e
--- /dev/null
+++ b/tools/probe_report.py
@@ -0,0 +1,40 @@
+"""Summarise what the baseline streamed in each probe run (eval/results/probe/raw_*.jsonl):
+where text and audio tokens arrive, and when.
+
+ python -m tools.probe_report eval/results/probe
+"""
+import json
+import re
+import sys
+from pathlib import Path
+
+AUDIO = re.compile(r"")
+
+
+def main():
+ for path in sorted(Path(sys.argv[1]).glob("raw_*.jsonl")):
+ rows = [json.loads(line) for line in open(path, encoding="utf-8")]
+ if not rows:
+ print(f"== {path.name}: empty")
+ continue
+ tts = lambda r, k: (r["delta"].get("tts_content") or {}).get(k) or ""
+ text = "".join(tts(r, "tts_text") or r["delta"].get("content") or "" for r in rows)
+ in_tts = [(r["t"], len(AUDIO.findall(tts(r, "tts_audio")))) for r in rows]
+ in_content = sum(len(AUDIO.findall(r["delta"].get("content") or "")) for r in rows)
+ n_audio = sum(n for _, n in in_tts)
+ first_audio = next((t for t, n in in_tts if n), None)
+ t25 = None
+ seen = 0
+ for t, n in in_tts:
+ seen += n
+ if seen >= 28 and t25 is None:
+ t25 = t
+ print(f"== {path.name}: {len(rows)} chunks, first at {rows[0]['t']} s, last at {rows[-1]['t']} s")
+ print(f" audio tokens in tts_audio: {n_audio} (first at {first_audio} s, 28th at {t25} s); audio tokens inside content: {in_content}")
+ print(f" delta keys: {sorted({k for r in rows for k in r['delta']})}")
+ print(f" text[:300]: {text[:300]!r}")
+ print(f" text[-200:]: {text[-200:]!r}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/run3.sh b/tools/run3.sh
new file mode 100644
index 0000000000000000000000000000000000000000..819f0a712781aadff6c2416631cc1e644390e70d
--- /dev/null
+++ b/tools/run3.sh
@@ -0,0 +1,84 @@
+#!/usr/bin/env bash
+# Third run (2026-11-30, 05:34Z to 06:14Z): cut the 9 to 11 s of silence before a reasoned answer. Results: docs/numbers.md.
+# Needs the eight baseline copies up (docs/runbook.md, second run) and tests/test_listen_think.py passing.
+#
+# bash tools/run3.sh arms | arms2 | one | round3 | round3b | round4 what was actually run, in that order (docs/numbers.md)
+# bash tools/run3.sh arms four arms at once, each on two copies, 100 questions per arm
+# bash tools/run3.sh confirm the best arm again with the fast audio settings, the second run's
+# reference arm again beside it, and the held-out caller turns
+#
+# Every copy answers four questions at a time, as the reference arm did in the second run
+# (judge_v1_think: 97 of 100, answer after 10.7 s), so the latencies can be compared.
+cd /data/train/duplex && . /data/train/venv/bin/activate
+J="--judge-prompt v1"
+declare -A ARGS=(
+ [carry]="--carry-thought --thought-min-chars 0" # only: a withdrawn reply keeps its reasoning
+ [listen_bare]="--listen-think --listen-stance bare --thought-min-chars 0" # also reason while the caller speaks, three wordings
+ [listen_plain]="--listen-think --listen-stance plain --thought-min-chars 0"
+ [listen_notes]="--listen-think --listen-stance notes --thought-min-chars 0"
+ # fourth round, after Whisper found short answers cut off: short replies decoded in one piece, longer lead-ins allowed
+ [lead_gate_300]="--lead-in --lead-in-after-ms 1200 --lead-in-max-tokens 300"
+ [reference]="" # the second run's arm, unchanged
+ # second round, after the first showed remarks piling up (serving/listen_think.py, MIN_KEEP): short additions dropped
+ [carry2]="--carry-thought --listen-stance bare"
+ [listen_bare2]="--listen-think --listen-stance bare"
+ [listen_check2]="--listen-think --listen-stance check"
+ [listen_notes2]="--listen-think --listen-stance notes"
+ [lead]="--lead-in --lead-in-after-ms 0" # third round: one spoken sentence while the reply reasons, played at once
+ [lead_gate]="--lead-in --lead-in-after-ms 1200 --lead-in-max-tokens 150" # the same, not played before 1.2 s of quiet (no pause inside these questions is longer than 1.44 s; 6 of 788 reach 1.2 s)
+)
+arm() { #
+ for i in 0 1; do OUT=bba3 SHARD=$i NSHARDS=2 CONC=4 bash tools/bba_arm.sh $(( $1 + i )) "$3" judge think "$J ${ARGS[$2]}" & done
+}
+
+arm4() { # the same on four copies
+ for i in 0 1 2 3; do OUT=bba3 SHARD=$i NSHARDS=4 CONC=4 bash tools/bba_arm.sh $(( $1 + i )) "$3" judge think "$J ${ARGS[$2]}" & done
+}
+
+case "${1:-}" in
+arms)
+ python -m tests.test_listen_think || exit 1
+ arm 0 carry carry; arm 2 listen_bare listen_bare; arm 4 listen_plain listen_plain; arm 6 listen_notes listen_notes
+ wait
+ for a in carry listen_bare listen_plain listen_notes; do echo "== $a"; python -m tools.bba_merge eval/results/bba3/$a/judge; done
+ ;;
+arms2)
+ python -m tests.test_listen_think || exit 1
+ arm 0 carry2 carry2; arm 2 listen_bare2 listen_bare2; arm 4 listen_check2 listen_check2; arm 6 listen_notes2 listen_notes2
+ wait
+ python -m tools.show_run3 eval/results/bba3
+ ;;
+one) # one arm on two copies: tools/run3.sh one
+ arm "$2" "$3" "$4"; wait
+ ;;
+round3) # the old arm again, and the gated lead-in with the released and with the fast audio settings
+ python -m tests.test_listen_think || exit 1
+ arm 0 reference reference_again
+ arm 2 lead_gate lead_gate
+ PROMPT=runs/prompt_af_heart_short.wav FIRST_CHUNK=12 MIN_CHUNK=12 LOW_WATER=500 WORKERS=4 arm 6 lead_gate lead_gate_fast_audio
+ wait
+ python -m tools.show_run3 eval/results/bba3
+ ;;
+round3b) # 40 held-out caller turns (the second run's judge_v1_think arm), with the gated lead-in and without
+ OUT=latency3 TURNS=40 CONC=4 bash tools/latency_arm.sh 4 judge_v1_think_lead_gate judge think "$J ${ARGS[lead_gate]}" &
+ OUT=latency3 TURNS=40 CONC=4 bash tools/latency_arm.sh 5 judge_v1_think_again judge think "$J" &
+ wait
+ ;;
+round4) # the answer asked for as a short sentence (eval/eval_bba.py --system sentence), each arm on four copies
+ EVAL_ARGS="--system sentence" arm4 0 lead_gate_300 lead_gate_sentence
+ EVAL_ARGS="--system sentence" arm4 4 reference reference_sentence
+ wait
+ python -m tools.show_run3 eval/results/bba3 reference_again lead_gate reference_sentence lead_gate_sentence
+ ;;
+confirm)
+ best=$2
+ arm 0 reference reference_again
+ PROMPT=runs/prompt_af_heart_short.wav FIRST_CHUNK=12 MIN_CHUNK=12 LOW_WATER=500 WORKERS=4 arm 2 "$best" "${best}_fast_audio"
+ OUT=latency3 TURNS=100 CONC=3 bash tools/latency_arm.sh 4 "$best" judge think "$J ${ARGS[$best]}" &
+ OUT=latency3 TURNS=100 CONC=3 bash tools/latency_arm.sh 5 "${best}_keep_interrupted" judge think "$J ${ARGS[$best]} --keep-interrupted" &
+ wait
+ for a in reference_again "${best}_fast_audio"; do echo "== $a"; python -m tools.bba_merge eval/results/bba3/$a/judge; done
+ ;;
+*) echo "usage: tools/run3.sh arms | confirm "; exit 2 ;;
+esac
+date -u +%FT%TZ
diff --git a/tools/server_run.sh b/tools/server_run.sh
new file mode 100644
index 0000000000000000000000000000000000000000..0a9526c9513c4983d7d16c522445286c84bf0453
--- /dev/null
+++ b/tools/server_run.sh
@@ -0,0 +1,14 @@
+#!/usr/bin/env bash
+# The WebSocket endpoint on GPU 0 (next to the baseline). Pass "controller" to load the trained controller (on GPU 1).
+# Pass "think" for think-then-speak. PORT= sets the port (default 8765).
+# FIRST_CHUNK= sets the size of a reply's first audio chunk (default 25, the released recipe).
+cd /data/train/duplex && . /data/train/venv/bin/activate
+# GPU= puts the audio decoder beside the baseline copy on that GPU; VLLM_PORT is that copy's port.
+# DECODER_GPU= moves the decoder to another GPU. FP16=1 runs it in half precision.
+export HF_HOME=/data/train/hf OMP_NUM_THREADS=8 CUDA_VISIBLE_DEVICES=${DECODER_GPU:-${GPU:-0}},$(( (${GPU:-0} + 1) % 8 ))
+EXTRA=""
+[ "${1:-}" = "think" ] && EXTRA="--think-first --think-max-tokens ${THINK_TOKENS:-2048}"
+[ "${1:-}" = "controller" ] && EXTRA="--encoder-ckpt runs/encoder/final.pt --controller-ckpt runs/controller/final.pt --controller-device cuda:1"
+exec python -u -m serving.server --reply-prefix '' --vllm-url "http://127.0.0.1:${VLLM_PORT:-9999}/v1/chat/completions" ${SERVER_ARGS:-} \
+ --step-audio2-dir /data/train/src/Step-Audio2 --token2wav-dir /data/train/models/Step-Audio-2-mini/token2wav \
+ --prompt-wav "${PROMPT:-runs/prompt_af_heart.wav}" --first-chunk "${FIRST_CHUNK:-25}" --min-chunk "${MIN_CHUNK:-25}" --low-water-ms "${LOW_WATER:-0}" --decoder-workers "${WORKERS:-1}" ${FP16:+--decoder-fp16} --port "${PORT:-8765}" $EXTRA
diff --git a/tools/serving_final.sh b/tools/serving_final.sh
new file mode 100644
index 0000000000000000000000000000000000000000..6217a80f85e38529ad243ef5024d25c38560f8eb
--- /dev/null
+++ b/tools/serving_final.sh
@@ -0,0 +1,15 @@
+#!/usr/bin/env bash
+# The serving comparison, alone on the machine: four endpoint configurations, each on its own GPU with its own
+# baseline copy, all at the same time. Then Whisper checks the saved reply audio of each.
+cd /data/train/duplex && . /data/train/venv/bin/activate
+S=runs/prompt_af_heart_short.wav
+GPU=0 bash tools/loadtest_cfg.sh q_released 1,2,4,8 &
+GPU=5 PROMPT=$S bash tools/loadtest_cfg.sh q_short_prompt 1,2,4,8 &
+GPU=7 PROMPT=$S FIRST_CHUNK=12 MIN_CHUNK=12 LOW_WATER=500 WORKERS=4 bash tools/loadtest_cfg.sh q_short_first12 1,2,4,8 &
+GPU=3 PROMPT=$S FIRST_CHUNK=16 MIN_CHUNK=16 LOW_WATER=400 WORKERS=4 bash tools/loadtest_cfg.sh q_short_first16 1,2,4,8 &
+wait
+export HF_HOME=/data/train/hf OMP_NUM_THREADS=8
+CUDA_VISIBLE_DEVICES=6 python -u -m eval.eval_wer --out eval/results/wer_replies \
+ --pairs eval/results/loadtest_q_released/audio eval/results/loadtest_q_short_prompt/audio \
+ eval/results/loadtest_q_short_first12/audio eval/results/loadtest_q_short_first16/audio > /data/train/logs/wer_replies.log 2>&1
+date -u +%FT%TZ > runs/serving_final_end
diff --git a/tools/show_bba.py b/tools/show_bba.py
new file mode 100644
index 0000000000000000000000000000000000000000..985bb2a89d65c9177a2e45ebd61c20b8afbe7ce2
--- /dev/null
+++ b/tools/show_bba.py
@@ -0,0 +1,15 @@
+"""One line per question of a benchmark run folder: what was asked for, what was said, timings.
+
+ python -m tools.show_bba eval/results/bba/manual
+"""
+import json
+import sys
+from pathlib import Path
+
+for f in sorted(Path(sys.argv[1]).glob("q_*.json")):
+ q = json.loads(f.read_text())
+ done = [e for e in q.get("events", []) if e["type"] == "reply.done"]
+ d = done[-1] if done else {}
+ spoken = q["text"].split("")[-1].strip()
+ print(f"{q['category'][:10]:10s} official {q['official_answer']:8s} answer {str(q['answer']):8s} spoken {spoken[:60]!r} "
+ f"thought_ms {d.get('thought_ms')} ttfa_ms {d.get('ttfa_ms')} audio_ms {d.get('audio_ms')} err {q.get('error')}")
diff --git a/tools/show_budget.py b/tools/show_budget.py
new file mode 100644
index 0000000000000000000000000000000000000000..2e20d824de913a4305567e15491b30668c1f64a6
--- /dev/null
+++ b/tools/show_budget.py
@@ -0,0 +1,14 @@
+"""One line per finished thinking-budget arm.
+
+ python -m tools.show_budget eval/results/bba_budget
+"""
+import json
+import sys
+from pathlib import Path
+
+rows = sorted((json.loads(p.read_text()) for p in Path(sys.argv[1]).glob("summary_*.json")), key=lambda d: (d["budget"], d["brief"]))
+for d in rows:
+ t, a = d["think_tokens"], d["seconds_to_spoken_answer"]
+ print(f"{d['arm']:18s} correct {d['accuracy'] * 100:3.0f}/100 | by category {[round(v, 2) for v in d['accuracy_by_category'].values()]}"
+ f" | reasoning closed itself {d['reasoning_closed_itself']:3d} | think tokens p50 {t.get('p50', 0):.0f} p90 {t.get('p90', 0):.0f}"
+ f" | seconds to spoken answer p50 {a.get('p50', 0):.2f} p90 {a.get('p90', 0):.2f} max {a.get('max', 0):.1f} | no answer {d['no_answer_found']} | errors {d['errors']}")
diff --git a/tools/show_judge.py b/tools/show_judge.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ed7ad3cbf452dccf605c686e8952c83d04228ad
--- /dev/null
+++ b/tools/show_judge.py
@@ -0,0 +1,20 @@
+"""One line per judge variant from eval/results/judge/judge.json.
+
+ python -m tools.show_judge eval/results/judge/judge.json
+"""
+import json
+import sys
+
+
+def f(x):
+ return f"{x['correct']}/{x['total']} ({x['rate']:.3f})" if x["total"] else "none"
+
+
+d = json.load(open(sys.argv[1]))
+print(d["cases"], d["held_out_pauses"], "| chosen on train:", d["chosen_on_train"])
+for v, r in d["variants"].items():
+ h, b = r["held_out"], r["benchmark_questions"]
+ print(f"{v:7s} train balanced {r['train_balanced_accuracy']:.3f} | turn end released {f(h['turn_end_released'])} | pause held: all {f(h['pause_held_all'])}"
+ f", cut off {f(h['pause_held_cut_off'])}, other {f(h['pause_held_other'])} | question inner held {f(b['inner_silence_held'])}"
+ f", end released {f(b['end_released'])}, never early {b['questions_never_released_early']}/100"
+ f" | ms p50 {r['judge_ms_held_out']['p50']:.0f} p90 {r['judge_ms_held_out']['p90']:.0f} | no word {r['no_answer_word']}")
diff --git a/tools/show_run3.py b/tools/show_run3.py
new file mode 100644
index 0000000000000000000000000000000000000000..c512a42dc4d707250c7eefd8d588f4ea1aca31e0
--- /dev/null
+++ b/tools/show_run3.py
@@ -0,0 +1,34 @@
+"""One table over the arms of a benchmark folder, from each arm's per-question files.
+
+ python -m tools.show_run3 eval/results/bba3 [arm ...]
+"""
+import json
+import sys
+from pathlib import Path
+
+from eval.ws_client import percentiles
+
+root = Path(sys.argv[1])
+arms = sys.argv[2:] or sorted(p.name for p in root.iterdir() if (p / "judge").is_dir())
+def answer_ms(r):
+ """Caller finished -> first audio of the answer itself (not of a lead-in). Older results have no such event: first audio."""
+ ev = [e for e in r["events"] if e["type"] == "reply.answer.first"]
+ return (ev[-1]["t_client"] - r["question_s"]) * 1000 if ev else r["latency_ms"]
+
+
+print("| Arm | Questions | Right | First audio after, p50 / p90 (s) | Answer after, p50 / p90 (s) | Reasoning left at the end, p50 (s) | Heard false starts | Withdrawn unheard "
+ "| Requests while listening | Replies needing no reasoning | Errors |")
+print("|---|---|---|---|---|---|---|---|---|---|---|")
+for arm in arms:
+ rows = [json.loads(p.read_text(encoding="utf-8")) for p in sorted((root / arm / "judge").glob("q_*.json"))]
+ if not rows:
+ continue
+ last = [([e for e in r["events"] if e["type"] == "reply.done"] or [{}])[-1] for r in rows]
+ lat = percentiles([r["latency_ms"] for r in rows if r["replied"]])
+ th = percentiles([d.get("thought_ms") for d in last])
+ ans = percentiles([answer_ms(r) for r in rows if r["replied"]])
+ s = lambda v: "-" if v is None else f"{v / 1000:.1f}"
+ print(f"| {arm} | {len(rows)} | {sum(r['correct'] for r in rows)} | {s(lat.get('p50'))} / {s(lat.get('p90'))} | {s(ans.get('p50'))} / {s(ans.get('p90'))} | {s(th.get('p50'))} "
+ f"| {sum(r['replies_cut_off'] > 0 for r in rows)} | {sum(sum(1 for e in r['events'] if e['type'] == 'reply.withdrawn') for r in rows)} "
+ f"| {sum(sum(1 for e in r['events'] if e.get('label') == 'LISTEN') for r in rows)} | {sum(bool(d.get('thought_ready')) for d in last)} "
+ f"| {sum(bool(r['error']) for r in rows)} |")
diff --git a/tools/start_copies.sh b/tools/start_copies.sh
new file mode 100644
index 0000000000000000000000000000000000000000..6763f6584f9b4cb08095f2e396fa500007d32ffd
--- /dev/null
+++ b/tools/start_copies.sh
@@ -0,0 +1,10 @@
+#!/usr/bin/env bash
+# One copy of the baseline per GPU, each in its own tmux session (ports 9999, 9991 ... 9997).
+# GPUS="0 1 2 3" bash tools/start_copies.sh default: all eight
+# Stop them with: for g in 0 1 2 3 4 5 6 7; do sudo docker stop duplex-vllm-$g; done
+mkdir -p /data/train/logs
+for g in ${GPUS:-0 1 2 3 4 5 6 7}; do
+ p=$([ "$g" = 0 ] && echo 9999 || echo 999$g)
+ tmux new-session -d -s vllm$g "cd /data/train/duplex && GPU=$g PORT=$p MODEL_DIR=/data/train/models/Step-Audio-R1.1 bash serving/launch_vllm.sh > /data/train/logs/vllm_$g.log 2>&1"
+done
+tmux ls
diff --git a/tools/start_llms.sh b/tools/start_llms.sh
new file mode 100644
index 0000000000000000000000000000000000000000..ed9a5a364cab83bdae0586d0c40a797ea8e8bc41
--- /dev/null
+++ b/tools/start_llms.sh
@@ -0,0 +1,11 @@
+#!/usr/bin/env bash
+# The dialogue writer: one Qwen3-32B (Apache-2.0) replica per GPU given, each on its own
+# local port 800. Uses the upstream vLLM image already on this machine (by digest).
+# Only containers named duplex-llm-* are ever started or stopped by this repository.
+set -euo pipefail
+IMAGE=vllm/vllm-openai@sha256:88175ddf4f59944ccbb24c6b60c1bc535a160be3c4f09a3b08702c5e301a599e
+for g in "$@"; do
+ sudo docker run -d --rm --name "duplex-llm-$g" --gpus "\"device=$g\"" --ipc=host \
+ -v /data/train/models/Qwen3-32B:/model:ro -p "127.0.0.1:800$g:8000" \
+ "$IMAGE" /model --served-model-name Qwen/Qwen3-32B --port 8000 --max-model-len 8192 --max-num-seqs 256
+done
diff --git a/tools/stop_llms.sh b/tools/stop_llms.sh
new file mode 100644
index 0000000000000000000000000000000000000000..3b7184114efef7d14feade20c3774a2fe4b05653
--- /dev/null
+++ b/tools/stop_llms.sh
@@ -0,0 +1,3 @@
+#!/usr/bin/env bash
+# Stops the dialogue-writer containers of this repository, and nothing else.
+for name in $(sudo docker ps --format '{{.Names}}' | grep '^duplex-llm-'); do sudo docker stop "$name" > /dev/null && echo "stopped $name"; done
diff --git a/tools/track_a_run.sh b/tools/track_a_run.sh
new file mode 100644
index 0000000000000000000000000000000000000000..2765f1c034bd190b8baf2d8e6f45610fb526f902
--- /dev/null
+++ b/tools/track_a_run.sh
@@ -0,0 +1,9 @@
+#!/usr/bin/env bash
+# Everything that needs the endpoint but not the controller: the load test (released audio recipe),
+# then the 100 benchmark questions with manual end of turn, then the fixed-silence latency baseline.
+cd /data/train/duplex && . /data/train/venv/bin/activate
+export OMP_NUM_THREADS=8
+python -u -m serving.loadtest --url http://127.0.0.1:8765/ws --wav-dir eval/data/bba --out eval/results/loadtest --turns 2 > /data/train/logs/loadtest.log 2>&1
+python -u -m eval.eval_bba --url http://127.0.0.1:8765/ws --data eval/data/bba --out eval/results/bba --modes manual --concurrency 4 > /data/train/logs/bba_manual.log 2>&1
+python -u -m eval.eval_latency --url http://127.0.0.1:8765/ws --data data/out/dataset --out eval/results/latency --modes vad --turns 100 --concurrency 4 > /data/train/logs/latency_vad.log 2>&1
+date -u +%FT%TZ > runs/track_a_end
diff --git a/tools/track_a_sweep.sh b/tools/track_a_sweep.sh
new file mode 100644
index 0000000000000000000000000000000000000000..4c428f56324e10c914013f26edf6c23cfe1065e6
--- /dev/null
+++ b/tools/track_a_sweep.sh
@@ -0,0 +1,14 @@
+#!/usr/bin/env bash
+# Track A, second run: the same load test with a smaller first audio chunk.
+# The released recipe waits for 25 audio tokens (plus look-ahead) before it decodes anything.
+cd /data/train/duplex && . /data/train/venv/bin/activate
+export OMP_NUM_THREADS=8
+for fc in ${FCS:-25 12 6}; do
+ tmux kill-session -t server 2>/dev/null; sleep 2
+ tmux new-session -d -s server "FIRST_CHUNK=$fc bash tools/server_run.sh > /data/train/logs/server_fc$fc.log 2>&1"
+ for i in $(seq 1 60); do ss -ltn 2>/dev/null | grep -q ":8765 " && break; sleep 2; done
+ python -u -m serving.loadtest --url http://127.0.0.1:8765/ws --wav-dir eval/data/bba --out eval/results/loadtest_fc$fc \
+ --levels "${LEVELS:-1,2,4,8}" --turns 3 --save-audio eval/results/loadtest_fc$fc/audio > /data/train/logs/loadtest_fc$fc.log 2>&1
+done
+tmux kill-session -t server 2>/dev/null
+date -u +%FT%TZ > runs/track_a_sweep_end
diff --git a/tools/train_ctl.sh b/tools/train_ctl.sh
new file mode 100644
index 0000000000000000000000000000000000000000..aff4037dce6d224c1991ece14ca3917009a8d8b0
--- /dev/null
+++ b/tools/train_ctl.sh
@@ -0,0 +1,14 @@
+#!/usr/bin/env bash
+# Controller training on GPUs 1 to 7 (36 minutes, a checkpoint every 10), then the held-out evaluation.
+# Shorter than first planned so that every evaluation ends before the sign-in certificate does.
+set -uo pipefail
+cd /data/train/duplex && . /data/train/venv/bin/activate
+export HF_HOME=/data/train/hf OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 OPENBLAS_NUM_THREADS=4
+date -u +%FT%TZ > runs/ctl_run_start
+CUDA_VISIBLE_DEVICES=1,2,3,4,5,6,7 torchrun --nproc_per_node=7 -m controller.model.train --data data/out/dataset \
+ --encoder runs/encoder/final.pt --out runs/controller \
+ --max-hours 0.6 --batch 24 --workers 10 --eval-every 1000 --ckpt-minutes 10 > /data/train/logs/train.log 2>&1
+[ -f runs/controller/final.pt ] || { echo "controller training failed" > runs/ctl_run_failed; exit 1; }
+CUDA_VISIBLE_DEVICES=1 python -m eval.eval_controller --data data/out/dataset --encoder runs/encoder/final.pt \
+ --controller runs/controller/final.pt --out eval/results/controller --device cuda:0 > /data/train/logs/eval_controller.log 2>&1
+date -u +%FT%TZ > runs/ctl_run_end
diff --git a/tools/train_run.sh b/tools/train_run.sh
new file mode 100644
index 0000000000000000000000000000000000000000..ff5f5bea0e785ba2413e3cb9440f68fbc48be791
--- /dev/null
+++ b/tools/train_run.sh
@@ -0,0 +1,20 @@
+#!/usr/bin/env bash
+# The two training runs on GPUs 1 to 7, back to back, then the held-out controller evaluation.
+# Budgets (changed on 2026-11-30 to use all 8 GPUs and finish fast): 25 min of distillation and 55 min of
+# controller training on 7 GPUs, about 9.3 GPU-hours, instead of the plan's 4 hours on 3 GPUs.
+set -uo pipefail
+cd /data/train/duplex && . /data/train/venv/bin/activate
+export HF_HOME=/data/train/hf OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 OPENBLAS_NUM_THREADS=4
+export CUDA_VISIBLE_DEVICES=1,2,3,4,5,6,7
+date -u +%FT%TZ > runs/train_run_start
+torchrun --nproc_per_node=7 -m controller.encoder.distill --data data/out/dataset \
+ --baseline-dir /data/train/models/Step-Audio-R1.1 --out runs/encoder \
+ --max-hours 0.42 --batch 12 --workers 10 --eval-every 1000 --ckpt-minutes 10 > /data/train/logs/distill.log 2>&1
+[ -f runs/encoder/final.pt ] || { echo "distillation failed" > runs/train_run_failed; exit 1; }
+torchrun --nproc_per_node=7 -m controller.model.train --data data/out/dataset \
+ --encoder runs/encoder/final.pt --out runs/controller \
+ --max-hours 0.92 --batch 24 --workers 10 --eval-every 1000 --ckpt-minutes 15 > /data/train/logs/train.log 2>&1
+[ -f runs/controller/final.pt ] || { echo "controller training failed" > runs/train_run_failed; exit 1; }
+CUDA_VISIBLE_DEVICES=1 python -m eval.eval_controller --data data/out/dataset --encoder runs/encoder/final.pt \
+ --controller runs/controller/final.pt --out eval/results/controller --device cuda:0 > /data/train/logs/eval_controller.log 2>&1
+date -u +%FT%TZ > runs/train_run_end
diff --git a/tools/tts_run.sh b/tools/tts_run.sh
new file mode 100644
index 0000000000000000000000000000000000000000..d047cb62c1e42ba08ac34c06a53d71abab3990ce
--- /dev/null
+++ b/tools/tts_run.sh
@@ -0,0 +1,13 @@
+#!/usr/bin/env bash
+# Voice all dialogues on GPUs 1 to 7: 8 processes per GPU, 4 CPU threads each. (Without the
+# thread cap every process takes all 256 cores: measured load average 1582, GPUs idle.)
+cd /data/train/duplex && . /data/train/venv/bin/activate
+export HF_HOME=/data/train/hf HF_HUB_OFFLINE=1
+export OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 OPENBLAS_NUM_THREADS=4 NUMEXPR_NUM_THREADS=4
+[ -f data/out/tts_start ] || date -u +%s > data/out/tts_start
+date -u +%s > data/out/tts_restart
+for g in 1 2 3 4 5 6 7; do for s in 0 1 2 3 4 5 6 7; do
+ CUDA_VISIBLE_DEVICES=$g python -m data.synth_tts --dialogues data/out/dialogues.jsonl --out data/out/tts \
+ --shard $(( (g-1)*8 + s )) --num-shards 56 > /data/train/logs/tts_${g}_${s}.log 2>&1 &
+done; done; wait
+date -u +%s > data/out/tts_end
diff --git a/tools/warm_copies.py b/tools/warm_copies.py
new file mode 100644
index 0000000000000000000000000000000000000000..8915466ab80ea676efca622cd2a12497b07bc651
--- /dev/null
+++ b/tools/warm_copies.py
@@ -0,0 +1,53 @@
+"""Wait until every baseline copy answers, then take the one-time stall out of each.
+
+Measured in the second run: after every start of the released image on this GPU, the first
+reply longer than one token stalls for about 100 s. So each copy is asked for two short
+replies here, and the time of each is printed.
+
+ python -m tools.warm_copies 9999 9991 9992
+"""
+import asyncio
+import sys
+import time
+
+import aiohttp
+import numpy as np
+
+from duplex.spec import SR
+from serving.baseline_client import human_turn, stream_chat
+
+NL = chr(10)
+
+
+async def warm(http, port, t0):
+ base = f"http://127.0.0.1:{port}/v1"
+ while True:
+ try:
+ async with http.get(base + "/models") as r:
+ if r.status == 200:
+ break
+ except aiohttp.ClientError:
+ pass
+ await asyncio.sleep(5)
+ up = time.perf_counter() - t0
+ pcm = (np.random.default_rng(port).standard_normal(SR) * 300).astype(np.int16)
+ took = []
+ for _ in range(2):
+ t = time.perf_counter()
+ messages = [human_turn(pcm), {"role": "assistant", "content": "" + NL, "eot": False}]
+ n = 0
+ async for _, text, _ in stream_chat(http, base + "/chat/completions", "Step-Audio-R1.1", messages, max_tokens=24, temperature=0.7):
+ n += bool(text)
+ took.append(round(time.perf_counter() - t, 1))
+ print(f"port {port}: answering after {up:.0f} s; first reply {took[0]} s, second {took[1]} s", flush=True)
+
+
+async def main():
+ t0 = time.perf_counter()
+ async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=None)) as http:
+ await asyncio.gather(*[warm(http, int(p), t0) for p in sys.argv[1:]])
+ print(f"all warm after {time.perf_counter() - t0:.0f} s", flush=True)
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/tools/wer_pairs.py b/tools/wer_pairs.py
new file mode 100644
index 0000000000000000000000000000000000000000..53afed103e06554002114d883b0ee4276c5b7b85
--- /dev/null
+++ b/tools/wer_pairs.py
@@ -0,0 +1,23 @@
+"""Pairs for eval/eval_wer.py from a benchmark arm: each reply's audio and the words it was meant to say
+(the lead-in, if there was one, and the answer).
+
+ python -m tools.wer_pairs eval/results/bba3/lead_gate/judge eval/results/wer_lead_gate/pairs
+"""
+import json
+import shutil
+import sys
+from pathlib import Path
+
+src, dst = Path(sys.argv[1]), Path(sys.argv[2])
+dst.mkdir(parents=True, exist_ok=True)
+n = 0
+for f in sorted(src.glob("q_*.json")):
+ r = json.loads(f.read_text(encoding="utf-8"))
+ done = [e for e in r["events"] if e["type"] == "reply.done" and e["reason"] == "done"]
+ wav = f.with_suffix(".wav")
+ if not done or not wav.exists():
+ continue
+ shutil.copy(wav, dst / wav.name)
+ (dst / f"{f.stem}.txt").write_text(((done[-1].get("lead_text") or "") + " " + done[-1]["text"]).strip(), encoding="utf-8")
+ n += 1
+print(n, "pairs")