Skip to content

Voice isolation — separating clean speech from background noise and mixed audio.

Python

Initial release

github-actions[bot]3bc1c04dfe2b
diff --git a/.agents/skills/integrate/SKILL.md b/.agents/skills/integrate/SKILL.md
new file mode 100644
index 0000000..31f9bd7
--- /dev/null
+++ b/.agents/skills/integrate/SKILL.md
@@ -0,0 +1,131 @@
+---
+name: integrate
+description: Integrate the Inworld Voice Isolator (the inworld-voice-isolation package) into another Python project or service via the pip package - install with the right extras, load weights by registry name, Hugging Face path or local file, call isolate() or the CLI correctly (rates, shapes, chunking, device, memory), and pin versions. Use when someone wants to use the model rather than develop it.
+---
+
+# Integrate the Inworld Voice Isolator
+
+## Install
+
+```bash
+pip install inworld-voice-isolation # the library (plain PyTorch path)
+pip install "inworld-voice-isolation[fast]" # + the Mamba CUDA kernels (needs a CUDA toolchain to build)
+```
+
+- Python ≥ 3.10, PyTorch ≥ 2.1 (install torch for your CUDA first if you need a specific build).
+- The `fast` extra provides optional CUDA Mamba kernels. Without it the scan runs in
+ plain PyTorch on CUDA and the CPU; on Apple's GPU (`mps`) it runs as a built-in
+ Metal kernel. Streaming uses plain PyTorch along time and the optional kernels
+ across frequency. Measure throughput on the target hardware and audio.
+- Weights come from the Hub on first use: `inworld/voice-isolator` (`denoiser.safetensors` 256 MB, `denoiser_realtime.safetensors` 233 MB, fp32 safetensors)
+ lands in the standard HF cache (`HF_HOME` / `HF_HUB_CACHE`). For an air-gapped machine:
+ `hf download inworld/voice-isolator` with `HF_HUB_OFFLINE=1` set afterwards.
+- Importing the package never imports mamba_ssm, demucs, transformers or gradio and never
+ touches the network; the first `VoiceIsolator(...)` does.
+- When PyPI cannot install it, the install routes, in order, are in
+ [the setup section of AGENTS.md](../../../AGENTS.md#setting-up-the-voice-isolator-for-a-user).
+- After installing, run `voice-isolate-doctor --full`: it fetches both models, runs each
+ on the device inference would use and ends with `All set: …` or one line per problem.
+
+## Load
+
+```python
+from inworld import voice_isolation
+
+isolator = voice_isolation.VoiceIsolator("inworld/voice-isolator") # the Hub repository: file + sha256 check
+isolator = voice_isolation.VoiceIsolator("voice-isolator-v1") # a registry name picks a checkpoint directly
+isolator = voice_isolation.VoiceIsolator("hf://inworld/voice-isolator/denoiser.safetensors@main")
+isolator = voice_isolation.VoiceIsolator("/models/denoiser.safetensors", device="cuda:1")
+live = voice_isolation.VoiceIsolator("inworld/voice-isolator", mode="streaming", lookahead_frames=2)
+# VoiceIsolator.load(...) is the same call with the same arguments
+```
+
+- `inworld/voice-isolator` loads the checkpoint for the mode: `voice-isolator-v1` offline, `voice-isolator-v1-realtime`
+ for streaming. It is the default, so `VoiceIsolator()` and `VoiceIsolator(mode="streaming")` work too.
+- `voice_isolation.MODELS` lists the registry (repo, filename, sha256, revision, stage, description).
+- `hf://<org>/<repo>/<file>[@<revision>]` fetches any Hub file with no checksum; pin a
+ revision (tag or commit) in production instead of `main`.
+- `device` defaults to CUDA when available, else `mps` on an Apple-silicon Mac with PyTorch ≥ 2.6
+ (earlier versions keep the CPU), else the CPU. Keep one `VoiceIsolator`
+ per process/GPU and reuse it. It is not thread-safe across concurrent calls; serialise calls or
+ run one worker per GPU.
+- `mode` is `"offline"` (every frame sees its whole chunk, best quality, the default; for `voice-isolator-v1`) or
+ `"streaming"` (causal, for `voice-isolator-v1-realtime`; `lookahead_frames` is one of
+ `live.lookahead_choices`, frames of 10 ms). Each released checkpoint runs in one mode; only a
+ dual-mode checkpoint switches with `.mode = ...`.
+
+## Call
+
+```python
+clean = isolator.isolate(wav, sample_rate) # same type and rate back
+clean48 = isolator.isolate(wav, sample_rate, output_sample_rate=48000)
+
+session = live.stream(block_frames=4) # delay in samples: session.latency_samples
+out = session.push(piece) # the samples that became final (same type as the piece)
+tail = session.flush() # the rest, once the input ends
+```
+
+- `wav`: 1-D mono or 2-D stereo (`[C, T]` or `[T, C]`, downmixed to mono), NumPy array or
+ torch Tensor, float in [-1, 1] or integer PCM. Output is mono, same container type, length
+ matched to the input, at the input rate unless `output_sample_rate` is given. Resampling in
+ and out is kaiser-quality (`voice_isolation.resample`).
+- Any input rate works. Content above the input's bandwidth is never invented: a 16 kHz input
+ comes back band-limited to 8 kHz even at `output_sample_rate=48000`.
+- `offline_passes` (constructor argument, `--offline-passes` on the CLI) runs the offline model again over
+ its own output, in the same chunks and precision: None takes the checkpoint's own count (one for the
+ released files). Each pass costs one offline render, so two passes double the time; above one it applies
+ to offline mode only.
+- Offline, long audio is processed in the checkpoint's chunks, 8 s with a 2 s crossfade for `voice-isolator-v1` (`chunk_seconds`,
+ `overlap_seconds` override); halve `chunk_seconds` if GPU memory is tight. In streaming mode
+ `isolate()` runs the stream itself over the clip (no chunks, no seams, exactly what a live
+ session gives); `isolate_many()` streams up to 16 clips in
+ lockstep for throughput.
+- The input's level is left alone: output level matches input level, with no normalisation.
+ Isolated speech can peak above full scale; when writing integer PCM, scale such a file down
+ rather than clipping it (`voice_isolation.save_audio` does).
+- The streaming session wants 48 kHz mono float samples; resample before pushing. Pieces of any
+ size work and never change the output; `block_frames` controls work per call, without
+ adding algorithmic latency. See `MODEL_CARD.md` for the algorithmic latency.
+ The state is never reset within a session.
+
+## Batch / CLI
+
+```bash
+voice-isolate noisy.wav clean.wav # clean.wav and clean_background.wav, both float32
+voice-isolate in_dir/ out_dir/ --shard 0 --num-shards 4 # resumable, one worker per shard/GPU
+voice-isolate in.wav out.wav --model hf://inworld/voice-isolator/denoiser.safetensors
+voice-isolate in.wav out.wav --output-sr 0 # keep the input rate for both float WAVs
+voice-isolate in.wav out.wav --background noise.wav # explicit background path, one input file
+voice-isolate in.wav out.wav --no-background --float32 # voice only, float WAV
+voice-isolate in.wav out.wav --mode streaming --lookahead 2 # what a live stream with 20 ms look-ahead gives
+```
+
+Offline writes the requested voice WAV and `<output-stem>_background.wav`. Both use
+float32 at the output rate, without independent normalization; their sum reconstructs
+the aligned mono input. `--background` overrides the companion path for one input
+file. `--no-background` disables it and uses PCM16 unless `--float32` is supplied.
+Streaming writes only the voice.
+
+Directory mode mirrors the tree and resumes only when all requested outputs for a
+recording exist. The output directory must be outside the input tree. Collisions
+with another output or any input are refused before inference. A failed file prints
+`FAIL <file>` and the batch continues with a nonzero exit status.
+`CUDA_VISIBLE_DEVICES` selects the GPU per worker.
+
+## Pinning and updates
+
+- Pin the package (`inworld-voice-isolation==<version>`) and refer to the model by the repository id
+ or a registry name: the name → file → sha256 mapping is part of the package, so a package version always
+ resolves the same weights. Use `hf://...@<revision>` only when you deliberately want a file
+ the registry does not know.
+- The package version tracks the API, the registry name tracks the model (`voice-isolator-v1` for
+ recorded audio, offline; `voice-isolator-v1-realtime` for live audio, streaming only). Read the model card (`README.md` on the Hub
+ repo, `MODEL_CARD.md` in this repository) for what the weights were trained and evaluated on.
+- Licenses: code and weights Apache-2.0; the Mamba kernels Apache-2.0.
+
+## Throughput
+
+`isolator.isolate_many([clip, ...], sample_rate)` isolates a list of clips, grouping equal
+lengths into one separator pass; results equal `isolate()` to about 1e-5 and come back in input
+order. On a GPU the separator is compute-bound, so for bulk work spread clips over several
+processes or cards rather than expecting batching alone to multiply speed.
diff --git a/.agents/skills/run-demo/SKILL.md b/.agents/skills/run-demo/SKILL.md
new file mode 100644
index 0000000..baa77cd
--- /dev/null
+++ b/.agents/skills/run-demo/SKILL.md
@@ -0,0 +1,25 @@
+---
+name: run-demo
+description: Launch the Inworld Voice Isolator demo with Offline file isolation and Online microphone recording. Use when someone wants to listen locally or explicitly asks for a temporary public demo.
+---
+
+# Run the demo
+
+Follow [demo/README.md](../../../demo/README.md) for setup, commands and outputs.
+It is the source of truth for demo operation; the demo extra pins Gradio 6.31.0.
+
+1. Load both requested checkpoints, using the released offline and realtime
+ models by default. `--offline-model` and `--online-model` select them
+ independently. Registered models verify their checksums; confirm the requested
+ file for a custom checkpoint. Both fixed modes must load successfully.
+2. Use the bundled samples by default. `--examples ''` hides the samples.
+3. Start locally. Add `--share` only when the user requested a public demo.
+ Keep authentication in `VOICE_ISOLATION_DEMO_AUTH`. Microphone access needs
+ localhost or HTTPS.
+4. For a background server, write logs and the URL file under `staging/`. Report
+ both checkpoints and the actual URL after startup succeeds.
+5. Smoke-test Offline voice/background outputs and Online recording, live
+ waveforms and spectrograms, stopping and playback, and the microphone input
+ and isolated voice players a take leaves. Each online take is limited to 60
+ seconds; capture pauses before playback. Check that the header names the
+ expected device. Report when microphone or browser testing was unavailable.
diff --git a/.claude/skills/integrate b/.claude/skills/integrate
new file mode 120000
index 0000000..a4078d9
--- /dev/null
+++ b/.claude/skills/integrate
@@ -0,0 +1 @@
+../../.agents/skills/integrate
\ No newline at end of file
diff --git a/.claude/skills/run-demo b/.claude/skills/run-demo
new file mode 120000
index 0000000..ce175a9
--- /dev/null
+++ b/.claude/skills/run-demo
@@ -0,0 +1 @@
+../../.agents/skills/run-demo
\ No newline at end of file
diff --git a/.github/requirements/build.in b/.github/requirements/build.in
new file mode 100644
index 0000000..53d2381
--- /dev/null
+++ b/.github/requirements/build.in
@@ -0,0 +1,9 @@
+# Copyright 2026 Inworld AI — Apache-2.0
+# Artifact construction and metadata validation on Linux / CPython 3.10.
+# Update these reviewed versions, regenerate build.txt, then verify both projects.
+pip==26.3
+build==1.6.1
+hatchling==1.33.0
+hatch-fancy-pypi-readme==25.1.0
+twine==7.0.0
+readme-renderer[md]==46.0
diff --git a/.github/requirements/build.txt b/.github/requirements/build.txt
new file mode 100644
index 0000000..4a8db47
--- /dev/null
+++ b/.github/requirements/build.txt
@@ -0,0 +1,651 @@
+# This file was autogenerated by uv via the following command:
+# uv pip compile .github/requirements/build.in --python-version 3.10 --python-platform x86_64-unknown-linux-gnu --generate-hashes --only-binary :all: --index-url https://pypi.org/simple --output-file .github/requirements/build.txt
+backports-tarfile==1.2.0 \
+ --hash=sha256:77e284d754527b01fb1e6fa8a1afe577858ebe4e9dad8919e34c862cb399bc34 \
+ --hash=sha256:d75e02c268746e1b8144c278978b6e98e85de6ad16f8e4b0844a154557eca991
+ # via jaraco-context
+build==1.6.1 \
+ --hash=sha256:51cc11666391ab6f092070437ac747002ff46f3e4113a3622177ee6b488bfc53 \
+ --hash=sha256:ecd351a4be9d35a9eaaba244a7687143c9c7d4aea6ac964e7e7ddab20cbcf4e7
+ # via -r .github/requirements/build.in
+certifi==2026.10.23 \
+ --hash=sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd \
+ --hash=sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1
+ # via requests
+cffi==2.1.1 \
+ --hash=sha256:046bfc24911b37851ee1b51aab8bffe713d89c68c6a057b09484ce9fd5f69b4e \
+ --hash=sha256:06c72bb76605a4b0cd0aad6930b69d4baf7dd5d806cfc409b824191099700e66 \
+ --hash=sha256:0beceaabe56af686895136a2de78db54ecd8e4046b236b8fd6d6cb61389e9bf2 \
+ --hash=sha256:154852545011f779917b11c78db2358d095da62a9a172b78ad0a583ee5adc0d0 \
+ --hash=sha256:194cffa889098ced9976c3fc6340305e43f6303657d298da55366907c05c22d6 \
+ --hash=sha256:19ee6127ee34de7d83ce3d371ebc5ed91addbdcc39f9ab15ce4eb35a4e534971 \
+ --hash=sha256:1a18a57b58cfb21fc28d72e876acf10eaed67a1ed96226f92af4df681d571c4c \
+ --hash=sha256:1aa5645c30469b09530c4ebca77ebf8f17618293c58f8549cb1a543a50236e7d \
+ --hash=sha256:1dea0e4d7d4f11f619fe8c1d76caf49e24405b4b5743c0e3be16a500ecd930c9 \
+ --hash=sha256:208f941bb9d18e768138677f0a6d2ce01f590df56043dda1df1535ac57c88517 \
+ --hash=sha256:210019b6c7cf07f081b4c54635c8cf744377001350e29cc0f81c4377b4797735 \
+ --hash=sha256:246fa40ce8645a614ff682e0b70f37134e460eaf93a775e0cbe3cca585a67a80 \
+ --hash=sha256:25792eac27877609e7bb06d42ff88278a6624fff2ba9bbb523c09616b117e80f \
+ --hash=sha256:27350daa11d4f10c540e6e89dada4c54feb7256ad03e9a4dc075ebad7ba360d1 \
+ --hash=sha256:28907ab9bfb6aa13184cfc17c6b8e1023c5ab6fd7076d8c20a35e59fe04f8f29 \
+ --hash=sha256:2ae64be792b8966f2c69538199728b290e34726562896df1e5dc8ffd8d8188e8 \
+ --hash=sha256:31348097ff5bbe827ccc41795d4dd099d9f0625e7def00ee653c137a490c2a6c \
+ --hash=sha256:3143d81e29e1e20a9ce10901ec369012947876596f75a222235965f2b7ae832e \
+ --hash=sha256:3222ba5d678f80a030e6afbcc33dc1ae5cb45facabb61cee2c7016b8432fde48 \
+ --hash=sha256:3311ed60d36f83378794e1009ac6258bafbf81f7888b4caa7b35a521e3f95813 \
+ --hash=sha256:334644fbac4eff73d985a17a91226df55d0f394160c4cfb880e084c8f7161cac \
+ --hash=sha256:34e261f78cb6ceaaa36f42f2613f4380d94d9c759a9c73c769ee6e0247364632 \
+ --hash=sha256:363e05fa78e15116c3c32c210ee36884fd6b9afa6d440e47112c3bd511d64cb6 \
+ --hash=sha256:398aff33cee2767e3e781d2554c54bd0dff386bb437581e0d8011fde1a942ec1 \
+ --hash=sha256:3d22a20b1fb1632cc72c22f95f7b0d2961c3e1c235f245ba4c606c4771035659 \
+ --hash=sha256:42a494cee34437f05546455144f2b5d9ac09b1face62bcfce597d2e521066688 \
+ --hash=sha256:42e2f76b9455f5a9a844f770bf3e200ed3da0e15f5df3db9c31fe80b04b3d004 \
+ --hash=sha256:42f6930c31dc7f50732c9ae793c2786c7b6b044195967bbdde40bb9be81c4cc0 \
+ --hash=sha256:456a61fa52d579ebf9df2e9552ead5129855dbaff6c1e5a9b1bc408809bdc062 \
+ --hash=sha256:471cee653ae88de62096552e6d24ccb4a5adb8c8c9f10b5054d0122c15bf2779 \
+ --hash=sha256:49cbc70e6542d4ccccb936558d1064a8012541e78f821f955cff24e357776c94 \
+ --hash=sha256:4a7c934f7360e8cd64fe9efadcbd10c7c6364f531e432b9a4bf5ccbc9e0e8b50 \
+ --hash=sha256:4be96343e422f2dfcd12ab5c9f5aebe03f82f737c6bffeca6830b3875cb44aab \
+ --hash=sha256:4f42141fc14250de6dde5ee7ea4432be017252d91f19c5ad043c084cea629cac \
+ --hash=sha256:507a24c282e0f42f8ed737cf048572cbf580468da5555764a8331735e9c736b6 \
+ --hash=sha256:51b31d1c98274844cfd7838ce00bfc27c7423a4dc00fc0772fc3331c2cc90676 \
+ --hash=sha256:58acb8ab8e295e6c5ea12f888cbb13cf21511ef2a3303a23f4325c29d17fe5c1 \
+ --hash=sha256:5a59cc1c4442bc3d5c703bf720b51138d0bfc173618807c9ee2490a7541dd3d9 \
+ --hash=sha256:5bb4e7ea95dcd6a014a6fef62e62467d67d8e582326443f3d68e71d6320a9fcf \
+ --hash=sha256:5c58fe613dc5e5336357eff555824a314d8e43282600435c8d1cb6a7a2fedd13 \
+ --hash=sha256:5e7cecbaadb83884793e05828cee59b210b24583b9c7425d0ba6a754fe22eb4e \
+ --hash=sha256:616f097f2fe415bc92a247f02e11f634e1f9e9a83d327e3c915c15089c87869e \
+ --hash=sha256:63bbfd5ded17c4840ac07cd8f1c21ba9d9708141f840b324f422f41b207e3973 \
+ --hash=sha256:64faea20f4e2613363a1a9b9c7dd73058f3ecd00133a511e72ad7c511658f527 \
+ --hash=sha256:661c298b4821edebead0c91edd2b00374d67ad7c5a1f7a91d4442633b79d6a72 \
+ --hash=sha256:68e62fe11f30d5ca8289242866f0a5291402d8529ca2178ab8afc5c9694ae890 \
+ --hash=sha256:6a8dddef476fab96d066d578fc88526767b836ab5ab21754e1d5bf3879c31c7c \
+ --hash=sha256:6e192623c49c94421616a5778fba35cf0d5a8d000650c1967ef4448ee5cdd990 \
+ --hash=sha256:7225e4514edb64eb6740324353e0da0711954fd8d7da4576755b1c6e09b697cd \
+ --hash=sha256:75f80557d1389eddbd0de2681f6a390a0c5338c31ddaa821381c203fc3fd50d9 \
+ --hash=sha256:770de9db11e84213beec501cfcaa013b019820ca881e03344dea5844f7876d94 \
+ --hash=sha256:7750c6449dff7864bb9bb27ddfb0267756189201a3afc911d82b3caacd70dfc3 \
+ --hash=sha256:7bde5e4cc5c10140859842b9d383af292b22639a4dffb725314baf45968cef80 \
+ --hash=sha256:7ce713ace7c0e4520535b42b77eaa742c16dab813978064913e5a3cf82973b41 \
+ --hash=sha256:7da0c5eff80f0197f3b3d1232ec5a682a9325f4ae9016a78f5f5ca35f9ced1f5 \
+ --hash=sha256:7dbb61fe3a7699468030f71bbe5f8a0e326a151daa91beb11a6fc1f980c55e1c \
+ --hash=sha256:811bd1e21d32de12efca32393a0ab3f5133b54fce9bd44b8bd77ab07da14bf6a \
+ --hash=sha256:8ef53b2de9bcb9197d31854256575d59dbac0cba72ac627bb291ef5eceb74be4 \
+ --hash=sha256:937c0052c05a31ca1daf18de3158eed4dbfcb9cc107adbea227728d647be701e \
+ --hash=sha256:9d2055050ea716bd38b7f7f1579c275386646b4894c155a3e2f3cd62ed41b7c6 \
+ --hash=sha256:9f8d177621de5cb38ee3e731eda45d421db093ec0739f46a5594babda7987a98 \
+ --hash=sha256:a2d7755bef5a12ed488f4ef1f1b69ee9191d7396083b755a5d2295f6edb4768b \
+ --hash=sha256:a48d62ab9d6f4f98c983223a547af44be6ca3691074c31cecced6facd3ba2dc1 \
+ --hash=sha256:a4f00aa42f75d6e4595e8866e748cc1705adc0cddfeb2ca86d0d03993d63ba03 \
+ --hash=sha256:a6e721d4b0e45d5b65e87534470e67b18dcd092c83f68fba09f152b9cbc061af \
+ --hash=sha256:a730a083190634c65cca36ba5f489531576ebd79bcd5c8e172130f6453127231 \
+ --hash=sha256:a931079504ecc49efed7744c476a5c343a92fabf66dec2db95edb1b2fdc770e2 \
+ --hash=sha256:aa9511c62d14da7aacc9b4bf51f3f697a621e83b2d6919008243c3aad168eea3 \
+ --hash=sha256:ab36d55f9ed2d067327667c2fea18dda018eb628dd6347aa01dda6cf1f5d3836 \
+ --hash=sha256:ad2c86c495b899d862ea0f4b42891b8713a3bd45dd4105c7fd51c2a72f39f3a5 \
+ --hash=sha256:aeae0e330c9f6acd681f647d46cefd30c29f93e3392882e792e82080c9691399 \
+ --hash=sha256:b0431303acaea1089ad4b3e9ce4e6518193def1118d4073ca848635ee4ea2e96 \
+ --hash=sha256:b5bdfd1c873d4e093aabc0ca84c4ca6dbc4f752afb5c86f146d9742580c9da2e \
+ --hash=sha256:baed1e86cc735622097354b9d1281406caf42ff42a886d29faa8e8d1630333be \
+ --hash=sha256:c1453022f490d2459a11819d83ad1d586e9ff65a12ac3e705ffebd46d3685dcf \
+ --hash=sha256:c26608d2222fb1e94487e4a387d85f13eb55d5ed725cb25a0c589ac4ee60e7bc \
+ --hash=sha256:c7659f22557c5a0bc4855cd635f55edec690cc008a40768527762cb9fb263455 \
+ --hash=sha256:c8c69575568085ba0b1b10c0249d779a214aea6f6522e949a0fc9fb0fcb449d0 \
+ --hash=sha256:c8d2c9fd1f2d16f780d15127abb050d13d1a76c03a4bd87d7e4980e45e511e12 \
+ --hash=sha256:ca82be1a1d406ecfe1d25dc16cb33488e5a16bf4438c9fb590484ea29d92478b \
+ --hash=sha256:cc572dace3f60ef98d7b12ff411d20f5362feb31a0439eab0085bbfd349982d7 \
+ --hash=sha256:d18e5ac0f2f03f4f518d3e23db0f0cad7faa1da8620e9c09461d443bbf6e6692 \
+ --hash=sha256:d28630f5854ab07ab1fd4aba756de52326c82e6be15d414b12793f1975048b54 \
+ --hash=sha256:d9c275eaacd24aa73f94ffd6de08fc3f932424d8b6c376f4bed7cde376fe7bc3 \
+ --hash=sha256:da0e573f9f97159390c89d9f1a9e41908b66d408cc5b58d08cf3847d844c531b \
+ --hash=sha256:dd31f52ea1086513bb9df30f8fcee9b8918323ae067a3d5b78bc826a000712be \
+ --hash=sha256:dddad92b554513a31f272570678ba307fb9f618f05e3d4a5eacafff9eae03e1d \
+ --hash=sha256:df423d40ee8654634421812bc3b196da3f9bd7d32929da813f8394c4348a5358 \
+ --hash=sha256:df913725b79db7bcf03448f36b7bf8815363417d5b58deecf9305e3e30f0f21a \
+ --hash=sha256:e0bcb7e0f677f543555d2adff3bf19c05f66cdb4796e5ff602442ab2fe3c4ef7 \
+ --hash=sha256:e2d65b31f36619cda3999b78b2aa9632e76b78448e7a56fc4240824200e7c4fc \
+ --hash=sha256:e6e8cff14d6fb0be70a09c0bdc58096f501952d04624ebf867e0e56da2df8960 \
+ --hash=sha256:f16c709686a78c727bbbf059f92b0bf41c6fc60deec706d2dc19f529175a6125 \
+ --hash=sha256:f24fb43132a4c6b4cb4eb029492919b2db645be6808d738f244fd146c03c32cb \
+ --hash=sha256:f53e442b08449d42821fa4a4fba000095af9f62742a500f978a9f557ec44339a \
+ --hash=sha256:f5cfbc5fe74540d335175b656c725d74d90e3730c626d92575eea35029d9afaa \
+ --hash=sha256:f81b3b8f3d4e343550fa4baa0e479bba9f2d29ce9c2e9b51d1ce1718d7442fcf \
+ --hash=sha256:f8ec5e643a9a937f64e1999eb9f75d072263751912dc5cd06d3c85f8f44be7c3 \
+ --hash=sha256:fb92203a88b3d3053034db775110081c49d28be6551923805e039924093761e4 \
+ --hash=sha256:fcd22650c908d7b7da162bbfaab594a1227a15d1643a98c68b122ac642fa2264
+ # via cryptography
+charset-normalizer==3.5.2 \
+ --hash=sha256:01077390b03f7988f11d700a2194e69b119741a86b1a638b1db88891e3eced8e \
+ --hash=sha256:01b0c0d2262a9e28e8484a278c7e1b5d650e3ac8cf2683d2967e25899f208bdf \
+ --hash=sha256:04851f73ae72b8413dddadb16a49dfee95263553741fd42d546f7d66907e6be5 \
+ --hash=sha256:0521c5665880b33d603717defa76c094048900010897909952397feb3039da56 \
+ --hash=sha256:0774bf9bf620249fee3e0b8b9fd3065de213be30f3aa94ce2494b3b638949e26 \
+ --hash=sha256:0891b9d3903c5571c03771ca669a4b0ec5618ca722a5c957d3d29cd4e5062848 \
+ --hash=sha256:0c951d5e6dd9c2ff60609476752bee49da4206adde960ebc247766937f72e718 \
+ --hash=sha256:0fed1d06615f022ee3b13caf5e8b180cfea32bb2c5aded8a9d44277afc040f93 \
+ --hash=sha256:114e4d0c92d618409ed82a99e22b5c5e768fe995f2973f78265f4524f49d4640 \
+ --hash=sha256:11912e4bb14baae7c5d8791aa55ba0a3a03ec6729073307b0f57270abaa713d3 \
+ --hash=sha256:11a4d68a6ecda3292cb1e50239e111543ba5d709bb62a6b4ea1afcfa729d8875 \
+ --hash=sha256:124fbf1a8ff966d87ae05bb8bd45a71f966055ed8bba320d0c7cf450bc5f4d0e \
+ --hash=sha256:1461ac396c4fdb983a675f20aa555624f0ee18ac83d832b9244ffff3d8055275 \
+ --hash=sha256:1503bccbeb36d5527790c3930327704c39af22de3112f1b1666a9f3ce15ee204 \
+ --hash=sha256:15bb4005af6320d259dc7593ca84a38d7fe06a421dbcf7b910ae23979101e787 \
+ --hash=sha256:15c44f7edfd477b06f517a5cc317fc1707edb9de2c865f43d4b6513907473234 \
+ --hash=sha256:16fa0eccf81304b79c5cd87f9271c3b85dd9dd99245e4422ae9c0dd45e0f99d3 \
+ --hash=sha256:183b88127acdb4fabe59d951ab424faf1af7b63cdbb5f776186c1ea2ffcaed98 \
+ --hash=sha256:195c26fb65950f8fce54e26349852b7bdd7c5f120aeefbcc440b8a20faaed4a3 \
+ --hash=sha256:1afb975bd5d68d5ce9f6b6d44fdf2f7e34b895a35e95708a7a91b20a3b51d187 \
+ --hash=sha256:1b4cbc7c3491ccb4aa17fcd8165649d01cf39f76de1696da8631b5f71b85401d \
+ --hash=sha256:1bc0baf5ef96b6ede57d47f4b8fe4d9d84019c3bfcbeb20a41edc6a6ee341f1f \
+ --hash=sha256:1c50fe28bbc2ced33386f298650d91218076c05420e6cbd790b913adc41659e7 \
+ --hash=sha256:1db38f4c5496827c1a501846d64d14c3b80c7e6714e406cd7dc36a9899fa1011 \
+ --hash=sha256:211d5a3eb6af8f513b8d4ca19a8c1b7accab1b5f0d3175f9826b03c1a920dc1f \
+ --hash=sha256:23851fb4e1b85ed3f6c2a27b777cdfe2e19fb5b38429a8faf38c7542b7665869 \
+ --hash=sha256:254eb48b9fa5ee9898a3c445825a1f340fe53712a098904b39b0bddba8ea3cb1 \
+ --hash=sha256:2625388c6c754520c37abaf3b41eb34d1cc4a373f457898f08606c8e362b891d \
+ --hash=sha256:281cb91036248400f4cc957495cccd44c275c2e0c5854f7e45ac5cf7dc193847 \
+ --hash=sha256:28a15fdad492a99b6eccfaaed66ef3f74050680545ea61ec8b2f4c538f1f1320 \
+ --hash=sha256:28b4f0d66fb834ff90f28209ac7bce77868c45d8c93e26f906709d9b7c2e1af9 \
+ --hash=sha256:2a925889534b3748302dae5dead07cc13480de1dac3aea80a941b729b471ef93 \
+ --hash=sha256:2b7b3bbfb4fe8ef40600792d762fbaa9057559f9d3fad209525b7a22b99e91fd \
+ --hash=sha256:2c9ad19a6cfcd5ea5c0d41161d22f9df1dcc277e9bef2751391334546a314c00 \
+ --hash=sha256:2cc961b171b3f3440f410489ab3573e86aea8736134ebbb40ea1338b7f0831bc \
+ --hash=sha256:2ce45c6627b22c47e390bc91a41c3d13032192e699fa0bea96e9671b373d69b0 \
+ --hash=sha256:2e06a3a98f916dd41d27f3105e02e7a40181c98c94b9158733d03a6f80506c09 \
+ --hash=sha256:304d5463e65a35d7bb0850550e0780395395f6fcf452f04db7d5ca7cecc425ac \
+ --hash=sha256:304d8e4d493af723536393eee0c689eb7813f4a474c8b479dee63f1fdd98f621 \
+ --hash=sha256:30fcd120b732aa79317f08dee04d7de0847822e4cf7ee0e9f445bb958832252c \
+ --hash=sha256:31f3930700408d211f13378ccbe1c40845d8da54bd0681fac3a9b5aae81c7aa8 \
+ --hash=sha256:34276fd796040bf0993ab33a369aa572e6979c7aab225a88893667ad8eac8f7a \
+ --hash=sha256:355ad8011081dec5412240c087a9a0c9d4d5039f3ed11a3f13e18c2b29b56c51 \
+ --hash=sha256:38a873987f3be698494da8b2e3085e29da02da7b633dce73e79c699a113d7bf0 \
+ --hash=sha256:39de2a259fc954455c57274dc94c79d5842774e1247a016aff30bc0efed0f4ef \
+ --hash=sha256:3d14b50de6bf4d0edf857a9386836846f982b8f524e188e2e68b96d702bcf4aa \
+ --hash=sha256:3d21b8b13c7592db2ac5e544a6d83187b995257472b0c9e8351b6d507ae37ed6 \
+ --hash=sha256:3d31298449090ab8d47b7b1b2a555ff73cac7ed438a08b7ac160980c7ebed649 \
+ --hash=sha256:3ddacd27458c45bdacd6bd6db644bfb730efbf9e830310186e3045c9c5be8fb2 \
+ --hash=sha256:3df041de8887954562c9b261cba85ca0e9ded74048daf125f45edcfaa4832229 \
+ --hash=sha256:40ab6bffa02ae10a0581e6c198be7d2d8ca5c2a0c64e4ed3465d766df457573e \
+ --hash=sha256:4275811936e2f06feff5e598fb42a1b7ae852da8e39605211892b56b81a34efd \
+ --hash=sha256:443eae2bf318abeaf6f15d785138f71fd6de770e99a92158b8b814265e079115 \
+ --hash=sha256:447441e76ec720b15e64418d32e092297340387053047c7c694f579efb0ee1d9 \
+ --hash=sha256:4495c5002a7b28557e7e222e77e0b661183e432b7d6d2e788101e3f240e05b8c \
+ --hash=sha256:44bd4fbb29dfbeba60e7d2bd000c59e4b21ddb3cc53912b14048d37092706d7c \
+ --hash=sha256:4685902cf26edf013ed7a3da0f426ebba7a00ebb9541386d835afbf002c11cab \
+ --hash=sha256:498dc3188ca05a68231ac3fdbfc7f57eb67e1343c30e0fea17f8218c1599b253 \
+ --hash=sha256:4c2b5031f63e331e3839b40aed2dd6f191e9c07edbde303e7876846ea1946995 \
+ --hash=sha256:4d48f2d08b9de5864e2c8744d4461b862fb149a18274abc8b698c45975573438 \
+ --hash=sha256:4f87960d57feabfb618e4e0af6e7371645fa26a277860739d6e5d6e0012c92f0 \
+ --hash=sha256:50e3adfb96fc189eb27b1cf62d3b598b89b4bb0420d93a3d3e42e137409011be \
+ --hash=sha256:51cf45226a9b588d0d2b4880c62d686934b63ab0bd79ca23ab0e9762eb27441b \
+ --hash=sha256:52aa6992700996af31f375de0c6bacd402b0097fe40b53c426b9f51a90ebabc7 \
+ --hash=sha256:55ea99acb17b9325618de155a0cd6a2e8f5d10be008113e1d433bbb58db543b2 \
+ --hash=sha256:56bc200a365efb37383b7852e4cc5898d3b2da5987289b543956cf8cad71018a \
+ --hash=sha256:588461c2e8384d309bd63e5826019b6977bc66d629b99ac8737bb795d7b2cb5a \
+ --hash=sha256:58ca3755ee7ff7f59b57789ec9833c9de9ea275405cdd240eda1f193112e398a \
+ --hash=sha256:58f361dcbab699cf8f42db3f47c8e7fd1036f138c23a5d08de9fde5f425a730c \
+ --hash=sha256:598a11a2c7ebaa5334bf698bf29568c9c390abac6a154d8170fedecd1cea38c5 \
+ --hash=sha256:59f63901b0031c3136cf64704dcb21de0bbae62ce2c9529bc39d27665463de37 \
+ --hash=sha256:5cde776b7cc66e4f6c99612cea4aa7269aa65863f7a15841b2c264f103822f4e \
+ --hash=sha256:5e2b6b57e9733d39f0c9fd3185efa6b8e29652c4cd8fe94180272cf6ed9a78c4 \
+ --hash=sha256:5fb29fb8cd1a46c27a1bf9613ad5ec2599310d46b4025d9556404a6b6a292800 \
+ --hash=sha256:6045373d5a89a5ec71afde535db987ca28e76dfa276c2d4c818265b375d4b055 \
+ --hash=sha256:619799369eeef6366ed3e8755a5670f4f2f0fb6b30a0fd7264dc0fdc2357058e \
+ --hash=sha256:62588a277bfb59def052abd940703fa35107152bf479781a878617d60faf8fb5 \
+ --hash=sha256:62603db9a7caa0802eaa28c1c46fecd7b3a263a774069c24c3c28c302448721c \
+ --hash=sha256:65cd72beeeca9d3aaea1201e5923859f308f952f9c71de93f06063c79f0f7a3b \
+ --hash=sha256:68eb192d85ab8e5f6ec69c2bc6ac0179fbf04a5ac1569d12fbef74883fe102d0 \
+ --hash=sha256:6bd128f206a7752ae1f2ab6c61bf8a24ba28913a10df8b14c2637b973ff97a80 \
+ --hash=sha256:6be488a102b8cf28d0391d8c4ba7748938ae28b78ad901f8585520fca33ead1a \
+ --hash=sha256:7218e8f32b0956cfcd048fd42d9d5779809745ca1d86113ca56f66e7ae1549c4 \
+ --hash=sha256:7441d755b7ab94f8d4eb3e43ec05482d760842fd263d003a99102d742cd835e2 \
+ --hash=sha256:749e97e1b32313717a565abbe321bc2190bc8b35f1a67e4cdbc7c56c8d8ffe58 \
+ --hash=sha256:75a3ceed0724d625d64b86ca20aba182e4df462e04c2414fc941c0f523f06aac \
+ --hash=sha256:780fbe7cab297b81dad9fb8dc5eb003c0468ffb0d9e5f65068c53a34661a96bc \
+ --hash=sha256:78456a747de8dc58360ffa581f30a002baf5aa28cb262536545e91f113ed7639 \
+ --hash=sha256:7967d08cf06dee78443b874f98c98036f624f3a4e73e11f9f64f5be4d25393cf \
+ --hash=sha256:7a881931aa470808df94a8c380eed2bbbc76cd9dc622310f99665658c821eb6d \
+ --hash=sha256:7dcd882da75ef9adf94903b1e3b9419e8aa8fb4c7396822b834b9ef7fb96954f \
+ --hash=sha256:7e841fb9010836c992c9f12fcbd43a831de93a5f726fc1ccd8ca1d0268c5014c \
+ --hash=sha256:7fdde2c9fd9e3eca40631e024664cf2584272cc8f96308cbe5fdfc930f51d8bc \
+ --hash=sha256:8024d00c3faf3fc0c16e07a69f4405e8eac7cc0ab15f65fe6cf43827c4cf72b4 \
+ --hash=sha256:80d02b6f04e92601a081dd97b23d3128033098bff5d35d392ddcc0476ea11253 \
+ --hash=sha256:838dcc90063569a0448120554591a1d6c4a4ffe11babf048908793154ab86ade \
+ --hash=sha256:849df64e889b2e17230d58410a03dba311a65b163508fd33679b2b737d4b7858 \
+ --hash=sha256:87475fabc8d9996fd9c27debb395e642e8c838d78a00b6e932227a0e06b81e26 \
+ --hash=sha256:87e50a3e7cb90af586b6c5faf23e302a970415ac73bd7bd90a515a04b427ef96 \
+ --hash=sha256:89b53f3cda69831909888e0494f4fa0bcd3537e3e138dabeb620bd6ad946bae8 \
+ --hash=sha256:8a893cc101149f80a653f82062ebc95b34525a2614382e1da5458fe7c6997249 \
+ --hash=sha256:8b2bfab86aa71ae13aa41a6a26aab338e0db2b8bc75434b05aea89e011ff35a4 \
+ --hash=sha256:8d86d6fc60743dc916eb79e2eb1ec4818e21e427731543af40a3021851174a13 \
+ --hash=sha256:915563965d418f986e7e145accc592eae9e1a1be3566ff98a05d7a9ec42a76e1 \
+ --hash=sha256:92888bb3187c5ba50500b00b3b310c9f2c651709d28036077680cb5255450a03 \
+ --hash=sha256:93223adc95033dd47133a46ccfc316a0139176fd79085762e27202ec56018f03 \
+ --hash=sha256:9373ad13ef0d2c0fb761e04e55bfdee5a08b52cef2c882c8fbe9935b1517152e \
+ --hash=sha256:9409a8bf35cf78353942504b24a57de3d75b708997a1e4bd8db71ac8633ce364 \
+ --hash=sha256:9b7f416ff0978e2f2249330527f0ad6fa02f4932e6199692d3b52da2048c19e4 \
+ --hash=sha256:9bde855991b7e362c146535e3136a50bfaffc0487d38b33ca7e5edefc6e23849 \
+ --hash=sha256:9cae88599c7219005d879f98e5ed53341e9a122af585e1091200358a3003d2a0 \
+ --hash=sha256:9cf9b1a857e25c4baceeb3624e92a56df3668f398c4acba74e174d81fb4d1d3a \
+ --hash=sha256:9f56f72050826f63dcee7a7f55b0a77168cb3bfc553fd405e7f8f9ece75a4036 \
+ --hash=sha256:a090bb2c68df85450502e3e20d665e3a5af9c65a84d6508ed477badd49166fd3 \
+ --hash=sha256:a192e2c40070d92c3ccf777e3a5c4ff515573cd2bb7ed0c537fdadbbec5bbf21 \
+ --hash=sha256:a19a731138fc27d5682277d3b9df22855cea1239bce7fcec5f78f42ef2d1f3c3 \
+ --hash=sha256:a66c3bc5ab1f0ff2164fc9965ddd611ff0802173f4b9d24554c563f6ab7e1d6e \
+ --hash=sha256:a815775b6c38d4e0ff7bcffbeba67feded90202bb6a226b8dd35f1c855217413 \
+ --hash=sha256:a89012d6d5476ee112d20d998570ed58df2260a852afb1758809cd6900411d21 \
+ --hash=sha256:ae4f5fea5b8b8ccff88238cc8569303e5ee95efae67fa62922a311397a71f346 \
+ --hash=sha256:b6856554c4f44d79fc2307d5768854310a8f0096e501c75637542c82292b0429 \
+ --hash=sha256:b6b751274acb69d77b3323d6b7dbaa3c7fdfc1eb829b7eb61d262f32e1af9685 \
+ --hash=sha256:b736353c0a625bbd5fcec108576e2385db3496f4f771f785ff32e108d3c3bc45 \
+ --hash=sha256:b7fd005a73d9e657273b7a10dc71a9e03c8fb9ee6999798d6918ce095b81ac7f \
+ --hash=sha256:b91363207bd9dc966a691e959bb47f64b30f7ac4b072be9968b366982f7db77c \
+ --hash=sha256:ba0b1d2620edf869789c3879223f52bf2afc5d31b3cb47cc57b3a12c05e2aa9d \
+ --hash=sha256:bbbfc8e28816f19d7c0f1816664980c0a9875d01b27cdf8eedddb639d9e108ad \
+ --hash=sha256:bd16aabe4a02a297c23417aa17ac6299dbd8c49f673bcd645b4929b11f5a4400 \
+ --hash=sha256:c0afc6800ba57ccc350374c5bd6150419915d95ce93cdbab2d783d75eaf30ecb \
+ --hash=sha256:c6708715abcf3c73b99508253e961a9967f02fe536532834149574eda6de0d1c \
+ --hash=sha256:c7c9ab723cde841fefb34efbad91e87f00a674b1fe1cd0784fde742bf2c154dc \
+ --hash=sha256:c8f3d67aeaf55f017982b73683f0e7342ba2f6635a78f69ce89ebb26aa411e5c \
+ --hash=sha256:c9790464842f85f437dbbb54417eda1e0e6bfc52dd8d22d6fd1c994b73b2dc74 \
+ --hash=sha256:ca403d7e4798f525fdfc78e258820419cbbd0f0ecbab9de7840e3c017cf6b8cf \
+ --hash=sha256:d008d90a7f2471519aef0c90dfbe73b3e6e4d5e66ac48e19154c17e89e98b604 \
+ --hash=sha256:d19fbd981a488e22cd04883659ca6b08f50b5974f9fd7c95655ef6a043e5893f \
+ --hash=sha256:d1befeed746d247c81127bb14de9dc3d30edb6e5976d34f83f86ed262b1d9105 \
+ --hash=sha256:d2374b62878abb00cd8309b32af6c0b715cd02dec0ca74ef12e5069bdc64144a \
+ --hash=sha256:d376bbd28b3a8999db1a103b3b388aee6f1ddeb3e51bc2172993efdcd86e064d \
+ --hash=sha256:d4a7319f304a774bed22115bc891618e45f85065ab44ea6acd07d274e750519a \
+ --hash=sha256:d6734d2ef8a50fbf8445c139477da401f50d62a0606bf00e20ec6d87773fefb1 \
+ --hash=sha256:d760fe2a4d7c3b226cb9026d6a842868d52a7901bd98420e1baf14e80da85cf5 \
+ --hash=sha256:d913de495d90407cd859d263bee2e5d1a4ed3eb6573c04e70d9ec619a7cbed7f \
+ --hash=sha256:db19d07e2e0129e974a0e65d0064fc222a446cd5122c2fd4184d2af9fc734a9e \
+ --hash=sha256:dca9ab98072a5a54ebacebdc45f53e645336b320c667410b061be1ca588ae709 \
+ --hash=sha256:ddc7dacc8ece3a182e7f15cb862d1fd616b46d076cb1ae9dd232b2c38b655874 \
+ --hash=sha256:ddf19c062bea7a0cc80f519243d2c01dd091be0cf952a0750d4ad576709559f5 \
+ --hash=sha256:def79fa35ef0cef8d2accec024f4fdc7ead3012ff02f5215c783f39f03ef8cfc \
+ --hash=sha256:df29a0a7107f7011e77f4eebdddec4c7331e24d787a0b21a46d63bdf7445da95 \
+ --hash=sha256:e09a3942ecbdee5cce73ea9d42da82b81b72ac1bf031ce069b93b5adf4eac8cd \
+ --hash=sha256:e242bb1c5e76e97dfa9e7f209a71e93a01d7f19ffdd5cfbb2e2d55b4f08f8ab0 \
+ --hash=sha256:e243bd13217235fc7290c621941c3f5cc8b66e4872495be821d7436ba2fb838d \
+ --hash=sha256:e2af3aad578aa6bd1384bcf4750fc285e5a9de53f40b7d41e5a0bf748edeb2b3 \
+ --hash=sha256:e4e81e09c1578b8df602e3db08b0b3ea0a6947ad612f52bf8dc5ea8d47691f0c \
+ --hash=sha256:e54da4baf05720032d527874d40b65fa4d7e5c6c6a43d0c3adbeffcaf275a2b3 \
+ --hash=sha256:e80e6c2f55656b4824d72065abb4ddd6a525c74bd78a0aab5d9fc2cf4fb5af50 \
+ --hash=sha256:ed2a239c0ea213acc1908150a3037257083c7c083128f1a4cec2ec4b97dca491 \
+ --hash=sha256:ed905975ab14056a2e5eb1c376cb2e1ebc5396baf84163939c518556fccde9f5 \
+ --hash=sha256:ee21e28f0430bd6dc9086c6e525d5e818a44a5ad19720c8a0ef766792f3eb5e5 \
+ --hash=sha256:ee43c17b173d46a3212baa6ead3ae258eeabdae48c263a01ccf0218c366dd655 \
+ --hash=sha256:ef4fcbf3327382cd4c9f540babd61248208af7b93eec4de397b4d5f58a09e288 \
+ --hash=sha256:eff0ac9dbe711a4aee69bf04a83896aa9b85f19641264053a9f6d48573abb7dd \
+ --hash=sha256:f0aa869112ef88429ae17820d99c3dd9504c9e9c671d3c246f3d7442cb051084 \
+ --hash=sha256:f3c96f633825733f735c5a9cf21d21a257d8e1edf0b1cee0a064b9c424ca0f7d \
+ --hash=sha256:f5833ad231be5eb6553de524a70f48d71b2c8563101750531e0b80184e175cd4 \
+ --hash=sha256:f5ec61164adcec446f8969a3358ec3f9b26bbda3b9213e5586d219afa8df2915 \
+ --hash=sha256:f7d486c83842422badd511868fd8a9a20e9407ace71564b6af47ce7e60a336c1 \
+ --hash=sha256:fb9e68df06293761f9fe66ade60a9bc6d0f5e42b8acf2939a9158af86ab0e5bd \
+ --hash=sha256:fc14a032f813bf5fe624d991960ea83e9715adc27e4c1830a2361eb1d02ac341 \
+ --hash=sha256:fcff63213e8e6e47770541a4607175404f47cbb3ebea7b6058cc82d524a0e424 \
+ --hash=sha256:fd1fbe0f116b6e55da77aca2c6ddcddcfac2186cbf78bdebf40fc156efca389d \
+ --hash=sha256:fe9753dfee015c570d73df76f899f18444d41388bffcde097deba51c4fadbb9f
+ # via requests
+comrak==0.0.16 \
+ --hash=sha256:0142dbc052d15b60d144999c60683e8dae2490f1cdaab5f2f08a59028b550568 \
+ --hash=sha256:032e53530822566cc5500c557ff0208afbf33f03d7c1b999bbd3f294ab828087 \
+ --hash=sha256:064d86c3d3e7c3bc55a5c621b66c54f1f291e73b3c5dc2f8fc9a97a64a2ec50f \
+ --hash=sha256:065d31040abe7544f77a36709c75d7764255be5917eda108f1c930bf807777aa \
+ --hash=sha256:16fd8458fc76a4dbf7473261e40fdff17e4af87f69133eb4d09ea8d40f61a2ef \
+ --hash=sha256:187770273c74749746f7fda91313620851552fe6afd96c8601efac5e52563926 \
+ --hash=sha256:1b61b04fe3a584f9162a866d3478c7e594ebe28a1f7056672f4326fa6f960ebe \
+ --hash=sha256:1bb98eb6ea3035c3f39914733fb764cfe98a8ea61c79fbbd6e9a8d92fd247a46 \
+ --hash=sha256:28c7387e337d9ac047744a2ea69cc2e1f154ccebaa1404b55d43cddf309be2dc \
+ --hash=sha256:2d843c90a7ade87408fbf8b6d6a8bdd9a855b784086ecbce9d968e61d0208a32 \
+ --hash=sha256:34873dac10e07fdd5befae53ed95be947611224b6be60efa9e9e2aa0b5c99a5a \
+ --hash=sha256:48c73528cb5b0fbc46951cb72a6b7bf782ee50e5b8d58fa8195ea8b4d1d2f113 \
+ --hash=sha256:53ce74a0052810be0ceb78ed2f0c7cdb92d66c6fd6d56c007ff7f6aab80daf32 \
+ --hash=sha256:5e2e960b2188efcc58f34034906e2eacadea67780b6edc4d501c522835b3d15a \
+ --hash=sha256:6a4f3dabc0e0242c5f8be9b33824b4020e894e0930ea16c2b6cb8ac4e8230274 \
+ --hash=sha256:6e527206db1dc313a807471a1c721575d3072fc11f3d02274b5b647b278b1cef \
+ --hash=sha256:768faa7b1912b62ea454b89c5a3e22ccbe23f10d8662c53400ee1b3b7fa5c0bc \
+ --hash=sha256:7f1009a6c09138a4c0769989fd3d8a9e1627930b0b7e50cafd43709a5789a526 \
+ --hash=sha256:7fcf7cb1151870a5390df7ca1659fb9f98dbf3bdde2fdd6c3d9bf00802965870 \
+ --hash=sha256:814ca7670771a9f17b062a4b25b7a86637ce2fc662eded75966d70850c0c644b \
+ --hash=sha256:87e4d62ef35a2073ae97d225895028c051c7ee573405b5fe5b99709f67b97eb4 \
+ --hash=sha256:8bbe78fd008dc14a8e846d97043fe588d08fa05833ef6d9076e5b2b668710de0 \
+ --hash=sha256:8bbf5572b2e963e0c535653bd7250bde91c08dd66a8487ac18c8bd01a06af37a \
+ --hash=sha256:921d306b5d42cb05831b857bd67bc49176ba2391b0df2ec5060d79be9b332d45 \
+ --hash=sha256:9790558f62dee76336258f86bcb5ff953d03e0fe7180480980774be950ebd6c1 \
+ --hash=sha256:984cd36a060adbb7796e14675e26136d5cb9d29740e5e70ee269de91b419d3f3 \
+ --hash=sha256:98bed85aef13efa1f95c51a1284ef45b0902d2409bdb9d153f9f4b1f519a4007 \
+ --hash=sha256:9918c35ecccee7b207d4877520058a2169efeb347fb19e039f7b1c5902e94fca \
+ --hash=sha256:a3a27e1f34c66572aa25c9df3d4e658b953e3d1c5113bfa7094ced53520bf9db \
+ --hash=sha256:a3c59ac1edbd7b34addd4f35a352f0e4608bc851f552f9d48df1ba68a8be251d \
+ --hash=sha256:a41e4c11bf9ca9d08234e15bd42e95a40bff6780024eff9e5ac1b82ec92059c3 \
+ --hash=sha256:a4439723a646898ce2f723bd62ef12b84a2fdf2b74f99c76721a9dda8398a1dc \
+ --hash=sha256:aa3d73ce79522a14893f640be088d033e7b949c5dd959cf92b303e7e8b8dba3d \
+ --hash=sha256:c835bdb520b8672d7a2b12b5b37cd0fdb7d64e527e6263b38b779abecf1cc5ea \
+ --hash=sha256:c86c286387352ea6d3449961ca9674063d1ef07b048e5a234e0023f1b40a221b \
+ --hash=sha256:d1a17fb510f6c82bba3daf6f24e259ceb73b3abf989b9b1d10546bfd0d1baa14 \
+ --hash=sha256:d296dfc3f655b376d24dd70532a91bf6921da9cddd473cc622b2082c05a408b8 \
+ --hash=sha256:d765c9398f70648cf7cbccfcd64f96cf768f33e4441353951fd85bad686906c7 \
+ --hash=sha256:e609d77c10b0c010f0e1ec845a49375603a9b8a7f8e402eaca4001334012d84e \
+ --hash=sha256:e778d26814fa537be2138b3e4613d0e93d0ca38fa1f8d23e3897bea3c7f52823 \
+ --hash=sha256:ee371ee417020dc53d7b1a57e191793710e1693605223cf9f38c0943275625cf \
+ --hash=sha256:f0530b214825fe1b754ffec06c181931ce174c2969c6cefeae84d0fed322fb3e \
+ --hash=sha256:f2a96811ca48224d493c257427c8967d2f2c84041927dc8e37d89c5a2c6e790c \
+ --hash=sha256:f39d9b7b1bc3018ff34f4125e6a5b773e8830a0a26bb15401f3abcdf90ecc96d \
+ --hash=sha256:f61b86065916cabd8b003133b79b11cfc634bf8cf947aaa7f7972e87d2fa5ec7 \
+ --hash=sha256:f8e5a77283efe7656fbdf418a4ea530f1df234405ab0489b9772b60de0a499c5 \
+ --hash=sha256:fc4c4845dc32ee3998401740e0ed4af1ec9254a086387b070d3a68d9830795cb
+ # via readme-renderer
+cryptography==50.0.2 \
+ --hash=sha256:0ddc924c04591c2811ca024d62ecad4f7f6f08af8939c211438f48a16bd23602 \
+ --hash=sha256:0ec5f09541743261e66e291b4a0cbf0fb2997aeaab6d9e9c740b9dba1b58d1c2 \
+ --hash=sha256:0ecbc5652bdb6fc9eaf89a7d196e20941adfe812f43bc4ca05d9150496821047 \
+ --hash=sha256:1981f1db4630889b9ef7803fadef12b056f428cb6b85c27ba57b774793b6093c \
+ --hash=sha256:1ba34f04897fcdaa73f74145c25f3ec146fbd56593853e88adc2e811303c5f42 \
+ --hash=sha256:241449bf940a5d27309bd317e6f9a2af6932113818bb2b8f5c59ddc7ef16da18 \
+ --hash=sha256:25784ce8b9621c90c643efb9e1e2162ab3b0224cae446ad5e70e7fcb1ce18b51 \
+ --hash=sha256:3dc4fd8058cea1644971207d530e1a03a184a805ffc8ebdddf0599d78a331b81 \
+ --hash=sha256:4061c0079120205fb760c58acab6443e217307dcf05e3702cf970e0689972856 \
+ --hash=sha256:4a20ce1e5cb4284a86692fdcba7cb8754185c6b2e5c56fcef3751cf451d3cdc2 \
+ --hash=sha256:4e81d95e5bafc2d6e34e4bed780e53e4d5b9a2f928573428aa4d35fbec1eb0de \
+ --hash=sha256:58a0c478eeca76fe5e07993c5a0703def34a6dc6a0cda4f5564639b33112ffe7 \
+ --hash=sha256:58ddb5a8e3179d12f19e4ea34d2d32e9d63a4baa142c875c1eb59f41b7243acd \
+ --hash=sha256:630ebfea3bf689d075f82316324ff7433dc447fe6bc1bfc76524b74b4a9567d2 \
+ --hash=sha256:6f8700550aa1474a91e5dc07049c46f98b423b5b1ddd0483e0b51362eeeaf5be \
+ --hash=sha256:78198641e5be9521beea5aa782bb551a58068d10e6eb04c9c680c1b69f2e7d45 \
+ --hash=sha256:79def8d059362e7831389ed3be0ecdf58a89386e1271e35dd9f5af84e81bffd0 \
+ --hash=sha256:7a8701d6b584d76e909e3d305b7d126b41439876a5aaf76cddc67fc230eafa2e \
+ --hash=sha256:7afa5a6602a9f29af1f3a2965f831bae7c9d5d597b7cbb716d41ab3b7d89879c \
+ --hash=sha256:7b46165bb56eb4704e2eaaf86f3c940d19154535d9b0ca7d6d590b04060e00d5 \
+ --hash=sha256:7b75de3c8b3be1cdb1052747c929440c3eea46c1bc2cb8a6e3a48388e9b7b452 \
+ --hash=sha256:7c6d0330c472d96f6a6afe24d80dfdf15176c33096f0a4397ae4c60f3dd3be48 \
+ --hash=sha256:828d49b0ff5a0e3975865571c5d91dbbdd0d38d8289b249a163e9425413a5e05 \
+ --hash=sha256:84f964e537f916e2cc85199e5a88742e964939b575ac8598b3f9d6cc416cdaf1 \
+ --hash=sha256:85d0d9a31b9098e98534226d5686b47264b95e62ce459dc2e62fdfc809f9fe93 \
+ --hash=sha256:87e9ce85beb6b328ba370cc6e6aea483c92617b4c95b1d33a49297eb662bfb04 \
+ --hash=sha256:8c71ba2cd31fc93748c38e1b613200ff1c2665cbfd5341fe3a61cfde35a1430e \
+ --hash=sha256:92e665960f25fcdc73725b9cec7a3824f279ba97a98653afe9ffac2e43668f67 \
+ --hash=sha256:94e5e9f108ee10471288214d3d233fbfbb492840a8457eb85178d643ddeb32c7 \
+ --hash=sha256:9c8402a82ea0dc4ceeab793db05f0fafa8ca139ca34fcde5df0f596103c74107 \
+ --hash=sha256:9dab55f57c74c3cad24c323bacbbd04be4705ba6eb0d92e920b1fc4837ed5079 \
+ --hash=sha256:a582ab2ae1d34f67112cadc86702774c9ea4374df6bca6afe672817203c99134 \
+ --hash=sha256:a6557e5f38e065ca9fbdaf7cfc7435ecb1d113aa81a022d1b51921ee7432e227 \
+ --hash=sha256:a9f7355e6fab51f6c369b86fb7571cffa05edee2c2121e0380a37fb9ac1cd5c1 \
+ --hash=sha256:ab50ee449bf968271e820086f10a33d101dd060370abc10bcd22279be2656539 \
+ --hash=sha256:ac9ed99d81760c62fe89d5f0815cdfa1ba9a35141cf30f1c2d044f04b4803d2e \
+ --hash=sha256:b13478603dcd0a2479ff8e87e2c19a7d525734686fe3c49542472293a204212d \
+ --hash=sha256:c423ab384a46c4dff7217b2ea5ba2e11cffdeab6441acd04cf65a369caf0366c \
+ --hash=sha256:c5e67125c7dca78d199ec4e116aa93dbb83494808ecbb8211a2cb09b1bf41dbd \
+ --hash=sha256:c71be1cbfa5cd9a41ee452acf1eccd82b2c05950358b106ec8ceb83411d1a020 \
+ --hash=sha256:cbc8738fd8526d80f35cb3a40d41f41a2e7030bb3b18b09a6778ef63d291c2fd \
+ --hash=sha256:ce47f66801c20ec6c6632453bb5960fe38939e9306970b48b3a5a26de7745d94 \
+ --hash=sha256:d370b8d1dfcdf7130178137f6fbee6140774a1acc6cacefc4b42643ec11d0a3a \
+ --hash=sha256:d38cdff612d06fa6a32840d5e1b1f7a27cee4a349aa9085d94a67789d6bfd408 \
+ --hash=sha256:d8947001be83df1394050758ce0e745dd74fb134eef0a4b5124208dfc3a68c37 \
+ --hash=sha256:deb9fde5c60e437ee4821bc9bc39ff31b42135c27e1dc61ef0a629389c1de62e \
+ --hash=sha256:dfe9763530994147d9af1def057a5b9658b00e8f8fe8743d144d1e0911c2e454 \
+ --hash=sha256:e105ab60406787da31fccc883fc0f733af1efd78f0136a4599692c4083a73d0c \
+ --hash=sha256:e275096ea1e60cc595cda2836fd4a6c725d1125108b868be17f53684d164e2cc \
+ --hash=sha256:edc3342adf8f697fc5f59c887a304356f147b397809440ed64e2fa6af2f50f37 \
+ --hash=sha256:ee247f5c245c9a2fe7c8e2214e295918838e44e00a45a6718451e4004219e767 \
+ --hash=sha256:eef4c2f3423810b3070ab391f85436d2f8bbfcb286ac15cbc73190b3563b1f1a \
+ --hash=sha256:f21e8a22c8605750c7af886bab299a363721264061b4ac0a30efb73cfd58efc5 \
+ --hash=sha256:f265528741e048bce55c3463ed721fb0aa45a5888d8add8cfeccb3035451bbdc \
+ --hash=sha256:f2f9bd7f90c64fe89253f0a2c05e3c4856072660429ce8831b4235bf29403a67 \
+ --hash=sha256:f785f6161f202ab04d8ca194158968798e480ca058943907972da5f12e2881e8 \
+ --hash=sha256:f9f6143a8c75945eb960d9eb98905a441394abfa24afaae239d514ffb2586480 \
+ --hash=sha256:fa8f5efb344d6908a1ce62f4a24e2e5780f825d6f53f5f50ec5ffacac72936cb \
+ --hash=sha256:fdd28f912fccfec1846a94e2e1e8f9b0012f557f0c46fe4f3eb0d7a87afcf90b
+ # via secretstorage
+docutils==0.23 \
+ --hash=sha256:25d013af9bf23bc1c7b2b093dff4208166c53a94786c9e447808335ef1185fea \
+ --hash=sha256:746f5060322511280a1e50eb76846ed6bf2342984b2ac04dc42caa1a8d78799e
+ # via readme-renderer
+hatch-fancy-pypi-readme==25.1.0 \
+ --hash=sha256:9c58ed3dff90d51f43414ce37009ad1d5b0f08ffc9fc216998a06380f01c0045 \
+ --hash=sha256:ce0134c40d63d874ac48f48ccc678b8f3b62b8e50e9318520d2bffc752eedaf3
+ # via -r .github/requirements/build.in
+hatchling==1.33.0 \
+ --hash=sha256:415290b84f464d2884303fca8974d38e7b85579069fab02a15db0828fbb1446d \
+ --hash=sha256:4c422bd4d554fcff5de5b73e9596f85e41e9f97f7e553d8f7595ecb31a627bef
+ # via
+ # -r .github/requirements/build.in
+ # hatch-fancy-pypi-readme
+id==1.6.1 \
+ --hash=sha256:d0732d624fb46fd4e7bc4e5152f00214450953b9e772c182c1c22964def1a069 \
+ --hash=sha256:f5ec41ed2629a508f5d0988eda142e190c9c6da971100612c4de9ad9f9b237ca
+ # via twine
+idna==3.20 \
+ --hash=sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44 \
+ --hash=sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c
+ # via requests
+importlib-metadata==9.0.1 \
+ --hash=sha256:ab830580bc0ef3db61ce8fae716389e5462b67e033018bab6d8f80ef17172f99 \
+ --hash=sha256:bba5600596a7e21f3eef53281cf28d6a5195634d2f2b78ff9501a3272c6eaab0
+ # via
+ # build
+ # keyring
+jaraco-classes==3.4.0 \
+ --hash=sha256:47a024b51d0239c0dd8c8540c6c7f484be3b8fcf0b2d85c13825780d3b3f3acd \
+ --hash=sha256:f662826b6bed8cace05e7ff873ce0f9283b5c924470fe664fff1c2f00f581790
+ # via keyring
+jaraco-context==6.1.2 \
+ --hash=sha256:bf8150b79a2d5d91ae48629d8b427a8f7ba0e1097dd6202a9059f29a36379535 \
+ --hash=sha256:f1a6c9d391e661cc5b8d39861ff077a7dc24dc23833ccee564b234b81c82dfe3
+ # via keyring
+jaraco-functools==4.6.0 \
+ --hash=sha256:880c577ec9720b3a052d5bc611fb9f2269b3d87902ef42440df443b88e443280 \
+ --hash=sha256:99e3dc0060c5cbe8fcd1cdb36258e2a65ca40f1566b2033b12abb1bb44dd3c30
+ # via keyring
+jeepney==0.9.0 \
+ --hash=sha256:97e5714520c16fc0a45695e5365a2e11b81ea79bba796e26f9f1d178cb182683 \
+ --hash=sha256:cf0e9e845622b81e4a28df94c40345400256ec608d0e55bb8a3feaa9163f5732
+ # via
+ # keyring
+ # secretstorage
+keyring==25.7.0 \
+ --hash=sha256:be4a0b195f149690c166e850609a477c532ddbfbaed96a404d4e43f8d5e2689f \
+ --hash=sha256:fe01bd85eb3f8fb3dd0405defdeac9a5b4f6f0439edbb3149577f244a2e8245b
+ # via twine
+markdown-it-py==4.3.0 \
+ --hash=sha256:7aa1511a46c39138de78d9eba92ce47e63124d8003fc98b3a351909e04239efa \
+ --hash=sha256:91a58fa5b72c71a40cf7177250fd767480d7a2bb3ac426ccfb76fb90305fdaaa
+ # via rich
+mdurl==0.1.2 \
+ --hash=sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8 \
+ --hash=sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba
+ # via markdown-it-py
+more-itertools==11.1.0 \
+ --hash=sha256:48e8f4d9e7e5878571ecf6f2b4e57634f93cd474cc8cfbd2376f2d11b396e30d \
+ --hash=sha256:4b65538ae22f6fed0ce4874efd317463a7489796a0939fa66824dd542125a192
+ # via
+ # jaraco-classes
+ # jaraco-functools
+nh3==0.3.7 \
+ --hash=sha256:157ec1eb7a62f3d9a7badb8d82d89aa810e3e24e097eedfa481a25d0c8a99877 \
+ --hash=sha256:15f5fbf090f5c88d61c820e1fc1fceecb6520cca9fe85649c06b57ef9dc9ff62 \
+ --hash=sha256:18f4278ecd157d43cb35acd5aae9f35cfa79f546b4922bd86536adc0f6312102 \
+ --hash=sha256:19f288c938ec6eef1f5d2c6cab47838e71fef8097e1c1233802be5a6230ba086 \
+ --hash=sha256:4968fe8d2db97c6f047659bf46a449fd8ec377f44ebf3e0a1b96c0d3a333ae32 \
+ --hash=sha256:5ffdfcb9a686ffb12765376bcfb6b5b55728516d3c0ee317d29982381ded3df8 \
+ --hash=sha256:614dac4a4c36ad084e78447d16fe898dedd762e354a7ab9cda2984e82f67883d \
+ --hash=sha256:618e3059caf41ccdf5dcccb3fa9df4cf6e4efe23d1382a8bbfca272a8a4f8bfc \
+ --hash=sha256:6698a822132beedab80f131c08d8d0ac5a178ddeb488d02ca4b67716ecfac7af \
+ --hash=sha256:6c3aa50eb26e9228238271db9f983cbc3b006dfbfeca2d4dc34c33ddc6ac5ea5 \
+ --hash=sha256:6e4280115d44c3b278eef712a86748c1a723105cd79feec46952383117ab4e59 \
+ --hash=sha256:70f5ac8626e899a4bab0ef74ca2f5bd602f49c7b739e6e5026b4afc6d63dac42 \
+ --hash=sha256:71860d01c16f4d8c72e334e0674beb2b0899dbd0bf760de18932ef4390303848 \
+ --hash=sha256:808def0c8c07843e6e50dc84f532457bfa2cfd17417b219a5d9e7c773709331a \
+ --hash=sha256:874b7d67a067bd29a59223f6270fc30da4edd8e6d87fd219fc93bcbaa662c946 \
+ --hash=sha256:91a4dab4e94d9fc54b9f67b1adfb23e81fab7ab43f33c3b8c97be9aa38f789ba \
+ --hash=sha256:94fd6e59553fbb9ffd8ba71bbd5a54e3126ba01799a097ae30d5341d750bc6ac \
+ --hash=sha256:9b7279d43323a25225df23576af6594a16693f61431170848b8b2ac21ad4f174 \
+ --hash=sha256:bc42bb1193c1e28a1e74c2cabaca178e118a7103e8832699fef8a2b3e2496493 \
+ --hash=sha256:be53a4825585f701955cb9baf49f478f56eb81e20294329fe4bc689dd5dd81fa \
+ --hash=sha256:d56e76bd3cadb09b6b0cef364850811663734b348a25f5f587a2819c495367bd \
+ --hash=sha256:de2b2aab32ea303405debefdcfc58043d3e635fa3f67b9eb140d2b0e0c0d2563 \
+ --hash=sha256:e8fd1ab205258b29254f72db377d99e2c96aa7653ef3b015ccab0420b094b506 \
+ --hash=sha256:eae64328e46a25785535afcb6885b6f182ecaf5ee8c88f8c075422db8aacc65b \
+ --hash=sha256:f04b7d333b27f13ca439da3cf1c75c2fba34f104969f6ce4ac8e7079699c2f4a \
+ --hash=sha256:f266d3f1b3647449923a8e406524632220dd5d8b647078dfe45b885d33d10479 \
+ --hash=sha256:fd4a70efb45d5372174f718878eb7a35c12677626a63b2f103b23b833457dcac
+ # via readme-renderer
+packaging==26.3 \
+ --hash=sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79 \
+ --hash=sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c
+ # via
+ # build
+ # hatchling
+ # twine
+pathspec==1.1.1 \
+ --hash=sha256:17db5ecd524104a120e173814c90367a96a98d07c45b2e10c2f3919fff91bf5a \
+ --hash=sha256:a00ce642f577bf7f473932318056212bc4f8bfdf53128c78bbd5af0b9b20b189
+ # via hatchling
+pip==26.3 \
+ --hash=sha256:6c36ae7da8695be67e3cd9f7d87919667ced53f57ce2ede75d89b5912ed2bc4c \
+ --hash=sha256:f3b60b20ffaadd4415ed7957212a38ac63fa4c5fa375bd0f4a797777940fad13
+ # via -r .github/requirements/build.in
+pluggy==1.7.0 \
+ --hash=sha256:7dd7b0d8832ba3cb632c306926ded123429211b83641b35dc5c41ad2d34f9bec \
+ --hash=sha256:d1eaa46ebb595891b860ab086b4d09c8588af65ebd4361b8e8f4bb8920b90ba8
+ # via hatchling
+pycparser==3.11 \
+ --hash=sha256:51d5a8ba2be0bbe440b99d2112604c95bbbc3c2748a64260186c541e1729cd80 \
+ --hash=sha256:d875f09c3507d00e1aba0eecc6dcadc1352f30fff09dc6bff2f1c2935e97c2bc
+ # via cffi
+pygments==2.21.0 \
+ --hash=sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9 \
+ --hash=sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c
+ # via
+ # readme-renderer
+ # rich
+pyproject-hooks==1.3.3 \
+ --hash=sha256:5fc53fdac9f7bd63fbcdc868fb5f90b4784d78a53a3d3388cd738b807441a20b \
+ --hash=sha256:defda19b854fa0d3bd4f76ea4ddcba8abd7dcfcdd585a6690ade050744fc5f43
+ # via build
+readme-renderer==46.0 \
+ --hash=sha256:af3e964914f6310a33ff67b72a4bdd940bed8d7c3bdecd2d14f40edf284bfe90 \
+ --hash=sha256:d0dae1f74bb273b534770cb4cccb6bb78735540afdb03c2146f4e19dcd412560
+ # via
+ # -r .github/requirements/build.in
+ # twine
+requests==2.34.2 \
+ --hash=sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0 \
+ --hash=sha256:f288924cae4e29463698d6d60bc6a4da69c89185ad1e0bcc4104f584e960b9ed
+ # via
+ # requests-toolbelt
+ # twine
+requests-toolbelt==1.0.0 \
+ --hash=sha256:7681a0a3d047012b5bdc0ee37d7f8f07ebe76ab08caeccfc3921ce23c88d5bc6 \
+ --hash=sha256:cccfdd665f0a24fcf4726e690f65639d272bb0637b9b92dfd91a5568ccf6bd06
+ # via twine
+rfc3986==2.0.0 \
+ --hash=sha256:50b1502b60e289cb37883f3dfd34532b8873c7de9f49bb546641ce9cbd256ebd \
+ --hash=sha256:97aacf9dbd4bfd829baad6e6309fa6573aaf1be3f6fa735c8ab05e46cecb261c
+ # via twine
+rich==15.0.0 \
+ --hash=sha256:33bd4ef74232fb73fe9279a257718407f169c09b78a87ad3d296f548e27de0bb \
+ --hash=sha256:edd07a4824c6b40189fb7ac9bc4c52536e9780fbbfbddf6f1e2502c31b068c36
+ # via twine
+secretstorage==3.5.0 \
+ --hash=sha256:0ce65888c0725fcb2c5bc0fdb8e5438eece02c523557ea40ce0703c266248137 \
+ --hash=sha256:f04b8e4689cbce351744d5537bf6b1329c6fc68f91fa666f60a380edddcd11be
+ # via keyring
+tomli==2.5.0 \
+ --hash=sha256:069435bd5480429b98c5e5afb02ab21c219b6f0064680671c6dc0d46817346ea \
+ --hash=sha256:0dc598040da8d42cf20f0be588ed7004f46db12a0ac6c32e03a59dccedaaadcd \
+ --hash=sha256:1245a6638fc4bb0a60af38a7d45413db34a13842027c77597c712c998c62fdf0 \
+ --hash=sha256:19b0dd8749f4ea2f112c5fcfb3c5248390c899d7e2e173f1d91abee1fa0ff391 \
+ --hash=sha256:1f4a40d03fb9f63424f0979855bdeaf44dd7696b8d59501822c10ed30ba532df \
+ --hash=sha256:20aa36de8f2cf87237143bc1fa1aae8d6612c09118f4da21c6a684db5dd1f6f9 \
+ --hash=sha256:21e4cae4114aba25aa0d4f85cdf486d290fb35c0954d7bba536248da64d43066 \
+ --hash=sha256:22185fad8a1e622f064e78008018a0dd3323550dcb479cb7a1d296888d74024f \
+ --hash=sha256:2419c2a189551987b59d80e63ec355671283336f41c6b9b89462df679c7d0c57 \
+ --hash=sha256:264507556cd8b8c8e7c6ee037cdf443a463f03f4c958e57195e3d369711b8ff6 \
+ --hash=sha256:32a7b79ac57a2e83670ce329ccf675798bc5a2094783a63676866b70503f2e2b \
+ --hash=sha256:3f89d10c1ff6a38d992c27fc8a4816af71a909e08a40ec66934240b1e74347c3 \
+ --hash=sha256:463b16086865b97facd8d0b3fb4cb7c544e3f58d2a69dc3113d6db9653fdb043 \
+ --hash=sha256:49096930c8d886c9bbdab62d2d0d17ce823ddeea522309a190b36245d5b49e01 \
+ --hash=sha256:521345fd1f19d45b8df87657aaa38b6f2ca3800059fadf428e7ebf479a383646 \
+ --hash=sha256:57b1c3b01fab802e2899bc3d168dca320e14165e2fd9fd584760fb4ca5826859 \
+ --hash=sha256:5d8bac3d603c97e6854424e5b2b5b741bdbde387e09f162fb0446812b4a8362b \
+ --hash=sha256:610b27d99f28ec5f191c7064a48f3ddb179a1fe6ca73d571483ae859f57b605e \
+ --hash=sha256:61ea1ebe1e55a34ea8199cc8dbff398d35027b82271c8ac4802fd3a1fd5b1bcc \
+ --hash=sha256:62fc1bc8eb03e3a9cadfca713d65614ed8e09d974a283295ffe3a831976b4dc5 \
+ --hash=sha256:6664b7ae7af7294256c53960a6103077f4914cec8ff98479c352f622c6f6b2f0 \
+ --hash=sha256:667e521b37a6c5ccaa044202c235b530f90177ffe2cd4a64ecc213c7dd535feb \
+ --hash=sha256:69491c143d2fe063046e0301e62a810bed338fa4d1ce0fd870c27dc1e09b0d84 \
+ --hash=sha256:6cf74416bdc94ae458b14e37286c1073081850ac8459a00d0c5efef5d44294c6 \
+ --hash=sha256:6e95c7614e705bfe2b04b27aa124adec59752d15813df37e2156747cab3a006b \
+ --hash=sha256:6f041843c4d3a37245c0c056fd955b186bf8b1fb85690cbe40b81230891dc34b \
+ --hash=sha256:752e8b1aa6a4367ef8bf6a1a1e005540f7ed055ba36d7193796812ca5404eb52 \
+ --hash=sha256:75dbcde8751b0a960aa3de173aa5e894d590755c6d7758b7e774c06f1dc3cbdd \
+ --hash=sha256:7ac2027d37c3afbdf4bdd377f2676f6f1d2122a5be1f1137b49dced590b37e75 \
+ --hash=sha256:7ad1ea345759240d6463efa0ed1c704402752e49aa21476620738d74d72d8aa1 \
+ --hash=sha256:86665cee9c4835b7a7f1e8ec2c719b5258d4dc782887aded5a8ae7352a96843b \
+ --hash=sha256:8ff3a2ca028c7eee0c777f9a092038d0a594a9fa04e215f929a22c329e2cb142 \
+ --hash=sha256:91294a9fb94a75542f6e46e4a2ae709bd8d9b51134098cae5cf3bea5478b6d03 \
+ --hash=sha256:943276cf269e0071948d9ff697159c1735e623c1151d88abb09b74659ef0cbea \
+ --hash=sha256:96243987194634bd411066ce40c952e108f86af04db533ecd8ac3ff2a85b1885 \
+ --hash=sha256:984012f71908165449a951de2050d52f276bfe3aa5d5f570f63ddad814370374 \
+ --hash=sha256:9b03d7dc168353b4132965bde20feceabaa470e570c6f59660dfae59b1f9eeb3 \
+ --hash=sha256:9dbb18c1cfb2f6517942fc9314437f66aa06d94436ffb1f06102ef3572f35276 \
+ --hash=sha256:9ebf8d19b17bd0daeb7b7dec81a946a439b753942fd0210d6e96c532249eea6b \
+ --hash=sha256:a525685c2f97da40762b8695eb7aa0af4c8344ca1905c73e4e29cb04d34607dc \
+ --hash=sha256:abdbf6313b8d9efe157edeb7ab6eae4de064b1300ad31abf73755154b30abe68 \
+ --hash=sha256:b69564772b5c8f22ea5f498dff08cfa825045b4d4c4400529000bdf818aa3b2a \
+ --hash=sha256:b8ade5023067f99fe72b88accd30d0ea05a158e9e32a11f124e731ea9695313f \
+ --hash=sha256:bbaefc84548d754be821bba7c4141c4787dda182f9e77f2f87b71213529efa7b \
+ --hash=sha256:bd05de8c1698f8413dd7d869492693a0bf2211543b787ac78cd5e7536af1a6d7 \
+ --hash=sha256:bf0b5e8e0f68ebb494356e577c06c139161efd8d3b9050f93b39b7c26cc54ff0 \
+ --hash=sha256:c414be4ed9d3cac80c42e348fa5a956117d1a48227f48026e31f59cb4a7671eb \
+ --hash=sha256:c47300f9bf791808f77d82747691c4bb09cb14bdf3060cca99b42cdc4361d5a7 \
+ --hash=sha256:c4dc1c1781f2f716de763d1e9a7b34c6a894e167e291c7c5d16c72f7a9538545 \
+ --hash=sha256:c804ae44fe7b4bab5da295e4f980a1ff04670bca9d23fe0a4e887e08ebd741a8 \
+ --hash=sha256:cfac177ebd6236003846ea339981f71457cb6eb748f23381eb257e45092e3980 \
+ --hash=sha256:d2ba24db8a9376921b5e87b4762b9adb0f3f1deaea68f2b8b0bb2c11efb9c3e7 \
+ --hash=sha256:d3182ee2d887e507bd67319a0a61105d1dd33facc111329559a233b772c1a105 \
+ --hash=sha256:d747252933c8a65ef6bd8da0fbb7ce28a90eb6119d8cd00772cd528aa07b68d5 \
+ --hash=sha256:d7e369fd63331746182360977b1892bfc215476a30d61612d732425311639f56 \
+ --hash=sha256:e12bbcd32897272fb05929110362ae9ff4c1b9bb26bd9e971e71dcd3275b4c3d \
+ --hash=sha256:e7ad033e27a516a233bea839cdb77b80146facb3b4f40bf02cd0cac165cdd5c2 \
+ --hash=sha256:e9e15b4a6c7dd6b85b5fbab29488a73f1f70de516942308daa266bf0e0aeb0d4 \
+ --hash=sha256:ed53f7e89bb04f6d9e8e7799112360b0c4d5cbff067de0814c98c37c39b920f7 \
+ --hash=sha256:eff8babca5a7999bc137acbc7482a8b7e17ffca5075ab41f5d770ab408c7bfef \
+ --hash=sha256:f15e3e0b835a6d68b10c86bf80a3149780498d6911c93c3ffd1861d19f9200f1 \
+ --hash=sha256:f3fcbc57b1791fa6cbe5d8434179d51de12be1a4811469529f47f6e7487a2571 \
+ --hash=sha256:f4b653094e18f9031102d3a1da5c729c8f222d85225b18037dac621695e46e1a \
+ --hash=sha256:f79203b3965b4000e91808aaa7c040206093f2b8bf86f455982f2274c9ccf442 \
+ --hash=sha256:fd4dc129784e0c5335bd4e61dfcc4487499a013419e655cf2da1d091b7e0efdc
+ # via
+ # build
+ # hatch-fancy-pypi-readme
+ # hatchling
+tomlkit==0.15.2 \
+ --hash=sha256:05562412163a3037b94497385fb7f9204c637bc605af7a48199e41cf2272f437 \
+ --hash=sha256:83e32755ba1d20d9340bd069ee97e9f6232ba2346b63ffcba425de01f7e327a6
+ # via hatchling
+trove-classifiers==2026.9.21.13 \
+ --hash=sha256:0a9ebc8d4e2f3e8a22848c5258033035bec17a3012ac3fea16dbaa764489eb71 \
+ --hash=sha256:8b1ff4f9c191b1040b71c37f1e445ab99732911e3cd91de52838453a854d7a17
+ # via hatchling
+twine==7.0.0 \
+ --hash=sha256:85cdb29c518efef867360ae4acd4b0dfd61c8654a22fca08e6f8539f05022177 \
+ --hash=sha256:b854164df26db268af05f49aa5c0344b10e27a494343ff05b1e0bad3b135f5a7
+ # via -r .github/requirements/build.in
+typing-extensions==4.16.0 \
+ --hash=sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8 \
+ --hash=sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5
+ # via cryptography
+urllib3==2.8.0 \
+ --hash=sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3 \
+ --hash=sha256:63bf2ead4c879426ebf22ef2a781eeb4aa3b4ae798a0435506f8687fd5bb9b63
+ # via
+ # id
+ # requests
+ # twine
+zipp==4.1.2 \
+ --hash=sha256:b30cb6cd253122169c47de245ca24a86bac2a5d3802ba15bf7ba6414eb9e144d \
+ --hash=sha256:cf474b90b07ea932637e17c6b9479de2b2882900b0d311bdaf4f5c000a15a97f
+ # via importlib-metadata
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..f416711
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,224 @@
+# Copyright 2026 Inworld AI — Apache-2.0
+#
+# What a newcomer's machine does: a fresh environment, the package installed from the checkout
+# and from a built wheel, the import contract, the command line, and the CPU tests. No weights,
+# no benchmark audio and no GPU are available here, so the two golden-parity tests skip and say so.
+name: ci
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+ workflow_call:
+ inputs:
+ release:
+ description: Stage the validated distributions for publication
+ type: boolean
+ default: false
+
+permissions:
+ contents: read
+
+concurrency:
+ group: ci-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ tests:
+ name: tests (Python ${{ matrix.python }})
+ runs-on: ubuntu-24.04
+ timeout-minutes: 30
+ strategy:
+ fail-fast: false
+ matrix:
+ python: ["3.10", "3.12"]
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
+ with:
+ ref: ${{ github.sha }}
+ persist-credentials: false
+ - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78
+ - name: Python ${{ matrix.python }}
+ # Use a uv-managed interpreter and pip consistently across runners.
+ run: |
+ uv venv --python ${{ matrix.python }} --python-preference only-managed --seed "${RUNNER_TEMP}/py"
+ echo "${RUNNER_TEMP}/py/bin" >> "$GITHUB_PATH"
+ - name: System audio libraries
+ run: sudo apt-get update && sudo apt-get install -y --no-install-recommends libsndfile1 ffmpeg
+ - name: CPU PyTorch
+ run: python -m pip install --no-cache-dir torch torchaudio --index-url https://download.pytorch.org/whl/cpu
+ - name: Install from the checkout
+ # the CPU index stays in reach, so a dependency that re-resolves torch gets the CPU build, not the CUDA stack
+ env:
+ PIP_EXTRA_INDEX_URL: https://download.pytorch.org/whl/cpu
+ run: python -m pip install --no-cache-dir -e ".[dev,eval,docs,demo]" # exercise benchmark, figure and demo tests
+ - name: Import contract and command line
+ run: |
+ python - <<'PY'
+ import sys
+ from inworld import voice_isolation
+ heavy = {"demucs", "transformers", "gradio"} & set(sys.modules)
+ assert not heavy, f"importing the package pulled in {heavy}"
+ assert "voice-isolator-v1" in voice_isolation.MODELS
+ print(sorted(voice_isolation.__all__))
+ PY
+ voice-isolate --help
+ voice-isolate-doctor # the default level uses no network; with no weights cached it still exits 0
+ - name: Tests on CPU
+ run: python -m pytest -q -rs
+
+ wheel:
+ name: distribution contents and installation outside the checkout
+ runs-on: ubuntu-24.04
+ timeout-minutes: 20
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
+ with:
+ ref: ${{ github.sha }}
+ persist-credentials: false
+ - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78
+ - name: Python 3.10
+ # Use a uv-managed interpreter and pip consistently across runners.
+ run: |
+ uv venv --python 3.10 --python-preference only-managed --seed "${RUNNER_TEMP}/py"
+ echo "${RUNNER_TEMP}/py/bin" >> "$GITHUB_PATH"
+ - name: System audio libraries
+ run: sudo apt-get update && sudo apt-get install -y --no-install-recommends libsndfile1
+ - name: Build distributions
+ run: |
+ python -m venv --without-pip "${RUNNER_TEMP}/build"
+ python -m pip --isolated --python "${RUNNER_TEMP}/build" install \
+ --require-hashes --only-binary=:all: --index-url https://pypi.org/simple \
+ -r .github/requirements/build.txt
+ sha256sum README.md > "${RUNNER_TEMP}/readme.sha256"
+ "${RUNNER_TEMP}/build/bin/python" -m build --no-isolation
+ sha256sum --check "${RUNNER_TEMP}/readme.sha256"
+ "${RUNNER_TEMP}/build/bin/python" -m twine check --strict dist/*
+ - name: Check archive contents and documentation links
+ run: |
+ python - <<'PY'
+ import email.parser
+ import pathlib
+ import posixpath
+ import re
+ import tarfile
+ import urllib.parse
+ import zipfile
+
+ package = "voice_isolation"
+ readme = pathlib.Path("README.md").read_text(encoding="utf-8")
+ images = re.findall(r'(?:src|srcset)="([^"]*docs/assets/[^"]+)"', readme)
+ assert images and all(path.startswith("docs/assets/") for path in images), (
+ "Repository README images must use relative paths", images)
+ expected_description = re.sub(
+ r'(src|srcset)="docs/assets/',
+ r'\1="https://raw.githubusercontent.com/inworld-ai/voice-isolator/main/docs/assets/',
+ readme)
+ # Hatchling includes the public VCS ignore file as build metadata.
+ allowed = {"src", "pyproject.toml", "README.md", "MODEL_CARD.md",
+ "LICENSE", "NOTICE", "PKG-INFO", ".gitignore"}
+ (source,) = pathlib.Path("dist").glob("*.tar.gz")
+ with tarfile.open(source) as archive:
+ files = {"/".join(pathlib.PurePosixPath(item.name).parts[1:]): item
+ for item in archive.getmembers() if item.isfile()}
+ unexpected = {name for name in files
+ if name.split("/")[0] not in allowed
+ and name != "docs/USAGE.md"
+ and not name.startswith("docs/assets/")}
+ assert not unexpected, f"unexpected source archive files: {sorted(unexpected)}"
+ assert f"src/inworld/{package}/__init__.py" in files
+ assert "src/inworld/__init__.py" not in files
+ assert archive.extractfile(files["README.md"]).read().decode("utf-8") == readme
+ assert all(path in files for path in images), "README image missing from sdist"
+ source_description = email.parser.Parser().parsestr(
+ archive.extractfile(files["PKG-INFO"]).read().decode("utf-8")).get_payload()
+ assert source_description == expected_description, "Unexpected sdist description"
+ # Check Markdown links and HTML image sources in the shipped docs.
+ for name, item in files.items():
+ if not name.endswith(".md"):
+ continue
+ document = archive.extractfile(item).read().decode("utf-8")
+ links = re.findall(r'\]\(([^)\s]+)\)|(?:src|srcset|href)="([^"]+)"', document)
+ for markdown, html in links:
+ link = urllib.parse.urlsplit(markdown or html)
+ if link.scheme or link.netloc or not link.path:
+ continue
+ target = posixpath.normpath(posixpath.join(
+ posixpath.dirname(name), urllib.parse.unquote(link.path)))
+ assert (target in files or any(
+ path.startswith(target + "/") for path in files)), (name, target)
+
+ (wheel,) = pathlib.Path("dist").glob("*.whl")
+ with zipfile.ZipFile(wheel) as archive:
+ names = set(archive.namelist())
+ (metadata_file,) = (name for name in names if name.endswith(".dist-info/METADATA"))
+ description = email.parser.Parser().parsestr(
+ archive.read(metadata_file).decode("utf-8")).get_payload()
+ assert description == source_description == expected_description, (
+ "Wheel and sdist descriptions must match the transformed README")
+ links = re.findall(r'\]\(([^)\s]+)\)|(?:src|srcset|href)="([^"]+)"', description)
+ for markdown, html in links:
+ link = urllib.parse.urlsplit(markdown or html)
+ assert not link.path or (link.scheme in {"http", "https"} and link.netloc), (markdown, html)
+ metadata = {name.split("/")[0] for name in names
+ if name.split("/")[0].endswith(".dist-info")}
+ assert len(metadata) == 1, f"unexpected wheel metadata: {metadata}"
+ unexpected = {name for name in names
+ if name.split("/")[0] not in metadata | {"inworld"}}
+ assert not unexpected, f"unexpected wheel files: {sorted(unexpected)}"
+ assert f"inworld/{package}/__init__.py" in names
+ assert "inworld/__init__.py" not in names
+ print("Source and wheel inventories and documentation links are valid.")
+ PY
+ - name: Install wheel in a fresh environment
+ run: |
+ python -m venv /tmp/fresh
+ /tmp/fresh/bin/python -m pip install --upgrade pip # the venv's bundled pip cannot read current wheel metadata
+ /tmp/fresh/bin/python -m pip install torch torchaudio --index-url https://download.pytorch.org/whl/cpu
+ /tmp/fresh/bin/python -m pip install dist/*.whl
+ - name: Use outside the checkout
+ working-directory: /tmp
+ run: |
+ /tmp/fresh/bin/python - <<'PY'
+ import torch
+ from inworld import voice_isolation
+ y = voice_isolation.resample(torch.zeros(16000), 16000, voice_isolation.SR)
+ assert y.shape == (48000,), y.shape
+ print("inworld-voice-isolation imports and resamples from a wheel")
+ PY
+ /tmp/fresh/bin/voice-isolate --help
+ /tmp/fresh/bin/voice-isolate-doctor
+
+ - name: Stage validated distributions
+ if: inputs.release
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
+ with:
+ name: python-distributions
+ path: dist/
+ if-no-files-found: error
+ retention-days: 7
+
+ style:
+ name: style and tracked-file hygiene
+ runs-on: ubuntu-24.04
+ timeout-minutes: 10
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
+ with:
+ ref: ${{ github.sha }}
+ persist-credentials: false
+ - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78
+ - name: Python 3.10
+ # Use a uv-managed interpreter and pip consistently across runners.
+ run: |
+ uv venv --python 3.10 --python-preference only-managed --seed "${RUNNER_TEMP}/py"
+ echo "${RUNNER_TEMP}/py/bin" >> "$GITHUB_PATH"
+ - name: yapf, isort and pylint (the Google style guide's pylintrc, unmodified)
+ run: |
+ python -m pip install "yapf==0.43.0" "isort==9.0.2" "pylint==4.1.1"
+ make PYTHON=python format-check lint
+ - name: No machine-specific paths in tracked files
+ run: |
+ if git grep -nE '(^|[^[:alnum:]_/.])/(home|inworld|mnt)/' -- . ':!AGENTS.md' ':!.github/workflows/ci.yml'; then
+ echo "machine-specific paths found in tracked files"; exit 1
+ fi
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
new file mode 100644
index 0000000..98bf540
--- /dev/null
+++ b/.github/workflows/publish.yml
@@ -0,0 +1,178 @@
+# Copyright 2026 Inworld AI — Apache-2.0
+# Dispatch on a reviewed v<version> tag after the repository and weights are public.
+name: publish
+
+on:
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: pypi-publish
+ cancel-in-progress: false
+
+jobs:
+ preflight:
+ if: >-
+ github.server_url == 'https://github.com' &&
+ github.repository == 'inworld-ai/voice-isolator' &&
+ !github.event.repository.private && github.ref_type == 'tag'
+ runs-on: ubuntu-24.04
+ timeout-minutes: 5
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
+ with:
+ ref: ${{ github.sha }}
+ fetch-depth: 0
+ persist-credentials: false
+ - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78
+ - name: Python 3.12
+ # Use a uv-managed interpreter and pip consistently across runners.
+ run: |
+ uv venv --python 3.12 --python-preference only-managed --seed "${RUNNER_TEMP}/py"
+ echo "${RUNNER_TEMP}/py/bin" >> "$GITHUB_PATH"
+ - name: Verify tag, version and model pins
+ env:
+ RELEASE_TAG: ${{ github.ref_name }}
+ RELEASE_SHA: ${{ github.sha }}
+ run: |
+ test "$(git rev-parse --verify "refs/tags/${RELEASE_TAG}^{commit}")" = "${RELEASE_SHA}"
+ git fetch --no-tags origin main:refs/remotes/origin/main
+ git merge-base --is-ancestor "${RELEASE_SHA}" origin/main
+ python - <<'PY'
+ import ast
+ import os
+ import pathlib
+ import re
+ import runpy
+ import tomllib
+
+ project = tomllib.loads(pathlib.Path("pyproject.toml").read_text())["project"]
+ module = ast.parse(pathlib.Path("src/inworld/voice_isolation/__init__.py").read_text())
+ version = next(ast.literal_eval(node.value) for node in module.body
+ if isinstance(node, ast.Assign)
+ and any(isinstance(target, ast.Name) and target.id == "__version__"
+ for target in node.targets))
+ assert project["name"] == "inworld-voice-isolation"
+ assert project["version"] == version
+ assert os.environ["RELEASE_TAG"] == "v" + version
+ registry = runpy.run_path("src/inworld/voice_isolation/registry.py")
+ expected = {
+ "MODELS": {"voice-isolator-v1", "voice-isolator-v1-realtime"},
+ "PINNED": {"voice-isolator-v0", "voice-isolator-v0-realtime"},
+ }
+ for group, names in expected.items():
+ assert set(registry[group]) == names, group
+ for name, entry in registry[group].items():
+ assert re.fullmatch(r"[0-9a-f]{40}", entry["revision"] or ""), (name, "pin the final HF commit")
+ assert re.fullmatch(r"[0-9a-f]{64}", entry["sha256"] or ""), (name, "missing weight checksum")
+ print("Version tag and immutable model identities verified.")
+ PY
+
+ ci:
+ needs: preflight
+ uses: ./.github/workflows/ci.yml
+ with:
+ release: true
+
+ verify:
+ needs: ci
+ runs-on: ubuntu-24.04
+ timeout-minutes: 20
+ env:
+ HF_HUB_DISABLE_IMPLICIT_TOKEN: "1"
+ HF_TOKEN: ""
+ HUGGING_FACE_HUB_TOKEN: ""
+ OMP_NUM_THREADS: "1"
+ MKL_NUM_THREADS: "1"
+ OPENBLAS_NUM_THREADS: "1"
+ steps:
+ - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093
+ with:
+ name: python-distributions
+ path: dist/
+ - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78
+ - name: Python 3.12
+ # Use a uv-managed interpreter and pip consistently across runners.
+ run: |
+ uv venv --python 3.12 --python-preference only-managed --seed "${RUNNER_TEMP}/py"
+ echo "${RUNNER_TEMP}/py/bin" >> "$GITHUB_PATH"
+ - name: Install the validated wheel
+ run: |
+ sudo apt-get update && sudo apt-get install -y --no-install-recommends libsndfile1
+ python -m pip install torch torchaudio --index-url https://download.pytorch.org/whl/cpu
+ python -m pip install dist/*.whl
+ voice-isolate --help
+ - name: Verify anonymous downloads and both inference modes
+ working-directory: ${{ runner.temp }}
+ env:
+ RELEASE_TAG: ${{ github.ref_name }}
+ HF_HOME: ${{ runner.temp }}/release-hf-home
+ run: |
+ python - <<'PY'
+ import os
+ import huggingface_hub
+ import torch
+ from inworld import voice_isolation
+ from inworld.voice_isolation import registry
+
+ torch.set_num_threads(1)
+ torch.set_num_interop_threads(1)
+ assert os.environ["RELEASE_TAG"] == "v" + voice_isolation.__version__
+ audio = 0.1 * torch.sin(2 * torch.pi * 440 * torch.arange(12000) / voice_isolation.SR)
+ verified = {}
+ for name, entry in {**voice_isolation.MODELS, **registry.PINNED}.items():
+ identity = (entry["repo_id"], entry["filename"], entry["revision"])
+ if identity not in verified:
+ checkpoint = huggingface_hub.hf_hub_download(
+ repo_id=entry["repo_id"], filename=entry["filename"],
+ revision=entry["revision"], token=False, force_download=True)
+ verified[identity] = registry.sha256_file(checkpoint)
+ assert verified[identity] == entry["sha256"], name
+ print(name, "anonymous pinned model download verified")
+ for mode in registry.MODE_MODELS:
+ isolator = voice_isolation.VoiceIsolator(
+ "inworld/voice-isolator", mode=mode, device="cpu", lookahead_frames=2 if mode == "streaming" else 0)
+ if mode == "offline":
+ voice = isolator.isolate(audio, voice_isolation.SR)
+ else:
+ stream = isolator.stream()
+ voice = torch.cat([stream.push(piece) for piece in audio.split(960)] + [stream.flush()])
+ assert voice.shape == audio.shape and torch.isfinite(voice).all(), mode
+ print(mode, "anonymous model download and inference passed")
+ PY
+
+ publish:
+ needs: [preflight, ci, verify]
+ if: >-
+ github.server_url == 'https://github.com' &&
+ github.repository == 'inworld-ai/voice-isolator' &&
+ !github.event.repository.private && github.ref_type == 'tag'
+ runs-on: ubuntu-24.04
+ timeout-minutes: 10
+ environment:
+ name: pypi
+ url: https://pypi.org/p/inworld-voice-isolation
+ permissions:
+ id-token: write
+ steps:
+ - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093
+ with:
+ name: python-distributions
+ path: dist/
+ - name: Verify the public tag still identifies these artifacts
+ env:
+ RELEASE_TAG: ${{ github.ref_name }}
+ RELEASE_SHA: ${{ github.sha }}
+ GIT_TERMINAL_PROMPT: "0"
+ run: |
+ refs=$(git ls-remote --exit-code "https://github.com/${GITHUB_REPOSITORY}.git" \
+ "refs/tags/${RELEASE_TAG}" "refs/tags/${RELEASE_TAG}^{}")
+ commit=$(awk '$2 ~ /\^\{\}$/ {print $1}' <<<"${refs}")
+ if [ -z "${commit}" ]; then
+ commit=$(awk '{print $1}' <<<"${refs}")
+ fi
+ test "${commit}" = "${RELEASE_SHA}"
+ - name: Publish the validated distributions
+ uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # release/v1
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..2de49f6
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,22 @@
+__pycache__/
+.ipynb_checkpoints/
+*.pyc
+.venv/
+dist/
+*.egg-info/
+.pytest_cache/
+.gradio/
+.nfs*
+.env
+
+# local only: checkpoints, audio, renders, scratch, downloads
+models/
+data/
+staging/
+internal/
+checkpoints/
+bench/venvs/
+bench/data/
+docs/audio/
+*.safetensors
+!tests/fixtures/*.safetensors
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
new file mode 100644
index 0000000..ba2c7aa
--- /dev/null
+++ b/.pre-commit-config.yaml
@@ -0,0 +1,26 @@
+# Copyright 2026 Inworld AI — Apache-2.0
+#
+# The style gate CI runs (.github/workflows/ci.yml), before each commit:
+# pip install pre-commit && pre-commit install
+repos:
+ - repo: local
+ hooks:
+ - id: isort
+ name: isort (Google profile, pyproject.toml)
+ entry: isort
+ language: system
+ types: [python]
+ # a wrapper's bytes are part of every receipt of its renders
+ exclude: ^bench/wrappers/
+ - repo: https://github.com/google/yapf
+ rev: v0.43.0
+ hooks:
+ - id: yapf
+ args: [--in-place, --parallel]
+ - repo: local
+ hooks:
+ - id: pylint
+ name: pylint (the Google style guide's pylintrc)
+ entry: pylint --rcfile=.pylintrc
+ language: system
+ types: [python]
diff --git a/.pylintrc b/.pylintrc
new file mode 100644
index 0000000..4085ecc
--- /dev/null
+++ b/.pylintrc
@@ -0,0 +1,416 @@
+# This Pylint rcfile contains a best-effort configuration to uphold the
+# best-practices and style described in the Google Python style guide:
+# https://google.github.io/styleguide/pyguide.html
+#
+# Its canonical open-source location is:
+# https://google.github.io/styleguide/pylintrc
+
+# Copyright 2018 Google LLC
+#
+# 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.
+
+[MAIN]
+
+# Files or directories to be skipped. They should be base names, not paths.
+ignore=third_party
+
+# Files or directories matching the regex patterns are skipped. The regex
+# matches against base names, not paths.
+ignore-patterns=
+
+# Pickle collected data for later comparisons.
+persistent=no
+
+# List of plugins (as comma separated values of python modules names) to load,
+# usually to register additional checkers.
+load-plugins=
+
+# Use multiple processes to speed up Pylint.
+jobs=4
+
+# Allow loading of arbitrary C extensions. Extensions are imported into the
+# active Python interpreter and may run arbitrary code.
+unsafe-load-any-extension=no
+
+
+[MESSAGES CONTROL]
+
+# Only show warnings with the listed confidence levels. Leave empty to show
+# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED
+confidence=
+
+# Enable the message, report, category or checker with the given id(s). You can
+# either give multiple identifier separated by comma (,) or put this option
+# multiple time (only on the command line, not in the configuration file where
+# it should appear only once). See also the "--disable" option for examples.
+#enable=
+
+# Disable the message, report, category or checker with the given id(s). You
+# can either give multiple identifiers separated by comma (,) or put this
+# option multiple times (only on the command line, not in the configuration
+# file where it should appear only once).You can also use "--disable=all" to
+# disable everything first and then reenable specific checks. For example, if
+# you want to run only the similarities checker, you can use "--disable=all
+# --enable=similarities". If you want to run only the classes checker, but have
+# no Warning level messages displayed, use"--disable=all --enable=classes
+# --disable=W"
+disable=R,
+ not-callable,
+ abstract-method,
+ apply-builtin,
+ arguments-differ,
+ attribute-defined-outside-init,
+ backtick,
+ bad-option-value,
+ basestring-builtin,
+ buffer-builtin,
+ c-extension-no-member,
+ consider-using-enumerate,
+ cmp-builtin,
+ cmp-method,
+ coerce-builtin,
+ coerce-method,
+ delslice-method,
+ div-method,
+ eq-without-hash,
+ execfile-builtin,
+ file-builtin,
+ filter-builtin-not-iterating,
+ fixme,
+ getslice-method,
+ global-statement,
+ hex-method,
+ idiv-method,
+ implicit-str-concat,
+ import-error,
+ import-self,
+ import-star-module-level,
+ input-builtin,
+ intern-builtin,
+ invalid-str-codec,
+ locally-disabled,
+ long-builtin,
+ long-suffix,
+ map-builtin-not-iterating,
+ misplaced-comparison-constant,
+ missing-function-docstring,
+ metaclass-assignment,
+ next-method-called,
+ next-method-defined,
+ no-absolute-import,
+ no-init, # added
+ no-member,
+ no-name-in-module,
+ no-self-use,
+ nonzero-method,
+ oct-method,
+ old-division,
+ old-ne-operator,
+ old-octal-literal,
+ old-raise-syntax,
+ parameter-unpacking,
+ print-statement,
+ raising-string,
+ range-builtin-not-iterating,
+ raw_input-builtin,
+ rdiv-method,
+ reduce-builtin,
+ relative-import,
+ reload-builtin,
+ round-builtin,
+ setslice-method,
+ signature-differs,
+ standarderror-builtin,
+ suppressed-message,
+ sys-max-int,
+ trailing-newlines,
+ unichr-builtin,
+ unicode-builtin,
+ unnecessary-pass,
+ unpacking-in-except,
+ useless-else-on-loop,
+ useless-suppression,
+ using-cmp-argument,
+ wrong-import-order,
+ xrange-builtin,
+ zip-builtin-not-iterating,
+
+
+[REPORTS]
+
+# Set the output format. Available formats are text, parseable, colorized, msvs
+# (visual studio) and html. You can also give a reporter class, eg
+# mypackage.mymodule.MyReporterClass.
+output-format=text
+
+# Tells whether to display a full report or only the messages
+reports=no
+
+# Activate the evaluation score.
+score=no
+
+# Python expression which should return a note less than 10 (10 is the highest
+# note). You have access to the variables errors warning, statement which
+# respectively contain the number of errors / warnings messages and the total
+# number of statements analyzed. This is used by the global evaluation report
+# (RP0004).
+evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
+
+# Template used to display messages. This is a python new-style format string
+# used to format the message information. See doc for all details
+#msg-template=
+
+
+[BASIC]
+
+# Good variable names which should always be accepted, separated by a comma
+good-names=main,_,A_log,D
+
+# Bad variable names which should always be refused, separated by a comma
+bad-names=
+
+# Colon-delimited sets of names that determine each other's naming style when
+# the name regexes allow several styles.
+name-group=
+
+# Include a hint for the correct naming format with invalid-name
+include-naming-hint=no
+
+# List of decorators that produce properties, such as abc.abstractproperty. Add
+# to this list to register other decorators that produce valid properties.
+property-classes=abc.abstractproperty,cached_property.cached_property,cached_property.threaded_cached_property,cached_property.cached_property_with_ttl,cached_property.threaded_cached_property_with_ttl
+
+# Regular expression matching correct function names
+function-rgx=^(?:(?P<exempt>setUp|tearDown|setUpModule|tearDownModule)|(?P<camel_case>_?[A-Z][a-zA-Z0-9]*)|(?P<snake_case>_?[a-z][a-z0-9_]*))$
+
+# Regular expression matching correct variable names
+variable-rgx=^[a-z][a-z0-9_]*$
+
+# Regular expression matching correct constant names
+const-rgx=^(_?[A-Z][A-Z0-9_]*|__[a-z0-9_]+__|_?[a-z][a-z0-9_]*)$
+
+# Regular expression matching correct attribute names
+attr-rgx=^_{0,2}[a-z][a-z0-9_]*$
+
+# Regular expression matching correct argument names
+argument-rgx=^[a-z][a-z0-9_]*$
+
+# Regular expression matching correct class attribute names
+class-attribute-rgx=^(_?[A-Z][A-Z0-9_]*|__[a-z0-9_]+__|_?[a-z][a-z0-9_]*)$
+
+# Regular expression matching correct inline iteration names
+inlinevar-rgx=^[a-z][a-z0-9_]*$
+
+# Regular expression matching correct class names
+class-rgx=^_?[A-Z][a-zA-Z0-9]*$
+
+# Regular expression matching correct module names
+module-rgx=^(_?[a-z][a-z0-9_]*|__init__)$
+
+# Regular expression matching correct method names
+method-rgx=(?x)^(?:(?P<exempt>_[a-z0-9_]+__|runTest|setUp|tearDown|setUpTestCase|tearDownTestCase|setupSelf|tearDownClass|setUpClass|(test|assert)_*[A-Z0-9][a-zA-Z0-9_]*|next)|(?P<camel_case>_{0,2}[A-Z][a-zA-Z0-9_]*)|(?P<snake_case>_{0,2}[a-z][a-z0-9_]*))$
+
+# Regular expression which should only match function or class names that do
+# not require a docstring.
+no-docstring-rgx=(__.*__|main|test.*|.*test|.*Test)$
+
+# Minimum line length for functions/classes that require docstrings, shorter
+# ones are exempt.
+docstring-min-length=12
+
+
+[TYPECHECK]
+
+# List of decorators that produce context managers, such as
+# contextlib.contextmanager. Add to this list to register other decorators that
+# produce valid context managers.
+contextmanager-decorators=contextlib.contextmanager,contextlib2.contextmanager
+
+# List of module names for which member attributes should not be checked
+# (useful for modules/projects where namespaces are manipulated during runtime
+# and thus existing member attributes cannot be deduced by static analysis. It
+# supports qualified module names, as well as Unix pattern matching.
+ignored-modules=
+
+# List of class names for which member attributes should not be checked (useful
+# for classes with dynamically set attributes). This supports the use of
+# qualified names.
+ignored-classes=optparse.Values,thread._local,_thread._local
+
+# List of members which are set dynamically and missed by pylint inference
+# system, and so shouldn't trigger E1101 when accessed. Python regular
+# expressions are accepted.
+generated-members=
+
+
+[FORMAT]
+
+# Maximum number of characters on a single line.
+max-line-length=80
+
+# TODO(https://github.com/pylint-dev/pylint/issues/3352): Direct pylint to exempt
+# lines made too long by directives to pytype.
+
+# Regexp for a line that is allowed to be longer than the limit.
+ignore-long-lines=(?x)(
+ ^\s*(\#\ )?<?https?://\S+>?$|
+ ^\s*(from\s+\S+\s+)?import\s+.+$)
+
+# Allow the body of an if to be on the same line as the test if there is no
+# else.
+single-line-if-stmt=yes
+
+# Maximum number of lines in a module
+max-module-lines=99999
+
+# String used as indentation unit. The internal Google style guide mandates 2
+# spaces. Google's externaly-published style guide says 4, consistent with
+# PEP 8.
+indent-string=' '
+
+# Number of spaces of indent required inside a hanging or continued line.
+indent-after-paren=4
+
+# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
+expected-line-ending-format=
+
+
+[MISCELLANEOUS]
+
+# List of note tags to take in consideration, separated by a comma.
+notes=TODO
+
+
+[STRING]
+
+# This flag controls whether inconsistent-quotes generates a warning when the
+# character used as a quote delimiter is used inconsistently within a module.
+check-quote-consistency=yes
+
+
+[VARIABLES]
+
+# Tells whether we should check for unused import in __init__ files.
+init-import=no
+
+# A regular expression matching the name of dummy variables (i.e. expectedly
+# not used).
+dummy-variables-rgx=^\*{0,2}(_$|unused_|dummy_)
+
+# List of additional names supposed to be defined in builtins. Remember that
+# you should avoid to define new builtins when possible.
+additional-builtins=
+
+# List of strings which can identify a callback function by name. A callback
+# name must start or end with one of those strings.
+callbacks=cb_,_cb
+
+# List of qualified module names which can have objects that can redefine
+# builtins.
+redefining-builtins-modules=six,six.moves,past.builtins,future.builtins,functools
+
+
+[LOGGING]
+
+# Logging modules to check that the string format arguments are in logging
+# function parameter format
+logging-modules=logging,absl.logging,tensorflow.io.logging
+
+
+[SIMILARITIES]
+
+# Minimum lines number of a similarity.
+min-similarity-lines=4
+
+# Ignore comments when computing similarities.
+ignore-comments=yes
+
+# Ignore docstrings when computing similarities.
+ignore-docstrings=yes
+
+# Ignore imports when computing similarities.
+ignore-imports=no
+
+
+[SPELLING]
+
+# Spelling dictionary name. Available dictionaries: none. To make it working
+# install python-enchant package.
+spelling-dict=
+
+# List of comma separated words that should not be checked.
+spelling-ignore-words=
+
+# A path to a file that contains private dictionary; one word per line.
+spelling-private-dict-file=
+
+# Tells whether to store unknown words to indicated private dictionary in
+# --spelling-private-dict-file option instead of raising a message.
+spelling-store-unknown-words=no
+
+
+[IMPORTS]
+
+# Deprecated modules which should not be used, separated by a comma
+deprecated-modules=regsub,
+ TERMIOS,
+ Bastion,
+ rexec,
+ sets
+
+# Create a graph of every (i.e. internal and external) dependencies in the
+# given file (report RP0402 must not be disabled)
+import-graph=
+
+# Create a graph of external dependencies in the given file (report RP0402 must
+# not be disabled)
+ext-import-graph=
+
+# Create a graph of internal dependencies in the given file (report RP0402 must
+# not be disabled)
+int-import-graph=
+
+# Force import order to recognize a module as part of the standard
+# compatibility libraries.
+known-standard-library=
+
+# Force import order to recognize a module as part of a third party library.
+known-third-party=enchant, absl
+
+# Analyse import fallback blocks. This can be used to support both Python 2 and
+# 3 compatible code, which means that the block might have code that exists
+# only in one or another interpreter, leading to false positives when analysed.
+analyse-fallback-blocks=no
+
+
+[CLASSES]
+
+# List of method names used to declare (i.e. assign) instance attributes.
+defining-attr-methods=__init__,
+ __new__,
+ setUp
+
+# List of member names, which should be excluded from the protected access
+# warning.
+exclude-protected=_asdict,
+ _fields,
+ _replace,
+ _source,
+ _make
+
+# List of valid names for the first argument in a class method.
+valid-classmethod-first-arg=cls,
+ class_
+
+# List of valid names for the first argument in a metaclass class method.
+valid-metaclass-classmethod-first-arg=mcs
diff --git a/.style.yapf b/.style.yapf
new file mode 100644
index 0000000..582084e
--- /dev/null
+++ b/.style.yapf
@@ -0,0 +1,3 @@
+[style]
+based_on_style = google
+column_limit = 80
diff --git a/AGENTS.md b/AGENTS.md
new file mode 100644
index 0000000..63fbf04
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1,243 @@
+# Inworld Voice Isolator — guide for coding agents
+
+This file serves two tasks:
+
+- **Setting up the Voice Isolator for someone to use** (install it, check the
+ machine, clean a first file): follow [Setting up the Voice Isolator for a user](#setting-up-the-voice-isolator-for-a-user),
+ the last section, and skip the rest. It installs with `pip`; `make install` is
+ the contributor setup, with development and evaluation extras a user does not need.
+- **Changing this repository:** read every section before that one first.
+ [CONTRIBUTING.md](CONTRIBUTING.md) covers setup and validation;
+ [README.md](README.md) covers usage.
+
+`CLAUDE.md` imports this file, and `.claude/skills/` links to `.agents/skills/`.
+
+## Repository layout
+
+| Path | Purpose |
+|---|---|
+| `src/inworld/voice_isolation/` | Inference package; `__init__.py` defines the public API |
+| `tests/` | Tests mirroring source paths; `tests/fixtures/` holds reference parity cases |
+| `bench/scripts/`, `bench/wrappers/` | Benchmark tools and external-system adapters; see [bench/README.md](bench/README.md) |
+| `demo/` | Interactive demo; see [demo/README.md](demo/README.md) |
+| `examples/` | Guided notebook for a first evaluation; see [examples/README.md](examples/README.md) |
+| `docs/` | Figure generator and README assets |
+| `MODEL_CARD.md` | The model card, shown as the Hugging Face page: purpose, quick start, benchmark, architecture, the two checkpoints and training data |
+| `models/`, `data/`, `staging/` | Gitignored checkpoints, local data and scratch files |
+
+## Coding conventions
+
+- Follow Google Python style, enforced by the pinned `isort`, `yapf` and `pylint`
+ tools. Use Google-style docstrings, type hints on public signatures, and module
+ imports rather than imports of individual functions or classes. Standard
+ aliases such as `np`, `sf`, `plt` and `gr` are fine.
+- Use lowercase module names with underscores and `test_<module>.py` beside the
+ mirrored source path under `tests/`. Keep tests in arrange, act and assert
+ sections separated by blank lines.
+- Every Python file in the package, tests, demo, docs and benchmark scripts starts
+ with the Apache-2.0 header. Shell scripts carry the one-line copyright notice.
+ External-system wrappers open with a docstring naming the system and license.
+- Modeling code in `model.py` uses names and docstrings without inline comments.
+ Elsewhere, explain contracts and caveats that the code cannot express.
+- `inworld` is a namespace package: do not add `src/inworld/__init__.py`.
+ Users import `from inworld import voice_isolation` and use its `__all__` API.
+ Importing the package must not access the network or import optional demo,
+ evaluation or third-party model dependencies.
+- Keep one module per concern. Optional dependencies belong behind the extras in
+ `pyproject.toml`, with useful errors when they are unavailable.
+
+## Data and reproducibility
+
+- Do not commit machine-specific paths, credentials, private audio, training
+ records or experimental checkpoint identifiers. Release names are public, not
+ experimental: Voice Isolator v1 (`voice-isolator-v1`,
+ `voice-isolator-v1-realtime`) and the v2 the Plans announce. Pass local paths through flags
+ or environment variables. Keep scratch work in the gitignored directories.
+- Every redistributed recording needs source and license attribution. A
+ recording's presence in a working directory does not establish permission to
+ publish it.
+- Fetch third-party models and dependencies from their upstream releases under
+ their own licenses; do not vendor their code or weights.
+- The checkpoint checksum in `registry.py` and each golden fixture's
+ `meta.json` must agree. Expected golden outputs come from the
+ independent training reference implementation; never hand-edit them or
+ regenerate them with the implementation being tested.
+- Benchmark scripts and wrappers are identified by their exact source bytes.
+ Changing them requires the corresponding re-score or re-render. `make format`
+ deliberately leaves them untouched; `make format-check` still checks them.
+- Generate benchmark figures and reported scores with the benchmark tools;
+ do not type in replacement results. The model card is the source of truth for
+ model and training disclosures; link to it instead of duplicating them. It is
+ also the page Hugging Face shows: its TL;DR and quick start repeat the
+ README's, so change them together.
+
+## Validation
+
+Use the commands in [CONTRIBUTING.md](CONTRIBUTING.md). Format and lint touched
+Python files and run the relevant tests. A new module needs tests at its mirrored
+path. Run the full suite for inference changes and before proposing a release.
+Report any skipped optional-dependency or golden-parity checks: the goldens need
+the released checkpoints under `models/` (or `VOICE_ISOLATION_GOLDEN_MODEL`).
+Tests run on CPU; demo inference can also use a GPU.
+
+[CONTRIBUTING.md](CONTRIBUTING.md#what-a-fresh-checkout-shows) lists what a
+fresh checkout shows: the skips to expect, and the platform and Python versions
+CI uses. Check a skip, a warning or a failure against it before investigating.
+If a check already fails on a clean checkout of `main`, before your change,
+report it in one line and carry on with the task you were given; do not
+investigate or fix it unasked.
+
+Architecture figures are hand-written SVG with live text in the board charts'
+font stack, at the board's width, laid out from the width table in
+`docs/build_figures.py`, with an accessible description and light/dark
+variants. Preserve that format when changing `docs/build_figures.py`.
+
+## Skills
+
+| Skill | Purpose |
+|---|---|
+| `run-demo` | Launch the demo using its documented example and file-access contract |
+| `integrate` | Install the package, load a model, process audio and pin versions |
+
+## Setting up the Voice Isolator for a user
+
+A person asked you to set up the Inworld Voice Isolator: a model that separates
+the voice in a recording from everything around it. You install the
+`inworld-voice-isolation` Python package, check the machine with
+`voice-isolate-doctor`, and clean a first file. The rest of this file is about
+changing the repository; you do not need it for this.
+
+Complete every step yourself with your own tools. A step marked
+**Ask the person** needs them: ask in one short line, wait until they answer,
+then go on. Tell them what to do and what they will get; do not explain how the
+model works inside.
+
+What the model does and how well is in the [model card](MODEL_CARD.md). To
+build the package into another project or service, the
+[integrate skill](.agents/skills/integrate/SKILL.md) covers its API.
+
+### 0. Before you start
+
+- **Already installed?** If `voice-isolate-doctor` runs, skip to [step 3](#3-verify).
+- **Use a virtual environment**, never the system Python. Use Python 3.10 or later.
+ - With `uv`: `uv venv`, then prefix every `pip` below with `uv`
+ (`uv pip install ...`), because a `uv` environment has no `pip` of its own.
+ - Without it: `python -m venv .venv`, then activate it.
+
+### 1. Install
+
+Try these in order. When one fails, go to the next.
+
+1. **Inside a clone** (a `pyproject.toml` in this folder names
+ `inworld-voice-isolation`). Do not use `make install` here: that is the
+ contributor setup.
+
+ ```
+ pip install -e .
+ ```
+
+2. **From PyPI:**
+
+ ```
+ pip install inworld-voice-isolation
+ ```
+
+3. **From GitHub**, pinned to the newest tag (`git ls-remote --tags
+ https://github.com/inworld-ai/voice-isolator.git` lists them; use `main` if
+ there is none):
+
+ ```
+ pip install "inworld-voice-isolation @ git+https://github.com/inworld-ai/voice-isolator.git@<tag>"
+ ```
+
+Extras, only when they apply:
+
+- `[demo]` (for example `pip install -e ".[demo]"`) when the person wants the
+ browser demo with microphone recording.
+- `[fast]` only on a machine with an NVIDIA GPU and CUDA. It builds optional
+ kernels; skip it if the build fails.
+
+If every route fails, stop and tell the person: "I couldn't install the
+Inworld Voice Isolator from PyPI or GitHub. Check the network or proxy
+settings and ask me again."
+
+### 2. Weights
+
+Nothing to do. The two models download from Hugging Face
+(`inworld/voice-isolator`, about 490 MB together) the first time they are used,
+with no account or sign-in, and their checksums are verified.
+
+### 3. Verify
+
+```
+voice-isolate-doctor --full
+```
+
+It prints one line per check, each starting with `OK`, `INFO`, `WARN` or
+`FAIL`, and ends with one summary line. The first run downloads the weights.
+
+- **`All set: …`** means it worked. Go to step 4.
+- **Anything else:** each `FAIL` line names one next step. Do the steps you
+ can, give the person the rest, and run the check again.
+
+`voice-isolate-doctor` without `--full` uses no network and loads no model; use
+it to report the machine's state, and `--json` for a machine-readable copy.
+
+### 4. First result
+
+Use the noisy example. In a clone it is `demo/examples/sample_14.wav`;
+otherwise download it:
+
+```
+curl -LO https://raw.githubusercontent.com/inworld-ai/voice-isolator/main/demo/examples/sample_14.wav
+voice-isolate sample_14.wav sample_14_clean.wav
+```
+
+This writes the voice to `sample_14_clean.wav` and the removed background to
+`sample_14_clean_background.wav`. Tell the person where both files are.
+
+**Ask the person:** "Want to try your own recording? Give me its path."
+
+For a recording they give you, run the same command with their file and an
+output name beside it. Options are in the
+[README](README.md#quick-start).
+
+### 5. Finish
+
+Tell the person, in one or two lines, for example:
+
+> The Voice Isolator is ready on the Metal GPU. The clean voice is in
+> sample_14_clean.wav and the removed background in
+> sample_14_clean_background.wav. Give me a file to clean, or say "open the
+> demo" for the microphone version.
+
+Name the device the doctor reported. To open the demo, follow the
+[demo README](demo/README.md).
+
+### Rules
+
+- Start the demo locally. Add `--share` (a public link) only when the person
+ asked for one.
+- Keep the person's audio on this machine: do not upload it anywhere.
+- Never ask the person to paste a Hugging Face token or any other secret into
+ the chat.
+
+### If something goes wrong
+
+| What you see | What to do |
+|---|---|
+| Every install route in step 1 fails | Check the network or proxy, then try again. Give the person the message in step 1. |
+| `FAIL … inworld/voice-isolator is not reachable` | Hugging Face refused the download. Check that `huggingface.co` opens from this machine, or pass local model files with `--offline-model` and `--online-model`. |
+| `FAIL … cannot reach huggingface.co` | No network, a proxy, or `HF_HUB_OFFLINE` is set. Fix the connection, or pass local model files. |
+| `FAIL … checksum mismatch` | Delete the file the line names and run `voice-isolate-doctor --full` again. |
+| `WARN device: cpu: upgrade torch to 2.6 or later` | On an Apple-silicon Mac, `pip install --upgrade torch torchaudio` to use the Metal GPU. |
+| `[fast]` fails to build | Skip it: it is optional and only speeds up NVIDIA GPUs. |
+| `FAIL … failed on mps` or `on cuda` | Run with `--device cpu`. Report the error line to the person. |
+| The demo cannot use the microphone | Open it at `http://127.0.0.1:7860` (or over HTTPS); browsers allow the microphone only there. |
+
+### Remove the Voice Isolator
+
+- `pip uninstall inworld-voice-isolation` (with `uv`: `uv pip uninstall`).
+- Delete the weight files at the paths `voice-isolate-doctor` prints on its
+ `cached at` lines.
+- Delete the virtual environment you created.
diff --git a/CLAUDE.md b/CLAUDE.md
new file mode 100644
index 0000000..5e91d53
--- /dev/null
+++ b/CLAUDE.md
@@ -0,0 +1,6 @@
+# CLAUDE.md
+
+The project guide is `AGENTS.md` (shared with every coding agent); procedures are
+skills under `.agents/skills/`, mirrored into `.claude/skills/` as symlinks.
+
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000..8ea8ffb
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,95 @@
+# Contributing
+
+This repository holds the inference package and the VIBE evaluation harness.
+Training code and the dataset builder are not included.
+Start with [README.md](README.md) for usage, [bench/README.md](bench/README.md) for evaluation and [AGENTS.md](AGENTS.md) for the coding conventions.
+
+## Development setup
+
+From a checkout, with Python 3.10 or later:
+
+```bash
+make install # requires uv; creates .venv on Python 3.11 (or reuses one) with dev, eval and docs
+make test # CPU tests, including a summary of skipped tests
+make lint
+make format-check
+```
+
+`make` lists the available commands. They use `.venv/bin/python` by default;
+set `PYTHON` to use another interpreter. The equivalent manual setup is:
+
+```bash
+python -m venv .venv
+source .venv/bin/activate
+python -m pip install -e ".[dev,eval,docs]"
+python -m pytest -q -rs
+```
+
+The tests use small CPU models and need no GPU, weights or benchmark audio.
+A test whose optional dependency is missing skips and names the extra; `eval` covers the benchmark's tests.
+A smaller install still gives a green run, with more skips.
+
+### What a fresh checkout shows
+
+After `make install`, `make test` passes with nothing failing and these skips; `pytest -rs` names each one:
+
+- The golden parity tests, without the released checkpoints under `models/` (or `VOICE_ISOLATION_GOLDEN_MODEL`).
+ The checkpoints' expected checksums are in `src/inworld/voice_isolation/registry.py`.
+- The demo tests, without the `demo` extra.
+- The Mamba kernel tests, without the `fast` extra, which needs CUDA.
+- The autocast parity test, without a GPU.
+- On macOS, the tests that need a case-sensitive file system or Linux's `/proc`.
+
+Include the skip count in test reports.
+
+CI runs the same development checks on pushes and pull requests, on Ubuntu: the tests on Python 3.10 and 3.12, and the style checks on Python 3.10 with the pinned tools.
+Lint on Python 3.11 or earlier: from 3.12, pylint reads quotes inside f-strings differently and reports `inconsistent-quotes` warnings that CI does not.
+
+Use the `eval`, `asr` or `demo` extras when working on those features.
+The `demucs` extra adds the benchmark's music-separation reference row.
+Third-party benchmark systems use their own environments; see [the wrapper contract](bench/WRAPPER_CONTRACT.md).
+
+## Reporting a problem
+
+Include the command or a minimal Python example, the expected behavior, the actual behavior and the traceback.
+For inference issues, paste the output of `voice-isolate-doctor --json`, and also include:
+
+- Package or git revision, model registry name or checkpoint checksum, and inference options.
+- OS, Python, PyTorch and torchaudio versions, and the CPU or GPU model.
+- Input sample rate, channel count and duration; use a synthetic or shareable clip if needed.
+
+For benchmark issues, name the system and the board or axis in question.
+If you ran a system on your own audio, say how you ran it, and explain what you hear as well as what a metric reports.
+
+## Preparing a change
+
+Keep changes focused and describe the behavior they fix.
+Commit notebooks with outputs cleared and execution counts reset; keep editor
+checkpoints untracked.
+Follow [AGENTS.md](AGENTS.md): format touched Python with `isort` and `yapf -i`, check it with `pylint --rcfile=.pylintrc`, keep the license headers, and put tests beside the mirrored module under `tests/`.
+Run the relevant tests from the repository root; run the full suite before proposing a release.
+
+`make format` applies the pinned isort and yapf versions to `src/`, `docs/`,
+`demo/` and `tests/`. Benchmark scripts and wrappers are checked by
+`make format-check` but left unchanged by `make format`: their bytes identify
+the scorer and the rendered outputs, so changing them requires the corresponding
+re-score or re-render. Keep touched tests in arrange / act / assert sections
+separated by blank lines, and exercise public behavior rather than private helpers.
+`make lint` also checks tracked files for machine-specific paths.
+
+Source archives contain the inference package, model documentation and README figures;
+wheels contain the package and license notices. Use a repository checkout for
+the benchmark, tests and development commands. CI checks both archive inventories.
+
+Rebuild the architecture figures with `python docs/build_figures.py`. A smaller
+installation can add just the `docs` extra with `pip install -e ".[docs]"`.
+Benchmark charts additionally need `--leaderboard <board.json>`; a checkout
+includes the generated charts.
+The architecture is written directly as SVG, with live text in the benchmark
+charts' font stack and a full accessible description. Both light and dark
+variants are generated from the same layout.
+
+Benchmark experiments write to `staging/` and local scratch.
+Generate reported benchmark numbers with the leaderboard scripts.
+Explain any change to model inference, metric meaning or ranking policy, so reviewers can assess its effect on comparisons.
+Model weights, third-party code and private audio do not belong in patches.
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..d645695
--- /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/MODEL_CARD.md b/MODEL_CARD.md
new file mode 100644
index 0000000..0ec4ebb
--- /dev/null
+++ b/MODEL_CARD.md
@@ -0,0 +1,175 @@
+---
+license: apache-2.0
+library_name: inworld-voice-isolation
+pipeline_tag: audio-to-audio
+tags: [audio, speech, speech-enhancement, speech-denoising, noise-suppression, voice-isolation, 48khz, full-band, streaming, realtime]
+---
+
+<p align="center">
+ <picture>
+ <source media="(prefers-color-scheme: dark)" srcset="docs/assets/inworld-logo-white.svg">
+ <img src="docs/assets/inworld-logo-black.svg" alt="Inworld" width="220">
+ </picture>
+</p>
+
+<h1 align="center">Voice Isolator</h1>
+
+<p align="center">
+ Open-license (Apache-2.0) 48 kHz voice isolation for noisy speech recordings and live audio.
+</p>
+
+<p align="center">
+ <a href="https://github.com/inworld-ai/voice-isolator"><img src="https://img.shields.io/badge/GitHub-inworld--ai%2Fvoice--isolator-181717?logo=github" alt="GitHub: inworld-ai/voice-isolator"></a>
+</p>
+
+---
+
+## TL;DR
+
+Inworld Voice Isolator v1 ships as two models that share one architecture:
+
+| | `voice-isolator-v1` | `voice-isolator-v1-realtime` |
+|---|---|---|
+| made for | recorded audio and anything not latency-sensitive, at the best quality | live audio, as a stream in your pipeline or production |
+| how it runs | offline: every frame sees its whole 8 s chunk | a causal stream with 20 ms of look-ahead |
+| parameters | 64M | 58M |
+
+**Use them for** cleaning recordings before playback or publication, curating speech datasets and voice pipelines where the speaker's identity must survive.
+With the realtime model, use them for live calls and streams.
+Subtract the isolated voice from the input to extract background noise or a backing-track residual for vocals/music separation.
+
+**They are not** a speaker selector or a restoration model.
+Restoration is planned for version 2 (see [Plans](https://github.com/inworld-ai/voice-isolator#plans)).
+
+## Quick start
+
+Using a coding agent? Point it at the [setup section of AGENTS.md](https://github.com/inworld-ai/voice-isolator/blob/main/AGENTS.md#setting-up-the-voice-isolator-for-a-user): it installs the package, checks the machine with `voice-isolate-doctor` and cleans a first file.
+
+```bash
+pip install inworld-voice-isolation
+# or from a clone: git clone https://github.com/inworld-ai/voice-isolator && cd voice-isolator && pip install -e .
+
+# a noisy example; a clone also has it at demo/examples/sample_14.wav
+curl -LO https://raw.githubusercontent.com/inworld-ai/voice-isolator/main/demo/examples/sample_14.wav
+
+# offline isolation (downloads the offline model on first use):
+# the voice goes to sample_14_clean.wav and the removed background
+# to sample_14_clean_background.wav, beside it
+voice-isolate sample_14.wav sample_14_clean.wav
+```
+
+Both are float32 WAVs at 48 kHz, with their original levels preserved; together they reconstruct the aligned mono input.
+Use `--output-sr 0` to keep the input rate, `--background noise.wav` to choose the background path for one file, or `--no-background` to save only the voice.
+
+```python
+from inworld import voice_isolation
+
+# isolate a recording offline
+offline = voice_isolation.VoiceIsolator("inworld/voice-isolator")
+wav, sample_rate = voice_isolation.load_audio("sample_14.wav")
+voice = offline.isolate(wav, sample_rate)
+voice_isolation.save_audio("sample_14_clean.wav", voice, sample_rate, subtype="FLOAT")
+voice_isolation.save_audio("sample_14_clean_background.wav", wav - voice, sample_rate, subtype="FLOAT") # what was removed
+```
+
+### Streaming
+
+The realtime model isolates the voice as the audio arrives, with 20 ms of look-ahead:
+
+```python
+import torch
+from inworld import voice_isolation
+
+live = voice_isolation.VoiceIsolator("inworld/voice-isolator",
+ mode="streaming", lookahead_frames=2)
+session = live.stream() # takes 48 kHz mono, in pieces of any size
+wav, sample_rate = voice_isolation.load_audio("sample_14.wav") # 48 kHz mono, standing in for a live source
+voice = []
+for start in range(0, len(wav), 960): # 20 ms at a time, as a microphone delivers it
+ voice.append(session.push(wav[start:start + 960])) # the samples that are final: play or send them
+voice.append(session.flush()) # the rest, once the source ends
+voice_isolation.save_audio("sample_14_streamed.wav", torch.cat(voice), sample_rate)
+```
+
+The streaming CLI writes only the isolated voice, after the whole file has gone through:
+
+```bash
+voice-isolate sample_14.wav sample_14_streamed.wav --mode streaming --lookahead 2
+```
+
+The weights download on first use, and their checksums are verified.
+The mode picks the checkpoint: `voice-isolator-v1` offline, `voice-isolator-v1-realtime` for streaming.
+CUDA is used when available, Apple's Metal backend (`mps`) on an Apple-silicon Mac with PyTorch 2.6 or later, and the CPU otherwise; `--device` picks one.
+
+The code, the [interactive demo](https://github.com/inworld-ai/voice-isolator/blob/main/demo/README.md) and the [benchmark](https://github.com/inworld-ai/voice-isolator/blob/main/bench/README.md) are on GitHub: [inworld-ai/voice-isolator](https://github.com/inworld-ai/voice-isolator).
+The demo loads both models at startup: **Offline** processes files and samples into voice and background audio; **Online** streams the microphone for up to 60 seconds with updating waveforms and spectrograms, pausing capture before playback.
+
+## Hardware
+
+Tested on NVIDIA Ampere, Hopper and Blackwell GPUs (A100, H100, B200 and B300) and on CPU.
+Smaller GPUs are not tested yet (see [Plans](https://github.com/inworld-ai/voice-isolator#plans)).
+
+## The VIBE benchmark
+
+<p align="center">
+ <picture>
+ <source media="(prefers-color-scheme: dark)" srcset="docs/assets/board-dark.svg">
+ <img src="docs/assets/board-light.svg" alt="Inworld VIBE full-band tier: denoising score per system" width="100%">
+ </picture>
+</p>
+
+Inworld VIBE (Voice Isolation Benchmark and Evals) ranks 48 kHz voice isolators on two boards.
+The chart is the denoising board, which ranks every system except those that put more than 10 dB more energy above a band-limited input's band than inside it; those are ranked on restoration.
+Inworld scores every system on its internal evaluation set, which is not distributed.
+
+[How the systems are scored and what the scores mean](https://github.com/inworld-ai/voice-isolator/blob/main/bench/README.md).
+
+## Architecture
+
+<p align="center">
+ <picture>
+ <source media="(prefers-color-scheme: dark)" srcset="docs/assets/architecture-dark.svg">
+ <img src="docs/assets/architecture-light.svg" alt="The network: STFT, band split, seven dual-path blocks, per-band heads, iSTFT; the two checkpoints" width="100%">
+ </picture>
+</p>
+
+A band-split dual-path network over the STFT (n_fft 2048, hop 480 at 48 kHz, 10 ms frames).
+Each frame's spectrum is cut into 46 bands, narrow at low frequency and wide at the top, one token per band and frame, width 512.
+Seven blocks refine the tokens, alternating two kinds.
+Four blocks run time attention with rotary position and exclusive self attention, followed by attention across bands.
+Three blocks run Mamba along time, followed by Mamba across bands (state 16).
+Per-band heads produce a bounded complex mask and a bounded per-bin residual, added to the input spectrum.
+The offline model has 64.0M parameters.
+The realtime model has 58.2M; its blocks are causal and it carries a look-ahead embedding.
+Input is one channel at 48 kHz; nothing is separated or synthesized beforehand.
+
+## Two checkpoints
+
+The offline model, `voice-isolator-v1`, is two-sided: every frame sees its whole 8 s chunk, and long inputs render in 8 s chunks overlapping by 2 s.
+The realtime model, `voice-isolator-v1-realtime`, is causal, with a trained look-ahead of 0, 20 or 40 ms; its algorithmic latency is 63 ms at 20 ms of look-ahead.
+Both keep the foreground voice: when two people speak at once, the louder voice is kept and one a few dB quieter is removed, while voices at similar levels are usually both kept.
+In the speech-enhancement literature, version 1 does denoising (noise suppression): it removes what surrounds the voice and restores nothing the recording lost, such as missing bandwidth; restoration comes with version 2.
+
+## Training data
+
+Inworld Voice Isolator v1 was trained on approximately 10,000 hours of unique audio.
+Paired examples built from recorded speech: read and conversational speech in many languages, expressive and character voices, whispered speech, singing, and the speaker's own non-verbal sounds such as laughter, breaths and sighs.
+The speech was mixed with environmental and household noise, traffic, rain and wind, music and crowd sound, isolated transient events and competing talkers, through measured and simulated room responses and telephony and codec degradations.
+Real recordings of the same speech, captured clean and in rooms, complete the set.
+The objective: return the voice as it was recorded, remove everything that is not the speaker (noise, music, other voices and the late room tail), keep the speaker's own non-verbal sounds, level and timing, and invent nothing.
+
+Third-party datasets used in training are credited in [NOTICE](NOTICE).
+
+## License
+
+Code and weights are Apache-2.0 ([LICENSE](LICENSE)).
+Third-party notices are in [NOTICE](NOTICE).
+
+## How to contribute
+
+Everyone is welcome to use the model however they like and to make it better in any way they see fit!
+Development happens on GitHub: see [CONTRIBUTING.md](https://github.com/inworld-ai/voice-isolator/blob/main/CONTRIBUTING.md) for setup, tests and bug reports.
+
+---
+
+<p align="center">Built for people with ❤️ by Inworld.</p>
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..51ad705
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,37 @@
+# Copyright 2026 Inworld AI — Apache-2.0
+.DEFAULT_GOAL := help
+
+PYTHON ?= .venv/bin/python
+STYLE_PATHS := src bench/scripts bench/wrappers docs demo tests
+ISORT_PATHS := src bench/scripts docs demo tests
+# Benchmark source bytes identify the scorer and the rendered outputs.
+FORMAT_PATHS := src docs demo tests
+
+.PHONY: help install test lint format format-check
+
+help: ## Show the available commands
+ @awk 'BEGIN {FS = ":.*?## "} /^[a-zA-Z_-]+:.*## / {printf "%-14s %s\n", $$1, $$2}' $(MAKEFILE_LIST)
+
+# Python 3.11 lints as CI's 3.10 does and runs every test on a current Mac.
+# From 3.12 pylint reads quotes inside f-strings differently and reports
+# inconsistent-quotes throughout; on 3.10 the newest SciPy that installs does
+# not load on recent macOS, which fails the benchmark tests that import it.
+install: ## Create .venv on Python 3.11, or reuse one, and install the dev, eval and docs extras (requires uv)
+ @test -x .venv/bin/python || uv venv --python 3.11 .venv
+ uv pip install --python $(PYTHON) -e ".[dev,eval,docs]"
+
+test: ## Run the CPU tests and report optional and golden-parity skips
+ $(PYTHON) -m pytest -q -rs
+
+lint: ## Check Google Python style and tracked-file hygiene
+ PYTHONPATH=src $(PYTHON) -m pylint --rcfile=.pylintrc inworld
+ $(PYTHON) -m pylint --rcfile=.pylintrc $(filter-out src,$(STYLE_PATHS))
+ @if git grep -nE '(^|[^[:alnum:]_/.])/(home|inworld|mnt)/' -- . ':!AGENTS.md' ':!Makefile' ':!.github/workflows/ci.yml'; then exit 1; fi
+
+format: ## Format Python, preserving the benchmark's digest-bound source files
+ $(PYTHON) -m isort $(FORMAT_PATHS)
+ $(PYTHON) -m yapf --in-place --recursive --style=.style.yapf $(FORMAT_PATHS)
+
+format-check: ## Check all Python formatting without changing files
+ $(PYTHON) -m yapf --diff --recursive --style=.style.yapf $(STYLE_PATHS)
+ $(PYTHON) -m isort --check-only --diff $(ISORT_PATHS)
diff --git a/NOTICE b/NOTICE
new file mode 100644
index 0000000..892f428
--- /dev/null
+++ b/NOTICE
@@ -0,0 +1,21 @@
+Inworld Voice Isolator
+Copyright 2026 Inworld AI
+
+The model weights were trained on Inworld's first-party data, including data
+purchased from vendors under private terms, and on these third-party datasets:
+
+- VocalSet — CC BY 4.0, https://zenodo.org/records/1442513
+- IndicVoices-R — CC BY 4.0,
+ https://huggingface.co/datasets/ai4bharat/indicvoices_r
+- VCTK — ODC-By 1.0, https://datashare.ed.ac.uk/handle/10283/2119
+
+This product optionally downloads and uses, at runtime, third-party models and
+libraries that remain under their own licenses:
+
+- Mamba selective-scan kernels (mamba-ssm, causal-conv1d) — Apache-2.0,
+ https://github.com/state-spaces/mamba (optional [fast] extra; without it
+ the same scan runs in plain PyTorch).
+
+The golden parity fixtures include a modified LibriSpeech recording under
+CC BY 4.0; see tests/fixtures/README.md. They are not included in the Python
+package.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..2571fe7
--- /dev/null
+++ b/README.md
@@ -0,0 +1,165 @@
+<p align="center">
+ <picture>
+ <source media="(prefers-color-scheme: dark)" srcset="docs/assets/inworld-logo-white.svg">
+ <img src="docs/assets/inworld-logo-black.svg" alt="Inworld" width="220">
+ </picture>
+</p>
+
+<h1 align="center">Voice Isolator</h1>
+
+<p align="center">
+ Open-license (Apache-2.0) 48 kHz voice isolation for noisy speech recordings and live audio.
+</p>
+
+<p align="center">
+ <a href="https://huggingface.co/inworld/voice-isolator"><img src="https://img.shields.io/badge/Hugging%20Face-inworld%2Fvoice--isolator-FFD21E?logo=huggingface&logoColor=FFD21E" alt="Hugging Face: inworld/voice-isolator"></a>
+</p>
+
+---
+
+## TL;DR
+
+Inworld Voice Isolator v1 ships as two models that share one architecture:
+
+| | `voice-isolator-v1` | `voice-isolator-v1-realtime` |
+|---|---|---|
+| made for | recorded audio and anything not latency-sensitive, at the best quality | live audio, as a stream in your pipeline or production |
+| how it runs | offline: every frame sees its whole 8 s chunk | a causal stream with 20 ms of look-ahead |
+| parameters | 64M | 58M |
+
+**Use them for** cleaning recordings before playback or publication, curating speech datasets and voice pipelines where the speaker's identity must survive.
+With the realtime model, use them for live calls and streams.
+Subtract the isolated voice from the input to extract background noise or a backing-track residual for vocals/music separation.
+
+**They are not** a speaker selector or a restoration model.
+Restoration is planned for version 2 (see [Plans](#plans)), stay tuned!
+
+## Quick start
+
+Using a coding agent? Point it at the [setup section of AGENTS.md](https://github.com/inworld-ai/voice-isolator/blob/main/AGENTS.md#setting-up-the-voice-isolator-for-a-user): it installs the package, checks the machine with `voice-isolate-doctor` and cleans a first file.
+
+```bash
+pip install inworld-voice-isolation
+# or from a clone: git clone https://github.com/inworld-ai/voice-isolator && cd voice-isolator && pip install -e .
+
+# a noisy example; a clone also has it at demo/examples/sample_14.wav
+curl -LO https://raw.githubusercontent.com/inworld-ai/voice-isolator/main/demo/examples/sample_14.wav
+
+# offline isolation (downloads the offline model on first use):
+# the voice goes to sample_14_clean.wav and the removed background
+# to sample_14_clean_background.wav, beside it
+voice-isolate sample_14.wav sample_14_clean.wav
+```
+
+Both are float32 WAVs at 48 kHz, with their original levels preserved; together they reconstruct the aligned mono input.
+Use `--output-sr 0` to keep the input rate, `--background noise.wav` to choose the background path for one file, or `--no-background` to save only the voice.
+
+```python
+from inworld import voice_isolation
+
+# isolate a recording offline
+offline = voice_isolation.VoiceIsolator("inworld/voice-isolator")
+wav, sample_rate = voice_isolation.load_audio("sample_14.wav")
+voice = offline.isolate(wav, sample_rate)
+voice_isolation.save_audio("sample_14_clean.wav", voice, sample_rate, subtype="FLOAT")
+voice_isolation.save_audio("sample_14_clean_background.wav", wav - voice, sample_rate, subtype="FLOAT") # what was removed
+```
+
+### Streaming
+
+The realtime model isolates the voice as the audio arrives, with 20 ms of look-ahead:
+
+```python
+import torch
+from inworld import voice_isolation
+
+live = voice_isolation.VoiceIsolator("inworld/voice-isolator",
+ mode="streaming", lookahead_frames=2)
+session = live.stream() # takes 48 kHz mono, in pieces of any size
+wav, sample_rate = voice_isolation.load_audio("sample_14.wav") # 48 kHz mono, standing in for a live source
+voice = []
+for start in range(0, len(wav), 960): # 20 ms at a time, as a microphone delivers it
+ voice.append(session.push(wav[start:start + 960])) # the samples that are final: play or send them
+voice.append(session.flush()) # the rest, once the source ends
+voice_isolation.save_audio("sample_14_streamed.wav", torch.cat(voice), sample_rate)
+```
+
+The streaming CLI writes only the isolated voice, after the whole file has gone through:
+
+```bash
+voice-isolate sample_14.wav sample_14_streamed.wav --mode streaming --lookahead 2
+```
+
+`inworld/voice-isolator` is the weights' repository, [huggingface.co/inworld/voice-isolator](https://huggingface.co/inworld/voice-isolator): they download on first use and are checked against the checksums in [the registry](https://github.com/inworld-ai/voice-isolator/blob/main/src/inworld/voice_isolation/registry.py).
+The mode picks the checkpoint: `voice-isolator-v1` offline, `voice-isolator-v1-realtime` for streaming.
+`--model` and `VoiceIsolator(...)` also take either name, a local checkpoint path or an `hf://<org>/<repo>/<file>[@<revision>]` location.
+Python 3.10 or later and PyTorch 2.1 or later; `pip install "inworld-voice-isolation[fast]"` adds the CUDA Mamba kernels.
+CUDA is used when available, Apple's Metal backend (`mps`) on an Apple-silicon Mac with PyTorch 2.6 or later, and the CPU otherwise; `--device` picks one.
+
+The [interactive demo](https://github.com/inworld-ai/voice-isolator/blob/main/demo/README.md) has **Offline** and **Online** tabs, with both models loaded at startup.
+Offline processes files and samples into voice and background audio. Online streams the microphone for up to 60 seconds, updating waveforms and spectrograms as you speak; capture pauses before playback.
+The background is whatever the model removed and can contain voice leakage.
+
+The [audio cleanup notebook](https://github.com/inworld-ai/voice-isolator/blob/main/examples/audio_cleanup.ipynb) walks through a first evaluation: clean a noisy sample, compare it with the original by ear, then try your own recording.
+
+## Hardware
+
+Tested on NVIDIA Ampere, Hopper and Blackwell GPUs (A100, H100, B200 and B300) and on CPU.
+Smaller GPUs are not tested yet (see [Plans](#plans)).
+
+## The VIBE benchmark
+
+<p align="center">
+ <picture>
+ <source media="(prefers-color-scheme: dark)" srcset="docs/assets/board-dark.svg">
+ <img src="docs/assets/board-light.svg" alt="Inworld VIBE full-band tier: denoising score per system" width="100%">
+ </picture>
+</p>
+<p align="center">
+ <picture>
+ <source media="(prefers-color-scheme: dark)" srcset="docs/assets/board-restoration-dark.svg">
+ <img src="docs/assets/board-restoration-light.svg" alt="Inworld VIBE full-band tier: restoration score per system" width="100%">
+ </picture>
+</p>
+
+Inworld VIBE (Voice Isolation Benchmark and Evals) ranks 48 kHz voice isolators on two boards.
+A system that puts more than 10 dB more energy above a band-limited input's band than inside it is ranked on restoration; every other system is ranked on denoising.
+Inworld scores every system on its internal evaluation set, which is not distributed.
+
+[How the systems are scored and what the scores mean](https://github.com/inworld-ai/voice-isolator/blob/main/bench/README.md).
+
+## Architecture
+
+<p align="center">
+ <picture>
+ <source media="(prefers-color-scheme: dark)" srcset="docs/assets/architecture-dark.svg">
+ <img src="docs/assets/architecture-light.svg" alt="The network: STFT, band split, seven dual-path blocks, per-band heads, iSTFT; the two checkpoints" width="100%">
+ </picture>
+</p>
+
+See the model card for [architecture details](https://github.com/inworld-ai/voice-isolator/blob/main/MODEL_CARD.md#architecture) and [training data](https://github.com/inworld-ai/voice-isolator/blob/main/MODEL_CARD.md#training-data).
+
+## Plans
+
+- [x] Version 1, denoising only: two checkpoints, one for recordings and one for live audio.
+- [ ] Version 2: one model that runs offline or streaming and does denoising and restoration.
+ It keeps removing what is around the voice, and restores what the recording lost when asked to.
+ It will be scored on both VIBE boards.
+- [ ] Testing on smaller GPUs.
+- [ ] On-device support (beyond Apple silicon).
+- [ ] Allow natural language prompting.
+
+## License
+
+Code and weights are Apache-2.0 ([LICENSE](https://github.com/inworld-ai/voice-isolator/blob/main/LICENSE)).
+Third-party notices are in [NOTICE](https://github.com/inworld-ai/voice-isolator/blob/main/NOTICE).
+
+## How to contribute
+
+Everyone is welcome to use the model however they like and to make it better in any way they see fit!
+Ask your agent to open a PR and we'll take a look.
+See [CONTRIBUTING.md](https://github.com/inworld-ai/voice-isolator/blob/main/CONTRIBUTING.md) for setup, tests and bug reports, and [AGENTS.md](https://github.com/inworld-ai/voice-isolator/blob/main/AGENTS.md) for coding conventions.
+
+---
+
+<p align="center">Built for people with ❤️ by Inworld.</p>
diff --git a/bench/CONTROLS.md b/bench/CONTROLS.md
new file mode 100644
index 0000000..35436f4
--- /dev/null
+++ b/bench/CONTROLS.md
@@ -0,0 +1,36 @@
+# Metric controls
+
+Known damage in, what the published metrics say about it out. Every row is a synthetic system built from the paired audio of a fixed, language-stratified slice of the set (360 items over 15 conditions; set `f5a6420d67b7ef45`) and scored by the same code as a real system. Columns are read on the `clean` items of the slice, where the reference is the input and a defect is the only thing that happened; `lost_pct` is the share of speech blocks kept below -10 dB, `mag_snr` the signal-to-error ratio of the magnitude spectrum, `nv_lost_pct` the share of vocal sounds outside speech lost on the clean recordings of laughs, breaths and sighs, `fidelity` the published axis, and babble suppression is read at +4 dB. A delay of up to 100 ms, a flipped polarity and a gain of up to 12 dB are conventions the scorer undoes, not damage. The last three columns are the same-room block's rows, read on its items from two renders of the control, of the mixture and of the reference, as the board reads every system (`scoreevents.py`): the noise left over the labelled events and pauses, in dB, and the voice's level with the noise against without; a slice without the block leaves them blank. Generated by `scripts/controls.py`; the expectations live in its `EXPECTED` table.
+
+| control | the system returns | `si_sdr` | `kept_coh_p10` | `lost_pct` | `level_err` | `hf_err` | `spk_sim` | `nisqa_mos` | `mag_snr` | `nv_lost_pct` | `fidelity` | `babble_supp_db` | `event_resid_db` | `floor_resid_db` | `voice_level_db` | held |
+|---|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---|
+| `reference` | the clean reference, untouched | 117.5 | 0.0 | 0.0 | 0.00 | 0.00 | 1.000 | 4.54 | 120.0 | 0.0 | 1.00 | -58.2 | -20.0 | -20.0 | 0.0 | yes |
+| `input` | the unprocessed mixture | 117.5 | 0.0 | 0.0 | 0.00 | 0.00 | 1.000 | 4.54 | 120.0 | 0.0 | 1.00 | 0.0 | 0.0 | 0.0 | -0.0 | yes |
+| `silence` | nothing | -90.0 | -68.0 | 100.0 | 212.10 | 84.05 | 0.528 | 2.11 | 0.0 | 100.0 | 0.00 | 4.0 | 0.0 | 0.0 | -20.0 | yes |
+| `bedonly` | the mixture minus the reference: everything but the voice | -90.0 | -68.0 | 100.0 | 212.10 | 84.05 | 0.528 | 2.11 | 0.0 | 100.0 | 0.00 | 12.6 | 0.0 | 0.0 | -20.0 | yes |
+| `gainup6db` | the reference 6 dB louder | 123.5 | -0.0 | 0.0 | 6.00 | 0.00 | 1.000 | 4.39 | 120.0 | 0.0 | 0.83 | -58.2 | -20.0 | -20.0 | 0.0 | yes |
+| `gaindown6db` | the reference 6 dB quieter | 111.5 | -0.0 | 0.0 | 6.00 | 0.00 | 1.000 | 4.43 | 120.0 | 0.0 | 0.84 | -58.2 | -20.0 | -20.0 | 0.0 | yes |
+| `polarity` | the reference with its sign flipped | 117.5 | 0.0 | 0.0 | 0.00 | 0.00 | 1.000 | 4.54 | 120.0 | 0.0 | 1.00 | -58.2 | -20.0 | -20.0 | 0.0 | yes |
+| `delay20ms` | the reference 20 ms late | 117.5 | 0.0 | 0.0 | 0.00 | 0.00 | 1.000 | 4.55 | 120.0 | 0.0 | 1.00 | -58.2 | -20.0 | -20.0 | 0.0 | yes |
+| `delete20ms` | the reference with 20 ms of speech removed | 31.2 | 0.0 | 0.0 | 0.01 | 0.01 | 1.000 | 4.18 | 33.4 | 0.0 | 0.91 | -24.1 | -20.0 | -20.0 | 0.0 | yes |
+| `delete40ms` | the reference with 40 ms of speech removed | 24.5 | 0.0 | 0.1 | 0.04 | 0.05 | 0.999 | 3.97 | 25.9 | 0.0 | 0.83 | -18.5 | -20.0 | -20.0 | 0.0 | yes |
+| `delete80ms` | the reference with 80 ms of speech removed | 19.7 | 0.0 | 1.6 | 0.07 | 0.06 | 0.998 | 3.88 | 20.4 | 1.3 | 0.78 | -16.5 | -20.0 | -20.0 | 0.0 | yes |
+| `delete160ms` | the reference with 160 ms of speech removed | 18.4 | 0.0 | 2.7 | 0.13 | 0.24 | 0.998 | 3.87 | 18.9 | 5.2 | 0.75 | -15.0 | -19.7 | -20.0 | -0.0 | yes |
+| `delete320ms` | the reference with 320 ms of speech removed | 15.6 | -1.8 | 5.9 | 0.27 | 0.85 | 0.997 | 3.83 | 16.0 | 0.0 | 0.70 | -10.5 | -19.7 | -20.0 | -0.0 | yes |
+| `hfinvented` | the reference with 8-24 kHz replaced by noise of the same energy | 20.3 | -0.7 | 0.9 | 0.00 | 0.19 | 1.000 | 4.50 | 28.9 | 2.6 | 0.97 | -15.2 | -20.0 | -20.0 | 0.0 | yes |
+| `hfcut` | the reference with 8-24 kHz removed | 23.4 | -0.6 | 0.7 | 0.06 | 70.43 | 1.000 | 4.61 | 23.4 | 2.6 | 0.79 | -18.2 | -20.0 | -20.0 | 0.0 | yes |
+| `resynth` | the reference re-synthesised: same spectrogram, phases perturbed (another waveform) | 26.0 | -0.0 | 0.0 | 0.03 | 0.00 | 1.000 | 4.52 | 31.9 | 0.0 | 1.00 | -22.0 | -20.0 | -20.0 | 0.0 | yes |
+| `floorless` | the reference with its own noise floor gated out | 59.9 | -0.0 | 0.0 | 0.00 | 0.00 | 0.999 | 4.50 | 61.5 | 0.0 | 1.00 | -52.9 | -20.0 | -20.0 | 0.0 | yes |
+| `halfnoise` | the reference with half of what the mixture added | 117.5 | 0.0 | 0.0 | 0.00 | 0.00 | 1.000 | 4.54 | 120.0 | 0.0 | 1.00 | -6.0 | -6.0 | -6.0 | -0.0 | yes |
+| `transientsleft` | the reference with what the mixture added above -40 dBFS: its transients left, its quiet floor gone | 117.5 | 0.0 | 0.0 | 0.00 | 0.00 | 1.000 | 4.54 | 120.0 | 0.0 | 1.00 | -0.0 | -0.6 | -19.2 | -0.0 | yes |
+| `floorleft` | the reference with what the mixture added under -40 dBFS: its quiet floor left, its transients gone | 117.5 | 0.0 | 0.0 | 0.00 | 0.00 | 1.000 | 4.54 | 120.0 | 0.0 | 1.00 | -40.1 | -15.2 | -0.0 | -0.0 | yes |
+| `voiceducked` | the reference 3 dB quieter wherever the mixture added anything: a gate rid of the noise at the voice's expense, under the voice gate | 117.5 | 0.0 | 0.0 | 0.00 | 0.00 | 1.000 | 4.54 | 120.0 | 0.0 | 1.00 | -6.7 | 0.0 | 0.0 | -3.0 | yes |
+
+## Blind spots
+
+- `delete20ms`: retention is read per 100 ms block and as a 10th percentile: a dropped 20-80 ms (a consonant, a syllable onset) moves neither; only NISQA, waveform SI-SDR and the magnitude ratio react, the last from 40 ms on (a 20 ms hole stays above its ceiling). A recogniser's transcript does not react either: Whisper large-v3 restores the word from context for holes up to 160 ms (scorecontent.py's ctl_ rows), so the content check sees a dropout only from about 320 ms.
+- `delete40ms`: as delete20ms.
+- `delete80ms`: as delete20ms; `lost_pct` starts to see it when the span empties a block.
+- `hfinvented`: a top octave replaced by noise of the same energy keeps every band level, the speaker embedding and NISQA; waveform SI-SDR reacts but cannot tell this from a harmless re-synthesis (`resynth`), and the magnitude ratio moves little, because the top octave holds little of the energy. Whether listeners hear it is an open listening question.
+
+Expectations: `reference` fidelity >= 0.95, kept_coh_p10 >= -1, lost_pct <= 0.5, nv_lost_pct <= 0.5, spk_sim >= 0.99, event_resid_db <= -19.9, floor_resid_db <= -19.9, voice_level_db >= -0.1, si_sdr >= 60; `input` fidelity >= 0.95, event_resid_db >= -0.05, floor_resid_db >= -0.05, voice_level_db <= 0.05; `silence` fidelity <= 0.5, kept_coh_p10 <= -40, lost_pct >= 99, nv_lost_pct >= 99; `bedonly` fidelity <= 0.5, kept_coh_p10 <= -40, lost_pct >= 99, nv_lost_pct >= 99, babble_supp_db >= 0; `gainup6db` level_err >= 5.5, fidelity <= 0.85, lost_pct <= 0.5, event_resid_db <= -19.9, floor_resid_db <= -19.9, voice_level_db >= -0.1; `gaindown6db` level_err >= 5.5, fidelity <= 0.85, lost_pct <= 0.5, event_resid_db <= -19.9, floor_resid_db <= -19.9, voice_level_db >= -0.1; `polarity` fidelity >= 0.95, kept_coh_p10 >= -1, lost_pct <= 0.5, nv_lost_pct <= 0.5, spk_sim >= 0.99, event_resid_db <= -19.9, floor_resid_db <= -19.9, voice_level_db >= -0.1; `delay20ms` fidelity >= 0.95, kept_coh_p10 >= -1, lost_pct <= 0.5, nv_lost_pct <= 0.5, spk_sim >= 0.99, event_resid_db <= -19.9, floor_resid_db <= -19.9, voice_level_db >= -0.1; `delete20ms` nisqa_mos <= 4.35; `delete40ms` nisqa_mos <= 4.35; `delete80ms` nisqa_mos <= 4.35; `delete160ms` nisqa_mos <= 4.35, fidelity <= 0.95; `delete320ms` lost_pct >= 2, fidelity <= 0.9; `hfinvented` si_sdr <= 25; `hfcut` hf_err >= 3, fidelity <= 0.85; `resynth` fidelity >= 0.95, kept_coh_p10 >= -1, lost_pct <= 0.5, nv_lost_pct <= 0.5, spk_sim >= 0.99, event_resid_db <= -19.9, floor_resid_db <= -19.9, voice_level_db >= -0.1, mag_snr >= 30; `floorless` fidelity >= 0.95, kept_coh_p10 >= -1, lost_pct <= 0.5, nv_lost_pct <= 0.5, spk_sim >= 0.99, event_resid_db <= -19.9, floor_resid_db <= -19.9, voice_level_db >= -0.1; `halfnoise` event_resid_db <= -5.9, floor_resid_db <= -5.9, voice_level_db >= -0.1; `transientsleft` event_resid_db >= -3, floor_resid_db <= -15; `floorleft` event_resid_db <= -10, floor_resid_db >= -0.5; `voiceducked` voice_level_db <= -2.9, floor_resid_db >= -0.1, event_resid_db >= -0.1.
diff --git a/bench/METRICS.md b/bench/METRICS.md
new file mode 100644
index 0000000..6942ecd
--- /dev/null
+++ b/bench/METRICS.md
@@ -0,0 +1,326 @@
+# Inworld VIBE: metrics, views and diagnostics
+
+The detail behind the [leaderboard](README.md): the two boards and the views of each, the task contracts, the conditions of the set, how every axis is measured, the diagnostics reported beside the boards and how a score is bound to what was rendered.
+This page defines what each view measures; the tables are generated by `scripts/leaderboard.py` and the sidecars from score files that are not distributed.
+
+## Views of the boards
+
+### Two boards: denoising and restoration
+
+VIBE publishes two scores per system, each on its own board, and no composite of both.
+Denoising is the mean of three parts, what a system removes (suppression, music, cleanup, events, voices), what it keeps (preservation, fidelity) and how the result sounds (timbre, quality); it reads the denoise contract, and it ranks the systems that add nothing above the input's band.
+Restoration is the fourth part alone, what a system restores: the room axis, the dry voice out of a real room; it ranks the systems that restore above the input's band (more than 10 dB on the band-limited rows).
+Every system is scored on both boards and the board `leaderboard.py --json-out` writes carries both scores; its tables list each system under the board that ranks it.
+The rule is the registry's (`axes.json`, `assign`): a system without the band-limited rows is ranked on neither board and listed as not ranked, since missing evidence is not a kept band, and the restoration board ranks the full-band tier, so a 16 kHz-tier system the rule sends there is listed as not ranked too.
+Each score needs its own axes and no other's, so a system complete on denoising ranks there whatever its restoration rows hold.
+The band axis is scored and shown beside both scores but included in neither.
+It uses the two band-limited rows whose input lacks the most, `srsweep_8k` (a 4 kHz band) and `srsweep_16k` (8 kHz), with two measurements each:
+
+- `band_added_db`: the energy the output holds above the input's band, against the reference band-limited the same way, less the mean of the bands inside it, so a gain applied everywhere cancels. It is derived from the scorer's per-band levels at load (and per item by the comparison tools) and scaled from the input's own −0.85 dB to a declared 40 dB, since the set holds no reference above the input's band.
+- `spk_sim`: the speaker's similarity to that reference.
+
+It credits any addition above the band, a tone included, and the speaker row, read at 16 kHz, cannot see what sits above 8 kHz, so the pair measures addition and not the restoration of speech.
+It stays a diagnostic until a measure of the reconstructed band's speech exists; the systems that add above the band are ranked on the restoration board, so a denoising reader meets none of them in the denoising table.
+The `*` after a system's name marks streaming: the streaming probe is yes.
+The script also prints the order under a strict deleted-rate gate.
+A row whose level calibration saturated is not ranked, and the script says why.
+
+### Raw diagnostics
+
+The tables print raw measurements beside the axes; higher is better for the normalized columns, and the raw ones read as follows.
+More negative `supp dB` means less interference left under crowd chatter at the voice's scale.
+More negative `pauses dB` means the real recordings' pauses sit further below the output's own voice (capped at −45).
+Lower `del %` means fewer deleted primary-speaker segments.
+Lower `laughs lost %` means fewer of the vocal sounds outside speech lost under a bed at the voice's level.
+Higher `NISQA` means greater predicted listening quality.
+`precision` is the arithmetic each wrapper runs its network in, declared beside its receipts rather than measured.
+Each row names how the system was run where that matters (`wrappers/meta/<name>.json`).
+The two URGENT 2026 baselines say whether the release script's final peak normalization is kept ([WRAPPER_CONTRACT.md](WRAPPER_CONTRACT.md)).
+
+### Core view
+A `*` after a system's name marks streaming (the streaming probe is yes); the systems that restore above the input's band are listed under Restoration and the others under Denoising, as on the whole-set board.
+
+The set has a multilingual core, where English carries about half of every paired condition and eleven other languages share the rest, and an English-only extension of extra items and the families that exist only in English.
+The leaderboard in [README.md](README.md) ranks on everything.
+This one ranks the same systems on the core alone, scored separately (`BENCH_SUBSET=core`, `results/core/`) on the core axes of the registry (`axes.json`), so the extension cannot move the multilingual result.
+Those axes leave out the rows of the English-only families, the −5 dB rows of stationary noise and traffic among them; crowd chatter at −5 dB, which the core's recordings carry, is read as on the whole set.
+The recordings of laughs, breaths and sighs exist in English only, so the core has no such rows and no `laughs lost %`.
+
+`scripts/leaderboard.py --view core --results <results>/core` prints both boards of the core.
+
+**How to read it.**
+Each score is a stated choice: the mean of its parts, fixed anchors, no hard gate, and a gap under 0.03 is a tie (the script prints every group of tied systems).
+The timbre axis stretches a twentieth of the speaker-similarity scale over its whole length, so a timbre gap under 0.05 is a tie as well.
+Quote the axis columns, not the rank.
+Per-item delay alignment cannot undo phase changes or time-varying changes from vocoder re-synthesis.
+Waveform-coherence and residual measurements can therefore penalize a natural-sounding re-synthesis without establishing that words were lost.
+For those systems, also read NISQA, speaker similarity, primary-speaker deletion, downstream ASR and the content check, and listen; the composite alone does not settle the comparison.
+A system is ranked only when every axis of the board that ranks it has at least 20 scored items per condition and its primary-anchored deletion sidecar covers the complete frozen INPUT cohort with unchanged segment denominators.
+All rows are measured on that cohort, independent of which competitors are present.
+A system that failed to return some items is listed under *missing outputs*.
+
+### Competing voices: the voices axis
+
+The voices axis reads SI-SDR on the competing-talker condition at +5 dB against the one voice the recording is of, scaled from the mixture's own 5 dB to the 20 dB ceiling the other SI-SDR rows use.
+It belongs to the removes part: the task contract makes the competing talker noise to remove.
+`scripts/leaderboard.py --outside-out <file> --axis-tables voices` writes the axis alone, in its own order.
+
+### Real rooms
+
+The room axis: speech recorded in real rooms, scored against the dry voice by speaker similarity and predicted quality.
+A system that removes the room scores high; one that leaves it as recorded, or does worse than the recording, scores zero: a zero is not by itself a passthrough.
+The axis is the restores part on its own: it is the restoration score.
+
+`scripts/leaderboard.py --outside-out <file> --axis-tables room` writes the axis alone, in its own order.
+
+### Streaming probe
+
+The `streaming probe` column is read from a probe, not from a model's description, so it measures the inference path a system actually ships, whatever its description says.
+The probe takes every paired 45 s item of the set and cuts four inputs from each: the fifteen seconds from 28.8 to 43.8 s with the 3.2 s before them as a lead-in, on their own, and the same cut whose audio from a splice point on is another recording, at three splice points.
+The cut starts on a 3.2 s grid, a multiple of every common frame hop, so the fresh render's frames fall where the whole render's did and the two differ by context alone; the lead-in lets a model's state warm up before the measured stretch.
+The splice points are not round numbers, so a processor that works on independent blocks of some common length cannot be lucky on every splice.
+Look-ahead is how far before a splice the two outputs already differ, at its worst over the three splices: a causal system reads its frame and look-ahead, an offline one reaches the start of the cut and is shown as at least that.
+Drift compares the published render of the whole item, on the fifteen seconds, with the render of the cut: a model that carries state should give the same answer after 28.8 s of context as after 3.2 s, and the SI-SDR difference against the reference says whether it did.
+Dropped speech counts the seconds where the reference speaks, the whole render sits 20 dB or more under it and the fresh render keeps it within 3 dB: speech the long context cost, not speech the system loses either way.
+Yes needs all of it on the complete inventory of long items: a look-ahead of at most 100 ms on every item, a drift of at least −1 dB on average with no item under −5 dB, and no dropped second.
+The scorer (`scripts/scorestream.py`) records every item's look-ahead, drift and dropped seconds under its own rule, which fixes how renders are read; the board (`scripts/streamview.py`) judges those measurements with the limits declared here, so a limit can move without reading a render again and every system is judged alike.
+The thresholds are a screening policy, stated here, not a measure of delivery or throughput.
+Reported beside the verdict and not gated: the cold start, how the first second of the cut compares with the same second inside the whole render (negative when the fresh start is worse; for a streaming model it reads its fresh state, for an offline one the edge of its input); and, for a release whose inference path depends on the input's length (a mark on the drift), that the whole item and the cut took different paths, so that difference includes the change of path.
+The probe renders must come from the environment that rendered the board and from these probe inputs (a wrapper's receipts carry the digest the stamp records and a marker names the probe), every output must be exactly its input's length, and the whole render must be the audio that was scored; the leaderboard shows no verdict whose probe rule, scorer or render has since changed.
+
+`scripts/leaderboard.py --streaming-out <file>` writes these measurements for every ranked system.
+A † on the drift marks a release that takes different inference paths for the whole item and the cut (whole-file inference up to a length, segmented beyond), so that difference includes the change of path.
+
+### How much of the order is policy
+
+`scripts/anchorsweep.py --results <results> --markdown-out <file>` measures it on the full-band tier.
+It draws every declared anchor constant inside its stated range (2000 seeded draws) and reports each system's denoising score between the 5th and 95th percentile and how often it ranks first, above the next system or tied with it; the raw measurements are the same in every draw, only the scale moves.
+It then names every single constant whose range alone reverses a pair the declared board separates by more than the tie band of 0.03.
+The other policy choice is how the axes combine; for it the sweep gives the order with one axis left out and how often each system ranks first when the weights of the axes are drawn uniformly at random.
+
+## Task contracts
+
+The set asks three different things, and a score is only meaningful under the contract it was measured against (`scripts/contracts.py` states them and what the axes may score; the leaderboard refuses any other row):
+
+- **Denoise** (every row of the denoising board, and every condition not named below): the voice as recorded stays, its laughs, breaths and sighs with it, at its level, in
+ its band and with its own room; everything that is not that voice goes, including noise that
+ shares the voice's room and microphone (`coroom@*`, whose reference is the voice after both) and a
+ competing talker (`talker@*`: the voice the recording is of stays, the other voice goes). `srsweep_*` belongs
+ here: mixture and reference are band-limited identically, so the band the input lacks is not
+ the system's to invent. A system that puts more than 10 dB more energy above the input's band
+ than inside it, each against the reference band-limited the same way, restores, which this
+ contract counts as invention: the restoration board ranks it, not the denoising board.
+ Crowd chatter is read over the whole item at the voice's scale (the chatter left at each babble
+ level, SI-SDR), so chatter under the speaker's own voice does move those rows; what no row
+ separates is the chatter under speech from the chatter in the pauses and from distortion, so a
+ difference in one of them is diluted across the denoising score. The competing talker itself is the
+ **voices** axis of the removes part ([Competing voices](#competing-voices-the-voices-axis)).
+- **Voice policy** (`singer@{-2,-5}`, `conversation@0`, `long@+4`, `music_vocal@{-6,+6}`; diagnostics
+ outside both boards): which voices are content. The boards' own answer is the denoise contract
+ above. These rows score the alternative policies: a singer who is the target stays, a song's own singer
+ behind speech goes, both sides of a conversation stay, and so do the several talkers of a long item,
+ who take turns. For a system that keeps one speaker, `conversation@0` and `long@+4` read how much of
+ the other voices went, by design, not a failure. `long@+4` also feeds the streaming probe, which
+ compares a system with itself.
+- **Restoration** (`reverb_real`, the room axis; `reverb_synth`, diagnostic): the reference is
+ better than the voice in the input, the dry voice out of a reverberant one. The room axis is
+ the restoration board and nothing else is: a system that only removes what was added scores
+ low there and keeps its denoising score. The band a narrow input lacks is shown beside
+ both scores (`band`) and included in neither, since energy above the band is addition, not yet
+ restoration.
+
+## The conditions
+
+The set's conditions (`family@SNR`), the reference each is scored against and what it catches:
+
+| family / condition | reference | what it catches |
+|---|---|---|
+| `babble@{+10,+4,0,-5,-10}` | paired clean | café, bar, market and street chatter; at −5 and −10 dB the crowd is above the voice |
+| `ambience@{-10,-5,0,+5}` | paired clean | street, transit, office, home and nature ambiences |
+| `events@{+5,-5}` | paired clean | sirens, horns, impacts, dogs: transients under, then over, the speech |
+| `wind@{0,+5}` | paired clean | real phone-recorded wind |
+| `stationary@{-10,-5,0,+5}` | paired clean | electrical hiss, mains hum, tonal whines, click bursts |
+| `traffic@{-10,-5,0,+5}` | paired clean | road, rail and air traffic |
+| `rain@0`, `water@0`, `animals@{0,+5}` | paired clean | rain and thunder; running water; birds, insects, dogs, farm animals |
+| `appliance@{0,+5}`, `tools@+5` | paired clean | fans, kitchen machines, keyboards, clocks; drills, saws, mowers |
+| `household@{0,+5}` | paired clean | sparse one-shots (cans, sprays, dusters): impulsive noise between words |
+| `nonverbal@0`, `nonverbal_clean` | paired clean | laughs, breaths, sighs and coughs: the voice outside speech, which a detector of speech never offers to a scorer |
+| `music@-6` | paired clean | instrumental bed louder than the voice |
+| `music_vocal@{-6,+6}` | paired clean | a song with its own singer behind speech; a diagnostic stress test outside both scores |
+| `singer@{-2,-5}` | singing target | a cappella solo singing over a bed: singing is content, kept |
+| `cheer@+5`, `cheer_tail` | paired / tapered | crowd cheering, including 1.5 s after the last word |
+| `expressive_tail@-5` | tapered clean | trailing-off speech; scored over the −18 dB taper and the 1.5 s tail after it |
+| `reverb_real`, `reverb_synth` | **dry** clean | measured responses of real rooms (the room axis) and a synthetic room (diagnostic) |
+| `clean` | itself | passthrough damage |
+| `srsweep_{8k..48k}` | band-limited clean | input-rate robustness; mix and reference limited identically |
+| `conversation@0` | both voices | a real two-party conversation, consecutive turns of one recording, both kept |
+| `quiet@-30dBFS` | paired clean | level conditioning on a very quiet input |
+| `long@+4` | paired clean | 45 s items with several talkers and changing ambience: chunk stitching |
+| `soft@{+5,0,-5}` | the soft take | softly spoken studio takes, quiet delivery with normal phonation, under electrical hiss or airflow; like the wild rows, the reference carries its own floor, so the items are scored for retention only and sit outside both scores |
+| `whisper@{+5,0}` | the whispered take | whispered speech, unvoiced and breathy, under electrical hiss or airflow: the case where the voice itself is noise-like; scored for retention only, outside both scores |
+| `wild@{-10,-5,0,+5}` | the wild recording | speech recorded in the wild (phone and laptop microphones, rooms, compression, its own floor) under a continuous real-world bed; scored for the voice coherent with the recording, speaker similarity and the energy removed where the recording holds no speech, never SI-SDR; outside both scores |
+| `babble@+20`, `ambience@+20`, `nonverbal@+20` | paired clean | the mildest rungs: a bed well under the voice, where a system must leave the voice alone and still take the little there is |
+| `everyday@{+10,+20}` | paired clean | everyday speech with 1 to 2.5 s pauses inside it, over electrical, appliance, street, traffic, distant-chatter and household beds: what a system leaves in a pause while the voice is quiet, with the pause intervals known |
+| `talker@+5` | paired clean | one other voice behind the target, 5 dB under it, band-limited and in a room: the words that leak from a television, a radio or a colleague |
+| `transition@+10` | paired clean | a bed that starts or stops at a word gap in the middle of the item: adaptation and the burst of leak after a change |
+| `noise_only` | none | a bed with no speech at all: every word a recognizer returns is invented, every second of voice-like output is as well |
+| `coroom@{pause,speech,floor,both}` | paired, the voice after the same room and microphone | noise in the voice's own room, simulated rather than recorded together: generated household one-shots as the events and mostly recorded floors, rendered through the voice's room and microphone; a quiet floor at the level of a recording's own (−50 to −65 dBFS) and isolated transient events (household one-shots) in the pauses and under the speech, through the voice's own room (two positions of one measured hall receiver, or a synthetic small room) and one microphone coloration; every event span, pause and floor level labeled |
+| `real_*` | none | reference-free real recordings: our own, voice actors, in-the-wild media and field recordings in seven of the set's languages, read speech in the wild across 43 further languages, and everyday recordings with pauses in more than a hundred languages (`real_everyday`) |
+
+## Metrics
+
+- Conventions the scorer undoes before anything is read, because nobody can hear them: a delay of
+ up to 100 ms and a flipped polarity (`lag_median`, `n_polarity_flipped` report them), and a
+ system's overall gain of up to 12 dB (`_level_cal_db`, the median output-over-input level of
+ the `clean` items). The gain is scored once, as the level change on clean speech, and undone
+ everywhere else: in the kept energy and the lost blocks, in the suppression of a competing
+ voice and of non-voiced sound, in the high-band error and in the deletion rule
+ (`scripts/levels.py`). The bound matters: an output that is silent on clean speech cannot
+ calibrate its deleted voice back.
+ [CONTROLS.md](CONTROLS.md) feeds the scorer known damage and known non-damage and shows what
+ every metric says about each, including what none of them sees.
+- `pause_level_db`, `pause_resid_db` (`scoreresidual.py`, on the real recordings of every `real_*`
+ family with at least 0.4 s of pause): what a system leaves in the input's own pauses, read at 48 kHz
+ in one-third-octave bands weighted for audibility, with the output's delay and polarity undone and
+ the first and last 300 ms of the item and 100/200 ms around every word left out. The level row reads
+ it against the output's own voice, held within ±20 dB of the input's own pause level and capped at
+ −45 dB where it is taken as inaudible, and feeds the cleanup axis;
+ the reduction row reads it against what the recording held, each item's own gain undone, and is
+ reported beside it. `babble_resid_db` (the same sidecar, on the crowd-chatter rows): the energy of
+ the output that no scaling of the clean voice explains, at the voice's own scale, over the chatter
+ the mixture held; interference and distortion together, so a quieter output earns nothing and loses
+ nothing, and a vanished voice reads the worst value. Every item is held inside ±20 dB before
+ pooling, so a few silenced pauses cannot carry an axis.
+- `event_resid_db`, `floor_resid_db`, `voice_level_db` (`scoreevents.py`, on the same-room block).
+ Each system renders the block twice, from the mixture and from the reference (the block's
+ references are linked under `pair_coroom/in` beside the renders by `scoreevents.py --pair` and
+ rendered the way the streaming probe is, in the environment that rendered the board). What the
+ noise did to the output is the difference between the two renders, so neither row penalizes
+ what a system does to the voice's own room.
+ - `event_resid_db`, `floor_resid_db`: the energy of that difference over the energy the mixture
+ added, in dB; the event row on each labeled event span plus 150 ms of the room's decay, the
+ floor row on the labeled pauses outside the events. Every event is bounded before the item's
+ mean.
+ - `voice_level_db`: the voice's level on the reference's loudest fifth of speech frames, the
+ lower of two comparisons: the mixture's render against the reference's render (what the noise
+ costs the voice), and against the reference with the room's measured share allowed
+ (`room_share_db` in the item's provenance: the room-free voice, level-matched, placed at the
+ direct sound's arrival where a system that removes the room renders it). A system that turns
+ the voice down, with or without the noise, is penalized; one that removes the room is not.
+ - On both renders the system's delay and base gain are undone, a silent render takes the bound,
+ and every item is held inside ±20 dB (the unbounded means stand beside the residual rows as
+ `*_raw_db`).
+
+ The event rows feed the events axis, the floor rows the cleanup axis and the voice level the
+ preservation axis. The same sidecar reports, beside the board, the transients the shared
+ detector finds in the real recordings outside speech (`_real_events`), a diagnostic because
+ most of them are the speaker's own sounds.
+- `si_sdr`: scale-invariant SDR against the reference.
+- `kept_coh_mean`, `kept_coh_p10`: the voice kept, per 100 ms block over the reference's speech
+ blocks (a voice-activity mask, so quiet speech counts), as the output's projection on the
+ reference. An added bed projects to nothing, so returning the background cannot pass as kept
+ speech, and a deleted quiet phrase shows as a large negative 10th percentile.
+ `kept_coh_lost_pct` is the share of those blocks kept below −10 dB: a percentile cannot see one
+ dropped syllable, a count of lost blocks can (reported, outside both scores). `kept_mean`,
+ `kept_p10` are the plain energy ratios, reported beside them.
+- `nv_lost_pct`, `nv_events_lost_pct` (`scorekept.py`, on the recordings of laughs, breaths and
+ sighs): the voice outside speech. The blocks are those of the clean recording that hold sound
+ (within 30 dB of its loudest block), that the voice-activity detector does not call speech,
+ and that the bed does not bury (the voice of the block no more than 10 dB under the bed of the
+ block). A block is lost by the rule of a speech block. The first is the share of blocks lost,
+ pooled over the condition, and feeds the keep axis under a bed and the fidelity axis on clean
+ recordings; the second reads runs of consecutive blocks as whole events and is reported beside
+ it. The recordings are few and in English: 48 per condition, of which only those holding a
+ block the rule can read observe the row (under the bed, fewer than half; a row needs 20).
+- `spk_sim`: WavLM-SV cosine similarity to the reference. The timbre axis is its mean over
+ twelve noise families, each at the level where the unprocessed mixture reads about 0.95
+ (crowd chatter at +4 dB; ambience, events, cheering, stationary noise, appliances and tools at
+ +5 dB; wind, traffic, household one-shots, animals and rain at 0 dB). Running water, mixed at
+ 0 dB only, leaves the mixture far under that scale and stays out.
+- Room: on the recordings in real rooms, `spk_sim` and NISQA against the dry voice, from what
+ the recording in its room reads to the dry reference's own.
+- Streaming probe (`scorestream.py`, outside both scores): `look_ahead_ms`, the time before a
+ splice in the input at which the output already differs (the first 10 ms block whose difference
+ rises 60 dB above the output's floor), at its worst over three splices per item; `drift_db`,
+ the SI-SDR of fifteen seconds of a 45 s item rendered whole minus the same stretch rendered
+ from a cut with a 3.2 s lead-in, frames aligned; `dropped_seconds`, seconds of speech the whole
+ render loses (20 dB or more under the reference) that the fresh render keeps (within 3 dB);
+ `cold_start_db`, the first second of the cut against the same second inside the whole render.
+ All are read on every 45 s item; the verdict is yes or no, never a score.
+- `band_kept_db`: per-band output/reference energy over speech-active frames for 0–0.5, 0.5–2,
+ 2–4, 4–8, 8–12, 12–16 and 16–24 kHz; 0 dB preserved, negative dulled, positive invented.
+- Fidelity is scored on `clean`, where there is nothing to remove, as harm someone could notice:
+ the quiet tenth of the voice (`kept_coh_p10`), the level change (`level_err_db`, the absolute
+ change per item, averaged), the error over 8–24 kHz (`hf_err_db`: per item, the mean absolute
+ band error once the gain is undone, then averaged, so invented high band costs as much as lost
+ high band and a dull item cannot cancel a bright one), `spk_sim` and NISQA, each
+ against the untouched recording and each saturating where differences stop being audible; the
+ spectrum (`mag_snr`, the signal-to-error ratio of the magnitude spectrogram after the best
+ single gain, which does not read phase, from 10 to 30 dB); and the vocal sounds outside speech
+ lost on clean recordings.
+ Clean `si_sdr` is reported but not scored: it measures identity of the waveform, and a system
+ that re-synthesizes a waveform its listener could not tell apart reads about 26 dB
+ (`CONTROLS.md`) while the recognizers and quality predictors find nothing wrong and a listener
+ hears no difference. The magnitude ratio
+ saturates under what that re-synthesis reads, so it does not bring the objection back.
+- `babble_supp_db`: energy of the residual (the output with its gain undone, minus the
+ reference) over the residual the input started with, per item, averaged in dB; 0 dB is a
+ passthrough, −10 dB ten decibels of din gone, positive an output further from clean than the
+ input was. The ratio with the gain left in stays beside it (`babble_supp_raw_db`): a system
+ that only turns everything down would read as suppression there and does not here.
+- `nisqa_*`: NISQA v2 no-reference quality. Never read it alone: it rewards a clean-sounding
+ rewrite even when the speaker is gone.
+- Real recordings: `deleted_rate_pct` (VAD speech segments that collapse by more than 10 dB once
+ the system's gain is undone, pooled over the real conditions and primary-speaker-anchored by
+ `scorerealx.py`, so a removed background voice is not charged as a deletion),
+ `speech_rms_delta_db`, `nonvoiced_supp_db` (the output's energy over the input's on the 20 ms
+ frames at least 40 ms clear of the detected speech whose input is above −80 dBFS at the 16 kHz reading, the output's
+ delay undone; gain undone; `nonvoiced_supp_raw_db` beside it),
+ `dnsmos_ovr`.
+
+Three corrections keep heterogeneous systems comparable, all reported: **level calibration** (the median output/input RMS over `clean`, undone in every kept, suppression, high-band and deletion reading, so an output gain can pose neither as preservation nor as suppression); **delay alignment** (best lag within ±100 ms before every reference metric); and a **band-limited twin** of every reference metric with both sides round-tripped through 16 kHz (`*_nb`), on which 16 kHz-native systems are ranked in their own tier.
+
+- Diagnostic, on the real recordings: NISQA on the primary speaker's segments alone (`nisqa_mos_primary` in the NISQA sidecar), each segment of two seconds or more scored on its own and the item read as their duration-weighted mean, with the eligible duration and its share of the primary speaker's speech. The segment boundaries are the input's, from the deletion sidecar, applied identically to every output: an output never chooses the segments it is judged on. The quality axis reads the whole-clip value; this per-segment reading is reported beside it.
+
+## Downstream ASR
+
+The value of isolation to a listener is hard to put in one number; the value to a recognizer is not.
+`scripts/scoreasr.py` transcribes every system's output of the conditions below with a popular open recognizer (Whisper large-v3 through faster-whisper, beam 5; Whisper small as a less robust second; the Inworld speech-to-text API as a hosted third) and scores the transcript against the item's golden text.
+Golden texts are part of the set (`transcripts.jsonl`), one per target utterance: the corpus transcript confirmed word for word against the audio by Gemini 3.1 Pro (tier `corpus-verified`), or, where the source came with none, Gemini's verbatim transcript where Whisper large-v3 independently agrees within 10 % (tier `recognisers-agree`).
+For the few recordings no second source confirms (proper nouns, numbers, a romanized corpus text, a whisper the recognizer misheard), Gemini's transcript, checked by ear, is kept as tier `gemini-accepted`; a text a person edits by ear is kept as `human-verified`.
+Where the audio is in another language than the item's label says, the row names the one `spoken`, and the item is decoded and normalized in it (the manifest is part of the set's identity and stays as built).
+An item without a golden text falls back to the recognizer's own transcript of the clean reference, and every sidecar records how many items each condition scored that way.
+The `wild` rows are scored that way throughout: spontaneous speech, with its fillers, false starts and clipped words, has no single verbatim text two transcribers agree on, so those rows measure what a system changes in the recognizer's reading of the recording, not its distance from a transcript.
+Both sides go through Whisper's text normalizer (the English one for English, the basic one otherwise); Chinese, Cantonese and Japanese are scored per character (a recognizer with no Cantonese model decodes it as written Chinese).
+The ASR table is generated by `scripts/asrtable.py` from the sidecars; its last column is the offline Inworld Voice Isolator's change in error rate against the unprocessed input, in % of the input's.
+Read it as where a front end helps or hurts a recognizer, not as a ranking: a robust recognizer needs little help above 0 dB, and every system that removes sound can remove words.
+The same sidecars hold Whisper small (`--asr small`), which is less robust and gains more from every front end, and the Inworld recognizer (`--asr inworld/inworld-stt-1`, `INWORLD_API_KEY`).
+
+The ASR table reports the error rate (%) of a recognizer's transcripts per condition, pooled, with the 95 % interval half-width; lower is better.
+
+### Under a competing voice
+
+Two things a recognizer can ask of an isolator when another voice is in the room, kept apart because they are opposite contracts: remove the chatter behind the speaker, or keep both sides of a conversation.
+For a system that keeps one speaker, the conversation slice reads the cost of that choice.
+
+`scripts/asrtable.py` writes the slices beside its main table: error rates pooled over each slice's items, one row per recognizer and unit, and the paired change against the unprocessed input with a 95 % interval that resamples the recordings and beds behind the items; a unit with fewer than 20 items in a slice is not shown.
+
+### Content preservation
+
+The preservation axis's retention metric (`kept_coh_p10`, which fidelity reads on `clean` too) reads 100 ms blocks through a percentile, and [CONTROLS.md](CONTROLS.md) shows what that cannot see: one dropped consonant, syllable or short word.
+`scripts/scorecontent.py` is an ASR-based content diagnostic.
+One recognizer (Whisper large-v3) transcribes every system's output, the transcript is aligned word by word to the item's verified transcript, and each reference word is counted as kept, substituted or deleted, with insertions counted separately, by kind of word: numbers, short words (three letters or fewer), consonant-final words and the rest.
+The panel is every English item of the scored conditions with a verified transcript (the corpus text confirmed against the audio by a language model, or the model's own transcript accepted by ear; the caption gives the counts), so the reference is never a recognizer's unchecked guess, and every rate is read next to the unprocessed input's. The change column's interval resamples the recordings and beds behind the items; where it includes zero, the change is a favorable or unfavorable point estimate, not a resolved difference, and most rows are of that kind.
+The `ctl_*` rows are the metric controls rendered onto the same panel (`--controls`): the reference untouched, with 20 to 320 ms of speech removed, re-synthesized, and with its top octave replaced by noise, so the table says what the check itself can and cannot see.
+It cannot see a dropout under about 320 ms: a strong recognizer restores the word from context, which is why the block-level blind spot in CONTROLS.md still needs a signal-level, word-timed metric.
+
+`scripts/scorecontent.py --markdown-out <file>` writes the table: words lost per hundred reference words of each kind, substitutions and insertions overall, and each system's change in deletions against the unprocessed input with a 95 % interval that resamples the recordings and beds behind the items.
+
+## How a score is bound to what was rendered
+
+Every rendering process writes a receipt beside its outputs before it renders (`wrappers/receipt.py`): the renderer's code and the package's, the weights, the installed packages, the device, the arguments and the inputs it renders.
+The score files carry that identity and a digest of the outputs' bytes.
+A system's probe and same-room pair renders must come from the environment that rendered its board row: the scorers refuse receipts of another one.
+The scorers fingerprint their own code through its syntax tree (`observations.code_digest`), and `leaderboard.py` refuses to mix score files of different scorers, anchor versions or builds of the set.
+
+`controls.py` scores synthetic systems built from the paired audio of a fixed slice (the reference untouched, louder, late, upside down, re-synthesized, with 20 to 320 ms removed, with its top octave cut or invented, silence, the bed alone) through the same scorer as a real system, holds every one to a declared expectation and writes [CONTROLS.md](CONTROLS.md).
diff --git a/bench/PROTOCOL.md b/bench/PROTOCOL.md
new file mode 100644
index 0000000..0d26d7f
--- /dev/null
+++ b/bench/PROTOCOL.md
@@ -0,0 +1,67 @@
+# How scores are scaled
+
+A composite, a system's score on the board that ranks it, is identified by its board, set ID, subset, anchor definition and resolved-calibration digests, and axis-membership version.
+Compare composites only within that identity.
+Adding or removing competitors cannot change another system's composite.
+The 0.03 tie band of the composite and the tie band an axis declares (timbre: 0.05) remain display conventions; they are not confidence intervals.
+
+## Fixed anchors
+
+`anchors.json` declares raw-unit floors, ceilings and rationales.
+Each sub-metric is `clip((value - floor) / (ceiling - floor), 0, 1)`.
+Lower-is-better metrics have decreasing endpoints.
+Average sub-metrics within an axis, axes within a part, and the parts equally.
+`axes.json` defines three things:
+
+- the four parts: what a system removes (suppression, music, cleanup, events, voices), keeps (preservation, fidelity), how the result sounds (timbre, quality) and what it restores (room);
+- the boards, published side by side, each the mean of the parts it names and together naming every part exactly once (denoising = removes + keeps + sounds; restoration = restores); the first board orders the table;
+- the axes scored and published beside the boards but included in neither (band).
+
+A registry without parts averages its axes equally; one without boards publishes that composite alone.
+The `*` after a system's name (the streaming probe) is not an axis and takes no weight: it is a yes or no read from a probe (`scorestream.py`: the future input the output depends on, and the drift over a long input), published beside the score as a screening, not a measure of delivery or throughput.
+
+| Measurement | Floor → ceiling | Verified against |
+|---|---|---|
+| Babble suppression | 0 → −20 dB | INPUT reads 0 |
+| Noisy SI-SDR | the nominal SNR (−5 or −6 dB) → +20 dB | INPUT reads the SNR |
+| Primary speech deletion | 5% → 0% | |
+| Quiet coherent voice retention | −10 → 0 dB | |
+| Speaker similarity, at the moderate level of each of twelve noise families | 0.95 → 1.0 | INPUT (REF under crowd chatter) |
+| Vocal sounds outside speech, lost | 30% → 0% | INPUT reads 0 |
+| Clean speech: quiet coherent voice retention | −10 → 0 dB | INPUT reads 0 |
+| Clean speech: level change | 6 → 1 dB | |
+| Clean speech: high-band error | 3 → 0.5 dB | |
+| Clean speech: speaker similarity | 0.95 → 1.0 | INPUT reads 1 |
+| Clean speech: predicted quality | 4.0 → 4.5 MOS | INPUT |
+| Clean speech: magnitude signal-to-error ratio | 10 → 30 dB | |
+| Real room: speaker similarity to the dry voice | 0.86 → 1.0 | INPUT |
+| Real room: predicted quality | 2.0 → 4.5 MOS | INPUT |
+| Paired quality | 2.0 → 4.5 MOS | INPUT, REF |
+| Reference-free quality | 2.4 → 5 MOS | INPUT |
+
+Every endpoint is a declared constant, so one raw value maps to one score on every build and view of the set.
+Where an endpoint stands for something the set can measure (the unprocessed input, the clean reference), freezing a calibration checks the measurement against the declared value within a stated tolerance and fails otherwise: a build that drifts needs a new anchor version, never a silently moved scale.
+Scores from different builds still differ because their audio differs; the scale does not.
+
+These constants express scoring policy, not demonstrated thresholds of audibility.
+INPUT is zero only on INPUT-anchored rows; REF is one only on REF-anchored rows.
+Neither has a meaningful ideal composite across all tasks.
+Predicted quality can exceed the recording's quality and saturates at one.
+Raw metrics remain available alongside the normalized axes.
+
+`REF` renders clean references only.
+Real recordings have no fabricated reference.
+Freeze one `anchors.resolved.json` per set/subset; INPUT and REF supply the verification measurements.
+Its deletion cohort is the INPUT-defined primary segment inventory.
+Every ranked system must cover that complete cohort with the same segment denominators; missing data invalidates that system, without shrinking anyone else's cohort.
+A missing/nonfinite measured anchor is an error.
+Declared fallbacks apply only to measured but degenerate gaps.
+
+A score file holds raw measurements; the anchor policy only scales them.
+A change of policy re-stamps the score files and resolves a new calibration; it never re-scores.
+
+The declared constants are policy, and each carries the range it could plausibly take.
+How much of the order depends on these constants is measured in [METRICS.md](METRICS.md#how-much-of-the-order-is-policy).
+
+Scores stamped with another anchor version are refused.
+A changed constant needs a new anchor version and changelog.
diff --git a/bench/README.md b/bench/README.md
new file mode 100644
index 0000000..a44ac69
--- /dev/null
+++ b/bench/README.md
@@ -0,0 +1,117 @@
+# Inworld VIBE: Voice Isolation Benchmark and Evals
+
+VIBE measures how well a system takes one voice out of a noisy recording.
+It ranks systems on two boards:
+
+- **Denoising**: remove everything that is not the voice, and keep the voice exactly as it was recorded.
+- **Restoration**: give back the dry voice of a speaker recorded in a reverberant room.
+
+Everything is scored at 48 kHz over the full band, with one implementation of every metric for every system, on recordings screened against our model's training data by recording; a few items share a speaker with it ([The eval set](#the-eval-set)).
+
+Read the boards with three facts in mind:
+
+- Inworld maintains both the benchmark and one of the models on it, and chose that model's checkpoints with these scores in view. The other systems run from their upstream releases and were not tuned on the benchmark.
+- Inworld scores every system itself, on an internal evaluation set that is not distributed.
+- The two scores measure the two tasks declared here, not speech enhancement in general.
+
+## Leaderboard
+
+<p align="center">
+ <picture>
+ <source media="(prefers-color-scheme: dark)" srcset="../docs/assets/board-dark.svg">
+ <img src="../docs/assets/board-light.svg" alt="Inworld VIBE full-band tier: denoising score per system" width="100%">
+ </picture>
+</p>
+<p align="center">
+ <picture>
+ <source media="(prefers-color-scheme: dark)" srcset="../docs/assets/board-restoration-dark.svg">
+ <img src="../docs/assets/board-restoration-light.svg" alt="Inworld VIBE full-band tier: restoration score per system" width="100%">
+ </picture>
+</p>
+
+- `*` marks a streaming system: it looks at most 100 ms ahead and holds its quality through a long recording, within 1 dB of the same stretch started fresh ([streaming probe](METRICS.md#streaming-probe)).
+- The charts show the full-band tier: systems that run at 48 kHz or 44.1 kHz. A 16 kHz tier, scored inside 0–8 kHz and not comparable with these charts, has no entrant on this build of the set.
+- The unprocessed input and Demucs vocals (a music-separation reference) are scored as reference rows and not ranked.
+- The charts come from Inworld's score files on build `f5a6420d67b7ef45…` of the set, ranked by `scripts/leaderboard.py`.
+
+## What the scores mean
+
+A system that adds sound above the band of a band-limited input (more than 10 dB more energy above that band than inside it) is ranked on restoration; every other system is ranked on denoising.
+Every system is scored on both.
+
+The scores are built from ten axes in four parts:
+
+| Part | Axis | What it checks |
+|---|---|---|
+| Removes | suppression (`supp`) | crowd chatter, and ambience, steady noise and traffic louder than the voice |
+| | `music` | an instrumental music bed louder than the voice |
+| | `cleanup` | what is left in the pauses of real recordings, and the noise floor of the voice's own room |
+| | `events` | sudden sounds in the voice's own room, in the pauses and under the speech |
+| | `voices` | a competing talker 5 dB under the speaker |
+| Keeps | preservation (`pres`) | the voice kept whole: no speech deleted from real recordings, quiet speech kept under chatter, laughs and breaths kept under noise, the voice's level held |
+| | fidelity (`fidel`) | clean speech left alone: its quiet parts, level, high band, speaker, quality, spectrum, laughs and breaths |
+| Sounds | `timbre` | the speaker still sounds like themselves, over twelve kinds of noise |
+| | quality (`qual`) | predicted listening quality (NISQA), under chatter and on real recordings |
+| Restores | `room` | the dry voice out of speech recorded in real rooms |
+
+- Denoising is the average of the first three parts. Restoration is the fourth part alone.
+- Each axis is the average of its rows and each part the average of its axes, so an axis added on one side takes no weight from another.
+- Every measurement sits on a 0–1 scale with fixed ends: 0 is the unprocessed input or a declared constant, 1 is the clean reference or a declared constant ([anchors.json](anchors.json), [PROTOCOL.md](PROTOCOL.md)). The ends belong to the set, not to the other systems, so adding or removing a system never moves another system's score.
+- Gaps under 0.03 on either score are ties, and so are timbre gaps under 0.05. These are reporting rules, not statistical confidence intervals.
+- A system that leaves the room as recorded scores zero on `room`, because that task asks for the dry voice.
+- A system that keeps every voice scores near zero on `voices`, because these boards count a competing talker as noise.
+- `band`, the sound a system adds above a band-limited input's band, is shown beside both scores and counts in neither: it measures added energy, not restored speech, and a tone added there would score on it.
+
+[METRICS.md](METRICS.md) defines every metric and shows the other views: the multilingual core, real rooms, the streaming probe, how much of the order is policy, and downstream speech recognition.
+
+### Task contracts
+
+Each condition of the set asks one of three things, and a score is only meaningful under the contract it was measured against ([`scripts/contracts.py`](scripts/contracts.py) states them, [METRICS.md](METRICS.md#task-contracts) gives the full rules):
+
+- **Denoise**, every condition not named below: keep the voice as it was recorded, at its level, in its band and in its own room, with its laughs, breaths and sighs. Remove everything else, including a competing talker and noise in the voice's own room. On the band-limited rows (`srsweep_*`), the band the input lacks is not the system's to invent.
+- **Voice policy** (`singer`, `conversation`, `long`, `music_vocal`): which voices are content. A singer who is the target stays, a song's own singer behind speech goes, and both sides of a conversation stay. These rows are shown beside the boards, not in them: a system that keeps only one speaker removes the other voices by design, which is not a failure.
+- **Restoration** (`reverb_real`, `reverb_synth`): the reference is the dry voice, better than the voice in the input. `reverb_real` is the room axis, the restoration score; `reverb_synth` is a diagnostic.
+
+## The eval set
+
+- 5,502 items over 77 conditions: 4,898 paired items in 13 languages, 96 noise beds with no speech at all, and 508 real recordings in 128 languages.
+- Most items are one whole utterance that ends naturally, three to twenty seconds long with room around it; the long items run 45 seconds.
+- A paired item comes with a clean full-band reference: speech at a normal level, well above its own noise floor. The mix and the reference share one gain, so the SNR label is exact.
+- 36 items are of speakers who have, or may have, other recordings in the Inworld model's training data.
+- Every build of the set has an id computed over its files and labels, so a changed crop or label makes a different set. The boards are scored on build `f5a6420d67b7ef45…`, and `scripts/validateset.py --full` re-checks a build.
+
+[METRICS.md](METRICS.md#the-conditions) lists the conditions, what each one catches, and the multilingual core.
+
+## How the numbers are produced
+
+Inworld renders and scores every system, its own included, with the scripts in this directory.
+Each external system runs from its upstream release at a pinned revision, in its own environment (`scripts/setupfield.sh`, `scripts/runfield.sh`), and `wrappers/meta/<system>.json` says how it was run.
+Every score file records the build of the set it was scored on, and the leaderboard refuses to rank results from different builds.
+`scripts/leaderboard.py --results <results>` prints both boards with every axis from a directory of score files.
+
+This directory holds the method, not the data: every scorer, the anchors ([anchors.json](anchors.json)), the axes ([axes.json](axes.json)) and each system's wrapper.
+The eval set and the score files are not distributed, so the boards cannot be recomputed outside Inworld.
+How a score is tied to the exact audio it rated, and what each metric can and cannot see, is in [METRICS.md](METRICS.md#how-a-score-is-bound-to-what-was-rendered).
+
+## Adding a system
+
+Write a wrapper that follows [WRAPPER_CONTRACT.md](WRAPPER_CONTRACT.md) and open a pull request with it; Inworld renders and scores it.
+
+## Licenses of the systems compared
+
+As each system's description states them (`wrappers/meta/<system>.json`); check upstream before building on any of them.
+
+| System | License |
+|---|---|
+| ClearerVoice-Studio | Apache-2.0 code and weights |
+| DeepFilterNet3 | MIT or Apache-2.0 |
+| FastEnhancer-L | MIT |
+| GAP-URGENet | MIT code, Apache-2.0 weights |
+| UniPASE | MIT code, Apache-2.0 weights |
+| Smule Renaissance Small | MIT code and weights |
+| NVIDIA NemotronLabs RE-USE and RE-USE-laughter | OpenMDW-1.1 code and weights |
+| URGENT 2026 baselines | Apache-2.0 code; checkpoints from the organizers' release, which states no license |
+| resemble-enhance | MIT code; weights without a stated license |
+| Demucs (the reference row) | MIT |
+
+Nothing third-party is redistributed here: `scripts/setupfield.sh` fetches each system from its source at a pinned revision.
diff --git a/bench/WRAPPER_CONTRACT.md b/bench/WRAPPER_CONTRACT.md
new file mode 100644
index 0000000..06eddcb
--- /dev/null
+++ b/bench/WRAPPER_CONTRACT.md
@@ -0,0 +1,122 @@
+# Wrapper contract (Inworld VIBE)
+
+Every external system is integrated the same way so the leaderboard is fair and re-runnable.
+Follow this exactly when adding a system.
+
+## 1. Own venv, on-demand download
+
+Never install a competitor into the benchmark's own environment, and never commit third-party code or weights to this repository.
+Add an install recipe to `scripts/setupfield.sh` (one venv under `$BENCH_VENVS/<name>_venv`, clones under `$BENCH_SRC/<name>`), so anyone can reproduce the field from upstream sources under their original licenses.
+
+## 2. Wrapper script
+
+Path: `wrappers/run<name>.py`, invoked as
+
+```
+<venv>/bin/python run<name>.py --in-dir IN --out-dir OUT [--limit N] [--shard i/k] [--device cuda:0]
+```
+
+Build it on `wrappers/writer.py`, the loop every wrapper shares: `writer.inputs(in_dir, shard, limit)` lists the files one process renders, and `writer.render(files, out_dir, enhance)` calls your `enhance(path, samples, rate) -> (samples, rate)` on every file not rendered yet.
+Most of the behavior below is that loop's:
+
+- Read every `*.wav` in `IN` (48 kHz mono float32, 3-20 s; the 45 s items; and, for the
+ streaming probe, 15 s cuts of them under `PROBE_IN`). Process each file on its own: the streaming
+ probe treats any cross-file dependence as a defect.
+- Write `OUT/<same basename>.wav`, **48 kHz mono float32** (`soundfile` `subtype="FLOAT"`;
+ the default PCM_16 would clip anything above full scale), of exactly the input's length. The
+ loop writes under a temporary name and renames, refuses NaN and inf, and fits the length,
+ refusing a difference beyond a release's frame rounding (`writer.TOLERANCE_SECONDS`): a
+ cut-off output is a failure, not something to pad. Do not clip, normalize or level-match: the
+ scorer calibrates gain itself. Resample in and back out yourself if the model is not 48 kHz
+ native.
+- **No loudness normalization of your own.** If the model itself changes the level (a
+ generative model that re-synthesizes at its own scale, a post-net that matches the input's
+ peak), leave that and set `"renormalizes": true` in the meta: the level is then part of what is
+ scored. Fidelity's level term reads it, and the scorer undoes it everywhere else (the kept
+ energy, suppression, the high-band error, the deletion rule), so a gain is charged once.
+ When an upstream *inference script* adds a normalization of its own (the URGENT
+ baselines peak-normalize every file to 0.9 because the challenge's metrics are
+ scale-invariant), render a few items without it and read the level against the input:
+ - if the model's own output keeps the input's scale (the FlowSE baseline: within a decibel),
+ the script's step is an evaluation convention, not the system; leave it out and say so in
+ `notes`, because kept it would read as a 9 dB level failure;
+ - if the model's own output is at a scale of its own (the BSRNN baseline: about 17 dB above
+ the input, peaks past full scale, a scale-invariant training loss), the script's step is how
+ the shipped system sets its level; keep it, set `"renormalizes": true` and say so, because
+ without it the scorer's level calibration saturates (`MAX_LEVEL_CAL_DB`, 12 dB) and the
+ leaderboard refuses to rank the row.
+- Resumable: a file whose output already exists is skipped.
+- Robust: a per-file exception prints `FAIL <basename> <err>` and the loop continues; the exit
+ status is non-zero unless every file is present, and a run that exits non-zero is never
+ stamped.
+- Progress: one line per 25 files and a final `DONE <n_ok>/<n_total>`.
+
+## 3. Description and identity
+
+The wrapper writes no result metadata, but it does write a **receipt**: right after parsing its arguments it calls `receipt.begin("<name>", __file__, args.out_dir, sys.argv, args.in_dir, args.device)` (`bench/wrappers/receipt.py`, standard library only, importable from every venv).
+Each process, each shard included, leaves `<out_dir>/.receipt-<host>-<pid>.json` naming what the render depends on:
+
+- the wrapper's sha256 and that of the sibling modules it imports;
+- the upstream checkout (`source_dir` in the description, relative to `BENCH_SRC`): its git commit and a digest of its files;
+- the sha256 of the weight files it loads (`weight_globs`, relative to that directory);
+- the code of the installed packages it runs (`package_dirs`);
+- the interpreter and every installed package with its version;
+- the device it computes on (its kind, such as the GPU model);
+- the inference arguments: the command line without the work selection (folders, shard, limit, device and threads), other paths reduced to their file names;
+- the inputs: the set build, or the probe.
+
+`bench/scripts/runfield.sh` stamps a run into `$BENCH_RESULTS/<name>.meta.json` only through `bench/scripts/stamprender.py`, which refuses a wrapper that exited non-zero, a directory without receipts, receipts that disagree with each other or with the environment stamping them, and any inventory that is not exactly the set's files as finite 48 kHz mono float32 audio of the input's length (stray files are ignored, never counted).
+The stamp carries the agreed identity and its digest (`render_receipt_sha256`), which the scorer copies into every record, and a digest of the outputs' bytes (`outputs_sha256`), which the scorer recomputes from the bytes it reads before it writes a score (an output changed since the stamp ends the run) and every score file carries: `leaderboard.py` refuses scores of other audio than the render stamped now, and the export refuses audio whose description names another render.
+Outputs held under receipts of another identity stop a run (`DISCARD=1` removes them first), an empty input set is an error rather than a successful zero-file run, and `STAMP_ONLY=1` (outputs rendered by sharded wrapper processes) verifies exactly the same way.
+Upstream clones and Hugging Face fetches in `setupfield.sh` are pinned to commits and revisions, so a receipt names a reproducible checkout.
+A wrapper is part of its render's identity byte for byte: edit it, even its docstring, and its render must be made again before it can be resumed, stamped or probed.
+
+`bench/wrappers/meta/<name>.json` (tracked, hand-maintained, no machine paths):
+
+```json
+{
+ "display": "MossFormer2_SE_48K",
+ "mechanism": "masking | spectral-mapping | GAN | diffusion | flow-matching | generative-codec-LM | time-domain-UNet | DSP-spectral-gating | hybrid-2-stage | SSL-feature+vocoder | separator",
+ "native_sr": 48000,
+ "fullband": true,
+ "params_m": 42.1,
+ "license_code": "Apache-2.0",
+ "license_weights": "Apache-2.0",
+ "commercial_ok": true,
+ "repo": "https://github.com/...",
+ "weights": "hf:org/model",
+ "renormalizes": false,
+ "install_notes": "pip install ...; weights auto-download on first use",
+ "notes": "anything the reader needs to interpret the numbers",
+ "source_dir": "<the clone's folder under BENCH_SRC>",
+ "weight_globs": ["checkpoints/*.pt"],
+ "package_dirs": ["<the installed package the wrapper imports>"]
+}
+```
+
+`source_dir`, `weight_globs` and `package_dirs` tell the receipt what to hash; the rest is copied into the stamp for the reader.
+
+`fullband` = can this model emit real content above 8 kHz (48 k native or
+>= 44.1 k)? A 16 kHz-native model is `false` and is ranked in the separate
+16 kHz tier.
+Be honest about `license_weights`: several research repos are non-commercial.
+
+## 4. Smoke test before reporting success
+
+```
+<venv>/bin/python wrappers/run<name>.py --in-dir <a folder of 48 kHz mono wavs> \
+ --out-dir staging/smoke_<name> --limit 3
+python -c "
+import soundfile as sf, glob, numpy as np
+for p in sorted(glob.glob('staging/smoke_<name>/*.wav')):
+ x, sr = sf.read(p); print(p.split('/')[-1], sr, x.shape, 'rms_db', round(20*np.log10(np.sqrt((x**2).mean())+1e-12),1))
+"
+```
+
+Must be `sr == 48000`, non-silent, and the same length as the input.
+A wrapper that emits silence or 16 kHz files is a failed install.
+
+## 5. Register it
+
+Add the system to `TIERS` in `scripts/roster.py` (or pass `--tiers`) and a line to `scripts/runfield.sh`.
+Scoring runs on the eval set, which is not distributed: Inworld renders and scores the system from the pull request.
diff --git a/bench/anchors.json b/bench/anchors.json
new file mode 100644
index 0000000..a264b73
--- /dev/null
+++ b/bench/anchors.json
@@ -0,0 +1,802 @@
+{
+ "schema_version": 1,
+ "version": "1",
+ "minimum_gap": 1e-06,
+ "changelog": [
+ {
+ "version": "0",
+ "reason": "The anchor policy as published: each sub-metric runs from a fixed floor (the unprocessed input, or a declared constant) at 0 to a fixed ceiling (the clean reference, or a declared constant) at 1, so the scale belongs to the set and not to the systems ranked on it."
+ },
+ {
+ "version": "1",
+ "reason": "The pause-level floor follows the unprocessed recordings again. The real-recording pause rows now pool every real family (real_everyday was left out) and bound each item's level within 20 dB of its input's, so INPUT reads -25.0 dB where it read -20.7. The declared floor and its swept range move with it; every other declared endpoint still agrees with INPUT and REF within its tolerance."
+ }
+ ],
+ "rules": [
+ {
+ "conditions": [
+ "babble@+4",
+ "babble@+0",
+ "babble@-5"
+ ],
+ "metrics": [
+ "babble_supp_db",
+ "babble_supp_db_nb"
+ ],
+ "direction": -1,
+ "floor": {
+ "value": 0,
+ "verify": {
+ "source": "INPUT",
+ "tolerance": 0.05
+ },
+ "rationale": "The unchanged mixture removes nothing: zero by definition of the metric."
+ },
+ "ceiling": {
+ "value": -20,
+ "range": [
+ -30,
+ -15
+ ],
+ "rationale": "Policy saturation after 20 dB of reconstruction-error reduction; not an audibility guarantee."
+ }
+ },
+ {
+ "conditions": [
+ "ambience@-5",
+ "stationary@-5",
+ "traffic@-5"
+ ],
+ "metrics": [
+ "si_sdr"
+ ],
+ "direction": 1,
+ "floor": {
+ "value": -5,
+ "verify": {
+ "source": "INPUT",
+ "tolerance": 0.25
+ },
+ "rationale": "The mixture's SI-SDR is the condition's nominal SNR by construction."
+ },
+ "ceiling": {
+ "value": 20,
+ "range": [
+ 15,
+ 30
+ ],
+ "rationale": "Finite policy ceiling avoids the unbounded identity-reference SI-SDR."
+ }
+ },
+ {
+ "conditions": [
+ "ambience@-5",
+ "stationary@-5",
+ "traffic@-5"
+ ],
+ "metrics": [
+ "si_sdr_nb"
+ ],
+ "direction": 1,
+ "floor": {
+ "value": -5,
+ "verify": {
+ "source": "INPUT",
+ "tolerance": 1.5
+ },
+ "rationale": "Nominal SNR; inside 0-8 kHz a bed with energy above the band reads up to a decibel higher."
+ },
+ "ceiling": {
+ "value": 20,
+ "range": [
+ 15,
+ 30
+ ],
+ "rationale": "Finite policy ceiling avoids the unbounded identity-reference SI-SDR."
+ }
+ },
+ {
+ "conditions": [
+ "music@-6"
+ ],
+ "metrics": [
+ "si_sdr",
+ "si_sdr_nb"
+ ],
+ "direction": 1,
+ "floor": {
+ "value": -6,
+ "verify": {
+ "source": "INPUT",
+ "tolerance": 0.25
+ },
+ "rationale": "The mixture's SI-SDR is the condition's nominal SNR by construction."
+ },
+ "ceiling": {
+ "value": 20,
+ "range": [
+ 15,
+ 30
+ ],
+ "rationale": "Finite policy ceiling avoids the unbounded identity-reference SI-SDR."
+ }
+ },
+ {
+ "conditions": [
+ "_deletion"
+ ],
+ "metrics": [
+ "pct"
+ ],
+ "direction": -1,
+ "floor": {
+ "value": 5,
+ "range": [
+ 2,
+ 10
+ ],
+ "rationale": "Five percent deleted primary segments is the declared failure floor."
+ },
+ "ceiling": {
+ "value": 0,
+ "rationale": "No primary segment deletion is the target."
+ }
+ },
+ {
+ "conditions": [
+ "babble@+4"
+ ],
+ "metrics": [
+ "kept_coh_p10",
+ "kept_coh_nb_p10"
+ ],
+ "direction": 1,
+ "floor": {
+ "value": -10,
+ "range": [
+ -20,
+ -6
+ ],
+ "rationale": "Ten dB attenuation of quiet coherent voice is the declared failure floor."
+ },
+ "ceiling": {
+ "value": 0,
+ "rationale": "Preserving the reference level closes the gap; amplification earns no extra credit."
+ }
+ },
+ {
+ "conditions": [
+ "babble@+4"
+ ],
+ "metrics": [
+ "spk_sim",
+ "spk_sim_nb"
+ ],
+ "direction": 1,
+ "floor": {
+ "value": 0.95,
+ "range": [
+ 0.9,
+ 0.96
+ ],
+ "verify": {
+ "source": "INPUT",
+ "tolerance": 0.02
+ },
+ "rationale": "Speaker similarity of the unprocessed mixture at this level: a system should not do worse than leaving the voice alone."
+ },
+ "ceiling": {
+ "value": 1.0,
+ "verify": {
+ "source": "REF",
+ "tolerance": 0.005
+ },
+ "rationale": "Self-similarity of the reference under the same embedding."
+ }
+ },
+ {
+ "conditions": [
+ "clean"
+ ],
+ "metrics": [
+ "kept_coh_p10",
+ "kept_coh_nb_p10"
+ ],
+ "direction": 1,
+ "floor": {
+ "value": -10,
+ "range": [
+ -20,
+ -6
+ ],
+ "rationale": "Ten dB off the quiet blocks of a voice nothing competed with is audible deletion: the preservation axis's scale."
+ },
+ "ceiling": {
+ "value": 0,
+ "verify": {
+ "source": "INPUT",
+ "tolerance": 0.05
+ },
+ "rationale": "The untouched recording keeps all of it; amplification earns no extra credit."
+ }
+ },
+ {
+ "conditions": [
+ "clean"
+ ],
+ "metrics": [
+ "_hf_err"
+ ],
+ "direction": -1,
+ "floor": {
+ "value": 3,
+ "range": [
+ 1.5,
+ 4
+ ],
+ "rationale": "Three dB mean absolute error over 8-24 kHz is a dull or bright copy of the recording."
+ },
+ "ceiling": {
+ "value": 0.5,
+ "range": [
+ 0,
+ 1
+ ],
+ "rationale": "Band-level differences under about half a decibel are not heard."
+ }
+ },
+ {
+ "conditions": [
+ "clean"
+ ],
+ "metrics": [
+ "_level_err"
+ ],
+ "direction": -1,
+ "floor": {
+ "value": 6,
+ "range": [
+ 3,
+ 9
+ ],
+ "rationale": "A six dB level change is a different recording."
+ },
+ "ceiling": {
+ "value": 1,
+ "range": [
+ 0.5,
+ 2
+ ],
+ "rationale": "A level step under about one decibel is not heard."
+ }
+ },
+ {
+ "conditions": [
+ "clean"
+ ],
+ "metrics": [
+ "spk_sim",
+ "spk_sim_nb"
+ ],
+ "direction": 1,
+ "floor": {
+ "value": 0.95,
+ "range": [
+ 0.9,
+ 0.98
+ ],
+ "rationale": "The timbre axis's floor: the similarity a noisy mixture still reaches."
+ },
+ "ceiling": {
+ "value": 1.0,
+ "verify": {
+ "source": "INPUT",
+ "tolerance": 0.005
+ },
+ "rationale": "Self-similarity of the untouched recording under the same embedding."
+ }
+ },
+ {
+ "conditions": [
+ "clean"
+ ],
+ "metrics": [
+ "nisqa_mos"
+ ],
+ "direction": 1,
+ "floor": {
+ "value": 4.0,
+ "range": [
+ 3.5,
+ 4.25
+ ],
+ "rationale": "Half a point of predicted quality lost on speech that was already clean is damage."
+ },
+ "ceiling": {
+ "value": 4.5,
+ "verify": {
+ "source": "INPUT",
+ "tolerance": 0.1
+ },
+ "rationale": "Predicted quality of the untouched clean recordings; a gain over them earns nothing."
+ }
+ },
+ {
+ "conditions": [
+ "babble@+4"
+ ],
+ "metrics": [
+ "nisqa_mos"
+ ],
+ "direction": 1,
+ "floor": {
+ "value": 2.0,
+ "range": [
+ 1.0,
+ 2.5
+ ],
+ "verify": {
+ "source": "INPUT",
+ "tolerance": 0.3
+ },
+ "rationale": "Predicted quality of the unprocessed mixture at this level."
+ },
+ "ceiling": {
+ "value": 4.5,
+ "range": [
+ 4.0,
+ 5.0
+ ],
+ "verify": {
+ "source": "REF",
+ "tolerance": 0.2
+ },
+ "rationale": "Predicted quality of clean studio references: a target, not a perceptual upper bound."
+ }
+ },
+ {
+ "conditions": [
+ "real_noisy"
+ ],
+ "metrics": [
+ "nisqa_mos"
+ ],
+ "direction": 1,
+ "floor": {
+ "value": 2.4,
+ "range": [
+ 1.0,
+ 2.8
+ ],
+ "verify": {
+ "source": "INPUT",
+ "tolerance": 0.3
+ },
+ "rationale": "Predicted quality of the unprocessed recordings."
+ },
+ "ceiling": {
+ "value": 5,
+ "range": [
+ 4.0,
+ 5.0
+ ],
+ "rationale": "Nominal quality-scale maximum; these recordings have no clean reference."
+ }
+ },
+ {
+ "conditions": [
+ "ambience@+5",
+ "events@+5",
+ "cheer@+5",
+ "wind@+0",
+ "stationary@+5",
+ "traffic@+0",
+ "appliance@+5",
+ "tools@+5",
+ "household@+0",
+ "animals@+0",
+ "rain@+0"
+ ],
+ "metrics": [
+ "spk_sim",
+ "spk_sim_nb"
+ ],
+ "direction": 1,
+ "floor": {
+ "value": 0.95,
+ "verify": {
+ "source": "INPUT",
+ "tolerance": 0.04
+ },
+ "range": [
+ 0.9,
+ 0.96
+ ],
+ "rationale": "Speaker similarity of the unprocessed mixture at the level of each noise family where it reads about 0.95 (0.91 to 0.98 over the families and views), the scale of crowd chatter at +4 dB: a system should not do worse than leaving the voice alone."
+ },
+ "ceiling": {
+ "value": 1.0,
+ "rationale": "Self-similarity of the reference under the same embedding: one by construction, measured under crowd chatter at +4 dB."
+ }
+ },
+ {
+ "conditions": [
+ "nonverbal@+0",
+ "nonverbal_clean"
+ ],
+ "metrics": [
+ "nv_lost_pct"
+ ],
+ "direction": -1,
+ "floor": {
+ "value": 30,
+ "range": [
+ 20,
+ 50
+ ],
+ "rationale": "Three in ten of the vocal sounds outside speech lost is the declared failure floor."
+ },
+ "ceiling": {
+ "value": 0,
+ "verify": {
+ "source": "INPUT",
+ "tolerance": 0.5
+ },
+ "rationale": "The unprocessed mixture loses none of them: only sounds the bed does not bury are counted."
+ }
+ },
+ {
+ "conditions": [
+ "clean"
+ ],
+ "metrics": [
+ "mag_snr",
+ "mag_snr_nb"
+ ],
+ "direction": 1,
+ "floor": {
+ "value": 10,
+ "range": [
+ 5,
+ 15
+ ],
+ "rationale": "A spectrum whose error holds a tenth of its energy is another rendition of the recording."
+ },
+ "ceiling": {
+ "value": 30,
+ "range": [
+ 25,
+ 35
+ ],
+ "rationale": "A re-synthesis that changes no spectrum reads 32 dB (the resynth control); above 30 dB a changed spectrum is not told from an unchanged one."
+ }
+ },
+ {
+ "conditions": [
+ "reverb_real"
+ ],
+ "metrics": [
+ "spk_sim",
+ "spk_sim_nb"
+ ],
+ "direction": 1,
+ "floor": {
+ "value": 0.86,
+ "verify": {
+ "source": "INPUT",
+ "tolerance": 0.02
+ },
+ "range": [
+ 0.8,
+ 0.9
+ ],
+ "rationale": "Speaker similarity of the recording in its room to the dry voice: a system that leaves the room in place stays here."
+ },
+ "ceiling": {
+ "value": 1.0,
+ "rationale": "Self-similarity of the dry reference under the same embedding: one by construction."
+ }
+ },
+ {
+ "conditions": [
+ "reverb_real"
+ ],
+ "metrics": [
+ "nisqa_mos"
+ ],
+ "direction": 1,
+ "floor": {
+ "value": 2.0,
+ "verify": {
+ "source": "INPUT",
+ "tolerance": 0.3
+ },
+ "range": [
+ 1.0,
+ 2.5
+ ],
+ "rationale": "Predicted quality of the recordings in their rooms."
+ },
+ "ceiling": {
+ "value": 4.5,
+ "range": [
+ 4.0,
+ 5.0
+ ],
+ "rationale": "Predicted quality of clean studio references, verified under crowd chatter at +4 dB: a target, not a perceptual upper bound."
+ }
+ },
+ {
+ "conditions": [
+ "babble@+4",
+ "babble@+0",
+ "babble@-5"
+ ],
+ "metrics": [
+ "babble_resid_db",
+ "babble_resid_db_nb"
+ ],
+ "direction": -1,
+ "floor": {
+ "value": 0,
+ "verify": {
+ "source": "INPUT",
+ "tolerance": 0.3
+ },
+ "rationale": "The unchanged mixture removes nothing: zero up to the share of the chatter the voice explains by chance."
+ },
+ "ceiling": {
+ "value": -20,
+ "range": [
+ -25,
+ -15
+ ],
+ "rationale": "Policy saturation after 20 dB of interference removed at the voice's scale, the bound every item is held inside before pooling; not an audibility guarantee. Below the bound no pooled value reaches the ceiling: a stricter ceiling compresses the axis rather than moving its top."
+ }
+ },
+ {
+ "conditions": [
+ "_real_cleanup"
+ ],
+ "metrics": [
+ "pause_resid_db",
+ "pause_resid_db_nb"
+ ],
+ "direction": -1,
+ "floor": {
+ "value": 0,
+ "verify": {
+ "source": "INPUT",
+ "tolerance": 0.05
+ },
+ "rationale": "The unchanged recording leaves every pause as it was: zero by definition of the metric."
+ },
+ "ceiling": {
+ "value": -20,
+ "range": [
+ -25,
+ -15
+ ],
+ "rationale": "Policy saturation after 20 dB of the pauses' audibility-weighted energy removed beyond what the voice lost, the bound every item is held inside before pooling; a pause silenced outright earns no more. Below the bound no pooled value reaches the ceiling: a stricter ceiling compresses the axis rather than moving its top."
+ }
+ },
+ {
+ "conditions": [
+ "_real_quality"
+ ],
+ "metrics": [
+ "nisqa_mos"
+ ],
+ "direction": 1,
+ "floor": {
+ "value": 2.7,
+ "verify": {
+ "source": "INPUT",
+ "tolerance": 0.3
+ },
+ "range": [
+ 1.0,
+ 3.5
+ ],
+ "rationale": "Predicted quality of the unprocessed recordings, the equal mean of the four families."
+ },
+ "ceiling": {
+ "value": 5,
+ "range": [
+ 4.0,
+ 5.0
+ ],
+ "rationale": "Nominal quality-scale maximum; these recordings have no clean reference."
+ }
+ },
+ {
+ "conditions": [
+ "_real_cleanup"
+ ],
+ "metrics": [
+ "pause_level_db"
+ ],
+ "direction": -1,
+ "floor": {
+ "value": -25.0,
+ "verify": {
+ "source": "INPUT",
+ "tolerance": 0.3
+ },
+ "range": [
+ -30.0,
+ -20.0
+ ],
+ "rationale": "What the unprocessed recordings hold in their pauses against their own voice, audibility weighted: the pooled mean over the eligible items."
+ },
+ "ceiling": {
+ "value": -45,
+ "range": [
+ -55,
+ -35
+ ],
+ "rationale": "The cap at which a residual under the voice is taken as inaudible (scoreresidual.LEVEL_CLIP_DB): every item saturates there, so no item earns more than its own distance to it; the swept range is centred on the declared value, as every range is."
+ }
+ },
+ {
+ "conditions": [
+ "coroom@pause",
+ "coroom@speech",
+ "coroom@both"
+ ],
+ "metrics": [
+ "event_resid_db"
+ ],
+ "direction": -1,
+ "floor": {
+ "value": 0,
+ "verify": {
+ "source": "INPUT",
+ "tolerance": 0.05
+ },
+ "rationale": "The unchanged mixture leaves the added noise as it was: zero by definition of the metric."
+ },
+ "ceiling": {
+ "value": -20,
+ "range": [
+ -25,
+ -15
+ ],
+ "rationale": "Policy saturation after 20 dB of the added noise removed over the labelled spans, the bound every item is held inside before pooling; a span silenced outright earns no more. Below the bound no pooled value reaches the ceiling: a stricter ceiling compresses the axis rather than moving its top."
+ }
+ },
+ {
+ "conditions": [
+ "coroom@floor",
+ "coroom@both"
+ ],
+ "metrics": [
+ "floor_resid_db"
+ ],
+ "direction": -1,
+ "floor": {
+ "value": 0,
+ "verify": {
+ "source": "INPUT",
+ "tolerance": 0.05
+ },
+ "rationale": "The unchanged mixture leaves the added noise as it was: zero by definition of the metric."
+ },
+ "ceiling": {
+ "value": -20,
+ "range": [
+ -25,
+ -15
+ ],
+ "rationale": "Policy saturation after 20 dB of the added noise removed over the labelled spans, the bound every item is held inside before pooling; a span silenced outright earns no more. Below the bound no pooled value reaches the ceiling: a stricter ceiling compresses the axis rather than moving its top."
+ }
+ },
+ {
+ "conditions": [
+ "_coroom"
+ ],
+ "metrics": [
+ "voice_level_db"
+ ],
+ "direction": 1,
+ "floor": {
+ "value": -3,
+ "range": [
+ -4.5,
+ -1.5
+ ],
+ "rationale": "Three decibels of the voice lost on its loudest speech frames, with the noise there or against the reference beyond the room's share, is the declared failure floor; a louder voice earns nothing beyond the ceiling."
+ },
+ "ceiling": {
+ "value": 0,
+ "verify": {
+ "source": "INPUT",
+ "tolerance": 0.05
+ },
+ "rationale": "The unchanged mixture keeps the voice's level: zero by definition of the metric."
+ }
+ },
+ {
+ "conditions": [
+ "talker@+5"
+ ],
+ "metrics": [
+ "si_sdr",
+ "si_sdr_nb"
+ ],
+ "direction": 1,
+ "floor": {
+ "value": 5,
+ "verify": {
+ "source": "INPUT",
+ "tolerance": 0.25
+ },
+ "rationale": "The mixture's SI-SDR is the condition's nominal SNR by construction: the competing talker 5 dB under the voice."
+ },
+ "ceiling": {
+ "value": 20,
+ "range": [
+ 15,
+ 30
+ ],
+ "rationale": "The same finite ceiling as the other SI-SDR rows; the competing talker removed to 20 dB is a clean voice."
+ }
+ },
+ {
+ "conditions": [
+ "srsweep_8k",
+ "srsweep_16k"
+ ],
+ "metrics": [
+ "band_added_db"
+ ],
+ "direction": 1,
+ "floor": {
+ "value": -0.85,
+ "range": [
+ -3.0,
+ 0.0
+ ],
+ "verify": {
+ "source": "INPUT",
+ "tolerance": 0.4
+ },
+ "rationale": "The band-limited input holds nothing above its band; the row reads it against the band-limited reference, less the mean of the bands inside, where the mixture carries the noise the reference does not, so the input sits a little under zero (verified against INPUT)."
+ },
+ "ceiling": {
+ "value": 40,
+ "range": [
+ 30,
+ 60
+ ],
+ "rationale": "A band above the input filled to the level of the band inside it reads about 40 dB over the empty reference band. The set holds no reference above the input's band, so the ceiling is declared, and the quality rows beside it say whether what was added sounds like speech."
+ }
+ },
+ {
+ "conditions": [
+ "srsweep_8k",
+ "srsweep_16k"
+ ],
+ "metrics": [
+ "spk_sim"
+ ],
+ "direction": 1,
+ "floor": {
+ "value": 0.94,
+ "range": [
+ 0.9,
+ 0.97
+ ],
+ "verify": {
+ "source": "INPUT",
+ "tolerance": 0.02
+ },
+ "rationale": "The band-limited input's speaker similarity to the reference band-limited the same way, with the noise it carries."
+ },
+ "ceiling": {
+ "value": 1.0,
+ "rationale": "The reference's own similarity to itself. A band filled with anything but the speaker lowers the row, so the energy row beside it is not paid for junk."
+ }
+ }
+ ]
+}
diff --git a/bench/axes.json b/bench/axes.json
new file mode 100644
index 0000000..6c84457
--- /dev/null
+++ b/bench/axes.json
@@ -0,0 +1,943 @@
+{
+ "schema_version": 1,
+ "version": "0",
+ "policy": {
+ "min_items": 20,
+ "min_source_groups": 2,
+ "min_human_items": 20,
+ "max_redundancy": 0.9
+ },
+ "baseline": {
+ "all": {
+ "full": {
+ "suppression": [
+ [
+ "babble@+4",
+ "babble_resid_db",
+ -1
+ ],
+ [
+ "babble@+0",
+ "babble_resid_db",
+ -1
+ ],
+ [
+ "babble@-5",
+ "babble_resid_db",
+ -1
+ ],
+ [
+ "ambience@-5",
+ "si_sdr",
+ 1
+ ],
+ [
+ "stationary@-5",
+ "si_sdr",
+ 1
+ ],
+ [
+ "traffic@-5",
+ "si_sdr",
+ 1
+ ]
+ ],
+ "music": [
+ [
+ "music@-6",
+ "si_sdr",
+ 1
+ ]
+ ],
+ "preservation": [
+ [
+ "_deletion",
+ "pct",
+ -1
+ ],
+ [
+ "babble@+4",
+ "kept_coh_p10",
+ 1
+ ],
+ [
+ "nonverbal@+0",
+ "nv_lost_pct",
+ -1
+ ],
+ [
+ "_coroom",
+ "voice_level_db",
+ 1
+ ]
+ ],
+ "timbre": [
+ [
+ "babble@+4",
+ "spk_sim",
+ 1
+ ],
+ [
+ "ambience@+5",
+ "spk_sim",
+ 1
+ ],
+ [
+ "events@+5",
+ "spk_sim",
+ 1
+ ],
+ [
+ "cheer@+5",
+ "spk_sim",
+ 1
+ ],
+ [
+ "wind@+0",
+ "spk_sim",
+ 1
+ ],
+ [
+ "stationary@+5",
+ "spk_sim",
+ 1
+ ],
+ [
+ "traffic@+0",
+ "spk_sim",
+ 1
+ ],
+ [
+ "appliance@+5",
+ "spk_sim",
+ 1
+ ],
+ [
+ "tools@+5",
+ "spk_sim",
+ 1
+ ],
+ [
+ "household@+0",
+ "spk_sim",
+ 1
+ ],
+ [
+ "animals@+0",
+ "spk_sim",
+ 1
+ ],
+ [
+ "rain@+0",
+ "spk_sim",
+ 1
+ ]
+ ],
+ "fidelity": [
+ [
+ "clean",
+ "kept_coh_p10",
+ 1
+ ],
+ [
+ "clean",
+ "_level_err",
+ -1
+ ],
+ [
+ "clean",
+ "_hf_err",
+ -1
+ ],
+ [
+ "clean",
+ "spk_sim",
+ 1
+ ],
+ [
+ "clean",
+ "nisqa_mos",
+ 1
+ ],
+ [
+ "clean",
+ "mag_snr",
+ 1
+ ],
+ [
+ "nonverbal_clean",
+ "nv_lost_pct",
+ -1
+ ]
+ ],
+ "quality": [
+ [
+ "babble@+4",
+ "nisqa_mos",
+ 1
+ ],
+ [
+ "_real_quality",
+ "nisqa_mos",
+ 1
+ ]
+ ],
+ "room": [
+ [
+ "reverb_real",
+ "spk_sim",
+ 1
+ ],
+ [
+ "reverb_real",
+ "nisqa_mos",
+ 1
+ ]
+ ],
+ "cleanup": [
+ [
+ "_real_cleanup",
+ "pause_level_db",
+ -1
+ ],
+ [
+ "coroom@floor",
+ "floor_resid_db",
+ -1
+ ],
+ [
+ "coroom@both",
+ "floor_resid_db",
+ -1
+ ]
+ ],
+ "events": [
+ [
+ "coroom@pause",
+ "event_resid_db",
+ -1
+ ],
+ [
+ "coroom@speech",
+ "event_resid_db",
+ -1
+ ],
+ [
+ "coroom@both",
+ "event_resid_db",
+ -1
+ ]
+ ],
+ "voices": [
+ [
+ "talker@+5",
+ "si_sdr",
+ 1
+ ]
+ ],
+ "band": [
+ [
+ "srsweep_8k",
+ "band_added_db",
+ 1
+ ],
+ [
+ "srsweep_16k",
+ "band_added_db",
+ 1
+ ],
+ [
+ "srsweep_8k",
+ "spk_sim",
+ 1
+ ],
+ [
+ "srsweep_16k",
+ "spk_sim",
+ 1
+ ]
+ ]
+ },
+ "nb": {
+ "suppression": [
+ [
+ "babble@+4",
+ "babble_resid_db_nb",
+ -1
+ ],
+ [
+ "babble@+0",
+ "babble_resid_db_nb",
+ -1
+ ],
+ [
+ "babble@-5",
+ "babble_resid_db_nb",
+ -1
+ ],
+ [
+ "ambience@-5",
+ "si_sdr_nb",
+ 1
+ ],
+ [
+ "stationary@-5",
+ "si_sdr_nb",
+ 1
+ ],
+ [
+ "traffic@-5",
+ "si_sdr_nb",
+ 1
+ ]
+ ],
+ "music": [
+ [
+ "music@-6",
+ "si_sdr_nb",
+ 1
+ ]
+ ],
+ "preservation": [
+ [
+ "_deletion",
+ "pct",
+ -1
+ ],
+ [
+ "babble@+4",
+ "kept_coh_nb_p10",
+ 1
+ ],
+ [
+ "nonverbal@+0",
+ "nv_lost_pct",
+ -1
+ ],
+ [
+ "_coroom",
+ "voice_level_db",
+ 1
+ ]
+ ],
+ "timbre": [
+ [
+ "babble@+4",
+ "spk_sim_nb",
+ 1
+ ],
+ [
+ "ambience@+5",
+ "spk_sim_nb",
+ 1
+ ],
+ [
+ "events@+5",
+ "spk_sim_nb",
+ 1
+ ],
+ [
+ "cheer@+5",
+ "spk_sim_nb",
+ 1
+ ],
+ [
+ "wind@+0",
+ "spk_sim_nb",
+ 1
+ ],
+ [
+ "stationary@+5",
+ "spk_sim_nb",
+ 1
+ ],
+ [
+ "traffic@+0",
+ "spk_sim_nb",
+ 1
+ ],
+ [
+ "appliance@+5",
+ "spk_sim_nb",
+ 1
+ ],
+ [
+ "tools@+5",
+ "spk_sim_nb",
+ 1
+ ],
+ [
+ "household@+0",
+ "spk_sim_nb",
+ 1
+ ],
+ [
+ "animals@+0",
+ "spk_sim_nb",
+ 1
+ ],
+ [
+ "rain@+0",
+ "spk_sim_nb",
+ 1
+ ]
+ ],
+ "fidelity": [
+ [
+ "clean",
+ "kept_coh_nb_p10",
+ 1
+ ],
+ [
+ "clean",
+ "_level_err",
+ -1
+ ],
+ [
+ "clean",
+ "spk_sim_nb",
+ 1
+ ],
+ [
+ "clean",
+ "nisqa_mos",
+ 1
+ ],
+ [
+ "clean",
+ "mag_snr_nb",
+ 1
+ ],
+ [
+ "nonverbal_clean",
+ "nv_lost_pct",
+ -1
+ ]
+ ],
+ "quality": [
+ [
+ "babble@+4",
+ "nisqa_mos",
+ 1
+ ],
+ [
+ "_real_quality",
+ "nisqa_mos",
+ 1
+ ]
+ ],
+ "room": [
+ [
+ "reverb_real",
+ "spk_sim_nb",
+ 1
+ ],
+ [
+ "reverb_real",
+ "nisqa_mos",
+ 1
+ ]
+ ],
+ "cleanup": [
+ [
+ "_real_cleanup",
+ "pause_level_db",
+ -1
+ ],
+ [
+ "coroom@floor",
+ "floor_resid_db",
+ -1
+ ],
+ [
+ "coroom@both",
+ "floor_resid_db",
+ -1
+ ]
+ ],
+ "events": [
+ [
+ "coroom@pause",
+ "event_resid_db",
+ -1
+ ],
+ [
+ "coroom@speech",
+ "event_resid_db",
+ -1
+ ],
+ [
+ "coroom@both",
+ "event_resid_db",
+ -1
+ ]
+ ],
+ "voices": [
+ [
+ "talker@+5",
+ "si_sdr_nb",
+ 1
+ ]
+ ],
+ "band": [
+ [
+ "srsweep_8k",
+ "band_added_db",
+ 1
+ ],
+ [
+ "srsweep_16k",
+ "band_added_db",
+ 1
+ ],
+ [
+ "srsweep_8k",
+ "spk_sim",
+ 1
+ ],
+ [
+ "srsweep_16k",
+ "spk_sim",
+ 1
+ ]
+ ]
+ }
+ },
+ "core": {
+ "full": {
+ "suppression": [
+ [
+ "babble@+4",
+ "babble_resid_db",
+ -1
+ ],
+ [
+ "babble@+0",
+ "babble_resid_db",
+ -1
+ ],
+ [
+ "babble@-5",
+ "babble_resid_db",
+ -1
+ ],
+ [
+ "ambience@-5",
+ "si_sdr",
+ 1
+ ]
+ ],
+ "music": [
+ [
+ "music@-6",
+ "si_sdr",
+ 1
+ ]
+ ],
+ "preservation": [
+ [
+ "_deletion",
+ "pct",
+ -1
+ ],
+ [
+ "babble@+4",
+ "kept_coh_p10",
+ 1
+ ],
+ [
+ "_coroom",
+ "voice_level_db",
+ 1
+ ]
+ ],
+ "timbre": [
+ [
+ "babble@+4",
+ "spk_sim",
+ 1
+ ],
+ [
+ "ambience@+5",
+ "spk_sim",
+ 1
+ ],
+ [
+ "events@+5",
+ "spk_sim",
+ 1
+ ],
+ [
+ "cheer@+5",
+ "spk_sim",
+ 1
+ ],
+ [
+ "wind@+0",
+ "spk_sim",
+ 1
+ ]
+ ],
+ "fidelity": [
+ [
+ "clean",
+ "kept_coh_p10",
+ 1
+ ],
+ [
+ "clean",
+ "_level_err",
+ -1
+ ],
+ [
+ "clean",
+ "_hf_err",
+ -1
+ ],
+ [
+ "clean",
+ "spk_sim",
+ 1
+ ],
+ [
+ "clean",
+ "nisqa_mos",
+ 1
+ ],
+ [
+ "clean",
+ "mag_snr",
+ 1
+ ]
+ ],
+ "quality": [
+ [
+ "babble@+4",
+ "nisqa_mos",
+ 1
+ ],
+ [
+ "_real_quality",
+ "nisqa_mos",
+ 1
+ ]
+ ],
+ "room": [
+ [
+ "reverb_real",
+ "spk_sim",
+ 1
+ ],
+ [
+ "reverb_real",
+ "nisqa_mos",
+ 1
+ ]
+ ],
+ "cleanup": [
+ [
+ "_real_cleanup",
+ "pause_level_db",
+ -1
+ ],
+ [
+ "coroom@floor",
+ "floor_resid_db",
+ -1
+ ],
+ [
+ "coroom@both",
+ "floor_resid_db",
+ -1
+ ]
+ ],
+ "events": [
+ [
+ "coroom@pause",
+ "event_resid_db",
+ -1
+ ],
+ [
+ "coroom@speech",
+ "event_resid_db",
+ -1
+ ],
+ [
+ "coroom@both",
+ "event_resid_db",
+ -1
+ ]
+ ],
+ "voices": [
+ [
+ "talker@+5",
+ "si_sdr",
+ 1
+ ]
+ ],
+ "band": [
+ [
+ "srsweep_8k",
+ "band_added_db",
+ 1
+ ],
+ [
+ "srsweep_16k",
+ "band_added_db",
+ 1
+ ],
+ [
+ "srsweep_8k",
+ "spk_sim",
+ 1
+ ],
+ [
+ "srsweep_16k",
+ "spk_sim",
+ 1
+ ]
+ ]
+ },
+ "nb": {
+ "suppression": [
+ [
+ "babble@+4",
+ "babble_resid_db_nb",
+ -1
+ ],
+ [
+ "babble@+0",
+ "babble_resid_db_nb",
+ -1
+ ],
+ [
+ "babble@-5",
+ "babble_resid_db_nb",
+ -1
+ ],
+ [
+ "ambience@-5",
+ "si_sdr_nb",
+ 1
+ ]
+ ],
+ "music": [
+ [
+ "music@-6",
+ "si_sdr_nb",
+ 1
+ ]
+ ],
+ "preservation": [
+ [
+ "_deletion",
+ "pct",
+ -1
+ ],
+ [
+ "babble@+4",
+ "kept_coh_nb_p10",
+ 1
+ ],
+ [
+ "_coroom",
+ "voice_level_db",
+ 1
+ ]
+ ],
+ "timbre": [
+ [
+ "babble@+4",
+ "spk_sim_nb",
+ 1
+ ],
+ [
+ "ambience@+5",
+ "spk_sim_nb",
+ 1
+ ],
+ [
+ "events@+5",
+ "spk_sim_nb",
+ 1
+ ],
+ [
+ "cheer@+5",
+ "spk_sim_nb",
+ 1
+ ],
+ [
+ "wind@+0",
+ "spk_sim_nb",
+ 1
+ ]
+ ],
+ "fidelity": [
+ [
+ "clean",
+ "kept_coh_nb_p10",
+ 1
+ ],
+ [
+ "clean",
+ "_level_err",
+ -1
+ ],
+ [
+ "clean",
+ "spk_sim_nb",
+ 1
+ ],
+ [
+ "clean",
+ "nisqa_mos",
+ 1
+ ],
+ [
+ "clean",
+ "mag_snr_nb",
+ 1
+ ]
+ ],
+ "quality": [
+ [
+ "babble@+4",
+ "nisqa_mos",
+ 1
+ ],
+ [
+ "_real_quality",
+ "nisqa_mos",
+ 1
+ ]
+ ],
+ "room": [
+ [
+ "reverb_real",
+ "spk_sim_nb",
+ 1
+ ],
+ [
+ "reverb_real",
+ "nisqa_mos",
+ 1
+ ]
+ ],
+ "cleanup": [
+ [
+ "_real_cleanup",
+ "pause_level_db",
+ -1
+ ],
+ [
+ "coroom@floor",
+ "floor_resid_db",
+ -1
+ ],
+ [
+ "coroom@both",
+ "floor_resid_db",
+ -1
+ ]
+ ],
+ "events": [
+ [
+ "coroom@pause",
+ "event_resid_db",
+ -1
+ ],
+ [
+ "coroom@speech",
+ "event_resid_db",
+ -1
+ ],
+ [
+ "coroom@both",
+ "event_resid_db",
+ -1
+ ]
+ ],
+ "voices": [
+ [
+ "talker@+5",
+ "si_sdr_nb",
+ 1
+ ]
+ ],
+ "band": [
+ [
+ "srsweep_8k",
+ "band_added_db",
+ 1
+ ],
+ [
+ "srsweep_16k",
+ "band_added_db",
+ 1
+ ],
+ [
+ "srsweep_8k",
+ "spk_sim",
+ 1
+ ],
+ [
+ "srsweep_16k",
+ "spk_sim",
+ 1
+ ]
+ ]
+ }
+ }
+ },
+ "history": [
+ {
+ "version": "0",
+ "action": "baseline",
+ "reason": "The axes and their rows, how they combine into parts and boards, the axes scored beside the boards, the tie bands and the rule that decides which board ranks a system, as published.",
+ "panel_run": null,
+ "study_id": null,
+ "parts": {
+ "removes": [
+ "suppression",
+ "music",
+ "cleanup",
+ "events",
+ "voices"
+ ],
+ "keeps": [
+ "preservation",
+ "fidelity"
+ ],
+ "sounds": [
+ "timbre",
+ "quality"
+ ],
+ "restores": [
+ "room"
+ ]
+ },
+ "outside": [
+ "band"
+ ],
+ "boards": {
+ "denoising": [
+ "removes",
+ "keeps",
+ "sounds"
+ ],
+ "restoration": [
+ "restores"
+ ]
+ },
+ "assign": {
+ "by": "band_above_input_db",
+ "above_db": 10.0,
+ "board": "restoration",
+ "otherwise": "denoising"
+ },
+ "tie_bands": {
+ "timbre": 0.05
+ }
+ }
+ ]
+}
diff --git a/bench/scripts/admission.py b/bench/scripts/admission.py
new file mode 100644
index 0000000..0b27017
--- /dev/null
+++ b/bench/scripts/admission.py
@@ -0,0 +1,990 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Evidence-gated, replayable membership of composite axes.
+
+Panel and listening inputs are private. Decisions retain aggregate evidence
+and content-addressed run/study identifiers, not checkpoint codenames, item
+IDs, transcripts, or source inventories. This evaluates evidence; it does
+not manufacture a listening verdict or automatically edit the live axes.
+"""
+
+import argparse
+import copy
+import json
+import math
+import os
+import pathlib
+
+import numpy as np
+
+import anchors
+import compare
+
+# BENCH_AXES selects another registry file (a protected copy of an earlier
+# revision, say) so an earlier policy's results stay reproducible while the
+# live one is revised; the published file is never overwritten for that
+DEFAULT = pathlib.Path(
+ os.environ.get("BENCH_AXES",
+ pathlib.Path(__file__).resolve().parents[1] / "axes.json"))
+
+
+def _measured(report: dict) -> bool:
+ """Whether the panel separated the regression, not the null, and listeners
+ agreed, every check passing."""
+ regression = report.get("regression", {}).get("ci95", [])
+ null = report.get("null", {}).get("ci95", [])
+ human = (report.get("human") or {}).get("ci95", [])
+ return (len(regression) == len(null) == len(human) == 2 and
+ regression[0] <= regression[1] < 0 and null[0] <= 0 <= null[1] and
+ human[0] <= human[1] < 0 and bool(report.get("panel_run")) and
+ bool(report.get("study_id")) and all(
+ report.get("checks", {}).get(k) is True
+ for k in ("E1", "E2", "E3", "E4")))
+
+
+def _valid_decision(report: dict) -> bool:
+ return _measured(report) and report.get("admitted") is True
+
+
+def _promotable(report: dict) -> bool:
+ """A review of a row already in its axis that passed every check, intact."""
+ return _measured(report) and report.get("admitted") is False and _intact(
+ report)
+
+
+def _intact(report: dict) -> bool:
+ return report.get("evidence_sha256") == anchors.digest({
+ k: v for k, v in report.items() if k != "evidence_sha256"
+ })
+
+
+def _failed_panel(report: dict) -> bool:
+ regression = report.get("regression", {}).get("ci95", [])
+ null = report.get("null", {}).get("ci95", [])
+ return (_intact(report) and report.get("checks", {}).get("E1") is False and
+ len(regression) == len(null) == 2 and
+ (regression[1] >= 0 or not null[0] <= 0 <= null[1]))
+
+
+def _is_int(value) -> bool:
+ """Returns whether ``value`` is an int; a bool, its subclass, is not."""
+ return isinstance(value, int) and not isinstance(value, bool)
+
+
+def _valid_removal(report: dict, row: dict) -> bool:
+ """Returns whether a removal rests on two consecutive failed panels.
+
+ Both read the row removed under this registry, on one build of the set
+ other than the previous one (so after a set change), in two panel runs.
+ """
+ failures = report.get("failures", [])
+ if (not _intact(report) or len(failures) != 2 or
+ not report.get("previous_set_id") or
+ not all(_failed_panel(r) for r in failures)):
+ return False
+ if not all(
+ r.get("axis_sha256") == report["axis_sha256"] and
+ _is_int(r.get("sequence")) for r in failures):
+ return False
+ first, second = failures
+ return (first.get("set_id") == second.get("set_id") and
+ first.get("set_id") != report["previous_set_id"] and
+ second.get("sequence") == first.get("sequence", -2) + 1 and
+ all(r.get("panel_run") and r.get("row") == row for r in failures)
+ and first["panel_run"] != second["panel_run"])
+
+
+def _redefine(views: dict, change: dict, prior: dict) -> None:
+ """Apply a maintainer's redefinition of what one axis measures to each view.
+
+ Admission adds a test condition on panel and listening evidence. A
+ redefinition is another kind of change: the maintainer decides that an axis
+ was scoring the wrong quantity and states the rows that replace it. It is
+ recorded as such, never dressed up as an admission: it names who decided,
+ the public note that shows the board under both definitions, the registry it
+ was made against, and the complete rows of every tier.
+ """
+ rows = change.get("rows")
+ if (change.get("axis_sha256") != anchors.digest(prior) or
+ not change.get("reason") or
+ change.get("decided_by") != "maintainer" or
+ not change.get("note") or not isinstance(rows, dict) or not rows):
+ raise ValueError(
+ "a redefinition names the maintainer, a reason, a public note and"
+ " the registry it was made against")
+ for tiers in views.values():
+ if set(rows) != set(tiers):
+ raise ValueError("a redefinition states the rows of every tier")
+ for tier, new in rows.items():
+ axis = change.get("axis")
+ if axis not in tiers[tier]:
+ raise ValueError("a redefinition names an existing axis")
+ valid = new and all(
+ isinstance(r, list) and len(r) == 3 and r[2] in (-1, 1) and all(
+ isinstance(v, str) and v for v in r[:2]) for r in new)
+ if not valid or len({tuple(r[:2]) for r in new}) != len(new):
+ raise ValueError(
+ "redefined rows are distinct [condition, metric, direction]"
+ )
+ if [list(r) for r in new] == tiers[tier][axis]:
+ raise ValueError("a redefinition changes the axis")
+ tiers[tier][axis] = [list(r) for r in new]
+
+
+def _valid_rows(rows) -> bool:
+ return (bool(rows) and all(
+ isinstance(r, list) and len(r) == 3 and r[2] in (-1, 1) and all(
+ isinstance(v, str) and v
+ for v in r[:2])
+ for r in rows) and len({tuple(r[:2]) for r in rows}) == len(rows))
+
+
+def _revise(views: dict, change: dict, prior: dict) -> None:
+ """Applies a maintainer's revision of the composite.
+
+ A revision may change several axes at once, add a new one among them, give
+ each view rows of its own, and change how the axes combine.
+
+ A redefinition restates one axis with the same rows in every view. A
+ revision is the larger decision: what the composite covers changed. It names
+ who decided, the public note that shows the board under both definitions and
+ the registry it was made against; it states the complete rows of every axis
+ it touches, in every view and tier it touches, because a view that lacks a
+ condition cannot take the row; a view it leaves out keeps its rows. It may
+ state the parts of the composite (see ``parts``), and it may move an axis
+ into the composite or beside it without restating any row.
+ """
+ stated = change.get("axes")
+ # a revision that restates no rows must still change what the composite
+ # covers: which axes it reads, and in which parts
+ moves = (("parts" in change and change["parts"] != (parts(prior) or {})) or
+ ("outside" in change and change["outside"] != outside(prior)) or
+ ("boards" in change and change["boards"] != boards(prior)) or
+ ("assign" in change and change["assign"] != assignment(prior)))
+ if (change.get("axis_sha256") != anchors.digest(prior) or
+ not change.get("reason") or
+ change.get("decided_by") != "maintainer" or
+ not change.get("note") or not isinstance(stated, dict) or
+ not (stated or moves) or not set(stated) <= set(views)):
+ raise ValueError(
+ "a revision names the maintainer, a reason, a public note, the"
+ " registry it was made against and the axes of the views it"
+ " changes, or the axes it moves into or out of the composite")
+ for view, stated_tiers in stated.items():
+ tiers = views[view]
+ if (not stated_tiers or not set(stated_tiers) <= set(tiers) or
+ not all(stated_tiers.values())):
+ raise ValueError(
+ "a revision states the axes of the tiers it changes")
+ for tier, axes in stated_tiers.items():
+ for axis, rows in axes.items():
+ if not _valid_rows(rows):
+ raise ValueError(
+ "revised rows are distinct [condition, metric,"
+ " direction]")
+ if [list(r) for r in rows] == tiers[tier].get(axis):
+ raise ValueError("a revision changes every axis it names")
+ tiers[tier][axis] = [list(r) for r in rows]
+ _check_layout(views, change, prior)
+
+
+def _check_layout(views: dict, change: dict, prior: dict) -> None:
+ """Raises ValueError unless what ``change`` states of how the axes combine
+ holds over ``views``: its tie bands, the axes beside the composite, the
+ parts, the boards and the assignment rule, each stated or inherited from
+ ``prior``. The baseline of a registry is checked the same way."""
+ names = [set(axes) for tiers in views.values() for axes in tiers.values()]
+ if any(n != names[0] for n in names):
+ raise ValueError("every view and tier scores the same axes")
+ bands = change.get("tie_bands")
+ if bands is not None and (not isinstance(bands, dict) or not bands or any(
+ axis not in names[0] or isinstance(band, bool) or
+ not isinstance(band, (int, float)) or not 0 < band < 1
+ for axis, band in bands.items())):
+ raise ValueError(
+ "a tie band names a scored axis and a gap between 0 and 1")
+ aside = change.get("outside", [])
+ if (not isinstance(aside, list) or any(a not in names[0] for a in aside) or
+ len(set(aside)) != len(aside) or len(aside) >= len(names[0])):
+ raise ValueError(
+ "axes outside the composite are scored axes, and not all of them")
+ members = change.get("parts")
+ if members is None and "outside" in change:
+ # the parts inherited from before must still hold every axis that is
+ # not beside the composite: an axis in neither has no place on the board
+ members = parts(prior)
+ if members is not None:
+ listed = ([a for part in members.values() for a in part] if isinstance(
+ members, dict) else [])
+ if not listed or sorted(listed) != sorted(
+ a for a in names[0] if a not in aside):
+ raise ValueError(
+ "the parts of a composite hold every axis inside it exactly"
+ " once")
+ declared = change.get("boards")
+ if declared is not None:
+ # each board is the mean of the parts it names; together they name
+ # every part exactly once, so no part is counted twice or dropped
+ of_parts = list((members if members is not None else
+ (parts(prior) or {})).keys())
+ named = ([p for board in declared.values() for p in board]
+ if isinstance(declared, dict) and declared and
+ all(declared.values()) else [])
+ if not named or sorted(named) != sorted(of_parts):
+ raise ValueError(
+ "the boards of a registry hold every part exactly once")
+ rule = change.get("assign", assignment(prior))
+ if rule is not None:
+ # the rule that sends each system to one board: stated or inherited, it
+ # must name the boards in force
+ _check_assignment(
+ rule, declared if declared is not None else boards(prior) or {})
+
+
+# what an assignment rule may read: a diagnostic of each system's score file
+ASSIGNABLE = ("band_above_input_db",)
+
+
+def _check_assignment(rule, declared: dict) -> None:
+ """Raises ValueError unless ``rule`` sends every system to one of the two
+ boards in force (see ``assignment``)."""
+ names = set(declared)
+ if (not isinstance(rule, dict) or
+ set(rule) != {"by", "above_db", "board", "otherwise"} or
+ rule["by"] not in ASSIGNABLE or
+ isinstance(rule["above_db"], bool) or
+ not isinstance(rule["above_db"], (int, float)) or
+ not math.isfinite(rule["above_db"]) or
+ rule["board"] == rule["otherwise"] or
+ {rule["board"], rule["otherwise"]} != names):
+ raise ValueError(
+ "an assignment reads one declared diagnostic against a threshold"
+ " and sends each system to one of the two boards in force")
+
+
+def parts(registry: dict) -> dict | None:
+ """Returns how the axes combine: {part: [axes]}, or None.
+
+ The parts come from the latest change that states them; the result is None
+ when no change does.
+
+ Without parts the composite is the mean of the axes, so adding an axis that
+ rewards removing takes weight from the axes that reward keeping. With parts
+ it is the mean of the parts, each the mean of its axes: what a system
+ removes, what it keeps and how the result sounds weigh the same however many
+ axes read each.
+ """
+ stated = [c["parts"] for c in registry.get("history", []) if c.get("parts")]
+ return {k: list(v) for k, v in stated[-1].items()} if stated else None
+
+
+def outside(registry: dict) -> list:
+ """Returns the axes scored and published beside the composite.
+
+ They come from the latest change that states them; the list is empty when
+ every axis is in the composite.
+
+ A row the task contracts keep out of the composite (a room, which the
+ denoising task leaves as recorded) can still be measured and shown for every
+ system: the axis says what each system does with it, and the composite says
+ nothing about it.
+ """
+ stated = [
+ c["outside"] for c in registry.get("history", []) if "outside" in c
+ ]
+ return list(stated[-1]) if stated else []
+
+
+def boards(registry: dict) -> dict | None:
+ """Returns {board: [parts]}: the scores the registry publishes side by side.
+
+ The boards come from the latest change that states them; None when the
+ registry publishes one composite of all its parts.
+
+ Each board is the mean of the parts it names, and together the boards name
+ every part exactly once: what a system removes, keeps and how it sounds
+ make one board, what it restores another, and no part is read twice.
+ """
+ stated = [
+ c["boards"] for c in registry.get("history", []) if c.get("boards")
+ ]
+ return {k: list(v) for k, v in stated[-1].items()} if stated else None
+
+
+def assignment(registry: dict) -> dict | None:
+ """Returns the rule that decides which board ranks a system, or None.
+
+ The rule comes from the latest change that states it: a system whose
+ diagnostic ``by`` (``band_above_input_db``, the most energy it puts above a
+ band-limited input's band) exceeds ``above_db`` is ranked on ``board``,
+ every other system on ``otherwise``. A system without that diagnostic is
+ ranked on neither. Every system is scored on every board; the rule only
+ says which board's score is its composite, and the boards rank the
+ full-band tier and the 16 kHz tier on the board that orders the table, so
+ a 16 kHz system the rule sends elsewhere is not ranked. None when the
+ registry publishes no boards or every system ranks on the first.
+ """
+ stated = [
+ c["assign"] for c in registry.get("history", []) if c.get("assign")
+ ]
+ return dict(stated[-1]) if stated else None
+
+
+def tie_bands(registry: dict) -> dict:
+ """Returns {axis: the gap under which two systems tie on it}.
+
+ The bands come from the latest change that states them.
+
+ A reporting policy, as the composite's own band is: an axis that stretches a
+ narrow range of a metric says so, and the board names the systems inside the
+ band instead of ordering them.
+ """
+ stated = [
+ c["tie_bands"]
+ for c in registry.get("history", [])
+ if c.get("tie_bands")
+ ]
+ return dict(stated[-1]) if stated else {}
+
+
+def replay(registry: dict) -> dict:
+ """Reproduce axes from the baseline and each versioned, evidenced change."""
+ if registry.get("schema_version") != 1:
+ raise ValueError("unsupported axis registry schema")
+ history = registry.get("history", [])
+ if not history or history[0].get("action") != "baseline":
+ raise ValueError("axis history must begin with an explicit baseline")
+ if len({r["version"] for r in history}) != len(history):
+ raise ValueError("every membership change requires a new axis version")
+ if registry.get("version") != history[-1]["version"]:
+ raise ValueError("axis version does not match the changelog")
+ views = copy.deepcopy(registry["baseline"])
+ if any(k in history[0]
+ for k in ("parts", "outside", "boards", "assign", "tie_bands")):
+ _check_layout(views, history[0], dict(registry, history=[]))
+ for index, change in enumerate(history[1:], 1):
+ report = change.get("evidence", {})
+ prior = dict(
+ registry,
+ version=history[index - 1]["version"],
+ history=history[:index],
+ )
+ if change.get("action") == "redefine":
+ _redefine(views, change, prior)
+ continue
+ if change.get("action") == "revise":
+ _revise(views, change, prior)
+ continue
+ if report.get("axis_sha256") != anchors.digest(prior):
+ raise ValueError(
+ "membership evidence belongs to another registry history")
+ if (change.get("panel_run") != report.get("panel_run") or
+ change.get("study_id") != report.get("study_id") or
+ not change.get("reason") or not change.get("study_id")):
+ raise ValueError(
+ "membership changes require named panel and listening evidence")
+ proposal = report.get("row", {})
+ target = views[proposal["view"]][proposal["tier"]][proposal["axis"]]
+ row = [proposal[k] for k in ("condition", "metric", "direction")]
+ action = change.get("action")
+ if action in ("admit", "replace"):
+ if not _valid_decision(report) or not _intact(report):
+ raise ValueError(
+ "admission evidence is incomplete or was modified")
+ if row in target:
+ raise ValueError("row is already in the axis")
+ if action == "replace":
+ old = proposal.get("replaces")
+ if old not in target:
+ raise ValueError(
+ "replacement does not identify an existing row")
+ target.remove(old)
+ elif proposal.get("replaces"):
+ raise ValueError(
+ "a replacement must be recorded as a replacement")
+ target.append(row)
+ elif action == "promote":
+ before_aside, before_parts = outside(prior), parts(prior) or {}
+ axis, part = change.get("axis"), change.get("part")
+ moved = {
+ k: list(v) + ([axis] if k == part else [])
+ for k, v in before_parts.items()
+ }
+ if (not _promotable(report) or row not in target or
+ proposal.get("axis") != axis or axis not in before_aside or
+ part not in before_parts or change.get("outside")
+ != [a for a in before_aside if a != axis] or
+ change.get("parts") != moved or
+ change.get("decided_by") != "maintainer" or
+ not change.get("note")):
+ raise ValueError(
+ "a promotion moves one axis scored beside the composite"
+ " into one existing part, on an intact review that passed"
+ " every check, and changes nothing else")
+ elif action == "remove":
+ if not _valid_removal(report, proposal):
+ raise ValueError(
+ "removal needs two consecutive failed panels after a set"
+ " change")
+ if row not in target or len(target) == 1:
+ raise ValueError("cannot remove an absent row or empty an axis")
+ target.remove(row)
+ else:
+ raise ValueError("unsupported membership change")
+ return views
+
+
+def load(path: str | pathlib.Path = DEFAULT) -> dict:
+ """Read a registry and validate its entire membership history."""
+ registry = json.loads(pathlib.Path(path).read_text(encoding="utf-8"))
+ replay(registry)
+ return registry
+
+
+def _grouped(rows: list, metadata: dict, condition: str, metric: str,
+ direction: int) -> dict:
+ """Returns {speech source: mean signed value} of one row of a system."""
+ groups = {}
+ for record in rows:
+ if record["condition"] != condition:
+ continue
+ v = compare.value(record, metric, metadata)
+ if math.isfinite(v):
+ groups.setdefault(record["speech_source"], []).append(direction * v)
+ return {k: float(np.mean(v)) for k, v in groups.items()}
+
+
+def _axis_and_row(entry) -> tuple:
+ """Returns (axis, row) of a redundancy entry: ``[axis, [condition, metric,
+ direction]]`` names the axis the row sits in; a bare row has none."""
+ if (len(entry) == 2 and isinstance(entry[0], str) and
+ isinstance(entry[1], (list, tuple))):
+ return entry[0], list(entry[1])
+ return None, list(entry)
+
+
+def _correlation(systems: dict, proposal: dict, existing: list) -> dict:
+ pairs = []
+ for metadata, rows in systems.values():
+ a = _grouped(rows, metadata, proposal["condition"], proposal["metric"],
+ proposal["direction"])
+ b = _grouped(rows, metadata, *existing)
+ pairs.extend((a[k], b[k]) for k in sorted(set(a) & set(b)))
+ if len(pairs) < 20:
+ return {"row": existing, "n_pairs": len(pairs), "abs_correlation": None}
+ array = np.asarray(pairs)
+ if np.std(array[:, 0]) == 0 or np.std(array[:, 1]) == 0:
+ return {"row": existing, "n_pairs": len(pairs), "abs_correlation": None}
+ return {
+ "row": existing,
+ "n_pairs": len(pairs),
+ "abs_correlation": float(abs(np.corrcoef(array.T)[0, 1])),
+ }
+
+
+def evaluate(
+ panel: dict,
+ systems: dict,
+ proposal: dict,
+ registry: dict,
+ policy: dict,
+ study: dict | None,
+ n_boot: int = 2000,
+ seed: int = 0,
+ review_existing: bool = False,
+ redundancy_rows: list | None = None,
+) -> dict:
+ """Evaluate E1–E4; missing human or redundancy evidence admits no row.
+
+ ``review_existing`` reviews a row already in the axis (for a removal or a
+ promotion) and never admits it. Redundancy (E3) is read against
+ ``redundancy_rows`` when given (a promotion: every row the composite reads,
+ each as ``[axis, row]`` so that the same measurement in another axis counts)
+ and otherwise against the axis's rows, never against the row itself.
+ """
+ limits = registry["policy"]
+ replayed = replay(registry)
+ current = replayed[proposal["view"]][proposal["tier"]][proposal["axis"]]
+ condition = proposal["condition"]
+ metric = proposal["metric"]
+ direction = proposal["direction"]
+ if [condition, metric, direction] in current and not review_existing:
+ raise ValueError("candidate row already belongs to the axis")
+ roster = panel.get("roster", {})
+ if (not roster.get("sha256") or not roster.get("systems") or
+ set(panel["ranked_systems"]) != set(roster["systems"])):
+ raise ValueError(
+ "coverage must include the entire pinned published roster")
+ base, regression, null = (
+ systems[panel[k]] for k in ("baseline", "regression", "null"))
+ for dataset in systems.values():
+ compare.aligned(dataset, base)
+ identity = base[0]
+ expected = anchors.stamp(policy)
+ if (identity.get("anchors_version") != expected["_anchors_version"] or
+ identity.get("anchors_sha256") != expected["_anchors_sha256"]):
+ raise ValueError(
+ "panel anchor version differs from the admission policy")
+ regression_result = compare.paired(regression, base, condition, metric,
+ direction, n_boot, seed)
+ null_result = compare.paired(null, base, condition, metric, direction,
+ n_boot, seed)
+ e1 = (regression_result["ci95"][1] < 0 and
+ null_result["ci95"][0] <= 0 <= null_result["ci95"][1] and
+ regression_result["groups_verified"] and
+ null_result["groups_verified"] and
+ regression_result["cluster_counts"][0] >= limits["min_source_groups"]
+ and all(r["matched_cohort"] and r["n_paired"] >= limits["min_items"]
+ for r in (regression_result, null_result)))
+ human = None
+ if study is not None:
+ if (study.get("set_id") != identity["set_id"] or
+ study.get("condition") != condition):
+ raise ValueError(
+ "listening study does not match the panel set and condition")
+ for role, dataset in (("baseline", base), ("regression", regression)):
+ model = dataset[0].get("render_identity", {}).get("weights_sha256")
+ if not model or study.get(f"{role}_sha256") != model:
+ raise ValueError(
+ "listening study checkpoint identity does not match the"
+ " panel")
+ candidates = {
+ r["id"]: r for r in base[1] if r["condition"] == condition
+ }
+ ratings = study.get("ratings", [])
+ seen = set()
+ for rating in ratings:
+ if rating.get("item_id") not in candidates or rating.get(
+ "preference") not in (-1, 0, 1):
+ raise ValueError(
+ "listening rating has an unknown item or invalid preference"
+ )
+ key = (rating["item_id"], rating.get("listener"))
+ if not key[1] or key in seen:
+ raise ValueError(
+ "listening ratings need distinct item/listener pairs")
+ seen.add(key)
+ if (len({r["item_id"] for r in ratings}) >= limits["min_human_items"]
+ and len({r["listener"] for r in ratings}) >= 2):
+ values = np.array([r["preference"] for r in ratings])
+ groups = [[candidates[r["item_id"]].get(k)
+ for r in ratings]
+ for k in compare.GROUPS]
+ groups.append([r["listener"] for r in ratings])
+ human = compare.interval(
+ lambda w: (float(w @ values / w.sum())
+ if w.sum() else float("nan")),
+ groups,
+ n_boot,
+ seed,
+ )
+ e2 = human is not None and human["ci95"][1] < 0
+ own = [condition, metric, direction]
+ compared = []
+ for entry in (current if redundancy_rows is None else redundancy_rows):
+ axis, row = _axis_and_row(entry)
+ # the candidate's own row is left out; the same measurement in another
+ # axis of the composite is a duplicate and stays in
+ if row == own and axis in (None, proposal.get("axis")):
+ continue
+ compared.append(row)
+ redundancy = [_correlation(systems, proposal, row) for row in compared]
+ replacement = proposal.get("replaces")
+ e3 = bool(redundancy) and all(r["abs_correlation"] is not None and (
+ (r["abs_correlation"] >= limits["max_redundancy"]) if r["row"] ==
+ replacement else (r["abs_correlation"] < limits["max_redundancy"]))
+ for r in redundancy)
+ if replacement is not None and replacement not in [
+ list(r) for r in current
+ ]:
+ e3 = False
+ coverage = {}
+ for name in panel["ranked_systems"]:
+ metadata, rows = systems[name]
+ selected = [r for r in rows if r["condition"] == condition]
+ coverage[anchors.digest(name)] = sum(
+ math.isfinite(compare.value(r, metric, metadata)) and
+ r.get("groups_verified", False) for r in selected)
+ try:
+ rule = anchors.rule_for(policy, condition, metric)
+ anchored = rule["direction"] == direction
+ except ValueError:
+ anchored = False
+ e4 = (bool(coverage) and
+ all(n >= limits["min_items"] for n in coverage.values()) and anchored)
+ checks = {"E1": bool(e1), "E2": bool(e2), "E3": bool(e3), "E4": bool(e4)}
+ result = {
+ "schema_version":
+ 1,
+ "row":
+ proposal,
+ "set_id":
+ identity["set_id"],
+ "anchors_version":
+ policy["version"],
+ "anchors_sha256":
+ anchors.digest(policy),
+ "axis_version":
+ registry["version"],
+ "axis_sha256":
+ anchors.digest(registry),
+ "panel_run":
+ anchors.digest({
+ "panel": panel,
+ "identities": {
+ role: systems[panel[role]][0]
+ for role in ("baseline", "regression", "null")
+ },
+ }),
+ "study_id":
+ anchors.digest(study) if study is not None else None,
+ "regression":
+ regression_result,
+ "null":
+ null_result,
+ "human":
+ human,
+ "redundancy":
+ redundancy,
+ "coverage":
+ coverage,
+ "checks":
+ checks,
+ "roster_sha256":
+ roster["sha256"],
+ "sequence":
+ panel.get("sequence"),
+ "admitted":
+ all(checks.values()) and not review_existing,
+ }
+ result["evidence_sha256"] = anchors.digest(result)
+ return result
+
+
+def record_change(registry: dict, report: dict, version: str,
+ reason: str) -> dict:
+ """Stage an admitted membership change.
+
+ The change carries its exact panel/study evidence.
+ """
+ if (not _valid_decision(report) or
+ report.get("axis_sha256") != anchors.digest(registry) or
+ report.get("axis_version") != registry["version"]):
+ raise ValueError(
+ "decision is not admitted or belongs to another axis registry")
+ if (not version or version in {r["version"] for r in registry["history"]} or
+ not reason):
+ raise ValueError("a new unique version and a reason are required")
+ result = copy.deepcopy(registry)
+ result["version"] = version
+ result["history"].append({
+ "version": version,
+ "action": "replace" if report["row"].get("replaces") else "admit",
+ "reason": reason,
+ "panel_run": report["panel_run"],
+ "study_id": report["study_id"],
+ "evidence": report,
+ })
+ replay(result)
+ return result
+
+
+def record_redefinition(registry: dict, axis: str, rows: dict, version: str,
+ reason: str, note: str) -> dict:
+ """Stage a maintainer's redefinition of one axis against the live registry.
+
+ Args:
+ registry: The live axis registry.
+ axis: The axis whose meaning changes.
+ rows: {tier: [[condition, metric, direction], ...]}, the complete rows
+ of every tier.
+ version: A new, unique membership version.
+ reason: Changelog rationale.
+ note: Repository path of the public note showing the board under both
+ definitions.
+
+ Returns:
+ The registry with the change appended, already replayed.
+ """
+ if not version or version in {r["version"] for r in registry["history"]}:
+ raise ValueError("a new unique version is required")
+ result = copy.deepcopy(registry)
+ result["version"] = version
+ result["history"].append({
+ "version": version,
+ "action": "redefine",
+ "axis": axis,
+ "rows": rows,
+ "reason": reason,
+ "decided_by": "maintainer",
+ "note": note,
+ "panel_run": None,
+ "study_id": None,
+ "axis_sha256": anchors.digest(registry),
+ })
+ replay(result)
+ return result
+
+
+def record_revision(
+ registry: dict,
+ axes: dict,
+ version: str,
+ reason: str,
+ note: str,
+ members: dict | None = None,
+ bands: dict | None = None,
+ aside: list | None = None,
+ published: dict | None = None,
+ assign: dict | None = None,
+) -> dict:
+ """Stage a maintainer's revision of the composite against the live registry.
+
+ Args:
+ registry: The live axis registry.
+ axes: {view: {tier: {axis: [[condition, metric, direction], ...]}}}, the
+ complete rows of every axis that changes or is new; ``{}`` when the
+ revision only moves axes into or out of the composite (``members``
+ and ``aside``).
+ version: A new, unique membership version.
+ reason: Changelog rationale.
+ note: Repository path of the public note showing the board under both
+ definitions.
+ members: {part: [axes]} when the revision states how the axes combine.
+ bands: {axis: tie band} when the revision declares one.
+ aside: The axes scored beside the composite, not in it, when the
+ revision states them.
+ published: {board: [parts]} when the revision states which scores the
+ registry publishes side by side (see ``boards``).
+ assign: The rule that decides which board ranks a system, when the
+ revision states it (see ``assignment``).
+
+ Returns:
+ The registry with the change appended, already replayed.
+ """
+ if not version or version in {r["version"] for r in registry["history"]}:
+ raise ValueError("a new unique version is required")
+ result = copy.deepcopy(registry)
+ result["version"] = version
+ change = {
+ "version": version,
+ "action": "revise",
+ "axes": axes,
+ "reason": reason,
+ "decided_by": "maintainer",
+ "note": note,
+ "panel_run": None,
+ "study_id": None,
+ "axis_sha256": anchors.digest(registry),
+ }
+ if members is not None:
+ change["parts"] = members
+ if bands is not None:
+ change["tie_bands"] = bands
+ if aside is not None:
+ change["outside"] = aside
+ if published is not None:
+ change["boards"] = published
+ if assign is not None:
+ change["assign"] = assign
+ result["history"].append(change)
+ replay(result)
+ return result
+
+
+def record_promotion(registry: dict, report: dict, part: str, version: str,
+ reason: str, note: str) -> dict:
+ """Stage the promotion of an axis scored beside the composite into a part.
+
+ The axis's row was reviewed on a panel and a listening study
+ (``evaluate(..., review_existing=True)``, redundancy read against every row
+ the composite reads) and passed all four checks. The change carries that
+ evidence; the axis leaves ``outside`` and joins ``part``; no row changes.
+
+ Raises:
+ ValueError: The review did not pass, was modified or belongs to another
+ registry; the axis is not beside the composite; the part does not
+ exist; the version is not new; the reason or the note is missing.
+ """
+ axis = (report.get("row") or {}).get("axis")
+ aside, members = outside(registry), parts(registry) or {}
+ if (not _promotable(report) or
+ report.get("axis_sha256") != anchors.digest(registry) or
+ report.get("axis_version") != registry["version"]):
+ raise ValueError(
+ "the review did not pass every check, was modified, or belongs to"
+ " another axis registry")
+ if axis not in aside or part not in members:
+ raise ValueError("only an axis scored beside the composite is promoted,"
+ " into an existing part")
+ if (not version or version in {r["version"] for r in registry["history"]} or
+ not reason or not note):
+ raise ValueError(
+ "a new unique version, a reason and a public note are required")
+ result = copy.deepcopy(registry)
+ result["version"] = version
+ result["history"].append({
+ "version": version,
+ "action": "promote",
+ "axis": axis,
+ "part": part,
+ "reason": reason,
+ "decided_by": "maintainer",
+ "note": note,
+ "panel_run": report["panel_run"],
+ "study_id": report["study_id"],
+ "evidence": report,
+ "parts": {
+ k: list(v) + ([axis] if k == part else [])
+ for k, v in members.items()
+ },
+ "outside": [a for a in aside if a != axis],
+ })
+ replay(result)
+ return result
+
+
+def record_removal(
+ registry: dict,
+ failures: list[dict],
+ previous_set_id: str,
+ version: str,
+ reason: str,
+) -> dict:
+ """Stage a removal backed by two sequential failures.
+
+ The failures come after a set replacement.
+ """
+ if (len(failures) != 2 or not version or not reason or
+ version in {r["version"] for r in registry["history"]}):
+ raise ValueError(
+ "removal requires two reports, a new version, and a reason")
+ report = {
+ "axis_sha256": anchors.digest(registry),
+ "row": failures[0]["row"],
+ "failures": failures,
+ "previous_set_id": previous_set_id,
+ "study_id": failures[-1].get("study_id"),
+ "panel_run": failures[-1].get("panel_run"),
+ }
+ report["evidence_sha256"] = anchors.digest(report)
+ result = copy.deepcopy(registry)
+ result["version"] = version
+ result["history"].append({
+ "version": version,
+ "action": "remove",
+ "reason": reason,
+ "panel_run": report["panel_run"],
+ "study_id": report["study_id"],
+ "evidence": report,
+ })
+ replay(result)
+ return result
+
+
+def main() -> None:
+ """Produce a reviewable decision.
+
+ Absence of a study writes a rejected decision.
+ """
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--panel",
+ required=True,
+ help="private panel configuration")
+ parser.add_argument(
+ "--board",
+ required=True,
+ help=("the published board (leaderboard.py --json-out), the roster"
+ " snapshot used for coverage and redundancy"),
+ )
+ parser.add_argument("--row", required=True, help="proposed row JSON")
+ parser.add_argument("--study", help="human paired-preference study JSON")
+ parser.add_argument("--axes", default=str(DEFAULT))
+ parser.add_argument("--anchors", default=str(anchors.DEFAULT))
+ parser.add_argument("--out", required=True)
+ parser.add_argument("--bootstrap", type=int, default=2000)
+ parser.add_argument("--review-existing", action="store_true")
+ parser.add_argument("--registry-out",
+ help="stage the admitted registry at this path")
+ parser.add_argument("--version",
+ help="new membership version when staging a change")
+ parser.add_argument("--reason",
+ help="changelog rationale when staging a change")
+ parser.add_argument(
+ "--promote-into",
+ default="",
+ help=("review the row of an axis scored beside the composite and, when"
+ " it passes, stage its axis's promotion into this part"))
+ parser.add_argument("--note",
+ default="bench/METRICS.md",
+ help="public note of a promotion")
+ args = parser.parse_args()
+ panel = json.loads(pathlib.Path(args.panel).read_text(encoding="utf-8"))
+ board = json.loads(pathlib.Path(args.board).read_text(encoding="utf-8"))
+ panel["roster"] = {
+ "sha256":
+ anchors.digest(board),
+ "systems":
+ sorted(
+ n for n, r in board["systems"].items()
+ if r.get("composite") is not None and r.get("tier") in ("full",
+ "nb")),
+ }
+ names = set(panel["ranked_systems"]) | {
+ panel[k] for k in ("baseline", "regression", "null")
+ }
+ systems = {
+ n: compare.load_system(panel["results"], n) for n in sorted(names)
+ }
+ if any(d[0].get("sealed") for d in systems.values()):
+ raise SystemExit(
+ "sealed confirmation material cannot be used to select axis"
+ " membership")
+ proposal = json.loads(pathlib.Path(args.row).read_text(encoding="utf-8"))
+ registry = load(args.axes)
+ against = None
+ if args.promote_into:
+ tier = replay(registry)[proposal["view"]][proposal["tier"]]
+ against = [[axis, row]
+ for part in (parts(registry) or {}).values()
+ for axis in part
+ for row in tier.get(axis, [])]
+ result = evaluate(
+ panel,
+ systems,
+ proposal,
+ registry,
+ anchors.definitions(args.anchors),
+ json.loads(pathlib.Path(args.study).read_text(
+ encoding="utf-8")) if args.study else None,
+ args.bootstrap,
+ review_existing=args.review_existing or bool(args.promote_into),
+ redundancy_rows=against,
+ )
+ anchors.atomic_json(args.out, result)
+ if args.registry_out:
+ staged = (record_promotion(registry, result, args.promote_into,
+ args.version, args.reason, args.note)
+ if args.promote_into else record_change(
+ registry, result, args.version, args.reason))
+ anchors.atomic_json(args.registry_out, staged)
+ print(
+ json.dumps({
+ "admitted": result["admitted"],
+ "checks": result["checks"]
+ }))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/bench/scripts/anchors.py b/bench/scripts/anchors.py
new file mode 100644
index 0000000..ee7fb94
--- /dev/null
+++ b/bench/scripts/anchors.py
@@ -0,0 +1,557 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Versioned, roster-independent calibration for benchmark composites.
+
+``anchors.json`` declares policy. ``anchors.resolved.json`` in a results
+directory freezes its set-derived endpoints and deletion cohort. Removing an
+INPUT, REF, or competitor score file after calibration cannot move a score.
+"""
+
+import argparse
+import hashlib
+import json
+import math
+import os
+import pathlib
+from typing import Any
+
+DEFAULT = pathlib.Path(
+ os.environ.get("BENCH_ANCHORS",
+ pathlib.Path(__file__).resolve().parents[1] /
+ "anchors.json"))
+RESOLVED = "anchors.resolved.json"
+
+
+def digest(value: Any) -> str:
+ """Return the digest of canonical, finite JSON data."""
+ data = json.dumps(value,
+ sort_keys=True,
+ separators=(",", ":"),
+ allow_nan=False)
+ return hashlib.sha256(data.encode()).hexdigest()
+
+
+def atomic_json(path: str | pathlib.Path, value: Any) -> None:
+ """Replace a JSON artifact only after its full serialization succeeds."""
+ path = pathlib.Path(path)
+ encoded = json.dumps(value, indent=2, allow_nan=False) + "\n"
+ path.parent.mkdir(parents=True, exist_ok=True)
+ temporary = path.with_name(f".{path.name}.{os.getpid()}.tmp")
+ try:
+ temporary.write_text(encoded, encoding="utf-8")
+ os.replace(temporary, path)
+ finally:
+ temporary.unlink(missing_ok=True)
+
+
+def definitions(path: str | pathlib.Path = DEFAULT) -> dict:
+ """Read and validate declared anchors without loading audio libraries."""
+ data = json.loads(pathlib.Path(path).read_text(encoding="utf-8"))
+ if data.get("schema_version") != 1 or not isinstance(
+ data.get("version"), str):
+ raise ValueError("unsupported anchor schema or missing anchor version")
+ changes = data.get("changelog", [])
+ if not changes or changes[-1].get("version") != data["version"]:
+ raise ValueError("anchor version needs a changelog entry")
+ if len({r["version"] for r in changes}) != len(changes):
+ raise ValueError("anchor versions must be unique")
+ gap = data.get("minimum_gap")
+ if not isinstance(gap, (int, float)) or not math.isfinite(gap) or gap <= 0:
+ raise ValueError("minimum_gap must be finite and positive")
+ seen = set()
+ for rule in data["rules"]:
+ if rule["direction"] not in (-1, 1):
+ raise ValueError("anchor direction must be -1 or 1")
+ for endpoint in (rule["floor"], rule["ceiling"]):
+ if not endpoint.get("rationale") or ("source"
+ in endpoint) == ("value"
+ in endpoint):
+ raise ValueError(
+ "each anchor needs one value or source and a rationale")
+ if "source" in endpoint and endpoint["source"] not in (
+ "INPUT",
+ "REF",
+ ):
+ raise ValueError(
+ "anchors may only depend on INPUT, REF, or constants")
+ for key in ("value", "fallback"):
+ if key in endpoint and (isinstance(endpoint[key], bool) or
+ not isinstance(endpoint[key],
+ (int, float)) or
+ not math.isfinite(endpoint[key])):
+ raise ValueError("anchor constants must be finite numbers")
+ verify = endpoint.get("verify")
+ if verify is not None:
+ if "value" not in endpoint or verify.get("source") not in (
+ "INPUT",
+ "REF",
+ ):
+ raise ValueError(
+ "verify checks a declared value against INPUT or REF")
+ tolerance = verify.get("tolerance")
+ if (isinstance(tolerance, bool) or
+ not isinstance(tolerance, (int, float)) or
+ not math.isfinite(tolerance) or tolerance <= 0):
+ raise ValueError("verify needs a finite positive tolerance")
+ span = endpoint.get("range")
+ if span is not None:
+ if ("value" not in endpoint or len(span) != 2 or not all(
+ isinstance(v, (int, float)) and math.isfinite(v)
+ for v in span) or
+ not span[0] <= endpoint["value"] <= span[1]):
+ raise ValueError(
+ "range must be a finite [low, high] containing the"
+ " declared value")
+ for condition in rule["conditions"]:
+ for metric in rule["metrics"]:
+ key = row_key(condition, metric)
+ if key in seen:
+ raise ValueError(f"duplicate anchor definition: {key}")
+ seen.add(key)
+ return data
+
+
+def reference_conditions(path: str | pathlib.Path = DEFAULT) -> set[str]:
+ """Returns the conditions the REF row must be scored on.
+
+ Every rule with an endpoint measured from REF, or with a declared value
+ verified against it.
+ """
+ return {
+ condition for rule in definitions(path)["rules"] if any("REF" in (
+ rule[side].get("source"),
+ (rule[side].get("verify") or {}).get("source"),
+ ) for side in ("floor", "ceiling")) for condition in rule["conditions"]
+ }
+
+
+def stamp(policy: dict | None = None) -> dict:
+ """Returns the normalization identity to stamp on newly computed scores."""
+ policy = definitions() if policy is None else policy
+ return {
+ "_anchors_version": policy["version"],
+ "_anchors_sha256": digest(policy),
+ }
+
+
+def row_key(condition: str, metric: str) -> str:
+ """Return an unambiguous condition/metric identity."""
+ return json.dumps([condition, metric], separators=(",", ":"))
+
+
+def rule_for(policy: dict, condition: str, metric: str) -> dict:
+ """Find the declared rule for one sub-metric, failing on undeclared rows."""
+ for rule in policy["rules"]:
+ if condition in rule["conditions"] and metric in rule["metrics"]:
+ return rule
+ raise ValueError(f"no anchors declared for {condition}/{metric}")
+
+
+def _endpoint(
+ endpoint: dict,
+ systems: dict,
+ condition: str,
+ metric: str,
+ verify: bool = True,
+) -> float:
+ if "value" in endpoint:
+ check = endpoint.get("verify")
+ # a declared endpoint the set must agree with
+ if check is not None and verify:
+ measured = _endpoint({"source": check["source"]}, systems,
+ condition, metric)
+ if abs(measured - endpoint["value"]) > check["tolerance"]:
+ raise ValueError(
+ f"declared anchor {endpoint['value']} for"
+ f" {condition}/{metric} is"
+ f" {abs(measured - endpoint['value']):.3f} from"
+ f" {check['source']}'s measured {measured:.3f} (tolerance"
+ f" {check['tolerance']}): fix the set or declare a new"
+ " anchor version")
+ return float(endpoint["value"])
+ name = endpoint["source"]
+ record = systems.get(name, {}).get(condition, {})
+ value = record.get(metric)
+ count = record.get("metric_counts", {}).get(metric, record.get("n", 0))
+ if count < 20 or not isinstance(value, (int, float)):
+ raise ValueError(
+ f"missing measured anchor {name}: {condition}/{metric}")
+ if not math.isfinite(value):
+ raise ValueError(
+ f"nonfinite measured anchor {name}: {condition}/{metric}; repair"
+ " scoring")
+ return float(value)
+
+
+def resolve(
+ policy: dict,
+ systems: dict,
+ axes: dict,
+ sealed: bool = False,
+ parent: dict | None = None,
+) -> dict:
+ """Freeze endpoints and the INPUT-defined cohort for one set and subset.
+
+ Args:
+ policy: Validated anchor definitions.
+ systems: Loaded, level-calibrated INPUT and REF scores.
+ axes: Tier-to-axis-to-sub-metric definitions for the selected view.
+ sealed: Whether this calibration belongs to sealed data, which is never
+ published.
+ parent: For a development panel, the frozen whole-set calibration of the
+ build it is drawn from. The declared endpoints were verified there
+ against every item; a panel inherits that verification instead of
+ repeating it on its few items, and records which calibration it
+ inherits.
+
+ Returns:
+ A self-identifying calibration with no dependence on competitors.
+ """
+ identities = {systems.get(n, {}).get("_set_id") for n in ("INPUT", "REF")}
+ subsets = {
+ systems.get(n, {}).get("_subset", "all") for n in ("INPUT", "REF")
+ }
+ if len(identities) != 1 or None in identities or len(subsets) != 1:
+ raise ValueError("INPUT and REF must identify the same set and subset")
+ if parent is not None and (parent.get("set_id") != next(iter(identities)) or
+ parent.get("subset") != "all" or
+ parent.get("anchors_sha256") != digest(policy) or
+ parent.get("sealed") != sealed):
+ raise ValueError(
+ "a panel inherits only the whole-set calibration of its own build, "
+ "policy and scope")
+ scopes = {bool(systems[n].get("_sealed")) for n in ("INPUT", "REF")}
+ if len(scopes) != 1:
+ raise ValueError("INPUT and REF disagree on private/public scope")
+ # the scorers both rows were read by must be one implementation each; REF
+ # has no deletion sidecar (real recordings have no clean reference)
+ input_scorers = systems["INPUT"].get("_scorers") or {}
+ ref_scorers = systems["REF"].get("_scorers") or {}
+ differ = sorted(k for k in set(input_scorers) & set(ref_scorers)
+ if input_scorers[k] != ref_scorers[k])
+ if differ:
+ raise ValueError(
+ "INPUT and REF were scored by different implementations"
+ f" ({', '.join(differ)})")
+ sealed = sealed or next(iter(scopes))
+ points = {}
+ for axis in axes.values():
+ for rows in axis.values():
+ for condition, metric, direction in rows:
+ key = row_key(condition, metric)
+ if key in points:
+ continue
+ rule = rule_for(policy, condition, metric)
+ if rule["direction"] != direction:
+ raise ValueError(
+ f"axis/anchor direction mismatch for {key}")
+ low = _endpoint(rule["floor"], systems, condition, metric,
+ parent is None)
+ high = _endpoint(rule["ceiling"], systems, condition, metric,
+ parent is None)
+ fallbacks = []
+ for side in ("floor", "ceiling"):
+ if direction * (high - low) > policy["minimum_gap"]:
+ break
+ if "fallback" in rule[side]:
+ if side == "floor":
+ low = float(rule[side]["fallback"])
+ else:
+ high = float(rule[side]["fallback"])
+ fallbacks.append(side)
+ if direction * (high - low) <= policy["minimum_gap"]:
+ raise ValueError(
+ f"degenerate anchors for {key}; declare a new policy")
+ points[key] = {
+ "floor": low,
+ "ceiling": high,
+ "direction": direction,
+ "fallbacks": fallbacks,
+ }
+ items = systems["INPUT"].get("_deletion", {}).get("items", {})
+ cohort = {}
+ for uid, counts in sorted(items.items()):
+ # bool is an int subclass, and a flag is not a count
+ if (len(counts) != 2 or counts[0] != 0 or isinstance(counts[1], bool) or
+ not isinstance(counts[1], int) or counts[1] <= 0):
+ raise ValueError(
+ "INPUT deletion cohort must have positive counts and zero"
+ " deletions")
+ cohort[uid] = counts[1]
+ if not cohort:
+ raise ValueError(
+ "INPUT needs a primary-anchored realx sidecar to freeze the cohort")
+ data = {
+ "schema_version": 1,
+ "anchors_version": policy["version"],
+ "anchors_sha256": digest(policy),
+ "set_id": next(iter(identities)),
+ "subset": next(iter(subsets)),
+ "sealed": sealed,
+ "points": points,
+ "axes_sha256": digest(axes),
+ "deletion_cohort": cohort,
+ "cohort_sha256": digest(cohort),
+ # the implementations whose INPUT and REF scores fixed the endpoints: a
+ # board read by another scorer is not on this scale
+ "scorers": systems["INPUT"].get("_scorers") or {},
+ }
+ if parent is not None:
+ data["inherits"] = parent["calibration_sha256"]
+ data["calibration_sha256"] = digest(data)
+ return data
+
+
+def load(path: str | pathlib.Path, policy: dict | None = None) -> dict:
+ """Returns the frozen calibration read from ``path``.
+
+ Refuses version, definition, or content drift.
+ """
+ policy = definitions() if policy is None else policy
+ data = json.loads(pathlib.Path(path).read_text(encoding="utf-8"))
+ if data.get("anchors_version") != policy["version"] or data.get(
+ "anchors_sha256") != digest(policy):
+ raise ValueError(
+ "anchor version/definition mismatch; recalibrate under a new"
+ " version")
+ expected = digest({
+ k: v for k, v in data.items() if k != "calibration_sha256"
+ })
+ if data.get("calibration_sha256") != expected:
+ raise ValueError("calibration contents do not match their digest")
+ return data
+
+
+def validate_scores(calibration: dict, systems: dict) -> None:
+ """Refuse scores that do not match the calibration.
+
+ These are scores from another set, subset, anchor policy or scorer
+ implementation than the calibration's.
+ """
+ bound = calibration.get("scorers") or {}
+ for name, score in systems.items():
+ mine = score.get("_scorers") or {}
+ differ = [
+ k for k, v in bound.items() if v and mine.get(k) and mine[k] != v
+ ]
+ if differ:
+ raise ValueError(
+ f"{name}: scored by another implementation than the"
+ f" calibration's ({', '.join(differ)}): re-score, or"
+ " recalibrate")
+ if (score.get("_set_id") != calibration["set_id"] or
+ score.get("_subset", "all") != calibration["subset"]):
+ raise ValueError(
+ f"{name}: score set/subset differs from calibration")
+ if (score.get("_anchors_version") != calibration["anchors_version"] or
+ score.get("_anchors_sha256") != calibration["anchors_sha256"]):
+ raise ValueError(
+ f"{name}: anchor version mismatch or unstamped legacy scores")
+
+
+def normalize(value: float, point: dict) -> float:
+ """Returns the fraction of a declared metric gap closed.
+
+ The fraction is saturated to [0, 1].
+ """
+ if not math.isfinite(value):
+ return float("nan")
+ fraction = (value - point["floor"]) / (point["ceiling"] - point["floor"])
+ return min(1.0, max(0.0, fraction))
+
+
+def composite(scores: dict, members: dict | None,
+ aside: tuple | list = ()) -> float:
+ """Returns the composite of one system's axis scores.
+
+ It is nan unless every axis is present.
+
+ Args:
+ scores: {axis: score in 0-1}, the axes beside the composite included.
+ members: ``parts`` of the registry, or None for the plain mean of the
+ axes inside.
+ aside: The axes scored beside the composite, which it does not read.
+ """
+ values = list(scores.values())
+ if not values or not all(
+ isinstance(v, (int, float)) and math.isfinite(v) for v in values):
+ return float("nan")
+ inside = {a: v for a, v in scores.items() if a not in aside}
+ if not inside:
+ return float("nan")
+ if not members:
+ return sum(inside.values()) / len(inside)
+ if sorted(a for part in members.values() for a in part) != sorted(inside):
+ raise ValueError(
+ "the parts of the composite do not hold the scored axes inside it")
+ return sum(
+ sum(inside[a]
+ for a in part) / len(part)
+ for part in members.values()) / len(members)
+
+
+def part_scores(scores: dict, members: dict | None) -> dict:
+ """Returns {part: mean of its axes} for one system.
+
+ It is empty without parts; a part is nan where one of its axes is.
+ """
+ return {
+ name: (
+ sum(scores[a]
+ for a in part) /
+ len(part) if all(
+ isinstance(scores.get(a), (int,
+ float)) and math.isfinite(scores[a])
+ for a in part) else float("nan")
+ ) for name, part in (members or {}).items()
+ }
+
+
+def migrate(results: str | pathlib.Path, previous: str, policy: dict) -> int:
+ """Re-stamp the results computed under anchor version ``previous``.
+
+ That covers every score file and item-record header computed under it.
+
+ A score file holds raw measurements; the anchor policy only scales them. A
+ policy change therefore needs no re-scoring, but it must be explicit: the
+ previous version is recorded in ``_anchors_migrated_from`` and the frozen
+ calibration of that version is removed so a new one is resolved. Files
+ stamped with any other version are left alone and will be refused.
+ """
+ identity, count = stamp(policy), 0
+ for path in sorted(pathlib.Path(results).glob("*.json")):
+ if path.name == RESOLVED:
+ continue
+ data = json.loads(path.read_text())
+ if (not isinstance(data, dict) or
+ data.get("_anchors_version") != previous):
+ continue
+ data.update(identity)
+ data["_anchors_migrated_from"] = list(
+ data.get("_anchors_migrated_from", [])) + [previous]
+ # a score file keeps the form its scorer gave it: one space of indent,
+ # and nan where a measurement is missing (the board reads it as missing)
+ temporary = path.with_name(f".{path.name}.{os.getpid()}.tmp")
+ temporary.write_text(json.dumps(data, indent=1))
+ temporary.replace(path)
+ count += 1
+ for path in sorted(pathlib.Path(results).glob("*.items.jsonl")):
+ lines = path.read_text().splitlines(keepends=True)
+ head = json.loads(lines[0]) if lines else {}
+ if head.get("anchors_version") != previous:
+ continue
+ head.update(
+ anchors_version=identity["_anchors_version"],
+ anchors_sha256=identity["_anchors_sha256"],
+ anchors_migrated_from=list(head.get("anchors_migrated_from", [])) +
+ [previous],
+ )
+ lines[0] = json.dumps(head, sort_keys=True) + "\n"
+ temporary = path.with_name(f"{path.name}.{os.getpid()}.tmp")
+ temporary.write_text("".join(lines))
+ temporary.replace(path)
+ count += 1
+ frozen = pathlib.Path(results) / RESOLVED
+ if (frozen.exists() and
+ json.loads(frozen.read_text()).get("anchors_version") == previous):
+ frozen.unlink()
+ print(
+ f"Migrated {count} files from anchors {previous} to {policy['version']}"
+ )
+ return count
+
+
+def main() -> None:
+ """Freeze a results directory's calibration.
+
+ Legacy scores are imported explicitly, and only if requested.
+ """
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--results", required=True)
+ parser.add_argument("--anchors", default=str(DEFAULT))
+ parser.add_argument(
+ "--view",
+ choices=("all", "core", "smoke", "gate", "exact"),
+ default="all",
+ )
+ parser.add_argument("--import-legacy", action="store_true")
+ parser.add_argument(
+ "--migrate-from",
+ default="",
+ help=("re-stamp scores computed under this earlier anchor version: raw"
+ " measurements do not depend on the anchor policy, only their"
+ " scaling does"),
+ )
+ parser.add_argument(
+ "--parent",
+ default="",
+ help=(
+ "a development panel's whole-set calibration, whose verification of"
+ " the declared endpoints it inherits (default: the parent"
+ " directory's)"),
+ )
+ parser.add_argument("--sealed", action="store_true")
+ args = parser.parse_args()
+ # pylint: disable-next=import-outside-toplevel
+ import common
+ # pylint: disable-next=import-outside-toplevel
+ import ranking
+ # pylint: disable-next=import-outside-toplevel
+ import scorefiles
+ policy = definitions(args.anchors)
+ parent = None
+ if args.view in common.PANELS:
+ path = (pathlib.Path(args.parent) if args.parent else
+ pathlib.Path(args.results).resolve().parent / RESOLVED)
+ if not path.exists():
+ raise SystemExit(
+ f"{path} is missing: freeze the whole set before one of its"
+ " panels")
+ parent = load(path, policy)
+ if args.migrate_from:
+ if args.migrate_from not in {
+ c["version"] for c in policy["changelog"][:-1]
+ }:
+ raise ValueError(
+ "--migrate-from names no earlier version of this anchor policy")
+ migrate(args.results, args.migrate_from, policy)
+ ranking.select_view(args.view)
+ systems = scorefiles.load(args.results)
+ calibration = resolve(policy, systems, ranking.AXES_BY_TIER, args.sealed,
+ parent)
+ pending = []
+ for suffix in ("metrics", "nisqa", "realx", "kept"):
+ for path in sorted(pathlib.Path(args.results).glob(f"*.{suffix}.json")):
+ data = json.loads(path.read_text())
+ if data.get("_anchors_version") is None and args.import_legacy:
+ data.update(stamp(policy))
+ pending.append((path, data))
+ validate_scores(calibration, {path.name: data})
+ destination = pathlib.Path(args.results) / RESOLVED
+ if destination.exists():
+ old = load(destination, policy)
+ if old != calibration:
+ raise ValueError(
+ "calibration is already frozen; use a new results directory")
+ for path, data in pending:
+ json.dumps(data, allow_nan=False)
+ for path, data in pending:
+ atomic_json(path, data)
+ atomic_json(destination, calibration)
+ print(
+ f"Calibration frozen: anchors {policy['version']}, subset {args.view}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/bench/scripts/anchorsweep.py b/bench/scripts/anchorsweep.py
new file mode 100644
index 0000000..1e90418
--- /dev/null
+++ b/bench/scripts/anchorsweep.py
@@ -0,0 +1,389 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Measures how much of the ranking is the anchor policy.
+
+It runs a sensitivity sweep over the declared constants.
+
+ anchorsweep.py --results bench/results [--view all] [--draws 2000]
+ [--seed 0] [--json-out FILE] [--markdown-out FILE]
+
+Every declared endpoint in ``anchors.json`` that carries a ``range`` is a policy
+choice, not a measurement. This recomputes the composites with those constants
+moved inside their ranges:
+
+ one at a time each ranged constant at the low and at the high end of its
+ range, everything else as declared: which single choice moves
+ the order, and by how much;
+ jointly ``--draws`` seeded draws, every ranged constant uniform in its
+ range at once: per system the 5th to 95th percentile of its
+ composite, how often it ranks first, and for every pair how
+ often one sits above the other and how often the two are inside
+ the tie band.
+
+Raw measurements never change; only the mapping from a raw value to a score
+does. The output says which statements about the board hold over the whole
+declared policy space and which hold only at the declared point.
+"""
+
+import argparse
+import copy
+import json
+import os
+import sys
+
+import numpy as np
+
+# pylint: disable=wrong-import-position
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import anchors
+import ranking
+import roster
+import scorefiles
+
+
+def ranged(policy):
+ """Returns [(rule index, side, low, high, label)] of the ranged constants.
+
+ There is one entry for every declared constant with a range.
+ """
+ out = []
+ for i, rule in enumerate(policy["rules"]):
+ for side in ("floor", "ceiling"):
+ span = rule[side].get("range")
+ if span is not None:
+ label = (f"{'/'.join(rule['conditions'])} {rule['metrics'][0]}"
+ f" {side}")
+ out.append((i, side, float(span[0]), float(span[1]), label))
+ return out
+
+
+def with_constants(calibration, policy, values):
+ """Returns a copy of ``calibration`` whose points use ``values``.
+
+ ``values`` is {(rule index, side): constant}.
+ """
+ cal = copy.deepcopy(calibration)
+ for (i, side), value in values.items():
+ rule = policy["rules"][i]
+ for condition in rule["conditions"]:
+ for metric in rule["metrics"]:
+ key = anchors.row_key(condition, metric)
+ if key in cal["points"]:
+ cal["points"][key][side] = float(value)
+ for key, point in cal["points"].items():
+ if point["direction"] * (point["ceiling"] - point["floor"]) <= 0:
+ raise ValueError(
+ f"ranges let the endpoints of {key} cross: narrow them")
+ return cal
+
+
+def composites(systems, tiers, calibration, tier="full"):
+ """Returns {system: composite} of the ranked systems of ``tier``.
+
+ Every composite is computed under ``calibration``.
+ """
+ _, comp, order = ranking.rank(systems, tiers, calibration)
+ return {n: comp[n] for n in order[tier]}
+
+
+def sweep(systems, tiers, calibration, policy, draws=2000, seed=0, tier="full"):
+ """Returns the sensitivity of the composites to the ranged constants.
+
+ The report holds both the one-at-a-time and the joint sensitivity.
+ """
+ knobs = ranged(policy)
+ base = composites(systems, tiers, calibration, tier)
+ names = sorted(base, key=lambda n: -base[n])
+ order0 = list(names)
+ single = []
+ for i, side, low, high, label in knobs:
+ declared = policy["rules"][i][side]["value"]
+ row = {
+ "constant": label,
+ "declared": declared,
+ "range": [low, high],
+ "ends": {},
+ }
+ for end, value in (("low", low), ("high", high)):
+ comp = composites(
+ systems,
+ tiers,
+ with_constants(calibration, policy, {(i, side): value}),
+ tier,
+ )
+ order = sorted(comp, key=lambda n, comp=comp: -comp[n])
+ # a swap between two systems tied at the declared point says
+ # nothing; a swap of a pair the declared board separates by more
+ # than the tie band does
+ reversed_pairs = [
+ [x, y]
+ for x in names
+ for y in names
+ if base[x] - base[y] > ranking.TIE_BAND and comp[y] > comp[x]
+ ]
+ row["ends"][end] = {
+ "value": value,
+ "composites": comp,
+ "order": order,
+ "order_changed": bool(reversed_pairs),
+ "reversed_pairs": reversed_pairs,
+ "leader": order[0],
+ }
+ row["max_shift"] = max(
+ abs(row["ends"][e]["composites"][n] - base[n])
+ for e in ("low", "high")
+ for n in names)
+ single.append(row)
+ rng = np.random.default_rng(seed)
+ samples = {n: [] for n in names}
+ first = {n: 0 for n in names}
+ above = {a: {b: 0 for b in names if b != a} for a in names}
+ tied = {a: {b: 0 for b in names if b != a} for a in names}
+ for _ in range(draws):
+ values = {
+ (i, side): rng.uniform(low, high) for i, side, low, high, _ in knobs
+ }
+ comp = composites(systems, tiers,
+ with_constants(calibration, policy, values), tier)
+ for n in names:
+ samples[n].append(comp[n])
+ first[max(comp, key=comp.get)] += 1
+ for a in names:
+ for b in names:
+ if a != b:
+ above[a][b] += comp[a] > comp[b]
+ tied[a][b] += abs(comp[a] - comp[b]) <= ranking.TIE_BAND
+ joint = {
+ n: {
+ "declared": base[n],
+ "p05": float(np.percentile(samples[n], 5)),
+ "p50": float(np.percentile(samples[n], 50)),
+ "p95": float(np.percentile(samples[n], 95)),
+ "first_fraction": first[n] / draws if draws else float("nan"),
+ } for n in names
+ }
+ pairs = {
+ a: {
+ b: {
+ "above_fraction":
+ (above[a][b] / draws if draws else float("nan")),
+ "tie_fraction": tied[a][b] / draws if draws else float("nan"),
+ } for b in above[a]
+ } for a in names
+ }
+ return {
+ "anchors_version": policy["version"],
+ "set_id": calibration["set_id"],
+ "subset": calibration["subset"],
+ "tier": tier,
+ "draws": draws,
+ "seed": seed,
+ "tie_band": ranking.TIE_BAND,
+ "declared_order": order0,
+ "single": single,
+ "joint": joint,
+ "pairs": pairs,
+ }
+
+
+def axis_sensitivity(systems,
+ tiers,
+ calibration,
+ draws=2000,
+ seed=0,
+ tier="full"):
+ """Returns how the order depends on the way the axes combine.
+
+ The order with each axis left out in turn (its part, when the composite has
+ parts, reads its remaining axes and goes when none remain), and how often
+ each system ranks first when the weights of the axes are drawn uniformly
+ from the simplex.
+ """
+ axes, _, order = ranking.rank(systems, tiers, calibration)
+ names = order[tier]
+ # scored beside the composite, or on another board: no weight to relax
+ board_parts = {
+ name: list(members)
+ for name, members in (ranking.PARTS or {}).items()
+ if not ranking.BOARDS or name in ranking.BOARDS[ranking.ranking_board()]
+ }
+ aside = set(ranking.OUTSIDE) | {
+ a for name, members in (ranking.PARTS or {}).items()
+ if name not in board_parts for a in members
+ }
+ axis_names = [
+ a for a in ranking.axis_order(ranking.AXES_BY_TIER[tier])
+ if a not in aside
+ ]
+ leave_out = {}
+ for axis in axis_names:
+ rest = [a for a in axis_names if a != axis]
+ parts = {
+ name: [a for a in members if a != axis]
+ for name, members in board_parts.items()
+ }
+ parts = {
+ name: members for name, members in parts.items() if members
+ } or None
+ c = {
+ n: anchors.composite({a: axes[n][a] for a in rest}, parts)
+ for n in names
+ }
+ leave_out[axis] = {
+ "composites": c,
+ "order": sorted(c, key=lambda n, c=c: -c[n]),
+ }
+ rng = np.random.default_rng(seed)
+ table = np.array([[axes[n][a] for a in axis_names] for n in names])
+ first = np.zeros(len(names))
+ for w in rng.dirichlet(np.ones(len(axis_names)), size=draws):
+ first[int(np.argmax(table @ w))] += 1
+ return {
+ "axis_scores": {
+ n: {
+ a: axes[n][a] for a in axis_names
+ } for n in names
+ },
+ "leave_one_out": leave_out,
+ "random_weights_first_fraction": {
+ n: float(first[i] / draws) if draws else float("nan")
+ for i, n in enumerate(names)
+ },
+ }
+
+
+def markdown(report, label=None):
+ """Returns the sweep as two markdown tables.
+
+ One is the joint sweep per system, the other the single constants that
+ change the order.
+ """
+ label = label or roster.display_name
+ names = report["declared_order"]
+ lines = [
+ ("Denoising scores of the full-band tier with every declared anchor"
+ f" constant drawn inside its stated range ({report['draws']} seeded"
+ " draws; anchors"
+ f" {report['anchors_version']}). The raw measurements are the same"
+ " in every draw; only the scale moves."),
+ "",
+ ("| system | declared | 5th to 95th percentile | ranked first |"
+ " above the next system | tied with it |"),
+ "|---|---:|---:|---:|---:|---:|",
+ ]
+ for k, n in enumerate(names):
+ j = report["joint"][n]
+ nxt = names[k + 1] if k + 1 < len(names) else None
+ pair = report["pairs"][n][nxt] if nxt else None
+ lines.append(
+ f"| {label(n)} | {j['declared']:.3f} | {j['p05']:.3f} to"
+ f" {j['p95']:.3f} | {100 * j['first_fraction']:.0f} % | " +
+ (f"{100 * pair['above_fraction']:.0f} % |"
+ f" {100 * pair['tie_fraction']:.0f} % |" if pair else "- | - |"))
+ movers = [
+ r for r in report["single"]
+ if any(e["order_changed"] for e in r["ends"].values())
+ ]
+ lines += [
+ "",
+ ("Single constants whose range alone reverses a pair the declared"
+ " board separates by more than the tie band of"
+ f" {report['tie_band']:.2f} (everything else as declared):"),
+ "",
+ ]
+ if not movers:
+ lines.append(
+ "None: no single constant, moved to either end of its range,"
+ " reverses such a pair.")
+ else:
+ lines += [
+ "| constant | declared | end of range | order at that end |",
+ "|---|---:|---:|---|",
+ ]
+ for r in movers:
+ for end in ("low", "high"):
+ e = r["ends"][end]
+ if e["order_changed"]:
+ lines.append(f"| {r['constant']} | {r['declared']:g} |"
+ f" {e['value']:g} | " +
+ " > ".join(label(n) for n in e["order"]) +
+ " |")
+ ax = report.get("axes")
+ if ax:
+ lines += [
+ "",
+ "The other policy choice is how the axes combine (" +
+ ranking.composite_rule() +
+ "). The order with one axis left out, and how often a system"
+ " ranks first when the weights of the axes are drawn uniformly at"
+ " random:",
+ "",
+ "| axis left out | order |",
+ "|---|---|",
+ ]
+ for axis, d in ax["leave_one_out"].items():
+ lines.append(f"| {axis} | " + " > ".join(
+ f"{label(n)} {d['composites'][n]:.3f}" for n in d["order"]) +
+ " |")
+ lines += [
+ "",
+ "| system | ranked first under random axis weights |",
+ "|---|---:|",
+ ]
+ for n in names:
+ lines.append(
+ f"| {label(n)} |"
+ f" {100 * ax['random_weights_first_fraction'][n]:.0f} % |")
+ return "\n".join(lines)
+
+
+def main():
+ here = os.path.dirname(os.path.abspath(__file__))
+ ap = argparse.ArgumentParser(description=__doc__,
+ formatter_class=argparse.RawTextHelpFormatter)
+ ap.add_argument(
+ "--results",
+ default=os.environ.get("BENCH_RESULTS",
+ os.path.join(os.path.dirname(here), "results")),
+ )
+ ap.add_argument("--view", default="all", choices=sorted(ranking.AXES_VIEWS))
+ ap.add_argument("--tiers",
+ default="",
+ help="JSON file with extra {name: [tier, label]}")
+ ap.add_argument("--draws", type=int, default=2000)
+ ap.add_argument("--seed", type=int, default=0)
+ ap.add_argument("--json-out", default="")
+ ap.add_argument("--markdown-out", default="")
+ a = ap.parse_args()
+ ranking.select_view(a.view)
+ tiers = roster.tiers(a.tiers)
+ policy = anchors.definitions()
+ systems = scorefiles.load(a.results)
+ calibration = anchors.load(os.path.join(a.results, anchors.RESOLVED),
+ policy)
+ report = sweep(systems, tiers, calibration, policy, a.draws, a.seed)
+ report["axes"] = axis_sensitivity(systems, tiers, calibration, a.draws,
+ a.seed)
+ md = markdown(report)
+ print(md)
+ if a.json_out:
+ with open(a.json_out, "w", encoding="utf-8") as fh:
+ json.dump(report, fh, indent=1)
+ if a.markdown_out:
+ with open(a.markdown_out, "w", encoding="utf-8") as fh:
+ fh.write(md + "\n")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/bench/scripts/asrtable.py b/bench/scripts/asrtable.py
new file mode 100644
index 0000000..7383bfd
--- /dev/null
+++ b/bench/scripts/asrtable.py
@@ -0,0 +1,338 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Downstream-ASR table: error rate per condition with and without processing.
+
+ asrtable.py [--results DIR] [--asr large-v3]
+ [--systems INPUT,voice_isolator_v0,...]
+ [--ours voice_isolator_v0] [--markdown-out FILE]
+
+Reads ``<system>.asr.json`` (scoreasr.py). One row per condition: the
+unprocessed input first, then every system, each as the pooled error rate with
+its 95 % interval, the best value in bold; a last column gives the --ours
+system's change against the input. Rows come from the conditions the input was
+scored on; a system missing a condition shows a dash.
+"""
+
+import argparse
+import glob
+import json
+import os
+import sys
+
+# pylint: disable=wrong-import-position
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import roster
+import scoreasr
+
+INPUT = "INPUT"
+# scoreasr.FALLBACK: no golden text, so the clean reference's transcript
+FALLBACK_TIER = "clean-asr"
+# two contracts a recogniser meets under competing speech, never pooled
+# together: chatter is to be removed, a conversation's second voice is to be
+# kept
+SLICES = (
+ ("background chatter removed", lambda c: c.startswith("babble@")),
+ ("a conversation kept, both voices", lambda c: c == "conversation@0"),
+)
+
+
+def load(results, tag):
+ """Returns {system: {condition: block}} for one recogniser.
+
+ The blocks come from every sidecar in ``results``.
+
+ Refuses sidecars of different set builds or scorers, scored on a partial
+ selection, or on other audio than their system's base records
+ (``scoreasr.stale_sidecar``).
+ """
+ out, set_ids, scorers = {}, set(), set()
+ for f in sorted(glob.glob(os.path.join(results, "*.asr.json"))):
+ with open(f, encoding="utf-8") as fh:
+ d = json.load(fh)
+ blk = (d.get("asr") or {}).get(tag)
+ if not blk:
+ continue
+ problem = scoreasr.stale_sidecar(d, results)
+ if problem:
+ raise SystemExit(
+ f"{os.path.basename(f)} {problem}: re-run scoreasr.py")
+ out[d["_system"]] = blk["conditions"]
+ set_ids.add(d.get("_set_id"))
+ scorers.add(d.get("_scorer_sha256"))
+ if len(set_ids) > 1:
+ raise SystemExit(f"asr sidecars from different set builds: {set_ids}")
+ if len(scorers) > 1:
+ raise SystemExit(
+ "asr sidecars scored by different implementations: re-run"
+ " scoreasr.py")
+ return out
+
+
+def complete(block, reference):
+ """Returns whether a condition's block covers the input's items.
+
+ It must cover every item the unprocessed input's block covers, with none
+ missing: a partial row would read as a result on easier items.
+ """
+ return (block is not None and not block.get("n_missing") and
+ (reference is None or set(block.get("items") or {}) == set(
+ reference.get("items") or {})))
+
+
+def cell(block):
+ if block is None:
+ return "-"
+ lo, hi = block["ci95"]
+ half = (hi - lo) / 2 if hi == hi else float("nan")
+ return (f"{block['wer_pct']:.1f} ± {half:.1f}"
+ if half == half else f"{block['wer_pct']:.1f}")
+
+
+def relative_change(ours, inp):
+ """Returns the --ours system's change in error rate, in % of the input's.
+
+ Negative means fewer errors.
+ """
+ if ours is None or inp is None or not inp["wer_pct"]:
+ return float("nan")
+ return 100.0 * (ours["wer_pct"] - inp["wer_pct"]) / inp["wer_pct"]
+
+
+def reference_phrase(conditions):
+ """Returns what the transcripts were scored against.
+
+ It is derived from the reference tiers the sidecar recorded.
+
+ Args:
+ conditions: {condition: block} of one system, each block with
+ ``reference_tiers``.
+
+ Returns:
+ The golden transcripts with the count of items that fell back to the
+ recogniser's transcript of the clean reference, or that fallback alone
+ when no item had a golden text.
+ """
+ tiers = {}
+ for block in conditions.values():
+ for tier, n in (block.get("reference_tiers") or {}).items():
+ tiers[tier] = tiers.get(tier, 0) + n
+ total, fallback = sum(tiers.values()), tiers.get(FALLBACK_TIER, 0)
+ if total == fallback:
+ return "the same recogniser's transcript of the clean reference"
+ if not fallback:
+ return "the set's golden transcripts"
+ return (
+ f"the set's golden transcripts ({total - fallback} of {total} items;"
+ f" the other {fallback} against the same recogniser's transcript of the"
+ " clean reference)")
+
+
+def table(sidecars, systems, ours, tag, label=None):
+ label = label or roster.display_name
+ cols = [INPUT] + [s for s in systems if s != INPUT]
+ conds = list(sidecars.get(INPUT, {}).keys()) or sorted(
+ {c for s in sidecars.values() for c in s})
+ names = ["unprocessed input" if c == INPUT else label(c) for c in cols]
+ head = f"| condition | {' | '.join(names)} | {label(ours)} vs input |"
+ sep = "|---|" + "---:|" * (len(cols) + 1)
+ lines = [
+ (f"Error rate (%) of `{tag}` transcripts against"
+ f" {reference_phrase(sidecars.get(INPUT) or {})}; words, characters"
+ " for Chinese and Japanese; pooled per condition, ± the 95 % interval"
+ " half-width. Lower is better; best in bold."),
+ "",
+ head,
+ sep,
+ ]
+ for cond in conds:
+ blocks = {c: sidecars.get(c, {}).get(cond) for c in cols}
+ whole = {
+ c: b for c, b in blocks.items() if complete(b, blocks.get(INPUT))
+ }
+ finite = [b["wer_pct"] for b in whole.values()]
+ best = min(finite) if finite else None
+ cells = []
+ for c in cols:
+ b = blocks[c]
+ txt = cell(b) if b is None or c in whole else "incomplete"
+ if c in whole and best is not None and b["wer_pct"] == best:
+ txt = f"**{txt}**"
+ cells.append(txt)
+ rel = relative_change(blocks.get(ours), blocks.get(INPUT))
+ rel_txt = "-" if rel != rel else f"{rel:+.0f} %"
+ lines.append(f"| `{cond}` | " + " | ".join(cells) + f" | {rel_txt} |")
+ return "\n".join(lines)
+
+
+# a pooled rate over fewer items is not shown: it is one or two recordings
+MIN_SLICE_ITEMS = 20
+
+
+def slices(by_tag,
+ rows,
+ golden,
+ systems,
+ ours,
+ label=None,
+ min_items=MIN_SLICE_ITEMS):
+ """Returns pooled error rates over each competing-speech slice.
+
+ One row per recogniser and unit (words, or characters for the languages
+ without word boundaries), with the --ours system's paired change against the
+ input under source-clustered resampling (compare.interval): the slice spans
+ a ladder, so the same recording enters at several levels and a per-item
+ bootstrap would overstate the precision.
+ """
+ # pylint: disable-next=import-outside-toplevel
+ import compare
+ # pylint: disable-next=import-outside-toplevel
+ import observations
+
+ label = label or roster.display_name
+ by_id = {r["id"]: r for r in rows}
+ cols = [INPUT] + [x for x in systems if x != INPUT]
+ lines = [
+ ("Error rate (%) pooled over the slice's items (total edits over"
+ " total reference tokens), one row per recogniser and unit; the"
+ f" last column is {label(ours)}'s paired change against the"
+ " unprocessed input in points, with a 95 % interval that resamples"
+ " the recordings and beds behind the items rather than the items"
+ f" themselves. Lower is better. A unit with fewer than {min_items}"
+ " items in a slice is not shown."),
+ "",
+ "| slice | recogniser | unit | items | " + " | ".join(
+ "unprocessed input" if c == INPUT else label(c) for c in cols) +
+ f" | {label(ours)} vs input |",
+ "|---|---|---|---:|" + "---:|" * (len(cols) + 1),
+ ]
+ for name, member in SLICES:
+ for tag in sorted(by_tag):
+ sidecars = by_tag[tag]
+ conds = [c for c in sidecars.get(INPUT, {}) if member(c)]
+ for unit in ("word", "char"):
+ ids = [
+ i for c in conds
+ for i in sidecars[INPUT][c].get("items", {})
+ if i in by_id and scoreasr.unit_for(
+ scoreasr.spoken_language(by_id[i], golden)) == unit
+ ]
+ if len(ids) < min_items:
+ continue
+ cells, rates = [], {}
+ for c in cols:
+ blocks = sidecars.get(c, {})
+ have = [(i, blocks[k]["items"][i]) for k in conds
+ if k in blocks for i in blocks[k].get("items", {})
+ if i in ids]
+ if len(have) < len(ids):
+ cells.append("-")
+ continue
+ e = sum(v[0] for _, v in have)
+ n = sum(v[1] for _, v in have)
+ rates[c] = (100.0 * e / n) if n else float("nan")
+ cells.append(f"{rates[c]:.1f}")
+ best = min((v for v in rates.values() if v == v), default=None)
+ cells = [(f"**{t}**"
+ if best is not None and rates.get(c) == best else t)
+ for c, t in zip(cols, cells)]
+ delta = "-"
+ if ours in rates and INPUT in rates:
+ pairs = {}
+ for k in conds:
+ for i, v in sidecars[ours][k]["items"].items():
+ if i in ids and i in sidecars[INPUT][k].get(
+ "items", {}):
+ pairs[i] = (v, sidecars[INPUT][k]["items"][i])
+ order = sorted(pairs)
+ e_ours = [pairs[i][0][0] for i in order]
+ e_in = [pairs[i][1][0] for i in order]
+ n_ref = [pairs[i][0][1] for i in order]
+ recs = [observations.item(by_id[i]) for i in order]
+ groups = [[r.get(g) for r in recs] for g in compare.GROUPS]
+ # pylint: disable-next=import-outside-toplevel
+ import numpy as np
+
+ eo, ei, nr = (
+ np.array(x, dtype=float) for x in (e_ours, e_in, n_ref))
+
+ def reduce(w, eo=eo, ei=ei, nr=nr):
+ d = w @ nr
+ return (100.0 * (w @ eo - w @ ei) /
+ d if d else float("nan"))
+
+ try:
+ d = compare.interval(reduce, groups)
+ delta = (f"{d['delta']:+.1f} [{d['ci95'][0]:+.1f},"
+ f" {d['ci95'][1]:+.1f}]")
+ except ValueError as e:
+ delta = f"no interval ({e})"
+ lines.append(f"| {name} | `{tag}` | {unit}s | {len(ids)} | " +
+ " | ".join(cells) + f" | {delta} |")
+ return "\n".join(lines)
+
+
+def main():
+ here = os.path.dirname(os.path.abspath(__file__))
+ ap = argparse.ArgumentParser()
+ ap.add_argument(
+ "--results",
+ default=os.environ.get("BENCH_RESULTS",
+ os.path.join(os.path.dirname(here), "results")),
+ )
+ ap.add_argument("--asr", default="large-v3")
+ ap.add_argument(
+ "--systems",
+ default="",
+ help="comma-separated; default: every sidecar found",
+ )
+ ap.add_argument("--ours", default="voice_isolator_v0")
+ ap.add_argument("--markdown-out", default="")
+ ap.add_argument(
+ "--slices-out",
+ default="",
+ help=(
+ "also write the competing-speech slices over every recogniser found"
+ ),
+ )
+ a = ap.parse_args()
+ sidecars = load(a.results, a.asr)
+ if not sidecars:
+ raise SystemExit(f"no asr sidecars for {a.asr!r} in {a.results}")
+ systems = [s for s in a.systems.split(",") if s
+ ] or [s for s in sidecars if s != INPUT]
+ md = table(sidecars, systems, a.ours, a.asr)
+ print(md)
+ if a.markdown_out:
+ with open(a.markdown_out, "w", encoding="utf-8") as fh:
+ fh.write(md + "\n")
+ print(f"wrote {a.markdown_out}")
+ if a.slices_out:
+ # pylint: disable-next=import-outside-toplevel
+ import common
+
+ tags = set()
+ for f in glob.glob(os.path.join(a.results, "*.asr.json")):
+ with open(f, encoding="utf-8") as fh:
+ tags |= set(json.load(fh).get("asr") or {})
+ by_tag = {t: load(a.results, t) for t in sorted(tags)}
+ md = slices(by_tag, common.manifest(), scoreasr.load_golden(), systems,
+ a.ours)
+ with open(a.slices_out, "w", encoding="utf-8") as fh:
+ fh.write(md + "\n")
+ print(md)
+ print(f"wrote {a.slices_out}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/bench/scripts/common.py b/bench/scripts/common.py
new file mode 100644
index 0000000..a2bb6df
--- /dev/null
+++ b/bench/scripts/common.py
@@ -0,0 +1,703 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Shared core for the benchmark: paths, 48 kHz audio IO, mixing, metrics.
+
+Every scorer imports this module. Paths come from environment variables so
+the same scripts run on any machine:
+
+ VOICE_ISOLATION_EVALS eval-set root: mix/ ref/ manifest.jsonl
+ (default: <repo>/data/voice-isolation-evals)
+ BENCH_OUT per-system outputs: <BENCH_OUT>/<system>/<id>.wav
+ (default: <repo>/data/outputs)
+ BENCH_RESULTS score JSONs (default: <repo>/bench/results)
+
+The metric primitives are defined here once, so every scorer and sidecar reads
+the same implementation.
+"""
+
+import json
+import os
+import re
+
+import numpy as np
+import soundfile as sf
+import torch
+import torchaudio
+
+from inworld import voice_isolation
+
+SR = 48000
+DEV = "cuda" if torch.cuda.is_available() else "cpu"
+BENCH_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+REPO_DIR = os.path.dirname(BENCH_DIR)
+EVAL = os.environ.get(
+ "VOICE_ISOLATION_EVALS",
+ os.path.join(REPO_DIR, "data", "voice-isolation-evals"),
+)
+OUT_ROOT = os.environ.get(
+ "BENCH_OUT",
+ os.path.join(REPO_DIR, "data", "outputs"),
+)
+RESULTS = os.environ.get("BENCH_RESULTS", os.path.join(BENCH_DIR, "results"))
+BANDS_HZ = (
+ (0, 500),
+ (500, 2000),
+ (2000, 4000),
+ (4000, 8000),
+ (8000, 12000),
+ (12000, 16000),
+ (16000, 24000),
+)
+NB_RATE = 16000 # the 0-8 kHz band that 16 kHz-native systems can emit
+MAX_LAG = int(0.100 * SR) # +-100 ms search window for algorithmic delay
+# a level offset beyond this is not a gain convention but another output
+MAX_LEVEL_CAL_DB = 12.0
+
+
+def set_id(root=None):
+ """The eval set's content fingerprint from its checksums.json, or None."""
+ p = os.path.join(root or EVAL, "checksums.json")
+ if not os.path.exists(p):
+ return None
+ with open(p, encoding="utf-8") as fh:
+ return json.load(fh).get("set_id")
+
+
+def outputs_digest(name: str, results: str | None = None) -> str | None:
+ """Returns the digest of a system's stamped outputs, or None.
+
+ The ``outputs_sha256`` that stamprender.py writes; None when the stamp
+ records none: the set's own mixtures and references, linked rather than
+ rendered.
+ """
+ path = os.path.join(results or RESULTS, f"{name}.meta.json")
+ if not os.path.exists(path):
+ return None
+ with open(path, encoding="utf-8") as fh:
+ return json.load(fh).get("outputs_sha256")
+
+
+# The set has two halves. The core is the multilingual draw: for every condition
+# the first CORE_INDEX_LIMIT indices of its ladder (real recordings are core
+# throughout). The extension is English only: the indices added above that limit
+# and the condition families that exist only in English (matched on the
+# condition name, so nonverbal_clean belongs with nonverbal@+0). Scores are
+# reported for both, so a language-heavy extension cannot move the multilingual
+# result.
+CORE_INDEX_LIMIT = 48
+EXTENSION_FAMILIES = frozenset((
+ "animals",
+ "appliance",
+ "household",
+ "nonverbal",
+ "rain",
+ "soft",
+ "stationary",
+ "tools",
+ "traffic",
+ "water",
+ "whisper",
+))
+# frozen development panels, drawn by panels.py
+PANELS = ("smoke", "gate", "exact")
+SUBSETS = ("all", "core", "extension") + PANELS
+SUBSET = os.environ.get("BENCH_SUBSET", "all")
+if SUBSET not in SUBSETS:
+ raise SystemExit(f"BENCH_SUBSET must be one of {SUBSETS}, not {SUBSET!r}")
+
+
+def item_index(row):
+ """The ladder index of a row: the number before .wav in its id, or -1."""
+ m = re.search(r"_(\d+)\.wav$", row["id"])
+ return int(m.group(1)) if m else -1
+
+
+def subset(row):
+ """'core' or 'extension' for a manifest row (see CORE_INDEX_LIMIT)."""
+ # the condition's family
+ if re.split(r"[@_]", row["condition"])[0] in EXTENSION_FAMILIES:
+ return "extension"
+ if (row.get("clean_path") and row.get("language") == "en" and
+ item_index(row) >= CORE_INDEX_LIMIT):
+ return "extension"
+ return "core"
+
+
+def manifest(root=None, which=None):
+ """Manifest rows with mix/clean paths made absolute under ``root``.
+
+ ``which`` selects 'all', 'core' or 'extension' (default: the BENCH_SUBSET
+ environment variable, 'all'), so every scorer sees the same items for a
+ given subset.
+ """
+ root = root or EVAL
+ which = which or SUBSET
+ panel = panel_members(which, root) if which in PANELS else None
+ rows = []
+ with open(os.path.join(root, "manifest.jsonl"), encoding="utf-8") as fh:
+ for line in fh:
+ if not line.strip():
+ continue
+ r = json.loads(line)
+ if panel is not None:
+ if r["id"] not in panel:
+ continue
+ elif which != "all" and subset(r) != which:
+ continue
+ for k in ("mix_path", "clean_path"):
+ if r.get(k) and not os.path.isabs(r[k]):
+ r[k] = os.path.join(root, r[k])
+ rows.append(r)
+ return rows
+
+
+def file_hashes(root=None):
+ """Returns a function from a path to the sha256 of a file of the set.
+
+ It reads checksums.json (the builder hashes every mixture and reference) and
+ computes the hash of anything the file does not list.
+ """
+ # pylint: disable-next=import-outside-toplevel
+ import hashlib
+
+ root = root or EVAL
+ path = os.path.join(root, "checksums.json")
+ listed = {}
+ if os.path.exists(path):
+ with open(path, encoding="utf-8") as fh:
+ listed = json.load(fh).get("files", {}) or {}
+ computed = {}
+
+ def digest(file_path):
+ rel = os.path.relpath(file_path, root)
+ if rel in listed:
+ return listed[rel]
+ if file_path not in computed:
+ with open(file_path, "rb") as fh:
+ computed[file_path] = hashlib.sha256(fh.read()).hexdigest()
+ return computed[file_path]
+
+ return digest
+
+
+def panel_members(name: str, root: str | None = None) -> set:
+ """Returns the item ids of a frozen panel (``bench/panels.json``).
+
+ A panel drawn on another build of the set is refused.
+ """
+ path = os.path.join(BENCH_DIR, "panels.json")
+ if not os.path.exists(path):
+ raise SystemExit(
+ f"no {path}: draw the panels with bench/scripts/panels.py")
+ with open(path, encoding="utf-8") as fh:
+ doc = json.load(fh)
+ current = set_id(root)
+ if current and doc.get("set_id") != current:
+ raise SystemExit(
+ f"{path} was drawn on set {str(doc.get('set_id'))[:8]}, not "
+ f"{current[:8]}: rebuild it with bench/scripts/panels.py")
+ if name not in doc.get("panels", {}):
+ raise SystemExit(f"no panel {name!r} in {path}")
+ return set(doc["panels"][name]["ids"])
+
+
+def is_sealed(rows: list[dict], root: str | None = None) -> bool:
+ """Checks both private-data markers, an inventory's receipt included."""
+ if any(r.get("internal_only") for r in rows):
+ return True
+ path = os.path.join(root or EVAL, "checksums.json")
+ if os.path.isfile(path):
+ with open(path, encoding="utf-8") as stream:
+ return json.load(stream).get("sealed") is True
+ return False
+
+
+def guard_private_results(rows: list[dict]) -> None:
+ """Keeps internal-only audio and its scores out of published results."""
+ if not is_sealed(rows):
+ return
+ # pylint: disable-next=import-outside-toplevel
+ import pathlib
+
+ public = [(pathlib.Path(REPO_DIR) / p).resolve()
+ for p in ("bench/results", "docs", "media")]
+ for target in (pathlib.Path(RESULTS).resolve(),
+ pathlib.Path(OUT_ROOT).resolve()):
+ if any(target == p or p in target.parents for p in public):
+ raise ValueError(
+ "internal-only evaluation material requires private"
+ " scratch/results")
+
+
+def load48(path, secs=None):
+ """Any audio file -> mono float32 Tensor at 48 kHz; pad/trim to ``secs``."""
+ x, sr = sf.read(path, dtype="float32", always_2d=True)
+ t = torch.from_numpy(x.mean(1))
+ if sr != SR:
+ t = voice_isolation.resample(t, sr, SR)
+ if secs is not None:
+ n = int(secs * SR)
+ t = (t[:n] if len(t) >= n else torch.nn.functional.pad(
+ t, (0, n - len(t))))
+ return t
+
+
+def nb8k(x):
+ """48k -> 16k -> 48k round-trip: keeps only the 0-8 kHz band."""
+ low = torchaudio.functional.resample(x, SR, NB_RATE)
+ return torchaudio.functional.resample(low, NB_RATE, SR)[:len(x)]
+
+
+def best_alignment(out, ref, max_lag=MAX_LAG):
+ """Returns the (lag, sign) that line ``out`` up with ``ref``.
+
+ The delay and the polarity a scorer undoes. The lag (samples) maximises
+ xcorr(out shifted by -lag, ref). A delay of up to ``max_lag`` and a flipped
+ sign are both inaudible, so neither may read as damage. The sign is -1 when
+ the negative peak is the larger one, as it is for a voice upside down and
+ never for an upright one (no lobe of a correlation exceeds its main peak),
+ and carries at least a fifth of the correlation two identical signals would
+ have, so an output that holds none of the voice is not flipped on a coin
+ toss. (0, 1) if aligned or (near) silent.
+ """
+ n = min(len(out), len(ref))
+ a, b = out[:n] - out[:n].mean(), ref[:n] - ref[:n].mean()
+ if float(a.abs().max()) < 1e-8 or float(b.abs().max()) < 1e-8:
+ return 0, 1
+ # a clip cannot be shifted by more than its length: with a larger window
+ # the two halves of the correlation would overlap and read a lag of
+ # -max_lag for an aligned clip
+ max_lag = min(max_lag, n - 1)
+ size = 1 << int(np.ceil(np.log2(2 * n)))
+ # a 2^19-point FFT per clip: milliseconds on a GPU, 0.1 s on a CPU
+ a, b = a.to(DEV), b.to(DEV)
+ spec_out = torch.fft.rfft(a, size)
+ spec_ref = torch.fft.rfft(b, size)
+ cc = torch.fft.irfft(spec_out * spec_ref.conj(), size)
+ cc = torch.cat([cc[-max_lag:], cc[:max_lag + 1]])
+ low, high = float(cc.min()), float(cc.max())
+ if -low > high and -low >= 0.2 * float(a.norm() * b.norm()):
+ return int(cc.argmin()) - max_lag, -1
+ return int(cc.argmax()) - max_lag, 1
+
+
+def best_lag(out, ref, max_lag=MAX_LAG):
+ """Returns the lag of ``best_alignment`` alone.
+
+ For callers that compare levels and not waveforms.
+ """
+ return best_alignment(out, ref, max_lag)[0]
+
+
+def apply_lag(out, lag, n):
+ """Shifts ``out`` back by ``lag`` samples and pads/trims it to ``n``."""
+ if lag > 0:
+ out = out[lag:]
+ elif lag < 0:
+ out = torch.nn.functional.pad(out, (-lag, 0))
+ return (out[:n] if len(out) >= n else torch.nn.functional.pad(
+ out, (0, n - len(out))))
+
+
+def effective_bandwidth_hz(x: torch.Tensor,
+ sr: int,
+ floor_db: float = -50.0) -> float:
+ """Returns the highest frequency the speech spectrum reaches.
+
+ The highest frequency below which the active-frame spectrum stays within
+ ``floor_db`` of its 1-4 kHz level. A clip upsampled from 24 kHz reads about
+ 12 kHz here, whatever its container rate says.
+ """
+ n_fft = 2048
+ spec = (torch.stft(
+ x.float(),
+ n_fft,
+ n_fft // 4,
+ window=torch.hann_window(n_fft),
+ return_complex=True,
+ ).abs().pow(2))
+ frame_energy = spec.sum(0)
+ active = frame_energy > frame_energy.median()
+ if not bool(active.any()):
+ return 0.0
+ ps = spec[:, active].mean(1)
+ freqs = torch.linspace(0, sr / 2, spec.shape[0])
+ ref = ps[(freqs >= 1000) & (freqs < 4000)].mean()
+ db = 10 * torch.log10(ps / (ref + 1e-12) + 1e-12)
+ start = int(4000 / (sr / 2) * len(freqs))
+ for i in range(start, len(freqs)):
+ if bool((db[i:] < floor_db).all()):
+ return float(freqs[i])
+ return float(sr / 2)
+
+
+def mix_at_snr(clean, noise, snr_db):
+ """clean + g*noise at the requested whole-clip SNR; returns (mix, clean)."""
+ ln = min(len(clean), len(noise))
+ c, n = clean[:ln], noise[:ln]
+ g = ((float(c.std()) + 1e-8) / (float(n.std()) + 1e-8) /
+ (10**(snr_db / 20)))
+ return c + g * n, c
+
+
+def si_sdr(est, ref):
+ ref = ref - ref.mean()
+ est = est - est.mean()
+ a = (est * ref).sum() / (ref.pow(2).sum() + 1e-9)
+ proj = a * ref
+ return float(10 * torch.log10(
+ proj.pow(2).sum() / ((est - proj).pow(2).sum() + 1e-9) + 1e-9))
+
+
+def voice_kept_db(out, clean, frame=960):
+ """Output-vs-clean energy (dB) inside speech-active frames of CLEAN."""
+ n = min(len(out), len(clean))
+ out, clean = out[:n], clean[:n]
+ ce = clean[:n // frame * frame].reshape(-1, frame).pow(2).mean(1)
+ oe = out[:n // frame * frame].reshape(-1, frame).pow(2).mean(1)
+ act = ce > ce.median()
+ return float(10 * torch.log10(
+ (oe[act].mean() + 1e-9) / (ce[act].mean() + 1e-9)))
+
+
+def block_mask(active16, n_blocks, frame16=1600):
+ """Returns a 16 kHz speech-sample mask as a mask of 100 ms blocks.
+
+ ``n_blocks`` long: a block counts as speech when more than half of its
+ samples are marked.
+ """
+ m = torch.zeros(n_blocks, dtype=torch.bool)
+ for b in range(n_blocks):
+ seg = active16[b * frame16:(b + 1) * frame16]
+ if len(seg) and float(seg.float().mean()) > 0.5:
+ m[b] = True
+ return m
+
+
+def coherent_blocks(out, ref, frame=4800, floor_db=40.0):
+ """Returns OUT's voice kept, residual and measurable blocks against REF.
+
+ Three tensors of 100 ms block values at 48 kHz. ``kept`` is 20 log10 of the
+ projection coefficient of the block of OUT on the block of REF: the part of
+ the output that is the voice (a coefficient <= 0 reads as the -80 dB floor).
+ ``resid`` is what remains once that projection is removed, relative to the
+ reference block: the bed and the artifacts, whatever is not the voice.
+ ``loud`` marks the blocks within ``floor_db`` of the loudest reference
+ block; below that nothing measurable is there to keep. coherent_kept_db and
+ the seam, re-pass and transition checks all read these.
+ """
+ n = min(len(out), len(ref))
+ o = out[:n // frame * frame].reshape(-1, frame)
+ r = ref[:n // frame * frame].reshape(-1, frame)
+ if len(r) == 0:
+ empty = torch.zeros(0)
+ return empty, empty.clone(), torch.zeros(0, dtype=torch.bool)
+ r = r - r.mean(1, keepdim=True)
+ o = o - o.mean(1, keepdim=True)
+ re_ = r.pow(2).mean(1)
+ loud = (10 * torch.log10(re_ + 1e-12)
+ > 10 * torch.log10(re_.max() + 1e-12) - floor_db)
+ # a silent reference: nothing is measurable anywhere
+ if float(re_.max()) < 1e-10:
+ loud[:] = False
+ # per-block projection of out on ref
+ a = (o * r).sum(1) / (r.pow(2).sum(1) + 1e-9)
+ kept = (20 * torch.log10(a.clamp(min=1e-4))).clamp(-80.0, 20.0)
+ resid = (o - a.unsqueeze(1) * r).pow(2).mean(1)
+ resid_db = (10 * torch.log10(resid / (re_ + 1e-12) + 1e-8)).clamp(
+ -80.0, 60.0)
+ return kept, resid_db, loud
+
+
+def coherent_kept_db(out, ref, frame=4800, act=None, floor_db=40.0):
+ """Returns the voice kept per 100 ms block, in dB relative to REF.
+
+ The per-block energy of the part of OUT that is coherent with REF, relative
+ to REF, over the speech blocks of REF, as a tensor of block values at 48
+ kHz.
+
+ An energy ratio cannot tell kept speech from an added bed: returning the bed
+ alone scores above 0 dB on voice_kept_db. Projecting the output onto the
+ reference does: the bed is uncorrelated with the voice and projects to
+ nothing, so a deleted foreground reads as a large negative number whatever
+ else the output holds. ``act`` names the speech blocks independently (a
+ voice-activity mask, see block_mask), so quiet speech counts; without it,
+ every block within ``floor_db`` of the loudest counts. Blocks more than
+ ``floor_db`` under the loudest are skipped either way: nothing measurable is
+ there to keep.
+ """
+ kept, _, loud = coherent_blocks(out, ref, frame, floor_db)
+ use = loud if act is None else (act[:len(loud)] & loud)
+ return kept[use]
+
+
+def band_kept_db(out, ref, bands=BANDS_HZ, n_fft=2048):
+ """Per-band out/ref energy ratio (dB) over speech-active frames of REF.
+
+ ~0 dB = band preserved, very negative = dulled/lost, strongly positive =
+ invented high frequency.
+ """
+ n = min(len(out), len(ref))
+ o, r = out[:n], ref[:n]
+ win = torch.hann_window(n_fft)
+ hop = n_fft // 4
+ spec_o = torch.stft(o, n_fft, hop, window=win, return_complex=True).abs()
+ spec_r = torch.stft(r, n_fft, hop, window=win, return_complex=True).abs()
+ fe = spec_r.pow(2).sum(0)
+ act = fe > fe.median()
+ if not bool(act.any()):
+ return [float("nan")] * len(bands)
+ freqs = torch.linspace(0, SR / 2, spec_o.shape[0])
+ out_db = []
+ for lo, hi in bands:
+ m = (freqs >= lo) & (freqs < hi)
+ if not bool(m.any()):
+ out_db.append(float("nan"))
+ continue
+ oe = spec_o[m][:, act].pow(2).mean()
+ rr = spec_r[m][:, act].pow(2).mean()
+ out_db.append(float(10 * torch.log10((oe + 1e-12) / (rr + 1e-12))))
+ return out_db
+
+
+def tercile_kept_db(out, ref, frame=960, act_db=40.0, act=None):
+ """Returns out/ref energy (dB) per loudness tercile of REF's active frames.
+
+ The terciles are [quiet, mid, loud].
+ """
+ n = min(len(out), len(ref))
+ re_ = ref[:n // frame * frame].reshape(-1, frame).pow(2).mean(1)
+ oe = out[:n // frame * frame].reshape(-1, frame).pow(2).mean(1)
+ # a scored region shorter than one frame carries no terciles
+ if len(re_) == 0:
+ return [float("nan")] * 3
+ if act is None:
+ fdb = 10 * torch.log10(re_ + 1e-12)
+ act = fdb > fdb.max() - act_db
+ else:
+ act = act[:len(re_)]
+ idx = act.nonzero(as_tuple=True)[0]
+ if len(idx) < 9:
+ return [float("nan")] * 3
+ idx = idx[re_[idx].argsort()]
+ k = len(idx)
+ return [
+ float(10 * torch.log10((oe[t].mean() + 1e-9) / (re_[t].mean() + 1e-9)))
+ for t in (idx[:k // 3], idx[k // 3:2 * k // 3], idx[2 * k // 3:])
+ ]
+
+
+def add_model_args(ap):
+ """Adds the model flags every check that runs the isolator shares.
+
+ The same flags as runsystem.py's.
+ """
+ ap.add_argument(
+ "--model",
+ default="voice-isolator-v0",
+ help="registry name or checkpoint path (.safetensors/.pt)",
+ )
+ ap.add_argument("--stage2", default=None)
+ ap.add_argument("--alpha", type=float, default=None)
+ ap.add_argument("--mode",
+ default="offline",
+ choices=("offline", "streaming"))
+ ap.add_argument("--lookahead",
+ type=int,
+ default=0,
+ help="streaming look-ahead in frames")
+ ap.add_argument("--precision",
+ default="fp32",
+ choices=("fp32", "fp16", "bf16"))
+ ap.add_argument("--device", default=None)
+
+
+def isolator_runner(a):
+ """Returns (isolator, run) for the model the command line names.
+
+ ``run(x48, chunk_seconds, overlap_seconds)`` returns the 48 kHz output
+ through the public path at the command line's mode, look-ahead and
+ precision (chunking and resampling included). The streaming window
+ knobs and the batching are runsystem.py's alone: an operational check
+ reads the plain stream.
+ """
+ vi = voice_isolation.VoiceIsolator.load(
+ a.model,
+ stage2=a.stage2,
+ device=a.device or DEV,
+ precision=a.precision,
+ mode=a.mode,
+ lookahead_frames=a.lookahead,
+ )
+
+ def run(x, chunk_seconds=None, overlap_seconds=None):
+ kw = dict(
+ output_sample_rate=SR,
+ chunk_seconds=chunk_seconds,
+ overlap_seconds=overlap_seconds,
+ )
+ if a.alpha is None:
+ return vi.isolate(x, SR, **kw)
+ return vi.enhance(x, SR, alpha=a.alpha, **kw)
+
+ return vi, run
+
+
+def model_tag(model):
+ """Returns a file-name tag for a model argument.
+
+ The registry name, or the checkpoint's stem.
+ """
+ base = os.path.basename(str(model).rstrip("/"))
+ return re.sub(r"\.(safetensors|pt)$", "", base) or "model"
+
+
+def ops_path(model, check, out=None):
+ """Returns where an operational check writes its results.
+
+ ``out`` when given, else ``staging/ops/<tag>.<check>.json`` under the
+ repository; never bench/results, which holds the published scores only.
+ """
+ if out:
+ return out
+ return os.path.join(REPO_DIR, "staging", "ops",
+ f"{model_tag(model)}.{check}.json")
+
+
+def pick_rows(rows, conds, limit=0, paired=None):
+ """Returns the manifest rows of the named conditions.
+
+ ``conds`` holds comma-separated exact names or one prefix, and every row is
+ taken when it is empty; the first ``limit`` rows are kept, and ``paired``
+ True keeps the rows with a reference, False those without.
+ """
+ want = [c for c in conds.split(",") if c]
+ if not want:
+ out = list(rows)
+ elif len(want) == 1 and not any(r["condition"] == want[0] for r in rows):
+ out = [r for r in rows if r["condition"].startswith(want[0])]
+ else:
+ out = [r for r in rows if r["condition"] in want]
+ if paired is not None:
+ out = [r for r in out if bool(r.get("clean_path")) == paired]
+ return out[:limit] if limit else out
+
+
+_NISQA = None
+
+
+def nisqa(wav48, sr=None):
+ """Returns NISQA v2's five scores of a clip (torchmetrics).
+
+ (mos, noisiness, discontinuity, coloration, loudness).
+
+ Returns NaNs rather than raising: a quality probe must never take down a
+ run.
+ """
+ global _NISQA
+ try:
+ if _NISQA is None:
+ # pylint: disable-next=import-outside-toplevel
+ from torchmetrics.functional.audio import nisqa as nisqa_metric
+
+ _NISQA = nisqa_metric.non_intrusive_speech_quality_assessment
+ x = wav48 if isinstance(wav48, torch.Tensor) else torch.as_tensor(wav48)
+ x = x.detach().float().cpu()
+ if x.dim() > 1:
+ x = x.mean(0)
+ out = _NISQA(x.unsqueeze(0), sr or SR).reshape(-1)
+ return tuple(float(v) for v in out[:5])
+ # a clip NISQA cannot read is a missing value, never a crash of the pass
+ except Exception: # pylint: disable=broad-exception-caught
+ return tuple([float(np.nan)] * 5)
+
+
+class SpeakerEmbedder:
+ """Frozen WavLM-SV embedding; cosine(out, clean) = timbre identity.
+
+ ``cache_dir`` keeps embeddings of signals that never change between systems
+ (the references) on disk, keyed by the caller's ``key`` under a folder of
+ the model and its revision, so another embedding model never reads them:
+ every system after the first then pays for its own outputs only.
+ """
+
+ def __init__(self,
+ model_name="microsoft/wavlm-base-plus-sv",
+ cache_dir=None):
+ # pylint: disable-next=import-outside-toplevel
+ import transformers
+
+ model = transformers.WavLMForXVector.from_pretrained(model_name)
+ self.m = model.to(DEV).eval()
+ revision = getattr(self.m.config, "_commit_hash", None) or "local"
+ folder = f"{model_name.replace('/', '--')}@{revision}"
+ self.cache_dir = os.path.join(cache_dir, folder) if cache_dir else None
+ self._mem = {}
+ if self.cache_dir:
+ os.makedirs(self.cache_dir, exist_ok=True)
+
+ @torch.inference_mode()
+ def emb(self, wav48, key=None):
+ if key is not None:
+ if key in self._mem:
+ return self._mem[key]
+ path = (os.path.join(self.cache_dir, f"{key}.pt")
+ if self.cache_dir else None)
+ if path and os.path.exists(path):
+ e = torch.load(path, weights_only=True)
+ self._mem[key] = e
+ return e
+ x = torchaudio.functional.resample(wav48.float(), SR, 16000).to(DEV)
+ out = self.m(x.unsqueeze(0) if x.ndim == 1 else x)
+ e = getattr(out, "embeddings", None)
+ if e is None:
+ e = out[0] if isinstance(out, (tuple, list)) else out
+ e = torch.nn.functional.normalize(e.squeeze(0), dim=-1).cpu()
+ if key is not None:
+ self._mem[key] = e
+ if self.cache_dir:
+ tmp = f"{path}.tmp{os.getpid()}"
+ torch.save(e, tmp)
+ os.replace(tmp, path)
+ return e
+
+ def sim(self, a48, b48, key_b=None):
+ """Returns the cosine similarity of two clips.
+
+ ``key_b`` names the second one for the cache.
+ """
+ return float(torch.dot(self.emb(a48), self.emb(b48, key=key_b)))
+
+
+class Vad:
+ """Silero VAD helpers for reference-free (real-file) metrics."""
+
+ def __init__(self):
+ # pylint: disable-next=import-outside-toplevel
+ import importlib.metadata
+
+ # pylint: disable-next=import-outside-toplevel
+ import silero_vad
+
+ self._get = silero_vad.get_speech_timestamps
+ self.vad = silero_vad.load_silero_vad()
+ # what decides the segments: a cache entry of another detector is never
+ # read
+ self.identity = (
+ f"silero-vad {importlib.metadata.version('silero-vad')}, defaults,"
+ " 16 kHz")
+
+ def segments(self, wav48):
+ w16 = torchaudio.functional.resample(wav48, SR, 16000)
+ return w16, self._get(w16, self.vad, sampling_rate=16000)
diff --git a/bench/scripts/compare.py b/bench/scripts/compare.py
new file mode 100644
index 0000000..4114f5e
--- /dev/null
+++ b/bench/scripts/compare.py
@@ -0,0 +1,917 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Paired comparisons with foreground/bed source-clustered uncertainty.
+
+Resample each source factor, multiply its cluster frequencies, and keep all
+repeated ladder observations together. Intervals describe this frozen panel;
+they do not correct repeated adaptive selection against the same panel.
+"""
+
+import argparse
+import json
+import math
+import pathlib
+from typing import Callable, Iterator
+
+import numpy as np
+
+import anchors
+import common
+import levels
+import observations
+import scorefiles
+
+IDENTITY = ("set_id", "subset", "anchors_version", "anchors_sha256")
+GROUPS = ("speech_source", "bed_source")
+CALIBRATED = frozenset((
+ "kept_mean",
+ "kept_p10",
+ "kept_nb_mean",
+ "kept_q1",
+ "kept_q2",
+ "kept_q3",
+ "kept_coh_mean",
+ "kept_coh_p10",
+ "kept_coh_nb_mean",
+ "kept_coh_nb_p10",
+))
+
+
+SIDECAR_KEYS = { # what each sidecar's per-item records add to a system's
+ "nisqa": (
+ "nisqa_mos",
+ "nisqa_noisiness",
+ "nisqa_discontinuity",
+ "nisqa_coloration",
+ "nisqa_loudness",
+ ),
+ "realx": ("primary_drops", "primary_segments"),
+ "kept": (
+ "mag_snr",
+ "mag_snr_nb",
+ "nv_blocks",
+ "nv_events",
+ "nv_lost",
+ "nv_lost_pct",
+ ),
+ "residual": (
+ "pause_resid_db",
+ "pause_resid_db_nb",
+ "pause_level_db",
+ "floor_db",
+ "floor_worst_db",
+ "babble_resid_db",
+ "babble_resid_db_nb",
+ ),
+ "events": (
+ "event_resid_db",
+ "event_resid_raw_db",
+ "floor_resid_db",
+ "floor_resid_raw_db",
+ "voice_level_db",
+ "voice_pair_db",
+ "voice_kept_db",
+ ),
+}
+# board value: 100 * sum / sum over the items
+POOLED = {"nv_lost_pct": ("nv_lost", "nv_blocks")}
+# the pooled rows: the equal mean of the named families' means
+# (scorefiles.real_quality), or the mean over every item of the named
+# conditions that carries the row (scoreresidual.aggregate,
+# scoreevents.aggregate)
+REAL_FAMILIES = ("real_dirty", "real_multi", "real_noisy", "real_wild")
+# the pause rows pool every real family (scoreresidual.REAL); the quality
+# pooling keeps its four (scorefiles.REAL_FAMILIES)
+CLEANUP_FAMILIES = REAL_FAMILIES + ("real_everyday",)
+BLOCK_CONDS = ("coroom@pause", "coroom@speech", "coroom@floor", "coroom@both")
+POOLED_ROWS = {
+ "_real_quality": ("families", REAL_FAMILIES),
+ "_real_cleanup": ("items", CLEANUP_FAMILIES),
+ "_coroom": ("items", BLOCK_CONDS),
+}
+
+
+def residual_db(energies: list) -> float:
+ """Returns one item's bounded residual (scoreresidual.babble_metrics)."""
+ # pylint: disable-next=import-outside-toplevel
+ import scoreresidual # imported here: it loads the audio stack
+
+ return scoreresidual.babble_metrics(energies)
+
+
+def level_saturated(level_cal_db) -> bool:
+ """Returns whether a system's level calibration hit the scorer's bound.
+
+ The bound is common.MAX_LEVEL_CAL_DB.
+
+ The scorer aligns a system's level to the input by at most that much; an
+ output further off is at a scale of its own, every calibrated metric of it
+ carries the remainder, and no ranking or paired comparison may read it. The
+ leaderboard, the paired comparisons and the panel report all decide through
+ this one rule.
+ """
+ return (isinstance(level_cal_db,
+ (int, float)) and math.isfinite(level_cal_db) and
+ abs(level_cal_db) >= common.MAX_LEVEL_CAL_DB)
+
+
+def saturated_systems(*metadata: dict) -> list:
+ """Returns the names of the systems whose level calibration saturated.
+
+ The names are taken from the given per-item headers.
+ """
+ return [
+ m.get("system", "?")
+ for m in metadata
+ if level_saturated(m.get("level_cal_db"))
+ ]
+
+
+def same_audio(base: dict, records: list[dict], what: str) -> None:
+ """Refuse sidecar records not measured on the audio of the base records.
+
+ Every per-item record carries the identity of what it read (``identity``:
+ the output samples, the mixture and reference files, the item's semantics).
+ A sidecar record measured the same audio when its output, mixture and
+ reference equal the base record's and its semantics agree on every field the
+ base states; a sidecar may add inputs of its own (the primary-speaker
+ segments it scored). Anything else measured other audio, an earlier render,
+ a changed reference, and must never be merged with it. ``base`` maps item
+ ids to base records; records of items the base does not hold are an
+ inventory error.
+ """
+ for record in records:
+ mine = base.get(record["id"])
+ if mine is None:
+ raise ValueError(
+ f"{what}: {record['id']} is not in the base records")
+ theirs, ours = record.get("identity") or {}, mine.get("identity") or {}
+ same = all(
+ theirs.get(k) == ours.get(k) for k in ("output", "mix", "ref"))
+ stated = ours.get("semantics") or {}
+ same = same and all((theirs.get("semantics") or {}).get(k) == v
+ for k, v in stated.items())
+ if not same or not ours:
+ raise ValueError(
+ f"{what}: {record['id']} was measured on other audio than the"
+ " base scores (output, mixture, reference or semantics"
+ " differ); re-run it")
+
+
+def load_system(results: str | pathlib.Path,
+ system: str) -> tuple[dict, list[dict]]:
+ """Loads a system's observations and the sidecars that match them.
+
+ Foreign identities and measurements of other audio are never accepted.
+ """
+ root = pathlib.Path(results)
+ metadata, rows = observations.read(root / f"{system}.items.jsonl")
+ if metadata["system"] != system:
+ raise ValueError("per-item system identity differs from filename")
+ by_id = {r["id"]: r for r in rows}
+ metadata["sidecar_scorers"] = {}
+ for suffix, keys in SIDECAR_KEYS.items():
+ path = root / f"{system}.{suffix}.items.jsonl"
+ if not path.exists():
+ continue
+ side, extra = observations.read(path)
+ if any(side.get(k) != metadata.get(k) for k in (*IDENTITY, "system")):
+ raise ValueError(f"{suffix} per-item identity mismatch")
+ if not side.get("scorer_sha256"):
+ raise ValueError(f"{suffix} per-item scorer identity is missing")
+ metadata["sidecar_scorers"][suffix] = side["scorer_sha256"]
+ same_audio(by_id, extra, f"{system}.{suffix}")
+ for record in extra:
+ base = by_id.get(record["id"])
+ if base is None or any(
+ base.get(k) != record.get(k)
+ for k in (*GROUPS, "condition")):
+ raise ValueError(
+ "sidecar observations do not match the base inventory")
+ for key in keys:
+ base["metrics"].pop(key, None)
+ if record["output_status"] == "ok":
+ base["metrics"].update(record["metrics"])
+ if "nv_blocks" in record["metrics"]:
+ base["metrics"].update(
+ lost_counts(record,
+ metadata.get("level_cal_db") or 0.0))
+ return metadata, rows
+
+
+def lost_counts(record: dict, level_cal_db: float) -> dict:
+ """Returns a kept record's lost blocks, read at ``level_cal_db``.
+
+ The sidecar stores the counts it read at the calibration of its own pass. A
+ pairing reads the blocks' raw levels again at the base scores' calibration,
+ as it reads deleted speech, so a count never comes from another gain than
+ the scores it is paired with.
+
+ Raises:
+ ValueError: The record keeps no block levels to read again.
+ """
+ kept_db = (record.get("measurements") or {}).get("nv_kept_db")
+ if kept_db is None:
+ raise ValueError(f"{record['id']}: a kept record without its block"
+ " levels: re-run scorekept.py")
+ gone = int(np.sum(levels.lost(kept_db, level_cal_db)))
+ counts = {"nv_lost": gone, "nv_blocks": len(kept_db)}
+ if kept_db:
+ counts["nv_lost_pct"] = 100.0 * gone / len(kept_db)
+ return counts
+
+
+def aligned(left: tuple,
+ right: tuple) -> tuple[dict, dict, list[dict], list[dict]]:
+ """Pair identical inventories.
+
+ Silent intersections and group changes are refused.
+ """
+ lm, lr = left
+ rm, rr = right
+ if any(lm.get(k) != rm.get(k) for k in IDENTITY):
+ raise ValueError(
+ "paired results have different set, subset, or anchor identities")
+ if (not lm.get("scorer_sha256") or
+ lm.get("scorer_sha256") != rm.get("scorer_sha256") or
+ lm.get("sidecar_scorers", {}) != rm.get("sidecar_scorers", {})):
+ raise ValueError(
+ "paired results were produced by different reference scorers")
+ a, b = {r["id"]: r for r in lr}, {r["id"]: r for r in rr}
+ if set(a) != set(b):
+ raise ValueError(
+ "paired result inventories differ; intersections are not"
+ " comparisons")
+ ids = sorted(a)
+ for uid in ids:
+ if any(a[uid].get(k) != b[uid].get(k)
+ for k in (*GROUPS, "condition", "language")):
+ raise ValueError("paired source groups or condition labels differ")
+ return lm, rm, [a[i] for i in ids], [b[i] for i in ids]
+
+
+def weights(groups: list[list],
+ n_boot: int = 2000,
+ seed: int = 0) -> Iterator[np.ndarray]:
+ """Yield deterministic product-multinomial weights.
+
+ The weights are for crossed source factors.
+
+ None means that an observation has no draw from that factor (clean audio
+ has no noise bed). Identical factor partitions are resampled only once.
+ """
+ if n_boot < 100 or not groups or not groups[0]:
+ raise ValueError(
+ "at least 100 bootstrap replicates and nonempty groups are required"
+ )
+ n = len(groups[0])
+ factors, seen = [], set()
+ for group in groups:
+ if len(group) != n:
+ raise ValueError("cluster vectors have different lengths")
+ labels = sorted({str(v) for v in group if v is not None})
+ mapping = {v: i for i, v in enumerate(labels)}
+ indices = np.array(
+ [mapping[str(v)] if v is not None else -1 for v in group])
+ partition = tuple(indices.tolist())
+ if partition in seen or len(labels) <= 1:
+ continue
+ seen.add(partition)
+ factors.append((indices, len(labels)))
+ if not factors:
+ raise ValueError(
+ "uncertainty requires at least two independent source groups")
+ rng = np.random.default_rng(seed)
+ for _ in range(n_boot):
+ result = np.ones(n, dtype=float)
+ for indices, count in factors:
+ frequency = rng.multinomial(count, np.full(count, 1 / count))
+ present = indices >= 0
+ result[present] *= frequency[indices[present]]
+ yield result
+
+
+def interval(reducer: Callable,
+ groups: list[list],
+ n_boot: int = 2000,
+ seed: int = 0) -> dict:
+ """Evaluate a paired effect and its percentile interval.
+
+ The interval is taken under source resampling.
+ """
+ estimate = float(reducer(np.ones(len(groups[0]))))
+ if not math.isfinite(estimate):
+ raise ValueError("paired effect is not finite")
+ values = [float(reducer(w)) for w in weights(groups, n_boot, seed)]
+ finite = np.array([v for v in values if math.isfinite(v)])
+ if len(finite) < 0.95 * n_boot:
+ raise ValueError(
+ "too many empty bootstrap cells; increase independent source"
+ " coverage")
+ low, high = np.quantile(finite, [0.025, 0.975]).tolist()
+ return {
+ "delta":
+ estimate,
+ "ci95": [low, high],
+ "excludes_zero":
+ low > 0 or high < 0,
+ "n_boot":
+ n_boot,
+ "n_valid_boot":
+ len(finite),
+ "seed":
+ seed,
+ "cluster_counts": [
+ len({v for v in g if v is not None}) for g in groups
+ ],
+ }
+
+
+def value(record: dict, metric: str, metadata: dict) -> float:
+ """Reads one item's value of a row, under the board's level convention.
+
+ As ``levels.py`` states it: the system's output gain, ``level_cal_db`` of
+ its records, is undone wherever the board undoes it, and the level and
+ high-band errors are the item's absolute errors.
+ """
+ if record.get("output_status") != "ok":
+ return float("nan")
+ metrics = record.get("metrics", {})
+ cal = metadata.get("level_cal_db") or 0.0
+ raw = metrics.get(metric)
+ if metric == "_level_err":
+ gain = metrics.get("out_in_rms_db")
+ raw = (levels.level_error_db(gain) if isinstance(gain,
+ (int,
+ float)) else None)
+ elif metric == "_hf_err":
+ bands = metrics.get("band_kept_db")
+ raw = levels.hf_error_db(bands, cal) if bands else None
+ elif metric == "band_added_db":
+ # derived from the item's per-band levels as the loader derives the
+ # aggregate (scorefiles.band_added_db); a gain cancels, so no level
+ first = dict(scorefiles.BAND_LIMITED_ROWS).get(record.get("condition"))
+ raw = (scorefiles.band_added_db(metrics, first)
+ if first is not None else None)
+ elif metric in ("babble_supp_db", "babble_supp_db_nb"):
+ energies = metrics.get(metric.replace("supp_db", "energy"))
+ raw = levels.suppression_db(energies, cal) if energies else None
+ elif metric in ("babble_resid_db", "babble_resid_db_nb"):
+ energies = metrics.get(metric.replace("resid_db", "energy"))
+ raw = residual_db(energies) if energies else None
+ elif metric == "nonvoiced_supp_db" and isinstance(raw, (int, float)):
+ raw = levels.energy_db(raw, cal)
+ elif metric in CALIBRATED and isinstance(raw, (int, float)):
+ raw = levels.energy_db(raw, cal)
+ if not isinstance(raw, (int, float)) or not math.isfinite(raw):
+ return float("nan")
+ return float(raw)
+
+
+def band_vector(record: dict, first: int | None) -> list | None:
+ """Returns one item's per-band levels for the band row, or None.
+
+ None without the bands, with a band missing, or off the band-limited rows
+ (``first`` None). The board pools these vectors over the items before it
+ derives the row (``scorefiles.band_added_db``), so a comparison pools them
+ the same way rather than averaging the items' own values.
+ """
+ if first is None or record.get("output_status") != "ok":
+ return None
+ bands = record.get("metrics", {}).get("band_kept_db")
+ if not isinstance(bands, list) or len(bands) <= first or not all(
+ isinstance(b, (int, float)) and math.isfinite(b) for b in bands):
+ return None
+ return [float(b) for b in bands]
+
+
+def paired(
+ left: tuple,
+ right: tuple,
+ condition: str,
+ metric: str,
+ direction: int = 1,
+ n_boot: int = 2000,
+ seed: int = 0,
+) -> dict:
+ """Returns the mean oriented left-minus-right effect.
+
+ The effect is computed for one condition/metric. The band row
+ (``band_added_db``) is pooled as the board pools it: the row's function of
+ the mean per-band levels, not the mean of the items' own values.
+ """
+ if direction not in (-1, 1):
+ raise ValueError("metric direction must be -1 or 1")
+ lm, rm, lr, rr = aligned(left, right)
+ if metric in CALIBRATED and saturated_systems(lm, rm):
+ raise ValueError(
+ "level calibration saturated for"
+ f" {', '.join(saturated_systems(lm, rm))}: {metric} is a calibrated"
+ " metric and cannot be compared")
+ selected = [(a, b) for a, b in zip(lr, rr) if a["condition"] == condition]
+ band_row = metric == "band_added_db"
+ first = dict(scorefiles.BAND_LIMITED_ROWS).get(condition)
+
+ def read(record, meta):
+ if band_row:
+ return band_vector(record, first)
+ v = value(record, metric, meta)
+ return v if math.isfinite(v) else None
+
+ complete = [(a, b, read(a, lm), read(b, rm)) for a, b in selected]
+ complete = [v for v in complete if v[2] is not None and v[3] is not None]
+ if len(complete) < 2:
+ raise ValueError("too few paired finite observations")
+ groups = [[a.get(key) for a, _, _, _ in complete] for key in GROUPS]
+ sides = delta = None
+ if band_row:
+ sides = [
+ np.array([v[2] for v in complete]),
+ np.array([v[3] for v in complete])
+ ]
+ else:
+ delta = direction * np.array([a - b for _, _, a, b in complete])
+
+ def reduce(w):
+ if not w.sum():
+ return float("nan")
+ if not band_row:
+ return float(w @ delta / w.sum())
+ pooled = [
+ scorefiles.band_added_db({"band_kept_db": list(w @ side / w.sum())},
+ first) for side in sides
+ ]
+ return float(direction * (pooled[0] - pooled[1]))
+
+ result = interval(reduce, groups, n_boot, seed)
+ left_count = sum(read(a, lm) is not None for a, _ in selected)
+ right_count = sum(read(b, rm) is not None for _, b in selected)
+ result.update(
+ condition=condition,
+ metric=metric,
+ direction=direction,
+ n_paired=len(complete),
+ n_expected=len(selected),
+ n_left=left_count,
+ n_right=right_count,
+ matched_cohort=len(complete) == left_count == right_count,
+ groups_verified=all(
+ a.get("groups_verified") and b.get("groups_verified")
+ for a, b, _, _ in complete),
+ )
+ return result
+
+
+def registry_parts() -> tuple[dict | None, list]:
+ """Returns how the published composite combines its axes.
+
+ The parts of the axis registry, and the axes scored beside the composite.
+ """
+ # pylint: disable-next=import-outside-toplevel
+ import admission # imported here: admission imports this module
+
+ registry = admission.load()
+ return admission.parts(registry), admission.outside(registry)
+
+
+def registry_boards() -> dict | None:
+ """Returns the registry's boards, {board: [parts]}, or None.
+
+ None when the registry publishes one composite of every part
+ (``admission.boards``).
+ """
+ # pylint: disable-next=import-outside-toplevel
+ import admission # imported here: admission imports this module
+
+ return admission.boards(admission.load())
+
+
+def registry_assignment() -> dict | None:
+ """Returns the registry's rule deciding which board ranks a system, or None
+ (``admission.assignment``)."""
+ # pylint: disable-next=import-outside-toplevel
+ import admission # imported here: admission imports this module
+
+ return admission.assignment(admission.load())
+
+
+def pooled_bands(records: list) -> dict:
+ """Returns {band-limited row: {"band_kept_db": levels}} of one system.
+
+ Each band's level is the mean over the row's items that hold it, the way
+ the scorer pools them into the row's cell (``scorebench.aggregate``), so
+ ``scorefiles.band_above_input_db`` reads the records as it reads the board.
+ """
+ cells = {}
+ for condition, first in scorefiles.BAND_LIMITED_ROWS:
+ rows = [
+ r["metrics"].get("band_kept_db") for r in records if
+ r.get("condition") == condition and r.get("output_status") == "ok"
+ ]
+ rows = [b for b in rows if isinstance(b, list) and len(b) > first]
+ if not rows:
+ continue
+ width = min(len(b) for b in rows)
+ levels_ = np.array(
+ [[
+ float(v) if isinstance(v, (int, float)) else np.nan
+ for v in b[:width]
+ ]
+ for b in rows],
+ dtype=float,
+ )
+ counts = np.isfinite(levels_).sum(0)
+ totals = np.where(np.isfinite(levels_), levels_, 0.0).sum(0)
+ cells[condition] = {
+ "band_kept_db": [
+ float(t / c) if c else float("nan")
+ for t, c in zip(totals, counts)
+ ]
+ }
+ return cells
+
+
+def records_board(records: list) -> str | None:
+ """Returns the board the registry's rule ranks a system on, from its
+ per-item records, or None.
+
+ None when the registry publishes no boards, and when the records hold no
+ band-limited rows to assign one (a development panel holds none).
+ """
+ boards = registry_boards()
+ if not boards:
+ return None
+ return scorefiles.assigned_board(pooled_bands(records),
+ registry_assignment(), next(iter(boards)))
+
+
+def compared_parts(axes: dict, parts, board: str | None, records: tuple):
+ """Returns (parts, axes read, aside, board) of a composite comparison.
+
+ ``parts`` "registry" reads the registry's parts. ``board`` names one of the
+ registry's boards to read alone; the axes requested must cover it. Without
+ a name, a request that covers more than one board (the whole registry)
+ reads the board the registry's rule ranks both systems on, from their
+ records (``records_board``); two systems the rule ranks on different
+ boards, or a system it cannot place, are refused, since the comparison
+ would otherwise answer for a task it did not name. Any other request reads
+ every axis requested, in the parts it holds, and an axis beside every part
+ as a group of its own; without boards the whole registry reads the
+ composite. A custom grouping must hold every axis requested exactly once.
+ None reads the plain mean.
+
+ Raises:
+ ValueError: The board is unknown, uncovered, unplaceable or ambiguous,
+ or a grouping drops or repeats a requested axis.
+ """
+ if parts != "registry":
+ if board is not None:
+ raise ValueError("a board is read with the registry's parts")
+ if parts is None:
+ return None, axes, (), None
+ grouped = {
+ name: [a for a in members if a in axes]
+ for name, members in parts.items()
+ }
+ grouped = {
+ name: members for name, members in grouped.items() if members
+ }
+ if sorted(a for members in grouped.values()
+ for a in members) != sorted(axes):
+ raise ValueError(
+ "a custom grouping holds every axis requested exactly once")
+ return grouped, axes, (), None
+ members, aside = registry_parts()
+ boards = registry_boards()
+ if board is not None and not (boards and board in boards):
+ raise ValueError(f"no board {board!r} in the registry")
+ if not members:
+ return None, axes, (), None
+ covered = [
+ name for name, held in (boards or {}).items()
+ if {a for part in held for a in members[part]} <= set(axes)
+ ]
+ if board is not None and board not in covered:
+ raise ValueError(f"the axes requested do not cover the {board} board")
+ if len(covered) > 1 and board is None:
+ sides = [records_board(r) for r in records]
+ if None in sides:
+ raise ValueError(
+ "the records hold no band-limited rows to assign a board; name"
+ " the board to compare on (" + ", ".join(boards) + ")")
+ if sides[0] != sides[1]:
+ raise ValueError(
+ f"the two systems are ranked on different boards ({sides[0]},"
+ f" {sides[1]}); name the board to compare on")
+ board = sides[0]
+ if board is not None:
+ held = {part: members[part] for part in boards[board]}
+ read = {a for axes_ in held.values() for a in axes_}
+ return held, {a: r for a, r in axes.items() if a in read}, (), board
+ inside = {a for part in members.values() for a in part}
+ if not boards and inside <= set(axes):
+ # one composite of every part, the axes beside it shown and not read
+ return members, axes, tuple(aside), None
+ grouped = {
+ name: [a for a in held if a in axes] for name, held in members.items()
+ }
+ grouped = {name: held for name, held in grouped.items() if held}
+ for axis in axes:
+ if axis not in inside:
+ grouped[axis] = [axis]
+ return grouped, axes, (), None
+
+
+def composite_delta(
+ left: tuple,
+ right: tuple,
+ calibration: dict,
+ axes: dict,
+ n_boot: int = 2000,
+ seed: int = 0,
+ parts: dict | str | None = "registry",
+ board: str | None = None,
+) -> dict:
+ """Bootstrap the actual composite.
+
+ Its nonlinear reducers and anchors are preserved.
+
+ Clean-level calibration and anchor endpoints stay frozen. Deletion pools
+ segment counts and the voice outside speech its block counts; HF error takes
+ the absolute value after band averaging, exactly as the leaderboard does.
+ Both systems need the same metric cohort. ``parts`` and ``board`` say what
+ is compared (``compared_parts``): one board's score, named or assigned by
+ the registry's rule, every axis of a subset, a custom grouping or the plain
+ mean. The result names the board it read (None for anything else) and the
+ grouping.
+ """
+ lm, rm, lr, rr = aligned(left, right)
+ parts, axes, aside, board = compared_parts(axes, parts, board, (lr, rr))
+ if saturated_systems(lm, rm):
+ raise ValueError(
+ "level calibration saturated for"
+ f" {', '.join(saturated_systems(lm, rm))}: no calibrated metric is"
+ " valid, so there is no composite to compare")
+ for meta in (lm, rm):
+ anchors.validate_scores(
+ calibration,
+ {
+ "paired": {
+ "_set_id": meta["set_id"],
+ "_subset": meta["subset"],
+ "_anchors_version": meta["anchors_version"],
+ "_anchors_sha256": meta["anchors_sha256"],
+ }
+ },
+ )
+ conditions = {
+ condition for members in axes.values() for condition, _, _ in members
+ }
+ for pooled in conditions & set(POOLED_ROWS):
+ conditions |= set(POOLED_ROWS[pooled][1])
+ selected = [
+ i for i, r in enumerate(lr) if r["condition"] in conditions or
+ r["id"] in calibration["deletion_cohort"]
+ ]
+ lr, rr = [lr[i] for i in selected], [rr[i] for i in selected]
+ if not all(r.get("groups_verified") for r in lr + rr):
+ raise ValueError("composite intervals require verified source groups")
+ ids = {r["id"]: i for i, r in enumerate(lr)}
+ cells = {}
+ for axis, members in axes.items():
+ cells[axis] = []
+ for condition, metric, _ in members:
+ point = calibration["points"][anchors.row_key(condition, metric)]
+ extra = None
+ if condition == "_deletion":
+ cohort = calibration["deletion_cohort"]
+ if not set(cohort) <= set(ids):
+ raise ValueError(
+ "fixed deletion cohort is missing from per-item records"
+ )
+ indices = np.array([ids[uid] for uid in sorted(cohort)])
+ arrays = []
+ for records, meta in ((lr, lm), (rr, rm)):
+ counts = []
+ cal = meta.get("level_cal_db") or 0.0
+ for uid in sorted(cohort):
+ record = records[ids[uid]]
+ drops = record["metrics"].get("primary_drops") or []
+ if (record["output_status"] != "ok" or
+ len(drops) != cohort[uid]):
+ raise ValueError(
+ "primary deletion counts do not cover the fixed"
+ " cohort")
+ counts.append((sum(levels.deleted(drops,
+ cal)), len(drops)))
+ arrays.append(np.array(counts, dtype=float))
+ kind = "deletion"
+ elif condition in POOLED_ROWS:
+ how, families = POOLED_ROWS[condition]
+ members = []
+ for family in families:
+ chosen = [
+ i for i, r in enumerate(lr) if r["condition"] == family
+ ]
+ if any(lr[i]["output_status"] != "ok" or
+ rr[i]["output_status"] != "ok" for i in chosen):
+ raise ValueError(
+ "incomplete system output in a composite condition")
+ left = [
+ i for i in chosen
+ if math.isfinite(value(lr[i], metric, lm))
+ ]
+ right = [
+ i for i in chosen
+ if math.isfinite(value(rr[i], metric, rm))
+ ]
+ if left != right:
+ raise ValueError(
+ f"different per-metric cohorts: {family}/{metric}")
+ members.append(np.array(left, dtype=int))
+ if how == "items":
+ members = [np.concatenate(members)]
+ if any(len(m) < scorefiles.MIN_ITEMS for m in members):
+ raise ValueError(
+ f"incomplete per-metric cohorts: {condition}/{metric}")
+ indices = members
+ arrays = [[
+ np.array([value(rows[i], metric, meta)
+ for i in m])
+ for m in members
+ ]
+ for rows, meta in ((lr, lm), (rr, rm))]
+ kind = "families"
+ else:
+ selected = [
+ i for i, r in enumerate(lr) if r["condition"] == condition
+ ]
+ if any(lr[i]["output_status"] != "ok" or
+ rr[i]["output_status"] != "ok" for i in selected):
+ raise ValueError(
+ "incomplete system output in a composite condition")
+ if metric == "band_added_db":
+ # pooled as the board pools it: the row's function of the
+ # mean per-band levels (scorefiles.band_added_db)
+ first = dict(scorefiles.BAND_LIMITED_ROWS).get(condition)
+ mask_left = [
+ i for i in selected
+ if band_vector(lr[i], first) is not None
+ ]
+ mask_right = [
+ i for i in selected
+ if band_vector(rr[i], first) is not None
+ ]
+ if (mask_left != mask_right or
+ len(mask_left) < scorefiles.MIN_ITEMS):
+ raise ValueError(
+ "incomplete or different per-metric cohorts:"
+ f" {condition}/{metric}")
+ indices = np.array(mask_left)
+ arrays = [
+ np.array([band_vector(rows[i], first)
+ for i in indices])
+ for rows in (lr, rr)
+ ]
+ kind, extra = "bands", first
+ elif metric in POOLED:
+ indices = np.array(selected)
+ arrays = []
+ for records in (lr, rr):
+ counts = [[
+ records[i]["metrics"].get(k) for k in POOLED[metric]
+ ] for i in selected]
+ if any(not isinstance(v, int) or v < 0
+ for pair in counts
+ for v in pair):
+ raise ValueError(
+ f"missing pooled counts: {condition}/{metric}")
+ arrays.append(np.array(counts, dtype=float))
+ # items carrying the observation
+ observing = int((arrays[0][:, 1] > 0).sum())
+ if observing < scorefiles.MIN_ITEMS or not np.array_equal(
+ arrays[0][:, 1], arrays[1][:, 1]):
+ raise ValueError(
+ "incomplete or different pooled cohorts:"
+ f" {condition}/{metric} ({observing} items"
+ " observe it)")
+ kind = "pooled"
+ else:
+ field = metric
+ mask_left = [
+ i for i in selected
+ if math.isfinite(value(lr[i], field, lm))
+ ]
+ mask_right = [
+ i for i in selected
+ if math.isfinite(value(rr[i], field, rm))
+ ]
+ if (mask_left != mask_right or
+ len(mask_left) < scorefiles.MIN_ITEMS):
+ raise ValueError(
+ "incomplete or different per-metric cohorts:"
+ f" {condition}/{metric}")
+ indices = np.array(mask_left)
+ arrays = [
+ np.array([value(rows[i], field, meta)
+ for i in indices])
+ for rows, meta in ((lr, lm), (rr, rm))
+ ]
+ kind = "mean"
+ cells[axis].append((indices, arrays, kind, point, extra))
+
+ def score(w, system):
+ axis_scores = {}
+ for axis, members in cells.items():
+ values = []
+ for indices, arrays, kind, point, extra in members:
+ array = arrays[system]
+ if kind == "families":
+ means = []
+ for member, values_f in zip(indices, array):
+ weight = w[member]
+ if not weight.sum():
+ return float("nan")
+ means.append(weight @ values_f / weight.sum())
+ values.append(
+ anchors.normalize(float(np.mean(means)), point))
+ continue
+ weight = w[indices]
+ if not weight.sum():
+ return float("nan")
+ if kind in ("deletion", "pooled"):
+ total = weight @ array[:, 1]
+ if not total:
+ return float("nan")
+ raw = 100 * (weight @ array[:, 0]) / total
+ elif kind == "bands":
+ raw = scorefiles.band_added_db(
+ {"band_kept_db": list(weight @ array / weight.sum())},
+ extra)
+ else:
+ raw = weight @ array / weight.sum()
+ values.append(anchors.normalize(float(raw), point))
+ axis_scores[axis] = sum(values) / len(values)
+ return anchors.composite(axis_scores, parts, aside)
+
+ groups = [[r.get(key) for r in lr] for key in GROUPS]
+ result = interval(lambda w: score(w, 0) - score(w, 1), groups, n_boot, seed)
+ ones = np.ones(len(lr))
+ result.update(left=score(ones, 0),
+ right=score(ones, 1),
+ n_items=len(lr),
+ board=board,
+ parts=parts)
+ return result
+
+
+def main() -> None:
+ """Write an aggregate paired comparison.
+
+ No item IDs or transcripts are exported.
+ """
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("left")
+ parser.add_argument("right")
+ parser.add_argument("--results", required=True)
+ parser.add_argument("--condition", required=True)
+ parser.add_argument("--metric", required=True)
+ parser.add_argument("--direction", type=int, choices=(-1, 1), default=1)
+ parser.add_argument("--bootstrap", type=int, default=2000)
+ parser.add_argument("--seed", type=int, default=0)
+ parser.add_argument("--out", required=True)
+ args = parser.parse_args()
+ left, right = (
+ load_system(args.results, name) for name in (args.left, args.right))
+ if left[0].get("sealed") or right[0].get("sealed"):
+ raise SystemExit(
+ "sealed comparisons must use the confirmation gate and its query"
+ " ledger")
+ result = paired(
+ left,
+ right,
+ args.condition,
+ args.metric,
+ args.direction,
+ args.bootstrap,
+ args.seed,
+ )
+ result.update({k: left[0].get(k) for k in IDENTITY})
+ result.update(left=args.left, right=args.right)
+ anchors.atomic_json(args.out, result)
+ print(json.dumps(result, indent=2, allow_nan=False))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/bench/scripts/contracts.py b/bench/scripts/contracts.py
new file mode 100644
index 0000000..1c51dd6
--- /dev/null
+++ b/bench/scripts/contracts.py
@@ -0,0 +1,179 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Task contracts: what every condition of the set holds a system to.
+
+The set asks three different things of a system, and a number only means
+something next to the one it was asked. ``PROFILES`` states them, ``FAMILIES``
+assigns every condition family to one, ``CONVENTIONS`` lists the changes a
+scorer undoes because nobody can hear them. ``AXES`` states what the board's
+axes may score: every denoising row, and the rooms of the restoration profile in
+one axis of their own, because most recordings are made in rooms and a board
+that leaves them out says nothing about most recordings. Whether that axis is
+read by a score or shown beside both is the axis registry's decision
+(``admission.outside``). ``check_axes`` refuses any other row, so a voice-policy
+or restoration row can only enter an axis as a stated decision, never by
+accident. A family that is not listed has no contract yet: ``profile`` raises
+instead of guessing.
+"""
+
+import common
+
+PROFILES = {
+ "denoise": (
+ "The voice as recorded stays, its laughs, breaths and sighs with it, at"
+ " its level, in its band and with its own room; everything that is not"
+ " that voice goes."),
+ "voice_policy":
+ ("Which voices are content is the question, and the boards' own"
+ " answer is the denoise contract: the voice the recording is of stays"
+ " and a competing talker goes. These rows read the other answers and"
+ " stay outside both scores: a singer who is the target stays, a"
+ " song's own singer behind speech goes, both sides of a conversation"
+ " stay, and so do the several talkers of a long item, who take turns;"
+ " for a system that keeps one speaker the conversation and long rows"
+ " are the diagnostics of that choice, not targets."),
+ "restoration": (
+ "The reference is better than the voice in the input: the dry voice out"
+ " of a reverberant one. A system that only removes what was added is"
+ " not expected to reach it: the real rooms make the restoration score,"
+ " which the denoising score does not read."),
+}
+FAMILIES = {
+ "denoise": (
+ "ambience",
+ "animals",
+ "appliance",
+ "babble",
+ "cheer",
+ "cheer_tail",
+ "clean",
+ "coroom",
+ "events",
+ "everyday",
+ "expressive_tail",
+ "household",
+ "music",
+ "noise_only",
+ "nonverbal",
+ "nonverbal_clean",
+ "quiet",
+ "rain",
+ "real_dirty",
+ "real_everyday",
+ "real_multi",
+ "real_noisy",
+ "real_wild",
+ "soft",
+ "srsweep_8k",
+ "srsweep_16k",
+ "srsweep_24k",
+ "srsweep_44.1k",
+ "srsweep_48k",
+ "stationary",
+ "talker",
+ "tools",
+ "traffic",
+ "transition",
+ "water",
+ "whisper",
+ "wild",
+ "wind",
+ ),
+ "voice_policy": ("conversation", "long", "music_vocal", "singer"),
+ "restoration": ("reverb_real", "reverb_synth"),
+}
+# What the board's axes may score: {profile: the axes its rows may feed, None
+# for any}. An axis named here belongs to that profile alone.
+AXES = {"denoise": None, "restoration": ("room",)}
+CONVENTIONS = (
+ (
+ "delay",
+ f"up to {1000 * common.MAX_LAG // common.SR} ms",
+ "measured and undone before anything is read",
+ ),
+ ("polarity", "a flipped sign", "undone with the delay"),
+ (
+ "gain",
+ f"up to {common.MAX_LEVEL_CAL_DB:g} dB",
+ ("removed from the retention metrics and scored "
+ "once, as the level change on clean speech"),
+ ),
+)
+_PROFILE_OF = {
+ family: name for name, families in FAMILIES.items() for family in families
+}
+
+
+def profile(condition: str) -> str:
+ """Returns the profile of a condition (``babble@-5`` -> ``denoise``).
+
+ Raises:
+ KeyError: The condition has no profile.
+ """
+ family = condition.split("@", 1)[0]
+ # pooled pseudo-conditions of the real recordings (``_deletion``)
+ if family.startswith("_"):
+ return "denoise"
+ return _PROFILE_OF[family]
+
+
+def check_axes(axes: dict, allowed: dict | None = None) -> None:
+ """Refuse an axis table whose rows ask for what ``allowed`` does not state.
+
+ Args:
+ axes: {axis: [(condition, metric, direction), ...]} of one tier.
+ allowed: {profile: axes or None}; ``AXES`` by default.
+
+ Raises:
+ ValueError: A row belongs to a profile the axes do not score, or
+ sits in an axis its profile may not feed, or shares an axis reserved
+ for another profile.
+ """
+ allowed = AXES if allowed is None else allowed
+ reserved = {
+ axis: name for name, named in allowed.items() for axis in named or ()
+ }
+ for axis, rows in axes.items():
+ for condition, metric, _ in rows:
+ name = profile(condition)
+ if name not in allowed:
+ raise ValueError(
+ f"{axis} row {condition}/{metric} is a {name} condition:"
+ f" the axes score {', '.join(allowed)} only")
+ if allowed[name] is not None and axis not in allowed[name]:
+ raise ValueError(
+ f"{axis} row {condition}/{metric} is a {name} condition:"
+ f" the axes score {name} in"
+ f" {', '.join(allowed[name])} only")
+ if reserved.get(axis, name) != name:
+ raise ValueError(
+ f"{axis} row {condition}/{metric} is a {name} condition in"
+ f" the axis that scores {reserved[axis]}")
+
+
+def axes_statement(allowed: dict | None = None) -> str:
+ """One sentence saying what the axes score, for the board and its JSON."""
+ allowed = AXES if allowed is None else allowed
+ return "the axes score " + " and ".join(
+ (f"{name} rows" if axes is
+ None else f"{name} rows in the {', '.join(axes)} axis alone")
+ for name, axes in allowed.items())
+
+
+def by_profile(conditions) -> dict:
+ """{profile: sorted conditions} for the conditions given."""
+ out = {name: [] for name in PROFILES}
+ for condition in sorted(set(conditions)):
+ out[profile(condition)].append(condition)
+ return out
diff --git a/bench/scripts/controls.py b/bench/scripts/controls.py
new file mode 100644
index 0000000..620adb1
--- /dev/null
+++ b/bench/scripts/controls.py
@@ -0,0 +1,897 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Frozen metric controls: known damage in, what every metric says about it out.
+
+ python bench/scripts/controls.py [--per-condition 24]
+ [--conds clean,babble@+4,...] [--controls reference,delete80ms,...]
+ [--out staging/controls] [--keep-renders]
+ [--markdown-out bench/CONTROLS.md]
+
+A metric is only worth ranking systems by if it reacts to damage someone could
+hear and stays quiet about changes nobody could. Each control is a synthetic
+"system" built from the paired audio of a fixed, language-stratified slice of
+the set: the reference returned untouched, the reference with one known defect,
+or something that is not the voice at all. Every control is scored by
+``scorebench.score_system``, the code every real system goes through, so the
+table describes the published metrics and not a reimplementation of them.
+
+CONTROLS names the defects, EXPECTED states per control what a sound metric
+suite must say (``check`` compares; the markdown marks every row that fails and
+says which metrics are blind). On the same-room block every control is also
+rendered on the reference track, and the block's rows are read from the two
+renders as the board reads them (``scoreevents.py``). Processing an output a
+second time needs a model and lives in twicetest.py.
+"""
+
+import argparse
+import hashlib
+import json
+import os
+import shutil
+import sys
+
+import numpy as np
+import soundfile as sf
+import torch
+
+import anchors
+import common
+
+SR = common.SR
+DEFAULT_CONDS = (
+ "clean",
+ "babble@+4",
+ "babble@+0",
+ "babble@-5",
+ "ambience@-5",
+ "stationary@-5",
+ "traffic@-5",
+ "music@-6",
+ "wild@-5",
+ "whisper@+0",
+ "coroom@pause",
+ "coroom@speech",
+ "coroom@floor",
+ "coroom@both",
+ "nonverbal_clean",
+)
+# a deletion lands on speech: a frame within this of the loudest
+ACTIVE_DB = 30.0
+# the same-room block (scoreevents.SAME_ROOM) and the gate that tells its
+# transient events from its quiet floor
+BLOCK_CONDS = ("coroom@pause", "coroom@speech", "coroom@floor", "coroom@both")
+BLOCK_COLUMNS = ("event_resid_db", "floor_resid_db", "voice_level_db")
+GATE_DB = -40.0
+N_FFT, HOP = 2048, 512
+
+
+def _seed(item_id: str, salt: str) -> int:
+ return int(hashlib.sha256(f"{salt}:{item_id}".encode()).hexdigest()[:8], 16)
+
+
+def _stft(x: torch.Tensor) -> torch.Tensor:
+ return torch.stft(x,
+ N_FFT,
+ HOP,
+ window=torch.hann_window(N_FFT),
+ return_complex=True)
+
+
+def _istft(z: torch.Tensor, n: int) -> torch.Tensor:
+ return torch.istft(z, N_FFT, HOP, window=torch.hann_window(N_FFT), length=n)
+
+
+def delete(ref: torch.Tensor, seconds: float, item_id: str) -> torch.Tensor:
+ """The reference with one span of speech removed (2 ms raised-cosine edges).
+
+ The span starts at a seeded position among the 10 ms frames within ACTIVE_DB
+ of the loudest, so it always lands on the voice and the same item always
+ loses the same span.
+ """
+ n, span, frame = len(ref), int(seconds * SR), SR // 100
+ if n <= span + 2 * frame:
+ return ref.clone()
+ energy = ref[:n // frame * frame].reshape(-1, frame).pow(2).mean(1)
+ level = 10 * torch.log10(energy + 1e-12)
+ active = torch.nonzero(level > level.max() - ACTIVE_DB).flatten()
+ active = active[active * frame + span < n]
+ if active.numel() == 0:
+ return ref.clone()
+ rng = np.random.default_rng(_seed(item_id, f"delete{seconds}"))
+ start = int(active[rng.integers(len(active))]) * frame
+ gain = torch.ones(n)
+ edge = int(0.002 * SR)
+ ramp = 0.5 * (1 + torch.cos(torch.linspace(0, torch.pi, edge)))
+ gain[start:start + span] = 0.0
+ gain[start:start + edge] = ramp
+ gain[start + span - edge:start + span] = ramp.flip(0)
+ return ref * gain
+
+
+def boundaries(ref: torch.Tensor,
+ pause_s: float = 0.15) -> tuple[list[int], list[int]]:
+ """Returns the speech onsets and offsets of a reference, in samples.
+
+ A 10 ms frame within ACTIVE_DB of the loudest is speech. An onset is the
+ first speech frame after at least ``pause_s`` of frames that are not (the
+ item's start counts as such a pause); an offset is the end of the last
+ speech frame before such a pause (the item's end counts as one).
+ """
+ frame = SR // 100
+ n = len(ref) // frame
+ if n == 0:
+ return [], []
+ energy = ref[:n * frame].reshape(-1, frame).pow(2).mean(1)
+ level = 10 * torch.log10(energy + 1e-12)
+ speech = (level > level.max() - ACTIVE_DB).tolist()
+ gap = max(1, int(round(pause_s * 100)))
+ onsets, offsets = [], []
+ quiet = gap
+ for i, active in enumerate(speech):
+ if active:
+ if quiet >= gap:
+ onsets.append(i * frame)
+ quiet = 0
+ continue
+ quiet += 1
+ if quiet == gap and speech[i - gap]:
+ offsets.append((i - gap + 1) * frame)
+ if speech[-1] or 0 < quiet < gap:
+ last = max(i for i, active in enumerate(speech) if active)
+ offsets.append((last + 1) * frame)
+ return onsets, offsets
+
+
+def _silence(ref: torch.Tensor, start: int, span: int) -> torch.Tensor:
+ """The reference with ``span`` samples from ``start`` silenced.
+
+ 2 ms raised-cosine edges, as ``delete`` uses.
+ """
+ gain = torch.ones(len(ref))
+ edge = int(0.002 * SR)
+ ramp = 0.5 * (1 + torch.cos(torch.linspace(0, torch.pi, edge)))
+ gain[start:start + span] = 0.0
+ gain[start:start + edge] = ramp
+ gain[start + span - edge:start + span] = ramp.flip(0)
+ return ref * gain
+
+
+def cut_onset(ref: torch.Tensor, seconds: float,
+ item_id: str) -> tuple[torch.Tensor, int | None]:
+ """The reference with the first ``seconds`` of one word start removed.
+
+ The onset (``boundaries``) is drawn, seeded by the item, among those
+ followed by at least that much signal. Returns the signal and the cut's
+ first sample, None (and the reference unchanged) when no onset fits.
+ """
+ span = int(seconds * SR)
+ onsets, _ = boundaries(ref)
+ usable = [o for o in onsets if o + span <= len(ref)]
+ if not usable:
+ return ref.clone(), None
+ rng = np.random.default_rng(_seed(item_id, f"onset{seconds}"))
+ start = usable[rng.integers(len(usable))]
+ return _silence(ref, start, span), start
+
+
+def cut_tail(ref: torch.Tensor, seconds: float,
+ item_id: str) -> tuple[torch.Tensor, int | None]:
+ """The reference with the last ``seconds`` before one trailing end removed.
+
+ The offset (``boundaries``) is drawn, seeded by the item, among those with
+ at least that much signal before them. Returns the signal and the cut's
+ first sample (the cut ends at the offset), None when no offset fits.
+ """
+ span = int(seconds * SR)
+ _, offsets = boundaries(ref)
+ usable = [o for o in offsets if o - span >= 0]
+ if not usable:
+ return ref.clone(), None
+ rng = np.random.default_rng(_seed(item_id, f"tail{seconds}"))
+ end = usable[rng.integers(len(usable))]
+ return _silence(ref, end - span, span), end - span
+
+
+def invent_high_band(ref: torch.Tensor,
+ item_id: str,
+ low_hz: float = 8000.0) -> torch.Tensor:
+ """Returns the reference with an invented band above ``low_hz``.
+
+ Everything above ``low_hz`` is replaced by noise that follows the band's own
+ envelope and carries its energy: the band a generative system invents, at
+ the level it was. Overlap-add of random phases loses energy, so the noise is
+ scaled back to the band's.
+ """
+ z = _stft(ref)
+ rows = torch.fft.rfftfreq(N_FFT, 1 / SR) >= low_hz
+ gen = torch.Generator().manual_seed(_seed(item_id, "hf"))
+ phase = (torch.rand(int(rows.sum()), z.shape[1], generator=gen) * 2 *
+ torch.pi)
+ noise = torch.zeros_like(z)
+ noise[rows] = z[rows].abs() * torch.exp(1j * phase)
+ noise = _istft(noise, len(ref))
+ low = cut_high_band(ref, low_hz)
+ band = ref - low
+ return low + noise * torch.sqrt(
+ band.pow(2).sum() / (noise.pow(2).sum() + 1e-20))
+
+
+def cut_high_band(ref: torch.Tensor, low_hz: float = 8000.0) -> torch.Tensor:
+ """Returns the reference with everything above ``low_hz`` removed."""
+ z = _stft(ref)
+ z[torch.fft.rfftfreq(N_FFT, 1 / SR) >= low_hz] = 0
+ return _istft(z, len(ref))
+
+
+def resynthesise(ref: torch.Tensor,
+ item_id: str,
+ sigma: float = 0.1) -> torch.Tensor:
+ """Returns the reference with every phase perturbed by N(0, sigma) radians.
+
+ The same spectrogram as another waveform (its clean SI-SDR is in the table):
+ what a vocoder-like system returns when it harms nothing.
+ """
+ z = _stft(ref)
+ gen = torch.Generator().manual_seed(_seed(item_id, "resynth"))
+ z = z * torch.exp(1j * sigma * torch.randn(z.shape, generator=gen))
+ return _istft(z, len(ref))
+
+
+def remove_floor(ref: torch.Tensor, floor_db: float = 50.0) -> torch.Tensor:
+ """Returns the reference with its own floor gated to silence.
+
+ Every 10 ms frame more than ``floor_db`` under the loudest is silenced: the
+ recording's own floor removed, the speech untouched.
+ """
+ frame = SR // 100
+ n = len(ref) // frame * frame
+ level = 10 * torch.log10(ref[:n].reshape(-1, frame).pow(2).mean(1) + 1e-12)
+ keep = (level > level.max() - floor_db).float().repeat_interleave(frame)
+ out = ref.clone()
+ out[:n] = ref[:n] * keep
+ return out
+
+
+def delay(ref: torch.Tensor, seconds: float) -> torch.Tensor:
+ k = int(seconds * SR)
+ return torch.nn.functional.pad(ref, (k, 0))[:len(ref)]
+
+
+def transients(added: torch.Tensor, gate_db: float = GATE_DB) -> torch.Tensor:
+ """Returns what the mixture added above ``gate_db`` dBFS, by 10 ms frame.
+
+ Its transient events kept, its quiet floor (and the quiet tail of every
+ event) gone.
+ """
+ frame = SR // 100
+ n = len(added) // frame * frame
+ frames = added[:n].reshape(-1, frame)
+ level = 10 * torch.log10(frames.pow(2).mean(1) + 1e-12)
+ out = torch.zeros_like(added)
+ out[:n] = (frames * (level >= gate_db).float()[:, None]).reshape(-1)
+ return out
+
+
+def ducked(ref: torch.Tensor,
+ mix: torch.Tensor,
+ db: float = 3.0) -> torch.Tensor:
+ """Returns the reference ``db`` quieter whenever the mixture added anything.
+
+ A gate that turns the voice down to be rid of the noise; on a mixture that
+ added nothing (the clean items) the reference stays as it is.
+ """
+ if float((mix - ref).pow(2).mean()) < 10**(-100 / 10):
+ return ref.clone()
+ return ref * 10**(-db / 20)
+
+
+# name -> (what the "system" returns, builder(ref, mix, item_id))
+CONTROLS = {
+ "reference": ("the clean reference, untouched", lambda r, x, i: r.clone()),
+ "input": ("the unprocessed mixture", lambda r, x, i: x.clone()),
+ "silence": ("nothing", lambda r, x, i: torch.zeros_like(r)),
+ "bedonly": (
+ "the mixture minus the reference: everything but the voice",
+ lambda r, x, i: x - r,
+ ),
+ "gainup6db": (
+ "the reference 6 dB louder",
+ lambda r, x, i: r * 10**(6 / 20),
+ ),
+ "gaindown6db": (
+ "the reference 6 dB quieter",
+ lambda r, x, i: r * 10**(-6 / 20),
+ ),
+ "polarity": ("the reference with its sign flipped", lambda r, x, i: -r),
+ "delay20ms": ("the reference 20 ms late", lambda r, x, i: delay(r, 0.020)),
+ "delete20ms": (
+ "the reference with 20 ms of speech removed",
+ lambda r, x, i: delete(r, 0.020, i),
+ ),
+ "delete40ms": (
+ "the reference with 40 ms of speech removed",
+ lambda r, x, i: delete(r, 0.040, i),
+ ),
+ "delete80ms": (
+ "the reference with 80 ms of speech removed",
+ lambda r, x, i: delete(r, 0.080, i),
+ ),
+ "delete160ms": (
+ "the reference with 160 ms of speech removed",
+ lambda r, x, i: delete(r, 0.160, i),
+ ),
+ "delete320ms": (
+ "the reference with 320 ms of speech removed",
+ lambda r, x, i: delete(r, 0.320, i),
+ ),
+ "hfinvented": (
+ "the reference with 8-24 kHz replaced by noise of the same energy",
+ lambda r, x, i: invent_high_band(r, i),
+ ),
+ "hfcut": (
+ "the reference with 8-24 kHz removed",
+ lambda r, x, i: cut_high_band(r),
+ ),
+ "resynth": (
+ ("the reference re-synthesised: same spectrogram, phases perturbed"
+ " (another waveform)"),
+ lambda r, x, i: resynthesise(r, i),
+ ),
+ "floorless": (
+ "the reference with its own noise floor gated out",
+ lambda r, x, i: remove_floor(r),
+ ),
+ "halfnoise": (
+ "the reference with half of what the mixture added",
+ lambda r, x, i: r + 0.5 * (x - r),
+ ),
+ "transientsleft": (
+ ("the reference with what the mixture added above -40 dBFS: its"
+ " transients left, its quiet floor gone"),
+ lambda r, x, i: r + transients(x - r),
+ ),
+ "floorleft": (
+ ("the reference with what the mixture added under -40 dBFS: its"
+ " quiet floor left, its transients gone"),
+ lambda r, x, i: x - transients(x - r),
+ ),
+ "voiceducked": (
+ ("the reference 3 dB quieter wherever the mixture added anything: a"
+ " gate rid of the noise at the voice's expense, under the voice gate"),
+ lambda r, x, i: ducked(r, x),
+ ),
+}
+
+# What a sound metric suite must say. Keys are columns of ``summarise``; values
+# (op, bound). "fidelity" is the published fidelity axis on the clean items of
+# the slice (0-1).
+# the block's rows under a control that returns the voice, whatever happened
+# to it on the way: nothing of the noise left, the voice's level kept
+BLOCK_CLEAN = {
+ "event_resid_db": ("<=", -19.9),
+ "floor_resid_db": ("<=", -19.9),
+ "voice_level_db": (">=", -0.1),
+}
+HARMLESS = {
+ "fidelity": (">=", 0.95),
+ "kept_coh_p10": (">=", -1.0),
+ "lost_pct": ("<=", 0.5),
+ "nv_lost_pct": ("<=", 0.5),
+ "spk_sim": (">=", 0.99),
+ **BLOCK_CLEAN,
+}
+GONE = {
+ "fidelity": ("<=", 0.5),
+ "kept_coh_p10": ("<=", -40.0),
+ "lost_pct": (">=", 99.0),
+ "nv_lost_pct": (">=", 99.0),
+}
+EXPECTED = {
+ "reference": dict(HARMLESS, si_sdr=(">=", 60.0)),
+ # on clean the input is the reference; on the block it leaves the noise
+ # as it was, by definition
+ "input": {
+ "fidelity": (">=", 0.95),
+ "event_resid_db": (">=", -0.05),
+ "floor_resid_db": (">=", -0.05),
+ "voice_level_db": ("<=", 0.05),
+ },
+ "silence": GONE,
+ # the bed returned is no suppression
+ "bedonly": dict(GONE, babble_supp_db=(">=", 0.0)),
+ # a gain on both renders alike: the block's rows read the voice's level
+ # with the noise against without, so none of it shows
+ "gainup6db": {
+ "level_err": (">=", 5.5),
+ "fidelity": ("<=", 0.85),
+ "lost_pct": ("<=", 0.5),
+ **BLOCK_CLEAN,
+ },
+ "gaindown6db": {
+ "level_err": (">=", 5.5),
+ "fidelity": ("<=", 0.85),
+ "lost_pct": ("<=", 0.5),
+ **BLOCK_CLEAN,
+ },
+ # a sign flip is inaudible: nothing may read it as damage
+ "polarity": HARMLESS,
+ "delay20ms": HARMLESS, # inside the +-100 ms the scorer undoes
+ "delete20ms": {
+ "nisqa_mos": ("<=", 4.35)
+ },
+ "delete40ms": {
+ "nisqa_mos": ("<=", 4.35)
+ },
+ "delete80ms": {
+ "nisqa_mos": ("<=", 4.35)
+ },
+ "delete160ms": {
+ "nisqa_mos": ("<=", 4.35),
+ "fidelity": ("<=", 0.95)
+ },
+ # retention is read per 100 ms block: only a deletion that empties whole
+ # blocks must show
+ "delete320ms": {
+ "lost_pct": (">=", 2.0),
+ "fidelity": ("<=", 0.9)
+ },
+ "hfinvented": {
+ "si_sdr": ("<=", 25.0)
+ },
+ "hfcut": {
+ "hf_err": (">=", 3.0),
+ "fidelity": ("<=", 0.85)
+ },
+ # another waveform, the same sound: must not read as damage, and sets the
+ # magnitude ceiling
+ "resynth": dict(HARMLESS, mag_snr=(">=", 30.0)),
+ "floorless": HARMLESS,
+ # the block's rows: a known share of the noise left reads as that share,
+ # the transients and the floor are told apart, and a voice turned down to
+ # be rid of the noise reads as the voice lost
+ "halfnoise": {
+ "event_resid_db": ("<=", -5.9),
+ "floor_resid_db": ("<=", -5.9),
+ "voice_level_db": (">=", -0.1),
+ },
+ "transientsleft": {
+ "event_resid_db": (">=", -3.0),
+ "floor_resid_db": ("<=", -15.0),
+ },
+ "floorleft": {
+ "event_resid_db": ("<=", -10.0),
+ "floor_resid_db": (">=", -0.5),
+ },
+ # the voice turned down to the declared floor reads as the voice lost,
+ # and under the gate nothing counts as removed: the noise rows read as
+ # left
+ "voiceducked": {
+ "voice_level_db": ("<=", -2.9),
+ "floor_resid_db": (">=", -0.1),
+ "event_resid_db": (">=", -0.1),
+ },
+}
+# Damage the published metrics do not see, stated rather than hidden.
+BLIND = {
+ "delete20ms": (
+ "retention is read per 100 ms block and as a 10th percentile: a dropped"
+ " 20-80 ms (a consonant, a syllable onset) moves neither; only NISQA,"
+ " waveform SI-SDR and the magnitude ratio react, the last from 40 ms on"
+ " (a 20 ms hole stays above its ceiling). A recogniser's transcript"
+ " does not react either: Whisper large-v3 restores the word from"
+ " context for holes up to 160 ms (scorecontent.py's ctl_ rows), so the"
+ " content check sees a dropout only from about 320 ms"),
+ "delete40ms":
+ "as delete20ms",
+ "delete80ms":
+ ("as delete20ms; `lost_pct` starts to see it when the span empties a"
+ " block"),
+ "hfinvented":
+ ("a top octave replaced by noise of the same energy keeps every band"
+ " level, the speaker embedding and NISQA; waveform SI-SDR reacts but"
+ " cannot tell this from a harmless re-synthesis (`resynth`), and the"
+ " magnitude ratio moves little, because the top octave holds little of"
+ " the energy. Whether listeners hear it is an open listening question"
+ ),
+}
+COLUMNS = (
+ "si_sdr",
+ "kept_coh_p10",
+ "lost_pct",
+ "level_err",
+ "hf_err",
+ "spk_sim",
+ "nisqa_mos",
+ "mag_snr",
+ "nv_lost_pct",
+ "fidelity",
+ "babble_supp_db",
+) + BLOCK_COLUMNS
+
+
+def stratified(rows: list[dict], conds: tuple[str, ...],
+ per_condition: int) -> list[dict]:
+ """Returns ``per_condition`` paired rows of each condition.
+
+ They are dealt round-robin over languages in id order, so every language of
+ a condition is heard before any is heard twice.
+ """
+ out = []
+ for cond in conds:
+ by_lang = {}
+ for r in sorted(
+ (r for r in rows if r["condition"] == cond and r.get("clean_path")),
+ key=lambda r: r["id"],
+ ):
+ by_lang.setdefault(r.get("language") or "", []).append(r)
+ picked, depth = [], 0
+ while len(picked) < per_condition and any(
+ len(v) > depth for v in by_lang.values()):
+ picked += [
+ v[depth] for _, v in sorted(by_lang.items()) if len(v) > depth
+ ]
+ depth += 1
+ out += picked[:per_condition]
+ return out
+
+
+def pair_dir(root: str, name: str) -> str:
+ """Where a control's renders of the block's reference tracks go."""
+ return os.path.join(root, "pair", name)
+
+
+def render(name: str, rows: list[dict], root: str) -> None:
+ """Writes one control's outputs for the slice as 48 kHz float WAV files.
+
+ On the same-room block the control is rendered on the reference track as
+ well, under ``pair_dir``, as every system is for the block's rows.
+ """
+ outd, paird = os.path.join(root, name), pair_dir(root, name)
+ os.makedirs(outd, exist_ok=True)
+ build = CONTROLS[name][1]
+ for r in rows:
+ ref, mix = common.load48(r["clean_path"]), common.load48(r["mix_path"])
+ n = min(len(ref), len(mix))
+ out = torch.zeros(len(mix))
+ out[:n] = build(ref[:n], mix[:n], r["id"])[:n]
+ sf.write(os.path.join(outd, r["id"]), out.numpy(), SR, subtype="FLOAT")
+ if r["condition"] in BLOCK_CONDS:
+ os.makedirs(paird, exist_ok=True)
+ out = torch.zeros(len(ref))
+ out[:n] = build(ref[:n], ref[:n], r["id"])[:n]
+ sf.write(os.path.join(paird, r["id"]),
+ out.numpy(),
+ SR,
+ subtype="FLOAT")
+
+
+def summarise(metrics: dict, calibration: dict, axes: dict) -> dict:
+ """Returns one row of the table from a control's scores.
+
+ The kept sidecar's scores are merged in: clean-item metrics, the fidelity
+ axis, and babble suppression at +4 dB.
+ """
+ clean = dict(metrics.get("clean") or {})
+ row = {
+ k: clean.get(k, float("nan"))
+ for k in ("si_sdr", "spk_sim", "nisqa_mos", "mag_snr")
+ }
+ # the board removes a system's global level offset before reading retention;
+ # so does this
+ row["kept_coh_p10"] = clean.get("kept_coh_p10", float("nan")) - metrics.get(
+ "_level_cal_db", 0.0)
+ row["lost_pct"] = clean.get("kept_coh_lost_pct", float("nan"))
+ row["level_err"] = clean.get("level_err_db", float("nan"))
+ row["hf_err"] = clean.get("hf_err_db", float("nan"))
+ nonverbal = metrics.get("nonverbal_clean") or {}
+ row["nv_lost_pct"] = nonverbal.get("nv_lost_pct", float("nan"))
+ values = {
+ cond: dict(cell)
+ for cond, cell in metrics.items()
+ if isinstance(cell, dict)
+ }
+ values["clean"] = dict(
+ clean,
+ kept_coh_p10=row["kept_coh_p10"],
+ _level_err=row["level_err"],
+ _hf_err=row["hf_err"],
+ )
+ subs = [
+ anchors.normalize(
+ float(values.get(cond, {}).get(metric, float("nan"))),
+ calibration["points"][anchors.row_key(cond, metric)],
+ ) for cond, metric, _ in axes["fidelity"]
+ ]
+ # a part that is missing (NaN) leaves the axis missing
+ row["fidelity"] = float(np.mean(subs))
+ babble = metrics.get("babble@+4") or {}
+ row["babble_supp_db"] = babble.get("babble_supp_db", float("nan"))
+ block = metrics.get("_coroom") or {}
+ for key in BLOCK_COLUMNS:
+ row[key] = block.get(key, float("nan"))
+ return row
+
+
+def kept(name: str, rows: list[dict], vad, level_cal_db: float) -> dict:
+ """Returns a control's kept-sidecar cells, to merge into its scores."""
+ # pylint: disable-next=import-outside-toplevel
+ import scorekept
+
+ selected = [r for r in rows if scorekept.wanted(r)]
+ cells = scorekept.aggregate(scorekept.assemble(name, selected, vad=vad),
+ selected, level_cal_db)
+ return {
+ cond: {
+ k: v for k, v in cell.items() if k.startswith(("nv_", "mag_"))
+ } for cond, cell in cells.items()
+ }
+
+
+def events(name: str, rows: list[dict], level_cal_db: float, lag: int,
+ paird: str) -> dict:
+ """Returns a control's events-sidecar cells, to merge into its scores.
+
+ Read over the slice's same-room items from the control's two renders, the
+ system's delay and gain undone as the board does.
+ """
+ # pylint: disable-next=import-outside-toplevel
+ import scoreevents
+
+ selected = [r for r in rows if r["condition"] in scoreevents.SAME_ROOM]
+ if not selected:
+ return {}
+ records = scoreevents.assemble(name,
+ selected,
+ None,
+ level_cal_db,
+ pair_out=paird,
+ lag=lag)
+ cells = scoreevents.aggregate(records, selected, level_cal_db)
+ return {
+ cond: {
+ k: v
+ for k, v in cell.items()
+ if k.startswith(("event_", "floor_resid", "voice_level"))
+ } for cond, cell in cells.items() if isinstance(cell, dict)
+ }
+
+
+def check(table: dict, block: bool = True) -> dict:
+ """Returns {control: [failed expectation, ...]} over ``table``.
+
+ For every control with a declared row; the block's columns are held only
+ when the slice holds the block (``block``).
+ """
+ failures = {}
+ for name, row in table.items():
+ bad = []
+ for column, (op, bound) in EXPECTED.get(name, {}).items():
+ if column in BLOCK_COLUMNS and not block:
+ continue
+ value = row.get(column, float("nan"))
+ ok = value == value and (value >= bound
+ if op == ">=" else value <= bound)
+ if not ok:
+ bad.append(f"{column} {value:.2f} should be {op} {bound:g}")
+ if bad:
+ failures[name] = bad
+ return failures
+
+
+def markdown(
+ table: dict,
+ failures: dict,
+ set_id: str,
+ n_items: int,
+ conds: tuple[str, ...],
+) -> str:
+ """Returns the controls table, each row with its expectation and verdict."""
+
+ def fmt(v, nd):
+ return "-" if v != v else f"{v:.{nd}f}"
+
+ digits = {
+ "spk_sim": 3,
+ "nisqa_mos": 2,
+ "fidelity": 2,
+ "hf_err": 2,
+ "level_err": 2,
+ }
+ lines = [
+ "# Metric controls",
+ "",
+ ("Known damage in, what the published metrics say about it out."
+ " Every row is a synthetic system built from the paired audio of a"
+ f" fixed, language-stratified slice of the set ({n_items} items"
+ f" over {len(conds)} conditions; set `{set_id[:16]}`) and scored by"
+ " the same code as a real system. Columns are read on the `clean`"
+ " items of the slice, where the reference is the input and a"
+ " defect is the only thing that happened; `lost_pct` is the share"
+ " of speech blocks kept below -10 dB, `mag_snr` the"
+ " signal-to-error ratio of the magnitude spectrum, `nv_lost_pct`"
+ " the share of vocal sounds outside speech lost on the clean"
+ " recordings of laughs, breaths and sighs, `fidelity` the"
+ " published axis, and babble suppression is read at +4 dB. A delay"
+ " of up to 100 ms, a flipped polarity and a gain of up to 12 dB"
+ " are conventions the scorer undoes, not damage. The last three"
+ " columns are the same-room block's rows, read on its items from"
+ " two renders of the control, of the mixture and of the reference,"
+ " as the board reads every system (`scoreevents.py`): the noise"
+ " left over the labelled events and pauses, in dB, and the voice's"
+ " level with the noise against without; a slice without the block"
+ " leaves them blank. Generated by"
+ " `scripts/controls.py`; the expectations live in its `EXPECTED`"
+ " table."),
+ "",
+ "| control | the system returns | " +
+ " | ".join(f"`{c}`" for c in COLUMNS) + " | held |",
+ "|---|---|" + "---:|" * len(COLUMNS) + "---|",
+ ]
+ for name, row in table.items():
+ held = ("no: " + "; ".join(failures[name]) if name in failures else
+ ("yes" if name in EXPECTED else ""))
+ lines.append(f"| `{name}` | {CONTROLS[name][0]} | " + " | ".join(
+ fmt(row[c], digits.get(c, 1)) for c in COLUMNS) + f" | {held} |")
+ lines += ["", "## Blind spots", ""
+ ] + [f"- `{name}`: {why}." for name, why in BLIND.items()]
+ lines += [
+ "",
+ "Expectations: " +
+ "; ".join(f"`{name}` " + ", ".join(f"{c} {op} {b:g}"
+ for c, (op, b) in exp.items())
+ for name, exp in EXPECTED.items()) + ".",
+ ]
+ return "\n".join(lines) + "\n"
+
+
+def identity(rows: list[dict]) -> dict:
+ """Returns what a control's saved scores were made by and of.
+
+ The scorers' digests, this module (the defects it builds), the anchor policy
+ and the exact slice of items. A cache that differs in any of them is stale,
+ however alike its numbers look.
+ """
+ # pylint: disable-next=import-outside-toplevel
+ import observations
+ # pylint: disable-next=import-outside-toplevel
+ import scorebench
+ # pylint: disable-next=import-outside-toplevel
+ import scoreevents
+ # pylint: disable-next=import-outside-toplevel
+ import scorekept
+
+ return {
+ "set_id":
+ common.set_id(),
+ "scorer_sha256":
+ scorebench.SCORER_SHA256,
+ "kept_sha256":
+ scorekept.SCORER_SHA256,
+ "events_sha256":
+ scoreevents.SCORER_SHA256,
+ "controls_sha256":
+ observations.implementation(__file__),
+ "items":
+ anchors.digest(sorted(r["id"] for r in rows)),
+ # the block's labels: a corrected event span or room allowance makes
+ # every saved control stale
+ "labels":
+ anchors.digest(
+ sorted(
+ [r["id"], scoreevents.labels_digest(r) or ""] for r in rows)
+ ),
+ **anchors.stamp(),
+ }
+
+
+def cached(metrics: dict, rows: list[dict]) -> bool:
+ """Returns whether a control's saved scores are current.
+
+ They must stand for this set, slice, scorer and anchor policy.
+ """
+ return metrics.get("_controls_identity") == identity(rows)
+
+
+def main() -> None:
+ """Renders, scores and tabulates the controls.
+
+ Renders are deleted once scored.
+ """
+ ap = argparse.ArgumentParser(description=__doc__,
+ formatter_class=argparse.RawTextHelpFormatter)
+ ap.add_argument("--conds", default=",".join(DEFAULT_CONDS))
+ ap.add_argument("--per-condition", type=int, default=24)
+ ap.add_argument("--controls", default=",".join(CONTROLS))
+ ap.add_argument("--out",
+ default=os.path.join(common.REPO_DIR, "staging",
+ "controls"))
+ ap.add_argument("--keep-renders", action="store_true")
+ ap.add_argument("--markdown-out", default="")
+ a = ap.parse_args()
+ # pylint: disable-next=import-outside-toplevel
+ import ranking
+ # pylint: disable-next=import-outside-toplevel
+ import scorebench
+
+ names = [n for n in a.controls.split(",") if n]
+ unknown = sorted(set(names) - set(CONTROLS))
+ if unknown:
+ raise SystemExit(f"unknown controls: {unknown}")
+ conds = tuple(c for c in a.conds.split(",") if c)
+ rows = stratified(common.manifest(), conds, a.per_condition)
+ if not any(r["condition"] == "clean" for r in rows):
+ raise SystemExit(
+ "the slice needs the clean condition: the table is read on it")
+ calibration = anchors.load(os.path.join(common.RESULTS, anchors.RESOLVED),
+ anchors.definitions())
+ os.makedirs(a.out, exist_ok=True)
+ renders = os.path.join(a.out, "renders")
+ common.OUT_ROOT = renders # score_system reads a system's outputs from here
+ set_tag = (common.set_id() or "noset")[:16]
+ spk_cache = os.path.join(common.EVAL, ".cache", "spkemb", set_tag)
+ spk = common.SpeakerEmbedder(cache_dir=spk_cache)
+ vad = common.Vad()
+ table = {}
+ for name in names:
+ path = os.path.join(a.out, f"{name}.metrics.json")
+ metrics = None
+ if os.path.exists(path):
+ with open(path, encoding="utf-8") as fh:
+ metrics = json.load(fh)
+ if metrics is None or not cached(metrics, rows):
+ render(name, rows, renders)
+ metrics = scorebench.score_system(name, rows, spk, vad, None)
+ level_cal = metrics.get("_level_cal_db", 0.0)
+ for cond, cell in kept(name, rows, vad, level_cal).items():
+ metrics.setdefault(cond, {}).update(cell)
+ lag = int(round((metrics.get("clean") or {}).get("lag_median") or
+ 0))
+ for cond, cell in events(name, rows, level_cal, lag,
+ pair_dir(renders, name)).items():
+ metrics.setdefault(cond, {}).update(cell)
+ metrics["_controls_identity"] = identity(rows)
+ anchors.atomic_json(path, metrics)
+ if not a.keep_renders:
+ shutil.rmtree(os.path.join(renders, name), ignore_errors=True)
+ shutil.rmtree(pair_dir(renders, name), ignore_errors=True)
+ table[name] = summarise(metrics, calibration, ranking.AXES_FULL)
+ print(
+ f"{name:12s} " +
+ " ".join(f"{c} {table[name][c]:.2f}" for c in COLUMNS),
+ flush=True,
+ )
+ failures = check(table, any(r["condition"] in BLOCK_CONDS for r in rows))
+ md = markdown(table, failures, common.set_id() or "", len(rows), conds)
+ anchors.atomic_json(
+ os.path.join(a.out, "controls.json"),
+ {
+ "set_id": common.set_id(),
+ "n_items": len(rows),
+ "conditions": conds,
+ "table": table,
+ "failures": failures,
+ },
+ )
+ if a.markdown_out:
+ with open(a.markdown_out, "w", encoding="utf-8") as fh:
+ fh.write(md)
+ print(md)
+ print(
+ f"{len(failures)} of {len(table)} controls miss their expectation",
+ file=sys.stderr,
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/bench/scripts/demucsvocals.py b/bench/scripts/demucsvocals.py
new file mode 100644
index 0000000..81635ae
--- /dev/null
+++ b/bench/scripts/demucsvocals.py
@@ -0,0 +1,94 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The htdemucs vocals stem, the benchmark's music-separation reference row."""
+
+import hashlib
+import os
+
+import torch
+
+from inworld.voice_isolation import audio as audio_lib
+
+STEM_CACHE_ENV = "VOICE_ISOLATION_STEM_CACHE"
+
+
+class DemucsVocals(torch.nn.Module):
+ """Extracts the htdemucs vocals stem at 48 kHz, deterministically.
+
+ Determinism matters for a reference row: a randomly time-shifted stem
+ (the demucs default, shifts=1) would make the renders differ between
+ runs. An optional content-addressed stem cache directory can be set via
+ the VOICE_ISOLATION_STEM_CACHE env var; an entry is keyed by the audio's
+ samples, the demucs version and the device type, and holds plain tensors
+ only.
+ """
+
+ def __init__(self, device: str | torch.device = "cpu"):
+ super().__init__()
+ try:
+ # pylint: disable-next=import-outside-toplevel
+ import demucs.apply
+ # pylint: disable-next=import-outside-toplevel
+ import demucs.pretrained
+ except ImportError as e:
+ raise ImportError(
+ "The Demucs reference row requires the [demucs] extra: "
+ 'pip install "inworld-voice-isolation[demucs]"') from e
+ self._apply_model = demucs.apply.apply_model
+ self.device = torch.device(device)
+ self.model = demucs.pretrained.get_model("htdemucs")
+ self.model = self.model.to(self.device).eval()
+ self.model_sr = int(self.model.samplerate)
+ self.vidx = self.model.sources.index("vocals")
+ self._cache_salt = (f"htdemucs|demucs {demucs.__version__}|"
+ f"{self.device.type}|{self.model_sr}|"
+ "split overlap 0.25 shifts 0".encode())
+
+ @torch.inference_mode()
+ def vocals(self, audio: torch.Tensor) -> torch.Tensor:
+ """audio [T] or [1, T] at 48 kHz -> vocals stem [T] at 48 kHz."""
+ cache_dir = os.environ.get(STEM_CACHE_ENV, "")
+ cache_path = None
+ if cache_dir:
+ os.makedirs(cache_dir, exist_ok=True)
+ data = audio.detach().cpu().float().numpy().tobytes()
+ key = hashlib.sha256(self._cache_salt + data).hexdigest()
+ cache_path = os.path.join(cache_dir, key + ".pt")
+ if os.path.exists(cache_path):
+ stem = torch.load(cache_path,
+ map_location=audio.device,
+ weights_only=True)
+ return stem.squeeze(0)
+ if audio.ndim == 1:
+ audio = audio.unsqueeze(0)
+ mix = audio_lib.resample(audio, audio_lib.SR, self.model_sr)
+ if mix.shape[0] == 1:
+ mix = mix.repeat(2, 1)
+ stems = self._apply_model(
+ self.model,
+ mix.unsqueeze(0).to(self.device),
+ device=self.device,
+ split=True,
+ overlap=0.25,
+ shifts=0,
+ progress=False,
+ )
+ stem = stems[0, self.vidx].mean(0, keepdim=True)
+ stem = audio_lib.resample(stem, self.model_sr, audio_lib.SR)
+ stem = stem.to(audio.device)
+ if cache_path:
+ tmp = cache_path + f".tmp{os.getpid()}"
+ torch.save(stem.cpu(), tmp)
+ os.replace(tmp, cache_path)
+ return stem.squeeze(0)
diff --git a/bench/scripts/leaderboard.py b/bench/scripts/leaderboard.py
new file mode 100644
index 0000000..14cbf71
--- /dev/null
+++ b/bench/scripts/leaderboard.py
@@ -0,0 +1,601 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Ranked leaderboard for Inworld VIBE, the voice-isolation benchmark.
+
+Ranking is the opinionated part, so the rules are stated here and printed with
+the table rather than buried in a weighted sum nobody can audit.
+
+TIERS. The goal is a voice isolator that is excellent across the whole 0-48 kHz
+band. A 16 kHz-native model emits nothing above 8 kHz, so it cannot meet that
+goal however well it suppresses; those are ranked in a separate tier. Plain
+DSP, the music-separation reference and the unprocessed input are reference
+rows.
+
+AXES. Eleven (bench/axes.json states the axes, their rows, the parts, the
+boards and the rule that assigns each system a board), because the target is a
+model with no weak side and an axis added on one side must not take weight
+from another:
+ removes
+ suppression babble_supp_db @+4 / @+0 / @-5, si_sdr on ambience, stationary
+ noise and traffic @-5
+ music si_sdr on music@-6
+ cleanup what is left in the pauses of the real recordings and the
+ same-room floors
+ events the same-room transient events left
+ voices si_sdr on the competing talker @+5
+ keeps
+ preservation real-file deleted-rate, voice-kept P10 on babble@+4, the vocal
+ sounds outside speech lost under a bed (scorekept.py) and the
+ voice's level while same-room noise goes
+ fidelity harm a listener could notice on clean speech: the quiet tenth
+ of the voice, level, the 8-24 kHz band (invented high
+ frequency costs as much as lost), speaker similarity, NISQA
+ and the magnitude spectrum, each against the untouched
+ recording, and the vocal sounds outside speech lost on clean
+ recordings.
+ Clean si_sdr is printed, not scored: it measures identity of
+ the waveform, not harm.
+ sounds
+ timbre spk_sim over twelve noise families at a moderate level; gaps
+ under its tie band are ties
+ quality NISQA v2 MOS on babble@+4 and on the real recordings
+ restores
+ room recordings in real rooms against the dry voice: spk_sim and
+ NISQA. A system that leaves the room as recorded scores zero.
+ beside both scores
+ band the energy above a band-limited input's band and the speaker
+ kept while it does
+
+BOARDS. Two scores, each the mean of its parts: denoising (removes, keeps,
+sounds) and restoration (restores). A system that restores above the input's
+band is ranked on restoration, every other system on denoising; every system is
+scored on both.
+
+NORMALISATION. Each sub-metric closes the gap between versioned, fixed anchors
+derived from INPUT, REF, or declared constants. The calibration and primary
+deletion cohort belong to the set, never to the competitor roster. Sub-metrics
+are averaged within an axis, axes within a part, parts into the score.
+
+NO HARD GATE. Deletion rides in the preservation axis, is printed as its own
+column, and a sensitivity line shows the order under a strict deletion gate.
+
+Systems not listed in roster.py can be added with --tiers extra.json
+({"name": ["full"|"nb"|"ref", "label"], ...}).
+"""
+
+import argparse
+import dataclasses
+import json
+import math
+import os
+
+import anchors
+import common
+import contracts
+import ranking
+import roster
+import scorefiles
+import scorestream
+import streamview
+import tables
+
+
+class Board:
+ """One ranked board: the scores, how they rank, and what is said beside."""
+ scores: dict
+ tiers: dict
+ anchored: dict
+ axis_scores: dict
+ comp: dict
+ order: dict
+ stream: dict
+ partial: dict
+ grouped: dict
+ missing: dict
+ precision: dict
+
+
+WIDTH = 38 # the system column of the printed board
+
+
+def parse_args() -> argparse.Namespace:
+ """Returns the command line."""
+ here = os.path.dirname(os.path.abspath(__file__))
+ ap = argparse.ArgumentParser()
+ ap.add_argument(
+ "--results",
+ default=os.environ.get("BENCH_RESULTS",
+ os.path.join(os.path.dirname(here), "results")),
+ )
+ ap.add_argument("--json-out", default="")
+ ap.add_argument("--markdown-out", default="")
+ ap.add_argument(
+ "--outside-out",
+ default="",
+ help=(
+ "markdown tables of the axes scored beside the composite, in their"
+ " order"),
+ )
+ ap.add_argument(
+ "--axis-tables",
+ default="",
+ help=("comma-separated axes to add to --outside-out in their own order "
+ "(e.g. room, the Real rooms section)"),
+ )
+ ap.add_argument(
+ "--streaming-out",
+ default="",
+ help="markdown table of the streaming probe behind the yes/no column",
+ )
+ ap.add_argument("--tiers",
+ default="",
+ help="JSON file with extra {name: [tier, label]}")
+ ap.add_argument(
+ "--anchors",
+ default=str(anchors.DEFAULT),
+ help="versioned anchor definitions",
+ )
+ ap.add_argument(
+ "--calibration",
+ default="",
+ help="frozen set calibration (default: results/anchors.resolved.json)",
+ )
+ ap.add_argument("--strict-delete", type=float, default=3.0)
+ ap.add_argument("--title", default="INWORLD VIBE BOARDS")
+ ap.add_argument(
+ "--view",
+ default="all",
+ choices=sorted(ranking.AXES_VIEWS) + list(common.PANELS),
+ help=("all: every condition; core: the multilingual half only "
+ "(rank results scored with BENCH_SUBSET=core)"),
+ )
+ return ap.parse_args()
+
+
+def board_scores(a: argparse.Namespace, tiers: dict) -> tuple[dict, dict]:
+ """Returns the scores a board may rank and its frozen calibration.
+
+ A result nobody registered and a filtered scoring pass are left out, each
+ with a line saying so.
+
+ Raises:
+ SystemExit: The scores mix scorer implementations, renders, subsets or
+ builds of the set, or are sealed.
+ """
+ scores = scorefiles.load(a.results)
+ unregistered = sorted(n for n in scores if n not in tiers)
+ # a result file nobody registered: a stray sweep, never a row of a board
+ if unregistered:
+ print("IGNORED (no tier registered; pass --tiers to rank them): " +
+ ", ".join(unregistered))
+ scores = {n: d for n, d in scores.items() if n not in unregistered}
+ filtered = scorefiles.partial_passes(scores)
+ if filtered:
+ print("NOT RANKED - a filtered scoring pass, never a board row: " +
+ ", ".join(f"{n} ({v})" for n, v in sorted(filtered.items())))
+ scores = {n: d for n, d in scores.items() if n not in filtered}
+ problem = scorefiles.scorer_problem(scores) or scorefiles.render_problem(
+ scores, a.results)
+ if problem:
+ raise SystemExit(problem)
+ set_ids = {n: scores[n].get("_set_id") for n in scores}
+ subsets = {n: scores[n].get("_subset", "all") for n in scores}
+ if len(set(subsets.values())) > 1:
+ raise SystemExit("systems were scored on different subsets of the set: "
+ f"{subsets}; one results directory holds one subset.")
+ if a.view == "core" and set(subsets.values()) != {"core"}:
+ raise SystemExit(
+ "--view core ranks results scored with BENCH_SUBSET=core; these"
+ f" were scored on {set(subsets.values())}")
+ if len({v for v in set_ids.values() if v}) > 1:
+ raise SystemExit(
+ "systems were scored on different eval sets (set_id):"
+ f" { {n: (v or 'none')[:12] for n, v in set_ids.items()} };"
+ " re-score before ranking.")
+ anchored = anchors.load(
+ a.calibration or os.path.join(a.results, anchors.RESOLVED),
+ anchors.definitions(a.anchors),
+ )
+ if anchored.get("sealed") or any(
+ score.get("_sealed") for score in scores.values()):
+ raise SystemExit("sealed results cannot be exported as a leaderboard")
+ return scores, anchored
+
+
+def condition_profiles(scores: dict, order: dict) -> dict:
+ """Returns the ranked systems' conditions grouped by task contract.
+
+ Raises:
+ SystemExit: A condition family has no task contract.
+ """
+ conditions = {
+ c for rows in order.values() for n in rows
+ for c, v in scores[n].items()
+ if isinstance(v, dict) and not c.startswith("_")
+ }
+ try:
+ return contracts.by_profile(conditions)
+ except KeyError as family:
+ raise SystemExit(
+ f"condition family {family} has no task contract: add it to a"
+ " profile in contracts.py") from None
+
+
+def load_precision(results: str, scores: dict) -> dict:
+ """Returns the arithmetic each system's wrapper declares it ran in.
+
+ From the stamped metadata beside the scores, else from the wrapper's own
+ description; a dash where neither says.
+ """
+ out = {}
+ for name in scores:
+ value = None
+ for path in (os.path.join(results, f"{name}.meta.json"),
+ os.path.join(common.BENCH_DIR, "wrappers", "meta",
+ f"{name}.json")):
+ if os.path.isfile(path):
+ with open(path, encoding="utf-8") as fh:
+ value = json.load(fh).get("precision")
+ if value:
+ break
+ out[name] = str(value) if value else "–"
+ return out
+
+
+# what each key of a board's order names when printed
+VIEW_NAMES = {
+ "full": "denoising, full-band tier",
+ "nb": "denoising, 16 kHz tier",
+ "restoration": "restoration, full-band tier",
+}
+
+
+def header(axis_names: list, part_names: list) -> str:
+ """Returns the column header of the printed board."""
+ scores = ([f"{b:>{max(len(b), 5)}s}" for b in ranking.BOARDS]
+ if ranking.BOARDS else [f"{'SCORE':>5s}"])
+ return (f"{'#':>2} {'system':{WIDTH}s} {'strm':>4s} {'prec':>5s}"
+ f" {' '.join(scores)} | " +
+ "".join(f"{k:>{max(len(k), 4)}s} " for k in part_names) +
+ ("| " if part_names else "") +
+ " ".join(f"{k[:4]:>4s}" for k in axis_names) +
+ f" | {'supp':>5s} {'del%':>5s} {'nv%':>5s} {'clean':>5s}"
+ f" {'HFerr':>5s} {'NISQA':>5s}")
+
+
+def present(value: float) -> bool:
+ """Returns whether a score is there: NaN marks one that is not."""
+ return not math.isnan(value)
+
+
+def cell(value: float) -> str:
+ """Returns an axis score as a four-wide cell, a dash where there is none."""
+ return f"{value:4.2f}" if present(value) else " -"
+
+
+def diagnostics(d: dict, sfx: str = "", high_band: bool = True) -> str:
+ """Returns the diagnostic columns of one row of the printed board."""
+ supp = scorefiles.get(d, "babble@+4", "babble_resid_db" + sfx)
+ deleted = scorefiles.get(d, "_deletion", "pct")
+ lost = scorefiles.get(d, "nonverbal@+0", "nv_lost_pct")
+ clean = scorefiles.get(d, "clean", "si_sdr" + sfx)
+ hf = scorefiles.get(d, "clean", "_hf_err")
+ nisqa = scorefiles.get(d, "babble@+4", "nisqa_mos")
+ return (f" | {supp:5.1f} {deleted:5.1f} {lost:5.1f} {clean:5.1f}" +
+ (f" {hf:5.1f}" if high_band else " n/a") + f" {nisqa:5.2f}")
+
+
+def print_tiers(board: Board, title: str) -> None:
+ """Prints the board's rules, its ranked tiers and its reference rows."""
+ scores, tiers, axis_scores = board.scores, board.tiers, board.axis_scores
+ entrants = [n for n in scores if tiers[n][0] in ranking.AXES_BY_TIER]
+ axis_names = ranking.axis_order()
+ part_names = list(ranking.PARTS or {})
+ hdr = header(axis_names, part_names)
+ print("=" * len(hdr))
+ print(title)
+ print(f"SCORE = {ranking.composite_rule()} (0-1, higher better);"
+ f" {len(entrants)} entrants")
+ print(f"strm (streaming probe): {streamview.rule_sentence()}; - not probed;"
+ " * after a name: the probe says yes")
+ print(f"Fixed anchors {board.anchored['anchors_version']}; calibration"
+ f" {board.anchored['calibration_sha256'][:12]}; complete frozen"
+ " deletion cohort")
+ print("=" * len(hdr))
+ views = [("full", "FULL-BAND TIER - eligible for the 0-48 kHz goal" +
+ (f"; {ranking.ranking_board()}: the systems that add nothing"
+ " above the input's band" if ranking.BOARDS else ""))]
+ views += [(b, f"{b.upper()} - the systems that restore above the input's"
+ f" band (more than {ranking.ASSIGN['above_db']:g} dB on the"
+ " band-limited rows)" if ranking.ASSIGN else b.upper())
+ for b in (ranking.BOARDS or {})
+ if b != ranking.ranking_board()]
+ views.append(("nb", "16 kHz TIER - band-limited by construction (scored"
+ " inside 0-8 kHz)"))
+ for tier, tier_title in views:
+ sfx = "_nb" if tier == "nb" else ""
+ print(f"\n{tier_title}\n{hdr}")
+ for i, n in enumerate(board.order[tier], 1):
+ scored = anchors.part_scores(axis_scores[n], ranking.PARTS)
+ row = axis_scores[n]
+ axes = " ".join(cell(row.get(k, math.nan)) for k in axis_names)
+ label = tiers[n][1] + ("*" if streamview.streaming_cell(
+ board.stream, n) == "yes" else "")
+ scored_boards = ranking.board_scores(row)
+ shown = (" ".join(f"{scored_boards[b]:>{max(len(b), 5)}.3f}"
+ for b in ranking.BOARDS)
+ if ranking.BOARDS else f"{board.comp[n]:5.3f}")
+ print(f"{i:2d}. {label:{WIDTH}s}"
+ f" {streamview.streaming_cell(board.stream, n):>4s}"
+ f" {board.precision.get(n, '–'):>5s}"
+ f" {shown} | " + "".join(f"{scored[k]:>{max(len(k), 4)}.2f} "
+ for k in part_names) +
+ ("| " if part_names else "") + axes +
+ diagnostics(scores[n], sfx, tier != "nb"))
+ print("\nREFERENCE ROWS (not ranked)")
+ for n in [x for x in scores if tiers[x][0] == "ref"]:
+ print(f" {tiers[n][1]:{WIDTH}s} {'':4s} {'':5s} | " + " " *
+ (5 * len(part_names)) + ("| " if part_names else "") + " " *
+ (5 * len(axis_names) - 1) + diagnostics(scores[n]))
+
+
+def print_ties(board: Board) -> None:
+ """Prints the ties of each tier and the axes scored beside the composite."""
+ tiers, axis_scores = board.tiers, board.axis_scores
+ for tier, rows in board.order.items():
+ if not rows:
+ continue
+ for cluster in ranking.tie_clusters(rows, board.comp):
+ print(f"\nTIED ({VIEW_NAMES.get(tier, tier)}, composite gaps under"
+ f" {ranking.TIE_BAND:.2f}): " + ", ".join(
+ f"#{rows.index(n) + 1} {tiers[n][1]}" for n in cluster))
+ print(
+ " Not close for the same reasons - compare the axis columns,"
+ " not the rank.")
+ for axis, labels in ranking.axis_ties(axis_scores, rows, tiers).items():
+ print(f"\nTIED ON {axis.upper()} ({VIEW_NAMES.get(tier, tier)},"
+ " within"
+ f" {ranking.TIE_BANDS[axis]:.2f} of the best): " +
+ ", ".join(labels))
+ for axis in ranking.OUTSIDE:
+ scored = sorted(
+ (n for n in rows
+ if present(axis_scores[n].get(axis, math.nan))),
+ key=lambda n, axis=axis: -axis_scores[n][axis],
+ )
+ print("\nBESIDE " +
+ ("BOTH SCORES" if ranking.BOARDS else "THE COMPOSITE") +
+ f" ({VIEW_NAMES.get(tier, tier)}) - {axis}, scored and shown,"
+ " not read by the score: " +
+ " > ".join(f"{tiers[n][1]} {axis_scores[n][axis]:.2f}"
+ for n in scored))
+
+
+def print_notes(board: Board, strict_delete: float) -> None:
+ """Prints the streaming probe, the strict-deletion order and the contracts.
+
+ It ends with what could not be ranked or rendered.
+ """
+ scores, tiers, order = board.scores, board.tiers, board.order
+ if board.stream:
+ print("\nSTREAMING PROBE - measured, not declared; a screening of"
+ " look-ahead and state, not of delivery or throughput:")
+ for n in [x for t in order for x in order[t] if x in board.stream]:
+ print(f" {tiers[n][1]:{WIDTH}s}"
+ f" {scorestream.describe(board.stream[n])}")
+ strict = [
+ n for n in order["full"]
+ if scorefiles.get(scores[n], "_deletion", "pct") <= strict_delete
+ ]
+ print("\nSENSITIVITY - the denoising order of the full-band tier among"
+ " systems that also keep"
+ f" deleted-rate <= {strict_delete:.0f}%:")
+ print(" " + " > ".join(tiers[n][1] for n in strict))
+ print(" excluded by that gate: " +
+ ", ".join(f"{tiers[n][1]}"
+ f" ({scorefiles.get(scores[n], '_deletion', 'pct'):.1f}%)"
+ for n in order["full"]
+ if n not in strict))
+ print("\nTASK CONTRACTS - what a row holds a system to;"
+ f" {contracts.axes_statement()}")
+ scored = {
+ c for axes in ranking.AXES_BY_TIER.values() for rows in axes.values()
+ for c, _, _ in rows
+ }
+ for name, listed in board.grouped.items():
+ print(f" {name:13s}{contracts.PROFILES[name]}")
+ print(f" {'':13s}{len(listed)} conditions" +
+ ("" if name == "denoise" else ": " +
+ ", ".join(c + ("" if c in scored else " (diagnostic)")
+ for c in listed)))
+ print(" undone before scoring: " + "; ".join(
+ f"{what} ({bound})" for what, bound, _ in contracts.CONVENTIONS))
+ for tier, systems in board.partial.items():
+ print(f"\nNOT RANKED ({tier}) - incomplete or invalid metrics (missing"
+ f" axes / < {ranking.MIN_ITEMS} items / level calibration"
+ " saturated):")
+ for n, reasons in systems.items():
+ print(f" {tiers[n][1]:{WIDTH}s} {'; '.join(reasons)}")
+ if board.missing:
+ print("\nMISSING OUTPUTS - items a system did not return (its means"
+ " exclude them):")
+ for n, m in board.missing.items():
+ print(f" {tiers[n][1]:{WIDTH}s} " +
+ ", ".join(f"{c} {k}" for c, k in m.items()))
+
+
+def payload(board: Board, view: str) -> dict:
+ """Returns the board as ``--json-out`` writes it."""
+ anchored, scores = board.anchored, board.scores
+ axis_scores = board.axis_scores
+ return {
+ "set_id":
+ anchored["set_id"],
+ "anchors_version":
+ anchored["anchors_version"],
+ "axes_version":
+ ranking.AXES_REGISTRY["version"],
+ "axes_sha256":
+ anchors.digest(ranking.AXES_REGISTRY),
+ "anchors": {
+ k: v for k, v in anchored.items() if k != "deletion_cohort"
+ },
+ "axes":
+ ranking.axis_order(),
+ "parts":
+ ranking.PARTS,
+ "outside":
+ ranking.OUTSIDE,
+ "boards":
+ ranking.BOARDS,
+ "ranking_board":
+ ranking.ranking_board(),
+ # the registry's rule that decides which board ranks a system
+ "assignment":
+ ranking.ASSIGN,
+ "composite_rule":
+ ranking.composite_rule(),
+ "streaming_rule":
+ streamview.rule_sentence(),
+ "tie_bands":
+ dict(ranking.TIE_BANDS, composite=ranking.TIE_BAND),
+ "tie_groups": {
+ t: ranking.tie_clusters(rows, board.comp)
+ for t, rows in board.order.items()
+ },
+ "contracts": {
+ "profiles": contracts.PROFILES,
+ "conditions": board.grouped,
+ "axes": {
+ k: list(v) if v else None for k, v in contracts.AXES.items()
+ },
+ "axes_statement": contracts.axes_statement(),
+ "conventions": [list(row) for row in contracts.CONVENTIONS],
+ },
+ "view":
+ view,
+ "subset":
+ next(iter(score.get("_subset", "all") for score in scores.values()),
+ "all"),
+ "incomplete":
+ board.partial,
+ "missing_outputs":
+ board.missing,
+ "systems": {
+ n: {
+ "tier":
+ board.tiers[n][0],
+ # the board the registry's rule assigns (None: no
+ # band-limited rows), and the board whose score the composite
+ # is (None: not ranked)
+ "board":
+ ranking.board_of(scores[n]),
+ "composite_board": (ranking.board_of(scores[n]) if board.comp[n]
+ == board.comp[n] else None),
+ "label":
+ board.tiers[n][1],
+ "composite":
+ board.comp[n],
+ "board_scores":
+ ranking.board_scores(axis_scores[n]),
+ "part_scores":
+ anchors.part_scores(axis_scores[n], ranking.PARTS),
+ "axis_scores":
+ axis_scores[n],
+ "streaming": (streamview.streaming_summary(board.stream[n])
+ if n in board.stream else None),
+ "precision":
+ board.precision.get(n),
+ "band_above_input_db":
+ scorefiles.band_above_input_db(scores[n]),
+ "metrics": {
+ k: ({
+ kk: vv for kk, vv in v.items() if kk != "items"
+ } if k == "_deletion" else v) for k, v in scores[n].items()
+ },
+ } for n in scores
+ },
+ "order":
+ board.order,
+ }
+
+
+def write(path: str, text: str) -> None:
+ """Writes one output file and says so."""
+ with open(path, "w", encoding="utf-8") as fh:
+ fh.write(text)
+ print(f"wrote {path}")
+
+
+def write_tables(board: Board, a: argparse.Namespace) -> None:
+ """Writes the markdown tables the command line asks for."""
+ scores, tiers, order = board.scores, board.tiers, board.order
+ if a.outside_out:
+ write(
+ a.outside_out,
+ tables.markdown_outside(board.axis_scores, order, tiers,
+ [x for x in a.axis_tables.split(",") if x])
+ + "\n")
+ if a.streaming_out:
+ write(a.streaming_out,
+ streamview.markdown_streaming(board.stream, order, tiers) + "\n")
+ if a.markdown_out:
+ text = tables.markdown_boards(scores, board.axis_scores, board.comp,
+ order, tiers, board.stream,
+ board.precision) + "\n"
+ nb = tables.markdown_table_nb(scores, board.axis_scores, board.comp,
+ order, tiers, board.stream,
+ board.precision)
+ # the 16 kHz tier follows the full-band table after a blank line, with
+ # its lead
+ if nb:
+ text += "\n" + tables.NB_LEAD + "\n\n" + nb + "\n"
+ write(a.markdown_out, text)
+
+
+def main() -> None:
+ a = parse_args()
+ ranking.select_view(a.view)
+ tiers = roster.tiers(a.tiers)
+ scores, anchored = board_scores(a, tiers)
+ axis_scores, comp, order = ranking.rank(scores, tiers, anchored)
+ board = Board(
+ scores=scores,
+ tiers=tiers,
+ anchored=anchored,
+ axis_scores=axis_scores,
+ comp=comp,
+ order=order,
+ stream=streamview.load_streaming(a.results, scores),
+ partial=ranking.incomplete(scores, axis_scores, comp, tiers),
+ grouped=condition_profiles(scores, order),
+ missing=ranking.missing_outputs(scores),
+ precision=load_precision(a.results, scores),
+ )
+ print_tiers(board, a.title)
+ print_ties(board)
+ print_notes(board, a.strict_delete)
+ if a.json_out:
+ with open(a.json_out, "w", encoding="utf-8") as fh:
+ json.dump(scorefiles.finite(payload(board, a.view)),
+ fh,
+ indent=1,
+ allow_nan=False)
+ print(f"\nwrote {a.json_out}")
+ write_tables(board, a)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/bench/scripts/levels.py b/bench/scripts/levels.py
new file mode 100644
index 0000000..781eb78
--- /dev/null
+++ b/bench/scripts/levels.py
@@ -0,0 +1,99 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The output-gain convention: one gain per system.
+
+The gain is undone wherever level is not the question.
+
+A system's gain is measured once, on clean speech (``level_cal_db``: the median
+output-over-input level of the ``clean`` items, bounded at
+``common.MAX_LEVEL_CAL_DB``), and scored once, as the level-change row of the
+fidelity axis. Everywhere else the output is read as if that gain were undone:
+the kept-energy rows, the lost blocks, suppression of a competing voice and of
+non-voiced sound, the high-band error and deleted speech. These functions read
+one item's raw measurements at a given calibration; the scorer, its sidecars
+and the paired comparison all read through them, so one rule holds everywhere.
+
+Per-item errors are absolute before they are averaged: a mean absolute error
+whose signs could cancel would hide a dull copy behind a bright one.
+"""
+
+import math
+
+import numpy as np
+
+# a speech segment whose energy drops further than this is deleted
+DEL_DB = -10.0
+# a block kept further than this under the recording is lost: the floor of the
+# preservation scale
+LOST_DB = -10.0
+HF_BANDS = slice(4, 7) # 8-12, 12-16 and 16-24 kHz of common.BANDS_HZ
+
+
+def gain(level_cal_db: float) -> float:
+ """Returns the linear factor that undoes a system's output gain."""
+ return 10.0**(-level_cal_db / 20.0)
+
+
+def suppression_db(energies: list, level_cal_db: float) -> float:
+ """Returns residual interference over input interference, in dB.
+
+ Args:
+ energies: Mean squares over the item, ``[|o|^2, <o, r>, |r|^2, |m -
+ r|^2]`` for output o, reference r and mixture m.
+ level_cal_db: The system's output gain, undone: |g o - r|^2 is
+ g^2 |o|^2 - 2 g <o, r> + |r|^2.
+ """
+ oo, orr, rr, mr = (float(v) for v in energies)
+ g = gain(level_cal_db)
+ residual = max(g * g * oo - 2.0 * g * orr + rr, 0.0)
+ return 10.0 * math.log10((residual + 1e-9) / (mr + 1e-9))
+
+
+def energy_db(raw_db: float, level_cal_db: float) -> float:
+ """Returns an output-over-input energy ratio with the output gain undone."""
+ return float(raw_db) - level_cal_db
+
+
+def hf_error_db(bands: list, level_cal_db: float) -> float:
+ """Returns one item's mean absolute level error over the high bands.
+
+ Args:
+ bands: The item's output-over-reference level per band (dB).
+ level_cal_db: The system's output gain, undone first.
+ """
+ high = np.asarray(bands[HF_BANDS], dtype=float)
+ if not high.size or not np.isfinite(high).all():
+ return float("nan")
+ return float(np.mean(np.abs(high - level_cal_db)))
+
+
+def level_error_db(out_in_rms_db: float) -> float:
+ """Returns one item's level change, in absolute dB: the gain itself."""
+ return abs(float(out_in_rms_db))
+
+
+def lost(kept_db: list, level_cal_db: float) -> np.ndarray:
+ """Returns, block by block, whether the output lost it.
+
+ Args:
+ kept_db: Each block's kept level: the output's energy coherent with the
+ recording over the recording's, in dB.
+ level_cal_db: The system's output gain, undone first.
+ """
+ return np.asarray(kept_db, dtype=float) - level_cal_db < LOST_DB
+
+
+def deleted(drops: list, level_cal_db: float) -> list:
+ """Returns 1.0 for each speech segment the output deleted, 0.0 otherwise."""
+ return [1.0 if d - level_cal_db < DEL_DB else 0.0 for d in drops]
diff --git a/bench/scripts/observations.py b/bench/scripts/observations.py
new file mode 100644
index 0000000..6605ef2
--- /dev/null
+++ b/bench/scripts/observations.py
@@ -0,0 +1,239 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Per-item scoring records with opaque source groups and explicit coverage."""
+
+import ast
+import hashlib
+import json
+import math
+import os
+import pathlib
+import re
+from typing import Any
+
+import anchors
+
+# conditions that add nothing to the recording
+BEDLESS = ("clean", "nonverbal_clean")
+# per-item coherence blocks: a view's lost-block share is derived under its own
+# level calibration
+BLOCKS = "coh_blocks"
+
+
+def revive(value: Any) -> Any:
+ """The inverse of ``finite``: JSON null back to nan.
+
+ This way pooled reducers see what was measured.
+ """
+ if value is None:
+ return math.nan
+ if isinstance(value, dict):
+ return {k: revive(v) for k, v in value.items()}
+ if isinstance(value, list):
+ return [revive(v) for v in value]
+ return value
+
+
+def finite(value: Any) -> Any:
+ """Replace nonfinite measurements with JSON null.
+
+ Their missingness is preserved.
+ """
+ if isinstance(value, float):
+ return value if math.isfinite(value) else None
+ if isinstance(value, dict):
+ return {k: finite(v) for k, v in value.items()}
+ if isinstance(value, (list, tuple)):
+ return [finite(v) for v in value]
+ return value
+
+
+def item(row: dict, status: str = "ok") -> dict:
+ """Make a record without exporting corpus names or source paths.
+
+ Background groups use the whole recording, not a window offset. A voice
+ placed in a room has the room's response as its second source: items that
+ share a room are no more independent than items that share a bed. Real
+ recordings and the conditions that add nothing to the recording
+ (``BEDLESS``) have one independent recording group and no separate draw.
+ Missing provenance is marked unverified and cannot support row admission.
+ """
+ provenance = row.get("provenance", {})
+ speech = provenance.get("speech")
+ noise = provenance.get("corruptor") or provenance.get("rir")
+ foreground = anchors.digest(["foreground", speech or row["id"]])
+ real = not row.get("clean_path")
+ if real or not noise:
+ bed = None
+ else:
+ bed = anchors.digest(["bed", re.sub(r"@[+-]?[\d.]+s", "", str(noise))])
+ return {
+ "id":
+ row["id"],
+ "condition":
+ row["condition"],
+ "family":
+ row.get("family", row["condition"].split("@")[0]),
+ "language":
+ row.get("language"),
+ "speaker":
+ anchors.digest(
+ ["speaker",
+ row.get("speaker") or speech or row["id"]]),
+ "speech_source":
+ foreground,
+ "bed_source":
+ bed,
+ "ladder_key":
+ anchors.digest([foreground, bed, row.get("family")]),
+ "groups_verified":
+ (isinstance(speech, str) and bool(speech) and
+ not any(token in speech for token in (" + ", "|", "[")) and
+ (real or isinstance(noise, str) and bool(noise) and
+ not any(token in noise for token in (" + ", "|", "[")) or
+ row["condition"] in BEDLESS)),
+ "output_status":
+ status,
+ "metrics": {},
+ "measurements": {},
+ }
+
+
+def capture(record: dict, accumulated: dict, before: dict) -> None:
+ """Preserve the exact observations the existing condition reducers use."""
+ raw = {
+ k: values[before.get(k, 0):]
+ for k, values in accumulated.items()
+ if len(values) > before.get(k, 0)
+ }
+ record["measurements"] = finite(raw)
+ metrics = {}
+ aliases = {
+ "kept": "kept_mean",
+ "kept_nb": "kept_nb_mean",
+ "band": "band_kept_db",
+ "band_vs_in": "band_vs_in_db",
+ "dnsmos": "dnsmos_ovr",
+ }
+ for key, values in raw.items():
+ if key == "terc":
+ metrics.update({
+ f"kept_q{i + 1}": v for i, v in enumerate(values[0])
+ })
+ elif key not in ("seg_drop", BLOCKS):
+ metrics[aliases.get(key, key)] = values[0]
+ # the deletions are read at a calibration: levels.deleted
+ if "seg_drop" in raw:
+ metrics["n_segments"] = len(raw["seg_drop"])
+ record["metrics"] = finite(metrics)
+
+
+def write(path: str | pathlib.Path, rows: list[dict], metadata: dict) -> None:
+ """Atomically write private observations, including a versioned header."""
+ path = pathlib.Path(path)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ records = [{"type": "metadata", "schema_version": 1, **metadata}] + rows
+ text = "".join(
+ json.dumps(finite(r), sort_keys=True, allow_nan=False) + "\n"
+ for r in records)
+ temporary = path.with_name(f".{path.name}.{os.getpid()}.tmp")
+ try:
+ fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
+ with os.fdopen(fd, "w") as stream:
+ stream.write(text)
+ os.replace(temporary, path)
+ finally:
+ temporary.unlink(missing_ok=True)
+
+
+def read(path: str | pathlib.Path) -> tuple[dict, list[dict]]:
+ """Read complete, uniquely identified observations and their header."""
+ with pathlib.Path(path).open(encoding="utf-8") as stream:
+ records = [json.loads(line) for line in stream if line.strip()]
+ if (not records or records[0].get("type") != "metadata" or
+ records[0].get("schema_version") != 1):
+ raise ValueError("per-item records need a versioned metadata header")
+ metadata, rows = records[0], records[1:]
+ ids = [r["id"] for r in rows]
+ if len(set(ids)) != len(ids) or len(rows) != metadata.get("n_expected"):
+ raise ValueError("per-item records are duplicated or truncated")
+ if not metadata.get("set_id") or not metadata.get("system"):
+ raise ValueError("per-item records need set and system identities")
+ return metadata, rows
+
+
+def sidecar(
+ path: str | pathlib.Path,
+ rows: list[dict],
+ system: str,
+ set_id: str,
+ subset: str,
+ sealed: bool = False,
+ scorer_sha256: str | None = None,
+ **header,
+) -> None:
+ """Writes per-item sidecar observations under one normalization identity.
+
+ ``header`` adds fields such as the level calibration the records were read
+ at.
+ """
+ identity = anchors.stamp()
+ write(
+ path,
+ rows,
+ {
+ "system": system,
+ "set_id": set_id,
+ "subset": subset,
+ "anchors_version": identity["_anchors_version"],
+ "anchors_sha256": identity["_anchors_sha256"],
+ "n_expected": len(rows),
+ "sealed": sealed,
+ "scorer_sha256": scorer_sha256,
+ **header,
+ },
+ )
+
+
+def code_digest(path: str | pathlib.Path) -> str:
+ """Returns the sha256 of a Python file's code.
+
+ Its syntax tree without docstrings, so a comment, a docstring or a
+ reformatting never changes it and any change of what runs always does.
+ """
+ tree = ast.parse(pathlib.Path(path).read_text(encoding="utf-8"))
+ for node in ast.walk(tree):
+ body = getattr(node, "body", None)
+ if (isinstance(
+ node,
+ (
+ ast.Module,
+ ast.FunctionDef,
+ ast.AsyncFunctionDef,
+ ast.ClassDef,
+ ),
+ ) and body and isinstance(body[0], ast.Expr) and
+ isinstance(body[0].value, ast.Constant) and
+ isinstance(body[0].value.value, str)):
+ node.body = body[1:] or [ast.Pass()]
+ return hashlib.sha256(ast.dump(tree).encode()).hexdigest()
+
+
+def implementation(*paths: str) -> str:
+ """Fingerprints scorer sources once, before an expensive run starts.
+
+ The code of each file (``code_digest``), so only a change of what runs makes
+ earlier scores another scorer's.
+ """
+ return anchors.digest({pathlib.Path(p).name: code_digest(p) for p in paths})
diff --git a/bench/scripts/ranking.py b/bench/scripts/ranking.py
new file mode 100644
index 0000000..c507c3d
--- /dev/null
+++ b/bench/scripts/ranking.py
@@ -0,0 +1,456 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Axes, composite and order: how a board scores and ranks its systems.
+
+The axes, their parts and tie bands come from the axis registry
+(``bench/axes.json``, admission.py). Each sub-metric is normalised between the
+frozen anchors (anchors.py) and averaged within its axis, the axes within a
+part and the parts into the composite. ``select_view`` points the module's
+axis tables at one view; ``rank`` and the rest read them.
+"""
+
+import math
+
+import admission
+import anchors
+import common
+import compare
+import contracts
+import roster
+import scorefiles
+
+AXES_REGISTRY = admission.load()
+
+AXES_VIEWS = admission.replay(AXES_REGISTRY)
+
+AXES_FULL = {k: list(v) for k, v in AXES_VIEWS["all"]["full"].items()}
+
+AXES_NB = {k: list(v) for k, v in AXES_VIEWS["all"]["nb"].items()}
+
+AXES_BY_TIER = {"full": AXES_FULL, "nb": AXES_NB}
+
+# how the axes combine; None: the plain mean of the axes
+PARTS = admission.parts(AXES_REGISTRY)
+
+# axes scored and shown beside the composite, not in it
+OUTSIDE = admission.outside(AXES_REGISTRY)
+
+# the scores published side by side, {board: [parts]}; None: one composite of
+# every part
+BOARDS = admission.boards(AXES_REGISTRY)
+
+# which board ranks a system (admission.assignment); None: every system ranks
+# on the first board
+ASSIGN = admission.assignment(AXES_REGISTRY)
+
+# {axis: gap under which two systems tie on it}
+TIE_BANDS = admission.tie_bands(AXES_REGISTRY)
+
+# the axes score what contracts.AXES states: no other row enters an axis
+# except as a stated change there
+for _view in AXES_VIEWS.values():
+ for _axes in _view.values():
+ contracts.check_axes(_axes)
+
+
+def axis_order(axes=None):
+ """Returns the axes in the order of the composite's parts.
+
+ Without parts, the registry's own order; the axes scored beside the
+ composite come last.
+ """
+ axes = AXES_FULL if axes is None else axes
+ inside = [a for a in axes if a not in OUTSIDE]
+ if PARTS:
+ inside = [a for part in PARTS.values() for a in part if a in axes]
+ return inside + [a for a in axes if a in OUTSIDE]
+
+
+def ranking_board():
+ """Returns the board whose score orders the table: the first declared.
+
+ None when the registry publishes one composite.
+ """
+ return next(iter(BOARDS)) if BOARDS else None
+
+
+def restoration_board():
+ """Returns the board the registry's assignment sends the systems that
+ restore above the input's band to; None without such a rule."""
+ return ASSIGN["board"] if ASSIGN else None
+
+
+def assigned(d: dict, rule: dict | None = None):
+ """Returns the board an assignment rule sends a system to, or None.
+
+ ``rule`` is the registry's (``admission.assignment``) by default. None when
+ the system lacks the diagnostic the rule reads (no band-limited rows):
+ missing evidence assigns no board. Without a rule every system goes to the
+ first board.
+ """
+ return scorefiles.assigned_board(d, ASSIGN if rule is None else rule,
+ ranking_board())
+
+
+def board_of(d: dict):
+ """Returns the board a system is ranked on, or None.
+
+ None when the registry publishes one composite, and when the system lacks
+ the band-limited rows the assignment reads (``assigned``). Every system is
+ scored on every board.
+ """
+ return assigned(d) if BOARDS else None
+
+
+def ranks_tier(board, tier: str) -> bool:
+ """Whether ``board`` ranks the systems of ``tier``: the first board ranks
+ every tier, any other board the full-band tier (``admission.assignment``).
+ """
+ return board == ranking_board() or tier == "full"
+
+
+def board_scores(scores: dict) -> dict:
+ """Returns {board: the mean of its parts' scores} for one system.
+
+ Empty without boards; a board is nan where one of its parts is.
+ """
+ if not BOARDS:
+ return {}
+ parts = anchors.part_scores(scores, PARTS)
+ out = {}
+ for name, members in BOARDS.items():
+ values = [parts.get(part, NAN) for part in members]
+ out[name] = (sum(values) / len(values) if values and all(
+ isinstance(v, (int, float)) and math.isfinite(v) for v in values)
+ else NAN)
+ return out
+
+
+def composite_rule():
+ """Returns how the axes combine, and which sit beside the composite."""
+ if not PARTS:
+ rule = f"mean of {len(AXES_FULL) - len(OUTSIDE)} equally weighted axes"
+ elif BOARDS:
+ parts = {
+ name: f"{name} ({', '.join(axes)})" for name, axes in PARTS.items()
+ }
+ rule = (
+ "two scores, each ranking the systems of its own task and"
+ " each the mean of its parts, each part the mean of its axes: " +
+ "; ".join(f"{board} = {' + '.join(parts[p] for p in members)}"
+ for board, members in BOARDS.items()))
+ if ASSIGN:
+ rule += (f"; a system that restores above the input's band (more"
+ f" than {ASSIGN['above_db']:g} dB on the band-limited"
+ f" rows) is ranked on {ASSIGN['board']}, every other on"
+ f" {ASSIGN['otherwise']}, one without those rows on"
+ " neither")
+ else:
+ rule += f"; the table is ordered by {ranking_board()}"
+ else:
+ rule = (
+ f"mean of {len(PARTS)} equally weighted parts, each the mean of its"
+ " axes: " + "; ".join(
+ f"{name} ({', '.join(axes)})" for name, axes in PARTS.items()))
+ if OUTSIDE:
+ rule += (f"; scored beside both, read by neither: {', '.join(OUTSIDE)}"
+ if BOARDS else
+ f"; scored beside it, not in it: {', '.join(OUTSIDE)}")
+ return rule
+
+
+def select_view(view):
+ """Points the module's axis tables at one view, in place.
+
+ ``rank`` and the rest read the module's tables. A development panel
+ (``common.PANELS``) reads the whole-set axes.
+ """
+ axes_view = "all" if view in common.PANELS else view
+ if axes_view not in AXES_VIEWS:
+ raise SystemExit(
+ f"--view must be one of"
+ f" {sorted(AXES_VIEWS) + list(common.PANELS)}, not {view!r}")
+ for tier, axes in AXES_VIEWS[axes_view].items():
+ AXES_BY_TIER[tier].clear()
+ AXES_BY_TIER[tier].update({k: list(v) for k, v in axes.items()})
+ return view
+
+
+NAN = float("nan")
+
+TIE_BAND = 0.03
+
+MIN_ITEMS = scorefiles.MIN_ITEMS # fewer scored items cannot feed an axis
+
+
+def whole_counts(entry: list, count: int) -> bool:
+ """Returns whether one recording's [deleted, segments] fit its cohort.
+
+ Both must be integers, the segments the cohort's count and the deleted ones
+ between none and all of them.
+ """
+ # bool is an int subclass, and a flag is not a count
+ integers = all(
+ isinstance(v, int) and not isinstance(v, bool) for v in entry)
+ return (len(entry) == 2 and integers and entry[1] == count and
+ 0 <= entry[0] <= count)
+
+
+def pool_deletion(scores: dict, cohort: dict) -> set:
+ """Pools each system's deletion on the frozen INPUT cohort.
+
+ Every expected segment is required.
+
+ A missing recording or changed segment denominator makes that system
+ incomplete. It cannot shrink another system's evaluation population.
+ """
+ for score in scores.values():
+ data = score["_deletion"]
+ items = data.get("items") or {}
+ complete = bool(cohort) and all(
+ uid in items and whole_counts(items[uid], count)
+ for uid, count in cohort.items())
+ if complete:
+ deleted = sum(items[uid][0] for uid in sorted(cohort))
+ total = sum(cohort.values())
+ data.update(
+ pct=100.0 * deleted / total,
+ n_segments=total,
+ cohort_items=len(cohort),
+ complete=True,
+ )
+ else:
+ data.update(pct=NAN, n_segments=0, cohort_items=0, complete=False)
+ return set(cohort)
+
+
+def missing_outputs(scores):
+ """Returns {system: {condition: items not returned}}.
+
+ Every system whose metrics report items it failed to render: a system does
+ not improve its means by failing on its hardest items, so the board says so
+ next to the rank.
+ """
+ out = {}
+ for n, d in scores.items():
+ m = {
+ c: int(v["n_missing"]) for c, v in d.items() if
+ isinstance(v, dict) and not c.startswith("_") and v.get("n_missing")
+ }
+ if m:
+ out[n] = m
+ return out
+
+
+def _covered(scores, n, cond, key):
+ """Returns whether a row may feed an axis.
+
+ It may with a finite value from at least ``MIN_ITEMS`` items that carry the
+ metric and no item the system or its sidecar failed to return: a missing
+ item is never a smaller mean, it is an incomplete row. A pooled row (one
+ named with a leading underscore) answers to the same rule through the
+ counts its sidecar states (the deletion row's are the segments of its
+ frozen cohort), and to its own completeness flag where it has one.
+ """
+ v = scorefiles.get(scores[n], cond, key)
+ data = scores[n].get(cond, {})
+ # the items behind the row, or for the deletion row the segments of its
+ # frozen cohort
+ count = data.get("metric_counts",
+ {}).get(key, data.get("n", data.get("n_segments", 0)))
+ missing = data.get("n_missing", 0) or data.get("metric_missing", {}).get(
+ key, 0)
+ return (math.isfinite(v) and bool(data.get("complete", True)) and
+ count >= MIN_ITEMS and not missing)
+
+
+def rank(scores: dict,
+ tiers: dict | None = None,
+ calibration: dict | None = None):
+ """Score and order every system. Returns (axis_scores, composite, order).
+
+ The caller supplies a frozen calibration. Neither endpoints nor the
+ deletion cohort are inferred from the systems being ranked. ``order``
+ holds each tier's systems by their score on the board that orders the
+ table and, under every other board's name, the full-band systems that
+ board ranks (``board_of``); the composite is each system's score on its
+ own board.
+ """
+ tiers = tiers or roster.TIERS
+ if calibration is None:
+ raise ValueError(
+ "a frozen anchors.resolved.json calibration is required")
+ anchors.validate_scores(calibration, scores)
+ if calibration.get("axes_sha256") != anchors.digest(AXES_BY_TIER):
+ raise ValueError("axis membership differs from the frozen calibration")
+ untiered = sorted(n for n in scores if n not in tiers and n != "INPUT")
+ # a result file nobody registered: a stray sweep, never a row of the
+ # published board
+ if untiered:
+ print("IGNORED (no tier registered; pass --tiers to rank them):"
+ f" {', '.join(untiered)}")
+ scores = {n: v for n, v in scores.items() if n not in untiered}
+ tier_of = {n: tiers.get(n, ("ref", n))[0] for n in scores}
+ pool_deletion(scores, calibration["deletion_cohort"])
+ axis_scores = {}
+ for tier, axes in AXES_BY_TIER.items():
+ members = [n for n in scores if tier_of[n] == tier]
+ for n in members:
+ out = {}
+ for axis, subs in axes.items():
+ vs = []
+ for cond, key, sign in subs:
+ if not _covered(scores, n, cond, key):
+ vs = []
+ break
+ point = calibration["points"][anchors.row_key(cond, key)]
+ if point["direction"] != sign:
+ raise ValueError(
+ f"axis/anchor direction mismatch: {cond}/{key}")
+ vs.append(
+ anchors.normalize(scorefiles.get(scores[n], cond, key),
+ point))
+ out[axis] = sum(vs) / len(vs) if vs else NAN
+ axis_scores[n] = out
+ for n in scores:
+ axis_scores.setdefault(n, {})
+
+ def composite(n):
+ """Returns the composite, only when every axis is present.
+
+ ``anchors.composite`` over the axis scores. Partial entrants are not
+ ranked, nor is a system whose level calibration saturated: its
+ calibrated metrics are not valid.
+ """
+ if level_saturated(scores[n]):
+ return NAN
+ if not BOARDS:
+ return anchors.composite(axis_scores[n], PARTS, OUTSIDE)
+ # each board needs its own axes and no other's: a system is ranked on
+ # the board of its task (board_of) by that board's score; a system the
+ # rule cannot place, or a board that does not rank its tier, gives no
+ # composite, and incomplete() says why
+ board = board_of(scores[n])
+ if board is None or not ranks_tier(board, tier_of[n]):
+ return NAN
+ return board_scores(axis_scores[n])[board]
+
+ comp = {n: composite(n) for n in scores}
+ first = ranking_board()
+ order = {
+ t:
+ sorted(
+ (n for n in scores if tier_of[n] == t and comp[n] == comp[n] and
+ board_of(scores[n]) == first),
+ key=lambda n: -comp[n],
+ ) for t in AXES_BY_TIER
+ }
+ # every other board ranks its own full-band systems by its own score
+ for board in BOARDS or ():
+ if board != first:
+ order[board] = sorted(
+ (n for n in scores if tier_of[n] == "full" and
+ comp[n] == comp[n] and board_of(scores[n]) == board),
+ key=lambda n: -comp[n],
+ )
+ return axis_scores, comp, order
+
+
+def level_saturated(scores: dict) -> bool:
+ """Returns whether the scorer's level calibration hit its bound.
+
+ The one rule shared with the paired comparisons and the panel report
+ (``compare.level_saturated``).
+ """
+ return compare.level_saturated(scores.get("_level_cal_db"))
+
+
+def incomplete(scores, axis_scores, comp, tiers):
+ """Returns {tier: {system: [reasons]}} for the entrants not ranked.
+
+ The reasons are the axes they miss, or a level calibration that saturated.
+ """
+ out = {}
+ for n in scores:
+ tier = tiers.get(n, ("ref", n))[0]
+ if tier in AXES_BY_TIER and comp[n] != comp[n]:
+ reasons = []
+ if level_saturated(scores[n]):
+ reasons.append(
+ f"level calibration saturated at"
+ f" {common.MAX_LEVEL_CAL_DB:g} dB (the output sits"
+ f" {scores[n]['_level_cal_db']:+.1f} dB or"
+ " further from the input: a scale of its own, so no"
+ " calibrated metric is valid)")
+ board = board_of(scores[n]) if BOARDS else None
+ if BOARDS and board is None:
+ reasons.append("no board: the band-limited rows (" + ", ".join(
+ c for c, _ in scorefiles.BAND_LIMITED_ROWS) +
+ ") that assign one are missing")
+ elif BOARDS and not ranks_tier(board, tier):
+ reasons.append(
+ f"assigned to {board}, which ranks the full-band tier"
+ " only")
+ needed = (set(a for part in BOARDS[board] for a in PARTS[part])
+ if board else None)
+ missing = [
+ ax for ax, v in axis_scores[n].items()
+ if v != v and (needed is None or ax in needed)
+ ]
+ if missing:
+ reasons.append("missing " + ", ".join(missing))
+ out.setdefault(tier, {})[n] = reasons or ["missing all"]
+ return out
+
+
+def tie_clusters(rows, comp):
+ """Returns the groups of tied systems among the ordered ``rows``.
+
+ Top down, a group holds the systems under ``TIE_BAND`` below its best
+ composite, so every pair inside it is a tie; only groups of two or more are
+ returned.
+ """
+ clusters, current = [], []
+ for n in rows:
+ if current and comp[current[0]] - comp[n] < TIE_BAND:
+ current.append(n)
+ continue
+ if len(current) > 1:
+ clusters.append(current)
+ current = [n]
+ if len(current) > 1:
+ clusters.append(current)
+ return clusters
+
+
+def axis_ties(axis_scores, rows, tiers):
+ """Returns {axis: labels} of the systems tied with an axis's best.
+
+ For every axis that declares a tie band and has more than one ranked system
+ within that band of its best score.
+ """
+ out = {}
+ for axis, band in TIE_BANDS.items():
+ scored = {n: axis_scores[n].get(axis, NAN) for n in rows}
+ scored = {n: v for n, v in scored.items() if v == v}
+ if not scored:
+ continue
+ best = max(scored.values())
+ tied = [
+ n for n in sorted(scored, key=lambda n, scored=scored: -scored[n])
+ if best - scored[n] < band
+ ]
+ if len(tied) > 1:
+ out[axis] = [tiers[n][1] for n in tied]
+ return out
diff --git a/bench/scripts/roster.py b/bench/scripts/roster.py
new file mode 100644
index 0000000..137af0b
--- /dev/null
+++ b/bench/scripts/roster.py
@@ -0,0 +1,79 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The systems a published board ranks: each one's tier and label.
+
+``full``: eligible for the 0-48 kHz goal. ``nb``: a 16 kHz-native model,
+ranked in its own tier on the band-limited readings. ``ref``: a reference row,
+shown and never ranked. A system missing here is ignored by the board unless
+``leaderboard.py --tiers`` names it.
+"""
+
+import json
+
+TIERS = {
+ "voice_isolator_v0": ("full", "Inworld Voice Isolator (64M, offline)"),
+ "voice_isolator_v0_realtime": (
+ "full",
+ "Inworld Voice Isolator realtime (58M, look-ahead 20 ms)",
+ ),
+ "clearvoice_mf2_48k": ("full", "ClearerVoice MossFormer2_SE_48K"),
+ "dfn3": ("full", "DeepFilterNet3"),
+ "fastenhancer_l_48k": ("full", "FastEnhancer-L 48k"),
+ "reuse_nemotron": (
+ "full",
+ "NVIDIA NemotronLabs RE-USE (9.6M, 2026-10)",
+ ),
+ "reuse_nemotron_laughter": (
+ "full",
+ "NVIDIA NemotronLabs RE-USE-laughter (9.6M, 2026-10)",
+ ),
+ "resemble_dn": ("full", "resemble-enhance (denoise)"),
+ "urgent26_bsrnn": (
+ "full",
+ ("URGENT 2026 BSRNN baseline (official, 48k, shipped peak"
+ " normalisation)"),
+ ),
+ "urgent26_bsrnn_flow": (
+ "full",
+ ("URGENT 2026 FlowSE baseline (official, 48k, without final peak"
+ " normalisation)"),
+ ),
+ "gap_urgenet": ("full", "GAP-URGENet (URGENT 2026 Track 1, 1st objective)"),
+ "unipase": (
+ "full",
+ "UniPASE (TASLP 2026, 16 kHz core, post-net to 48 kHz)",
+ ),
+ "smule": ("full", "Smule Renaissance Small (10.4M)"),
+ "demucs_vocals": ("ref", "Demucs vocals (separation reference)"),
+ "INPUT": ("ref", "unprocessed input"),
+ "REF": ("ref", "clean reference (paired items only)"),
+}
+
+
+def tiers(path: str | None = None) -> dict:
+ """Returns the registered tiers, with those of a ``--tiers`` file added.
+
+ Args:
+ path: A JSON file mapping system names to ``[tier, label]``, or None.
+ """
+ merged = dict(TIERS)
+ if path:
+ with open(path, encoding="utf-8") as fh:
+ merged.update({k: tuple(v) for k, v in json.load(fh).items()})
+ return merged
+
+
+def display_name(name: str) -> str:
+ """Returns a system's label without its parenthesised details."""
+ return TIERS.get(name, (None, name))[1].split(" (")[0]
diff --git a/bench/scripts/runfield.sh b/bench/scripts/runfield.sh
new file mode 100755
index 0000000..a24e0c7
--- /dev/null
+++ b/bench/scripts/runfield.sh
@@ -0,0 +1,122 @@
+#!/usr/bin/env bash
+# Copyright 2026 Inworld AI — Apache-2.0
+#
+# Renders the board's external systems over the eval set, one venv each
+# (installed by setupfield.sh).
+#
+# VOICE_ISOLATION_EVALS=<set> BENCH_OUT=<outputs> BENCH_RESULTS=<results> \
+# BENCH_VENVS=<venvs> BENCH_SRC=<sources> [DEVICE=cuda:0] runfield.sh [system ...]
+#
+# Every wrapper process writes a receipt before it renders (wrappers/receipt.py:
+# its code, the release's source and weights, packages, device, arguments and
+# inputs). Before a system renders, this script takes the receipt its venv
+# would write now and compares it with the receipts in the system's output
+# folder: outputs of this identity are resumed (wrappers skip the files they
+# hold); outputs of another identity, or without receipts, stop the system
+# unless DISCARD=1, which removes them first. After the wrapper,
+# stamprender.py stamps $BENCH_RESULTS/<name>.meta.json only if the wrapper
+# exited zero, every receipt carries this identity and the inventory is exact.
+# STAMP_ONLY=1 verifies and stamps outputs that wrapper processes rendered
+# elsewhere (shards: <wrapper> --shard i/k), the same way. DEVICE is what
+# every GPU system computes on; CUDA_VISIBLE_DEVICES chooses the card.
+#
+# PROBE_IN=<dir> renders another folder of inputs instead, the streaming probe
+# (scorestream.py --probe) or the same-room pair (scoreevents.py --pair), into
+# $BENCH_OUT/<name>, only in the environment that rendered the board (its
+# receipt's environment digest must equal the board's stamp), and stamps
+# nothing: the scorer that cut the inputs reads the receipts.
+set -uo pipefail
+HERE=$(cd "$(dirname "$0")" && pwd)
+ROOT=$(cd "$HERE/../.." && pwd)
+IN=${PROBE_IN:-${VOICE_ISOLATION_EVALS:-$ROOT/data/voice-isolation-evals}/mix}
+OUT=${BENCH_OUT:-$ROOT/data/outputs}
+RES=${BENCH_RESULTS:-$ROOT/bench/results}
+VENVS=${BENCH_VENVS:-$HOME/.cache/voice-isolation-bench/venvs}
+DEVICE=${DEVICE:-cuda:0}
+W=$HERE/../wrappers
+export BENCH_SRC=${BENCH_SRC:-$HOME/.cache/voice-isolation-bench/src}
+[ -n "$(ls "$IN"/*.wav 2>/dev/null | head -1)" ] || {
+ echo "no inputs under $IN (set VOICE_ISOLATION_EVALS or PROBE_IN)"; exit 1; }
+SET_ID=""
+if [ -z "${PROBE_IN:-}" ]; then
+ SET_ID=$(python3 -c "import json,sys; print(json.load(open(sys.argv[1]))['set_id'])" \
+ "$(dirname "$IN")/checksums.json" 2>/dev/null) || {
+ echo "no checksums.json with a set_id beside $IN"; exit 1; }
+fi
+mkdir -p "$OUT" "$RES"
+
+field () { # field <key>: one field of the JSON document on stdin
+ python3 -c "import json,sys; print(json.load(sys.stdin).get(sys.argv[1]) or '')" "$1"
+}
+
+held () { # held <out dir>: the identity digests of the receipts there
+ python3 - "$1" <<'PY'
+import glob, json, os, sys
+paths = glob.glob(os.path.join(sys.argv[1], ".receipt-*.json"))
+print(" ".join(sorted({json.load(open(p)).get("digest", "") for p in paths})))
+PY
+}
+
+FAILS=0
+fail () { echo " !! $*"; FAILS=$((FAILS + 1)); }
+
+run () { # run <system> <venv> <wrapper> <device> [wrapper arguments]
+ local name=$1 venv=$2 wrap=$3 dev=$4; shift 4
+ local py="$VENVS/${venv}_venv/bin/python" out="$OUT/$name" probe digest
+ echo "===== $name"
+ # each venv carries its own CUDA libraries: the node's must not shadow them
+ probe=$(env -u LD_LIBRARY_PATH "$py" "$W/receipt.py" probe "$name" "$W/$wrap" \
+ --in-dir "$IN" --device "$dev" -- "$@") || {
+ fail "$name: no receipt from this environment (venv, release or weights missing)"; return; }
+ digest=$(field digest <<< "$probe")
+ if [ -n "${PROBE_IN:-}" ]; then
+ local board
+ board=$(field render_environment_sha256 < "$RES/$name.meta.json" 2>/dev/null)
+ [ "$(field environment_digest <<< "$probe")" = "$board" ] || {
+ fail "$name: this environment did not render the board's stamp ($RES/$name.meta.json)"; return; }
+ fi
+ if [ -z "${STAMP_ONLY:-}" ]; then
+ local holds foreign=""
+ holds=$(held "$out")
+ if [ -n "$holds" ]; then
+ [ "$holds" = "$digest" ] || foreign=1
+ elif [ -n "$(ls "$out"/*.wav 2>/dev/null | head -1)" ]; then
+ foreign=1 # outputs without a receipt: of unknown origin
+ fi
+ if [ -n "$foreign" ]; then
+ [ -n "${DISCARD:-}" ] || {
+ fail "$name: $out holds outputs of another identity; DISCARD=1 removes them"; return; }
+ echo " discarding the outputs of another identity in $out"
+ rm -rf "$out"
+ fi
+ env -u LD_LIBRARY_PATH "$py" "$W/$wrap" --in-dir "$IN" --out-dir "$out" \
+ --device "$dev" "$@" 2>&1 | tail -3
+ local code=${PIPESTATUS[0]}
+ [ "$code" -eq 0 ] || { fail "$name: the wrapper exited $code"; return; }
+ fi
+ [ -n "${PROBE_IN:-}" ] && return
+ "${BENCH_PY:-python3}" "$HERE/stamprender.py" "$name" --wrapper "$W/$wrap" \
+ --inputs "$IN" --outputs "$out" --results "$RES" --set-id "$SET_ID" \
+ --wrapper-exit 0 --probe-digest "$digest" || fail "$name: not stamped"
+}
+
+ALL="reuse_nemotron reuse_nemotron_laughter gap_urgenet clearvoice_mf2_48k urgent26_bsrnn_flow resemble_dn \
+fastenhancer_l_48k dfn3 urgent26_bsrnn unipase smule"
+for s in ${*:-$ALL}; do
+ case $s in
+ reuse_nemotron) run reuse_nemotron reuse runreusenemotron.py "$DEVICE" ;;
+ reuse_nemotron_laughter) run reuse_nemotron_laughter reuse runreusenemotronlaughter.py "$DEVICE" ;;
+ gap_urgenet) run gap_urgenet gap_urgenet rungapurgenet.py "$DEVICE" ;;
+ clearvoice_mf2_48k) run clearvoice_mf2_48k clearvoice runclearvoice.py "$DEVICE" ;;
+ urgent26_bsrnn_flow) run urgent26_bsrnn_flow urgent26 runurgent26bsrnnflow.py "$DEVICE" ;;
+ resemble_dn) run resemble_dn resemble runresembledn.py "$DEVICE" ;;
+ fastenhancer_l_48k) run fastenhancer_l_48k fastenhancer runfastenhancer.py cpu ;;
+ dfn3) run dfn3 dfn3 rundfn3.py "$DEVICE" ;;
+ urgent26_bsrnn) run urgent26_bsrnn urgent26 runurgent26bsrnn.py "$DEVICE" ;;
+ unipase) run unipase unipase rununipase.py "$DEVICE" ;;
+ smule) run smule smule runsmule.py "$DEVICE" ;;
+ *) fail "unknown system $s" ;;
+ esac
+done
+echo "FIELD DONE ($FAILS problem(s))"
+[ "$FAILS" -eq 0 ]
diff --git a/bench/scripts/runsystem.py b/bench/scripts/runsystem.py
new file mode 100644
index 0000000..bc0d485
--- /dev/null
+++ b/bench/scripts/runsystem.py
@@ -0,0 +1,780 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Renders the Inworld isolator, or a reference system, over the eval set.
+
+Writes ``<BENCH_OUT>/<name>/<id>.wav`` in the file layout of every external
+wrapper, so the scorer compares systems, not harnesses, and stamps
+``<BENCH_RESULTS>/<name>.meta.json``.
+
+ runsystem.py --name voice_isolator_v0 --model voice-isolator-v0
+ runsystem.py --name <tag> --model ckpt.safetensors --chunk-seconds 8
+ runsystem.py --name demucs_vocals --demucs # the separation reference
+ runsystem.py --name INPUT --input # the unprocessed input
+ runsystem.py --name REF --reference # clean references, paired
+ runsystem.py --name <tag> --outputs <dir> # rendered elsewhere
+
+A computed render (``--model``, ``--demucs``) is held to what a wrapper is:
+every process writes a receipt (``bench/wrappers/receipt.py``: this script,
+the package's code, every checkpoint including the Demucs hint's, the
+installed packages, the device, the arguments and the inputs) before it
+renders; each output is written whole or not at all; outputs already there
+are resumed only when every receipt beside them carries this run's identity,
+another identity's outputs (the code, the weights, the packages, the
+arguments or the set changed) are discarded and rendered again, with what
+differed printed, and outputs without a receipt stop the run; and the process
+that completes the selection (the set, or ``BENCH_SUBSET``, with every shard's
+outputs) stamps it through ``stamprender.stamp``. ``--overwrite`` first
+removes every output and receipt of the system whatever their identity.
+``--inputs`` renders another folder (the streaming probe of
+``scorestream.py --probe`` or the same-room pair of ``scoreevents.py --pair``)
+and stamps nothing: that render is matched to the board's by its receipts.
+
+INPUT, REF and ``--outputs`` link files instead of computing them; their
+stamp names the set and, for ``--outputs``, a digest of the linked folder and
+of the outputs it answers the set with (``outputs_sha256``, as a computed
+render's stamp records it).
+"""
+
+import argparse
+import contextlib
+import glob
+import hashlib
+import json
+import os
+import socket
+import sys
+import time
+
+import torch
+
+# pylint: disable=wrong-import-position
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import common
+import stamprender
+
+sys.path.insert(0, os.path.join(common.BENCH_DIR, "wrappers"))
+import receipt
+import writer
+
+SR = common.SR
+HTDEMUCS = "955717e8" # demucs/remote/htdemucs.yaml: the bag's one model
+OURS_META = {
+ "mechanism":
+ ("band-split dual-path network: 46 bands, time attention (RoPE, "
+ "exclusive self attention) and dual-path Mamba blocks, per-bin "
+ "complex mask + bounded residual; one set of weights runs offline "
+ "({chunk:g} s windows, {overlap:g} s crossfades) or streaming (the "
+ "stateful session, block by block)"),
+ "native_sr":
+ 48000,
+ "fullband":
+ True,
+ "license_code":
+ "Apache-2.0",
+ "license_weights":
+ "Apache-2.0",
+ "commercial_ok":
+ True,
+ "renormalizes":
+ False,
+ "notes":
+ ("no input level conditioning: the bare model, output gain matches "
+ "the input"),
+}
+DEMUCS_META = {
+ "mechanism": "music source separation (HTDemucs v4) - vocals stem only",
+ "native_sr": 44100,
+ "fullband": True,
+ "license_code": "MIT",
+ "license_weights": "MIT",
+ "commercial_ok": True,
+ "renormalizes": False,
+ "params_m": 42.0,
+ "repo": "https://github.com/adefossez/demucs",
+ "notes": "separator, not a denoiser: the music-separation reference.",
+ "precision": "fp32",
+}
+
+
+def parse_args() -> argparse.Namespace:
+ """Returns the command line, checked."""
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--name", required=True)
+ g = ap.add_mutually_exclusive_group(required=True)
+ g.add_argument("--model",
+ help="registry name or checkpoint (dir, .safetensors, .pt)")
+ g.add_argument("--input",
+ action="store_true",
+ help="the unprocessed input as a system")
+ g.add_argument(
+ "--reference",
+ action="store_true",
+ help="the clean references as a system",
+ )
+ g.add_argument(
+ "--demucs",
+ action="store_true",
+ help="the htdemucs vocals stem as a system",
+ )
+ g.add_argument(
+ "--outputs",
+ help=("a folder of <id>.wav rendered elsewhere (an "
+ "architecture the package cannot load, a hosted system), "
+ "linked in as the system"),
+ )
+ ap.add_argument(
+ "--inputs",
+ default="",
+ help=("render this folder of 48 kHz WAVs instead of the "
+ "set's mixtures (the streaming probe or the same-room "
+ "pair); with --model or --demucs"),
+ )
+ ap.add_argument("--stage2", default=None)
+ ap.add_argument("--alpha", type=float, default=None)
+ ap.add_argument("--mode",
+ default="offline",
+ choices=("offline", "streaming"),
+ help="offline (every frame sees the whole window) or "
+ "streaming (causal, with --lookahead frames)")
+ ap.add_argument("--lookahead",
+ type=int,
+ default=0,
+ help="streaming look-ahead in frames (10 ms each)")
+ ap.add_argument("--block-frames",
+ type=int,
+ default=4,
+ help="streaming mode: frames processed together")
+ ap.add_argument("--cache-frames",
+ type=int,
+ default=None,
+ help=("streaming mode: frames the time attention "
+ "remembers; default: the training window"))
+ ap.add_argument("--window-frames",
+ type=int,
+ default=None,
+ help=("streaming mode: the attention window in frames; "
+ "default: the model's (600); 0: no windows"))
+ ap.add_argument("--crossfade-frames",
+ type=int,
+ default=None,
+ help=("streaming mode: frames the two lanes blend over "
+ "before a window boundary; default: the model's "
+ "(200)"))
+ ap.add_argument("--chunk-seconds", type=float, default=None)
+ ap.add_argument("--overlap-seconds", type=float, default=None)
+ ap.add_argument("--limit", type=int, default=0)
+ ap.add_argument(
+ "--precision",
+ default="auto",
+ choices=("auto", "fp32", "fp16", "bf16"),
+ help=("network precision: auto is bf16 on a GPU (the training "
+ "precision) and fp32 on CPU; the stamp records what ran"),
+ )
+ ap.add_argument(
+ "--batch",
+ type=int,
+ default=1,
+ help=("clips per separator pass (equal lengths are "
+ "grouped; numerics match --batch 1 up to kernel "
+ "rounding)"),
+ )
+ ap.add_argument(
+ "--shard",
+ default="",
+ help=("i/k: render every k-th item from the i-th (one "
+ "process per GPU; the last to finish stamps)"),
+ )
+ ap.add_argument(
+ "--overwrite",
+ action="store_true",
+ help=("remove every output and receipt of this system "
+ "first, instead of resuming"),
+ )
+ a = ap.parse_args()
+ if (a.name == "REF") != a.reference:
+ ap.error("the reserved REF name requires --reference, and vice versa")
+ if a.inputs and not (a.model or a.demucs):
+ ap.error("--inputs renders the model or the Demucs hint; INPUT, REF "
+ "and linked outputs have no probe")
+ if a.overwrite and a.shard:
+ ap.error("--overwrite with --shard would remove the other shards' "
+ "work: clear the folder once, then render the shards")
+ return a
+
+
+def selection(a: argparse.Namespace, rows: list) -> tuple[str, list, dict]:
+ """Returns (input folder, input files, {name: reference}) a run answers.
+
+ Raises:
+ SystemExit: The probe folder is empty, or REF lacks a reference.
+ """
+ if a.inputs:
+ files = sorted(glob.glob(os.path.join(a.inputs, "*.wav")))
+ if not files:
+ raise SystemExit(f"no WAV files under {a.inputs}")
+ return a.inputs, files, {}
+ mix = os.path.join(common.EVAL, "mix")
+ if a.reference:
+ refs = {r["id"]: r["clean_path"] for r in rows if r.get("clean_path")}
+ if not refs or any(not os.path.isfile(p) for p in refs.values()):
+ raise SystemExit("REF requires every declared clean reference; "
+ "real inputs are not substitutes")
+ return mix, [os.path.join(mix, uid) for uid in sorted(refs)], refs
+ return mix, sorted(r["mix_path"] for r in rows), {}
+
+
+def share(files: list, shard: str, limit: int) -> list:
+ """Returns this process's part of the selection."""
+ if shard:
+ index, count = (int(v) for v in shard.split("/"))
+ if count < 1 or not 0 <= index < count:
+ raise SystemExit(f"--shard {shard}: need 0 <= i < k")
+ files = files[index::count]
+ return files[:limit] if limit else files
+
+
+def checkpoint_file(model: str) -> str:
+ """Returns the checkpoint file a model argument names.
+
+ A registry name, an ``hf://`` spec or a path; ``model.pt`` inside an
+ export folder.
+ """
+ # pylint: disable-next=import-outside-toplevel
+ from inworld.voice_isolation import registry
+
+ path = registry.resolve(model)
+ return os.path.join(path, "model.pt") if os.path.isdir(path) else path
+
+
+def weights_digest(model: str) -> str:
+ """Returns the sha256 of the checkpoint behind ``model``."""
+ return receipt.sha256_file(checkpoint_file(model))
+
+
+def public_path(path: str | None) -> str | None:
+ """Returns a checkpoint path fit for a published file.
+
+ Relative to the repository inside it, the bare file name outside; registry
+ names pass through.
+ """
+ if not path or not os.path.exists(path):
+ return path
+ full = os.path.abspath(path)
+ repo = os.path.dirname(common.BENCH_DIR)
+ if full.startswith(repo + os.sep):
+ return os.path.relpath(full, repo)
+ return os.path.basename(full)
+
+
+def demucs_weights() -> list:
+ """Returns the htdemucs checkpoint the hint frontend loaded.
+
+ Demucs keeps it, hash-checked on download, in torch hub's cache.
+ """
+ hub = os.path.join(torch.hub.get_dir(), "checkpoints")
+ found = sorted(glob.glob(os.path.join(hub, f"{HTDEMUCS}-*.th")))
+ if len(found) != 1:
+ raise FileNotFoundError(
+ f"expected one htdemucs checkpoint under {hub}, found {len(found)}")
+ return found
+
+
+def ours(a: argparse.Namespace) -> tuple:
+ """Returns the isolator and what identifies it.
+
+ A tuple (run, run_many, description, weights, packages).
+ """
+ # pylint: disable-next=import-outside-toplevel
+ from inworld import voice_isolation
+
+ vi = voice_isolation.VoiceIsolator.load(
+ checkpoint_file(a.model),
+ stage2=checkpoint_file(a.stage2) if a.stage2 else None,
+ device=common.DEV,
+ precision=a.precision,
+ mode=a.mode,
+ lookahead_frames=a.lookahead,
+ block_frames=a.block_frames,
+ cache_frames=a.cache_frames,
+ window_frames=a.window_frames,
+ crossfade_frames=a.crossfade_frames,
+ )
+ chunk, overlap = vi.model.default_window()
+ desc = dict(OURS_META)
+ desc["mechanism"] = desc["mechanism"].format(
+ chunk=chunk if a.chunk_seconds is None else a.chunk_seconds,
+ overlap=overlap if a.overlap_seconds is None else a.overlap_seconds)
+ desc.update(
+ weights=public_path(a.model),
+ weights_sha256=weights_digest(a.model),
+ stage2=public_path(a.stage2),
+ stage2_sha256=weights_digest(a.stage2) if a.stage2 else None,
+ alpha=a.alpha,
+ mode=vi.mode,
+ lookahead_frames=vi.lookahead_frames,
+ latency_samples=vi.latency_samples()
+ if vi.mode == "streaming" else None,
+ block_frames=vi.block_frames if vi.mode == "streaming" else None,
+ cache_frames=vi.cache_frames if vi.mode == "streaming" else None,
+ window_frames=vi.window_frames if vi.mode == "streaming" else None,
+ crossfade_frames=(vi.crossfade_frames
+ if vi.mode == "streaming" else None),
+ precision=vi.precision, # resolved: what the render ran in
+ chunk_seconds=chunk if a.chunk_seconds is None else a.chunk_seconds,
+ overlap_seconds=(overlap
+ if a.overlap_seconds is None else a.overlap_seconds),
+ params_m=round(vi.model.num_params / 1e6, 1),
+ batch=a.batch,
+ )
+ kw = dict(
+ output_sample_rate=SR,
+ chunk_seconds=a.chunk_seconds,
+ overlap_seconds=a.overlap_seconds,
+ )
+
+ def run(x):
+ if a.alpha is None:
+ return vi.isolate(x, SR, **kw)
+ return vi.enhance(x, SR, alpha=a.alpha, **kw)
+
+ def run_many(xs):
+ return vi.isolate_many(xs, SR, **kw)
+
+ weights = [checkpoint_file(a.model)]
+ weights += [checkpoint_file(a.stage2)] if a.stage2 else []
+ packages = ["inworld.voice_isolation"]
+ return (run, run_many if a.alpha is None else None, desc, weights, packages)
+
+
+def oracle() -> tuple:
+ """Returns the Demucs vocals stem and what identifies it.
+
+ A tuple (run, run_many, description, weights, packages).
+ """
+ # pylint: disable-next=import-outside-toplevel
+ import demucsvocals
+
+ demucs_vocals = demucsvocals.DemucsVocals(common.DEV)
+
+ def run(x):
+ return demucs_vocals.vocals(x.to(common.DEV)).cpu()
+
+ return (
+ run,
+ None,
+ dict(DEMUCS_META),
+ demucs_weights(),
+ ["inworld.voice_isolation", "demucs"],
+ )
+
+
+FIELDS = {
+ "wrapper_sha256": "the renderer",
+ "helpers_sha256": "the renderer's code",
+ "source": "the release",
+ "package_code_sha256": "the package code",
+ "weights_sha256": "the weights",
+ "python": "python",
+ "packages_sha256": "the installed packages",
+ "n_packages": "the installed packages",
+ "device": "the device",
+ "inference_args": "the arguments",
+ "inputs": "the inputs (set build or probe)",
+}
+
+
+def differences(old: dict, new: dict) -> list[str]:
+ """Names the parts of a render's identity that differ between two."""
+ fields = {k for k in set(old) | set(new) if old.get(k) != new.get(k)}
+ return sorted({FIELDS.get(k, k) for k in fields})
+
+
+def taken(out_dir: str, wait: float = 300.0):
+ """Holds the folder's lock while a process decides what it resumes.
+
+ The shards of one render arrive together: the lock serialises their look
+ at the receipts, so the first discards another identity's outputs and the
+ rest resume its. A lock older than ``wait`` seconds was abandoned and is
+ taken over; a live one is waited for that long.
+ """
+ path = os.path.join(out_dir, ".prepare-lock")
+ deadline = time.time() + wait
+ fd = None
+ while fd is None:
+ try:
+ fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
+ except FileExistsError:
+ try:
+ abandoned = time.time() - os.path.getmtime(path) > wait
+ except FileNotFoundError:
+ continue
+ if abandoned:
+ with contextlib.suppress(FileNotFoundError):
+ os.remove(path)
+ elif time.time() > deadline:
+ raise SystemExit(f"{path} has been held for over {wait:.0f} s;"
+ " remove it if its owner is gone") from None
+ else:
+ time.sleep(0.1)
+ try:
+ os.write(fd, f"{socket.gethostname()} {os.getpid()}\n".encode())
+ os.close(fd)
+ yield
+ finally:
+ with contextlib.suppress(FileNotFoundError):
+ os.remove(path)
+
+
+def prepare(out_dir: str, ident: dict, argv: list, overwrite: bool) -> str:
+ """Resumes or empties ``out_dir`` and writes this process's receipt.
+
+ Outputs are resumed only under the identity that rendered them. Another
+ identity's outputs (the code, the weights, the installed packages, the
+ arguments or the set differ) are discarded with their receipts, what
+ differed printed, and rendered again; ``overwrite`` discards everything
+ whatever its identity.
+
+ Returns:
+ The identity's digest.
+
+ Raises:
+ SystemExit: The folder holds outputs without a receipt: nothing says
+ what they are, so nothing is removed.
+ """
+ digest = receipt.digest(ident)
+ os.makedirs(out_dir, exist_ok=True)
+ with taken(out_dir):
+ held = glob.glob(os.path.join(out_dir, "*.wav"))
+ receipts = receipt.read_all(out_dir)
+ foreign = [r for r in receipts if r.get("digest") != digest]
+ live = [r for r in foreign if process_alive(r)]
+ if live and not overwrite:
+ raise SystemExit(
+ f"{out_dir}: another identity is still rendering here (pid "
+ f"{live[0].get('pid')} on {live[0].get('host')}); wait for "
+ "it, stop it, or use a new --name")
+ if overwrite:
+ reason = "--overwrite"
+ elif foreign:
+ differed = sorted({
+ part for r in foreign
+ for part in differences(r.get("identity", {}), ident)
+ })
+ reason = "another identity: " + (", ".join(differed) or
+ "the receipt's fields") + " differ"
+ elif held and not receipts and all(os.path.islink(p) for p in held):
+ # linked in by --input, --reference or --outputs: nothing is lost
+ reason = "linked outputs"
+ elif held and not receipts:
+ raise SystemExit(
+ f"{out_dir} holds {len(held)} outputs without a receipt "
+ "(unknown origin); remove them or use --overwrite")
+ else:
+ reason = None
+ if reason is not None:
+ stale = (glob.glob(os.path.join(out_dir, ".receipt-*")) +
+ glob.glob(os.path.join(out_dir, ".partial-*")))
+ for path in held + stale:
+ os.remove(path)
+ print(f"discarded {len(held)} outputs ({reason}); rendering again",
+ flush=True)
+ receipt.write(out_dir, ident, argv)
+ return digest
+
+
+def process_alive(doc: dict) -> bool:
+ """Whether the process that wrote a receipt still runs on this host.
+
+ Another host's process cannot be seen; its receipt reads as finished,
+ and so does this process's own earlier receipt. A process the signal
+ may not reach (another user's) is alive; a pid that now names another
+ process (the receipt's start time differs) is not.
+ """
+ if doc.get("host") != socket.gethostname() or not doc.get("pid"):
+ return False
+ try:
+ pid = int(doc["pid"])
+ if pid == os.getpid():
+ return False
+ os.kill(pid, 0)
+ except PermissionError:
+ pass
+ except (OSError, ValueError):
+ return False
+ start = doc.get("process_start")
+ now = receipt.process_start(pid)
+ if start is not None and now is not None and start != now:
+ return False
+ return True
+
+
+def read(path: str) -> torch.Tensor:
+ """Returns one input as a mono float32 tensor.
+
+ Raises:
+ ValueError: The input is not at the set's rate.
+ """
+ samples, rate = writer.read(path)
+ if rate != SR:
+ raise ValueError(f"{rate} Hz input; the set is {SR} Hz")
+ return torch.from_numpy(samples)
+
+
+def render(todo: list, out_dir: str, run, run_many, batch: int) -> int:
+ """Renders ``todo`` into ``out_dir``; returns how many were written.
+
+ Every output is published under the folder's lock, after this process's
+ receipt is seen to be still there: a takeover (another identity, or
+ ``--overwrite``) holds the same lock, so it cannot slip in between the
+ check and the write and stamp this render's audio as its own.
+ """
+ t0, ok, step = time.time(), 0, max(1, batch)
+ for start in range(0, len(todo), step):
+ xs = {}
+ for path in todo[start:start + step]:
+ try:
+ xs[path] = read(path)
+ except Exception as e: # pylint: disable=broad-exception-caught
+ print(f"FAIL {os.path.basename(path)} {e}", flush=True)
+ ys = {}
+ if run_many is not None and len(xs) > 1:
+ try:
+ with torch.inference_mode():
+ ys = dict(zip(xs, run_many(list(xs.values()))))
+ except Exception as e: # pylint: disable=broad-exception-caught
+ # one clip at a time keeps per-file failures apart
+ print(f" batch of {len(xs)} failed ({e}); one by one",
+ flush=True)
+ for path, x in xs.items():
+ try:
+ if path not in ys:
+ with torch.inference_mode():
+ ys[path] = run(x)
+ y = writer.fit(ys[path].float().cpu().numpy(), len(x), SR)
+ with taken(out_dir):
+ if not os.path.exists(receipt.own_path(out_dir)):
+ # another identity took the folder: its stamp must
+ # not vouch for this render's outputs
+ raise SystemExit(
+ f"{out_dir}: this render's receipt is gone "
+ "(another identity or --overwrite took the "
+ "folder); stopping")
+ writer.save(os.path.join(out_dir, os.path.basename(path)),
+ y, SR)
+ ok += 1
+ except Exception as e: # pylint: disable=broad-exception-caught
+ print(f"FAIL {os.path.basename(path)} {e}", flush=True)
+ done = min(start + step, len(todo))
+ if done // 25 != start // 25:
+ print(
+ f" {done}/{len(todo)} {(time.time() - t0) / done:.2f}s/clip",
+ flush=True,
+ )
+ print(f"DONE {ok}/{len(todo)} ({time.time() - t0:.0f}s)", flush=True)
+ return ok
+
+
+def compute(
+ a: argparse.Namespace,
+ in_dir: str,
+ selected: list,
+ files: list,
+ out_dir: str,
+) -> int:
+ """Renders the model or the Demucs stem; stamps a complete selection.
+
+ Returns:
+ 0 when every file of this process's share was written.
+ """
+ run, run_many, desc, weights, packages = oracle() if a.demucs else ours(a)
+ code = [writer.__file__]
+ if a.demucs:
+ # pylint: disable-next=import-outside-toplevel
+ import demucsvocals
+ code.append(demucsvocals.__file__)
+ ident = receipt.identity(
+ a.name,
+ os.path.abspath(__file__),
+ sys.argv,
+ in_dir,
+ common.DEV,
+ weights=tuple(weights),
+ desc={"package_dirs": packages},
+ code=tuple(code),
+ )
+ digest = prepare(out_dir, ident, sys.argv, a.overwrite)
+ todo = [
+ p for p in files
+ if not os.path.exists(os.path.join(out_dir, os.path.basename(p)))
+ ]
+ print(
+ f"{len(files)} inputs from {in_dir}; {len(todo)} to do -> {out_dir}",
+ flush=True,
+ )
+ if render(todo, out_dir, run, run_many, a.batch) < len(todo):
+ return 1
+ if a.inputs:
+ return 0
+ present = sum(
+ os.path.exists(os.path.join(out_dir, os.path.basename(p)))
+ for p in selected)
+ if present < len(selected):
+ print(
+ f"{present}/{len(selected)} outputs present: the run that "
+ "completes the selection stamps it",
+ flush=True,
+ )
+ return 0
+ meta = stamprender.stamp(
+ a.name,
+ os.path.abspath(__file__),
+ selected,
+ out_dir,
+ common.RESULTS,
+ common.set_id(),
+ digest,
+ desc,
+ common.SUBSET,
+ )
+ print(
+ f"stamped {a.name}: {meta['n_files']} files, identity {digest[:12]}",
+ flush=True,
+ )
+ return 0
+
+
+def folder_digest(path: str) -> str:
+ """Returns the content identity of a folder of outputs.
+
+ Every WAV's name and bytes, in name order.
+ """
+ hasher = hashlib.sha256()
+ for name in sorted(os.listdir(path)):
+ if name.endswith(".wav"):
+ hasher.update(name.encode())
+ hasher.update(
+ bytes.fromhex(receipt.sha256_file(os.path.join(path, name))))
+ return hasher.hexdigest()
+
+
+def link(a: argparse.Namespace, selected: list, files: list, refs: dict,
+ out_dir: str) -> int:
+ """Links INPUT, REF or a folder rendered elsewhere in as the system.
+
+ Raises:
+ SystemExit: The folder lacks an item, or links already there point
+ elsewhere than this run would point them.
+ """
+
+ def source(path: str) -> str:
+ base = os.path.basename(path)
+ if a.reference:
+ return refs[base]
+ return os.path.join(a.outputs, base) if a.outputs else path
+
+ missing = [p for p in selected if not os.path.isfile(source(p))]
+ if missing:
+ raise SystemExit(
+ f"{len(missing)} of {len(selected)} items are missing (first: "
+ f"{os.path.basename(missing[0])}); every item must be there")
+ os.makedirs(out_dir, exist_ok=True)
+ # under the folder's lock, like a render's publication: a renderer
+ # re-checking its receipt cannot interleave with the takeover
+ with taken(out_dir):
+ held = glob.glob(os.path.join(out_dir, "*.wav"))
+ if a.overwrite:
+ # the receipts go too: a later computed run must not resume the
+ # links as its own render
+ for path in held + glob.glob(os.path.join(
+ out_dir, ".receipt-*")) + glob.glob(
+ os.path.join(out_dir, ".partial-*")):
+ os.remove(path)
+ else:
+ targets = {os.path.basename(p): source(p) for p in selected}
+ foreign = [
+ p for p in held
+ if os.path.basename(p) not in targets or os.path.realpath(p) !=
+ os.path.realpath(targets[os.path.basename(p)])
+ ]
+ if foreign:
+ raise SystemExit(
+ f"{out_dir} holds {len(foreign)} outputs that are not "
+ "links to what this run links (e.g. "
+ f"{os.path.basename(foreign[0])}: another folder or "
+ "system); use --overwrite or a new --name")
+ for path in files:
+ dst = os.path.join(out_dir, os.path.basename(path))
+ if not os.path.lexists(dst):
+ os.symlink(os.path.abspath(source(path)), dst)
+ if a.reference:
+ meta = {
+ "mechanism": "clean reference",
+ "scope": "paired",
+ "reference": True,
+ }
+ elif a.input:
+ meta = {"mechanism": "unprocessed input"}
+ else:
+ meta = {
+ "mechanism":
+ "rendered elsewhere",
+ "source":
+ os.path.basename(os.path.abspath(a.outputs.rstrip("/"))),
+ "source_sha256":
+ folder_digest(a.outputs),
+ "outputs_sha256":
+ stamprender.outputs_digest(selected, a.outputs),
+ "notes": ("outputs linked in from a folder rendered outside this "
+ "harness; the tier and the display name are declared in "
+ "leaderboard.py --tiers"),
+ }
+ if not a.outputs:
+ meta.update(native_sr=SR, fullband=True)
+ present = sum(
+ os.path.lexists(os.path.join(out_dir, os.path.basename(p)))
+ for p in selected)
+ print(f"linked {len(files)} -> {out_dir}", flush=True)
+ if present == len(selected):
+ meta.update(
+ name=a.name,
+ display=a.name,
+ wrapper="bench/scripts/runsystem.py",
+ set_id=common.set_id(),
+ subset=common.SUBSET,
+ n_files=len(selected),
+ )
+ os.makedirs(common.RESULTS, exist_ok=True)
+ dst = os.path.join(common.RESULTS, f"{a.name}.meta.json")
+ tmp = f"{dst}.{os.getpid()}.tmp"
+ with open(tmp, "w", encoding="utf-8") as fh:
+ json.dump(meta, fh, indent=1)
+ os.replace(tmp, dst)
+ return 0
+
+
+def main() -> int:
+ a = parse_args()
+ rows = common.manifest() # BENCH_SUBSET=<panel>: that panel's items only
+ common.guard_private_results(rows)
+ in_dir, selected, refs = selection(a, rows)
+ files = share(selected, a.shard, a.limit)
+ out_dir = os.path.join(common.OUT_ROOT, a.name)
+ if a.model or a.demucs:
+ return compute(a, in_dir, selected, files, out_dir)
+ return link(a, selected, files, refs, out_dir)
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/bench/scripts/scoreasr.py b/bench/scripts/scoreasr.py
new file mode 100644
index 0000000..d973ff3
--- /dev/null
+++ b/bench/scripts/scoreasr.py
@@ -0,0 +1,754 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Downstream ASR: what a recogniser gets out of the audio, processed or not.
+
+ scoreasr.py --systems INPUT,voice_isolator_v0[,...]
+ [--asr large-v3,small,inworld/inworld-stt-1] [--conds ...] [--limit N]
+ [--device cuda] [--workers 8]
+
+Recognisers: a bare name is a faster-whisper model size run locally;
+``inworld/<model>`` is the Inworld speech-to-text API (key in
+``INWORLD_API_KEY``), called concurrently with ``--workers``.
+
+For every paired item of the chosen conditions the recogniser transcribes each
+system's output and the transcript is scored against the item's golden text:
+``transcripts.jsonl`` in the set root, one verified transcript per target
+utterance with the tier of its verification. An item without a golden text falls
+back to the recogniser's own transcript of the clean reference (cached), and the
+sidecar records how many items each condition scored that way, so a number can
+always be traced to its ground truth. Whisper's own English normaliser, or its
+basic normaliser for the other languages, is applied to both sides; Chinese and
+Japanese are scored per character. For each condition the sidecar holds the
+pooled error rate (total edits over total reference tokens), a bootstrap 95 %
+interval over items, and the per-item edit counts.
+
+Writes ``<BENCH_RESULTS>/<system>.asr.json``, one block per recogniser.
+Transcripts are cached by the audio a recogniser hears (the decoded samples,
+their rate and channel count, never the file's bytes, which a float WAV also
+stamps with the time it was written) and by decoding identity under
+``BENCH_CACHE`` (default ``<repo>/data/asr_cache``), so a re-run, or a re-render
+that reproduces the same audio, transcribes only new audio, and any change of
+recogniser, version or decoding setting transcribes everything again.
+"""
+
+import argparse
+import base64
+from concurrent import futures
+import hashlib
+import io
+import json
+import os
+import random
+import sys
+import tempfile
+import threading
+import time
+import wave
+
+import numpy as np
+import soundfile as sf
+import torch
+import torchaudio
+
+# pylint: disable=wrong-import-position
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import common
+import observations
+import scorebench
+
+SCORER_SHA256 = observations.implementation(__file__, common.__file__,
+ observations.__file__,
+ scorebench.__file__)
+
+DEFAULT_CONDS = (
+ "clean",
+ "babble@+4",
+ "babble@+0",
+ "babble@-5",
+ "babble@-10",
+ "ambience@-5",
+ "ambience@-10",
+ "stationary@-5",
+ "stationary@-10",
+ "traffic@-5",
+ "traffic@-10",
+ "events@-5",
+ "music@-6",
+ "wind@+0",
+ "quiet@-30dBFS",
+ "conversation@0",
+ "long@+4",
+ "wild@+0",
+ "wild@-5",
+ "wild@-10",
+ "soft@+5",
+ "soft@+0",
+ "soft@-5",
+ "whisper@+5",
+ "whisper@+0",
+)
+CHAR_LANGS = frozenset(
+ # no word boundaries: per character
+ ("zh", "yue", "ja", "th", "lo", "my", "km"))
+# a recogniser without a model for a language decodes it as its nearest written
+# standard
+NEAREST = {"yue": "zh"}
+CACHE_ROOT = os.environ.get("BENCH_CACHE",
+ os.path.join(common.REPO_DIR, "data", "asr_cache"))
+# verified transcripts of the target utterances, in the set root
+GOLDEN = "transcripts.jsonl"
+FALLBACK = "clean-asr" # the recogniser's own transcript of the clean reference
+N_BOOT = 1000
+
+
+def edit_distance(a, b):
+ """Levenshtein distance between two token sequences."""
+ if not a:
+ return len(b)
+ if not b:
+ return len(a)
+ prev = list(range(len(b) + 1))
+ for i, x in enumerate(a, 1):
+ cur = [i]
+ for j, y in enumerate(b, 1):
+ cur.append(min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (x != y)))
+ prev = cur
+ return prev[-1]
+
+
+class Normalizer:
+ """Whisper's text normalisers, from the tokenizer that ships them.
+
+ The English one for ``en`` (spelling, numbers, contractions), the basic one
+ otherwise. Tokens are words, or characters for the languages without word
+ boundaries.
+ """
+
+ def __init__(self, tokenizer_name="openai/whisper-tiny"):
+ # pylint: disable-next=import-outside-toplevel
+ import transformers
+
+ self._tok = transformers.WhisperTokenizer.from_pretrained(
+ tokenizer_name)
+
+ def tokens(self, text, language):
+ if language == "en":
+ norm = self._tok.normalize(text or "")
+ else:
+ norm = self._tok.basic_normalize(text or "")
+ if language in CHAR_LANGS:
+ return [ch for ch in norm if not ch.isspace()]
+ return norm.split()
+
+
+def unit_for(language):
+ return "char" if language in CHAR_LANGS else "word"
+
+
+class FasterWhisper:
+ """faster-whisper (CTranslate2) in fp16 on the GPU.
+
+ ``tag`` is the model size.
+ """
+
+ def __init__(self, size="large-v3", device=None, beam_size=5):
+ # pylint: disable-next=import-outside-toplevel
+ import ctranslate2
+ # pylint: disable-next=import-outside-toplevel
+ import faster_whisper
+
+ self.tag = size
+ self.beam_size = beam_size
+ on_gpu = str(device or common.DEV).startswith("cuda")
+ compute_type = "float16" if on_gpu else "int8"
+ # the cached snapshot: <...>/snapshots/<rev>
+ weights = faster_whisper.download_model(size)
+ self.model = faster_whisper.WhisperModel(
+ weights,
+ device="cuda" if on_gpu else "cpu",
+ compute_type=compute_type,
+ )
+ # everything that can change a transcript of the same audio
+ self.identity = {
+ "engine": "faster-whisper",
+ "version": faster_whisper.__version__,
+ "ctranslate2": ctranslate2.__version__,
+ "model": size,
+ "model_revision": os.path.basename(os.path.normpath(weights)),
+ "compute_type": compute_type,
+ "beam_size": beam_size,
+ "condition_on_previous_text": False,
+ "vad_filter": False,
+ }
+
+ def transcribe(self, path, language=None):
+ # Cantonese entered Whisper with large-v3; smaller checkpoints list the
+ # token, were never trained with it and emit noise, so they decode it as
+ # written Chinese
+ if language in NEAREST and not self.tag.startswith("large-v3"):
+ language = NEAREST[language]
+ segs, _ = self.model.transcribe(
+ path,
+ beam_size=self.beam_size,
+ language=None if language in (None, "und") else language,
+ condition_on_previous_text=False,
+ vad_filter=False,
+ )
+ return " ".join(s.text for s in segs).strip()
+
+
+API_LANG = { # the set's language codes as the API's locale tags
+ "en": "en-US",
+ "de": "de-DE",
+ "fr": "fr-FR",
+ "es": "es-ES",
+ "it": "it-IT",
+ "pt": "pt-PT",
+ "ja": "ja-JP",
+ "ko": "ko-KR",
+ "zh": "zh-CN",
+ "hi": "hi-IN",
+ "bn": "bn-IN",
+ "ta": "ta-IN",
+}
+API_SR = 16000
+
+
+def wav_bytes_16k(path):
+ """The clip as 16 kHz 16-bit mono WAV bytes: what the speech APIs take."""
+ x, sr = sf.read(path, dtype="float32", always_2d=True)
+ x = torch.from_numpy(x.mean(1))
+ if sr != API_SR:
+ x = torchaudio.functional.resample(x, sr, API_SR)
+ pcm = (x.numpy() * 32767).clip(-32768, 32767).astype(np.int16)
+ buf = io.BytesIO()
+ with wave.open(buf, "wb") as w:
+ w.setnchannels(1)
+ w.setsampwidth(2)
+ w.setframerate(API_SR)
+ w.writeframes(pcm.tobytes())
+ return buf.getvalue()
+
+
+class InworldSTT:
+ """The Inworld speech-to-text REST API, one request per clip.
+
+ ``tag`` is the model id.
+ """
+
+ URL = "https://api.inworld.ai/stt/v1/transcribe"
+ concurrent = True
+
+ def __init__(self,
+ model="inworld/inworld-stt-1",
+ key=None,
+ tries=6,
+ timeout=120):
+ self.tag = model
+ self.key = key or os.environ.get("INWORLD_API_KEY")
+ if not self.key:
+ raise SystemExit(
+ "INWORLD_API_KEY is not set (the Inworld API key, Basic auth)")
+ self.tries, self.timeout = tries, timeout
+ self.identity = {
+ "engine": "inworld-stt-api",
+ "model": model,
+ "encoding": "LINEAR16 16 kHz mono",
+ }
+
+ def transcribe(self, path, language=None):
+ # pylint: disable-next=import-outside-toplevel
+ import requests
+
+ body = {
+ "transcribeConfig": {
+ "modelId": self.tag,
+ "audioEncoding": "LINEAR16",
+ "sampleRateHertz": API_SR,
+ "numberOfChannels": 1,
+ },
+ "audioData": {
+ "content": base64.b64encode(wav_bytes_16k(path)).decode()
+ },
+ }
+ if language and language != "und":
+ body["transcribeConfig"]["language"] = API_LANG.get(
+ language, API_LANG.get(NEAREST.get(language), language))
+ delay = 1.0
+ for k in range(self.tries):
+ try:
+ r = requests.post(
+ self.URL,
+ headers={
+ "Authorization": f"Basic {self.key}",
+ "Content-Type": "application/json",
+ },
+ json=body,
+ timeout=self.timeout,
+ )
+ if r.status_code == 200:
+ transcription = r.json().get("transcription") or {}
+ return transcription.get("transcript", "").strip()
+ if r.status_code < 500 and r.status_code != 429:
+ raise RuntimeError(f"HTTP {r.status_code}: {r.text[:200]}")
+ # network or a non-JSON body
+ except (requests.RequestException, ValueError) as e:
+ if k == self.tries - 1:
+ raise RuntimeError(f"{type(e).__name__}: {e}") from e
+ if k == self.tries - 1:
+ raise RuntimeError(
+ f"HTTP {r.status_code} after {self.tries} tries:"
+ f" {r.text[:200]}")
+ time.sleep(delay + random.random())
+ delay = min(delay * 2, 30)
+
+
+def make_asr(spec, device=None, beam_size=5):
+ """Returns a recogniser from its spec.
+
+ ``inworld/<model>`` is the Inworld API, anything else a faster-whisper model
+ size.
+ """
+ if spec.startswith("inworld/"):
+ return InworldSTT(spec)
+ return FasterWhisper(spec, device, beam_size)
+
+
+def cache_tag(asr):
+ return f"{asr.identity['engine']}_{asr.tag}".replace("/", "_")
+
+
+def file_sha(path):
+ h = hashlib.sha256()
+ with open(path, "rb") as fh:
+ for chunk in iter(lambda: fh.read(1 << 20), b""):
+ h.update(chunk)
+ return h.hexdigest()
+
+
+# bumped whenever the audio a recogniser is handed, or its key, changes
+CACHE_FORMAT = 3
+
+
+def audio_key(path):
+ """Returns the cache key of a file: what a recogniser hears.
+
+ The decoded samples with their rate and channel count; two files of the same
+ audio share it whatever their container bytes.
+ """
+ samples, rate = sf.read(path, dtype="float32", always_2d=True)
+ digest = hashlib.sha256(f"{rate}|{samples.shape[1]}|".encode())
+ digest.update(np.ascontiguousarray(samples).tobytes())
+ return digest.hexdigest()
+
+
+def identity_key(identity: dict) -> str:
+ """Returns the cache directory of one decoding identity.
+
+ A digest of every setting that can change a transcript (engine, model,
+ version, decoding options) and of the cache format.
+ """
+ doc = dict(identity, cache_format=CACHE_FORMAT)
+ text = json.dumps(doc, sort_keys=True)
+ return hashlib.sha256(text.encode()).hexdigest()[:16]
+
+
+class Cache:
+ """Transcripts by ``audio_key``, one JSON file per audio.
+
+ The files live under ``<root>/<asr tag>/<identity key>/``. A transcript is
+ reused only for the same audio decoded with the same identity: every entry
+ records the identity it was decoded with and is read back only when that
+ matches, and a new beam size, model or recogniser version starts a directory
+ of its own. Requests for the same audio from several threads decode it once;
+ each write goes through its own temporary file.
+ """
+
+ def __init__(self, root, tag, identity):
+ self.identity = dict(identity)
+ self.dir = os.path.join(root, tag, identity_key(identity))
+ os.makedirs(self.dir, exist_ok=True)
+ stamp = os.path.join(self.dir, "identity.json")
+ if not os.path.exists(stamp):
+ _write_json(stamp, dict(self.identity, cache_format=CACHE_FORMAT))
+ self.hits = self.misses = 0
+ self._lock = threading.Lock()
+ self._pending = {}
+
+ def _read(self, path, language):
+ try:
+ with open(path, encoding="utf-8") as fh:
+ entry = json.load(fh)
+ except (OSError, ValueError):
+ return None
+ if (entry.get("identity") != self.identity or
+ entry.get("language", language) != language):
+ # decoded otherwise, or in another language: asked again
+ return None
+ return entry["text"]
+
+ def get(self, asr, path, language):
+ key = audio_key(path)
+ target = os.path.join(self.dir, f"{key}.json")
+ with self._lock:
+ lock = self._pending.setdefault((key, language), threading.Lock())
+ # a second request for the same audio waits and then reads the first's
+ # entry
+ with lock:
+ text = self._read(target, language)
+ if text is not None:
+ with self._lock:
+ self.hits += 1
+ return text
+ text = asr.transcribe(path, language)
+ _write_json(
+ target,
+ {
+ "text": text,
+ "language": language,
+ "source": os.path.basename(path),
+ "identity": self.identity,
+ },
+ )
+ with self._lock:
+ self.misses += 1
+ return text
+
+
+def _write_json(path, doc):
+ """Writes ``doc`` to ``path`` through a temporary file of its own.
+
+ The file is then renamed into place.
+ """
+ fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path), suffix=".tmp")
+ try:
+ with os.fdopen(fd, "w") as fh:
+ json.dump(doc, fh)
+ os.replace(tmp, path)
+ finally:
+ if os.path.exists(tmp):
+ os.unlink(tmp)
+
+
+def pooled(items):
+ """Returns (pooled error rate %, total edits, total reference tokens).
+
+ Over {id: [edits, ref_len]}.
+ """
+ e = sum(v[0] for v in items.values())
+ n = sum(v[1] for v in items.values())
+ return (100.0 * e / n if n else float("nan")), e, n
+
+
+def bootstrap_ci(items, n_boot=N_BOOT, seed=0):
+ """95 % interval of the pooled rate under resampling of items."""
+ vals = np.array(list(items.values()), dtype=float)
+ if len(vals) < 2 or vals[:, 1].sum() == 0:
+ return [float("nan"), float("nan")]
+ rng = np.random.default_rng(seed)
+ rates = []
+ for _ in range(n_boot):
+ pick = vals[rng.integers(0, len(vals), len(vals))]
+ n = pick[:, 1].sum()
+ rates.append(100.0 * pick[:, 0].sum() / n if n else float("nan"))
+ rates = np.array(rates)
+ rates = rates[np.isfinite(rates)]
+ return [float(np.percentile(rates, 2.5)), float(np.percentile(rates, 97.5))]
+
+
+def load_golden(root=None):
+ """Returns {id: {"text", "tier", ...}} from the set's transcripts.jsonl.
+
+ Empty when the set has none.
+ """
+ path = os.path.join(root or common.EVAL, GOLDEN)
+ if not os.path.exists(path):
+ return {}
+ out = {}
+ with open(path, encoding="utf-8") as fh:
+ for line in fh:
+ if line.strip():
+ r = json.loads(line)
+ out[r["id"]] = r
+ return out
+
+
+def spoken_language(r, golden):
+ """Returns the language an item is decoded and normalised in.
+
+ The manifest's, unless its golden transcript says another one is spoken
+ (``spoken``: a label found wrong by ear).
+ """
+ return ((golden.get(r["id"]) or {}).get("spoken") or r.get("language") or
+ "und")
+
+
+def reference_tokens(r, golden, asr, cache, norm):
+ """Returns (tokens, tier) of the item's ground truth.
+
+ The golden text, else the clean-reference transcript of the same recogniser.
+ """
+ lang = spoken_language(r, golden)
+ g = golden.get(r["id"])
+ if g and g.get("text"):
+ return norm.tokens(g["text"], lang), g.get("tier") or "golden"
+ return norm.tokens(cache.get(asr, r["clean_path"], lang), lang), FALLBACK
+
+
+def prefill(asr, cache, rows, outd, workers, golden=None):
+ """Transcribes every output, and every reference without a golden text.
+
+ ``workers`` at a time: the API recognisers are latency-bound, so the
+ sequential scoring pass then hits the cache.
+ """
+ golden = golden or {}
+ jobs = []
+ for r in rows:
+ lang = spoken_language(r, golden)
+ if not (golden.get(r["id"]) or {}).get("text"):
+ jobs.append((r["clean_path"], lang))
+ op = os.path.join(outd, r["id"])
+ if os.path.exists(op):
+ jobs.append((op, lang))
+ with futures.ThreadPoolExecutor(workers) as ex:
+ list(ex.map(lambda j: cache.get(asr, *j), jobs))
+
+
+def score_system(name, rows, asr, cache, norm, golden=None, workers=1):
+ """Returns one system's per-condition error rates against the ground truth.
+
+ ``rows`` are the paired manifest rows to score, ``golden`` the loaded
+ transcripts.jsonl (may be empty).
+ """
+ golden = golden or {}
+ outd = os.path.join(common.OUT_ROOT, name)
+ if workers > 1 and getattr(asr, "concurrent", False):
+ prefill(asr, cache, rows, outd, workers, golden)
+ by_cond = {}
+ for r in rows:
+ by_cond.setdefault(r["condition"], []).append(r)
+ scores = {}
+ for cond, items in sorted(by_cond.items()):
+ recs, units, n_empty_ref, n_missing = {}, {"word": 0, "char": 0}, 0, 0
+ tiers = {}
+ for r in items:
+ op = os.path.join(outd, r["id"])
+ if not os.path.exists(op):
+ n_missing += 1
+ continue
+ lang = spoken_language(r, golden)
+ ref, tier = reference_tokens(r, golden, asr, cache, norm)
+ if not ref:
+ n_empty_ref += 1
+ continue
+ hyp = norm.tokens(cache.get(asr, op, lang), lang)
+ recs[r["id"]] = [edit_distance(hyp, ref), len(ref)]
+ units[unit_for(lang)] += 1
+ tiers[tier] = tiers.get(tier, 0) + 1
+ if not recs:
+ continue
+ rate, e, n = pooled(recs)
+ scores[cond] = {
+ "n": len(recs),
+ "n_missing": n_missing,
+ "n_empty_reference": n_empty_ref,
+ "units": units,
+ "reference_tiers": tiers,
+ "edits": e,
+ "ref_tokens": n,
+ "wer_pct": rate,
+ "ci95": bootstrap_ci(recs),
+ "items": recs,
+ }
+ return scores
+
+
+def stale_sidecar(doc, results):
+ """Returns why an ASR-family sidecar may not be shown, or None.
+
+ It was scored by another implementation (``_scorer_sha256`` against
+ ``expected``), on a partial selection, or on other audio than the system's
+ base records describe (when they are at hand in ``results``).
+ """
+ name = doc.get("_system")
+ if (doc.get("_selection") or {}).get("limit"):
+ return (f"scored only {doc['_selection']['limit']} items per condition"
+ " (--limit)")
+ base = os.path.join(results, f"{name}.items.jsonl")
+ if doc.get("_outputs") is None:
+ return "records no audio identity (scored before outputs were recorded)"
+ if os.path.isfile(base):
+ _, records = observations.read(base)
+ scored = {
+ r["id"]: (r.get("identity") or {}).get("output") for r in records
+ }
+ other = [
+ uid for uid, h in doc["_outputs"].items() if scored.get(uid, h) != h
+ ]
+ if other:
+ return (
+ f"read other audio than the base scores for {len(other)} items"
+ f" ({other[0]})")
+ return None
+
+
+def output_hashes(name, rows):
+ """Returns {item id: sample hash} of the outputs of ``name`` in ``rows``.
+
+ Hashed as the base records identify the audio they scored.
+ """
+ outd = os.path.join(common.OUT_ROOT, name)
+ return {
+ r["id"]:
+ scorebench.sample_hash(common.load48(os.path.join(outd, r["id"])))
+ for r in rows
+ if os.path.exists(os.path.join(outd, r["id"]))
+ }
+
+
+def write_sidecar(path, name, tag, block, asr_identity, normaliser_version,
+ outputs, selection):
+ """Merges one recogniser's block into <system>.asr.json.
+
+ The file records the audio its transcripts came from (``_outputs``: the
+ sample hash of every output, as the base records identify it), the scorer
+ that read them and the items selected. Blocks of other recognisers are kept
+ only when they read the same audio with the same scorer and selection; a
+ file of another set build or subset is replaced, not merged.
+ """
+ doc = {}
+ if os.path.exists(path):
+ try:
+ with open(path, encoding="utf-8") as fh:
+ doc = json.load(fh)
+ except (OSError, ValueError):
+ doc = {}
+ same = (doc.get("_set_id") == common.set_id() and
+ doc.get("_subset", "all") == common.SUBSET and
+ doc.get("_outputs") == outputs and
+ doc.get("_scorer_sha256") == SCORER_SHA256 and
+ doc.get("_selection") == selection)
+ if not same:
+ dropped = sorted(t for t in doc.get("asr") or {} if t != tag)
+ if dropped:
+ print(
+ f" {name}: dropping {', '.join(dropped)}: read other"
+ " audio, scorer or items",
+ flush=True,
+ )
+ doc = {}
+ doc.update({
+ "_system": name,
+ "_set_id": common.set_id(),
+ "_subset": common.SUBSET,
+ "_scorer_sha256": SCORER_SHA256,
+ "_selection": selection,
+ "_outputs": outputs,
+ "_reference": f"{GOLDEN} where present, else {FALLBACK}",
+ "_normaliser": (f"transformers {normaliser_version} WhisperTokenizer"),
+ })
+ doc.setdefault("asr", {})[tag] = {
+ "identity": asr_identity,
+ "conditions": block,
+ }
+ tmp = f"{path}.{os.getpid()}.tmp"
+ with open(tmp, "w", encoding="utf-8") as fh:
+ json.dump(doc, fh, indent=1)
+ os.replace(tmp, path)
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument(
+ "--systems",
+ required=True,
+ help="comma-separated system names (INPUT included)",
+ )
+ ap.add_argument(
+ "--asr",
+ default="large-v3",
+ help=(
+ "comma-separated: faster-whisper sizes, or inworld/<model> for the"
+ " Inworld API"),
+ )
+ ap.add_argument(
+ "--workers",
+ type=int,
+ default=8,
+ help="concurrent requests for API recognisers",
+ )
+ ap.add_argument("--conds", default=",".join(DEFAULT_CONDS))
+ ap.add_argument("--limit",
+ type=int,
+ default=0,
+ help="items per condition (0: all)")
+ ap.add_argument("--device", default=None)
+ ap.add_argument("--beam-size", type=int, default=5)
+ a = ap.parse_args()
+ # pylint: disable-next=import-outside-toplevel
+ import transformers
+
+ rows_all = common.manifest()
+ common.guard_private_results(rows_all)
+ if common.is_sealed(rows_all):
+ raise SystemExit(
+ "sealed audio cannot be sent to an ASR service or exported through"
+ " ASR reports")
+ rows = []
+ for cond in [c for c in a.conds.split(",") if c]:
+ rows += common.pick_rows(rows_all, cond, a.limit, paired=True)
+ norm = Normalizer()
+ golden = load_golden()
+ print(
+ (f"golden transcripts: {len(golden)} items in"
+ f" {os.path.join(common.EVAL, GOLDEN)}" if golden else
+ f"no {GOLDEN} in the set: every item falls back to {FALLBACK}"),
+ flush=True,
+ )
+ os.makedirs(common.RESULTS, exist_ok=True)
+ for tag in [t for t in a.asr.split(",") if t]:
+ asr = make_asr(tag, a.device, a.beam_size)
+ cache = Cache(CACHE_ROOT, cache_tag(asr), asr.identity)
+ for name in [s for s in a.systems.split(",") if s]:
+ problem = name != "INPUT" and scorebench.render_problem(name)
+ if problem:
+ print(f"skip {name}: {problem}", flush=True)
+ continue
+ scores = score_system(name, rows, asr, cache, norm, golden,
+ a.workers)
+ outputs = output_hashes(name, rows)
+ write_sidecar(
+ os.path.join(common.RESULTS, f"{name}.asr.json"),
+ name,
+ tag,
+ scores,
+ asr.identity,
+ transformers.__version__,
+ outputs,
+ {
+ "conds": a.conds,
+ "limit": a.limit
+ },
+ )
+ worst = sorted(scores.items(), key=lambda kv: -kv[1]["wer_pct"])[:3]
+ print(
+ f"{tag} {name}: " +
+ " ".join(f"{c} {d['wer_pct']:.1f}%" for c, d in worst) +
+ f" (cache {cache.hits} hits / {cache.misses} new)",
+ flush=True,
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/bench/scripts/scorebench.py b/bench/scripts/scorebench.py
new file mode 100644
index 0000000..41eb9ec
--- /dev/null
+++ b/bench/scripts/scorebench.py
@@ -0,0 +1,929 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Score every system's outputs with the benchmark's own metric implementations.
+
+Layout: <BENCH_OUT>/<system>/<id>.wav
+Output: <BENCH_RESULTS>/<system>.metrics.json
+
+FAIRNESS MACHINERY (all three are reported, never silently applied):
+
+1. LEVEL CALIBRATION. ``level_cal_db`` = median over the ``clean``-condition
+ items of 20*log10(rms(out)/rms(in)), bounded at ``common.MAX_LEVEL_CAL_DB``:
+ one gain per system, scored once, as the level change on clean speech
+ (``level_err_db``), and undone everywhere else (``levels.py``). The kept
+ energy rows are stored raw and calibrated by the board (``raw -
+ level_cal_db``); the rows a single subtraction cannot calibrate are computed
+ here at the calibration, from per-item measurements: competing-voice
+ suppression (``babble_supp_db``, from each item's energies), non-voiced
+ suppression, the high-band error (``hf_err_db``, per-item absolute errors,
+ averaged) and deleted speech. Their raw values stay beside them as
+ ``*_raw_db``. si_sdr is scale-invariant by construction.
+
+2. ALGORITHMIC DELAY. Each item is aligned to the reference by the best lag
+ within +-100 ms (FFT cross-correlation) before reference-based scoring; the
+ median lag is reported per condition.
+
+3. BAND-LIMITED REFERENCE. Every reference metric is also computed with BOTH
+ sides band-limited to 8 kHz (``*_nb``), so a 16 kHz-native model is not
+ judged for HF it structurally cannot emit. ``band_kept_db`` per (0-0.5,
+ 0.5-2, 2-4, 4-8, 8-12, 12-16, 16-24) kHz is the direct measurement of
+ full-band integrity.
+
+Adding a metric to an already-scored field: write a SIDECAR (scorenisqa.py,
+scorerealx.py, scorekept.py), never ``--force`` a full re-score.
+"""
+
+import argparse
+import collections
+import glob
+import hashlib
+import io
+import json
+import os
+import sys
+
+import numpy as np
+import torch
+import torchaudio
+
+# pylint: disable=wrong-import-position
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import anchors
+import common
+import levels
+import observations
+import stamprender
+
+NISQA_ON = os.environ.get("SCORE_NISQA", "1") != "0"
+# the non-voiced floor of a real recording is read on the 20 ms frames whose
+# input is above this: digital silence has no floor to suppress
+NONVOICED_FLOOR_DBFS = -80.0
+# and clear of the detected speech by this many 20 ms frames on either side
+NONVOICED_GUARD_FRAMES = 2
+# the log's guard, far below any floor the row admits (-200 dB): a 1e-9 guard
+# capped the output at about -90 dBFS and read 40 dB of suppression of a
+# -78 dBFS floor as 12
+NONVOICED_EPS = 1e-20
+NISQA_N = int(os.environ.get("SCORE_NISQA_N", "12"))
+SCORER_SHA256 = observations.implementation(__file__, common.__file__,
+ observations.__file__,
+ levels.__file__)
+
+
+def speech_segments(vad, wav48, path):
+ """Returns ``vad.segments`` of a file, cached under the set's ``.cache``.
+
+ The cache is keyed by the audio's samples and the detector's identity: a
+ mixture and its reference share a name but never an entry, and a new
+ detector never reads an old one's segments. The references and mixtures are
+ the same for every system scored, and the voice-activity pass is the
+ scorer's largest cost. ``path`` names the file in error messages only.
+ """
+ del path # the samples, not the name, identify the audio
+ salt = f"{getattr(vad, 'identity', 'vad')}|".encode()
+ samples = wav48.contiguous().numpy().tobytes()
+ key = hashlib.sha256(salt + samples).hexdigest()
+ cache_dir = os.path.join(common.EVAL, ".cache", "vad2")
+ cached = os.path.join(cache_dir, key + ".json")
+ w16 = torchaudio.functional.resample(wav48, common.SR, 16000)
+ if os.path.exists(cached):
+ with open(cached, encoding="utf-8") as fh:
+ return w16, json.load(fh)
+ w16, segs = vad.segments(wav48)
+ os.makedirs(cache_dir, exist_ok=True)
+ tmp = f"{cached}.{os.getpid()}.tmp"
+ with open(tmp, "w", encoding="utf-8") as fh:
+ json.dump([{
+ "start": int(s["start"]),
+ "end": int(s["end"])
+ } for s in segs], fh)
+ os.replace(tmp, cached)
+ return w16, segs
+
+
+def rms_db(x):
+ return float(20 * torch.log10(x.pow(2).mean().sqrt() + 1e-12))
+
+
+def sample_hash(x):
+ """Returns the identity of decoded audio.
+
+ The 48 kHz float32 samples the scorer consumes.
+ """
+ return hashlib.sha256(x.contiguous().numpy().tobytes()).hexdigest()
+
+
+def item_identity(r, out_hash, hashes):
+ """Returns what one item's observation depends on, besides the scorer.
+
+ The output samples, the mixture and reference files, and the item's scoring
+ semantics.
+ """
+ return {
+ "output": out_hash,
+ "mix": hashes(r["mix_path"]),
+ "ref": hashes(r["clean_path"]) if r.get("clean_path") else None,
+ "semantics": {
+ "condition": r["condition"],
+ "score_from": int(r.get("score_from") or 0),
+ "score_policy": r.get("score_policy"),
+ "paired": bool(r.get("clean_path")),
+ },
+ }
+
+
+def reuse_key(identity):
+ return json.dumps(identity, sort_keys=True)
+
+
+NISQA_KEYS = (
+ "nisqa_mos",
+ "nisqa_noisiness",
+ "nisqa_discontinuity",
+ "nisqa_coloration",
+ "nisqa_loudness",
+)
+
+
+def suppression_energies(out, ref, mix):
+ """Returns an item's mean squares |o|^2, <o, r>, |r|^2 and |m - r|^2.
+
+ In float64, so suppression can be read at any output gain
+ (``levels.suppression_db``).
+ """
+ o, r, m = out.double(), ref.double(), mix.double()
+ return [
+ float(o.pow(2).mean()),
+ float((o * r).mean()),
+ float(r.pow(2).mean()),
+ float((m - r).pow(2).mean()),
+ ]
+
+
+def nisqa_measurements(out):
+ values = {}
+ for k, v in zip(NISQA_KEYS, common.nisqa(out)):
+ if v == v:
+ values[k] = [v]
+ return values
+
+
+def score_item(r, out, mix, spk, vad, dnsmos_ovr, want_nisqa):
+ """Returns one item's raw measurements from decoded audio of equal length.
+
+ The lists the condition reducers pool. The lost-block share is not among
+ them: it depends on the system's level calibration, so the coherence blocks
+ are kept and the share derived per view.
+ """
+ acc = collections.defaultdict(list)
+ cond = r["condition"]
+ real = cond.startswith("real") or not r.get("clean_path")
+ acc["out_in_rms_db"].append(rms_db(out) - rms_db(mix))
+ if want_nisqa:
+ for k, v in nisqa_measurements(out).items():
+ acc[k].extend(v)
+ if not real:
+ ref = common.load48(r["clean_path"])
+ n = min(len(ref), len(mix))
+ lag, sign = common.best_alignment(out, ref)
+ acc["lag"].append(lag)
+ acc["polarity"].append(sign)
+ o = sign * common.apply_lag(out, lag, n)
+ ref, mix_a = ref[:n], mix[:n]
+ sfrom = int(r.get("score_from") or 0)
+ if sfrom:
+ o, ref, mix_a = o[sfrom:], ref[sfrom:], mix_a[sfrom:]
+ # the reference is a wild recording: kept speech, speaker and bed
+ # residual, never SI-SDR
+ retention = r.get("score_policy") == "retention"
+ if not retention:
+ acc["si_sdr"].append(common.si_sdr(o, ref))
+ acc["kept"].append(common.voice_kept_db(o, ref))
+ # the voice that survived: the output's projection on the reference per
+ # 100 ms block over the reference's speech blocks (a VAD mask, so quiet
+ # speech counts)
+ r16, segs = speech_segments(vad, ref, r["clean_path"])
+ m16 = torch.zeros(len(r16), dtype=torch.bool)
+ for sg in segs:
+ m16[sg["start"]:sg["end"]] = True
+ mask = common.block_mask(m16, len(ref) // 4800)
+ coh = common.coherent_kept_db(o, ref, act=mask)
+ if len(coh):
+ acc["kept_coh_mean"].append(float(coh.mean()))
+ acc["kept_coh_p10"].append(float(torch.quantile(coh, 0.1)))
+ acc[observations.BLOCKS].append([float(v) for v in coh])
+ acc["terc"].append(common.tercile_kept_db(o, ref))
+ acc["band"].append(common.band_kept_db(o, ref))
+ acc["spk_sim"].append(spk.sim(o, ref, key_b=f"{r['id']}.ref"))
+ onb, rnb = common.nb8k(o), common.nb8k(ref)
+ coh_nb = common.coherent_kept_db(onb, rnb, act=mask)
+ if len(coh_nb):
+ acc["kept_coh_nb_mean"].append(float(coh_nb.mean()))
+ acc["kept_coh_nb_p10"].append(float(torch.quantile(coh_nb, 0.1)))
+ if not retention:
+ acc["si_sdr_nb"].append(common.si_sdr(onb, rnb))
+ else:
+ # what was removed where the wild recording holds no speech: bed and
+ # the recording's own floor alike, against the input (lower is
+ # better)
+ o16 = torchaudio.functional.resample(o, common.SR, 16000)[:len(r16)]
+ x16 = torchaudio.functional.resample(mix_a, common.SR, 16000)
+ x16 = x16[:len(r16)]
+ nv = ~m16[:min(len(o16), len(x16))]
+ if nv.any():
+ acc["nonvoiced_supp_db"].append(
+ float(10 * torch.log10(
+ (o16[:len(nv)][nv].pow(2).mean() + 1e-9) /
+ (x16[:len(nv)][nv].pow(2).mean() + 1e-9))))
+ acc["kept_nb"].append(common.voice_kept_db(onb, rnb))
+ acc["spk_sim_nb"].append(spk.sim(onb, rnb, key_b=f"{r['id']}.refnb"))
+ if cond.startswith("babble"):
+ acc["babble_energy"].append(suppression_energies(o, ref, mix_a))
+ acc["babble_energy_nb"].append(
+ suppression_energies(onb, rnb, common.nb8k(mix_a)))
+ else:
+ n = min(len(out), len(mix))
+ # the output's delay and polarity undone against the recording, as
+ # every reference metric undoes them against the reference: a late
+ # passthrough is not a changed floor
+ lag, sign = common.best_alignment(out[:n], mix[:n])
+ out = sign * common.apply_lag(out, lag, n)
+ i16, segs = (speech_segments(vad, mix, r["mix_path"])
+ if n == len(mix) else vad.segments(mix[:n]))
+ o16 = torchaudio.functional.resample(out[:n], common.SR, 16000)
+ o16 = o16[:len(i16)]
+ i16 = i16[:len(o16)]
+ if dnsmos_ovr is not None:
+ acc["dnsmos"].append(dnsmos_ovr(o16))
+ # every segment the detector marks is speech; the deletion rule reads
+ # the ones of at least half a second (a shorter segment cannot show a
+ # deletion apart from the detector's own jitter)
+ m = torch.zeros(len(i16), dtype=torch.bool)
+ for sg in segs:
+ a, b = sg["start"], min(sg["end"], len(o16))
+ m[a:b] = True
+ if b - a < 8000:
+ continue
+ d = float(10 * torch.log10((o16[a:b].pow(2).mean() + 1e-9) /
+ (i16[a:b].pow(2).mean() + 1e-9)))
+ acc["seg_drop"].append(d)
+ fr16, nf = 320, min(len(i16), len(o16))
+ mfrm = m[:nf // fr16 * fr16].reshape(-1, fr16).float().mean(1) > 0.5
+ # the non-voiced floor by 20 ms frame: frames clear of speech by a
+ # guard band (a word's tail spills past the detector's boundary) whose
+ # input is above digital silence, the output read on the same frames
+ # (reading sample by sample where the input is large read any output
+ # that is not sample-identical, a delayed passthrough included, as
+ # suppression)
+ in_frames = i16[:nf // fr16 * fr16].reshape(-1, fr16).pow(2).mean(1)
+ out_frames = o16[:nf // fr16 * fr16].reshape(-1, fr16).pow(2).mean(1)
+ any_speech = m[:nf // fr16 * fr16].reshape(-1, fr16).any(1)
+ near_speech = any_speech.clone()
+ for shift in range(1, NONVOICED_GUARD_FRAMES + 1):
+ near_speech[shift:] |= any_speech[:-shift]
+ near_speech[:-shift] |= any_speech[shift:]
+ nonvoiced = (~near_speech &
+ (in_frames > 10**(NONVOICED_FLOOR_DBFS / 10)))
+ if nonvoiced.any():
+ acc["nonvoiced_supp_db"].append(
+ float(10 * torch.log10(
+ (out_frames[nonvoiced].mean() + NONVOICED_EPS) /
+ (in_frames[nonvoiced].mean() + NONVOICED_EPS))))
+ acc["terc"].append(
+ common.tercile_kept_db(o16[:nf], i16[:nf], frame=fr16, act=mfrm))
+ if m[:nf].any():
+ acc["speech_rms_delta_db"].append(
+ float(10 * torch.log10(
+ (o16[:nf][m[:nf]].pow(2).mean() + 1e-9) /
+ (i16[:nf][m[:nf]].pow(2).mean() + 1e-9))))
+ acc["band_vs_in"].append(common.band_kept_db(out[:n], mix[:n]))
+ return acc
+
+
+def reuse_index(path, system, scorer_sha256=None):
+ """Returns an earlier pass's records indexed by content identity.
+
+ When that pass ran this scorer (or the sidecar whose digest is given);
+ otherwise an empty index with the reason. Reuse never crosses a scorer
+ change: the digest in the records' header must equal the caller's.
+ """
+ if not os.path.isfile(path):
+ return {}, "no earlier records"
+ try:
+ metadata, records = observations.read(path)
+ except (OSError, ValueError) as e:
+ return {}, f"earlier records unreadable ({e})"
+ if metadata.get("system") != system:
+ return {}, "earlier records belong to another system"
+ if metadata.get("scorer_sha256") != (scorer_sha256 or SCORER_SHA256):
+ return {}, "earlier records were made by another scorer"
+ index = {
+ reuse_key(r["identity"]): r
+ for r in records
+ if r.get("identity") and r.get("output_status") == "ok"
+ }
+ return index, f"{len(index)} reusable records"
+
+
+def assemble(name, rows, spk, vad, dnsmos_ovr, reuse=None, hashes=None):
+ """Returns a system's per-item records over ``rows``.
+
+ Reused from ``reuse`` (an earlier pass, by content identity) where the
+ output samples, the mixture, the reference and the scoring semantics are
+ unchanged, scored otherwise. The NISQA sample stays the first NISQA_N items
+ of each condition with an output, exactly as a pass without reuse would take
+ it.
+ """
+ outd = os.path.join(common.OUT_ROOT, name)
+ hashes = hashes or common.file_hashes()
+ reuse = reuse or {}
+ by_cond = collections.defaultdict(list)
+ for r in rows:
+ by_cond[r["condition"]].append(r)
+ records, counts = [], collections.Counter()
+ for _, items in sorted(by_cond.items()):
+ n_have = 0
+ for r in items:
+ record = observations.item(r)
+ records.append(record)
+ op = os.path.join(outd, r["id"])
+ if not os.path.exists(op):
+ record["output_status"] = "missing"
+ continue
+ try:
+ with open(op, "rb") as fh:
+ data = fh.read()
+ out = common.load48(io.BytesIO(data))
+ except (OSError, RuntimeError, ValueError):
+ record["output_status"] = "unreadable"
+ continue
+ # the bytes measured, which the stamp's outputs digest vouches for
+ record["output_sha256"] = hashlib.sha256(data).hexdigest()
+ mix = common.load48(r["mix_path"])
+ if len(out) != len(mix):
+ record["output_status"] = "wrong_length"
+ continue
+ if not bool(torch.isfinite(out).all()):
+ record["output_status"] = "nonfinite"
+ continue
+ n_have += 1
+ want_nisqa = NISQA_ON and n_have <= NISQA_N
+ record["identity"] = item_identity(r, sample_hash(out), hashes)
+ old = reuse.get(reuse_key(record["identity"]))
+ if old is not None:
+ measurements = {
+ k: v
+ for k, v in old["measurements"].items()
+ if want_nisqa or k not in NISQA_KEYS
+ }
+ if want_nisqa and "nisqa_mos" not in measurements:
+ measurements.update(nisqa_measurements(out))
+ acc = collections.defaultdict(list,
+ observations.revive(measurements))
+ counts["reused"] += 1
+ else:
+ acc = score_item(r, out, mix, spk, vad, dnsmos_ovr, want_nisqa)
+ counts["scored"] += 1
+ observations.capture(record, acc, {})
+ if reuse:
+ print(
+ f" reused {counts['reused']} records, scored {counts['scored']}"
+ " items",
+ flush=True,
+ )
+ return records
+
+
+def aggregate(records, rows):
+ """Returns the metrics file for ``rows`` from their per-item records.
+
+ The level calibration from the clean items, each item's lost-block share
+ from its coherence blocks under it, then the condition reducers over the
+ pooled measurements. Pure: no audio is read, so any view of the set (the
+ core, a panel) is this function over the whole-set records of its items.
+ """
+ by_id = {rec["id"]: rec for rec in records}
+ by_cond = collections.defaultdict(list)
+ for r in rows:
+ by_cond[r["condition"]].append(r)
+
+ def ok(r):
+ rec = by_id.get(r["id"])
+ return (rec if rec is not None and rec.get("output_status") == "ok" else
+ None)
+
+ lvl = [
+ ok(r)["metrics"]["out_in_rms_db"]
+ for r in by_cond.get("clean", [])
+ if ok(r)
+ ]
+ # a system's gain convention, removed before retention is read; bounded, so
+ # an output that is silent on clean speech cannot calibrate its deleted
+ # voice back into existence
+ level_cal_db = (float(
+ np.clip(np.median(lvl), -common.MAX_LEVEL_CAL_DB,
+ common.MAX_LEVEL_CAL_DB)) if lvl else 0.0)
+ scores = {}
+ n_total_have = 0
+ for cond, items in sorted(by_cond.items()):
+ # reference-free items
+ real = cond.startswith("real") or not items[0].get("clean_path")
+ acc = collections.defaultdict(list)
+ n_have = 0
+ for r in items:
+ rec = ok(r)
+ if rec is None:
+ continue
+ n_have += 1
+ for key, values in observations.revive(rec["measurements"]).items():
+ if key == observations.BLOCKS:
+ # speech blocks that are gone: a percentile cannot see one
+ # dropped syllable
+ lost = levels.lost(values[0], level_cal_db)
+ pct = 100 * float(np.mean(lost))
+ acc["kept_coh_lost_pct"].append(pct)
+ rec["metrics"]["kept_coh_lost_pct"] = pct
+ else:
+ acc[key].extend(values)
+ n_total_have += n_have
+ if not n_have:
+ continue
+ # items the system did not return: a mean over the rest is not a mean
+ # over the condition
+ d = {
+ "n": n_have,
+ "n_missing": len(items) - n_have,
+ "metric_counts": {
+ k: len(v) for k, v in acc.items()
+ },
+ }
+ for name in NISQA_KEYS:
+ if acc[name]:
+ d[name] = float(np.mean(acc[name]))
+ if not real:
+ k = np.array(acc["kept"])
+ d.update({
+ "kept_mean": float(k.mean()),
+ "kept_p10": float(np.percentile(k, 10)),
+ "spk_sim": float(np.mean(acc["spk_sim"])),
+ "kept_nb_mean": float(np.mean(acc["kept_nb"])),
+ "spk_sim_nb": float(np.mean(acc["spk_sim_nb"])),
+ "lag_median": float(np.median(acc["lag"])),
+ "lag_max_abs": float(np.max(np.abs(acc["lag"]))),
+ })
+ if acc["si_sdr"]:
+ d["si_sdr"] = float(np.mean(acc["si_sdr"]))
+ d["si_sdr_nb"] = float(np.mean(acc["si_sdr_nb"]))
+ for key in (
+ "kept_coh_mean",
+ "kept_coh_p10",
+ "kept_coh_nb_mean",
+ "kept_coh_nb_p10",
+ "kept_coh_lost_pct",
+ ):
+ if acc[key]:
+ d[key] = float(np.mean(acc[key]))
+ d["n_polarity_flipped"] = int(sum(s < 0 for s in acc["polarity"]))
+ # retention-only items (score_policy "retention")
+ if acc["nonvoiced_supp_db"]:
+ raw = float(np.mean(acc["nonvoiced_supp_db"]))
+ d["nonvoiced_supp_raw_db"] = raw
+ d["nonvoiced_supp_db"] = levels.energy_db(raw, level_cal_db)
+ d["score_policy"] = "retention"
+ t = np.array(acc["terc"], dtype=float)
+ d.update({
+ "kept_q1": float(np.nanmean(t[:, 0])),
+ "kept_q2": float(np.nanmean(t[:, 1])),
+ "kept_q3": float(np.nanmean(t[:, 2])),
+ })
+ b = np.array(acc["band"], dtype=float)
+ d["band_kept_db"] = [
+ float(np.nanmean(b[:, j])) for j in range(b.shape[1])
+ ]
+ hf = [
+ levels.hf_error_db(item, level_cal_db) for item in acc["band"]
+ ]
+ if any(np.isfinite(hf)):
+ d["hf_err_db"] = float(np.nanmean(hf))
+ for key, energies in (
+ ("babble_supp_db", acc["babble_energy"]),
+ ("babble_supp_db_nb", acc["babble_energy_nb"]),
+ ):
+ if energies:
+ d[key] = float(
+ np.mean([
+ levels.suppression_db(e, level_cal_db)
+ for e in energies
+ ]))
+ d[key.replace("_db", "_raw_db", 1)] = float(
+ np.mean(
+ [levels.suppression_db(e, 0.0) for e in energies]))
+ else:
+ drops = acc["seg_drop"]
+ raw_nv = (float(np.mean(acc["nonvoiced_supp_db"]))
+ if acc["nonvoiced_supp_db"] else float("nan"))
+ d.update({
+ "deleted_rate_pct":
+ (float(100 * np.mean(levels.deleted(drops, level_cal_db)))
+ if drops else float("nan")),
+ "n_segments":
+ len(drops),
+ "median_drop_db": (levels.energy_db(
+ np.median(drops), level_cal_db) if drops else float("nan")),
+ "nonvoiced_supp_raw_db":
+ raw_nv,
+ "nonvoiced_supp_db":
+ levels.energy_db(raw_nv, level_cal_db),
+ "speech_rms_delta_db":
+ (float(np.mean(acc["speech_rms_delta_db"]))
+ if acc["speech_rms_delta_db"] else float("nan")),
+ })
+ t = np.array(acc["terc"], dtype=float)
+ d.update({
+ "kept_q1": float(np.nanmean(t[:, 0])),
+ "kept_q2": float(np.nanmean(t[:, 1])),
+ "kept_q3": float(np.nanmean(t[:, 2])),
+ })
+ b = np.array(acc["band_vs_in"], dtype=float)
+ d["band_vs_in_db"] = [
+ float(np.nanmean(b[:, j])) for j in range(b.shape[1])
+ ]
+ if acc["dnsmos"]:
+ d["dnsmos_ovr"] = float(np.mean(acc["dnsmos"]))
+ d["out_in_rms_db"] = float(np.mean(acc["out_in_rms_db"]))
+ d["level_err_db"] = float(
+ np.mean([levels.level_error_db(v) for v in acc["out_in_rms_db"]]))
+ scores[cond] = d
+ scores["_level_cal_db"] = level_cal_db
+ scores["_n_missing"] = len(rows) - n_total_have
+ scores["_set_id"] = common.set_id()
+ scores["_subset"] = common.SUBSET
+ scores["_sealed"] = common.is_sealed(rows)
+ scores["_bands_hz"] = [list(b) for b in common.BANDS_HZ]
+ scores.update(anchors.stamp())
+ return scores
+
+
+def dnsmos_scorer():
+ """Returns DNSMOS's overall score as a function of 16 kHz audio.
+
+ None when DNSMOS cannot load.
+ """
+ try:
+ # pylint: disable-next=import-outside-toplevel
+ from torchmetrics.functional.audio import dnsmos
+ # a diagnostic only: any failure to load it leaves the column empty, never
+ # the scores
+ except Exception as e: # pylint: disable=broad-exception-caught
+ print(f" [warn] DNSMOS unavailable: {e}", flush=True)
+ return None
+
+ def overall(w16):
+ s = dnsmos.deep_noise_suppression_mean_opinion_score(w16,
+ fs=16000,
+ personalized=False)
+ return float(s[..., 3].mean())
+
+ return overall
+
+
+def score_system(name, rows, spk, vad, dnsmos_ovr, records=None, reuse=None):
+ """Scores a system over ``rows``.
+
+ Assembles its per-item records, then aggregates them.
+ """
+ if name == "REF":
+ rows = [r for r in rows if r.get("clean_path")]
+ assembled = assemble(name, rows, spk, vad, dnsmos_ovr, reuse=reuse)
+ scores = aggregate(assembled, rows)
+ if records is not None:
+ records.extend(assembled)
+ return scores
+
+
+def accept_render(name, records, stamp):
+ """Accepts scores only of the outputs their render's stamp vouches for.
+
+ The bytes each record was measured on (``output_sha256``) must add up to the
+ stamp's outputs digest (``stamprender.digest_of``): an output changed or
+ gone since the stamp means these are scores of another render. A render the
+ set links in rather than stamps (its mixtures, its references) carries no
+ digest and is not checked.
+
+ Raises:
+ SystemExit: The outputs read are not the stamped render.
+ """
+ stamped = (stamp or {}).get("outputs_sha256")
+ if not stamped:
+ return
+ if stamp.get("n_files") not in (None, len(records)):
+ raise SystemExit(
+ f"{name}: {len(records)} of the {stamp['n_files']} outputs its"
+ " stamp vouches for were read: a view of a render is derived from"
+ " its whole-set records (--aggregate-only), never scored again")
+ hashes = {rec["id"]: rec.get("output_sha256") for rec in records}
+ if not all(hashes.values()) or stamprender.digest_of(hashes) != stamped:
+ raise SystemExit(
+ f"{name}: the outputs read are not the render its stamp vouches for"
+ " (changed or gone since it was stamped): render it again or stamp"
+ " it again")
+
+
+def view_source(path, system, scorer_sha256=None):
+ """Returns why whole-set records cannot stand for a view, or ''.
+
+ The records under ``path`` must be this set's, this scorer's (or the
+ sidecar's whose digest is given), and the whole set's.
+ """
+ if not os.path.isfile(path):
+ return "no whole-set records"
+ try:
+ metadata, _ = observations.read(path)
+ except (OSError, ValueError) as e:
+ return f"unreadable ({e})"
+ if metadata.get("system") != system:
+ return "records belong to another system"
+ if metadata.get("set_id") != common.set_id():
+ return (f"records of set {str(metadata.get('set_id'))[:12]}, current"
+ f" {str(common.set_id())[:12]}")
+ if metadata.get("subset", "all") != "all":
+ return (
+ f"records of subset {metadata.get('subset')!r}, not the whole set")
+ if metadata.get("scorer_sha256") != (scorer_sha256 or SCORER_SHA256):
+ return "records were made by another scorer: re-score the whole set"
+ return ""
+
+
+def view_records(path, system, ids, scorer_sha256=None):
+ """Returns the whole-set records under ``path`` that a view keeps.
+
+ A tuple (problem, metadata, records): ``problem`` says why the records
+ cannot stand for the view (``view_source``) and is '' when they can. A view
+ item the records lack ends the run: a view is never scored on its own.
+ """
+ problem = view_source(path, system, scorer_sha256)
+ if problem:
+ return problem, None, None
+ metadata, whole = observations.read(path)
+ records = [rec for rec in whole if rec["id"] in ids]
+ absent = sorted(ids - {rec["id"] for rec in records})
+ if absent:
+ raise SystemExit(
+ f"{path} holds no record for {len(absent)} items of subset"
+ f" {common.SUBSET!r} (first: {absent[0]}): score the whole set"
+ " first")
+ return "", metadata, records
+
+
+def render_problem(name):
+ """Why a system's outputs may not be scored, or None.
+
+ Renders belong to one build of the set and carry its id in
+ ``<name>.meta.json`` (written by runsystem.py / runfield.sh). Outputs
+ without that record, or from another build, would be scored against
+ references they were never made for.
+ """
+ meta_path = os.path.join(common.RESULTS, f"{name}.meta.json")
+ if not os.path.exists(meta_path):
+ return (
+ "no identity (meta.json missing): render it with runsystem.py or"
+ " runfield.sh")
+ with open(meta_path, encoding="utf-8") as fh:
+ recorded = json.load(fh).get("set_id")
+ current = common.set_id()
+ if not recorded:
+ return "meta carries no set_id: re-render it with the current harness"
+ if current and recorded != current:
+ return (
+ f"rendered on set {recorded[:12]}, current set is {current[:12]}:"
+ " re-render it")
+ return None
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--systems", default="")
+ ap.add_argument("--shard", default="", help="i/k over the system list")
+ ap.add_argument("--force", action="store_true")
+ ap.add_argument("--conds", default="", help="comma substrings; debug only")
+ ap.add_argument("--limit",
+ type=int,
+ default=0,
+ help="items/cond; debug only")
+ ap.add_argument("--suffix", default="", help="results filename suffix")
+ ap.add_argument(
+ "--anchor-reference",
+ action="store_true",
+ help=(
+ "REF only: score complete conditions required by anchor definitions"
+ ),
+ )
+ ap.add_argument(
+ "--reuse-from",
+ default="",
+ metavar="DIR",
+ help=(
+ "results of an earlier pass of this scorer: an item whose output"
+ " samples, mixture, reference and semantics are unchanged keeps its"
+ " record; only the rest is scored"),
+ )
+ ap.add_argument(
+ "--aggregate-only",
+ default="",
+ metavar="DIR",
+ help=("derive this subset's files (BENCH_SUBSET) from the whole-set"
+ " per-item records under DIR; no audio is read"),
+ )
+ a = ap.parse_args()
+ if a.aggregate_only and (a.conds or a.limit or a.reuse_from):
+ ap.error(
+ "--aggregate-only takes no debug filtering and no --reuse-from")
+
+ rows = common.manifest()
+ common.guard_private_results(rows)
+ if a.anchor_reference:
+ if a.systems != "REF" or a.conds or a.limit or a.suffix:
+ ap.error("--anchor-reference requires --systems REF and no debug"
+ " filtering")
+ rows = [
+ r for r in rows if r["condition"] in anchors.reference_conditions()
+ ]
+ if a.conds:
+ pats = a.conds.split(",")
+ rows = [r for r in rows if any(p in r["condition"] for p in pats)]
+ if a.limit:
+ seen = collections.Counter()
+ keep = []
+ for r in rows:
+ if seen[r["condition"]] < a.limit:
+ keep.append(r)
+ seen[r["condition"]] += 1
+ rows = keep
+ if a.systems:
+ systems = a.systems.split(",")
+ else:
+ systems = sorted(
+ os.path.basename(d)
+ for d in glob.glob(common.OUT_ROOT + "/*")
+ if os.path.isdir(d))
+ # a filtered pass (--conds, --limit) scores what it names and nothing
+ # else: INPUT's whole-set files are never replaced by a selection
+ if ("INPUT" not in systems and systems != ["REF"] and
+ not (a.conds or a.limit)):
+ systems = ["INPUT"] + systems
+ if (a.conds or a.limit) and not a.suffix:
+ print(
+ "filtered pass: the whole-set files of the named systems are "
+ "replaced by this selection (the board refuses them); pass "
+ "--suffix to keep them",
+ flush=True)
+ # every output directory is a candidate; only identified ones are scored,
+ # and a filtered pass scores the discovered INPUT no more than a named one
+ if not a.systems:
+ systems = [
+ s for s in systems if (s == "INPUT" and not (a.conds or a.limit)) or
+ (s != "INPUT" and not render_problem(s))
+ ]
+ if a.shard:
+ i, k = (int(x) for x in a.shard.split("/"))
+ systems = systems[i::k]
+ print(f"scoring {len(systems)} systems: {systems}", flush=True)
+
+ os.makedirs(common.OUT_ROOT + "/INPUT", exist_ok=True)
+ if not glob.glob(common.OUT_ROOT + "/INPUT/*.wav"):
+ for r in rows:
+ lp = os.path.join(common.OUT_ROOT, "INPUT", r["id"])
+ if not os.path.exists(lp):
+ os.symlink(os.path.abspath(r["mix_path"]), lp)
+
+ spk = vad = dnsmos_ovr = None
+ if not a.aggregate_only:
+ # reference embeddings are the same for every system: cache them next to
+ # the set
+ set_tag = (common.set_id() or "noset")[:16]
+ spk_cache = os.path.join(common.EVAL, ".cache", "spkemb", set_tag)
+ spk = common.SpeakerEmbedder(cache_dir=spk_cache)
+ vad = common.Vad()
+ dnsmos_ovr = dnsmos_scorer()
+
+ os.makedirs(common.RESULTS, exist_ok=True)
+ for s in systems:
+ dst = os.path.join(common.RESULTS, f"{s}{a.suffix}.metrics.json")
+ own = os.path.join(common.RESULTS, f"{s}{a.suffix}.items.jsonl")
+ if a.aggregate_only:
+ if s == "REF" and not a.anchor_reference:
+ print(
+ "skip REF: derived with --systems REF --anchor-reference",
+ flush=True,
+ )
+ continue
+ src = os.path.join(a.aggregate_only, f"{s}{a.suffix}.items.jsonl")
+ view = rows
+ if s == "REF":
+ view = [r for r in rows if r.get("clean_path")]
+ ids = {r["id"] for r in view}
+ problem, metadata, records = view_records(src, s, ids)
+ if problem:
+ print(f"skip {s}: {problem}", flush=True)
+ continue
+ print(f"\n=== {s} ({len(records)} whole-set records)", flush=True)
+ scores = aggregate(records, view)
+ identity = metadata.get("render_identity")
+ else:
+ if not os.path.isdir(os.path.join(common.OUT_ROOT, s)):
+ print(f"skip {s} (no output dir)", flush=True)
+ continue
+ problem = render_problem(s)
+ if problem:
+ print(f"skip {s}: {problem}", flush=True)
+ continue
+ n_out = len(glob.glob(os.path.join(common.OUT_ROOT, s, "*.wav")))
+ print(f"\n=== {s} ({n_out} wavs)", flush=True)
+ # a system is never skipped as scored: its existing records (or an
+ # earlier pass named by --reuse-from) are reused item by item where
+ # the content identity holds, so a changed output or another scorer
+ # can never leave a stale score behind
+ reuse, why = {}, "--force: every item scored afresh"
+ if not a.force:
+ if a.reuse_from:
+ reuse, why = reuse_index(
+ os.path.join(a.reuse_from,
+ f"{s}{a.suffix}.items.jsonl"),
+ s,
+ )
+ why = f"reuse from {a.reuse_from}: {why}"
+ elif os.path.isfile(own):
+ reuse, why = reuse_index(own, s)
+ why = (
+ f"existing records: {why}; every item re-validated by"
+ " content")
+ else:
+ why = "no earlier records"
+ print(f" {why}", flush=True)
+ records = []
+ scores = score_system(s,
+ rows,
+ spk,
+ vad,
+ dnsmos_ovr,
+ records=records,
+ reuse=reuse)
+ meta_path = os.path.join(common.RESULTS, f"{s}.meta.json")
+ with open(meta_path, encoding="utf-8") as fh:
+ identity = json.load(fh)
+ if not (a.conds or a.limit):
+ accept_render(s, records, identity)
+ if a.anchor_reference:
+ scores["_scope"] = "anchor_reference"
+ # one implementation per board (leaderboard.py)
+ scores["_scorer_sha256"] = SCORER_SHA256
+ # the audio these scores read: the board refuses them once the stamp
+ # vouches for other outputs
+ scores["_outputs_sha256"] = (identity or {}).get("outputs_sha256")
+ # a filtered look at part of the set, never a board row: too few of the
+ # render's outputs to vouch for it
+ if a.conds or a.limit:
+ scores["_selection"] = {"conds": a.conds, "limit": a.limit}
+ scores["_outputs_sha256"] = None
+ observations.write(
+ os.path.join(common.RESULTS, f"{s}{a.suffix}.items.jsonl"),
+ records,
+ {
+ "system": s,
+ "set_id": scores["_set_id"],
+ "subset": common.SUBSET,
+ "anchors_version": scores["_anchors_version"],
+ "anchors_sha256": scores["_anchors_sha256"],
+ "level_cal_db": scores["_level_cal_db"],
+ "render_identity": identity,
+ "scorer_sha256": SCORER_SHA256,
+ "n_expected": len(records),
+ "sealed": common.is_sealed(rows),
+ },
+ )
+ # whole or absent: parallel passes re-validate INPUT
+ tmp = f"{dst}.{os.getpid()}.tmp"
+ with open(tmp, "w", encoding="utf-8") as fh:
+ json.dump(scores, fh, indent=1)
+ os.replace(tmp, dst)
+ n_conditions = len([k for k in scores if not k.startswith("_")])
+ print(
+ f" level_cal {scores['_level_cal_db']:+.2f} dB |"
+ f" {n_conditions} conditions -> {dst}",
+ flush=True,
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/bench/scripts/scorecontent.py b/bench/scripts/scorecontent.py
new file mode 100644
index 0000000..cc96d8e
--- /dev/null
+++ b/bench/scripts/scorecontent.py
@@ -0,0 +1,703 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Content preservation: which words survive, by kind, as a recogniser reads.
+
+ python bench/scripts/scorecontent.py --systems INPUT,voice_isolator_v0[,...]
+ [--asr large-v3] [--conds clean,babble@+4,...]
+ [--markdown-out staging/content_table.md]
+
+The composite's retention metric reads 100 ms blocks through a percentile: it
+cannot see one dropped consonant, syllable or short word (CONTROLS.md). This
+sidecar is an ASR-based content diagnostic. Every system's output is transcribed
+by one recogniser, the transcript is aligned word by word to the item's verified
+transcript, and each reference word is counted as kept, substituted or deleted,
+with insertions counted on the hypothesis side. Reference words are classed as
+numbers, short words (three letters or fewer), consonant-final words and the
+rest, because numbers, short function words and word-final consonants are what a
+front end loses first.
+
+The panel is every English item of the named conditions with a verified
+transcript (the corpus text confirmed against the audio by a language model, or
+the model's own transcript the maintainer accepted by ear), so the reference is
+never a recogniser's unchecked guess. Rates are pooled per class over the panel,
+as errors per hundred reference words of that class, with a bootstrap interval
+that resamples the recordings and beds behind the items rather than the items
+(the panel repeats a recording at several levels, so items are not independent
+draws), and are read next to the unprocessed input's: the change column is the
+difference of two pooled rates under the same resampling. A front end is judged
+by what it changes, so the same items must have been scored for every system
+compared: a system that misses items is marked incomplete and never compared on
+the intersection.
+
+``--controls`` renders the metric controls of controls.py (the reference
+untouched, with 20 to 320 ms of speech removed, re-synthesised, with its top
+octave replaced by noise) from the panel items' own references as systems named
+``ctl_<control>`` and scores them too: the table then says what the check itself
+can and cannot see, next to the systems.
+
+Writes ``<system>.content.json`` beside the other sidecars, per-item counts
+included so systems can be paired, and with ``--markdown-out`` one table over
+the systems given.
+"""
+
+import argparse
+import json
+import os
+
+import numpy as np
+import soundfile as sf
+
+import anchors
+import common
+import compare
+import controls
+import observations
+import scoreasr
+import scorebench
+
+SCORER_SHA256 = observations.implementation(__file__, scoreasr.__file__,
+ common.__file__,
+ observations.__file__,
+ scorebench.__file__)
+
+VERIFIED = ("corpus-verified", "gemini-accepted", "human-verified")
+CLASSES = ("number", "short", "consonant-final", "other")
+CONSONANTS = frozenset("bcdfghjklmnpqrstvwxz")
+N_BOOT = 1000
+
+
+def word_class(token: str) -> str:
+ """The class of a normalised reference token."""
+ if any(ch.isdigit() for ch in token):
+ return "number"
+ if len(token) <= 3:
+ return "short"
+ if token[-1] in CONSONANTS:
+ return "consonant-final"
+ return "other"
+
+
+def align(hyp: list, ref: list) -> tuple:
+ """Levenshtein alignment of ``hyp`` to ``ref``.
+
+ Returns:
+ A list with one entry per reference token, ``kept``, ``sub`` or
+ ``del``, and the number of hypothesis tokens inserted. Ties go to a
+ match or substitution first, then a deletion.
+ """
+ n, m = len(ref), len(hyp)
+ d = [[0] * (m + 1) for _ in range(n + 1)]
+ for i in range(1, n + 1):
+ d[i][0] = i
+ for j in range(1, m + 1):
+ d[0][j] = j
+ for i in range(1, n + 1):
+ for j in range(1, m + 1):
+ d[i][j] = min(
+ d[i - 1][j] + 1,
+ d[i][j - 1] + 1,
+ d[i - 1][j - 1] + (ref[i - 1] != hyp[j - 1]),
+ )
+ ops, ins, i, j = [None] * n, 0, n, m
+ while i > 0 or j > 0:
+ if (i > 0 and j > 0 and
+ d[i][j] == d[i - 1][j - 1] + (ref[i - 1] != hyp[j - 1])):
+ ops[i - 1] = "kept" if ref[i - 1] == hyp[j - 1] else "sub"
+ i, j = i - 1, j - 1
+ elif i > 0 and d[i][j] == d[i - 1][j] + 1:
+ ops[i - 1] = "del"
+ i -= 1
+ else:
+ ins += 1
+ j -= 1
+ return ops, ins
+
+
+def panel(rows: list, golden: dict, conds: tuple, language: str = "en") -> list:
+ """Returns the items scored.
+
+ Paired, in ``conds``, in ``language``, with a verified transcript.
+ """
+ return [
+ r for r in rows if r["condition"] in conds and
+ r.get("language") == language and r.get("clean_path") and
+ (golden.get(r["id"]) or {}).get("tier") in VERIFIED
+ ]
+
+
+def count(ops: list, ref: list) -> dict:
+ """Per-class counts of reference tokens kept, substituted and deleted."""
+ out = {c: {"n": 0, "kept": 0, "sub": 0, "del": 0} for c in CLASSES}
+ for op, token in zip(ops, ref):
+ cell = out[word_class(token)]
+ cell["n"] += 1
+ cell[op] += 1
+ return out
+
+
+def groups_of(records: dict) -> list:
+ """Returns the two cluster vectors of the items, in id order.
+
+ One for the foreground recording, one for the bed.
+ """
+ ids = sorted(records)
+ return [
+ [records[i].get("speech_group") for i in ids],
+ [records[i].get("bed_group") for i in ids],
+ ]
+
+
+def _interval(numer: list,
+ denom: list,
+ groups: list,
+ n_boot: int = N_BOOT,
+ seed: int = 0) -> list:
+ """Returns the 95 % interval of a pooled rate under clustered resampling.
+
+ The rate is 100 * sum(numer) / sum(denom), resampled by source
+ (compare.weights); [nan, nan] when the items span too few sources for one.
+ """
+ k, n = np.array(numer, dtype=float), np.array(denom, dtype=float)
+ if len(k) < 2 or n.sum() == 0:
+ return [float("nan"), float("nan")]
+ try:
+ d = compare.interval(
+ lambda w: 100.0 * (w @ k) / (w @ n) if (w @ n) else float("nan"),
+ groups,
+ n_boot,
+ seed,
+ )
+ except ValueError:
+ return [float("nan"), float("nan")]
+ return d["ci95"]
+
+
+def pooled(records: dict) -> dict:
+ """Returns per-class and overall error rates per hundred reference words.
+
+ The deletion and substitution rates carry source-clustered bootstrap
+ intervals.
+ """
+ ids = sorted(records)
+ items = [records[i] for i in ids]
+ groups = groups_of(records)
+ out = {}
+ for cls in CLASSES + ("all",):
+ take = ((lambda r, cls=cls: r["classes"][cls]) if cls != "all" else
+ (lambda r: {
+ k: sum(r["classes"][c][k] for c in CLASSES)
+ for k in ("n", "kept", "sub", "del")
+ }))
+ n = sum(take(r)["n"] for r in items)
+ cell = {"n": n}
+ for key in ("del", "sub"):
+ total = sum(take(r)[key] for r in items)
+ cell[f"{key}_pct"] = 100.0 * total / n if n else float("nan")
+ cell[f"{key}_ci95"] = _interval(
+ [take(r)[key] for r in items],
+ [take(r)["n"] for r in items],
+ groups,
+ )
+ out[cls] = cell
+ n_all = out["all"]["n"]
+ out["all"]["n_items"] = len(items)
+ out["all"]["n_recordings"] = len({g for g in groups[0] if g is not None})
+ out["all"]["n_beds"] = len({g for g in groups[1] if g is not None})
+ ins = sum(r["ins"] for r in items)
+ out["all"]["ins_pct"] = 100.0 * ins / n_all if n_all else float("nan")
+ out["all"]["ins_ci95"] = _interval(
+ [r["ins"] for r in items],
+ [sum(r["classes"][c]["n"] for c in CLASSES) for r in items],
+ groups,
+ )
+ return out
+
+
+def label_groups(records: dict, rows: list) -> None:
+ """Returns opaque group labels per item, numbered within this panel.
+
+ ``s<k>`` for the foreground recording, ``b<k>`` for the bed: the clustered
+ bootstrap needs equal labels for equal sources and nothing else, and a
+ number cannot be run back to a corpus the way a digest could.
+ """
+ by_id = {r["id"]: r for r in rows}
+ seen = {"speech_source": {}, "bed_source": {}}
+ for uid in sorted(records):
+ rec = observations.item(by_id[uid])
+ for key, prefix, field in (
+ ("speech_source", "s", "speech_group"),
+ ("bed_source", "b", "bed_group"),
+ ):
+ value = rec.get(key)
+ records[uid][field] = (None
+ if value is None else seen[key].setdefault(
+ value, f"{prefix}{len(seen[key])}"))
+
+
+def score_system(name: str, rows: list, asr, cache, norm, golden: dict) -> dict:
+ """Returns one system's per-item content counts over the panel.
+
+ The pooled rates come with them.
+ """
+ outd = os.path.join(common.OUT_ROOT, name)
+ records, missing = {}, []
+ for r in rows:
+ path = r["mix_path"] if name == "INPUT" else os.path.join(outd, r["id"])
+ if not os.path.exists(path):
+ missing.append(r["id"])
+ continue
+ lang = scoreasr.spoken_language(r, golden)
+ ref = norm.tokens(golden[r["id"]]["text"], lang)
+ hyp = norm.tokens(cache.get(asr, path, lang), lang)
+ ops, ins = align(hyp, ref)
+ records[r["id"]] = {
+ "condition": r["condition"],
+ "classes": count(ops, ref),
+ "ins": ins,
+ }
+ label_groups(records, rows)
+ return {
+ "items": records,
+ "missing": missing,
+ "rates": pooled(records) if records else {},
+ "asr_identity": getattr(asr, "identity", None),
+ }
+
+
+def asr_identity(doc: dict):
+ """The recogniser identity of a scored result or a loaded sidecar."""
+ return doc.get("asr_identity") or doc.get("_asr_identity")
+
+
+def paired_delta(left: dict,
+ right: dict,
+ key: str = "del",
+ cls: str = "all") -> dict:
+ """Returns two systems' difference in pooled error rate, with its interval.
+
+ Left minus right, in points, over the panel, with a source-clustered
+ bootstrap interval: the same quantity the table's rate columns show. Only on
+ identical complete cohorts read by the same recogniser against the same
+ reference tokens: a system that misses items is reported as incomplete,
+ never compared on the intersection, and a mismatch of recogniser or
+ reference is reported as incompatible.
+ """
+ nan = float("nan")
+ ids = sorted(left["items"])
+ if (set(left["items"]) != set(right["items"]) or left.get("missing") or
+ right.get("missing")):
+ differ = set(left.get("missing", [])) | set(right.get("missing", []))
+ differ |= set(left["items"]) ^ set(right["items"])
+ return {
+ "delta": nan,
+ "ci95": [nan, nan],
+ "n_items": len(set(left["items"]) & set(right["items"])),
+ "incomplete": True,
+ "missing": sorted(differ),
+ }
+
+ # the same recogniser read both sides, and both sides were aligned to the
+ # same reference tokens: otherwise a difference of pooled rates compares
+ # nothing
+ li, ri = asr_identity(left), asr_identity(right)
+ if li is not None and ri is not None and li != ri:
+ return {
+ "delta": nan,
+ "ci95": [nan, nan],
+ "n_items": len(ids),
+ "incomplete": False,
+ "incompatible": "recognisers differ",
+ }
+ for i in ids:
+ if any(left["items"][i]["classes"][c]["n"] != right["items"][i]
+ ["classes"][c]["n"] for c in CLASSES):
+ return {
+ "delta": nan,
+ "ci95": [nan, nan],
+ "n_items": len(ids),
+ "incomplete": False,
+ "incompatible": "reference tokens differ",
+ }
+
+ def counts(rec):
+ cells = ([rec["classes"][cls]]
+ if cls != "all" else list(rec["classes"].values()))
+ return sum(c[key] for c in cells), sum(c["n"] for c in cells)
+
+ kl = np.array([counts(left["items"][i])[0] for i in ids], dtype=float)
+ kr = np.array([counts(right["items"][i])[0] for i in ids], dtype=float)
+ n = np.array([counts(left["items"][i])[1] for i in ids], dtype=float)
+ if len(ids) < 2 or n.sum() == 0:
+ return {
+ "delta": nan,
+ "ci95": [nan, nan],
+ "n_items": len(ids),
+ "incomplete": False,
+ }
+ delta = 100.0 * (kl.sum() - kr.sum()) / n.sum()
+ try:
+ d = compare.interval(
+ lambda w: 100.0 * (w @ kl - w @ kr) / (w @ n) if (w @ n) else nan,
+ groups_of(left["items"]),
+ N_BOOT,
+ 0,
+ )
+ ci = d["ci95"]
+ except ValueError:
+ ci = [nan, nan]
+ return {
+ "delta": float(delta),
+ "ci95": ci,
+ "n_items": len(ids),
+ "incomplete": False,
+ }
+
+
+def write_sidecar(
+ path: str,
+ name: str,
+ tag: str,
+ result: dict,
+ identity: dict,
+ rows: list,
+ conds: tuple,
+) -> None:
+ doc = {
+ "_system": name,
+ "_set_id": common.set_id(),
+ "_subset": common.SUBSET,
+ "_asr": tag,
+ "_asr_identity": identity,
+ "_panel": {
+ "language": "en",
+ "tiers": list(VERIFIED),
+ "conditions": list(conds),
+ "n_items": len(rows),
+ },
+ "_scorer_sha256": SCORER_SHA256,
+ "_selection": {
+ "conds": ",".join(conds),
+ "limit": 0
+ },
+ "_outputs": scoreasr.output_hashes(name, rows),
+ "rates": result["rates"],
+ "missing": result["missing"],
+ "items": result["items"],
+ }
+ tmp = f"{path}.{os.getpid()}.tmp"
+ with open(tmp, "w", encoding="utf-8") as fh:
+ json.dump(doc, fh, indent=1)
+ os.replace(tmp, path)
+
+
+# a metric control rendered onto the panel, read against ctl_reference
+CONTROL_PREFIX = "ctl_"
+# beside each control's folder: item -> digest of (ref, mix, code)
+LEDGER = ".provenance.json"
+CONTROLS = (
+ "reference",
+ "delete20ms",
+ "delete40ms",
+ "delete80ms",
+ "delete160ms",
+ "delete320ms",
+ "resynth",
+ "hfinvented",
+)
+
+
+def render_controls(rows: list, names: tuple = CONTROLS) -> list:
+ """Renders the named controls into ``BENCH_OUT`` as systems ``ctl_<name>``.
+
+ Each is built by controls.py from the panel's references and stamped with
+ the set id and the controls' implementation digest; an existing file is
+ reused only while its reference, mixture and the control code are unchanged.
+ Returns the system names.
+ """
+ controls_sha = observations.implementation(controls.__file__)
+ hashes = common.file_hashes()
+ systems = []
+ for name in names:
+ system = CONTROL_PREFIX + name
+ outd = os.path.join(common.OUT_ROOT, system)
+ os.makedirs(outd, exist_ok=True)
+ # a control's output is a function of the reference, the mixture and the
+ # control code; a file already there is reused only while the ledger
+ # says all three are what they were
+ ledger_path = os.path.join(common.OUT_ROOT, system + LEDGER)
+ ledger = {}
+ if os.path.exists(ledger_path):
+ with open(ledger_path, encoding="utf-8") as fh:
+ ledger = json.load(fh)
+ for r in rows:
+ out = os.path.join(outd, r["id"])
+ stamp = anchors.digest([
+ hashes(r["clean_path"]),
+ hashes(r["mix_path"]),
+ name,
+ controls_sha,
+ ])
+ if os.path.exists(out) and ledger.get(r["id"]) == stamp:
+ continue
+ ref = common.load48(r["clean_path"])
+ mix = common.load48(r["mix_path"])
+ n = min(len(ref), len(mix))
+ y = controls.CONTROLS[name][1](ref[:n], mix[:n], r["id"])[:n]
+ sf.write(out,
+ y.numpy().astype("float32"),
+ common.SR,
+ subtype="FLOAT")
+ ledger[r["id"]] = stamp
+ with open(ledger_path, "w", encoding="utf-8") as fh:
+ json.dump(ledger, fh, indent=0)
+ with open(os.path.join(common.RESULTS, f"{system}.meta.json"),
+ "w",
+ encoding="utf-8") as fh:
+ json.dump(
+ {
+ "name":
+ system,
+ "display":
+ f"control: {controls.CONTROLS[name][0]}",
+ "set_id":
+ common.set_id(),
+ "n_files":
+ len(rows),
+ "controls_sha256":
+ controls_sha,
+ "notes": ("a metric control rendered onto the content panel"
+ " (scorecontent.py --controls)"),
+ },
+ fh,
+ indent=1,
+ )
+ systems.append(system)
+ return systems
+
+
+def _table(docs: dict, order: list, baseline: str, against: str, label) -> list:
+
+ def fmt(v):
+ return "-" if v != v else f"{v:.1f}"
+
+ # the classes' sizes travel with their columns: a class of a few dozen
+ # tokens is read as such
+ sizes = docs[order[0]]["rates"] if order else {}
+
+ def size(c):
+ return f" ({sizes[c]['n']})" if c in sizes and sizes[c].get("n") else ""
+
+ lines = [
+ (f"| system | items | deleted: all{size('all')} |"
+ f" numbers{size('number')} | short words{size('short')} |"
+ f" consonant-final{size('consonant-final')} | substituted |"
+ f" inserted | deletions vs {against} |"),
+ "|---|---:|---:|---:|---:|---:|---:|---:|---:|",
+ ]
+ expected = max(
+ len(docs[n]["items"]) + len(docs[n].get("missing", [])) for n in order)
+ for n in order:
+ r = docs[n]["rates"]
+ cells = [fmt(r["all"]["del_pct"])
+ ] + [fmt(r[c]["del_pct"]) for c in CLASSES[:3]]
+ cells += [fmt(r["all"]["sub_pct"]), fmt(r["all"]["ins_pct"])]
+ items = str(len(docs[n]["items"]))
+ if docs[n].get("missing") or len(docs[n]["items"]) < expected:
+ items = f"{len(docs[n]['items'])} of {expected} (incomplete)"
+ delta = "-"
+ if n != baseline and baseline in docs:
+ d = paired_delta(docs[n], docs[baseline])
+ if d.get("incomplete"):
+ delta = f"incomplete ({len(d['missing'])} items differ)"
+ elif d.get("incompatible"):
+ delta = f"incompatible ({d['incompatible']})"
+ elif d["delta"] == d["delta"]:
+ delta = (f"{d['delta']:+.1f} [{d['ci95'][0]:+.1f},"
+ f" {d['ci95'][1]:+.1f}]")
+ lines.append(f"| {label(n)} | {items} | " + " | ".join(cells) +
+ f" | {delta} |")
+ return lines
+
+
+def markdown(docs: dict, label=None) -> str:
+ """Returns the content tables over the systems given.
+
+ Deletions by class, substitutions, insertions, and the paired change in
+ deletions against the unprocessed input. Controls (``ctl_*``) get their own
+ table, read against the untouched reference they were made from.
+ """
+ label = label or (lambda n: n)
+ systems = [n for n in docs if not n.startswith(CONTROL_PREFIX)]
+ control_names = [n for n in docs if n.startswith(CONTROL_PREFIX)]
+ lines = [
+ ("Words lost per hundred reference words of each kind, from one"
+ " recogniser's reading of every output against the item's verified"
+ " transcript; substitutions and insertions per hundred reference"
+ " words overall; the last column is the difference of the pooled"
+ " deletion rates against the unprocessed input (points, 95 %"
+ " interval resampling the recordings and beds behind the items, not"
+ " the items). Lower is better. The number in each class header is"
+ " how many reference words the class holds; a system that misses"
+ " items is marked incomplete and not compared."),
+ "",
+ ]
+ order = (["INPUT"] if "INPUT" in systems else []) + sorted(
+ n for n in systems if n != "INPUT")
+ rates = docs[order[0]]["rates"].get("all", {}) if order else {}
+ if rates.get("n_recordings"):
+ lines[0] += (
+ f" The intervals rest on the {rates['n_recordings']} recordings and"
+ f" {rates['n_beds']} beds behind the {rates['n_items']} items.")
+ lines += _table(docs, order, "INPUT", "input", label)
+ if control_names:
+ ref = CONTROL_PREFIX + "reference"
+ order = ([ref] if ref in control_names else []) + sorted(
+ n for n in control_names if n != ref)
+ lines += [
+ "",
+ ("What the check itself can see: the metric controls rendered"
+ " onto the same panel, read against the untouched reference"
+ " they were made from."),
+ "",
+ ]
+ lines += _table(docs, order, ref, "reference", label)
+ return "\n".join(lines)
+
+
+def missing_render(name: str) -> str:
+ """Why a system has nothing to score here, or an empty string.
+
+ The identity check (``scorebench.render_problem``) reads only
+ ``<name>.meta.json``, which a results directory seeded from another run
+ also holds; the outputs themselves live under ``BENCH_OUT``. Without them
+ the scorer would write an empty sidecar over the seeded one.
+ """
+ if name == "INPUT" or os.path.isdir(os.path.join(common.OUT_ROOT, name)):
+ return ""
+ return f"no outputs under {common.OUT_ROOT}"
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--systems",
+ required=True,
+ help="comma-separated system names")
+ ap.add_argument(
+ "--asr",
+ default="large-v3",
+ help="one recogniser, as scoreasr.py names it",
+ )
+ ap.add_argument(
+ "--conds",
+ default=",".join(
+ c for c in scoreasr.DEFAULT_CONDS if not c.startswith("wild")),
+ )
+ ap.add_argument("--device", default=None)
+ ap.add_argument("--beam-size", type=int, default=5)
+ ap.add_argument("--markdown-out", default="")
+ ap.add_argument(
+ "--controls",
+ action="store_true",
+ help="also render and score the metric controls on the panel",
+ )
+ ap.add_argument(
+ "--table-only",
+ action="store_true",
+ help="render the table from existing sidecars; score nothing",
+ )
+ a = ap.parse_args()
+ if a.table_only:
+ docs = {}
+ for name in [s for s in a.systems.split(",") if s]:
+ path = os.path.join(common.RESULTS, f"{name}.content.json")
+ if os.path.exists(path):
+ with open(path, encoding="utf-8") as fh:
+ doc = json.load(fh)
+ problem = scoreasr.stale_sidecar(doc, common.RESULTS) or (
+ "was scored by another implementation"
+ if doc.get("_scorer_sha256") != SCORER_SHA256 else None)
+ if problem:
+ raise SystemExit(
+ f"{name}.content.json {problem}: re-run scorecontent.py"
+ )
+ docs[name] = doc
+ md = markdown(docs)
+ if a.markdown_out:
+ with open(a.markdown_out, "w", encoding="utf-8") as fh:
+ fh.write(md + "\n")
+ print(md)
+ return
+ rows_all = common.manifest()
+ common.guard_private_results(rows_all)
+ if common.is_sealed(rows_all):
+ raise SystemExit("sealed audio cannot be sent to an ASR service")
+ conds = tuple(c for c in a.conds.split(",") if c)
+ golden = scoreasr.load_golden()
+ rows = panel(rows_all, golden, conds)
+ if not rows:
+ raise SystemExit(
+ "no verified English transcripts in the named conditions")
+ print(
+ f"content panel: {len(rows)} items over {len(conds)} conditions",
+ flush=True,
+ )
+ norm = scoreasr.Normalizer()
+ asr = scoreasr.make_asr(a.asr, a.device, a.beam_size)
+ cache = scoreasr.Cache(scoreasr.CACHE_ROOT, scoreasr.cache_tag(asr),
+ asr.identity)
+ os.makedirs(common.RESULTS, exist_ok=True)
+ names = [s for s in a.systems.split(",") if s]
+ if a.controls:
+ names += render_controls(rows)
+ docs = {}
+ for name in names:
+ problem = (name != "INPUT" and
+ scorebench.render_problem(name)) or missing_render(name)
+ if problem:
+ print(f"skip {name}: {problem}", flush=True)
+ continue
+ result = score_system(name, rows, asr, cache, norm, golden)
+ if not result["items"]:
+ print(
+ f"skip {name}: none of the panel's {len(rows)} outputs is"
+ " there; an earlier sidecar is left as it was",
+ flush=True,
+ )
+ continue
+ write_sidecar(
+ os.path.join(common.RESULTS, f"{name}.content.json"),
+ name,
+ a.asr,
+ result,
+ asr.identity,
+ rows,
+ conds,
+ )
+ docs[name] = result
+ r = result["rates"]["all"]
+ print(
+ f"{name}: deleted {r['del_pct']:.1f} substituted"
+ f" {r['sub_pct']:.1f} inserted {r['ins_pct']:.1f} per 100 words;"
+ f" {len(result['missing'])} missing",
+ flush=True,
+ )
+ if a.markdown_out and docs:
+ md = markdown(docs)
+ with open(a.markdown_out, "w", encoding="utf-8") as fh:
+ fh.write(md + "\n")
+ print(md)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/bench/scripts/scoreevents.py b/bench/scripts/scoreevents.py
new file mode 100644
index 0000000..ef641f9
--- /dev/null
+++ b/bench/scripts/scoreevents.py
@@ -0,0 +1,980 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Noise recorded with the voice: transient events and quiet floors in the
+voice's own room and microphone, and the voice's level while they go.
+
+The same-room items are paired: the voice after the room and the microphone
+is the reference, and the mixture adds, through the same room and microphone,
+isolated transient events (one-shots in the pauses or under the speech) and a
+quiet floor, every one of them labelled in the item's provenance. The block
+is read from two renders of every system: the mixtures, as for every other
+item, and the references, which ``--pair`` links under ``<pair>/in`` by the
+same file names and which ``runfield.sh`` with ``PROBE_IN`` and
+``runsystem.py --inputs`` render into ``<pair>/out/<system>`` in the
+environment that rendered the board (the receipts say so). What the noise
+did to the output is the difference between the two renders, whatever the
+system makes of the voice's own room: a system that removes the room is
+charged for the room on neither row. Three rows are read per item, each
+bounded to ``ITEM_CLIP_DB`` before pooling:
+
+``event_resid_db`` is, over each labelled event span (kept open ``DECAY_S``
+after its end for the room's decay), the energy of the difference between
+the two renders against the energy the mixture added there, in dB, every
+event bounded to ``ITEM_CLIP_DB`` and the item reading their mean: zero
+leaves the event as it was, ``-ITEM_CLIP_DB`` is an event removed outright.
+``floor_resid_db`` is the same ratio over the labelled pauses outside the
+events. ``voice_level_db`` is the lower of two reads of the voice on the
+reference's loudest fifth of speech frames, in dB: the mixture's render
+against the reference's render, what the noise costs the voice; and the
+mixture's render against the reference itself with the room's share of
+those frames allowed (``room_share_db``: how much louder the voice is on
+them with its room than without it at the recording's level, the room-free
+voice placed at the direct sound's arrival, where a system that removes the
+room renders it; measured when the set was built), capped at zero. A
+system that removes the room is charged for it on neither; one that turns
+the voice down, with the noise there or without, is; and a render with no
+voice on those frames reads the bound. The system's delay (its median lag
+on clean speech, as its base scores record
+it) and the gain its base scores record are undone on both renders first; a
+flipped polarity cannot matter, since every row reads energies of the
+difference between the two renders or ratios of their energies. The
+unbounded means stand beside the two residual rows (``*_raw_db``, floored
+at ``RAW_FLOOR_DB``) for reads outside the board, and every cell counts the
+items carrying each row (``metric_counts``). Removal is credited only while
+the voice is kept: an item whose voice row is at or under ``VOICE_GATE_DB``
+reads its event and floor rows as left (zero), and an event under speech
+whose span lost the voice in the reference's render, beyond the room's
+share, reads as left; silencing the output, or deleting the speech an event
+sits on, earns nothing.
+
+The real recordings have no reference. ``_real_events`` pools the items on
+which the shared detector finds a transient on the INPUT outside the speech
+the VAD marks (a rise of ``JUMP_DB`` within one 10 ms frame to
+``ABOVE_MEDIAN_DB`` over the running median of the previous half second, kept
+until the level is back within 6 dB of that median): ``event_att_db`` is the
+level change of the output over those spans, ``voice_level_db`` the level
+change on the input's loudest fifth of speech frames. An item without such an
+event is counted as having none, never as missing.
+
+Usage: scoreevents.py --pair [--pair-dir DIR]
+ scoreevents.py --systems a,b [--pair-dir DIR] [--reuse-from DIR]
+ [--aggregate-only DIR]
+Output: <BENCH_RESULTS>/<system>.events.json and .events.items.jsonl
+"""
+
+import argparse
+import collections
+import glob
+import hashlib
+import json
+import math
+import os
+import shutil
+import sys
+
+import numpy as np
+import torch
+
+# pylint: disable=wrong-import-position
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import anchors
+import common
+import levels
+import observations
+import scorebench
+
+sys.path.insert(0, os.path.join(common.BENCH_DIR, "wrappers"))
+import receipt
+
+SCORER_SHA256 = observations.implementation(
+ __file__,
+ common.__file__,
+ observations.__file__,
+ levels.__file__,
+ scorebench.__file__,
+)
+
+FRAME = 480
+DECAY_S = 0.15
+EDGE_S = 0.3
+JUMP_DB, ABOVE_MEDIAN_DB = 12.0, 15.0
+RELEASE_DB = 6.0
+HISTORY_FRAMES = 50
+# the loudest fifth of the speech frames give the voice's level
+TOP_SHARE = 0.2
+# no item reads beyond this much credit or penalty in any pooled row
+ITEM_CLIP_DB = 20.0
+# the unbounded rows stop here, where the difference between the two renders
+# is numerically nothing
+RAW_FLOOR_DB = -60.0
+# removal is credited only while the voice is kept: an item whose voice row
+# is at or under this (the declared floor of the preservation row) reads its
+# noise rows as left, and an event under speech whose span lost the voice in
+# the reference's render reads as left; removing the voice is not removing
+# the noise
+VOICE_GATE_DB = -3.0
+# the pair of renders: the references under <pair>/in, identified like the
+# streaming probe's inputs (receipt.py reads probe.json beside the folder)
+PAIR_KIND = "same_room_references"
+PAIR_VERSION = "1"
+SAME_ROOM = ("coroom@pause", "coroom@speech", "coroom@floor", "coroom@both")
+EVENT_CONDS = ("coroom@pause", "coroom@speech", "coroom@both")
+FLOOR_CONDS = ("coroom@floor", "coroom@both")
+REAL = ("real_dirty", "real_multi", "real_noisy", "real_wild", "real_everyday")
+
+
+def frames_db(x: torch.Tensor) -> np.ndarray:
+ """Level of every 10 ms frame of ``x`` in dBFS."""
+ n = len(x) // FRAME
+ energy = x[:n * FRAME].view(n, FRAME).pow(2).mean(1).numpy()
+ return 10 * np.log10(energy + 1e-12)
+
+
+def detect_events(db: np.ndarray) -> list:
+ """Event spans [start, end) in frames by the shared definition."""
+ db = np.asarray(db, dtype=np.float64)
+ n = len(db)
+ spans = []
+ jumps = np.flatnonzero(np.diff(db) >= JUMP_DB) + 1
+ allowed = 1
+ for i in jumps:
+ if i < allowed:
+ continue
+ lo = max(0, i - HISTORY_FRAMES)
+ median = float(np.median(db[lo:i])) if i - lo > 5 else float(db[i])
+ if db[i] - median < ABOVE_MEDIAN_DB:
+ continue
+ j = i
+ while j + 1 < n and db[j + 1] > median + RELEASE_DB and j - i < 60:
+ j += 1
+ spans.append((int(i), int(j + 1)))
+ allowed = j + 30
+ return spans
+
+
+def _frame_mask(n_frames: int,
+ spans_s: list,
+ tail_s: float = 0.0) -> np.ndarray:
+ mask = np.zeros(n_frames, dtype=bool)
+ for start, end in spans_s:
+ a = max(0, int(start * common.SR) // FRAME)
+ b = min(n_frames, int((end + tail_s) * common.SR) // FRAME + 1)
+ mask[a:b] = True
+ return mask
+
+
+def _energy(x: torch.Tensor, mask: np.ndarray) -> float:
+ """The energy of ``x`` over the frames ``mask`` marks, summed in float64."""
+ frames = x[:len(mask) * FRAME].view(len(mask), FRAME).double().pow(2)
+ return float(frames.sum(1).numpy()[mask].sum())
+
+
+def _loud_speech(reference_db: np.ndarray, speech: np.ndarray) -> np.ndarray:
+ if not speech.any():
+ return speech
+ cut = np.quantile(reference_db[speech], 1.0 - TOP_SHARE)
+ return speech & (reference_db >= cut)
+
+
+def pair_dir(path: str = "") -> str:
+ """Returns the pair's directory.
+
+ The flag, ``BENCH_PAIR``, or ``pair_coroom`` beside ``BENCH_OUT``.
+ """
+ return (path or os.environ.get("BENCH_PAIR") or os.path.join(
+ os.path.dirname(os.path.abspath(common.OUT_ROOT.rstrip("/"))),
+ "pair_coroom",
+ ))
+
+
+def pair_rows(rows: list) -> list:
+ """Returns the same-room items with a reference, in id order.
+
+ The complete inventory.
+ """
+ return sorted(
+ (r for r in rows
+ if r["condition"] in SAME_ROOM and r.get("clean_path")),
+ key=lambda r: r["id"],
+ )
+
+
+def identity_of(hashes) -> str:
+ """Returns one identity for a set of inputs or outputs: the sha256 of their
+ sorted sample hashes."""
+ return hashlib.sha256("\n".join(sorted(hashes)).encode()).hexdigest()
+
+
+def pair_problem(root: str, rows: list) -> str | None:
+ """Returns why ``<root>/probe.json`` is not this build's pair, or None.
+
+ It must name this build and the complete inventory of same-room items,
+ every input verified by its samples.
+ """
+ path = os.path.join(root, "probe.json")
+ if not os.path.isfile(path):
+ return "no probe.json"
+ with open(path, encoding="utf-8") as fh:
+ pair = json.load(fh)
+ if pair.get("kind") != PAIR_KIND:
+ return "not the same-room pair (another probe's inputs)"
+ if pair.get("set_id") != common.set_id():
+ return (f"linked from set {str(pair.get('set_id'))[:12]}, the current"
+ f" set is {str(common.set_id())[:12]}")
+ if pair.get("pair_version") != PAIR_VERSION:
+ return (f"linked by pair version {pair.get('pair_version')!r}, this"
+ f" scorer links version {PAIR_VERSION!r}")
+ wanted = [r["id"] for r in pair_rows(rows)]
+ if [e["id"] for e in pair.get("items", [])] != wanted:
+ return ("its items are not the complete inventory of the set's"
+ " same-room items")
+ if pair.get("identity") != identity_of(e["sha256"] for e in pair["items"]):
+ return "its identity does not match its inputs"
+ in_dir = os.path.join(root, "in")
+ listed = {e["id"] for e in pair["items"]}
+ stray = (sorted(set(os.listdir(in_dir)) -
+ listed) if os.path.isdir(in_dir) else [])
+ if stray: # runsystem.py --inputs identifies the directory as it stands
+ return (f"{len(stray)} files under in/ are not pair inputs (first:"
+ f" {stray[0]})")
+ for entry in pair["items"]:
+ file = os.path.join(in_dir, entry["id"])
+ if (not os.path.isfile(file) or
+ scorebench.sample_hash(common.load48(file)) != entry["sha256"]):
+ return f"{entry['id']} is not the recorded pair input"
+ return None
+
+
+def write_pair(rows: list, root: str) -> dict:
+ """Links the same-room references under ``<root>/in`` and records them.
+
+ The record is ``<root>/probe.json``; a pair that is already current is
+ left as it is, so renders made from it stay valid.
+ """
+ items = pair_rows(rows)
+ if not items:
+ raise SystemExit("the set has no same-room items with a reference")
+ if pair_problem(root, rows) is None:
+ with open(os.path.join(root, "probe.json"), encoding="utf-8") as fh:
+ return json.load(fh)
+ in_dir = os.path.join(root, "in")
+ os.makedirs(in_dir, exist_ok=True)
+ # the directory is exactly the pair, nothing else
+ for stale in os.listdir(in_dir):
+ os.remove(os.path.join(in_dir, stale))
+ listed = []
+ for r in items:
+ target = os.path.join(in_dir, r["id"])
+ try:
+ os.link(r["clean_path"], target)
+ except OSError:
+ shutil.copyfile(r["clean_path"], target)
+ listed.append({
+ "id": r["id"],
+ "sha256": scorebench.sample_hash(common.load48(target)),
+ })
+ pair = {
+ "kind": PAIR_KIND,
+ "pair_version": PAIR_VERSION,
+ "set_id": common.set_id(),
+ "source_conditions": list(SAME_ROOM),
+ "items": listed,
+ }
+ pair["identity"] = identity_of(e["sha256"] for e in listed)
+ tmp = os.path.join(root, f"probe.json.{os.getpid()}.tmp")
+ with open(tmp, "w", encoding="utf-8") as fh:
+ json.dump(pair, fh, indent=1)
+ os.replace(tmp, os.path.join(root, "probe.json"))
+ return pair
+
+
+def read_pair(root: str, rows: list) -> dict:
+ """Returns the pair's record once its inputs are verified."""
+ problem = pair_problem(root, rows)
+ if problem:
+ raise SystemExit(
+ f"{os.path.join(root, 'probe.json')}: {problem}; link the pair"
+ " again (scoreevents.py --pair) and render it")
+ with open(os.path.join(root, "probe.json"), encoding="utf-8") as fh:
+ return json.load(fh)
+
+
+def pair_render_problem(name: str, results: str, root: str,
+ pair: dict) -> str | None:
+ """Returns why the pair render of ``name`` does not stand for it, or None.
+
+ Every pair render carries the receipts its processes wrote: they must
+ agree on the environment the board's stamp records
+ (``render_environment_sha256``: code, weights, packages, device and
+ arguments, the inputs aside) and name this pair's inputs.
+ """
+ path = os.path.join(results, f"{name}.meta.json")
+ if not os.path.isfile(path):
+ return "no stamp for the board's render (meta.json missing)"
+ with open(path, encoding="utf-8") as fh:
+ board = json.load(fh)
+ if not board.get("render_environment_sha256"):
+ return ("the board's stamp records no render environment: re-render"
+ " the board")
+ out_dir = os.path.join(root, "out", name)
+ if not os.path.isdir(out_dir):
+ return f"no pair render under {os.path.join(root, 'out')}"
+ docs = receipt.read_all(out_dir)
+ if not docs:
+ return "the pair render carries no receipt"
+ environments = {d.get("environment_digest") for d in docs}
+ if environments != {board["render_environment_sha256"]}:
+ return (
+ "the pair was rendered in another environment than the board's"
+ " render (receipts"
+ f" {', '.join(str(e)[:12] for e in sorted(map(str, environments)))}"
+ f" vs stamp {board['render_environment_sha256'][:12]})")
+ inputs = {
+ (d.get("identity", {}).get("inputs") or {}).get("probe") for d in docs
+ }
+ if inputs != {pair["identity"]}:
+ return "the pair render was made from other inputs: render it again"
+ return None
+
+
+def score_same_room(it: dict,
+ out: torch.Tensor,
+ mix: torch.Tensor,
+ ref: torch.Tensor,
+ out_ref: torch.Tensor,
+ gain_db: float,
+ lag: int = 0,
+ room_share_db: float = 0.0) -> dict:
+ """Energies of one same-room item: per event, over the floor, on the voice.
+
+ ``out`` renders the mixture, ``out_ref`` the reference; the system's
+ delay ``lag`` (samples) and gain are undone on both. ``room_share_db``
+ is the room's share of the reference's level on its loudest speech
+ frames, allowed to a system that removes the room.
+ """
+ n = min(len(out), len(mix), len(ref), len(out_ref))
+ scale = 10**(-gain_db / 20)
+ o = scale * common.apply_lag(out, lag, n)
+ p = scale * common.apply_lag(out_ref, lag, n)
+ x, r = mix[:n], ref[:n]
+ n_frames = n // FRAME
+ prov = it.get("provenance") or {}
+ events = [(e[0], e[1]) for e in prov.get("events", [])]
+ event_mask = _frame_mask(n_frames, events, DECAY_S)
+ pauses = _frame_mask(n_frames, prov.get("pauses", []))
+ edge = np.zeros(n_frames, dtype=bool)
+ k = int(EDGE_S * common.SR) // FRAME
+ edge[:k] = edge[n_frames - k:] = True
+ floor = pauses & ~event_mask & ~edge
+ ref_db = frames_db(r)
+ speech = (ref_db > np.median(ref_db) + 6.0) & ~pauses & ~edge
+ loud = _loud_speech(ref_db, speech)
+ added, left = o - p, x - r
+ kinds = [str(e[2]) if len(e) > 2 else "" for e in prov.get("events", [])]
+ return {
+ "lag": lag,
+ # per event: what the noise did, what the mixture added, and the voice
+ # the reference's render keeps on the span against the reference
+ "events": [[
+ _energy(added, _frame_mask(n_frames, [e], DECAY_S)),
+ _energy(left, _frame_mask(n_frames, [e], DECAY_S)),
+ _energy(p, _frame_mask(n_frames, [e], DECAY_S)),
+ _energy(r, _frame_mask(n_frames, [e], DECAY_S)),
+ ] for e in events],
+ "event_kinds": kinds,
+ "floor": [_energy(added, floor),
+ _energy(left, floor)],
+ "floor_frames": int(floor.sum()),
+ "voice": [_energy(o, loud), _energy(p, loud)],
+ "voice_ref": _energy(r, loud),
+ "room_share_db": float(room_share_db),
+ "loud_frames": int(loud.sum()),
+ }
+
+
+def score_real(it: dict, out: torch.Tensor, mix: torch.Tensor, vad,
+ gain_db: float) -> dict:
+ """Energies of one real recording over the events the input holds."""
+ n = min(len(out), len(mix))
+ lag, sign = common.best_alignment(out[:n], mix[:n])
+ o = sign * common.apply_lag(out, lag, n) * 10**(-gain_db / 20)
+ x = mix[:n]
+ n_frames = n // FRAME
+ _, segs = (scorebench.speech_segments(vad, x, it["mix_path"])
+ if n == len(mix) else vad.segments(x))
+ speech = np.zeros(n_frames, dtype=bool)
+ for s in segs:
+ speech[s["start"] * 3 // FRAME:min(n_frames, s["end"] * 3 // FRAME +
+ 1)] = True
+ in_db = frames_db(x)
+ spans = [(i, j) for i, j in detect_events(in_db) if not speech[i:j].any()]
+ event_mask = np.zeros(n_frames, dtype=bool)
+ for i, j in spans:
+ event_mask[i:min(n_frames, j +
+ int(DECAY_S * common.SR) // FRAME)] = True
+ loud = _loud_speech(in_db, speech & ~event_mask)
+ return {
+ "lag": lag,
+ "polarity": sign,
+ "events": [[
+ _energy(
+ o,
+ _frame_mask(n_frames,
+ [(i * FRAME / common.SR, j * FRAME / common.SR)],
+ DECAY_S)),
+ _energy(
+ x,
+ _frame_mask(n_frames,
+ [(i * FRAME / common.SR, j * FRAME / common.SR)],
+ DECAY_S)),
+ ] for i, j in spans],
+ "event_spans_s": [[
+ round(i * FRAME / common.SR, 3),
+ round(j * FRAME / common.SR, 3)
+ ] for i, j in spans],
+ "voice": [_energy(o, loud), _energy(x, loud)],
+ "loud_frames": int(loud.sum()),
+ }
+
+
+def bounded(db: float,
+ low: float = -ITEM_CLIP_DB,
+ high: float = ITEM_CLIP_DB) -> float:
+ return float(min(max(db, low), high))
+
+
+def _ratio_db(num: float, den: float) -> float:
+ if den <= 0:
+ return math.nan
+ return 10 * math.log10(max(num, 0.0) / den + 1e-20)
+
+
+def same_room_metrics(m: dict, condition: str) -> dict:
+ """The item's rows from its energies, each bounded, the residual rows
+ beside their unbounded means; removal credited only while the voice is
+ kept (``VOICE_GATE_DB``)."""
+ out = {}
+ share = float(m.get("room_share_db") or 0.0)
+ if m.get("loud_frames", 0) > 0 and m.get("voice_ref", 0.0) > 0:
+ with_noise, without = m["voice"]
+ if with_noise <= 0 or without <= 0:
+ # no voice on the loudest speech frames of a render: the voice
+ # is gone, whatever the other render holds
+ out["voice_level_db"] = -ITEM_CLIP_DB
+ else:
+ pair = _ratio_db(with_noise, without)
+ kept = min(0.0, _ratio_db(with_noise, m["voice_ref"]) + share)
+ out["voice_pair_db"] = bounded(pair)
+ out["voice_kept_db"] = bounded(kept)
+ out["voice_level_db"] = bounded(min(pair, kept))
+ voice_gone = out.get("voice_level_db", 0.0) <= VOICE_GATE_DB
+ if condition in EVENT_CONDS and m.get("events"):
+ kinds = m.get("event_kinds") or [""] * len(m["events"])
+ values = []
+ for entry, kind in zip(m["events"], kinds):
+ if entry[1] <= 0:
+ continue
+ value = _ratio_db(entry[0], entry[1])
+ if voice_gone:
+ value = 0.0
+ elif kind == "speech" and len(entry) >= 4 and entry[3] > 0:
+ # the voice the reference's render keeps on the span, the
+ # room's share allowed: a span that lost it was not cleaned
+ if _ratio_db(entry[2], entry[3]) + share <= VOICE_GATE_DB:
+ value = 0.0
+ values.append(value)
+ if values:
+ # each event bounded on its own: one of two removed is half credit
+ out["event_resid_db"] = float(np.mean([bounded(v) for v in values]))
+ out["event_resid_raw_db"] = float(
+ np.mean([max(v, RAW_FLOOR_DB) for v in values]))
+ if (condition in FLOOR_CONDS and m.get("floor_frames", 0) > 0 and
+ m["floor"][1] > 0):
+ raw = 0.0 if voice_gone else max(_ratio_db(*m["floor"]), RAW_FLOOR_DB)
+ out["floor_resid_db"] = bounded(raw)
+ out["floor_resid_raw_db"] = raw
+ return out
+
+
+def real_metrics(m: dict) -> dict:
+ out = {"n_events": len(m.get("events", []))}
+ values = [_ratio_db(a, b) for a, b in m.get("events", []) if b > 0]
+ if values:
+ out["event_att_db"] = bounded(float(np.mean(values)))
+ if m.get("loud_frames", 0) > 0 and m["voice"][1] > 0:
+ out["voice_level_db"] = bounded(_ratio_db(*m["voice"]))
+ return out
+
+
+def _render(path: str, length: int) -> tuple:
+ """Returns (samples, problem) of one render: the file at ``path``, of
+ ``length`` samples and finite."""
+ if not os.path.exists(path):
+ return None, "missing"
+ out = common.load48(path)
+ if len(out) != length:
+ return None, "wrong_length"
+ if not bool(torch.isfinite(out).all()):
+ return None, "nonfinite"
+ return out, None
+
+
+# the labels a same-room measurement reads, and the rule that produced the room
+# allowance: both enter every observation's identity, so a label edit or a new
+# allowance rule invalidates the cached measurements and the controls that read
+# them instead of leaving a valid-looking cache
+SCORE_LABELS = ("events", "pauses", "floor", "split", "room_share_db",
+ "room_share_rule")
+# v2: the room-free voice sits at the direct sound's arrival, where a system
+# that removes the room renders it (v1 placed it at its cross-correlation peak
+# with the reverberant reference, a median 12 ms later, which read a perfect
+# room remover 0.4 dB under the allowance). The set's provenance records the
+# rule its shares were measured under (``room_share_rule``); the scorer reads
+# only shares measured under this one, and every label digest carries the
+# recorded rule.
+ROOM_SHARE_RULE = ("level-matched dry share on the reference's loudest fifth of"
+ " speech frames, the dry voice at the direct arrival, v2")
+
+
+def labels_digest(row: dict) -> str | None:
+ """Returns the digest of the labels a same-room item is scored by.
+
+ None for an item outside the block, whose measurements read no label.
+ """
+ if row.get("condition") not in SAME_ROOM:
+ return None
+ prov = row.get("provenance") or {}
+ labels = {key: prov.get(key) for key in SCORE_LABELS}
+ return hashlib.sha256(json.dumps(labels,
+ sort_keys=True).encode()).hexdigest()
+
+
+def labels_identity(rows: list) -> str:
+ """Returns one digest of the labels every same-room row of ``rows`` is
+ scored by, which a sidecar carries so that a frozen view can be traced to
+ the labels it measured."""
+ return anchors.digest(
+ sorted([r["id"], labels_digest(r)]
+ for r in rows
+ if r.get("condition") in SAME_ROOM))
+
+
+def stale_labels(records: list, rows: list) -> str | None:
+ """Returns why ``records`` cannot derive a view of ``rows``, or None.
+
+ A same-room record measured under labels other than its row's: the
+ scoring pass measures such an item again, a view never may.
+ """
+ want = {
+ r["id"]: labels_digest(r)
+ for r in rows
+ if r.get("condition") in SAME_ROOM
+ }
+ stale = sorted(rec["id"]
+ for rec in records
+ if rec["id"] in want and rec.get("output_status") == "ok" and
+ (rec.get("identity") or {}).get("labels") != want[rec["id"]])
+ if not stale:
+ return None
+ return (f"{len(stale)} same-room records were measured under other labels"
+ f" (first: {stale[0]}): score the whole set again")
+
+
+def room_shares(rows: list) -> dict:
+ """Returns {item id: the room's share of the voice's level, dB} of the
+ same-room items, from their provenance (``room_share_db``).
+
+ An item without the figure allows nothing: a system that removes its
+ room is then charged for it on the voice row.
+
+ Raises:
+ SystemExit: An item's share was measured under another rule than
+ ``ROOM_SHARE_RULE`` (or under none recorded, the v1 sets): the
+ set's shares must be re-measured before the block is scored.
+ """
+ shares = {}
+ for r in rows:
+ if r["condition"] in SAME_ROOM:
+ prov = r.get("provenance") or {}
+ rule = prov.get("room_share_rule")
+ if rule != ROOM_SHARE_RULE:
+ raise SystemExit(
+ f"{r['id']}: room_share_db was measured under "
+ f"{rule or 'an unrecorded rule (v1)'}; this scorer reads "
+ f"{ROOM_SHARE_RULE!r}. Re-measure the set's shares before "
+ "scoring the same-room block.")
+ value = prov.get("room_share_db")
+ shares[r["id"]] = float(value) if value is not None else 0.0
+ return shares
+
+
+def assemble(name,
+ rows,
+ vad,
+ gain_db,
+ reuse=None,
+ hashes=None,
+ pair_out=None,
+ lag=0):
+ """Returns per-item records over ``rows``.
+
+ ``pair_out`` holds the system's renders of the same-room references by
+ the items' names (``<pair>/out/<system>``); INPUT's are the references
+ themselves; ``lag`` is the system's delay in samples. An item whose
+ output samples are unchanged since an earlier pass keeps its record
+ (``reuse``), read at the same gain and delay.
+ """
+ hashes = hashes or common.file_hashes()
+ reuse = reuse or {}
+ shares = room_shares(rows)
+ records, counts = [], collections.Counter()
+ for it in rows:
+ record = observations.item(it)
+ records.append(record)
+ op = (it["mix_path"] if name == "INPUT" else os.path.join(
+ common.OUT_ROOT, name, it["id"]))
+ mix = common.load48(it["mix_path"])
+ out, problem = _render(op, len(mix))
+ if problem:
+ record["output_status"] = problem
+ continue
+ record["identity"] = scorebench.item_identity(
+ it, scorebench.sample_hash(out), hashes)
+ record["identity"]["labels"] = labels_digest(it)
+ ref = out_ref = None
+ if it.get("clean_path"):
+ ref = common.load48(it["clean_path"])
+ if name == "INPUT":
+ out_ref = ref
+ else:
+ out_ref, problem = _render(
+ os.path.join(pair_out or "", it["id"]), len(ref))
+ if problem:
+ record["output_status"] = f"{problem}_pair"
+ continue
+ record["identity"]["pair_output"] = scorebench.sample_hash(out_ref)
+ old = reuse.get(scorebench.reuse_key(record["identity"]))
+ if (old is not None and old.get("gain_db") == gain_db and
+ old.get("lag", 0) == lag):
+ record["measurements"] = dict(old["measurements"])
+ counts["reused"] += 1
+ elif ref is not None:
+ record["measurements"] = observations.finite(
+ score_same_room(it, out, mix, ref, out_ref, gain_db, lag,
+ shares.get(it["id"], 0.0)))
+ counts["scored"] += 1
+ else:
+ record["measurements"] = observations.finite(
+ score_real(it, out, mix, vad, gain_db))
+ counts["scored"] += 1
+ record["gain_db"] = gain_db
+ record["lag"] = lag
+ if reuse:
+ print(
+ f" reused {counts['reused']} records, scored {counts['scored']}"
+ " items",
+ flush=True,
+ )
+ return records
+
+
+def at_gain(m: dict, from_db: float | None, to_db: float, paired: bool) -> dict:
+ """Returns an item's energies re-read at another gain.
+
+ The output's energies were undone at ``from_db`` when the item was scored;
+ a view calibrated at ``to_db`` reads them scaled by the difference. The
+ mixture's and the reference's energies do not move.
+ """
+ if from_db is None or abs(float(from_db) - to_db) < 1e-12:
+ return m
+ k = 10**((float(from_db) - to_db) / 10)
+ m = dict(m)
+ if m.get("events"):
+ # the output's energies move: what the noise did and the voice the
+ # reference's render keeps; the mixture's and the reference's stay
+ m["events"] = [[e[0] * k, e[1]] +
+ ([e[2] * k, e[3]] if len(e) >= 4 else [])
+ for e in m["events"]]
+ if m.get("floor"):
+ m["floor"] = [m["floor"][0] * k, m["floor"][1]]
+ if m.get("voice"):
+ o, other = m["voice"]
+ m["voice"] = [o * k, other * k if paired else other]
+ return m
+
+
+def aggregate(records: list, rows: list, level_cal_db: float) -> dict:
+ """Returns the sidecar file for ``rows``: per condition the mean of its
+ items' rows, pooled over the same-room block (``_coroom``) and over the
+ real recordings with an event (``_real_events``). Pure, so any view of the
+ set derives from the whole-set records, read at the view's own
+ calibration ``level_cal_db``."""
+ by_id = {r["id"]: r for r in records}
+ out = {}
+ pooled = collections.defaultdict(list)
+ real_items, real_events, real_without = 0, 0, 0
+ for it in rows:
+ cond = it["condition"]
+ rec = by_id.get(it["id"])
+ cell = out.setdefault(cond, {"n_expected": 0, "n_missing": 0, "n": 0})
+ cell["n_expected"] += 1
+ if rec is None or rec.get("output_status") != "ok":
+ cell["n_missing"] += 1
+ continue
+ m = observations.revive(rec.get("measurements", {}))
+ m = at_gain(m, rec.get("gain_db"), level_cal_db, cond in SAME_ROOM)
+ if cond in SAME_ROOM:
+ values = same_room_metrics(m, cond)
+ key = "_coroom"
+ else:
+ values = real_metrics(m)
+ key = "_real_events"
+ real_items += 1
+ real_events += values["n_events"]
+ if not values["n_events"]:
+ real_without += 1
+ rec["metrics"] = observations.finite(values)
+ cell["n"] += 1
+ for k, v in values.items():
+ if isinstance(v, float) and math.isfinite(v):
+ cell.setdefault("_values", {}).setdefault(k, []).append(v)
+ pooled[(key, k)].append(v)
+ for cell in out.values():
+ values = cell.pop("_values", {})
+ for k, vs in values.items():
+ cell[k] = float(np.mean(vs))
+ # the items carrying each row, so coverage is read per row
+ cell["metric_counts"] = {k: len(vs) for k, vs in values.items()}
+ if any(c in out for c in SAME_ROOM):
+ block = {
+ k: float(np.mean(vs))
+ for (key, k), vs in pooled.items()
+ if key == "_coroom"
+ }
+ block["metric_counts"] = {
+ k: len(vs) for (key, k), vs in pooled.items() if key == "_coroom"
+ }
+ block.update({
+ "n":
+ sum(out[c]["n"] for c in SAME_ROOM if c in out),
+ "n_expected":
+ sum(out[c]["n_expected"] for c in SAME_ROOM if c in out),
+ "n_missing":
+ sum(out[c]["n_missing"] for c in SAME_ROOM if c in out),
+ })
+ out["_coroom"] = block
+ if real_items:
+ real = {
+ k: float(np.mean(vs))
+ for (key, k), vs in pooled.items()
+ if key == "_real_events"
+ }
+ real["metric_counts"] = {
+ k: len(vs)
+ for (key, k), vs in pooled.items()
+ if key == "_real_events"
+ }
+ real.update({
+ "n": real_items - real_without,
+ "n_expected": sum(out[c]["n_expected"] for c in REAL if c in out),
+ "n_missing": sum(out[c]["n_missing"] for c in REAL if c in out),
+ "n_without_events": real_without,
+ "n_events": real_events,
+ })
+ out["_real_events"] = real
+ out["_level_cal_db"] = level_cal_db
+ return out
+
+
+def base_calibration(results: str, name: str, outputs: str) -> tuple:
+ """Returns the system's output gain (dB) and delay (samples) from its
+ base scores: the level calibration and the median lag on clean speech.
+
+ Bound to the render the base scores read.
+ """
+ path = os.path.join(results, f"{name}.metrics.json")
+ if not os.path.isfile(path):
+ raise SystemExit(f"{path} is missing: score {name} with scorebench"
+ " before this sidecar")
+ with open(path, encoding="utf-8") as fh:
+ base = json.load(fh)
+ if base.get("_scorer_sha256") != scorebench.SCORER_SHA256:
+ raise SystemExit(f"{path}: scored by another base scorer; re-score"
+ f" {name} with scorebench first")
+ if base.get("_outputs_sha256") != outputs:
+ raise SystemExit(f"{path}: scores of another render of {name};"
+ " re-score it with scorebench first")
+ lag = (base.get("clean") or {}).get("lag_median") or 0.0
+ return float(base.get("_level_cal_db") or 0.0), int(round(lag))
+
+
+def pair_outputs_digest(records: list) -> str | None:
+ """Returns the identity of the pair renders the records read, or None."""
+ hashes = [
+ r["identity"]["pair_output"]
+ for r in records
+ if r.get("output_status") == "ok" and
+ (r.get("identity") or {}).get("pair_output")
+ ]
+ return identity_of(hashes) if hashes else None
+
+
+def write(name, records, out, rows, level_cal_db, outputs, pair=None, lag=0):
+ """Writes the system's records and sidecar; ``pair`` names the pair of
+ renders they read (its inputs' identity and its outputs' identity),
+ ``lag`` the delay undone."""
+ pair = pair or {}
+ observations.sidecar(
+ os.path.join(common.RESULTS, f"{name}.events.items.jsonl"),
+ records,
+ name,
+ common.set_id(),
+ common.SUBSET,
+ common.is_sealed(rows),
+ SCORER_SHA256,
+ level_cal_db=level_cal_db,
+ lag=lag,
+ outputs_sha256=outputs,
+ pair_sha256=pair.get("inputs"),
+ pair_outputs_sha256=pair.get("outputs"),
+ )
+ out["_set_id"] = common.set_id()
+ out["_subset"] = common.SUBSET
+ out.update(anchors.stamp())
+ out["_sealed"] = common.is_sealed(rows)
+ out["_scorer_sha256"] = SCORER_SHA256
+ out["_labels_sha256"] = labels_identity(rows)
+ out["_outputs_sha256"] = outputs
+ out["_pair_sha256"] = pair.get("inputs")
+ out["_pair_outputs_sha256"] = pair.get("outputs")
+ path = os.path.join(common.RESULTS, f"{name}.events.json")
+ tmp = f"{path}.{os.getpid()}.tmp"
+ with open(tmp, "w", encoding="utf-8") as fh:
+ json.dump(observations.finite(out), fh, indent=1)
+ os.replace(tmp, path)
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument(
+ "--pair",
+ action="store_true",
+ help="link the same-room references under <pair>/in (or confirm the"
+ " current ones) and stop",
+ )
+ ap.add_argument(
+ "--pair-dir",
+ default="",
+ help="default: BENCH_PAIR or pair_coroom beside BENCH_OUT",
+ )
+ ap.add_argument("--systems", default="")
+ ap.add_argument("--reuse-from", default="", metavar="DIR")
+ ap.add_argument("--aggregate-only", default="", metavar="DIR")
+ a = ap.parse_args()
+
+ rows = common.manifest()
+ common.guard_private_results(rows)
+ root = pair_dir(a.pair_dir)
+ if a.pair:
+ before = pair_problem(root, rows)
+ pair = write_pair(rows, root)
+ n = len(pair["items"])
+ print(f"pair is current: {n} references under {root}/in" if before is
+ None else (
+ f"{n} references -> {root}/in ({before}); renders of the"
+ " earlier inputs no longer match: render the pair again into"
+ " a fresh folder"))
+ return
+ selected = [r for r in rows if r["condition"] in SAME_ROOM + REAL]
+ pair = (read_pair(root, rows)
+ if pair_rows(selected) and not a.aggregate_only else None)
+ systems = [s for s in a.systems.split(",") if s] or sorted(
+ os.path.basename(d)
+ for d in glob.glob(common.OUT_ROOT + "/*")
+ if os.path.isdir(d))
+ vad = None if a.aggregate_only else common.Vad()
+ os.makedirs(common.RESULTS, exist_ok=True)
+ for name in systems:
+ if a.aggregate_only:
+ src = os.path.join(a.aggregate_only, f"{name}.events.items.jsonl")
+ ids = {r["id"] for r in selected}
+ problem, source, records = scorebench.view_records(
+ src, name, ids, SCORER_SHA256)
+ problem = problem or stale_labels(records, selected)
+ if problem:
+ print(f"skip {name}: {problem}", flush=True)
+ continue
+ outputs = source.get("outputs_sha256")
+ # the view's own calibration, from the base scores derived for it
+ level_cal_db, _ = base_calibration(common.RESULTS, name, outputs)
+ lag = int(source.get("lag") or 0)
+ renders = {
+ "inputs": source.get("pair_sha256"),
+ "outputs": source.get("pair_outputs_sha256"),
+ }
+ else:
+ problem = name != "INPUT" and scorebench.render_problem(name)
+ if problem:
+ print(f"skip {name}: {problem}", flush=True)
+ continue
+ pair_out = None
+ if pair is not None and name != "INPUT":
+ problem = pair_render_problem(name, common.RESULTS, root, pair)
+ if problem:
+ raise SystemExit(f"{name}: {problem}")
+ pair_out = os.path.join(root, "out", name)
+ outputs = common.outputs_digest(name)
+ level_cal_db, lag = base_calibration(common.RESULTS, name, outputs)
+ own = os.path.join(common.RESULTS, f"{name}.events.items.jsonl")
+ reuse, why = {}, "no earlier records"
+ if a.reuse_from:
+ reuse, why = scorebench.reuse_index(
+ os.path.join(a.reuse_from, f"{name}.events.items.jsonl"),
+ name,
+ SCORER_SHA256,
+ )
+ why = f"reuse from {a.reuse_from}: {why}"
+ elif os.path.isfile(own):
+ reuse, why = scorebench.reuse_index(own, name, SCORER_SHA256)
+ why = f"existing records: {why}"
+ print(f" {why}", flush=True)
+ records = assemble(name,
+ selected,
+ vad,
+ level_cal_db,
+ reuse=reuse,
+ pair_out=pair_out,
+ lag=lag)
+ renders = {
+ "inputs": pair["identity"] if pair else None,
+ "outputs": pair_outputs_digest(records),
+ }
+ out = aggregate(records, selected, level_cal_db)
+ out["_lag"] = lag
+ write(name, records, out, rows, level_cal_db, outputs, renders, lag)
+ block, real = out.get("_coroom", {}), out.get("_real_events", {})
+ print(
+ f"{name:24s} same room: events"
+ f" {block.get('event_resid_db', math.nan):6.1f} dB, floor"
+ f" {block.get('floor_resid_db', math.nan):6.1f} dB, voice"
+ f" {block.get('voice_level_db', math.nan):5.1f} dB over"
+ f" {block.get('n', 0)} items; real events"
+ f" {real.get('event_att_db', math.nan):6.1f} dB on"
+ f" {real.get('n', 0)} items",
+ flush=True,
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/bench/scripts/scorefiles.py b/bench/scripts/scorefiles.py
new file mode 100644
index 0000000..6b6e0eb
--- /dev/null
+++ b/bench/scripts/scorefiles.py
@@ -0,0 +1,434 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Loads the score files a board reads and refuses stale or foreign ones.
+
+A system's base metrics come with its sidecars merged in (NISQA, the kept
+voice, the real recordings). A sidecar of another set build, subset, anchor
+version or render, or one read at another level calibration, is ignored or
+refused, never mixed in; the checks at the end keep a filtered pass, a mix of
+scorer implementations or scores of replaced audio off a board.
+"""
+
+import glob
+import json
+import math
+import os
+import sys
+
+import common
+
+KEPT_KEYS = (
+ "kept_mean",
+ "kept_p10",
+ "kept_nb_mean",
+ "kept_q1",
+ "kept_q2",
+ "kept_q3",
+ "kept_coh_mean",
+ "kept_coh_p10",
+ "kept_coh_nb_mean",
+ "kept_coh_nb_p10",
+) # every dB ratio a gain shifts
+
+REAL_FAMILIES = ("real_dirty", "real_multi", "real_noisy", "real_wild")
+# a row (a condition's, or a pooled one's) feeds an axis or a pairing only
+# with this many items behind it: one admission rule for the board and for
+# the paired comparison
+MIN_ITEMS = 20
+
+# sidecars that read the output gain: refused at another calibration than
+# the base scores'
+CALIBRATED_SIDECARS = (".kept.json", ".residual.json", ".events.json")
+# the level calibration is a median over the clean items, read in float32 on
+# a GPU: scoring the same records again can move it by a millionth of a
+# decibel; a sidecar read beyond this of its base scores' calibration was
+# read at another one
+CALIBRATION_TOLERANCE_DB = 1e-4
+
+
+def same_calibration(a, b) -> bool:
+ """Whether two level calibrations are one read (both absent, or within
+ ``CALIBRATION_TOLERANCE_DB``)."""
+ if a is None or b is None:
+ return a is None and b is None
+ return abs(float(a) - float(b)) <= CALIBRATION_TOLERANCE_DB
+
+
+def real_quality(d):
+ """Returns the pooled quality row of the real recordings, or None.
+
+ The equal mean of the four families' NISQA, so no family weighs by its
+ size. Its count is the smallest family's. None unless every family carries
+ the metric on every item it was asked for: a missing item is an incomplete
+ row, never a smaller mean.
+ """
+ values, counts = [], []
+ for family in REAL_FAMILIES:
+ cell = d.get(family) or {}
+ value = cell.get("nisqa_mos")
+ missing = (cell.get("metric_missing") or
+ {}).get("nisqa_mos", cell.get("n_missing", 0))
+ if (not isinstance(value, (int, float)) or not math.isfinite(value) or
+ missing):
+ return None
+ values.append(float(value))
+ counts.append((cell.get("metric_counts") or
+ {}).get("nisqa_mos", cell.get("n", 0)))
+ return {
+ "nisqa_mos": sum(values) / len(values),
+ "n": min(counts),
+ "metric_counts": {
+ "nisqa_mos": min(counts)
+ },
+ }
+
+
+def finite(o):
+ """Returns ``o`` with NaN as None, so the file is strict JSON.
+
+ Browsers' ``JSON.parse`` rejects NaN.
+ """
+ if isinstance(o, float):
+ return o if math.isfinite(o) else None
+ if isinstance(o, dict):
+ return {k: finite(v) for k, v in o.items()}
+ if isinstance(o, (list, tuple)):
+ return [finite(v) for v in o]
+ return o
+
+
+def record_outputs(path):
+ """Returns {item id: hash of the output samples scored}.
+
+ Read from a per-item record file; None when the file is absent (a public
+ clone holds the aggregate scores alone).
+ """
+ if not os.path.isfile(path):
+ return None
+ out = {}
+ with open(path, encoding="utf-8") as fh:
+ next(fh, None) # the header
+ for line in fh:
+ record = json.loads(line)
+ output = (record.get("identity") or {}).get("output")
+ if output:
+ out[record["id"]] = output
+ return out
+
+
+def _sidecar(results,
+ name,
+ ext,
+ set_id,
+ subset="all",
+ anchor_identity=None,
+ outputs=None):
+ """Returns a sidecar's content, or None when it may not be merged.
+
+ None when it is absent, was computed on another build of the set, on another
+ subset of it (a sidecar without a subset stamp counts as whole-set data), or
+ on other output samples than the base scores were (``outputs``: the base
+ records' hashes, when the per-item records are at hand), or read another
+ render. A stale or foreign sidecar must never overwrite fresh scores.
+ """
+ path = os.path.join(results, f"{name}{ext}")
+ if not os.path.exists(path):
+ return None
+ with open(path, encoding="utf-8") as fh:
+ side = json.load(fh)
+ scored = (record_outputs(path[:-len(".json")] +
+ ".items.jsonl") if outputs else None)
+ if scored:
+ differ = [
+ uid for uid, output in scored.items()
+ if outputs.get(uid, output) != output
+ ]
+ if differ:
+ print(
+ f"[warn] {os.path.basename(path)} was measured on other outputs"
+ f" than the base scores for {len(differ)} items (first:"
+ f" {differ[0]}): ignored, re-run the sidecar",
+ file=sys.stderr,
+ )
+ return None
+ if side.get("_set_id") != set_id:
+ print(
+ f"[warn] {os.path.basename(path)} was computed on set"
+ f" {str(side.get('_set_id'))[:12]}, metrics on {str(set_id)[:12]}:"
+ " ignored",
+ file=sys.stderr,
+ )
+ return None
+ if side.get("_subset", "all") != subset:
+ print(
+ f"[warn] {os.path.basename(path)} was computed on subset "
+ f"{side.get('_subset', 'all')!r}, metrics on {subset!r}: ignored",
+ file=sys.stderr,
+ )
+ return None
+ if anchor_identity is not None and any(
+ side.get(k) != anchor_identity.get(k)
+ for k in ("_anchors_version", "_anchors_sha256")):
+ raise ValueError(
+ f"{name}{ext}: anchor version differs from its base metrics")
+ if anchor_identity is not None and bool(side.get("_sealed")) != bool(
+ anchor_identity.get("_sealed")):
+ raise ValueError(
+ f"{name}{ext}: private/public scope differs from its base metrics")
+ if anchor_identity is not None and side.get(
+ "_outputs_sha256") != anchor_identity.get("_outputs_sha256"):
+ print(
+ f"[warn] {os.path.basename(path)} read another render than the base"
+ " scores: ignored, re-run the sidecar",
+ file=sys.stderr,
+ )
+ return None
+ return side
+
+
+def load(results):
+ """Returns each system's metrics.json with its sidecars merged in.
+
+ The NISQA, kept, residual, events and realx sidecars, and the pooled
+ quality of the real recordings (``real_quality``).
+
+ Every sidecar that reads the output gain must have read it at the base
+ scores' calibration (``_level_cal_db``); one that did not is refused, never
+ mixed in.
+ """
+ out = {}
+ for f in sorted(glob.glob(os.path.join(results, "*.metrics.json"))):
+ name = os.path.basename(f)[:-len(".metrics.json")]
+ with open(f, encoding="utf-8") as fh:
+ d = json.load(fh)
+ outputs = record_outputs(f[:-len(".metrics.json")] + ".items.jsonl")
+ d["_scorers"] = {"metrics": d.get("_scorer_sha256")}
+ for ext, pref in (
+ (".nisqa.json", "nisqa"),
+ (".kept.json", ("nv_", "mag_")),
+ (".residual.json", ("pause_", "floor_", "babble_resid")),
+ (".events.json", ("event_", "floor_resid", "voice_level")),
+ ):
+ side = _sidecar(
+ results,
+ name,
+ ext,
+ d.get("_set_id"),
+ d.get("_subset", "all"),
+ d,
+ outputs,
+ )
+ if side is None:
+ continue
+ if side.get("_selection"):
+ print(
+ f"[warn] {name}{ext} reads part of each condition"
+ f" ({side['_selection']}): ignored",
+ file=sys.stderr,
+ )
+ continue
+ d["_scorers"][ext.split(".")[1]] = side.get("_scorer_sha256")
+ if ext in CALIBRATED_SIDECARS and not same_calibration(
+ side.get("_level_cal_db"), d.get("_level_cal_db")):
+ raise ValueError(
+ f"{name}{ext}: read at another level calibration than its"
+ " base metrics: re-run the sidecar")
+ for cond, vals in side.items():
+ if isinstance(vals, dict):
+ d.setdefault(cond, {}).update({
+ k: v for k, v in vals.items() if k.startswith(pref)
+ })
+ # coverage per metric, the pooled rows included: the items
+ # carrying it (the sidecar's own count when it states one),
+ # and what the sidecar did not get back
+ counts = vals.get("metric_counts") or {}
+ keys = [
+ k for k in vals
+ if k.startswith(pref) and k not in ("n",)
+ ]
+ if "n" in vals:
+ d[cond].setdefault("metric_counts", {}).update(
+ {k: counts.get(k, vals["n"]) for k in keys})
+ if vals.get("n_missing"):
+ d[cond].setdefault("metric_missing", {}).update(
+ {k: vals["n_missing"] for k in keys})
+ # per-item absolute errors, averaged (levels.py)
+ for vals in d.values():
+ if isinstance(vals, dict):
+ for row, key in (
+ ("_hf_err", "hf_err_db"),
+ ("_level_err", "level_err_db"),
+ ):
+ if isinstance(vals.get(key), (int, float)):
+ vals[row] = float(vals[key])
+ derive_band_rows(d)
+ pooled = real_quality(d)
+ if pooled is not None:
+ d["_real_quality"] = pooled
+ rx = _sidecar(
+ results,
+ name,
+ ".realx.json",
+ d.get("_set_id"),
+ d.get("_subset", "all"),
+ d,
+ outputs,
+ )
+ if rx is not None and not same_calibration(rx.get("_level_cal_db"),
+ d.get("_level_cal_db")):
+ raise ValueError(
+ f"{name}.realx.json: read at another level calibration than its"
+ " base metrics: re-run the sidecar")
+ if rx is not None:
+ d["_scorers"]["realx"] = rx.get("_scorer_sha256")
+ items = rx.get("_items_primary") if rx is not None else None
+ d["_deletion"] = {
+ "pct": math.nan,
+ "primary_anchored": items is not None,
+ "items": items or {},
+ }
+ lvl = d.get("_level_cal_db")
+ if isinstance(lvl, (int, float)) and lvl == lvl:
+ for vals in d.values():
+ if isinstance(vals, dict):
+ for k in KEPT_KEYS:
+ if isinstance(vals.get(k), (int, float)):
+ vals[k] = float(vals[k]) - float(lvl)
+ d["_level_cal_applied_db"] = float(lvl)
+ out[name] = d
+ return out
+
+
+def get(d, cond, key):
+ """Returns one metric of one condition as a float, NaN when absent."""
+ v = d.get(cond, {}).get(key, math.nan)
+ return float(v) if isinstance(v, (int, float)) else math.nan
+
+
+# the band-limited rows and the index of the first band wholly above each
+# input's band (band edges at 0.5, 2, 4, 8, 12 and 16 kHz)
+BAND_LIMITED_ROWS = (("srsweep_8k", 3), ("srsweep_16k", 4), ("srsweep_24k", 5))
+
+
+def band_added_db(cell, first):
+ """Returns the energy a system adds above a band-limited input's band on one
+ row, in dB: the highest of the bands above the input's band, each read
+ against the reference band-limited the same way, less the mean of the bands
+ inside it, so a gain applied everywhere cancels. NaN without the bands.
+
+ The band axis beside the scores reads it (``band_added_db`` in the row's
+ cell, derived here at load from the scorer's per-band levels); the
+ restoration mark reads its maximum over the rows (``band_above_input_db``).
+ """
+ bands = (cell or {}).get("band_kept_db")
+ if not isinstance(bands, list) or len(bands) <= first:
+ return math.nan
+ levels = [
+ float(b) if isinstance(b, (int, float)) and math.isfinite(b) else None
+ for b in bands
+ ]
+ inside = [b for b in levels[:first] if b is not None]
+ above = [b for b in levels[first:] if b is not None]
+ if not inside or not above:
+ return math.nan
+ return max(above) - sum(inside) / len(inside)
+
+
+def band_above_input_db(d):
+ """Returns the most energy a system adds above a band-limited input's band,
+ over the band-limited rows (``band_added_db``). NaN when none was scored."""
+ values = [
+ v for v in (band_added_db(d.get(cond), first)
+ for cond, first in BAND_LIMITED_ROWS) if not math.isnan(v)
+ ]
+ return max(values) if values else math.nan
+
+
+def assigned_board(d, rule, default):
+ """Returns the board an assignment rule sends a system to, or None.
+
+ ``rule`` is the axis registry's (``admission.assignment``): a system whose
+ ``band_above_input_db`` exceeds ``above_db`` goes to ``board``, every other
+ to ``otherwise``; one without the band-limited rows to neither, since
+ missing evidence is not a kept band. Without a rule every system goes to
+ ``default``.
+ """
+ if not rule:
+ return default
+ value = band_above_input_db(d)
+ if math.isnan(value):
+ return None
+ return rule["board"] if value > rule["above_db"] else rule["otherwise"]
+
+
+def derive_band_rows(d):
+ """Writes ``band_added_db`` into each band-limited row's cell of one system,
+ with its coverage: the items that carry the per-band levels."""
+ for cond, first in BAND_LIMITED_ROWS:
+ cell = d.get(cond)
+ value = band_added_db(cell, first)
+ if cell is None or math.isnan(value):
+ continue
+ cell["band_added_db"] = value
+ if "n" in cell:
+ counts = cell.setdefault("metric_counts", {})
+ counts["band_added_db"] = counts.get("band_kept_db", cell["n"])
+
+
+def partial_passes(scores):
+ """Returns {system: its selection} for a filtered scoring pass.
+
+ Score files of a pass restricted with ``--conds`` or ``--limit``: a debug
+ look at part of the set, never a row of a board.
+ """
+ selected = {n: d.get("_selection") for n, d in scores.items()}
+ return {n: selection for n, selection in selected.items() if selection}
+
+
+def render_problem(scores, results):
+ """Returns why the scores do not fit the stamped renders, or None.
+
+ Each system's base scores must have read the outputs its stamp vouches for
+ (``outputs_sha256``), so a render replaced after scoring is never shown with
+ the scores of the one before.
+ """
+ stale = sorted(
+ n for n, d in scores.items()
+ if d.get("_outputs_sha256") != common.outputs_digest(n, results))
+ if stale:
+ return (f"the scores of {', '.join(stale)} read other audio than the"
+ " render stamped now: re-score them")
+ return None
+
+
+def scorer_problem(scores):
+ """Returns why the scores cannot share one board, or None.
+
+ Each kind of score file (the base metrics and every sidecar) must come from
+ one implementation of its scorer.
+ """
+ for kind in ("metrics", "nisqa", "kept", "residual", "events", "realx"):
+ digests = {
+ n: (d.get("_scorers") or {}).get(kind) for n, d in scores.items()
+ }
+ known = {v for v in digests.values() if v}
+ if len(known) > 1:
+ groups = {}
+ for n, v in digests.items():
+ groups.setdefault(str(v)[:12], []).append(n)
+ return (
+ f"the {kind} files come from {len(known)} implementations of"
+ f" their scorer ({groups}): re-score so one implementation"
+ " reads every system")
+ return None
diff --git a/bench/scripts/scorekept.py b/bench/scripts/scorekept.py
new file mode 100644
index 0000000..03ebeb6
--- /dev/null
+++ b/bench/scripts/scorekept.py
@@ -0,0 +1,447 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""What the voice kept where the main scorer does not look.
+
+The vocal sounds that are not speech, and the spectrum of speech that needed no
+cleaning.
+
+ python bench/scripts/scorekept.py [--systems a,b]
+
+**Voice outside speech** (the ``nonverbal`` conditions). The main scorer reads
+retention over the blocks a voice-activity detector calls speech, so a laugh, a
+breath or a sigh it does not call speech is never read. Here the blocks are the
+rest of the voice: the 100 ms blocks of the clean recording that hold sound
+(within ``VOCAL_DB`` of its loudest block), that the detector leaves out, and
+that the bed does not bury (the voice of the block no more than ``BURIED_DB``
+under the bed of the block, the lowest level the set mixes at; nobody keeps what
+nobody could hear). The recording is one voice in a quiet room, so whatever
+sounds there is that voice. A block is lost when the part of the output that is
+coherent with it, less the system's level calibration, falls under
+``levels.LOST_DB``: the main scorer's rule for a speech block (``levels.lost``).
+``nv_lost_pct`` is the share of those blocks that are lost, pooled over the
+condition, so a long laugh weighs what it lasts. Consecutive blocks are one
+event, and ``nv_events_lost_pct`` reads the same for whole events (the output
+projected on the recording over the event).
+
+**Clean-speech magnitude fidelity** (the ``clean`` condition). ``mag_snr`` is
+the energy of the input's magnitude spectrogram over the energy of its
+difference from the output's, in dB, after the one gain that best matches them:
+a signal-to-error ratio that does not read phase. A waveform ratio calls a
+change of phase an error; this one counts only a spectrum that changed.
+``mag_snr_nb`` reads the same inside 0-8 kHz.
+
+Delay and polarity are undone as the main scorer does. Output:
+``<system>.kept.json`` and the per-item records ``<system>.kept.items.jsonl``
+beside the other sidecars; views derive from the whole-set records
+(``--aggregate-only``) and unchanged items are reused by content.
+"""
+
+import argparse
+import collections
+import glob
+import json
+import os
+import sys
+
+import numpy as np
+import torch
+
+# pylint: disable=wrong-import-position
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import anchors
+import common
+import levels
+import observations
+import scorebench
+
+SCORER_SHA256 = observations.implementation(__file__, common.__file__,
+ observations.__file__,
+ scorebench.__file__,
+ levels.__file__)
+
+FRAME = 4800 # 100 ms at 48 kHz: the scorer's block
+# a block holds a vocal sound when it sits within this of the loudest block
+VOCAL_DB = 30.0
+# and is there to keep when the voice is no further than this under the bed
+BURIED_DB = -10.0
+N_FFT, HOP = 2048, 480
+MAG_KEYS = ("mag_snr", "mag_snr_nb")
+# derived per view, under the view's level calibration
+ITEM_KEYS = ("nv_lost", "nv_lost_pct")
+
+
+def family(condition: str) -> str:
+ return condition.split("@", 1)[0]
+
+
+def wanted(row: dict) -> bool:
+ if not row.get("clean_path"):
+ return False
+ condition = row["condition"]
+ return family(condition).startswith("nonverbal") or condition == "clean"
+
+
+def vocal_blocks(ref: torch.Tensor, speech: torch.Tensor,
+ mix: torch.Tensor) -> torch.Tensor:
+ """Returns the blocks of a clean recording that hold vocal sound to keep.
+
+ They hold sound, are not speech and are not buried.
+
+ Args:
+ ref: The clean recording at 48 kHz.
+ speech: The detector's speech blocks of it (bool, one per 100 ms).
+ mix: The mixture the recording sits in, sample-aligned with it (the
+ recording itself when nothing was added).
+
+ Returns:
+ A bool mask over the recording's whole blocks.
+ """
+ _, _, loud = common.coherent_blocks(ref, ref, FRAME, VOCAL_DB)
+ n = len(loud)
+ voice = ref[:n * FRAME].reshape(-1, FRAME).pow(2).mean(1)
+ residual = mix[:n * FRAME] - ref[:n * FRAME]
+ bed = residual.reshape(-1, FRAME).pow(2).mean(1)
+ heard = 10 * torch.log10((voice + 1e-12) / (bed + 1e-12)) >= BURIED_DB
+ mask = torch.zeros(n, dtype=torch.bool)
+ k = min(n, len(speech))
+ mask[:k] = loud[:k] & ~speech[:k] & heard[:k]
+ return mask
+
+
+def events(mask: torch.Tensor) -> list:
+ """Returns the runs of consecutive blocks in a mask.
+
+ As [(first block, last block + 1)].
+ """
+ out, start = [], None
+ for b, on in enumerate(mask.tolist()):
+ if on and start is None:
+ start = b
+ elif not on and start is not None:
+ out.append((start, b))
+ start = None
+ if start is not None:
+ out.append((start, len(mask)))
+ return out
+
+
+def event_kept_db(out: torch.Tensor, ref: torch.Tensor, span: tuple) -> float:
+ """Returns how much of one event the output keeps, in dB.
+
+ 20 log10 of the projection of the output on the recording over the event.
+ """
+ start, end = span[0] * FRAME, span[1] * FRAME
+ o, r = out[start:end], ref[start:end]
+ o, r = o - o.mean(), r - r.mean()
+ coefficient = float((o * r).sum() / (r.pow(2).sum() + 1e-9))
+ return float(np.clip(20 * np.log10(max(coefficient, 1e-4)), -80.0, 20.0))
+
+
+def mag_snr(out: torch.Tensor, ref: torch.Tensor) -> float:
+ """Returns the magnitude spectrograms' signal-to-error ratio, in dB.
+
+ After the best single gain.
+ """
+ n = min(len(out), len(ref))
+ if n < N_FFT:
+ return float("nan")
+ window = torch.hann_window(N_FFT)
+ x = torch.stft(ref[:n], N_FFT, HOP, window=window, return_complex=True)
+ y = torch.stft(out[:n], N_FFT, HOP, window=window, return_complex=True)
+ x, y = x.abs(), y.abs()
+ scale = float((x * y).sum() / (y * y).sum().clamp(min=1e-12))
+ error = (scale * y - x).pow(2).sum().clamp(min=1e-12)
+ ratio = float(10 * torch.log10(x.pow(2).sum().clamp(min=1e-12) / error))
+ return min(120.0, max(-20.0, ratio))
+
+
+def score_item(it: dict, out: torch.Tensor, vad) -> tuple:
+ """(metrics, measurements) of one item after the main scorer's alignment."""
+ ref, mix = common.load48(it["clean_path"]), common.load48(it["mix_path"])
+ n = min(len(ref), len(mix))
+ lag, sign = common.best_alignment(out, ref)
+ o, r = sign * common.apply_lag(out, lag, n), ref[:n]
+ if it["condition"] == "clean":
+ return {
+ "mag_snr": mag_snr(o, r),
+ "mag_snr_nb": mag_snr(common.nb8k(o), common.nb8k(r)),
+ }, {}
+ r16, segments = scorebench.speech_segments(vad, ref, it["clean_path"])
+ active = torch.zeros(len(r16), dtype=torch.bool)
+ for s in segments:
+ active[s["start"]:s["end"]] = True
+ mask = vocal_blocks(r, common.block_mask(active, len(r) // FRAME), mix[:n])
+ kept, _, _ = common.coherent_blocks(o, r, FRAME)
+ spans = events(mask)
+ return {
+ "nv_blocks": int(mask.sum()),
+ "nv_events": len(spans)
+ }, {
+ "nv_kept_db": [float(v) for v in kept[mask[:len(kept)]]],
+ "nv_event_kept_db": [event_kept_db(o, r, span) for span in spans],
+ "nv_event_blocks": [b - a for a, b in spans],
+ }
+
+
+def assemble(name: str,
+ rows: list,
+ reuse: dict | None = None,
+ hashes=None,
+ vad=None) -> list:
+ """Returns per-item records over ``rows``.
+
+ Reused by content identity where output, mixture and reference are unchanged
+ since an earlier pass of this sidecar.
+ """
+ hashes = hashes or common.file_hashes()
+ reuse = reuse or {}
+ records, counts = [], collections.Counter()
+ for it in rows:
+ record = observations.item(it)
+ records.append(record)
+ op = (it["mix_path"] if name == "INPUT" else
+ (it["clean_path"] if name == "REF" else os.path.join(
+ common.OUT_ROOT, name, it["id"])))
+ if not os.path.exists(op):
+ record["output_status"] = "missing"
+ continue
+ out = common.load48(op)
+ record["identity"] = scorebench.item_identity(
+ it, scorebench.sample_hash(out), hashes)
+ old = reuse.get(scorebench.reuse_key(record["identity"]))
+ if old is not None:
+ record["metrics"] = {
+ k: v for k, v in old["metrics"].items() if k not in ITEM_KEYS
+ }
+ record["measurements"] = dict(old.get("measurements") or {})
+ counts["reused"] += 1
+ continue
+ if vad is None and it["condition"] != "clean":
+ vad = common.Vad()
+ record["metrics"], record["measurements"] = score_item(it, out, vad)
+ counts["scored"] += 1
+ if reuse:
+ print(
+ f" reused {counts['reused']} records, scored {counts['scored']}"
+ " items",
+ flush=True,
+ )
+ return records
+
+
+def level_calibration(results: str, name: str) -> float:
+ """Returns the system's level calibration from its base scores.
+
+ Kept levels are read less it.
+ """
+ path = os.path.join(results, f"{name}.metrics.json")
+ if not os.path.exists(path):
+ raise SystemExit(
+ f"{path} is missing: score {name} with scorebench.py first (kept"
+ " levels are read less the system's level calibration)")
+ with open(path, encoding="utf-8") as fh:
+ doc = json.load(fh)
+ if (doc.get("_set_id") != common.set_id() or
+ doc.get("_subset", "all") != common.SUBSET):
+ raise SystemExit(
+ f"{path} was scored on another build or subset of the set")
+ return float(doc.get("_level_cal_db") or 0.0)
+
+
+def aggregate(records: list, rows: list, level_cal_db: float) -> dict:
+ """Returns the sidecar file for ``rows``.
+
+ Every item's lost share is written into its record. Pure, so any view of the
+ set derives from the whole-set records under its own level calibration, as
+ the main scorer's lost-block share does.
+ """
+ by_id = {r["id"]: r for r in records}
+ by = collections.defaultdict(list)
+ for r in rows:
+ if wanted(r):
+ by[r["condition"]].append(r)
+ out = {}
+ for cond, items in sorted(by.items()):
+ have = [
+ by_id[r["id"]]
+ for r in items
+ if r["id"] in by_id and by_id[r["id"]].get("output_status") == "ok"
+ and by_id[r["id"]].get("metrics")
+ ]
+ if not have:
+ continue
+ # metric_counts: the items that carry the observation, which the board's
+ # coverage rule reads instead of the items scored (a recording without a
+ # laugh observes nothing)
+ cell = {
+ "n": len(have),
+ "n_missing": len(items) - len(have),
+ "metric_counts": {},
+ }
+ if cond == "clean":
+ for key in MAG_KEYS:
+ vals = [r["metrics"].get(key) for r in have]
+ vals = [
+ v for v in vals
+ if isinstance(v, (int, float)) and np.isfinite(v)
+ ]
+ if vals:
+ cell[key] = float(np.mean(vals))
+ cell["metric_counts"][key] = len(vals)
+ out[cond] = cell
+ continue
+ lost, total, event_levels, n_items = 0, 0, [], 0
+ for rec in have:
+ measured = rec.get("measurements") or {}
+ blocks = np.array(measured.get("nv_kept_db") or [], dtype=float)
+ for key in ITEM_KEYS:
+ rec["metrics"].pop(key, None)
+ gone = int(np.sum(levels.lost(blocks, level_cal_db)))
+ # with nv_blocks, what a paired composite pools
+ rec["metrics"]["nv_lost"] = gone
+ if len(blocks):
+ rec["metrics"]["nv_lost_pct"] = 100.0 * gone / len(blocks)
+ n_items += 1
+ lost, total = lost + gone, total + len(blocks)
+ event_levels += list(measured.get("nv_event_kept_db") or [])
+ if not total:
+ continue
+ events_lost = levels.lost(event_levels, level_cal_db)
+ cell.update(
+ nv_lost_pct=100.0 * lost / total,
+ nv_events_lost_pct=100.0 * float(np.mean(events_lost)),
+ nv_items=n_items,
+ nv_blocks=total,
+ nv_events=len(events_lost),
+ metric_counts={
+ "nv_lost_pct": n_items,
+ "nv_events_lost_pct": n_items,
+ },
+ )
+ out[cond] = cell
+ return out
+
+
+def write(name: str,
+ records: list,
+ out: dict,
+ rows: list,
+ level_cal_db: float,
+ outputs: str | None = None) -> None:
+ observations.sidecar(
+ os.path.join(common.RESULTS, f"{name}.kept.items.jsonl"),
+ records,
+ name,
+ common.set_id(),
+ common.SUBSET,
+ common.is_sealed(rows),
+ SCORER_SHA256,
+ outputs_sha256=outputs,
+ )
+ if out:
+ # the leaderboard ignores a sidecar from another build
+ out["_set_id"] = common.set_id()
+ out["_subset"] = common.SUBSET # and one from another subset of the set
+ out["_level_cal_db"] = level_cal_db
+ out["_scorer_sha256"] = SCORER_SHA256
+ out["_outputs_sha256"] = outputs # the render these records read
+ out.update(anchors.stamp())
+ out["_sealed"] = common.is_sealed(rows)
+ path = os.path.join(common.RESULTS, f"{name}.kept.json")
+ tmp = f"{path}.{os.getpid()}.tmp"
+ with open(tmp, "w", encoding="utf-8") as fh:
+ json.dump(out, fh, indent=1)
+ os.replace(tmp, path)
+
+
+def describe(out: dict) -> str:
+ shown = []
+ for cond in sorted(c for c in out if not c.startswith("_")):
+ cell = out[cond]
+ if "nv_lost_pct" in cell:
+ shown.append(
+ f"{cond}: {cell['nv_lost_pct']:.1f} % of {cell['nv_blocks']}"
+ f" blocks, {cell['nv_events_lost_pct']:.1f} % of"
+ f" {cell['nv_events']} events lost")
+ elif "mag_snr" in cell:
+ shown.append(f"{cond}: magnitude SNR {cell['mag_snr']:.1f} dB")
+ return " ".join(shown)
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--systems", default="")
+ ap.add_argument(
+ "--reuse-from",
+ default="",
+ metavar="DIR",
+ help=(
+ "results of an earlier pass of this sidecar: unchanged items keep "
+ "their records"),
+ )
+ ap.add_argument(
+ "--aggregate-only",
+ default="",
+ metavar="DIR",
+ help="derive this subset's files from the whole-set records under DIR",
+ )
+ a = ap.parse_args()
+ rows = common.manifest()
+ common.guard_private_results(rows)
+ selected = [r for r in rows if wanted(r)]
+ systems = [s for s in a.systems.split(",") if s] or sorted(
+ os.path.basename(d)
+ for d in glob.glob(common.OUT_ROOT + "/*")
+ if os.path.isdir(d))
+ os.makedirs(common.RESULTS, exist_ok=True)
+ for name in systems:
+ if a.aggregate_only:
+ src = os.path.join(a.aggregate_only, f"{name}.kept.items.jsonl")
+ ids = {r["id"] for r in selected}
+ problem, source, records = scorebench.view_records(
+ src, name, ids, SCORER_SHA256)
+ if problem:
+ print(f"skip {name}: {problem}", flush=True)
+ continue
+ outputs = source.get("outputs_sha256")
+ else:
+ exempt = name in ("INPUT", "REF")
+ problem = not exempt and scorebench.render_problem(name)
+ if problem:
+ print(f"skip {name}: {problem}", flush=True)
+ continue
+ own = os.path.join(common.RESULTS, f"{name}.kept.items.jsonl")
+ reuse, why = {}, "no earlier records"
+ if a.reuse_from:
+ reuse, why = scorebench.reuse_index(
+ os.path.join(a.reuse_from, f"{name}.kept.items.jsonl"),
+ name,
+ SCORER_SHA256,
+ )
+ why = f"reuse from {a.reuse_from}: {why}"
+ # never skipped as scored: re-validated item by item
+ elif os.path.isfile(own):
+ reuse, why = scorebench.reuse_index(own, name, SCORER_SHA256)
+ why = f"existing records: {why}"
+ print(f" {why}", flush=True)
+ records = assemble(name, selected, reuse=reuse)
+ outputs = common.outputs_digest(name)
+ level = level_calibration(common.RESULTS, name)
+ out = aggregate(records, selected, level)
+ write(name, records, out, rows, level, outputs)
+ print(f"{name:24s} {describe(out)}", flush=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/bench/scripts/scorenisqa.py b/bench/scripts/scorenisqa.py
new file mode 100644
index 0000000..c2c30e0
--- /dev/null
+++ b/bench/scripts/scorenisqa.py
@@ -0,0 +1,443 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""NISQA v2 no-reference quality sidecar over wavs already on disk.
+
+Every other metric is reference-based, so a system that removes the noise but
+leaves the speech buzzy, warbly or spectrally scooped still scores well;
+NISQA's discontinuity and coloration dimensions are the "cleaned it but it
+hurts to listen to" axes. Never read NISQA alone: it rewards a clean-sounding
+rewrite even when speaker identity is destroyed.
+
+Usage: scorenisqa.py [--systems a,b] [--conds substr,substr] [--limit N]
+Output: <BENCH_RESULTS>/<system>.nisqa.json
+"""
+
+import argparse
+import collections
+import glob
+import json
+import math
+import os
+import sys
+
+import numpy as np
+
+# pylint: disable=wrong-import-position
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import anchors
+import common
+import observations
+import scorebench
+
+SCORER_SHA256 = observations.implementation(__file__, common.__file__,
+ observations.__file__,
+ scorebench.__file__)
+
+KEYS = ("mos", "noisiness", "discontinuity", "coloration", "loudness")
+
+# every real family: the board reads their equal mean (scorefiles.real_quality)
+DEFAULT_CONDS = ("babble@+4,babble@+0,ambience@-5,clean,real_noisy,"
+ "real_dirty,real_multi,real_wild,expressive_tail@-5,"
+ "reverb_real")
+
+# a primary-speaker segment shorter than this is not scored on its own
+MIN_PRIMARY_S = 2.0
+
+
+def primary_segments(root=None, rows=None):
+ """Returns the input's usable segments and primary-speaker flags per item.
+
+ Per real item, from the deletion sidecar's records of INPUT: boundaries
+ frozen on the input side, identical for every output. The sidecar must be
+ INPUT's, of this set and the whole set, made by the current deletion scorer
+ with speaker anchoring, and cover every real item of the manifest; stale or
+ unanchored boundaries are refused.
+ """
+ # pylint: disable-next=import-outside-toplevel
+ import scorerealx
+
+ path = os.path.join(root or common.RESULTS, "INPUT.realx.items.jsonl")
+ if not os.path.isfile(path):
+ raise SystemExit(f"{path} is missing: score INPUT with scorerealx.py"
+ " --primary-anchor first")
+ metadata, records = observations.read(path)
+ if metadata.get("system") != "INPUT":
+ raise SystemExit(f"{path}: not INPUT's records")
+ if (metadata.get("set_id") != common.set_id() or
+ metadata.get("subset", "all") != "all"):
+ raise SystemExit(
+ f"{path}: records of set {str(metadata.get('set_id'))[:8]} subset "
+ f"{metadata.get('subset', 'all')!r}, not the whole current set")
+ if metadata.get("scorer_sha256") != scorerealx.SCORER_SHA256:
+ raise SystemExit(
+ f"{path}: made by another deletion scorer; re-run scorerealx.py"
+ " first")
+ real_ids = {
+ r["id"]
+ for r in (rows if rows is not None else common.manifest(which="all"))
+ if r["condition"].startswith("real")
+ }
+ have = {r["id"] for r in records}
+ if not real_ids <= have:
+ raise SystemExit(
+ f"{path} covers {len(real_ids & have)} of {len(real_ids)} real"
+ " items: re-run scorerealx.py --primary-anchor for INPUT")
+ # a pass without --primary-anchor leaves the segments but flags none as the
+ # primary speaker and stores no anchor similarities: that is not a recording
+ # without speech, it is an unanchored pass, and its empty primary set would
+ # silently score nothing
+ unanchored = [
+ r["id"]
+ for r in records
+ if (r.get("measurements") or {}).get("seg_start") and
+ not (r.get("measurements") or {}).get("anchor_sims")
+ ]
+ if unanchored:
+ raise SystemExit(
+ f"{path}: {len(unanchored)} records with speech segments carry no"
+ f" speaker anchoring (first: {unanchored[0]}): re-run scorerealx.py"
+ " --primary-anchor for INPUT")
+ out = {}
+ for r in records:
+ m = r.get("measurements") or {}
+ if m.get("seg_start") and m.get("seg_primary"):
+ out[r["id"]] = [(int(b), int(e)) for b, e, p in zip(
+ m["seg_start"], m["seg_end"], m["seg_primary"]) if p]
+ if not out:
+ raise SystemExit(
+ f"{path} carries no segment boundaries: re-run scorerealx.py")
+ return out
+
+
+def primary_quality(out, segments, min_seconds=MIN_PRIMARY_S):
+ """Returns NISQA over the primary speaker's segments that stand alone.
+
+ Segments of ``out`` (16 kHz indices, cut at 48 kHz) long enough to stand
+ alone; the item's value is their duration-weighted mean, with the eligible
+ duration and its share of the primary speaker's total. Segments are never
+ joined: a stitched signal has discontinuities of its own, which is what a
+ quality model reacts to.
+ """
+ total = sum(e - b for b, e in segments) / 16000
+ eligible = [(b, e) for b, e in segments if (e - b) / 16000 >= min_seconds]
+ if not eligible:
+ return {
+ "nisqa_primary_eligible_s": 0.0,
+ "nisqa_primary_coverage": 0.0 if total else float("nan"),
+ }
+ weights, values = [], []
+ for b, e in eligible:
+ mos = common.nisqa(out[b * 3:e * 3])[0]
+ if mos == mos:
+ weights.append((e - b) / 16000)
+ values.append(mos)
+ covered = sum((e - b) for b, e in eligible) / 16000
+ return {
+ "nisqa_mos_primary": (float(np.average(values, weights=weights))
+ if values else float("nan")),
+ "nisqa_primary_eligible_s": covered,
+ "nisqa_primary_coverage": covered / total if total else float("nan"),
+ }
+
+
+def assemble(name, rows, reuse=None, hashes=None, primary=None):
+ """Returns per-item NISQA records over ``rows``.
+
+ An item whose output samples are unchanged since an earlier pass of this
+ sidecar keeps its record (``reuse``, by content identity). With ``primary``
+ (real items' frozen segments), a real item also gets the primary-speaker
+ values.
+ """
+ hashes = hashes or common.file_hashes()
+ reuse = reuse or {}
+ records, counts = [], collections.Counter()
+ for it in rows:
+ record = observations.item(it)
+ records.append(record)
+ path = (it["mix_path"] if name == "INPUT" else os.path.join(
+ common.OUT_ROOT, name, it["id"]))
+ if not os.path.exists(path):
+ record["output_status"] = "missing"
+ continue
+ out = common.load48(path)
+ record["identity"] = scorebench.item_identity(
+ it, scorebench.sample_hash(out), hashes)
+ segs = ((primary or {}).get(it["id"])
+ if primary is not None and not it.get("clean_path") else None)
+ if primary is not None and not it.get("clean_path"):
+ record["identity"]["semantics"]["primary_segments"] = (
+ anchors.digest(segs or []))
+ old = reuse.get(scorebench.reuse_key(record["identity"]))
+ if old is not None:
+ record["metrics"] = dict(measured(old))
+ record["output_status"] = old["output_status"]
+ counts["reused"] += 1
+ continue
+ values = common.nisqa(out)
+ record["metrics"] = observations.finite({
+ f"nisqa_{k}": v for k, v in zip(KEYS, values)
+ })
+ if segs is not None:
+ record["metrics"].update(
+ observations.finite(primary_quality(out, segs)))
+ if not np.isfinite(values[0]):
+ record["output_status"] = "metric_failed"
+ counts["scored"] += 1
+ if reuse:
+ print(
+ f" reused {counts['reused']} records, scored {counts['scored']}"
+ " items",
+ flush=True,
+ )
+ return records
+
+
+def measured(record):
+ """Returns a record's NISQA values, inside the published cohort or not.
+
+ Values in the cohort sit under ``metrics``; those outside it are kept under
+ ``measurements``, so a paired comparison reads the cohort the board reads.
+ """
+ return (record.get("metrics") or
+ record.get("measurements", {}).get("nisqa") or {})
+
+
+def cohort(rows, want, limit):
+ """Returns the items whose NISQA the published mean reads.
+
+ Every item of each condition, or the first ``limit`` of each when a limit is
+ given (a quick look, never published).
+ """
+ by = collections.defaultdict(list)
+ for r in rows:
+ if r["condition"] in want:
+ by[r["condition"]].append(r)
+ return {r["id"] for c in want for r in (by[c][:limit] if limit else by[c])}
+
+
+def mark(records, members):
+ """Puts each record's values where its cohort membership says.
+
+ ``metrics`` inside the cohort, ``measurements`` outside it, so every reader
+ of per-item metrics sees the board's cohort.
+ """
+ for record in records:
+ values = measured(record)
+ record["cohort"] = record["id"] in members
+ record["metrics"] = dict(values) if record["cohort"] else {}
+ record["measurements"] = ({} if record["cohort"] else ({
+ "nisqa": dict(values)
+ } if values else {}))
+
+
+def aggregate(records, rows, want, limit):
+ """Returns the sidecar file for ``rows``.
+
+ Per condition, the mean over its items that carry a measurement (the first
+ ``limit`` when one is given), with the condition's size beside it. Pure: any
+ view of the set is this function over the whole-set records of its items.
+ """
+ by_id = {r["id"]: r for r in records}
+ by = collections.defaultdict(list)
+ for r in rows:
+ if r["condition"] in want:
+ by[r["condition"]].append(r)
+ out = {}
+ for cond in want:
+ selected = by[cond][:limit] if limit else by[cond]
+ values = [
+ measured(by_id[r["id"]])
+ for r in selected
+ if r["id"] in by_id and measured(by_id[r["id"]])
+ ]
+ if not values:
+ continue
+ a = np.array(
+ [[observations.revive(m.get(f"nisqa_{k}"))
+ for k in KEYS]
+ for m in values],
+ dtype=float,
+ )
+ out[cond] = {
+ f"nisqa_{k}": float(np.nanmean(a[:, i])) for i, k in enumerate(KEYS)
+ }
+ out[cond]["n"] = int(np.isfinite(a[:, 0]).sum())
+ out[cond]["n_expected"] = len(selected)
+ out[cond]["n_missing"] = out[cond]["n_expected"] - out[cond]["n"]
+ prim = [
+ observations.revive(m["nisqa_mos_primary"])
+ for m in values
+ if "nisqa_mos_primary" in m
+ ]
+ prim = [v for v in prim if v == v]
+ # the diagnostic: quality where the primary speaker talks, on frozen
+ # segments
+ if prim:
+ out[cond]["nisqa_mos_primary"] = float(np.mean(prim))
+ out[cond]["nisqa_primary_items"] = len(prim)
+ eligible = [
+ observations.revive(m.get("nisqa_primary_eligible_s"))
+ for m in values
+ ]
+ # an item without primary segments revives to NaN, which is
+ # truthy: only the finite durations are summed
+ out[cond]["nisqa_primary_eligible_s"] = float(
+ sum(v for v in eligible
+ if isinstance(v, (int, float)) and math.isfinite(v)))
+ cov = [
+ observations.revive(m.get("nisqa_primary_coverage"))
+ for m in values
+ if m.get("nisqa_primary_coverage") is not None
+ ]
+ cov = [c for c in cov if c == c]
+ out[cond]["nisqa_primary_coverage"] = (float(np.mean(cov))
+ if cov else float("nan"))
+ return out
+
+
+def write(name, records, out, rows, members, limit=0, outputs=None):
+ mark(records, members)
+ observations.sidecar(
+ os.path.join(common.RESULTS, f"{name}.nisqa.items.jsonl"),
+ records,
+ name,
+ common.set_id(),
+ common.SUBSET,
+ common.is_sealed(rows),
+ SCORER_SHA256,
+ outputs_sha256=outputs,
+ )
+ if out:
+ # the leaderboard ignores a sidecar from another build
+ out["_set_id"] = common.set_id()
+ out["_subset"] = common.SUBSET # and one from another subset of the set
+ out.update(anchors.stamp())
+ out["_sealed"] = common.is_sealed(rows)
+ out["_scorer_sha256"] = SCORER_SHA256
+ out["_outputs_sha256"] = outputs # the render these records read
+ # the first items of each condition: a quick look, never a board row
+ if limit:
+ out["_selection"] = {"limit": limit}
+ # whole or absent: parallel passes each re-validate INPUT
+ path = os.path.join(common.RESULTS, f"{name}.nisqa.json")
+ tmp = f"{path}.{os.getpid()}.tmp"
+ with open(tmp, "w", encoding="utf-8") as f:
+ json.dump(out, f, indent=1)
+ os.replace(tmp, path)
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--systems", default="")
+ ap.add_argument("--conds", default=DEFAULT_CONDS)
+ ap.add_argument(
+ "--limit",
+ type=int,
+ default=0,
+ help=("items per condition the mean reads (0, the published rule: every"
+ " item); every item of the conditions is scored, so a view can be"
+ " derived"),
+ )
+ ap.add_argument(
+ "--reuse-from",
+ default="",
+ metavar="DIR",
+ help=(
+ "results of an earlier pass of this sidecar: unchanged outputs keep"
+ " their records"),
+ )
+ ap.add_argument(
+ "--aggregate-only",
+ default="",
+ metavar="DIR",
+ help="derive this subset's files from the whole-set records under DIR",
+ )
+ ap.add_argument(
+ "--segments",
+ choices=("clip", "primary"),
+ default="clip",
+ help=(
+ "primary: also score each real item's primary-speaker segments on"
+ " their own (boundaries frozen from the input's deletion sidecar),"
+ " a diagnostic"),
+ )
+ args = ap.parse_args()
+
+ want = [c for c in args.conds.split(",") if c]
+ rows = common.manifest()
+ common.guard_private_results(rows)
+ selected = [r for r in rows if r["condition"] in want]
+
+ systems = [s for s in args.systems.split(",") if s] or sorted(
+ os.path.basename(d)
+ for d in glob.glob(common.OUT_ROOT + "/*")
+ if os.path.isdir(d))
+ if systems != ["REF"]:
+ systems = ["INPUT"] + [s for s in systems if s != "INPUT"]
+ os.makedirs(common.RESULTS, exist_ok=True)
+ for sysname in systems:
+ if args.aggregate_only:
+ src = os.path.join(args.aggregate_only,
+ f"{sysname}.nisqa.items.jsonl")
+ ids = {r["id"] for r in selected}
+ problem, source, records = scorebench.view_records(
+ src, sysname, ids, SCORER_SHA256)
+ if problem:
+ print(f"skip {sysname}: {problem}", flush=True)
+ continue
+ outputs = source.get("outputs_sha256")
+ else:
+ problem = sysname != "INPUT" and scorebench.render_problem(sysname)
+ if problem:
+ print(f"skip {sysname}: {problem}", flush=True)
+ continue
+ own = os.path.join(common.RESULTS, f"{sysname}.nisqa.items.jsonl")
+ reuse, why = {}, "no earlier records"
+ if args.reuse_from:
+ reuse, why = scorebench.reuse_index(
+ os.path.join(args.reuse_from,
+ f"{sysname}.nisqa.items.jsonl"),
+ sysname,
+ SCORER_SHA256,
+ )
+ why = f"reuse from {args.reuse_from}: {why}"
+ # never skipped as scored: re-validated item by item
+ elif os.path.isfile(own):
+ reuse, why = scorebench.reuse_index(own, sysname, SCORER_SHA256)
+ why = f"existing records: {why}"
+ print(f" {why}", flush=True)
+ primary = primary_segments() if args.segments == "primary" else None
+ records = assemble(sysname, selected, reuse=reuse, primary=primary)
+ outputs = common.outputs_digest(sysname)
+ out = aggregate(records, selected, want, args.limit)
+ write(
+ sysname,
+ records,
+ out,
+ rows,
+ cohort(selected, want, args.limit),
+ args.limit,
+ outputs,
+ )
+ if out:
+ print(
+ f"{sysname:24s} " +
+ " ".join(f"{c}: mos {out[c]['nisqa_mos']:.2f}" for c in want
+ if c in out),
+ flush=True,
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/bench/scripts/scorerealx.py b/bench/scripts/scorerealx.py
new file mode 100644
index 0000000..fcc5b74
--- /dev/null
+++ b/bench/scripts/scorerealx.py
@@ -0,0 +1,609 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Deleted-rate over the real-recording conditions, pooled, as a sidecar.
+
+Deleted-rate is a RARE BINARY event over VAD speech segments; the 24-file
+conditions alone give confidence intervals too wide to separate systems, so
+this pools every real condition (~900 segments) and reports a 95%
+Clopper-Pearson interval.
+
+Primary-speaker anchoring (--primary-anchor): a deleted BACKGROUND voice is
+an isolator working as intended; only a deleted PRIMARY-speaker segment is a
+defect. Each segment's INPUT audio is embedded (WavLM-SV) and compared to the
+file's anchor segment (max energy x duration); deletions are then charged only
+for primary segments (sim >= threshold). A denoiser that keeps every voice
+scores identically under both definitions. The board pools the
+primary-anchored counts (``_items_primary``) over the frozen INPUT cohort
+(``ranking.pool_deletion``).
+
+A segment is deleted when the output's energy over it, with the system's output
+gain undone (``levels.deleted`` at the base scores' ``_level_cal_db``), is more
+than 10 dB under the input's: a louder or quieter output convention neither
+hides nor invents a deletion. The records keep every segment's raw drop, so any
+view re-reads them at its own calibration.
+
+Every segment the detector reports counts (``MIN_SEG``, its own minimum), so a
+deleted short word costs what a long one does; this is segment coverage, not
+word-level detection, and a word removed inside a longer segment that keeps
+its energy is not seen here. A segment that touches the item's first or last
+50 ms (``EDGE``) holds a word the recording cut off: it loses ``TRIM`` at that
+edge, and what remains, when it is still a segment, is read like any other.
+A remainder shorter than that is a fragment: it is in the input and no system's
+to repair, so it leaves the pools and is counted apart (``_edge_segments``).
+
+The primary-speaker flags are decided once, on INPUT, and read by every other
+system from INPUT's records (``frozen_sims``): the embeddings are not
+bit-reproducible across machines, and a flag that flips between two scoring
+runs would change the cohort under the board. Each system's records are bound
+to INPUT's decisions by a digest of its segment boundaries and similarities in
+their identity, so a record made under another INPUT pass is never reused, and
+a fresh pass must reproduce INPUT's boundaries exactly. A segment shorter than
+the embedder reads is embedded with the input around it and counted as widened
+(``_widened_segments``): a consistent decision, not a confident one.
+
+Usage: scorerealx.py --systems a,b [--conds ...] [--primary-anchor]
+Output: <BENCH_RESULTS>/<system>.realx.json
+"""
+
+import argparse
+import collections
+import hashlib
+import json
+import os
+import sys
+
+import numpy as np
+import torch
+import torchaudio
+
+# pylint: disable=wrong-import-position
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import anchors
+import common
+import levels
+import observations
+import scorebench
+
+SCORER_SHA256 = observations.implementation(
+ __file__,
+ common.__file__,
+ observations.__file__,
+ levels.__file__,
+ scorebench.__file__,
+)
+
+# Silero's own shortest segment, 250 ms at 16 kHz: nothing shorter is reported
+MIN_SEG = 4000
+# a segment starting within 50 ms of the item's start, or ending within 50 ms
+# of its end, holds a word the recording cut off
+EDGE = 800
+# what such a segment loses at that edge, 300 ms at 16 kHz: the cut-off word
+TRIM = 4800
+# the shortest input the speaker embedder reads: half a second at 16 kHz
+EMB_MIN = 8000
+
+
+def embedding_span(start, end, length):
+ """Returns ``[start, end)`` widened to ``EMB_MIN`` samples inside the item.
+
+ Centred on the segment where the item allows, so a short word is embedded
+ with the voice around it.
+ """
+ short = EMB_MIN - (end - start)
+ if short <= 0:
+ return start, end
+ start = max(0, start - short // 2)
+ end = min(length, start + EMB_MIN)
+ return max(0, end - EMB_MIN), end
+
+
+def select_items(rows, conds):
+ """Returns the manifest rows named by ``conds``.
+
+ A comma-separated list of exact condition names, or a single prefix (the
+ default ``real``) when no row carries that exact name.
+ """
+ want = [c for c in conds.split(",") if c]
+ if len(want) == 1 and not any(r["condition"] == want[0] for r in rows):
+ return [r for r in rows if r["condition"].startswith(want[0])]
+ return [r for r in rows if r["condition"] in want]
+
+
+def ci95(k, n):
+ # pylint: disable-next=import-outside-toplevel
+ from scipy import stats
+
+ lo = stats.beta.ppf(0.025, k, n - k + 1) if k > 0 else 0.0
+ hi = stats.beta.ppf(0.975, k + 1, n - k) if k < n else 1.0
+ return 100 * lo, 100 * hi
+
+
+def anchor_sims(mix, vad, spk):
+ """Returns each usable input segment's similarity to the anchor segment.
+
+ The anchor is the segment with the largest energy x duration; None when the
+ input holds no usable segment.
+ """
+ i16, segs = vad.segments(mix)
+ usable = [(s["start"], min(s["end"], len(i16)))
+ for s in segs
+ if min(s["end"], len(i16)) - s["start"] >= MIN_SEG]
+ if not usable:
+ return None
+ embs, scores = [], []
+ for b, e in usable:
+ w48 = mix[b * 3:e * 3]
+ scores.append(float(w48.pow(2).mean()) * (e - b))
+ # the embedder needs half a second: a shorter segment is read with the
+ # input around it
+ if e - b < EMB_MIN:
+ b, e = embedding_span(b, e, len(i16))
+ embs.append(spk.emb(mix[b * 3:e * 3]))
+ anchor = int(np.argmax(scores))
+ return [float(torch.dot(em, embs[anchor])) for em in embs]
+
+
+def score_item(it, out, mix, vad, sims, threshold):
+ """Returns one item's usable input segments and the output's drop on each.
+
+ The output's raw energy drop on each segment, and whether the segment
+ belongs to the primary speaker (``sims`` against ``threshold``; unknown
+ without anchoring).
+ """
+ n = min(len(out), len(mix))
+ i16, segs = (scorebench.speech_segments(vad, mix, it["mix_path"])
+ if n == len(mix) else vad.segments(mix[:n]))
+ o16 = torchaudio.functional.resample(out[:n], common.SR, 16000)[:len(i16)]
+ i16 = i16[:len(o16)]
+ drops, prim, edge, trimmed, widened = [], [], [], [], []
+ starts, ends = [], []
+ k = -1
+ for s in segs:
+ b, e = s["start"], min(s["end"], len(o16))
+ if e - b < MIN_SEG:
+ continue
+ k += 1
+ widened.append(1.0 if e - b < EMB_MIN else 0.0)
+ # the edge a segment touches takes the cut-off word with it; what
+ # remains is read whole, or reported as a fragment when too short
+ tb = b + TRIM if b <= EDGE else b
+ te = e - TRIM if e >= len(o16) - EDGE else e
+ touches = (tb, te) != (b, e)
+ fragment = touches and te - tb < MIN_SEG
+ trimmed.append(1.0 if touches and not fragment else 0.0)
+ edge.append(1.0 if fragment else 0.0)
+ if touches and not fragment:
+ b, e = tb, te
+ starts.append(int(b))
+ ends.append(int(e))
+ drop = float(10 * torch.log10(
+ (o16[b:e].pow(2).mean() + 1e-9) / (i16[b:e].pow(2).mean() + 1e-9)))
+ drops.append(drop)
+ prim.append(1.0 if sims is not None and k < len(sims) and
+ sims[k] >= threshold else 0.0)
+ return {
+ "seg_drop": drops,
+ "seg_primary": prim,
+ "seg_edge": edge,
+ "seg_trimmed": trimmed,
+ "seg_widened": widened,
+ # 16 kHz sample indices of the input's segments as read: frozen
+ # boundaries every output is read on, never an output's own VAD
+ "seg_start": starts,
+ "seg_end": ends,
+ "anchor_sims": [list(sims)] if sims is not None and drops else [],
+ }
+
+
+def item_metrics(m):
+ """Returns per-item segment counts and the primary segments' raw drops.
+
+ They do not depend on the view: the deletions are read at a calibration
+ (``levels.deleted``).
+ """
+ drops, prim = m.get("seg_drop", []), m.get("seg_primary", [])
+ edge = m.get("seg_edge") or [0.0] * len(drops)
+ metrics = {
+ "n_segments": len(drops),
+ "n_edge_segments": int(sum(edge)),
+ "n_trimmed_segments": int(sum(m.get("seg_trimmed") or [])),
+ "n_widened_segments": int(sum(m.get("seg_widened") or [])),
+ }
+ primary = [d for d, p, x in zip(drops, prim, edge) if p and not x]
+ if primary:
+ metrics["primary_segments"] = len(primary)
+ metrics["primary_drops"] = primary
+ return metrics
+
+
+def frozen_key(decision):
+ """Returns the digest of INPUT's decision on one item (``frozen_sims``)."""
+ return hashlib.sha256(json.dumps(
+ decision, sort_keys=True).encode("utf-8")).hexdigest()[:16]
+
+
+def frozen_sims(path, items):
+ """Returns {item id: INPUT's decision} for ``items``.
+
+ A decision is ``{"sims", "start", "end"}``: the anchor similarities every
+ other system reads its flags from (None where the input holds no usable
+ segment) and the segment boundaries, in 16 kHz samples, every other system
+ must reproduce. INPUT's records must be of this set, the whole set and this
+ scorer, anchored, and cover every item.
+ """
+ if not os.path.isfile(path):
+ raise SystemExit(f"{path} is missing: score INPUT with --primary-anchor"
+ " first, into the same results directory")
+ metadata, records = observations.read(path)
+ if metadata.get("system") != "INPUT":
+ raise SystemExit(f"{path}: not INPUT's records")
+ if (metadata.get("set_id") != common.set_id() or
+ metadata.get("subset", "all") != "all"):
+ raise SystemExit(f"{path}: records of another set or subset")
+ if metadata.get("scorer_sha256") != SCORER_SHA256:
+ raise SystemExit(f"{path}: made by another deletion scorer; re-score"
+ " INPUT first")
+ by_id = {r["id"]: r for r in records}
+ missing = [it["id"] for it in items if it["id"] not in by_id]
+ if missing:
+ raise SystemExit(f"{path} lacks {len(missing)} items (first:"
+ f" {missing[0]}): re-score INPUT over the whole set")
+ out = {}
+ for it in items:
+ m = by_id[it["id"]].get("measurements") or {}
+ if m.get("seg_drop") and not m.get("anchor_sims"):
+ raise SystemExit(f"{path}: {it['id']} carries no speaker anchoring;"
+ " re-score INPUT with --primary-anchor")
+ sims = m.get("anchor_sims") or []
+ first = list(sims[0]) if sims else []
+ out[it["id"]] = {
+ "sims": first or None,
+ "start": [int(v) for v in m.get("seg_start") or []],
+ "end": [int(v) for v in m.get("seg_end") or []],
+ }
+ return out
+
+
+def assemble(name,
+ items,
+ vad,
+ spk,
+ threshold,
+ reuse=None,
+ hashes=None,
+ frozen=None):
+ """Returns per-item records over the real ``items``.
+
+ Reused by content identity (output, mixture, the anchoring rule and INPUT's
+ decision on the item) since an earlier pass of this sidecar, scored
+ otherwise. With ``frozen`` (INPUT's decisions, ``frozen_sims``) the flags
+ are INPUT's, no embedding is computed, and the segments read must be
+ INPUT's to the sample.
+
+ Raises:
+ SystemExit: An item's segments differ from INPUT's.
+ """
+ hashes = hashes or common.file_hashes()
+ reuse = reuse or {}
+ records, counts = [], collections.Counter()
+ sims_cache = {}
+ for it in items:
+ record = observations.item(it)
+ records.append(record)
+ op = (it["mix_path"] if name == "INPUT" else os.path.join(
+ common.OUT_ROOT, name, it["id"]))
+ if not os.path.exists(op):
+ record["output_status"] = "missing"
+ continue
+ out, mix = common.load48(op), common.load48(it["mix_path"])
+ if len(out) != len(mix):
+ record["output_status"] = "wrong_length"
+ continue
+ if not bool(torch.isfinite(out).all()):
+ record["output_status"] = "nonfinite"
+ continue
+ record["identity"] = scorebench.item_identity(
+ it, scorebench.sample_hash(out), hashes)
+ record["identity"]["semantics"]["sim_threshold"] = (
+ threshold if spk is not None else None)
+ # INPUT's decision is part of what this record depends on: another
+ # INPUT pass means another record
+ decision = frozen[it["id"]] if frozen is not None else None
+ record["identity"]["semantics"]["frozen"] = (
+ frozen_key(decision) if decision is not None else None)
+ old = reuse.get(scorebench.reuse_key(record["identity"]))
+ if old is not None:
+ record["measurements"] = dict(old["measurements"])
+ counts["reused"] += 1
+ else:
+ sims = None
+ if decision is not None:
+ sims = decision["sims"]
+ elif spk is not None:
+ if it["id"] not in sims_cache:
+ sims_cache[it["id"]] = anchor_sims(mix, vad, spk)
+ sims = sims_cache[it["id"]]
+ measured = score_item(it, out, mix, vad, sims, threshold)
+ if decision is not None and (
+ measured["seg_start"] != decision["start"] or
+ measured["seg_end"] != decision["end"]):
+ raise SystemExit(
+ f"{it['id']}: the segments read differ from INPUT's"
+ f" ({len(measured['seg_start'])} against"
+ f" {len(decision['start'])}, or other boundaries): the"
+ " voice detector or its cache changed; re-score INPUT")
+ record["measurements"] = observations.finite(measured)
+ counts["scored"] += 1
+ record["metrics"] = item_metrics(
+ observations.revive(record["measurements"]))
+ if reuse:
+ print(
+ f" reused {counts['reused']} records, scored {counts['scored']}"
+ " items",
+ flush=True,
+ )
+ return records
+
+
+def aggregate(records, items, threshold, level_cal_db):
+ """Returns the sidecar file for ``items`` from their records.
+
+ Deletions at the system's calibration pooled per condition and over the
+ view, the primary-anchored pool, and the per-item cohorts. Pure, so any view
+ of the set derives from the whole-set records.
+ """
+ by_id = {r["id"]: r for r in records}
+ per_cond = collections.defaultdict(lambda: [0, 0])
+ prim = collections.defaultdict(lambda: [0, 0])
+ edges = collections.defaultdict(lambda: [0, 0])
+ items_real, items_prim, sims_out = {}, {}, {}
+ missing = trimmed = widened = 0
+ for it in items:
+ rec = by_id.get(it["id"])
+ if rec is None or rec.get("output_status") != "ok":
+ missing += 1
+ continue
+ m = observations.revive(rec.get("measurements", {}))
+ trimmed += int(sum(m.get("seg_trimmed") or []))
+ widened += int(sum(m.get("seg_widened") or []))
+ drops = m.get("seg_drop", [])
+ edge = m.get("seg_edge") or [0.0] * len(drops)
+ inner = [i for i, x in enumerate(edge) if not x]
+ cut = levels.deleted([d for d, x in zip(drops, edge) if x],
+ level_cal_db)
+ if cut:
+ edges[it["condition"]][0] += int(sum(cut))
+ edges[it["condition"]][1] += len(cut)
+ dels = levels.deleted([drops[i] for i in inner], level_cal_db)
+ flags = m.get("seg_primary", [])
+ prims = [flags[i] for i in inner] if flags else []
+ if not dels:
+ continue
+ cell = per_cond[it["condition"]]
+ cell[0] += int(sum(dels))
+ cell[1] += len(dels)
+ items_real[it["id"]] = [int(sum(dels)), len(dels)]
+ sims = m.get("anchor_sims") or []
+ if sims:
+ sims_out[it["id"]] = sims[0]
+ n_prim = int(sum(prims))
+ if n_prim:
+ k_prim = int(sum(d for d, p in zip(dels, prims) if p))
+ prim[it["condition"]][0] += k_prim
+ prim[it["condition"]][1] += n_prim
+ items_prim[it["id"]] = [k_prim, n_prim]
+ out_d = {}
+ k_all = n_all = 0
+ for cond, (k, n) in sorted(per_cond.items()):
+ lo, hi = ci95(k, n)
+ out_d[cond] = {
+ "deleted_rate_pct": 100 * k / max(1, n),
+ "n_segments": n,
+ "n_deleted": k,
+ "ci95": [lo, hi],
+ }
+ k_all += k
+ n_all += n
+ if n_all:
+ lo, hi = ci95(k_all, n_all)
+ out_d["_pooled_real"] = {
+ "deleted_rate_pct": 100 * k_all / n_all,
+ "n_segments": n_all,
+ "n_deleted": k_all,
+ "ci95": [lo, hi],
+ }
+ if prim:
+ kp = sum(v[0] for v in prim.values())
+ np_ = sum(v[1] for v in prim.values())
+ if np_:
+ lo, hi = ci95(kp, np_)
+ out_d["_pooled_primary"] = {
+ "deleted_rate_pct": 100 * kp / np_,
+ "n_segments": np_,
+ "n_deleted": kp,
+ "ci95": [lo, hi],
+ "sim_threshold": threshold,
+ }
+ out_d["_anchor_sims"] = sims_out
+ out_d["_items_primary"] = items_prim
+ out_d["_items_real"] = items_real
+ # the words the recordings cut off at an edge: shown, never charged
+ out_d["_edge_segments"] = {
+ cond: {
+ "n_segments": n,
+ "n_deleted": k
+ } for cond, (k, n) in sorted(edges.items())
+ }
+ # segments read without the edge they touched, and short segments whose
+ # speaker was decided with the input around them
+ out_d["_trimmed_segments"] = trimmed
+ out_d["_widened_segments"] = widened
+ out_d["_missing_outputs"] = missing
+ out_d["_level_cal_db"] = level_cal_db
+ return out_d
+
+
+def level_calibration(results, name):
+ """Returns the system's output gain from its base scores in ``results``.
+
+ The view's own scores.
+ """
+ path = os.path.join(results, f"{name}.metrics.json")
+ if not os.path.isfile(path):
+ raise SystemExit(
+ f"{path} is missing: score {name} before its deletion sidecar")
+ with open(path, encoding="utf-8") as fh:
+ return float(json.load(fh).get("_level_cal_db") or 0.0)
+
+
+def threshold_of(records, given):
+ """Returns the anchoring threshold the records were scored with.
+
+ One threshold for all records, or ``given`` when they state none.
+ """
+ stated = set()
+ for r in records:
+ if r.get("output_status") == "ok":
+ semantics = (r.get("identity") or {}).get("semantics", {})
+ stated.add(semantics.get("sim_threshold"))
+ stated.discard(None)
+ if len(stated) > 1:
+ raise SystemExit(
+ f"records scored with {len(stated)} anchoring thresholds")
+ return stated.pop() if stated else given
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--systems", required=True)
+ ap.add_argument(
+ "--conds",
+ default="real",
+ help=("comma-separated conditions, or a prefix every pooled condition"
+ " starts with"),
+ )
+ ap.add_argument("--primary-anchor", action="store_true")
+ ap.add_argument("--sim-threshold", type=float, default=0.85)
+ ap.add_argument(
+ "--reuse-from",
+ default="",
+ metavar="DIR",
+ help=(
+ "results of an earlier pass of this sidecar: unchanged items keep "
+ "their records"),
+ )
+ ap.add_argument(
+ "--aggregate-only",
+ default="",
+ metavar="DIR",
+ help="derive this subset's files from the whole-set records under DIR",
+ )
+ a = ap.parse_args()
+
+ items = select_items(common.manifest(), a.conds)
+ common.guard_private_results(items)
+ vad = spk = None
+ if not a.aggregate_only:
+ vad = common.Vad()
+ spk = common.SpeakerEmbedder() if a.primary_anchor else None
+
+ os.makedirs(common.RESULTS, exist_ok=True)
+ # INPUT first: its records carry the flags every other system reads
+ names = [n for n in a.systems.split(",") if n]
+ names = [n for n in names if n == "INPUT"
+ ] + [n for n in names if n != "INPUT"]
+ for name in names:
+ if a.aggregate_only:
+ src = os.path.join(a.aggregate_only, f"{name}.realx.items.jsonl")
+ ids = {it["id"] for it in items}
+ problem, source, records = scorebench.view_records(
+ src, name, ids, SCORER_SHA256)
+ if problem:
+ print(f"skip {name}: {problem}", flush=True)
+ continue
+ outputs = source.get("outputs_sha256")
+ else:
+ problem = name != "INPUT" and scorebench.render_problem(name)
+ if problem:
+ print(f"skip {name}: {problem}", flush=True)
+ continue
+ own = os.path.join(common.RESULTS, f"{name}.realx.items.jsonl")
+ reuse, why = {}, "no earlier records"
+ if a.reuse_from:
+ reuse, why = scorebench.reuse_index(
+ os.path.join(a.reuse_from, f"{name}.realx.items.jsonl"),
+ name,
+ SCORER_SHA256,
+ )
+ why = f"reuse from {a.reuse_from}: {why}"
+ # never skipped as scored: re-validated item by item
+ elif os.path.isfile(own):
+ reuse, why = scorebench.reuse_index(own, name, SCORER_SHA256)
+ why = f"existing records: {why}"
+ print(f" {why}", flush=True)
+ frozen = None
+ if spk is not None and name != "INPUT":
+ frozen = frozen_sims(
+ os.path.join(common.RESULTS, "INPUT.realx.items.jsonl"),
+ items)
+ records = assemble(name,
+ items,
+ vad,
+ spk,
+ a.sim_threshold,
+ reuse=reuse,
+ frozen=frozen)
+ outputs = common.outputs_digest(name)
+ level_cal_db = level_calibration(common.RESULTS, name)
+ out_d = aggregate(records, items,
+ threshold_of(records, a.sim_threshold), level_cal_db)
+ observations.sidecar(
+ os.path.join(common.RESULTS, f"{name}.realx.items.jsonl"),
+ records,
+ name,
+ common.set_id(),
+ common.SUBSET,
+ common.is_sealed(items),
+ SCORER_SHA256,
+ level_cal_db=level_cal_db,
+ outputs_sha256=outputs,
+ )
+ # the leaderboard ignores a sidecar from another build, and one from
+ # another subset of the set
+ out_d["_set_id"] = common.set_id()
+ out_d["_subset"] = common.SUBSET
+ out_d.update(anchors.stamp())
+ out_d["_sealed"] = common.is_sealed(common.manifest())
+ out_d["_scorer_sha256"] = SCORER_SHA256
+ out_d["_outputs_sha256"] = outputs # the render these records read
+ path = os.path.join(common.RESULTS, f"{name}.realx.json")
+ tmp = f"{path}.{os.getpid()}.tmp"
+ with open(tmp, "w", encoding="utf-8") as f:
+ json.dump(out_d, f, indent=1)
+ os.replace(tmp, path)
+ p = out_d.get("_pooled_real", {})
+ pp = out_d.get("_pooled_primary", {})
+ extra = (f" PRIMARY={pp.get('deleted_rate_pct', 0):.1f}% "
+ f"({pp.get('n_deleted', 0)}/{pp.get('n_segments', 0)})"
+ if pp else "")
+ print(
+ f"{name:24s} pooled deleted={p.get('deleted_rate_pct', 0):5.1f}% "
+ f"({p.get('n_deleted', 0)}/{p.get('n_segments', 0)}){extra} "
+ f"missing_outputs={out_d['_missing_outputs']}",
+ flush=True,
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/bench/scripts/scoreresidual.py b/bench/scripts/scoreresidual.py
new file mode 100644
index 0000000..14398fd
--- /dev/null
+++ b/bench/scripts/scoreresidual.py
@@ -0,0 +1,577 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Residual noise in the pauses of real recordings and under the voice.
+
+Two rows the board reads from this sidecar, both bounded per item: no single
+item contributes more than ``ITEM_CLIP_DB`` of credit or of penalty to a
+pooled mean, so a few silenced pauses cannot buy the whole axis.
+
+``pause_resid_db`` is what a system leaves in the pauses of a real recording
+over what the recording held there, in dB (lower is cleaner), beyond what it
+did to the voice: the item's own gain, read on the loudest fifth of its speech
+frames, is undone, so an item merely turned down earns nothing and a voice
+turned down with its pauses earns nothing for the part the voice lost. The
+system's delay and polarity are undone first. The pauses are the input's:
+outside every detected speech segment widened by 100 ms before an onset and
+200 ms after an offset (breaths, onsets and tails belong to the voice), never
+inside the item's first and last 300 ms (a word cut off at an edge is the
+recording's, not the system's), and never where the input holds digital
+silence. It is read at 48 kHz in one-third-octave bands weighted by the ITU-R
+468 curve: an audibility proxy only (the standard's quasi-peak detection is not
+applied), under which hiss at 2-10 kHz counts more than hum of the same energy.
+An item needs 0.4 s of pause. ``pause_level_db`` reads the same residual
+against the output's own voice, capped where it is taken as inaudible, so it
+says whether what is left is audible at all; the per-band energies stay
+unweighted in the records for the data-cleaning reading of the floor, whose
+worst band is taken over the bands the voice occupies.
+
+``babble_resid_db`` is, at each crowd-chatter level, the energy of the output
+that no scaling of the clean voice explains, at the voice's own scale, over the
+chatter the mixture held, in dB: the mixture's SDR minus the output's SI-SDR.
+It is interference and distortion together, over the whole item, not noise
+under speech alone. ``babble_supp_db`` reads |g o - r|^2 with one gain per
+system, so a voice 2 dB quieter on one item reads as chatter left; this row
+reads |o - a r|^2 / a^2 at the least-squares scale a = <o, r> / |r|^2 (the
+mixture's SDR minus the output's SI-SDR), so a quieter output earns nothing and
+loses nothing. A deleted or distorted voice counts, as it does for SI-SDR; an
+output holding none of the voice reads the bound, the worst value, never the
+floor. It comes from the base records' energies, so no audio is read; the base
+records must be this set's, this render's and the base scorer's.
+
+Usage: scoreresidual.py --systems a,b [--reuse-from DIR] [--aggregate-only DIR]
+Output: <BENCH_RESULTS>/<system>.residual.json and .residual.items.jsonl
+"""
+
+import argparse
+import collections
+import glob
+import json
+import math
+import os
+import sys
+
+import numpy as np
+import torch
+
+# pylint: disable=wrong-import-position
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import anchors
+import common
+import levels
+import observations
+import scorebench
+
+SCORER_SHA256 = observations.implementation(
+ __file__,
+ common.__file__,
+ observations.__file__,
+ levels.__file__,
+ scorebench.__file__,
+)
+
+N_FFT, HOP = 2048, 480
+PRE_S, POST_S = 0.100, 0.200
+EDGE_S = 0.300
+MIN_PAUSE_S = 0.4
+SILENCE_DBFS = -80.0
+# the loudest fifth of the speech frames give the voice's level
+TOP_SHARE = 0.2
+# a residual this far under the voice is taken as inaudible
+LEVEL_CLIP_DB = -45.0
+# no item reads beyond this much credit or penalty in any pooled row
+ITEM_CLIP_DB = 20.0
+# a band the voice occupies holds at least this share of its loudest band
+OCCUPIED = 1e-3
+# one-third-octave bands, 50 Hz to 20 kHz
+CENTRES_HZ = tuple(1000.0 * 2.0**(k / 3.0) for k in range(-13, 14))
+# the bands a 16 kHz-native system can fill
+NB_BANDS = sum(1 for f in CENTRES_HZ if f * 2.0**(1 / 6) <= 8000.0)
+REAL = ("real_dirty", "real_everyday", "real_multi", "real_noisy", "real_wild")
+BABBLE = ("babble@+4", "babble@+0", "babble@-5")
+
+
+def weighting(hz):
+ """Returns the ITU-R 468 amplitude response at ``hz``, one at 1 kHz."""
+
+ def response(f):
+ h1 = (-4.737338981378384e-24 * f**6 + 2.043828333606125e-15 * f**4 -
+ 1.363894795463638e-7 * f**2 + 1.0)
+ h2 = (1.306612257412824e-19 * f**5 - 2.118150887518656e-11 * f**3 +
+ 5.559488023498642e-4 * f)
+ return f / math.sqrt(h1 * h1 + h2 * h2)
+
+ return response(float(hz)) / response(1000.0)
+
+
+WEIGHTS = np.array([weighting(f)**2 for f in CENTRES_HZ])
+
+
+def band_index():
+ """Returns each STFT bin's band, -1 outside the bands."""
+ freqs = np.arange(N_FFT // 2 + 1) * common.SR / N_FFT
+ index = np.full(len(freqs), -1, dtype=np.int64)
+ for b, centre in enumerate(CENTRES_HZ):
+ low, high = centre * 2.0**(-1 / 6), centre * 2.0**(1 / 6)
+ index[(freqs >= low) & (freqs < high)] = b
+ return index
+
+
+BAND_OF_BIN = band_index()
+# the bands at least one STFT bin falls in: the lowest holds none
+SUPPORTED = np.array(
+ [bool((BAND_OF_BIN == b).any()) for b in range(len(CENTRES_HZ))])
+
+
+def spectrum(x):
+ """Returns the power spectrogram of ``x`` as [frames, bins]."""
+ window = torch.hann_window(N_FFT, dtype=x.dtype)
+ z = torch.stft(x,
+ N_FFT,
+ HOP,
+ window=window,
+ center=False,
+ return_complex=True)
+ return z.abs().pow(2).T.numpy()
+
+
+def band_energies(power, frames):
+ """Returns the energy per band over the given ``frames`` of ``power``."""
+ total = power[frames].sum(0) if len(frames) else np.zeros(power.shape[1])
+ out = np.zeros(len(CENTRES_HZ))
+ for b in range(len(CENTRES_HZ)):
+ out[b] = float(total[BAND_OF_BIN == b].sum())
+ return out
+
+
+def frame_masks(n, segs):
+ """Returns the speech, widened-speech and edge masks over the frames.
+
+ ``segs`` are the input's segments in 16 kHz samples; frames are those of
+ ``spectrum`` over ``n`` samples at 48 kHz.
+ """
+ frames = (n - N_FFT) // HOP + 1
+ centre = (np.arange(frames) * HOP + N_FFT / 2) / common.SR
+ # a pause frame lies in the pause whole: one that straddles the voice's
+ # boundary would read the voice as residual
+ half = N_FFT / 2 / common.SR
+ speech = np.zeros(frames, dtype=bool)
+ wide = np.zeros(frames, dtype=bool)
+ for s in segs:
+ start, end = s["start"] / 16000.0, s["end"] / 16000.0
+ speech |= (centre >= start) & (centre < end)
+ wide |= (centre >= start - PRE_S - half) & (centre
+ < end + POST_S + half)
+ edge = (centre < EDGE_S + half) | (centre > n / common.SR - EDGE_S - half)
+ return speech, wide, edge
+
+
+def score_real(it, out, mix, vad):
+ """Returns one real item's pause and voice energies per band.
+
+ The output's delay and polarity against the input are undone first. The
+ energies are raw: the item's gain is undone when they are read.
+ """
+ n = min(len(out), len(mix))
+ lag, sign = common.best_alignment(out[:n], mix[:n])
+ o = sign * common.apply_lag(out, lag, n)
+ x = mix[:n]
+ _, segs = (scorebench.speech_segments(vad, x, it["mix_path"])
+ if n == len(mix) else vad.segments(x))
+ if n < N_FFT:
+ return {"pause_seconds": 0.0, "speech_seconds": 0.0}
+ power_o, power_x = spectrum(o), spectrum(x)
+ speech, wide, edge = frame_masks(n, segs)
+ frames = x.unfold(0, N_FFT, HOP).pow(2).mean(1).numpy()
+ silent = 10 * np.log10(frames + 1e-20) < SILENCE_DBFS
+ pause = ~wide & ~edge & ~silent
+ speech &= ~edge
+ loud = np.zeros(len(frames), dtype=bool)
+ if speech.any():
+ cut = np.quantile(frames[speech], 1.0 - TOP_SHARE)
+ loud = speech & (frames >= cut)
+ return {
+ "lag": lag,
+ "polarity": sign,
+ "pause_seconds": float(pause.sum() * HOP / common.SR),
+ "speech_seconds": float(speech.sum() * HOP / common.SR),
+ "pause_frames": int(pause.sum()),
+ "loud_frames": int(loud.sum()),
+ "pause_out": band_energies(power_o, np.flatnonzero(pause)).tolist(),
+ "pause_in": band_energies(power_x, np.flatnonzero(pause)).tolist(),
+ "speech_in": band_energies(power_x, np.flatnonzero(loud)).tolist(),
+ "speech_out": band_energies(power_o, np.flatnonzero(loud)).tolist(),
+ }
+
+
+def bounded(db, low=-ITEM_CLIP_DB, high=ITEM_CLIP_DB):
+ """Returns ``db`` held inside one item's bounds."""
+ return float(min(max(db, low), high))
+
+
+def pause_metrics(m):
+ """Returns one item's pause rows from its measurements.
+
+ Nothing for an item with too little pause, or whose records lack the
+ output's voice energy (an earlier scorer's).
+ """
+ if (m.get("pause_seconds", 0.0) < MIN_PAUSE_S or not m.get("pause_out") or
+ not m.get("loud_frames") or not m.get("speech_out")):
+ return {}
+ # energies per frame: the pauses and the voice's loudest frames are
+ # different numbers of frames
+ out = np.array(m["pause_out"]) / m["pause_frames"]
+ inp = np.array(m["pause_in"]) / m["pause_frames"]
+ voice_in = np.array(m["speech_in"]) / m["loud_frames"]
+ voice_out = np.array(m["speech_out"]) / m["loud_frames"]
+
+ def ratio(a, b, w):
+ return 10 * math.log10((float((w * a).sum()) + 1e-20) / (float(
+ (w * b).sum()) + 1e-20))
+
+ nb = np.array([1.0 if b < NB_BANDS else 0.0 for b in range(len(WEIGHTS))])
+ # the item's own gain, from its voice: what the pause lost beyond what
+ # the voice lost is cleanup; what both lost is the item turned down
+ gain = ratio(voice_out, voice_in, WEIGHTS)
+ gain_nb = ratio(voice_out, voice_in, WEIGHTS * nb)
+ occupied = SUPPORTED & (voice_in >= voice_in.max() * OCCUPIED) & (voice_out
+ > 0)
+ worst = ((out[occupied] + 1e-20) /
+ (voice_out[occupied] + 1e-20)).max() if occupied.any() else None
+ return {
+ "pause_resid_db":
+ bounded(ratio(out, inp, WEIGHTS) - gain),
+ "pause_resid_db_nb":
+ bounded(ratio(out, inp, WEIGHTS * nb) - gain_nb),
+ # the level row is bounded per item like the reduction row: an item
+ # earns or loses at most ITEM_CLIP_DB against its own input, then the
+ # cap at which a residual under the voice is taken as inaudible
+ "pause_level_db":
+ bounded(
+ bounded(ratio(out, voice_out, WEIGHTS),
+ ratio(inp, voice_in, WEIGHTS) - ITEM_CLIP_DB,
+ ratio(inp, voice_in, WEIGHTS) + ITEM_CLIP_DB),
+ LEVEL_CLIP_DB),
+ "pause_gain_db":
+ gain,
+ "floor_db":
+ ratio(out, voice_out, np.ones(len(WEIGHTS))),
+ "floor_worst_db":
+ 10 * math.log10(float(worst)) if worst is not None else math.nan,
+ }
+
+
+def babble_metrics(energies):
+ """Returns one item's bounded voice-free residual in dB, from its energies.
+
+ Args:
+ energies: ``[|o|^2, <o, r>, |r|^2, |m - r|^2]``.
+ """
+ oo, orr, rr, mr = (float(v) for v in energies)
+ if rr <= 0.0:
+ # no voice in the reference: nothing to read against (never in the set)
+ return 0.0
+ # the voice's scale in the output; the residual is read at that scale, so
+ # a quieter output earns nothing and loses nothing. An output holding none
+ # of the voice, or its opposite, removed the voice: the worst reading
+ scale = orr / rr
+ if scale <= 0.0:
+ return ITEM_CLIP_DB
+ resid = max(oo - orr * orr / rr, 0.0) / (scale * scale)
+ return bounded(10 * math.log10((resid + 1e-9) / (mr + 1e-9)))
+
+
+def base_energies(path, ids, name, outputs):
+ """Returns {item id: (identity, energies, nb energies)} of base records.
+
+ The records must be this system's, this set's, the whole set's, the base
+ scorer's and of the render under evaluation: the chatter rows derive from
+ them and are stamped with this run's identity.
+
+ Raises:
+ SystemExit: The base records are missing or of another provenance.
+ """
+ if not os.path.isfile(path):
+ raise SystemExit(f"{path} is missing: score the system with scorebench"
+ " first")
+ problem = scorebench.view_source(path, name, scorebench.SCORER_SHA256)
+ if problem:
+ raise SystemExit(f"{path}: {problem}")
+ metadata, records = observations.read(path)
+ # the base records carry the render's stamp in their header
+ stamped = (metadata.get("render_identity") or {}).get("outputs_sha256")
+ if stamped != outputs:
+ raise SystemExit(f"{path}: records of another render of {name}:"
+ " re-score it with scorebench first")
+ out = {}
+ for r in records:
+ if r["id"] not in ids or r.get("output_status") != "ok":
+ continue
+ m = r.get("measurements") or {}
+ if m.get("babble_energy") and m.get("babble_energy_nb"):
+ out[r["id"]] = (r["identity"], m["babble_energy"][0],
+ m["babble_energy_nb"][0])
+ return out
+
+
+def assemble(name, rows, vad, reuse=None, hashes=None, base=None):
+ """Returns per-item records over ``rows``.
+
+ Real items are read from audio; crowd-chatter items take their energies
+ from the base records (``base``). An item whose output samples are
+ unchanged since an earlier pass keeps its record (``reuse``).
+ """
+ hashes = hashes or common.file_hashes()
+ reuse, base = reuse or {}, base or {}
+ records, counts = [], collections.Counter()
+ for it in rows:
+ record = observations.item(it)
+ records.append(record)
+ if it.get("clean_path"):
+ held = base.get(it["id"])
+ if held is None:
+ record["output_status"] = "missing"
+ continue
+ identity, energies, energies_nb = held
+ record["identity"] = identity
+ record["measurements"] = {
+ "babble_energy": [list(energies)],
+ "babble_energy_nb": [list(energies_nb)],
+ }
+ record["metrics"] = {
+ "babble_resid_db": babble_metrics(energies),
+ "babble_resid_db_nb": babble_metrics(energies_nb),
+ }
+ continue
+ op = (it["mix_path"] if name == "INPUT" else os.path.join(
+ common.OUT_ROOT, name, it["id"]))
+ if not os.path.exists(op):
+ record["output_status"] = "missing"
+ continue
+ out, mix = common.load48(op), common.load48(it["mix_path"])
+ if len(out) != len(mix):
+ record["output_status"] = "wrong_length"
+ continue
+ if not bool(torch.isfinite(out).all()):
+ record["output_status"] = "nonfinite"
+ continue
+ record["identity"] = scorebench.item_identity(
+ it, scorebench.sample_hash(out), hashes)
+ old = reuse.get(scorebench.reuse_key(record["identity"]))
+ if old is not None:
+ record["measurements"] = dict(old["measurements"])
+ counts["reused"] += 1
+ else:
+ record["measurements"] = observations.finite(
+ score_real(it, out, mix, vad))
+ counts["scored"] += 1
+ if reuse:
+ print(
+ f" reused {counts['reused']} records, scored {counts['scored']}"
+ " items",
+ flush=True,
+ )
+ return records
+
+
+def aggregate(records, rows, level_cal_db):
+ """Returns the sidecar file for ``rows``.
+
+ Per real family the mean of its items' rows, and pooled over every real
+ item (``_real_cleanup``); per crowd-chatter level the mean residual. Every
+ condition keeps its expected and missing counts whether or not it has a
+ value; an item without enough pause is counted as short and one whose
+ pauses hold no speech to read the voice from as no_speech, never as
+ missing. Pure, so any view of the set derives from the whole-set records.
+ The rows undo each item's own gain, so the system's calibration is recorded
+ and not applied.
+ """
+ by_id = {r["id"]: r for r in records}
+ out = {}
+ pooled = collections.defaultdict(list)
+ short, no_speech = collections.Counter(), collections.Counter()
+ for it in rows:
+ cond = it["condition"]
+ rec = by_id.get(it["id"])
+ cell = out.setdefault(cond, {"n_expected": 0, "n_missing": 0, "n": 0})
+ cell["n_expected"] += 1
+ if rec is None or rec.get("output_status") != "ok":
+ cell["n_missing"] += 1
+ continue
+ m = observations.revive(rec.get("measurements", {}))
+ if it.get("clean_path"):
+ values = {
+ "babble_resid_db": babble_metrics(m["babble_energy"][0]),
+ "babble_resid_db_nb": babble_metrics(m["babble_energy_nb"][0]),
+ }
+ else:
+ values = pause_metrics(m)
+ rec["metrics"] = observations.finite(values)
+ if not values:
+ # too little pause, or no speech left to read the voice from
+ if (m.get("pause_seconds", 0.0) >= MIN_PAUSE_S and
+ not m.get("loud_frames")):
+ no_speech[cond] += 1
+ else:
+ short[cond] += 1
+ continue
+ for k, v in values.items():
+ if math.isfinite(v):
+ pooled[k].append(v)
+ cell["n"] += 1
+ for k, v in values.items():
+ if math.isfinite(v):
+ cell.setdefault("_values", {}).setdefault(k, []).append(v)
+ for cond, cell in out.items():
+ for k, vs in cell.pop("_values", {}).items():
+ cell[k] = float(np.mean(vs))
+ if short[cond]:
+ cell["n_short"] = short[cond]
+ if no_speech[cond]:
+ cell["n_no_speech"] = no_speech[cond]
+ real = [c for c in REAL if c in out]
+ if real:
+ cleanup = {k: float(np.mean(vs)) for k, vs in pooled.items()}
+ cleanup.update({
+ "n": sum(out[c]["n"] for c in real),
+ "n_expected": sum(out[c]["n_expected"] for c in real),
+ "n_missing": sum(out[c]["n_missing"] for c in real),
+ "n_short": sum(short[c] for c in real),
+ "n_no_speech": sum(no_speech[c] for c in real),
+ "by_family": {
+ c: out[c]["pause_resid_db"]
+ for c in real
+ if "pause_resid_db" in out[c]
+ },
+ })
+ out["_real_cleanup"] = cleanup
+ out["_level_cal_db"] = level_cal_db
+ return out
+
+
+def level_calibration(results, name, outputs):
+ """Returns the system's output gain from its base scores.
+
+ The base scores must be the base scorer's and of the render under
+ evaluation.
+
+ Raises:
+ SystemExit: The base scores are missing or of another provenance.
+ """
+ path = os.path.join(results, f"{name}.metrics.json")
+ if not os.path.isfile(path):
+ raise SystemExit(f"{path} is missing: score {name} with scorebench"
+ " before this sidecar")
+ with open(path, encoding="utf-8") as fh:
+ base = json.load(fh)
+ if base.get("_scorer_sha256") != scorebench.SCORER_SHA256:
+ raise SystemExit(f"{path}: scored by another base scorer; re-score"
+ f" {name} with scorebench first")
+ if base.get("_outputs_sha256") != outputs:
+ raise SystemExit(f"{path}: scores of another render of {name};"
+ " re-score it with scorebench first")
+ return float(base.get("_level_cal_db") or 0.0)
+
+
+def write(name, records, out, rows, level_cal_db, outputs):
+ observations.sidecar(
+ os.path.join(common.RESULTS, f"{name}.residual.items.jsonl"),
+ records,
+ name,
+ common.set_id(),
+ common.SUBSET,
+ common.is_sealed(rows),
+ SCORER_SHA256,
+ level_cal_db=level_cal_db,
+ outputs_sha256=outputs,
+ )
+ out["_set_id"] = common.set_id()
+ out["_subset"] = common.SUBSET
+ out.update(anchors.stamp())
+ out["_sealed"] = common.is_sealed(rows)
+ out["_scorer_sha256"] = SCORER_SHA256
+ out["_outputs_sha256"] = outputs
+ path = os.path.join(common.RESULTS, f"{name}.residual.json")
+ tmp = f"{path}.{os.getpid()}.tmp"
+ with open(tmp, "w", encoding="utf-8") as fh:
+ json.dump(observations.finite(out), fh, indent=1)
+ os.replace(tmp, path)
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--systems", default="")
+ ap.add_argument("--reuse-from", default="", metavar="DIR")
+ ap.add_argument("--aggregate-only", default="", metavar="DIR")
+ a = ap.parse_args()
+
+ rows = common.manifest()
+ common.guard_private_results(rows)
+ selected = [r for r in rows if r["condition"] in REAL + BABBLE]
+ systems = [s for s in a.systems.split(",") if s] or sorted(
+ os.path.basename(d)
+ for d in glob.glob(common.OUT_ROOT + "/*")
+ if os.path.isdir(d))
+ vad = None if a.aggregate_only else common.Vad()
+ os.makedirs(common.RESULTS, exist_ok=True)
+ for name in systems:
+ if a.aggregate_only:
+ src = os.path.join(a.aggregate_only, f"{name}.residual.items.jsonl")
+ ids = {r["id"] for r in selected}
+ problem, source, records = scorebench.view_records(
+ src, name, ids, SCORER_SHA256)
+ if problem:
+ print(f"skip {name}: {problem}", flush=True)
+ continue
+ outputs = source.get("outputs_sha256")
+ else:
+ problem = name != "INPUT" and scorebench.render_problem(name)
+ if problem:
+ print(f"skip {name}: {problem}", flush=True)
+ continue
+ outputs = common.outputs_digest(name)
+ own = os.path.join(common.RESULTS, f"{name}.residual.items.jsonl")
+ reuse, why = {}, "no earlier records"
+ if a.reuse_from:
+ reuse, why = scorebench.reuse_index(
+ os.path.join(a.reuse_from, f"{name}.residual.items.jsonl"),
+ name,
+ SCORER_SHA256,
+ )
+ why = f"reuse from {a.reuse_from}: {why}"
+ elif os.path.isfile(own):
+ reuse, why = scorebench.reuse_index(own, name, SCORER_SHA256)
+ why = f"existing records: {why}"
+ print(f" {why}", flush=True)
+ base = base_energies(
+ os.path.join(common.RESULTS, f"{name}.items.jsonl"),
+ {r["id"] for r in selected if r.get("clean_path")},
+ name,
+ outputs,
+ )
+ records = assemble(name, selected, vad, reuse=reuse, base=base)
+ level_cal_db = level_calibration(common.RESULTS, name, outputs)
+ out = aggregate(records, selected, level_cal_db)
+ write(name, records, out, rows, level_cal_db, outputs)
+ pooled = out.get("_real_cleanup", {})
+ babble = out.get("babble@+4", {}).get("babble_resid_db", math.nan)
+ print(
+ f"{name:24s} pauses {pooled.get('pause_resid_db', math.nan):6.1f}"
+ f" dB over {pooled.get('n', 0)} real items; babble@+4 residual"
+ f" {babble:6.1f} dB",
+ flush=True,
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/bench/scripts/scorestream.py b/bench/scripts/scorestream.py
new file mode 100644
index 0000000..b0d3079
--- /dev/null
+++ b/bench/scripts/scorestream.py
@@ -0,0 +1,845 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The streaming probe: whether a system can run as audio arrives and hold up.
+
+Three steps: cut the probe inputs, render them through every system (each in
+its own venv, our model through runsystem.py), score the renders::
+
+ python bench/scripts/scorestream.py --probe
+ PROBE_IN=<probe>/in BENCH_OUT=<probe>/out \
+ bench/scripts/runfield.sh <systems>
+ BENCH_OUT=<probe>/out BENCH_RESULTS=<probe>/results \
+ python bench/scripts/runsystem.py --name voice_isolator_v0 \
+ --model ... --inputs <probe>/in
+ python bench/scripts/scorestream.py [--systems a,b] # <system>.stream.json
+
+The leaderboard's ``streaming probe`` column says yes or no from measurements
+made on renders rather than on claims, so a model that is streaming by design
+but is shipped through an offline path reads what it ships. The probe takes
+every paired long item of the set (``long@+4``, 45 s with several talkers and a
+changing ambience) and cuts from each a ``tail``: the fifteen seconds from 28.8
+s to 43.8 s, preceded by 3.2 s of the real audio before them as a lead-in, and
+three ``future`` inputs, the same tail whose audio from a splice point on is
+another recording. The cut starts on a 3.2 s grid, a multiple of every common
+frame hop at 48 kHz, so the fresh render's frames fall where the whole render's
+did; a system that frames otherwise (another internal rate, windows placed from
+the input's start) differs by that placement too, and the drift includes it. The
+lead-in lets a streaming model's state warm up before the measured stretch
+begins. The splice points are not round numbers, so a processor that works on
+independent blocks of some common length cannot be lucky on every splice.
+
+* **Causal with a bounded look-ahead.** The outputs on ``tail`` and on a
+ ``future`` are identical up to the splice minus the system's look-ahead: the
+ first 10 ms block whose difference rises above the floor (``FLOOR_DB`` under
+ the tail output's mean power) is where the future began to matter. The
+ look-ahead is the time from that block to the splice, read on every splice and
+ taken at its worst per item; an offline system reads the whole stretch before
+ the splice and is reported as reaching that boundary. A system is
+ streaming-compatible when every item's look-ahead is at most
+ ``LOOK_AHEAD_MAX_MS``.
+* **No drift over a long input.** The published render of the whole 45 s item
+ and the render of the cut are two outputs of the same fifteen seconds of
+ audio, once after 28.8 s of context and once after 3.2 s; the SI-SDR of each
+ against the reference is compared on the stretch. A model that carries state
+ should give the same answer both times. The drift is the first minus the
+ second, negative when the long context hurt; a system holds up when the mean
+ is at least ``DRIFT_MEAN_DB``, no item is under ``DRIFT_MIN_DB``, and no
+ second of speech is dropped: a second where the reference speaks, the whole
+ render sits ``DROP_DB`` under it and the fresh render keeps it within
+ ``KEEP_DB``. Reported beside these, not gated: the cold start, how the first
+ second of the cut compares with the same second inside the whole render (a
+ streaming model's fresh state, an offline model's edge of input); and, for a
+ release whose inference path depends on the input's length
+ (``path_switch_seconds`` in the wrapper's meta), that the whole item and the
+ cut took different paths, which the drift then includes.
+
+The verdict is yes when both hold on the complete inventory of long items, no
+otherwise, and the measurements are reported for every probed system so a no
+says which failed and by how much. What the probe reads is bound to what it was
+cut from and what the board scored: the probe inputs are identified by their
+samples (``probe.json``; a float WAV's bytes also carry the time it was written)
+and summarised in one identity that the receipts of every probe render record
+(``bench/wrappers/receipt.py``, for a wrapper and for ``runsystem.py --inputs``
+alike); those receipts must name one environment, the one the board's stamp
+records; every output must be exactly its input's length and finite; and the
+whole render must hash to the identity in the system's scoring records. The
+sidecar carries the rule version, the scorer digest and the output hashes it
+read, and the leaderboard shows no verdict whose rule, scorer or render has
+since changed. Output: ``<system>.stream.json`` beside the other sidecars,
+whole-set only. This is a screening probe: it establishes a bounded dependence
+on future input and stable state, not incremental delivery or real-time
+throughput.
+"""
+
+import argparse
+import glob
+import hashlib
+import json
+import os
+import sys
+
+import numpy as np
+import soundfile as sf
+import torch
+
+# pylint: disable=wrong-import-position
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import common
+import observations
+
+sys.path.insert(0, os.path.join(common.BENCH_DIR, "wrappers"))
+import receipt
+
+# scorebench supplies the sample hash the whole render is matched by; it is
+# imported where used
+SCORER_SHA256 = observations.implementation(
+ __file__,
+ common.__file__,
+ observations.__file__,
+ os.path.join(os.path.dirname(os.path.abspath(__file__)), "scorebench.py"),
+)
+# the geometry of the probe inputs; a change re-cuts the probe and its renders
+PROBE_VERSION = "3"
+# how renders are read into a verdict; a change re-reads the renders only
+RULE_VERSION = "5"
+SOURCE_CONDITION = "long@+4"
+# 153,600 samples, a multiple of every common frame hop (200, 240, 480, 512,
+GRID_SECONDS = 3.2
+# 1024, 1920, 2048 samples): a cut that starts on this grid puts its frames
+# where the whole render's frames were, so at 48 kHz the two renders differ by
+# context and not by frame placement nine grids: the measured stretch of every
+# long item begins here
+TAIL_START = 28.8
+# the real preceding audio before the stretch, so the fresh render is warm
+LEAD_IN = GRID_SECONDS
+TAIL_SECONDS = 15.0 # the measured stretch
+# seconds into the stretch where a future input changes
+SPLICES = (9.3137, 10.0, 10.6809)
+# the cold start is read on the first second of the cut
+COLD_START_SECONDS = 1.0
+BLOCK_MS = 10
+# a block differs when its difference exceeds this, relative to the tail output
+FLOOR_DB = -60.0
+# streaming-compatible: every item's look-ahead at most this
+LOOK_AHEAD_MAX_MS = 100.0
+# holds up over a long input: mean SI-SDR delta at least this
+DRIFT_MEAN_DB = -1.0
+DRIFT_MIN_DB = -3.0 # and no item under this
+# a second of the stretch holds speech when within this of its loudest second
+SPEECH_DB = 25.0
+# and is dropped when the whole render sits this far under the reference there
+DROP_DB = 20.0
+# while the fresh render keeps it, within this of the reference: speech the long
+KEEP_DB = 3.0
+# context cost, not speech the system loses either way
+MIN_ITEMS = 8 # a set with fewer long items has no probe
+
+
+def probe_dir(path: str = "") -> str:
+ """Returns the probe's directory.
+
+ The flag, ``BENCH_PROBE``, or ``probe_stream`` beside ``BENCH_OUT``.
+ """
+ return (path or os.environ.get("BENCH_PROBE") or os.path.join(
+ os.path.dirname(os.path.abspath(common.OUT_ROOT.rstrip("/"))),
+ "probe_stream",
+ ))
+
+
+def rule_sentence() -> str:
+ """One sentence saying what the streaming probe column reads."""
+ return (
+ "the streaming probe is yes when the output depends on at most"
+ f" {LOOK_AHEAD_MAX_MS:.0f} ms of future input and {TAIL_SECONDS:.0f} s"
+ f" of a 45 s item score within {-DRIFT_MEAN_DB:.0f} dB SI-SDR (no item"
+ f" under {-DRIFT_MIN_DB:.0f} dB, and no second of speech lost that a"
+ " fresh start keeps) of the same stretch processed after a"
+ f" {LEAD_IN:.1f} s lead-in")
+
+
+def source_rows(rows: list) -> list:
+ """Returns the paired long items the probe is cut from, in id order.
+
+ The complete inventory.
+ """
+ return sorted(
+ (r for r in rows
+ if r["condition"] == SOURCE_CONDITION and r.get("clean_path")),
+ key=lambda r: r["id"],
+ )
+
+
+def stem(item_id: str) -> str:
+ return item_id[:-4] if item_id.endswith(".wav") else item_id
+
+
+def cut_bounds() -> tuple:
+ """Returns the cut's first sample, the stretch's first sample and the last.
+
+ The same for every item: the cut starts a lead-in before the stretch, on the
+ frame grid.
+ """
+ a = int(round((TAIL_START - LEAD_IN) * common.SR))
+ k = int(round(TAIL_START * common.SR))
+ return a, k, k + int(round(TAIL_SECONDS * common.SR))
+
+
+def sample_sha256(path: str) -> str:
+ """Returns the identity of a probe input: its decoded samples.
+
+ As the scorer identifies every output.
+ """
+ # pylint: disable-next=import-outside-toplevel
+ import scorebench
+
+ return scorebench.sample_hash(common.load48(path))
+
+
+def identity_of(hashes) -> str:
+ """Returns one identity for a set of probe inputs.
+
+ The sha256 of their sorted sample hashes, which runfield.sh computes from
+ probe.json and runsystem.py from the files themselves.
+ """
+ return hashlib.sha256("\n".join(sorted(hashes)).encode()).hexdigest()
+
+
+def probe_hashes(probe: dict) -> list:
+ return [
+ h for e in probe["items"]
+ for h in [e["tail_sha256"]] + [f["sha256"] for f in e["futures"]]
+ ]
+
+
+def cut(mix: np.ndarray, other: np.ndarray, a: int, b: int) -> tuple:
+ """Returns (tail, [future per splice]) of one item.
+
+ The stretch [a, b) of its mixture, and the same stretch whose audio from
+ each splice on is the start of another item's stretch.
+ """
+ tail = mix[a:b].astype(np.float32)
+ futures = []
+ for splice in SPLICES:
+ # a splice sits LEAD_IN + splice into the cut
+ k = int(round((LEAD_IN + splice) * common.SR))
+ future = tail.copy()
+ future[k:] = other[a:a + len(tail) - k]
+ futures.append(future)
+ return tail, futures
+
+
+def probe_problem(root: str, rows: list) -> str | None:
+ """Returns why ``<root>/probe.json`` is not this build's probe, or None.
+
+ It must match this build, rule and inventory, with every input verified by
+ its samples.
+ """
+ path = os.path.join(root, "probe.json")
+ if not os.path.isfile(path):
+ return "no probe.json"
+ with open(path, encoding="utf-8") as fh:
+ probe = json.load(fh)
+ if probe.get("set_id") != common.set_id():
+ return (
+ f"cut from set {str(probe.get('set_id'))[:12]}, the current set is"
+ f" {str(common.set_id())[:12]}")
+ if probe.get("probe_version") != PROBE_VERSION:
+ return (
+ "cut by probe version"
+ f" {probe.get('probe_version', probe.get('rule_version'))!r}, this"
+ f" scorer cuts version {PROBE_VERSION!r}")
+ geometry = {
+ "cut_seconds": cut_bounds()[0] / common.SR,
+ "lead_in_seconds": LEAD_IN,
+ "stretch_seconds": TAIL_SECONDS,
+ "splices_seconds": [LEAD_IN + x for x in SPLICES],
+ }
+ differ = [k for k, v in geometry.items() if probe.get(k) != v]
+ if differ:
+ return ("its recorded geometry differs from this scorer's"
+ f" ({', '.join(differ)})")
+ wanted = [r["id"] for r in source_rows(rows)]
+ if [e["id"] for e in probe.get("items", [])] != wanted:
+ return (
+ "its items are not the complete inventory of the set's long items")
+ if probe.get("identity") != identity_of(probe_hashes(probe)):
+ return "its identity does not match its inputs"
+ listed = {e["tail"] for e in probe["items"]
+ } | {f["name"] for e in probe["items"] for f in e["futures"]}
+ stray = (sorted(set(os.listdir(os.path.join(root, "in"))) -
+ listed) if os.path.isdir(os.path.join(root, "in")) else [])
+ if stray: # runsystem.py --inputs identifies the directory as it stands
+ return (f"{len(stray)} files under in/ are not probe inputs (first:"
+ f" {stray[0]})")
+ for entry in probe["items"]:
+ for name, sha in [(entry["tail"], entry["tail_sha256"])] + [
+ (f["name"], f["sha256"]) for f in entry["futures"]
+ ]:
+ file = os.path.join(root, "in", name)
+ if not os.path.isfile(file) or sample_sha256(file) != sha:
+ return f"{name} is not the recorded probe input"
+ return None
+
+
+def write_probe(rows: list, root: str) -> dict:
+ """Cuts the probe inputs under ``<root>/in`` and records them.
+
+ The record is ``<root>/probe.json``; a probe that is already current is left
+ as it is, so renders made from it stay valid.
+ """
+ items = source_rows(rows)
+ if len(items) < MIN_ITEMS:
+ raise SystemExit(
+ f"{len(items)} paired items of {SOURCE_CONDITION}: the probe needs "
+ f"{MIN_ITEMS}")
+ if probe_problem(root, rows) is None:
+ with open(os.path.join(root, "probe.json"), encoding="utf-8") as fh:
+ return json.load(fh)
+ in_dir = os.path.join(root, "in")
+ os.makedirs(in_dir, exist_ok=True)
+ # the directory is exactly the probe, nothing else
+ for stale in os.listdir(in_dir):
+ os.remove(os.path.join(in_dir, stale))
+ mixes = [common.load48(r["mix_path"]).numpy() for r in items]
+ a, k, b = cut_bounds()
+ short = [r["id"] for r, m in zip(items, mixes) if len(m) < b]
+ if short:
+ raise SystemExit(
+ f"{len(short)} items of {SOURCE_CONDITION} are shorter than "
+ f"{b / common.SR:.2f} s (first: {short[0]})")
+ listed = []
+ for i, (r, mix) in enumerate(zip(items, mixes)):
+ tail, futures = cut(mix, mixes[(i + 1) % len(mixes)], a, b)
+ name = f"{stem(r['id'])}__tail.wav"
+ sf.write(os.path.join(in_dir, name), tail, common.SR, subtype="FLOAT")
+ entry = {
+ "id": r["id"],
+ "cut_seconds": a / common.SR,
+ "stretch_seconds": k / common.SR,
+ "tail": name,
+ "tail_sha256": sample_sha256(os.path.join(in_dir, name)),
+ "futures": [],
+ }
+ for j, (splice, future) in enumerate(zip(SPLICES, futures), 1):
+ name = f"{stem(r['id'])}__future{j}.wav"
+ sf.write(os.path.join(in_dir, name),
+ future,
+ common.SR,
+ subtype="FLOAT")
+ entry["futures"].append({
+ "name": name,
+ "splice_seconds": LEAD_IN + splice, # into the cut
+ "sha256": sample_sha256(os.path.join(in_dir, name)),
+ })
+ listed.append(entry)
+ probe = {
+ "probe_version": PROBE_VERSION,
+ "set_id": common.set_id(),
+ "source_condition": SOURCE_CONDITION,
+ "cut_seconds": a / common.SR,
+ "lead_in_seconds": LEAD_IN,
+ "stretch_seconds": TAIL_SECONDS,
+ "splices_seconds": [LEAD_IN + x for x in SPLICES],
+ "items": listed,
+ }
+ probe["identity"] = identity_of(probe_hashes(probe))
+ tmp = os.path.join(root, f"probe.json.{os.getpid()}.tmp")
+ with open(tmp, "w", encoding="utf-8") as fh:
+ json.dump(probe, fh, indent=1)
+ os.replace(tmp, os.path.join(root, "probe.json"))
+ return probe
+
+
+def read_probe(root: str, rows: list) -> dict:
+ """Returns the probe's manifest once its inputs are verified.
+
+ They must be the recorded files of this build, this rule and the complete
+ inventory.
+ """
+ problem = probe_problem(root, rows)
+ if problem:
+ raise SystemExit(
+ f"{os.path.join(root, 'probe.json')}: {problem}; write the probe"
+ " again (scorestream.py --probe) and re-render it")
+ with open(os.path.join(root, "probe.json"), encoding="utf-8") as fh:
+ return json.load(fh)
+
+
+def scored_outputs(results: str, name: str) -> dict:
+ """Returns {item id: hash of the output samples scored} of a system.
+
+ Read from the system's whole-set records.
+ """
+ path = os.path.join(results, f"{name}.items.jsonl")
+ if not os.path.isfile(path):
+ raise SystemExit(f"{path} is missing: score {name} before probing it")
+ metadata, records = observations.read(path)
+ if (metadata.get("set_id") != common.set_id() or
+ metadata.get("subset", "all") != "all"):
+ raise SystemExit(
+ f"{path}: records of set {str(metadata.get('set_id'))[:8]} subset "
+ f"{metadata.get('subset', 'all')!r}, not the whole current set")
+ return {r["id"]: (r.get("identity") or {}).get("output") for r in records}
+
+
+def board_meta(results: str, name: str) -> dict | None:
+ path = os.path.join(results, f"{name}.meta.json")
+ if not os.path.isfile(path):
+ return None
+ with open(path, encoding="utf-8") as fh:
+ return json.load(fh)
+
+
+def environment_problem(name: str, results: str, root: str,
+ probe: dict) -> str | None:
+ """Returns why the probe renders of ``name`` do not stand for it, or None.
+
+ They must be the board's system, on this probe.
+
+ Every probe render carries the receipts its processes wrote: they must agree
+ on the environment the board's stamp records (``render_environment_sha256``:
+ code, weights, packages, device and arguments, the inputs aside) and name
+ this probe's inputs.
+ """
+ board = board_meta(results, name)
+ if board is None:
+ return "no stamp for the board's render (meta.json missing)"
+ if not board.get("render_environment_sha256"):
+ return ("the board's stamp records no render environment: re-render the"
+ " board")
+ docs = receipt.read_all(os.path.join(root, "out", name))
+ if not docs:
+ return "the probe render carries no receipt"
+ environments = {d.get("environment_digest") for d in docs}
+ if environments != {board["render_environment_sha256"]}:
+ return (
+ "the probe was rendered in another environment than the board's"
+ " render (receipts"
+ f" {', '.join(str(e)[:12] for e in sorted(map(str, environments)))}"
+ f" vs stamp {board['render_environment_sha256'][:12]})")
+ probes = {
+ (d.get("identity", {}).get("inputs") or {}).get("probe") for d in docs
+ }
+ if probes != {probe["identity"]}:
+ return "the probe render was made from other probe inputs: re-render it"
+ return None
+
+
+def sisdr(est: np.ndarray, ref: np.ndarray) -> float:
+ g = float((est * ref).sum() / ((ref * ref).sum() + 1e-12))
+ target = g * ref
+ err = est - target
+ return float(10 * np.log10(
+ ((target * target).sum() + 1e-12) / ((err * err).sum() + 1e-12)))
+
+
+def diff_db(x: np.ndarray, y: np.ndarray) -> float:
+ """10 log10 |x - y|^2 / |y|^2 over the common length, floored at -100 dB."""
+ n = min(len(x), len(y))
+ num = float(((x[:n] - y[:n])**2).mean())
+ den = float((y[:n]**2).mean())
+ return max(-100.0, float(10 * np.log10(num / (den + 1e-14) + 1e-10)))
+
+
+def look_ahead_ms(alone: np.ndarray, future: np.ndarray,
+ splice_s: float) -> tuple:
+ """Returns (ms, capped): how far before the splice the output differs.
+
+ Read from the first block before it whose difference rises above the floor;
+ capped when that is the very first block, so the dependence reaches at least
+ to the start of the stretch.
+ """
+ block = common.SR * BLOCK_MS // 1000
+ n = min(len(alone), len(future), int(round(splice_s * common.SR)))
+ nb = n // block
+ a = alone[:nb * block].reshape(nb, block)
+ f = future[:nb * block].reshape(nb, block)
+ floor = float((alone[:n]**2).mean()) * 10**(FLOOR_DB / 10)
+ hits = np.nonzero(((a - f)**2).mean(1) > floor)[0]
+ first = int(hits[0]) if len(hits) else nb
+ return (nb - first) * BLOCK_MS, first == 0
+
+
+def probe_output(out_dir: str, name: str, n: int) -> np.ndarray:
+ """One probe output, exactly its input's length and finite, or a refusal."""
+ path = os.path.join(out_dir, name)
+ if not os.path.isfile(path):
+ raise SystemExit(
+ f"{path} is missing: the probe render must be complete")
+ y = common.load48(path).numpy()
+ if len(y) != n:
+ raise SystemExit(f"{path}: {len(y)} samples for an input of {n}")
+ if not np.isfinite(y).all():
+ raise SystemExit(f"{path}: not finite")
+ return y
+
+
+def seconds_db(x: np.ndarray) -> np.ndarray:
+ """RMS level per whole second, in dB."""
+ n = len(x) // common.SR
+ return 10 * np.log10((x[:n * common.SR].reshape(n, common.SR)**2).mean(1) +
+ 1e-12)
+
+
+def dropped(
+ whole: np.ndarray,
+ alone: np.ndarray,
+ ref: np.ndarray,
+ level_cal_db: float = 0.0,
+) -> tuple:
+ """Returns (dropped, speech) seconds of the stretch.
+
+ Speech seconds are those where the reference speaks (within SPEECH_DB of its
+ loudest second); dropped ones are those where the whole render sits DROP_DB
+ under it while the fresh render stays within KEEP_DB of it either way:
+ speech the long context cost. Both renders are read with the system's output
+ gain undone (``levels.py``), so neither a quieter nor a louder convention
+ decides it, and a fresh render made loud by noise is not speech kept.
+ """
+ r = seconds_db(ref)
+ if not r.size:
+ return 0, 0
+ w = seconds_db(whole) - level_cal_db
+ f = seconds_db(alone) - level_cal_db
+ speech = r >= r.max() - SPEECH_DB
+ lost = speech & (w <= r - DROP_DB) & (np.abs(f - r) <= KEEP_DB)
+ return int(lost.sum()), int(speech.sum())
+
+
+def path_switch(board: dict, whole_seconds: float, cut_seconds: float) -> bool:
+ """Returns whether the release takes another inference path for the cut.
+
+ As its wrapper's description declares (``path_switch_seconds`` in
+ ``wrappers/meta/<system>.json``: whole-file inference up to that length), or
+ the board's stamp when it carries the field.
+ """
+ desc = receipt.description((board or {}).get("name", "")) if board else {}
+ limit = (desc.get("path_switch_seconds") or
+ (board or {}).get("path_switch_seconds"))
+ return bool(limit) and whole_seconds > float(limit) >= cut_seconds
+
+
+def measure_item(
+ entry: dict,
+ row: dict,
+ root: str,
+ name: str,
+ scored: dict,
+ board: dict,
+ level_cal_db: float = 0.0,
+) -> dict:
+ """Returns one item's measurements.
+
+ Read after the whole render is verified to be the audio scored and every
+ probe output to be complete.
+ """
+ # pylint: disable-next=import-outside-toplevel
+ import scorebench
+
+ whole_all = common.load48(os.path.join(common.OUT_ROOT, name, row["id"]))
+ output_sha256 = scorebench.sample_hash(whole_all)
+ if not scored.get(row["id"]) or output_sha256 != scored[row["id"]]:
+ raise SystemExit(
+ f"{name}/{row['id']} is not the audio that was scored: re-score"
+ " first")
+ a = int(round(entry["cut_seconds"] * common.SR))
+ k = int(round(entry["stretch_seconds"] * common.SR)) - a # into the cut
+ n = k + int(round(TAIL_SECONDS * common.SR))
+ ref_all = common.load48(row["clean_path"])
+ # the delay and polarity the scorer undoes, found once on the whole item and
+ # undone in both renders: an aligned output must not read as drift, a lost
+ # second or a cold start
+ lag, sign = common.best_alignment(whole_all, ref_all)
+
+ def aligned(x):
+ lagged = common.apply_lag(torch.as_tensor(x), lag, len(x))
+ return (sign * lagged).numpy()
+
+ whole = aligned(whole_all.numpy())[a:a + n]
+ ref = ref_all.numpy()[a:a + n]
+ out_dir = os.path.join(root, "out", name)
+ alone_raw = probe_output(out_dir, entry["tail"], n)
+ alone = aligned(alone_raw)
+ # the cut's aligned render runs out where the shift left no sample
+ end = n - abs(lag)
+ looks = [ # two renders of one system share its delay: compared as rendered
+ look_ahead_ms(alone_raw, probe_output(out_dir, f["name"], n),
+ f["splice_seconds"]) for f in entry["futures"]
+ ]
+ r = int(COLD_START_SECONDS * common.SR)
+ cold = (sisdr(alone[:r], ref[:r]) - sisdr(whole[:r], ref[:r]) if
+ (ref[:r]**2).mean() > 1e-10 else float("nan"))
+ lost, speech = dropped(whole[k:end], alone[k:end], ref[k:end], level_cal_db)
+ return {
+ "id":
+ row["id"],
+ "output_sha256":
+ output_sha256,
+ "look_ahead_ms":
+ max(ms for ms, _ in looks),
+ # at least that much when the splice that gave the maximum reached the
+ # start of the cut
+ "look_ahead_capped":
+ any(capped for ms, capped in looks if ms == max(m for m, _ in looks)
+ ),
+ "look_ahead_by_splice_ms": [ms for ms, _ in looks],
+ "drift_db":
+ (sisdr(whole[k:end], ref[k:end]) - sisdr(alone[k:end], ref[k:end])),
+ "cold_start_db":
+ cold,
+ "dropped_seconds":
+ lost,
+ "speech_seconds":
+ speech,
+ "context_diff_db":
+ diff_db(whole[k:end], alone[k:end]),
+ "lag":
+ lag,
+ "path_switch":
+ path_switch(board,
+ len(whole_all) / common.SR, n / common.SR),
+ }
+
+
+def verdict(items: list) -> dict:
+ """Returns the streaming verdict from the per-item measurements.
+
+ The reasons come with it.
+ """
+ la = np.array([it["look_ahead_ms"] for it in items], dtype=float)
+ dr = np.array([it["drift_db"] for it in items], dtype=float)
+ lost = sum(it.get("dropped_seconds", 0) for it in items)
+ speech = sum(it.get("speech_seconds", 0) for it in items)
+ drop_items = sum(1 for it in items if it.get("dropped_seconds", 0))
+ causal = bool(la.max() <= LOOK_AHEAD_MAX_MS)
+ holds = bool(dr.mean() >= DRIFT_MEAN_DB and dr.min() >= DRIFT_MIN_DB and
+ lost == 0)
+ capped = any(it.get("look_ahead_capped") for it in items)
+ n_capped = sum(1 for it in items if it.get("look_ahead_capped"))
+ max_capped = any(
+ it.get("look_ahead_capped")
+ for it in items
+ if it["look_ahead_ms"] == la.max())
+ colds = np.array([it.get("cold_start_db", float("nan")) for it in items],
+ dtype=float)
+ reasons = []
+ if not causal:
+ reasons.append(
+ "the output depends on"
+ f" {'at least ' if max_capped else ''}{la.max():.0f} ms of future"
+ f" input (limit {LOOK_AHEAD_MAX_MS:.0f} ms)")
+ if lost:
+ reasons.append(
+ f"drops speech after a long context: {lost} of {speech} speech"
+ f" seconds on {drop_items} of {len(items)} items")
+ if dr.mean() < DRIFT_MEAN_DB or dr.min() < DRIFT_MIN_DB:
+ reasons.append(
+ f"drifts over a long input: {dr.mean():+.1f} dB SI-SDR on average,"
+ f" {dr.min():+.1f} dB at worst, on {TAIL_SECONDS:.0f} s of 45 s"
+ f" items (limits {DRIFT_MEAN_DB:+.0f} / {DRIFT_MIN_DB:+.0f})")
+ return {
+ "verdict":
+ "yes" if causal and holds else "no",
+ "causal":
+ causal,
+ "holds":
+ holds,
+ "look_ahead_ms":
+ float(np.median(la)),
+ "look_ahead_max_ms":
+ float(la.max()),
+ "look_ahead_capped":
+ capped,
+ # the median sits on the boundary
+ "look_ahead_median_capped":
+ n_capped * 2 >= len(items),
+ "look_ahead_max_capped":
+ max_capped,
+ "drift_mean_db":
+ float(dr.mean()),
+ "drift_min_db":
+ float(dr.min()),
+ "cold_start_db": (float(np.nanmean(colds))
+ if np.isfinite(colds).any() else float("nan")),
+ "dropped_seconds":
+ lost,
+ "speech_seconds":
+ speech,
+ "dropout_items":
+ drop_items,
+ "path_switch":
+ any(it.get("path_switch") for it in items),
+ "context_diff_db":
+ float(np.mean([it["context_diff_db"] for it in items])),
+ "n_items":
+ len(items),
+ "reasons":
+ reasons,
+ }
+
+
+def measure(name: str, rows: list, probe: dict, root: str,
+ results: str) -> dict:
+ """Returns every item of the probe measured through the system.
+
+ The probe's inventory was verified against the set.
+ """
+ by_id = {r["id"]: r for r in source_rows(rows)}
+ scored = scored_outputs(results, name)
+ board = board_meta(results, name) or {}
+ level_cal_db = base_calibration(results, name)
+ items = [
+ measure_item(entry, by_id[entry["id"]], root, name, scored, board,
+ level_cal_db) for entry in probe["items"]
+ ]
+ out = verdict(items)
+ out["items"] = items
+ out["rule"] = {
+ "version": RULE_VERSION,
+ "look_ahead_max_ms": LOOK_AHEAD_MAX_MS,
+ "drift_mean_db": DRIFT_MEAN_DB,
+ "drift_min_db": DRIFT_MIN_DB,
+ "speech_db": SPEECH_DB,
+ "drop_db": DROP_DB,
+ "floor_db": FLOOR_DB,
+ "cut_seconds": TAIL_START - LEAD_IN,
+ "lead_in_seconds": LEAD_IN,
+ "stretch_seconds": TAIL_SECONDS,
+ "splices_seconds": list(SPLICES),
+ "cold_start_seconds": COLD_START_SECONDS,
+ "keep_db": KEEP_DB,
+ "probe_version": PROBE_VERSION,
+ }
+ out["_level_cal_db"] = level_cal_db
+ return out
+
+
+def base_calibration(results: str, name: str) -> float:
+ """Returns the system's output gain from its base scores (``levels.py``).
+
+ 0 when it has none.
+ """
+ path = os.path.join(results, f"{name}.metrics.json")
+ if not os.path.isfile(path):
+ return 0.0
+ with open(path, encoding="utf-8") as fh:
+ return float(json.load(fh).get("_level_cal_db") or 0.0)
+
+
+def write(name: str, out: dict, rows: list, probe: dict, results: str) -> str:
+ board = board_meta(results, name) or {}
+ # the leaderboard ignores a sidecar from another build,
+ out["_set_id"] = common.set_id()
+ out["_subset"] = "all" # the probe is cut from the whole set
+ out["_rule_version"] = RULE_VERSION # another rule,
+ out["_probe_version"] = PROBE_VERSION
+ out["_scorer_sha256"] = SCORER_SHA256 # another implementation,
+ out["_probe_identity"] = probe["identity"]
+ # or another render
+ out["_render_receipt_sha256"] = board.get("render_receipt_sha256")
+ out["_outputs_sha256"] = board.get("outputs_sha256")
+ out["_sealed"] = common.is_sealed(rows)
+ path = os.path.join(results, f"{name}.stream.json")
+ tmp = f"{path}.{os.getpid()}.tmp"
+ with open(tmp, "w", encoding="utf-8") as fh:
+ json.dump(out, fh, indent=1)
+ os.replace(tmp, path)
+ return path
+
+
+def look_ahead_text(side: dict) -> str:
+ """Returns the look-ahead as shown: the median and the maximum over items.
+
+ Each is marked as at least that much when it reached the start of the cut,
+ the most the probe can observe.
+ """
+ capped = side.get("look_ahead_capped")
+ med = side.get("look_ahead_median_capped", capped)
+ top = side.get("look_ahead_max_capped", capped)
+ return (f"{'≥' if med else ''}{side['look_ahead_ms']:.0f} (max"
+ f" {'≥' if top else ''}{side['look_ahead_max_ms']:.0f})")
+
+
+def describe(out: dict) -> str:
+ cold = out.get("cold_start_db", float("nan"))
+ return (
+ f"streaming probe {out['verdict']}: look-ahead {look_ahead_text(out)}"
+ f" ms, drift {out['drift_mean_db']:+.1f} dB (min"
+ f" {out['drift_min_db']:+.1f}), cold start"
+ f" {'n/a' if cold != cold else f'{cold:+.1f} dB'}, dropped"
+ f" {out.get('dropped_seconds', 0)}/{out.get('speech_seconds', 0)}"
+ f" speech s over {out['n_items']} items" +
+ ("; the whole item and the cut take different inference paths"
+ if out.get("path_switch") else "") +
+ ("; " + "; ".join(out["reasons"]) if out["reasons"] else ""))
+
+
+def rendered(root: str) -> list:
+ return sorted(
+ os.path.basename(d)
+ for d in glob.glob(os.path.join(root, "out", "*"))
+ if os.path.isdir(d))
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser()
+ ap.add_argument(
+ "--probe",
+ action="store_true",
+ help="cut the probe inputs (or confirm the current ones) and stop",
+ )
+ ap.add_argument(
+ "--probe-dir",
+ default="",
+ help="default: BENCH_PROBE or probe_stream beside BENCH_OUT",
+ )
+ ap.add_argument(
+ "--systems",
+ default="",
+ help="comma-separated; default: every probe render",
+ )
+ a = ap.parse_args()
+ root = probe_dir(a.probe_dir)
+ rows = common.manifest(which="all")
+ common.guard_private_results(rows)
+ if a.probe:
+ before = probe_problem(root, rows)
+ probe = write_probe(rows, root)
+ n = len(probe["items"])
+ print(f"probe is current: {n} items x {1 + len(SPLICES)} inputs under"
+ f" {root}/in" if before is None else
+ (f"{n} items x {1 + len(SPLICES)} probe inputs -> {root}/in"
+ f" ({before}); renders of the earlier inputs no longer match:"
+ " render the probe again into a fresh folder (runfield.sh with"
+ " DISCARD=1, runsystem.py --overwrite)"))
+ return
+ probe = read_probe(root, rows)
+ systems = [s for s in a.systems.split(",") if s] or rendered(root)
+ os.makedirs(common.RESULTS, exist_ok=True)
+ for name in systems:
+ if name in ("INPUT", "REF"):
+ continue
+ if not os.path.isdir(os.path.join(root, "out", name)):
+ print(f"skip {name}: no probe render under {root}/out", flush=True)
+ continue
+ problem = environment_problem(name, common.RESULTS, root, probe)
+ if problem:
+ raise SystemExit(f"{name}: {problem}")
+ out = measure(name, rows, probe, root, common.RESULTS)
+ write(name, out, rows, probe, common.RESULTS)
+ print(f"{name:24s} {describe(out)}", flush=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/bench/scripts/seamtest.py b/bench/scripts/seamtest.py
new file mode 100644
index 0000000..0ecda10
--- /dev/null
+++ b/bench/scripts/seamtest.py
@@ -0,0 +1,404 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Chunk seams: whether the output depends on where the windows fell.
+
+It also reads whether the voice is hurt at the seams::
+
+ seamtest.py --model voice-isolator-v1 [--conds long@+4] [--limit 12]
+ [--windows 8/2,5/1] [--shift-seconds 1.0] [--precision fp32]
+ [--out staging/ops/<tag>.seams.json]
+
+The isolator processes long audio in overlapped windows (``chunk_seconds`` /
+``overlap_seconds``, crossfaded), and its hint frontend has windows of its own.
+Two passes per item tell the two things that matter. The clip processed as it is
+and processed again with ``--shift-seconds`` of silence in front (removed
+afterwards) differ only where the window placement mattered, so the per-block
+difference between the two outputs is the position dependence of the whole
+processing path, inside the crossfade zones and away from them. On paired items
+the voice kept (the coherent projection on the reference) and the residual (bed
+and artifacts) inside the zones against outside them are the damage the seams
+do; the worst block of a zone is judged against the worst block of stretches of
+the same length away from the seams, the same order statistic on both sides, so
+a system whose blocks merely fluctuate reads zero. Clips shorter than one window
+have no seams; their shift difference is still reported (the frontend's own
+windows and any non-determinism show there). Reports per window setting; the
+block is 100 ms.
+"""
+
+import argparse
+import json
+import os
+import sys
+
+import numpy as np
+import torch
+
+# pylint: disable=wrong-import-position
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import common
+
+FRAME = 4800 # 100 ms at 48 kHz
+DIFF_FLOOR_DB, DIFF_CEIL_DB = -100.0, 40.0
+
+
+def window_samples(chunk_seconds, overlap_seconds, sr=common.SR):
+ """Returns (chunk, overlap, hop) in samples.
+
+ Rounded and capped as the separator does.
+ """
+ chunk = int(chunk_seconds * sr)
+ overlap = min(int(overlap_seconds * sr), chunk // 2)
+ return chunk, overlap, chunk - overlap
+
+
+def seam_zones(
+ n,
+ chunk_seconds,
+ overlap_seconds,
+ shift_seconds=0.0,
+ margin_seconds=0.2,
+ sr=common.SR,
+ frame=FRAME,
+):
+ """Returns the crossfade zones of an ``n``-sample clip as block ranges.
+
+ Each zone is [first_block, last_block).
+
+ Window k (k >= 1) starts at k * hop and fades in over ``overlap`` samples
+ while window k - 1 fades out; that zone exists only when window k - 1 did
+ not already reach the end. A clip processed with ``shift_seconds`` of
+ silence in front sees the same zones ``shift`` earlier in its own
+ coordinates. ``margin_seconds`` widens every zone on both sides: seam damage
+ does not stop at the crossfade's edge.
+ """
+ chunk, overlap, hop = window_samples(chunk_seconds, overlap_seconds, sr)
+ shift, margin = int(shift_seconds * sr), int(margin_seconds * sr)
+ n_blocks = n // frame
+ zones = []
+ k = 1
+ while (k - 1) * hop + chunk < n + shift:
+ start = k * hop - shift
+ if start >= n:
+ break
+ lo, hi = max(0, start - margin), min(n, start + overlap + margin)
+ b0, b1 = lo // frame, min(n_blocks, -(-hi // frame))
+ if b1 > b0:
+ zones.append((b0, b1))
+ k += 1
+ return zones
+
+
+def seam_mask(n_blocks, zones):
+ m = torch.zeros(n_blocks, dtype=torch.bool)
+ for b0, b1 in zones:
+ m[b0:b1] = True
+ return m
+
+
+def control_windows(n_blocks, zones, width):
+ """Returns ``width``-block windows tiled over the blocks outside every zone.
+
+ Non-overlapping: the statistic read over a zone (its worst block) is read
+ over these too, so a seam is judged against what a stretch of the same
+ length shows anywhere else.
+ """
+ seam = seam_mask(n_blocks, zones)
+ out, b = [], 0
+ while b < n_blocks:
+ if bool(seam[b]):
+ b += 1
+ continue
+ e = b
+ while e < n_blocks and not bool(seam[e]) and e - b < width:
+ e += 1
+ if e - b == width:
+ out.append((b, e))
+ b = e
+ return out
+
+
+def block_diff_db(a, b, base, frame=FRAME, floor_db=40.0):
+ """Returns per-block 10 log10 |a - b|^2 / |base|^2 and the usable blocks.
+
+ The blocks where ``base`` is measurable.
+ """
+ n = min(len(a), len(b), len(base))
+ n = n // frame * frame
+ d = (a[:n] - b[:n]).reshape(-1, frame).pow(2).mean(1)
+ e = base[:n].reshape(-1, frame).pow(2).mean(1)
+ loud = (10 * torch.log10(e + 1e-12)
+ > 10 * torch.log10(e.max() + 1e-12) - floor_db)
+ # identical signals read the floor exactly
+ ratio = d / (e + 1e-12) + 10**(DIFF_FLOOR_DB / 10)
+ return (10 * torch.log10(ratio)).clamp(DIFF_FLOOR_DB, DIFF_CEIL_DB), loud
+
+
+def _mean(t):
+ return float(t.mean()) if len(t) else float("nan")
+
+
+def _zone_extremes(values, loud, zones, fn):
+ """Returns ``fn`` (min or max) of ``values`` over each zone's loud blocks.
+
+ Zones without a loud block are skipped.
+ """
+ out = []
+ for b0, b1 in zones:
+ v = values[b0:b1][loud[b0:b1]]
+ if len(v):
+ out.append(float(fn(v)))
+ return out
+
+
+def measure_item(
+ run,
+ x,
+ ref,
+ chunk_seconds,
+ overlap_seconds,
+ shift_seconds=1.0,
+ margin_seconds=0.2,
+ frame=FRAME,
+):
+ """Returns every per-item number of the report for one clip.
+
+ Both passes go through ``run(x, chunk_seconds, overlap_seconds)``; ``ref``
+ is None for a reference-free clip.
+ """
+ n = len(x)
+ y0 = run(x, chunk_seconds, overlap_seconds)[:n]
+ shift = int(shift_seconds * common.SR)
+ padded = torch.nn.functional.pad(x, (shift, 0))
+ y1 = run(padded, chunk_seconds, overlap_seconds)[shift:shift + n]
+ base = ref if ref is not None else x
+ diff, loud = block_diff_db(y0, y1, base, frame)
+ n_blocks = len(diff)
+ own = seam_zones(n,
+ chunk_seconds,
+ overlap_seconds,
+ 0.0,
+ margin_seconds,
+ frame=frame)
+ both = own + seam_zones(
+ n,
+ chunk_seconds,
+ overlap_seconds,
+ shift_seconds,
+ margin_seconds,
+ frame=frame,
+ )
+ seam_both = seam_mask(n_blocks, both)
+ seam_own = seam_mask(n_blocks, own)
+ width = max((b1 - b0 for b0, b1 in own), default=0)
+ ctrl_both = control_windows(n_blocks, both, width) if width else []
+ ctrl_own = control_windows(n_blocks, own, width) if width else []
+ seam_max = _zone_extremes(diff, loud, both, torch.max)
+ ctrl_max = _zone_extremes(diff, loud, ctrl_both, torch.max)
+ d = {
+ "seconds":
+ n / common.SR,
+ "n_blocks":
+ n_blocks,
+ "n_seam_blocks":
+ int((seam_own & loud).sum()),
+ "n_else_blocks":
+ int((~seam_both & loud).sum()),
+ "n_control_windows":
+ len(ctrl_own),
+ "shift_diff_db":
+ _mean(diff[loud]),
+ "shift_diff_seam_mean_db":
+ _mean(diff[seam_both & loud]),
+ "shift_diff_else_mean_db":
+ _mean(diff[~seam_both & loud]),
+ "shift_diff_seam_max_db":
+ (float(np.mean(seam_max)) if seam_max else float("nan")),
+ "shift_diff_else_max_db":
+ (float(np.mean(ctrl_max)) if ctrl_max else float("nan")),
+ }
+ if bool(loud.any()):
+ masked = torch.where(loud, diff,
+ torch.full_like(diff, DIFF_FLOOR_DB - 1))
+ worst = int(masked.argmax())
+ d.update({
+ "worst_block_s": worst * frame / common.SR,
+ "worst_diff_db": float(diff[worst]),
+ "worst_in_seam": bool(seam_both[worst]),
+ })
+ if ref is not None:
+ kept, resid, loudr = common.coherent_blocks(y0, ref, frame)
+ m = min(len(kept), n_blocks)
+ kept, resid, loudr, so = kept[:m], resid[:m], loudr[:m], seam_own[:m]
+ else_kept = kept[~so & loudr]
+ else_resid = resid[~so & loudr]
+ dips = _zone_extremes(kept, loudr, own, torch.min)
+ ctrl_dips = _zone_extremes(kept, loudr, ctrl_own, torch.min)
+ d.update({
+ "kept_seam_db":
+ _mean(kept[so & loudr]),
+ "kept_else_db":
+ _mean(else_kept),
+ "seam_penalty_db":
+ _mean(kept[so & loudr]) - _mean(else_kept),
+ # the worst block of a zone against the worst block of a stretch of
+ # the same length away from the seams: the same order statistic on
+ # both sides
+ "seam_dip_db": (float(np.mean(dips)) - float(np.mean(ctrl_dips))
+ if dips and ctrl_dips else float("nan")),
+ "resid_seam_db":
+ _mean(resid[so & loudr]),
+ "resid_else_db":
+ _mean(else_resid),
+ "seam_resid_excess_db":
+ (_mean(resid[so & loudr]) - _mean(else_resid)),
+ })
+ return d
+
+
+SUMMARY_KEYS = (
+ "shift_diff_db",
+ "shift_diff_seam_mean_db",
+ "shift_diff_seam_max_db",
+ "shift_diff_else_mean_db",
+ "shift_diff_else_max_db",
+ "kept_seam_db",
+ "kept_else_db",
+ "seam_penalty_db",
+ "seam_dip_db",
+ "resid_seam_db",
+ "resid_else_db",
+ "seam_resid_excess_db",
+)
+
+
+def aggregate(items):
+ """Means over items of every per-item number (NaN-aware), plus counts."""
+ out = {
+ "n_items": len(items),
+ "n_with_seams": sum(1 for d in items if d["n_seam_blocks"]),
+ }
+ for k in SUMMARY_KEYS:
+ vals = [d[k] for d in items if k in d and d[k] == d[k]]
+ out[k] = float(np.mean(vals)) if vals else float("nan")
+ worst = [
+ d["worst_in_seam"]
+ for d in items
+ if "worst_in_seam" in d and d["n_seam_blocks"]
+ ]
+ out["worst_in_seam_frac"] = float(np.mean(worst)) if worst else float("nan")
+ return out
+
+
+def parse_windows(spec, default):
+ """"8/2,5/1" -> [(8.0, 2.0), (5.0, 1.0)]; empty -> [default]."""
+ if not spec:
+ return [tuple(float(v) for v in default)]
+ out = []
+ for part in spec.split(","):
+ c, o = part.split("/")
+ out.append((float(c), float(o)))
+ return out
+
+
+def label(chunk_seconds, overlap_seconds):
+ return f"{chunk_seconds:g}/{overlap_seconds:g}"
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ common.add_model_args(ap)
+ ap.set_defaults(model="voice-isolator-v1")
+ ap.add_argument(
+ "--conds",
+ default="long@+4",
+ help="conditions (comma-separated) or a prefix",
+ )
+ ap.add_argument("--limit", type=int, default=0)
+ ap.add_argument(
+ "--windows",
+ default="",
+ help='"chunk/overlap,..." in seconds; default: the model\'s own window',
+ )
+ ap.add_argument("--shift-seconds", type=float, default=1.0)
+ ap.add_argument("--margin-seconds", type=float, default=0.2)
+ ap.add_argument("--out", default="")
+ a = ap.parse_args()
+ rows = common.pick_rows(common.manifest(), a.conds, a.limit)
+ if not rows:
+ raise SystemExit(f"no items match {a.conds!r} in {common.EVAL}")
+ vi, run = common.isolator_runner(a)
+ windows = parse_windows(a.windows, vi.model.default_window())
+ report = {
+ "check": "seams",
+ "model": common.model_tag(a.model),
+ "precision": a.precision,
+ "device": str(vi.device),
+ "mode": vi.mode,
+ "lookahead_frames": vi.lookahead_frames,
+ "set_id": common.set_id(),
+ "conds": a.conds,
+ "shift_seconds": a.shift_seconds,
+ "margin_seconds": a.margin_seconds,
+ "frame": FRAME,
+ "windows": {},
+ }
+ for chunk_seconds, overlap_seconds in windows:
+ items = []
+ for r in rows:
+ x = common.load48(r["mix_path"])
+ ref = common.load48(
+ r["clean_path"]) if r.get("clean_path") else None
+ d = measure_item(
+ run,
+ x,
+ ref,
+ chunk_seconds,
+ overlap_seconds,
+ a.shift_seconds,
+ a.margin_seconds,
+ )
+ d["id"] = r["id"]
+ items.append(d)
+ print(
+ f" {label(chunk_seconds, overlap_seconds)} {r['id']}: shift"
+ f" diff seam {d['shift_diff_seam_mean_db']:6.1f} / else"
+ f" {d['shift_diff_else_mean_db']:6.1f} dB" +
+ (f", seam dip {d['seam_dip_db']:5.1f} dB"
+ if "seam_dip_db" in d else ""),
+ flush=True,
+ )
+ report["windows"][label(chunk_seconds, overlap_seconds)] = {
+ "chunk_seconds": chunk_seconds,
+ "overlap_seconds": overlap_seconds,
+ "summary": aggregate(items),
+ "items": items,
+ }
+ out = common.ops_path(a.model, "seams", a.out)
+ os.makedirs(os.path.dirname(out), exist_ok=True)
+ with open(out, "w", encoding="utf-8") as fh:
+ json.dump(report, fh, indent=1)
+ print(f"\n{'window':>8s} {'items':>5s} {'shift seam':>10s}"
+ f" {'shift else':>10s} {'seam dip':>8s} {'resid xs':>8s}"
+ f" {'worst@seam':>10s}")
+ for w, d in report["windows"].items():
+ s = d["summary"]
+ print(
+ f"{w:>8s} {s['n_items']:5d} {s['shift_diff_seam_mean_db']:10.1f} "
+ f"{s['shift_diff_else_mean_db']:10.1f} {s['seam_dip_db']:8.1f} "
+ f"{s['seam_resid_excess_db']:8.1f} {s['worst_in_seam_frac']:10.2f}")
+ print(f"wrote {out}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/bench/scripts/setupfield.sh b/bench/scripts/setupfield.sh
new file mode 100644
index 0000000..9f937fe
--- /dev/null
+++ b/bench/scripts/setupfield.sh
@@ -0,0 +1,170 @@
+#!/usr/bin/env bash
+# Copyright 2026 Inworld AI — Apache-2.0
+#
+# Installs the board's external systems from upstream, each into its own venv.
+# Nothing third-party is vendored in this repository: code and weights are
+# fetched here, each under its own licence (bench/README.md, "Licenses of the systems compared").
+#
+# BENCH_VENVS=<venvs> BENCH_SRC=<sources> setupfield.sh [system ...]
+#
+# Every venv is synced to its lock (bench/wrappers/locks/<venv>.txt: the exact
+# packages that rendered the board), every checkout must be its pinned commit,
+# and every weight file must match its pinned sha256: any difference stops the
+# script. Each render's receipt records all of it again (wrappers/receipt.py).
+# Needs uv, git with git-lfs, curl, unzip and sha256sum.
+set -euo pipefail
+HERE=$(cd "$(dirname "$0")" && pwd)
+LOCKS=$HERE/../wrappers/locks
+UV=${UV:-uv}
+VENVS=${BENCH_VENVS:-$HOME/.cache/voice-isolation-bench/venvs}
+SRC=${BENCH_SRC:-$HOME/.cache/voice-isolation-bench/src}
+HF=https://huggingface.co
+GH=https://github.com
+mkdir -p "$VENVS" "$SRC"
+
+die () { echo " !! $*" >&2; exit 1; }
+
+pinned () { # a wheel named by its URL reads as name==version, whichever uv printed it
+ sed -E 's#^([A-Za-z0-9_.-]+) @ https://[^ ]+/[A-Za-z0-9_.]+-([^-]+)-cp[^ ]+\.whl.*#\1==\2#; s#%2B#+#g' | sort
+}
+
+locked () { # locked <lock>: its packages as uv pip freeze prints them (index options aside)
+ grep -v -E '^(#|-)' "$1" | pinned
+}
+
+frozen () { # frozen <venv>: its packages, read the same way
+ "$UV" pip freeze --python "$1/bin/python" | pinned
+}
+
+venv () { # venv <name> <python> [package built against the installed torch]
+ local name=$1 py=$2 late=${3:-} v="$VENVS/${1}_venv" lock="$LOCKS/$1.txt"
+ [ -x "$v/bin/python" ] || "$UV" venv --quiet --python "$py" "$v"
+ if [ "$(locked "$lock")" = "$(frozen "$v")" ]; then
+ echo " venv $name: at its lock"; return
+ fi
+ local first; first=$(mktemp --suffix=.txt)
+ grep -v "^$late==" "$lock" > "$first"
+ "$UV" pip sync --python "$v/bin/python" "$first"
+ rm -f "$first"
+ if [ -n "$late" ]; then
+ "$UV" pip install --python "$v/bin/python" --no-build-isolation --no-deps \
+ "$(grep "^$late==" "$lock")"
+ fi
+ [ "$(locked "$lock")" = "$(frozen "$v")" ] \
+ || die "venv $name differs from $lock"
+}
+
+clone () { # clone <dir> <repository> <commit>: a clean checkout at the pinned commit
+ local d="$SRC/$1"
+ [ -d "$d/.git" ] || git clone --quiet "$2" "$d"
+ if [ "$(git -C "$d" rev-parse HEAD)" != "$3" ]; then
+ git -C "$d" fetch --quiet origin
+ git -C "$d" -c advice.detachedHead=false checkout --quiet "$3"
+ fi
+ [ "$(git -C "$d" rev-parse HEAD)" = "$3" ] || die "$d is not at $3"
+ # upstream tracks some __pycache__ files, which running the code rewrites
+ [ -z "$(git -C "$d" status --porcelain --untracked-files=no -- . ':(exclude)*.pyc')" ] \
+ || die "$d has local changes"
+}
+
+sha () { sha256sum "$1" | cut -d' ' -f1; }
+
+check () { # check <file> <sha256>
+ [ -f "$1" ] || die "$1 is missing"
+ [ "$(sha "$1")" = "$2" ] || die "$1: sha256 $(sha "$1"), pinned $2"
+}
+
+fetch () { # fetch <file> <url> <sha256>: downloaded unless present at its pin
+ if [ ! -f "$1" ] || [ "$(sha "$1")" != "$3" ]; then
+ mkdir -p "$(dirname "$1")"
+ curl -fsSL --retry 3 -o "$1.partial" "$2"
+ mv "$1.partial" "$1"
+ fi
+ check "$1" "$3"
+}
+
+SYSTEMS=${*:-"reuse_nemotron reuse_nemotron_laughter gap_urgenet clearvoice urgent26 resemble fastenhancer dfn3 unipase smule"}
+for s in $SYSTEMS; do
+ echo "===== $s"
+ case $s in
+ reuse_nemotron) # NVIDIA NemotronLabs RE-USE: OpenMDW-1.1
+ venv reuse 3.11
+ clone reuse_nemotron "$HF/nvidia/NVIDIA-NemotronLabs-RE-USE" 31f82f2efad1095034492f236e8dac9239ba713b
+ check "$SRC/reuse_nemotron/model.safetensors" 06badaf4029b297f97f7fe48d62990b48d5482608210df577354e0d4e0ed70e1
+ ;;
+ reuse_nemotron_laughter) # NVIDIA NemotronLabs RE-USE-laughter: OpenMDW-1.1
+ venv reuse 3.11
+ clone reuse_nemotron_laughter "$HF/nvidia/NVIDIA-NemotronLabs-RE-USE-laughter" 1b1521dd659608e1e063ada83e0acfe1da473a8b
+ check "$SRC/reuse_nemotron_laughter/model.safetensors" 35c2a4e284515275d2e49a8e8cb5cd392ae67a1f1d345de1c12a0202c7b6b610
+ ;;
+ gap_urgenet) # MIT code, Apache-2.0 weights
+ venv gap_urgenet 3.10
+ clone gap-urgenet "$GH/Xiaobin-Rong/gap-urgenet" fbf467378fbfd27dd8fd8d0318c05a98eb926705
+ w="$HF/Xiaobin-Rong/gap-urgenet/resolve/f1916ff86b83777e2c3e7ecae8752a04b8d88d41"
+ while read -r f h; do fetch "$SRC/gap-urgenet/ckpts/$f" "$w/$f" "$h"; done <<'PINS'
+config.json faba0c6f14ef6066eebf93568c4914e70d03ab66fc9c969b796aed5067bc8371
+DeWavLM-Omni.pt 117a0ced06a2ccc41f5766bcc8da6aa43f98fdc336feb5997a5e5dfea1426738
+Adapter.pt 63473a9f764e4a97971530e4d7b987f9472d7b431aee6a982f25f91bcb4d48c6
+Vocoder.pt 6881d02168698de3d1083becb6b0c30d4468323f8cfed61f02afb675f4fd81b0
+Predictor.pt 1e58c270c12ab953e4df32a34e4b580f780d016bee9bf5580684d6c982f77866
+PostNet.pt d401c7572451341d1482bf35a1bc2c590b9fe8c21d17f0b4b1268e0d88d1c066
+PINS
+ ;;
+ unipase) # MIT code, Apache-2.0 weights
+ venv unipase 3.10
+ clone unipase "$GH/Xiaobin-Rong/unipase" 857b60ad05d37a2cf6d7a89883ec9fc4fc164b45
+ w="$HF/Xiaobin-Rong/unipase/resolve/f0b4d4c4411fe08fc2dddbf2d9f33260c27ac4a0"
+ while read -r f h; do fetch "$SRC/unipase/ckpts/$f" "$w/$f" "$h"; done <<'PINS'
+config.json 4c11a811af333dd8e93db110b08d1277623e906df549c8c8d5ecac9ffc633136
+DeWavLM-Omni.pt 16c94d05ff6ef2bdf08b0be2853826afda687c2d63c833382198db7682476689
+Adapter.pt 3f3f9f8076e304bc740fef5496f91528ca9ea6be7f5a63deec71cdc33471c8c7
+Vocoder_DWO-L1.pt 7595d48962c296bab2f7cb307f299acf5a02ec6a972d9ab7da3ed71b4a54a3d5
+PostNet.pt 1bf950dd2432e3cd2ef7055226b259bb3ac3fba8d7ce1f5f2424581a3d19cf63
+PINS
+ ;;
+ clearvoice) # Apache-2.0 (the clearvoice package and the checkpoint)
+ venv clearvoice 3.11
+ w="$HF/alibabasglab/MossFormer2_SE_48K/resolve/eff8c97925c8bec812af707814b3e5d777fd4503"
+ d="$SRC/clearvoice/checkpoints/MossFormer2_SE_48K"
+ fetch "$d/last_best_checkpoint" "$w/last_best_checkpoint" 315744c841441f8831cb2f896e06102b4d864776bf272febaa30c639c903e1c0
+ fetch "$d/last_best_checkpoint.pt" "$w/last_best_checkpoint.pt" 03692b9f773bbd6bb43b9c5a41f96b1e28affd66e13796b7bec66ad3d8b227c6
+ ;;
+ urgent26) # the URGENT 2026 Track-1 baselines and the challenge's evaluation toolkit (Apache-2.0)
+ venv urgent26 3.10
+ clone urgent26 "$GH/urgent-challenge/urgent2026_challenge_track1" b1dc3ad1e86419ff0bd666f455bda7936bff0e9a
+ git -C "$SRC/urgent26" submodule update --quiet --init --recursive # lib/NISQA, lib/scoreq
+ w="$HF/lichenda/icassp_2026_urgent_baseline/resolve/d4add2435a74b3f2dd54a9bbd417a058c68983b1"
+ fetch "$SRC/urgent26/ckpts/bsrnn.ckpt" "$w/bsrnn.ckpt" 5d6b24eb0ba387428f3490a36238d17902cdc96da534fd2707a8e44f0d2431c8
+ fetch "$SRC/urgent26/ckpts/flow_bsrnn.ckpt" "$w/flow_bsrnn.ckpt" f9201821243797fd5f9b852779040057b6f204267935712f96ccf0353cd9d438
+ ;;
+ resemble) # MIT (the resemble-enhance package and its weights)
+ venv resemble 3.10
+ clone resemble-enhance "$HF/ResembleAI/resemble-enhance" 4e3510ce4a8391159f665903544c5150bee7b2cb
+ check "$SRC/resemble-enhance/enhancer_stage2/ds/G/default/mp_rank_00_model_states.pt" f9d035f318de3e6d919bc70cf7ad7d32b4fe92ec5cbe0b30029a27f5db07d9d6
+ ;;
+ fastenhancer) # MIT
+ venv fastenhancer 3.11
+ fetch "$SRC/fastenhancer_onnx/fastenhancer_l.onnx" \
+ "$GH/aask1357/fastenhancer/releases/download/onnx-48khz-v1/fastenhancer_l.onnx" \
+ d7138309ec98266c668b2f86658fcc8f4e82ded67cd7fc8d6598534104b4bf89
+ ;;
+ dfn3) # MIT or Apache-2.0 (the deepfilternet package and the model of tag v0.5.6)
+ venv dfn3 3.11
+ fetch "$SRC/deepfilternet/DeepFilterNet3.zip" \
+ "$GH/Rikorose/DeepFilterNet/raw/v0.5.6/models/DeepFilterNet3.zip" \
+ 49c52edc8947ae1f9bf50d81530beaf3a2c3245aeaf34b6f31ff535cd22284d2
+ unzip -qo "$SRC/deepfilternet/DeepFilterNet3.zip" -d "$SRC/deepfilternet"
+ check "$SRC/deepfilternet/DeepFilterNet3/config.ini" 415eb925d44990d938fb739f514aa3662c1ec0ea836cff044fa1291b82cb4290
+ check "$SRC/deepfilternet/DeepFilterNet3/checkpoints/model_120.ckpt.best" 23b92884f63ccf54bb026014604625ab231657b6480df65db4095c4c171e6003
+ ;;
+ smule) # MIT code and weights
+ venv smule 3.10
+ clone smule-renaissance "$GH/smulelabs/smule-renaissance" b80e3a69c347f1290e62dddcb8e069654825aa7b
+ fetch "$SRC/smule-renaissance/smule-renaissance-small.pt" \
+ "$HF/smulelabs/Smule-Renaissance-Small/resolve/12024e3250ace99e566662a2963e6158d104e69c/smule-renaissance-small.pt" \
+ dd73b487ed058fdea66a25915f9f5a50b3d2dd97c03480f268a1d50a00fe2b06
+ ;;
+ *) die "unknown system $s" ;;
+ esac
+done
+echo "setup done -> $VENVS, $SRC"
diff --git a/bench/scripts/speedtest.py b/bench/scripts/speedtest.py
new file mode 100644
index 0000000..6699bd0
--- /dev/null
+++ b/bench/scripts/speedtest.py
@@ -0,0 +1,284 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Runtime of the public processing path on real audio, cold and warm.
+
+The cold start, the warm p50 and p95, the memory and the failures::
+
+ speedtest.py --model voice-isolator-v1 [--durations 3,10,45]
+ [--per-duration 3] [--repeat 5] [--device cuda] [--precision fp32]
+ [--out staging/ops/<tag>.speed.json]
+ speedtest.py --model voice-isolator-v1 --synthetic 30 # one noise clip
+
+Clips come from the eval set (VOICE_ISOLATION_EVALS): for every requested
+duration, the ``--per-duration`` items whose length is nearest, so the numbers
+describe real speech through the whole public path (hint frontend, resampling,
+level conditioning, chunking). The first call after loading is the cold start
+(CUDA context, kernel selection, the frontend's first pass) and is reported on
+its own; the warm figures are p50 / p95 / max over ``--repeat`` passes of every
+clip, with the realtime factor from the p50. Peak GPU memory is read after the
+warm passes. A pass that raises, returns NaN or the wrong length is a failure,
+counted and never averaged in. Prints the README's "Tested on" line and writes
+the full report as JSON.
+"""
+
+import argparse
+import json
+import os
+import platform
+import sys
+import time
+
+import numpy as np
+import soundfile as sf
+import torch
+
+# pylint: disable=wrong-import-position
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import common
+
+
+def summarize(times):
+ """p50 / p95 / max / mean of a list of seconds (NaN when empty)."""
+ if not times:
+ return {
+ "n": 0,
+ "p50": float("nan"),
+ "p95": float("nan"),
+ "max": float("nan"),
+ "mean": float("nan"),
+ }
+ t = np.array(times, dtype=float)
+ return {
+ "n": len(t),
+ "p50": float(np.percentile(t, 50)),
+ "p95": float(np.percentile(t, 95)),
+ "max": float(t.max()),
+ "mean": float(t.mean()),
+ }
+
+
+def check_output(y, n):
+ """Returns the failure reason of an output, or None when it is valid.
+
+ Valid is a finite signal of ``n`` samples.
+ """
+ try:
+ y = torch.as_tensor(y)
+ except Exception as e: # pylint: disable=broad-exception-caught
+ # whatever cannot become a tensor is not a signal
+ return f"not a signal: {e}"
+ if y.ndim != 1 or len(y) != n:
+ return f"length {tuple(y.shape)} != ({n},)"
+ if not bool(torch.isfinite(y.float()).all()):
+ return "nan"
+ return None
+
+
+def timed(run, x, clock, sync):
+ """(seconds, failure reason or None) of one pass."""
+ t0 = clock()
+ try:
+ y = run(x)
+ if sync:
+ sync()
+ except Exception as e: # pylint: disable=broad-exception-caught
+ # the failure is the measurement
+ return clock() - t0, f"raised: {e}"
+ return clock() - t0, check_output(y, len(x))
+
+
+def measure(run, clips, repeat=5, clock=time.perf_counter, sync=None):
+ """Cold start on the first clip, then ``repeat`` warm passes of every clip.
+
+ ``clips`` is a list of (group, label, x48). Returns the cold pass and, per
+ group, the warm timings, their summary, the realtime factor at the p50 and
+ the failures.
+ """
+ if not clips:
+ raise ValueError("no clips to time")
+ group0, label0, x0 = clips[0]
+ cold_s, cold_err = timed(run, x0, clock, sync)
+ report = {
+ "cold": {
+ "group": group0,
+ "clip": label0,
+ "seconds": cold_s,
+ "failure": cold_err,
+ },
+ "groups": {},
+ }
+ for group, label, x in clips:
+ g = report["groups"].setdefault(
+ group,
+ {
+ "clip_seconds": [],
+ "clips": [],
+ "times": [],
+ "failures": []
+ },
+ )
+ g["clips"].append(label)
+ g["clip_seconds"].append(len(x) / common.SR)
+ for _ in range(repeat):
+ s, err = timed(run, x, clock, sync)
+ if err:
+ g["failures"].append({
+ "clip": label,
+ "reason": err,
+ "seconds": s
+ })
+ else:
+ g["times"].append(s)
+ for g in report["groups"].values():
+ g["summary"] = summarize(g["times"])
+ secs = float(np.mean(g["clip_seconds"]))
+ g["mean_clip_seconds"] = secs
+ g["realtime_p50"] = (secs / g["summary"]["p50"]
+ if g["times"] else float("nan"))
+ g["n_failed"] = len(g["failures"])
+ return report
+
+
+def clip_seconds(rows):
+ """Returns [(row, seconds)] from the wav headers, with no decoding.
+
+ The manifest rows carry resolved paths.
+ """
+ return [(r, sf.info(r["mix_path"]).duration) for r in rows]
+
+
+def pick_clips(rows_with_seconds, durations, per_duration):
+ """Returns, for every requested duration, the rows nearest in length.
+
+ ``per_duration`` rows per duration, no row serving two durations: [(group
+ label, row, seconds)], one group per duration.
+ """
+ out, used = [], set()
+ for d in durations:
+ near = sorted(rows_with_seconds,
+ key=lambda rs, d=d: (abs(rs[1] - d), rs[0]["id"]))
+ for r, s in [rs for rs in near if rs[0]["id"] not in used
+ ][:per_duration]:
+ out.append((f"{d:g}s", r, s))
+ used.add(r["id"])
+ return out
+
+
+def readme_line(report, memory):
+ """Returns the README's "Tested on" cell.
+
+ Every group at its p50, then the memory.
+ """
+ parts = []
+ for name, g in report["groups"].items():
+ p50 = g["summary"]["p50"]
+ if p50 != p50:
+ parts.append(f"{name} clip: every pass failed")
+ continue
+ parts.append(f"{g['mean_clip_seconds']:.0f} s clip in {p50:.1f} s "
+ f"({g['realtime_p50']:.1f}× realtime)")
+ return "; ".join(parts) + f"; {memory}"
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ common.add_model_args(ap)
+ ap.set_defaults(model="voice-isolator-v1")
+ ap.add_argument("--durations",
+ default="3,10,45",
+ help="seconds, comma-separated")
+ ap.add_argument("--per-duration", type=int, default=3)
+ ap.add_argument("--repeat", type=int, default=5)
+ ap.add_argument(
+ "--synthetic",
+ type=float,
+ default=0.0,
+ help="time one S-second noise clip",
+ )
+ ap.add_argument("--chunk-seconds", type=float, default=None)
+ ap.add_argument("--overlap-seconds", type=float, default=None)
+ ap.add_argument("--out", default="")
+ a = ap.parse_args()
+ vi, run_ = common.isolator_runner(a)
+
+ def run(x):
+ return run_(x, a.chunk_seconds, a.overlap_seconds)
+
+ dev = vi.device
+ if a.synthetic:
+ g = torch.Generator().manual_seed(0)
+ clips = [(
+ f"{a.synthetic:g}s",
+ "synthetic noise",
+ torch.randn(int(a.synthetic * common.SR), generator=g) * 0.3,
+ )]
+ else:
+ rows = common.pick_rows(common.manifest(), "", 0)
+ durations = [float(v) for v in a.durations.split(",") if v]
+ picked = pick_clips(clip_seconds(rows), durations, a.per_duration)
+ clips = [
+ (grp, r["id"], common.load48(r["mix_path"])) for grp, r, _ in picked
+ ]
+ sync = torch.cuda.synchronize if dev.type == "cuda" else None
+ if dev.type == "cuda":
+ torch.cuda.reset_peak_memory_stats(dev)
+ report = measure(run, clips, a.repeat, sync=sync)
+ memory = (
+ f"{torch.cuda.max_memory_allocated(dev) / 2**30:.1f} GB peak GPU memory"
+ if dev.type == "cuda" else "CPU")
+ name = (torch.cuda.get_device_name(dev)
+ if dev.type == "cuda" else platform.processor() or "cpu")
+ report.update({
+ "check": "speed",
+ "model": common.model_tag(a.model),
+ "device": name,
+ "device_type": dev.type,
+ "precision": a.precision,
+ "mode": vi.mode,
+ "lookahead_frames": vi.lookahead_frames,
+ "chunk_seconds": (a.chunk_seconds if a.chunk_seconds is not None else
+ vi.model.default_window()[0]),
+ "overlap_seconds": (a.overlap_seconds if a.overlap_seconds is not None
+ else vi.model.default_window()[1]),
+ "threads": torch.get_num_threads(),
+ "torch": torch.__version__,
+ "cuda": torch.version.cuda,
+ "python": platform.python_version(),
+ "synthetic": bool(a.synthetic),
+ "set_id": None if a.synthetic else common.set_id(),
+ "peak_memory": memory,
+ "readme_line": readme_line(report, memory),
+ })
+ print(f"device: {name} precision {a.precision} torch {torch.__version__} "
+ f" cuda {torch.version.cuda} python {platform.python_version()}")
+ c = report["cold"]
+ print(f"cold start: {c['seconds']:.2f} s on {c['clip']}" +
+ (f" FAILED {c['failure']}" if c["failure"] else ""))
+ for grp, g in report["groups"].items():
+ s = g["summary"]
+ print(
+ f"{grp:>5s} ({g['mean_clip_seconds']:5.1f} s, {len(g['clips'])}"
+ f" clips x {a.repeat}): p50 {s['p50']:6.2f} s p95 {s['p95']:6.2f} "
+ f" max {s['max']:6.2f} {g['realtime_p50']:5.1f}x realtime failed"
+ f" {g['n_failed']}")
+ print(report["readme_line"])
+ out = common.ops_path(a.model, "speed", a.out)
+ os.makedirs(os.path.dirname(out), exist_ok=True)
+ with open(out, "w", encoding="utf-8") as fh:
+ json.dump(report, fh, indent=1)
+ print(f"wrote {out}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/bench/scripts/stamprender.py b/bench/scripts/stamprender.py
new file mode 100644
index 0000000..fd39f57
--- /dev/null
+++ b/bench/scripts/stamprender.py
@@ -0,0 +1,279 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Stamps a complete, verified render of one system, or refuses.
+
+ python bench/scripts/stamprender.py <system> --wrapper path/runX.py \\
+ --inputs IN --outputs OUT --results RES --set-id ID \\
+ --wrapper-exit N --probe-digest D
+
+A render is stamped (``<RES>/<system>.meta.json``: the system's description
+plus the identity of the run) only when every check holds:
+
+* the renderer exited zero: a failed run is never stamped, whatever it left;
+* every process that rendered left a receipt (``wrappers/receipt.py``), every
+ receipt names this system and this renderer, all carry one identity digest,
+ and that digest equals the environment and inputs being stamped
+ (``--probe-digest``, from ``receipt.py probe`` in the same venv), so outputs
+ of two backends, two checkpoints or two set builds are never one system;
+* the receipts' inputs are the set build being stamped (``--set-id``);
+* the inventory is exact: every input has an output of the same name, a
+ 48 kHz mono float32 WAV of exactly the input's length with only finite
+ samples; stray files are ignored, not counted. Outputs that are entirely
+ silent are counted in the stamp, not refused: silence can be a system's
+ answer, and the scorer reads it as one.
+
+The stamp records the agreed identity (``render_receipt``), its digest
+(``render_receipt_sha256``) and that of its environment without the inputs
+(``render_environment_sha256``); the scorer copies them into every record.
+It also records ``outputs_sha256``, a digest of every output's bytes: each
+score file carries the digest of the render it read, and the board refuses a
+score of other audio than the render stamped now.
+``runsystem.py`` stamps its own renders through ``stamp`` with its
+description and the subset it rendered.
+"""
+
+import argparse
+import datetime
+import glob
+import hashlib
+import io
+import json
+import os
+import sys
+
+import numpy as np
+import soundfile as sf
+
+BENCH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+REPO = os.path.dirname(BENCH)
+# pylint: disable=wrong-import-position
+sys.path.insert(0, os.path.join(BENCH, "wrappers"))
+import receipt # pylint: disable=wrong-import-position
+
+SR = 48000
+
+
+def check_receipts(out_dir: str, system: str, wrapper: str, set_id: str,
+ probe_digest: str) -> dict:
+ """Returns the one identity every receipt in ``out_dir`` agrees on.
+
+ Raises:
+ SystemExit: A receipt is missing, retroactive, of another system,
+ renderer or set build, or of another environment.
+ """
+ docs = receipt.read_all(out_dir)
+ if not docs:
+ raise SystemExit(f"{out_dir}: no render receipt; render it with a "
+ "renderer that calls receipt.begin")
+ if any(d.get("retroactive") for d in docs):
+ raise SystemExit(f"{out_dir}: a receipt was written after the render; "
+ "only receipts taken as the render began are trusted")
+ digests = {d["digest"] for d in docs}
+ if len(digests) != 1:
+ raise SystemExit(
+ f"{out_dir}: {len(docs)} receipts carry {len(digests)} "
+ "identities: outputs of different code, weights or "
+ "environments were mixed; render again")
+ if probe_digest not in digests:
+ raise SystemExit(
+ f"{out_dir}: the receipts name another environment or "
+ "other inputs than the ones being stamped: render again")
+ ident = docs[0]["identity"]
+ if ident.get("system") != system:
+ raise SystemExit(
+ f"{out_dir}: rendered as {ident.get('system')!r}, not {system!r}")
+ if ident.get("wrapper") != os.path.basename(wrapper):
+ raise SystemExit(f"{out_dir}: rendered by {ident.get('wrapper')!r}, "
+ f"not {os.path.basename(wrapper)!r}")
+ if (ident.get("inputs") or {}).get("set_id") != set_id:
+ raise SystemExit(
+ f"{out_dir}: rendered from {ident.get('inputs')}, not set {set_id}")
+ return {
+ "identity": ident,
+ "digest": docs[0]["digest"],
+ "environment_digest": receipt.environment_digest(ident),
+ "n_receipts": len(docs),
+ "first": min(d["time"] for d in docs),
+ "last": max(d["time"] for d in docs),
+ }
+
+
+def digest_of(hashes: dict) -> str:
+ """Returns the outputs digest of {output name: sha256 of its bytes}.
+
+ The sha256 of one line per output, its name and the sha256 of its bytes,
+ in name order: what a stamp vouches for, and what a scorer recomputes from
+ the bytes it read.
+ """
+ lines = [f"{name} {hashes[name]}" for name in sorted(hashes)]
+ return hashlib.sha256("\n".join(lines).encode()).hexdigest()
+
+
+def outputs_digest(files: list, out_dir: str) -> str:
+ """Returns the digest of the outputs in ``out_dir`` answering ``files``.
+
+ What ``check_inventory`` computes for a stamp, for a render linked in rather
+ than stamped.
+ """
+ hashes = {}
+ for path in files:
+ name = os.path.basename(path)
+ with open(os.path.join(out_dir, name), "rb") as fh:
+ hashes[name] = hashlib.sha256(fh.read()).hexdigest()
+ return digest_of(hashes)
+
+
+def check_inventory(files: list, out_dir: str) -> tuple[int, int, str]:
+ """Returns (outputs, silent ones, digest) once every input has a valid one.
+
+ The digest is the sha256 of one line per output, its name and the sha256
+ of its bytes, in name order: the exact audio the stamp vouches for.
+
+ Args:
+ files: The input files the render must answer.
+ out_dir: The render.
+
+ Raises:
+ SystemExit: An output is missing, a link (a render writes files; a
+ folder linked in is stamped by runsystem.py --outputs, never
+ here), of another format or length, or holds NaN or inf.
+ """
+ if not files:
+ raise SystemExit(f"{out_dir}: no inputs to answer")
+ missing, bad, silent, hashes = [], [], 0, {}
+ for path in sorted(files, key=os.path.basename):
+ name = os.path.basename(path)
+ out = os.path.join(out_dir, name)
+ if not os.path.isfile(out):
+ missing.append(name)
+ continue
+ if os.path.islink(out):
+ bad.append(f"{name}: a link to {os.readlink(out)}")
+ continue
+ with open(out, "rb") as fh:
+ data = fh.read()
+ hashes[name] = hashlib.sha256(data).hexdigest()
+ try:
+ info, want = sf.info(io.BytesIO(data)), sf.info(path)
+ except RuntimeError as e: # not a readable sound file
+ bad.append(f"{name}: {e}")
+ continue
+ if (info.samplerate, info.channels, info.subtype) != (SR, 1, "FLOAT"):
+ bad.append(f"{name}: {info.samplerate} Hz, {info.channels} ch, "
+ f"{info.subtype}")
+ elif info.frames != want.frames:
+ bad.append(f"{name}: {info.frames} frames for {want.frames}")
+ else:
+ samples, _ = sf.read(io.BytesIO(data), dtype="float32")
+ if not np.isfinite(samples).all():
+ bad.append(f"{name}: NaN or inf")
+ elif not samples.any():
+ silent += 1
+ if missing or bad:
+ head = "; ".join(missing[:3] + bad[:3])
+ raise SystemExit(
+ f"{out_dir}: {len(missing)} outputs missing, {len(bad)} "
+ f"invalid (first: {head})")
+ return len(files), silent, digest_of(hashes)
+
+
+def stamp(
+ system: str,
+ renderer: str,
+ files: list,
+ out_dir: str,
+ results: str,
+ set_id: str,
+ probe_digest: str,
+ desc: dict,
+ subset: str = "all",
+) -> dict:
+ """Writes ``<results>/<system>.meta.json`` for a verified render.
+
+ Args:
+ system: The system's name.
+ renderer: The script that rendered it.
+ files: The inputs it had to answer.
+ out_dir: The render.
+ results: Where the stamp goes.
+ set_id: The set build the inputs belong to.
+ probe_digest: The identity digest the environment gives now.
+ desc: The system's description, the stamp's first fields.
+ subset: The part of the set the files are (``BENCH_SUBSET``).
+
+ Returns:
+ The stamp.
+ """
+ receipts = check_receipts(out_dir, system, renderer, set_id, probe_digest)
+ now = datetime.datetime.now(datetime.timezone.utc)
+ n, silent, outputs = check_inventory(files, out_dir)
+ meta = dict(desc)
+ meta.update(
+ name=system,
+ wrapper=os.path.relpath(os.path.abspath(renderer), REPO),
+ wrapper_sha256=receipts["identity"]["wrapper_sha256"],
+ set_id=set_id,
+ subset=subset,
+ n_files=n,
+ n_silent=silent,
+ outputs_sha256=outputs,
+ rendered_at=receipts["last"],
+ stamped_at=now.strftime("%Y-%m-%dT%H:%MZ"),
+ render_receipt=receipts,
+ render_receipt_sha256=receipts["digest"],
+ render_environment_sha256=receipts["environment_digest"],
+ )
+ meta.setdefault("display", system)
+ os.makedirs(results, exist_ok=True)
+ dst = os.path.join(results, f"{system}.meta.json")
+ tmp = f"{dst}.{os.getpid()}.tmp"
+ with open(tmp, "w", encoding="utf-8") as fh:
+ json.dump(meta, fh, indent=1)
+ os.replace(tmp, dst)
+ return meta
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("system")
+ ap.add_argument("--wrapper", required=True, help="the renderer's path")
+ ap.add_argument("--inputs", required=True)
+ ap.add_argument("--outputs", required=True)
+ ap.add_argument("--results", required=True)
+ ap.add_argument("--set-id", required=True)
+ ap.add_argument("--wrapper-exit", type=int, required=True)
+ ap.add_argument("--probe-digest", required=True)
+ a = ap.parse_args()
+ if a.wrapper_exit != 0:
+ raise SystemExit(f"{a.system}: the renderer exited {a.wrapper_exit}; "
+ "a failed run is not stamped")
+ files = glob.glob(os.path.join(a.inputs, "*.wav"))
+ meta = stamp(
+ a.system,
+ a.wrapper,
+ files,
+ a.outputs,
+ a.results,
+ a.set_id,
+ a.probe_digest,
+ receipt.description(a.system),
+ )
+ print(f" stamped {a.system}: {meta['n_files']} files "
+ f"({meta['n_silent']} silent), "
+ f"{meta['render_receipt']['n_receipts']} receipt(s), identity "
+ f"{meta['render_receipt_sha256'][:12]}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/bench/scripts/streamview.py b/bench/scripts/streamview.py
new file mode 100644
index 0000000..2ed6dc2
--- /dev/null
+++ b/bench/scripts/streamview.py
@@ -0,0 +1,243 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The streaming probe on the board: its sidecars, its cell and its table.
+
+The probe is scored by scorestream.py; a sidecar is shown only while its set,
+rule, scorer and the render it compared with are the board's. The scorer
+records every item's look-ahead, drift and dropped seconds under its rule,
+which fixes how renders are read; the board judges those measurements with
+the limits declared here, so a limit can move without reading a render again
+and every system is judged alike.
+"""
+
+import json
+import os
+import sys
+
+import scorefiles
+import scorestream
+
+STREAM_EXT = ".stream.json"
+# the board's verdict policy over the recorded per-item measurements
+LOOK_AHEAD_MAX_MS = scorestream.LOOK_AHEAD_MAX_MS
+DRIFT_MEAN_DB = scorestream.DRIFT_MEAN_DB
+DRIFT_MIN_DB = -5.0 # no item under this (the scorer records under -3)
+
+
+def rule_sentence() -> str:
+ """One sentence saying what the streaming probe column reads."""
+ return (
+ "the streaming probe is yes when the output depends on at most"
+ f" {LOOK_AHEAD_MAX_MS:.0f} ms of future input and"
+ f" {scorestream.TAIL_SECONDS:.0f} s of a 45 s item score within"
+ f" {-DRIFT_MEAN_DB:.0f} dB SI-SDR (no item under"
+ f" {-DRIFT_MIN_DB:.0f} dB, and no second of speech lost that a fresh"
+ " start keeps) of the same"
+ f" stretch processed after a {scorestream.LEAD_IN:.1f} s lead-in")
+
+
+def judged(side: dict) -> dict:
+ """Returns the sidecar with the board's verdict over its recorded items.
+
+ A sidecar without per-item measurements keeps the scorer's verdict.
+ """
+ items = [
+ it for it in side.get("items", [])
+ if "drift_db" in it and "look_ahead_ms" in it
+ ]
+ if not items:
+ return side
+ ahead = max(float(it["look_ahead_ms"]) for it in items)
+ drifts = [float(it["drift_db"]) for it in items]
+ mean, low = sum(drifts) / len(drifts), min(drifts)
+ lost = sum(it.get("dropped_seconds", 0) for it in items)
+ speech = sum(it.get("speech_seconds", 0) for it in items)
+ dropped = sum(1 for it in items if it.get("dropped_seconds", 0))
+ capped = any(
+ it.get("look_ahead_capped")
+ for it in items
+ if float(it["look_ahead_ms"]) == ahead)
+ causal = ahead <= LOOK_AHEAD_MAX_MS
+ holds = mean >= DRIFT_MEAN_DB and low >= DRIFT_MIN_DB and lost == 0
+ reasons = []
+ if not causal:
+ reasons.append(
+ f"the output depends on {'at least ' if capped else ''}{ahead:.0f}"
+ f" ms of future input (limit {LOOK_AHEAD_MAX_MS:.0f} ms)")
+ if lost:
+ reasons.append(
+ f"drops speech after a long context: {lost} of {speech} speech"
+ f" seconds on {dropped} of {len(items)} items")
+ if mean < DRIFT_MEAN_DB or low < DRIFT_MIN_DB:
+ reasons.append(
+ f"drifts over a long input: {mean:+.1f} dB SI-SDR on average,"
+ f" {low:+.1f} dB at worst, on {scorestream.TAIL_SECONDS:.0f} s of"
+ f" 45 s items (limits {DRIFT_MEAN_DB:+.0f} / {DRIFT_MIN_DB:+.0f})")
+ out = dict(side)
+ out.update(
+ verdict="yes" if causal and holds else "no",
+ causal=causal,
+ holds=holds,
+ reasons=reasons,
+ rule=dict(side.get("rule") or {},
+ board_look_ahead_max_ms=LOOK_AHEAD_MAX_MS,
+ board_drift_mean_db=DRIFT_MEAN_DB,
+ board_drift_min_db=DRIFT_MIN_DB),
+ )
+ return out
+
+
+def _stale_streaming(side, d, records):
+ """Returns why a streaming sidecar may not be shown, or None.
+
+ Another build, another probe rule, another scorer, another render than the
+ base scores read, or whole-render outputs other than the ones the base
+ records scored (``records``: the system's per-item record file, when at
+ hand).
+ """
+ if side.get("_set_id") != d.get("_set_id"):
+ return (f"probed on set {str(side.get('_set_id'))[:12]}, metrics on "
+ f"{str(d.get('_set_id'))[:12]}")
+ if side.get("_rule_version") != scorestream.RULE_VERSION:
+ return (f"follows probe rule {side.get('_rule_version')!r}, the current"
+ f" rule is {scorestream.RULE_VERSION!r}")
+ if side.get("_scorer_sha256") != scorestream.SCORER_SHA256:
+ return "scored by another implementation of the probe"
+ if side.get("_outputs_sha256") != d.get("_outputs_sha256"):
+ return "compared with another render than the base scores read"
+ outputs = scorefiles.record_outputs(records)
+ if outputs:
+ stale = [
+ it["id"] for it in side.get("items", []) if outputs.get(
+ it["id"], it.get("output_sha256")) != it.get("output_sha256")
+ ]
+ if stale:
+ return (f"read other outputs than the base scores for {len(stale)}"
+ f" items ({stale[0]})")
+ return None
+
+
+def load_streaming(results, scores):
+ """Returns {system: its streaming sidecar} for current probes.
+
+ The systems whose probe was scored on this build with the current rule and
+ scorer, on the outputs the base scores read; anything else is ignored with a
+ warning, never shown. The probe is cut from the whole set, so a subset view
+ (results scored with ``BENCH_SUBSET``) reads the sidecar of the whole-set
+ directory beside it when its own has none.
+ """
+ out = {}
+ for name, d in scores.items():
+ dirs = [results]
+ if d.get("_subset", "all") != "all":
+ dirs.append(os.path.dirname(os.path.abspath(results.rstrip("/"))))
+ for where in dirs:
+ path = os.path.join(where, f"{name}{STREAM_EXT}")
+ if not os.path.isfile(path):
+ continue
+ with open(path, encoding="utf-8") as fh:
+ side = json.load(fh)
+ if bool(side.get("_sealed")) != bool(d.get("_sealed")):
+ raise ValueError(
+ f"{name}{STREAM_EXT}: private/public scope differs from its"
+ " base metrics")
+ why = _stale_streaming(side, d,
+ os.path.join(where, f"{name}.items.jsonl"))
+ if why:
+ print(
+ f"[warn] {os.path.basename(path)} {why}: ignored, re-run"
+ " scorestream.py",
+ file=sys.stderr,
+ )
+ continue
+ out[name] = judged(side)
+ break
+ return out
+
+
+def streaming_cell(stream, name):
+ """yes, no, or – for a system that was not probed."""
+ side = (stream or {}).get(name)
+ return (side["verdict"]
+ if side and side.get("verdict") in ("yes", "no") else "–")
+
+
+def streaming_summary(side):
+ """Returns what the JSON carries of a streaming sidecar.
+
+ The verdict and the measurements behind it.
+ """
+ keys = (
+ "verdict",
+ "causal",
+ "holds",
+ "look_ahead_ms",
+ "look_ahead_max_ms",
+ "look_ahead_capped",
+ "look_ahead_median_capped",
+ "look_ahead_max_capped",
+ "drift_mean_db",
+ "drift_min_db",
+ "cold_start_db",
+ "dropped_seconds",
+ "speech_seconds",
+ "dropout_items",
+ "path_switch",
+ "context_diff_db",
+ "n_items",
+ "reasons",
+ "rule",
+ )
+ return {k: side.get(k) for k in keys}
+
+
+def markdown_streaming(stream, order, tiers):
+ """Returns the streaming probe of the ranked systems as markdown.
+
+ In board order: the measurements behind the yes or no, then the systems not
+ probed.
+ """
+ ranked = [n for rows in order.values() for n in rows]
+ lines = [
+ ("| system | future input (ms) | drift over a long input (dB) | cold"
+ " start (dB) | speech dropped (s) | streaming probe |"),
+ "|---|---|---|---|---|---|",
+ ]
+ switched = False
+ for n in ranked:
+ side = stream.get(n)
+ if not side:
+ continue
+ cold = side.get("cold_start_db")
+ cold_text = "–" if cold is None or cold != cold else f"{cold:+.1f}"
+ mark = " †" if side.get("path_switch") else ""
+ switched = switched or bool(side.get("path_switch"))
+ lines.append(f"| {tiers[n][1]} | {scorestream.look_ahead_text(side)} |"
+ f" {side['drift_mean_db']:+.1f} (min"
+ f" {side['drift_min_db']:+.1f}){mark} | {cold_text} |"
+ f" {side.get('dropped_seconds', 0)} of"
+ f" {side.get('speech_seconds', 0)} | {side['verdict']} |")
+ text = "\n".join(lines)
+ notes = []
+ if switched:
+ notes.append(
+ "† the release takes different inference paths for the whole item"
+ " and the cut (whole-file inference up to a length, segmented"
+ " beyond), so this difference includes the change of path.")
+ missing = [tiers[n][1] for n in ranked if n not in stream]
+ if missing:
+ notes.append("Not probed: " + ", ".join(missing) + ".")
+ if notes:
+ text += "\n\n" + "\n".join(notes)
+ return text
diff --git a/bench/scripts/tables.py b/bench/scripts/tables.py
new file mode 100644
index 0000000..69415bc
--- /dev/null
+++ b/bench/scripts/tables.py
@@ -0,0 +1,210 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The board as markdown tables, for the README and the page's sources."""
+
+import anchors
+import ranking
+import scorefiles
+import streamview
+
+SHORT = {
+ "suppression": "supp",
+ "preservation": "pres",
+ "fidelity": "fidel",
+ "quality": "qual",
+}
+
+
+def _marked(stream, name):
+ """The mark after a system's name: the streaming probe says yes."""
+ return STREAM_MARK[streamview.streaming_cell(stream, name) == "yes"]
+
+
+def _view(board):
+ """Returns (score column, parts, axes inside) of one board's view.
+
+ Without boards the composite's: its column, every part, no filter.
+ """
+ boards = ranking.BOARDS or {}
+ if not boards:
+ return "score", list(ranking.PARTS or {}), None
+ shown = board or ranking.ranking_board()
+ parts = list(boards[shown])
+ return shown, parts, [a for p in parts for a in ranking.PARTS[p]]
+
+
+def _markdown_rows(scores,
+ axis_scores,
+ comp,
+ rows,
+ tiers,
+ axes,
+ sfx,
+ stream=None,
+ precision=None,
+ board=None):
+ """Returns one tier of one board's view as a markdown table.
+
+ The board's score, the parts it reads and their axes, the axes scored
+ beside every score, then the diagnostics.
+ """
+ column, parts, inside = _view(board)
+ names = [
+ a for a in ranking.axis_order(axes)
+ if inside is None or a in inside or a in ranking.OUTSIDE
+ ]
+ head = (["#", "system", "precision", column] + parts +
+ [SHORT.get(a, a) for a in names] + [
+ "supp dB" + (" (0–8 kHz)" if sfx else ""),
+ "pauses dB",
+ "del %",
+ "laughs lost %",
+ "NISQA",
+ ])
+ lines = ["| " + " | ".join(head) + " |", "|" + "---|" * len(head)]
+ for i, n in enumerate(rows, 1):
+ d = scores[n]
+ scored = anchors.part_scores(axis_scores[n], ranking.PARTS)
+ # a view without the recordings has none
+ lost = scorefiles.get(d, "nonverbal@+0", "nv_lost_pct")
+ value = (ranking.board_scores(axis_scores[n])[column]
+ if ranking.BOARDS else comp[n])
+ cells = ([
+ str(i),
+ tiers[n][1] + _marked(stream, n),
+ (precision or {}).get(n, "–"),
+ f"**{value:.3f}**",
+ ] + [f"{scored[k]:.2f}" for k in parts] + [
+ f"{axis_scores[n].get(k, ranking.NAN):.2f}" for k in names
+ ] + [
+ f"{scorefiles.get(d, 'babble@+4', 'babble_resid_db' + sfx):.1f}",
+ f"{scorefiles.get(d, '_real_cleanup', 'pause_level_db'):.1f}",
+ f"{scorefiles.get(d, '_deletion', 'pct'):.1f}",
+ "–" if lost != lost else f"{lost:.1f}",
+ f"{scorefiles.get(d, 'babble@+4', 'nisqa_mos'):.2f}",
+ ])
+ lines.append("| " + " | ".join(cells) + " |")
+ return "\n".join(lines)
+
+
+def markdown_table(scores,
+ axis_scores,
+ comp,
+ order,
+ tiers,
+ stream=None,
+ precision=None):
+ """Full-band tier as a GitHub-flavoured markdown table: the view of the
+ board that orders the table."""
+ return _with_streaming_note(
+ _markdown_rows(scores, axis_scores, comp, order["full"], tiers,
+ ranking.AXES_FULL, "", stream, precision), stream,
+ order["full"])
+
+
+def board_lead(board):
+ """One line saying which systems a board ranks, and by what."""
+ if board == ranking.restoration_board():
+ return (f"**{board.capitalize()}**: the systems that restore above the"
+ f" input's band (more than {ranking.ASSIGN['above_db']:g} dB"
+ f" on the band-limited rows), ordered by their {board} score.")
+ return (f"**{board.capitalize()}**: the systems that add nothing above the"
+ f" input's band, ordered by their {board} score.")
+
+
+def markdown_boards(scores,
+ axis_scores,
+ comp,
+ order,
+ tiers,
+ stream=None,
+ precision=None):
+ """Returns every board's view of the full-band tier (for the README), each
+ after its lead, with the streaming note once; without boards, the one
+ table."""
+ if not ranking.BOARDS:
+ return markdown_table(scores, axis_scores, comp, order, tiers, stream,
+ precision)
+ blocks, shown = [], []
+ for board in ranking.BOARDS:
+ rows = (order["full"]
+ if board == ranking.ranking_board() else order.get(board, []))
+ blocks.append(
+ board_lead(board) + "\n\n" +
+ _markdown_rows(scores, axis_scores, comp, rows, tiers,
+ ranking.AXES_FULL, "", stream, precision, board))
+ shown += rows
+ return _with_streaming_note("\n\n".join(blocks), stream, shown)
+
+
+def _with_streaming_note(table, stream, rows):
+ """The table, with the note on the mark when any row carries it."""
+ if any(streamview.streaming_cell(stream, n) == "yes" for n in rows):
+ return table + "\n\n" + STREAMING_NOTE
+ return table
+
+
+# the mark after a system's name: the streaming probe says yes
+STREAM_MARK = {True: "\\*", False: ""}
+STREAMING_NOTE = "\\* streaming: " + streamview.rule_sentence() + "."
+
+NB_LEAD = ("The 16 kHz tier, scored inside 0–8 kHz on the same items and not"
+ " comparable to the full-band tier's boards above: suppression,"
+ " speaker similarity and passthrough are read on the band-limited"
+ " signals, and there is no"
+ " high-band term.")
+
+
+def markdown_table_nb(scores,
+ axis_scores,
+ comp,
+ order,
+ tiers,
+ stream=None,
+ precision=None):
+ """Returns the 16 kHz tier as a markdown table, empty without entrants."""
+ rows = order.get("nb", [])
+ if not rows:
+ return ""
+ return _with_streaming_note(
+ _markdown_rows(scores, axis_scores, comp, rows, tiers, ranking.AXES_NB,
+ "_nb", stream, precision), stream, rows)
+
+
+def markdown_outside(axis_scores, order, tiers, axes=None):
+ """Returns one markdown table per axis, in the axis's own order.
+
+ The axes scored beside the composite (so what the composite does not read is
+ published all the same) and any named in ``axes``, for a section that lists
+ the board by one axis.
+ """
+ blocks = []
+ for axis in list(ranking.OUTSIDE) + [
+ a for a in axes or () if a not in ranking.OUTSIDE
+ ]:
+ # every ranked full-band system, whichever board ranks it
+ ranked = [n for key in order if key != "nb" for n in order[key]]
+ rows = [
+ n for n in ranked
+ if axis_scores[n].get(axis, ranking.NAN) == axis_scores[n].get(
+ axis, ranking.NAN)
+ ]
+ rows.sort(key=lambda n, axis=axis: -axis_scores[n][axis])
+ lines = [f"| # | system | {axis} |", "|---|---|---|"]
+ lines += [
+ f"| {i} | {tiers[n][1]} | {axis_scores[n][axis]:.2f} |"
+ for i, n in enumerate(rows, 1)
+ ]
+ blocks.append("\n".join(lines))
+ return "\n\n".join(blocks)
diff --git a/bench/scripts/transitiontest.py b/bench/scripts/transitiontest.py
new file mode 100644
index 0000000..c6b3f73
--- /dev/null
+++ b/bench/scripts/transitiontest.py
@@ -0,0 +1,288 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Recovery after a background change: a bed that starts or stops mid-speech.
+
+ transitiontest.py --model voice-isolator-v1
+ [--conds ambience@+0,babble@+0,stationary@+0,traffic@+0] [--limit 16]
+ [--ramp-ms 20] [--tolerance-db 3]
+ [--out staging/ops/<tag>.transitions.json]
+
+The set's beds run for the whole clip; real backgrounds start and stop (a door,
+a fan, a passing car). From every paired item, bed = mix - ref (exact: mix and
+reference share one gain), and two stimuli are built: ``onset``, the bed enters
+at the centre of the speech, and ``offset``, it leaves there. Every output is
+read per 100 ms block against the unchanged reference (voice kept, the coherent
+projection; residual, bed leak and artifacts) and compared block by block with
+the model's own output on the steady stimulus of the new state: the whole mix
+for an onset, the clean reference for an offset. That pairing removes the speech
+content from the comparison (a pause reads the same in both), so what remains is
+the model's reaction to the change.
+
+For each stimulus the test reports the dip (the worst block of the first second
+after the change, against the steady output at the same block), the recovery
+time (blocks until the output is back within ``--tolerance-db`` of the steady
+one and stays there), the leak (residual over the first 300 ms after the change,
+against the steady residual), the pre-echo (the worst block of the second before
+the change against the steady output of the old state: a windowed model that
+reacts before the change shows it here), and the steady delta (the median
+difference from one second after the change to the end, which a model that
+converges reads as zero). A model that adapts instantly reads zero everywhere.
+"""
+
+import argparse
+import json
+import os
+import sys
+
+import numpy as np
+import torch
+
+# pylint: disable=wrong-import-position
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import common
+
+FRAME = 4800
+AFTER_FROM = 10 # steady after: from t + 1.0 s
+DIP_BLOCKS = 10 # the first second after the change
+LEAK_BLOCKS = 3 # the first 300 ms after the change
+HOLD = 3 # blocks the recovered level must hold
+
+
+def speech_center_block(ref, frame=FRAME, floor_db=40.0):
+ """The block at the centre of the reference's measurable speech span."""
+ _, _, loud = common.coherent_blocks(ref, ref, frame, floor_db)
+ idx = loud.nonzero(as_tuple=True)[0]
+ if idx.numel() == 0:
+ return len(ref) // frame // 2
+ return int((int(idx[0]) + int(idx[-1])) // 2)
+
+
+def build_stimulus(ref, bed, t_block, kind, frame=FRAME, ramp=960):
+ """Returns ``ref`` plus ``bed`` gated on or off at block ``t_block``.
+
+ On for ``onset``, off for ``offset``, over a ``ramp``-sample linear ramp
+ that ends at the block boundary, so every block from ``t_block`` on holds
+ the new state entirely.
+ """
+ n = min(len(ref), len(bed))
+ t = t_block * frame
+ g = torch.zeros(n)
+ lo, hi = max(0, t - ramp), min(n, t)
+ g[hi:] = 1.0
+ g[lo:hi] = torch.linspace(0.0, 1.0, hi - lo)
+ if kind == "offset":
+ g = 1.0 - g
+ elif kind != "onset":
+ raise ValueError(f"kind must be onset or offset, not {kind!r}")
+ return ref[:n] + bed[:n] * g
+
+
+def recovery_blocks(kept, loud, t_block, steady_after, tolerance_db, hold=HOLD):
+ """Returns the blocks after ``t_block`` until the kept voice recovers.
+
+ Recovered means within ``tolerance_db`` of ``steady_after`` for ``hold``
+ consecutive loud blocks; NaN when it never is.
+ """
+ # a quiet block neither helps nor hurts
+ ok = (kept >= steady_after - tolerance_db) | ~loud
+ run = 0
+ for b in range(t_block, len(kept)):
+ if bool(ok[b]):
+ run += int(bool(loud[b]))
+ if run >= hold:
+ first = b
+ while first > t_block and bool(ok[first - 1]):
+ first -= 1
+ # the recovery point is a speech block
+ while not bool(loud[first]):
+ first += 1
+ return first - t_block
+ else:
+ run = 0
+ return float("nan")
+
+
+def _median(t):
+ return float(t.median()) if len(t) else float("nan")
+
+
+def read_response(y, y_old, y_new, ref, t_block, tolerance_db, frame=FRAME):
+ """Returns the per-stimulus numbers, block by block over the loud blocks.
+
+ The transition output ``y`` against the steady outputs of the old state
+ (``y_old``, what the input was before the change) and of the new state
+ (``y_new``), over the reference's loud blocks.
+ """
+ kept, resid, loud = common.coherent_blocks(y, ref, frame)
+ k_old, _, _ = common.coherent_blocks(y_old, ref, frame)
+ k_new, r_new, _ = common.coherent_blocks(y_new, ref, frame)
+ nb = min(len(kept), len(k_old), len(k_new))
+ kept, resid, loud = kept[:nb], resid[:nb], loud[:nb]
+ d_after = kept - k_new[:nb] # the reaction to the new state
+ # before the change: the same input as the old steady state
+ d_before = kept - k_old[:nb]
+ r_after = resid - r_new[:nb]
+ t = min(t_block, nb)
+ dip_win = d_after[t:t + DIP_BLOCKS][loud[t:t + DIP_BLOCKS]]
+ pre_win = d_before[max(0, t - DIP_BLOCKS):t][loud[max(0, t - DIP_BLOCKS):t]]
+ leak_win = r_after[t:t + LEAK_BLOCKS][loud[t:t + LEAK_BLOCKS]]
+ steady = d_after[t + AFTER_FROM:][loud[t + AFTER_FROM:]]
+ rec = (recovery_blocks(d_after, loud, t, 0.0, tolerance_db)
+ if nb > t else float("nan"))
+ return {
+ "t_s":
+ t_block * frame / common.SR,
+ "n_blocks":
+ nb,
+ "dip_db":
+ float(dip_win.min()) if len(dip_win) else float("nan"),
+ "pre_db":
+ float(pre_win.min()) if len(pre_win) else float("nan"),
+ "recovery_ms":
+ (rec * frame / common.SR * 1000 if rec == rec else float("nan")),
+ "leak_db":
+ float(leak_win.mean()) if len(leak_win) else float("nan"),
+ "steady_delta_db":
+ _median(steady),
+ "kept_new_state_db":
+ _median(k_new[:nb][t + AFTER_FROM:][loud[t + AFTER_FROM:]]),
+ "resid_new_state_db":
+ _median(r_new[:nb][t + AFTER_FROM:][loud[t + AFTER_FROM:]]),
+ }
+
+
+def measure_item(run,
+ mix,
+ ref,
+ tolerance_db=3.0,
+ ramp=960,
+ t_block=None,
+ frame=FRAME):
+ """Returns both stimuli of one paired item through ``run(x)``.
+
+ Next to the two steady passes (``run(mix)``, ``run(ref)``): {"onset": {...},
+ "offset": {...}}.
+ """
+ n = min(len(mix), len(ref))
+ mix, ref = mix[:n], ref[:n]
+ bed = mix - ref
+ t = speech_center_block(ref, frame) if t_block is None else t_block
+ y_mix = torch.as_tensor(run(mix)).float()[:n]
+ y_ref = torch.as_tensor(run(ref)).float()[:n]
+ out = {}
+ for kind, y_old, y_new in (
+ ("onset", y_ref, y_mix),
+ ("offset", y_mix, y_ref),
+ ):
+ stim = build_stimulus(ref, bed, t, kind, frame, ramp)
+ y = torch.as_tensor(run(stim)).float()[:n]
+ out[kind] = read_response(y, y_old, y_new, ref, t, tolerance_db, frame)
+ return out
+
+
+RESPONSE_KEYS = (
+ "dip_db",
+ "pre_db",
+ "recovery_ms",
+ "leak_db",
+ "steady_delta_db",
+ "kept_new_state_db",
+ "resid_new_state_db",
+)
+
+
+def aggregate(items):
+ """Returns per-stimulus means, the worst dip and the longest recovery.
+
+ Means are NaN-aware; the count of items that never recovered is beside them.
+ """
+ out = {"n_items": len(items)}
+ for kind in ("onset", "offset"):
+ rs = [d[kind] for d in items if kind in d]
+ s = {}
+ for k in RESPONSE_KEYS:
+ vals = [r[k] for r in rs if r[k] == r[k]]
+ s[k] = float(np.mean(vals)) if vals else float("nan")
+ dips = [r["dip_db"] for r in rs if r["dip_db"] == r["dip_db"]]
+ recs = [
+ r["recovery_ms"] for r in rs if r["recovery_ms"] == r["recovery_ms"]
+ ]
+ s["dip_worst_db"] = min(dips) if dips else float("nan")
+ s["recovery_max_ms"] = max(recs) if recs else float("nan")
+ s["n_never_recovered"] = sum(
+ 1 for r in rs if r["recovery_ms"] != r["recovery_ms"])
+ out[kind] = s
+ return out
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ common.add_model_args(ap)
+ ap.set_defaults(model="voice-isolator-v1")
+ ap.add_argument("--conds",
+ default="ambience@+0,babble@+0,stationary@+0,traffic@+0")
+ ap.add_argument("--limit",
+ type=int,
+ default=16,
+ help="items per condition (0: all)")
+ ap.add_argument("--ramp-ms", type=float, default=20.0)
+ ap.add_argument("--tolerance-db", type=float, default=3.0)
+ ap.add_argument("--out", default="")
+ a = ap.parse_args()
+ rows = common.manifest()
+ vi, run = common.isolator_runner(a)
+ ramp = int(a.ramp_ms / 1000 * common.SR)
+ report = {
+ "check": "transitions",
+ "model": common.model_tag(a.model),
+ "precision": a.precision,
+ "device": str(vi.device),
+ "mode": vi.mode,
+ "lookahead_frames": vi.lookahead_frames,
+ "set_id": common.set_id(),
+ "frame": FRAME,
+ "ramp_ms": a.ramp_ms,
+ "tolerance_db": a.tolerance_db,
+ "conditions": {},
+ }
+ for cond in [c for c in a.conds.split(",") if c]:
+ items = []
+ for r in common.pick_rows(rows, cond, a.limit, paired=True):
+ mix = common.load48(r["mix_path"])
+ ref = common.load48(r["clean_path"])
+ d = measure_item(run, mix, ref, a.tolerance_db, ramp)
+ d["id"] = r["id"]
+ items.append(d)
+ s = aggregate(items)
+ report["conditions"][cond] = {"summary": s, "items": items}
+ for kind in ("onset", "offset"):
+ k = s[kind]
+ print(
+ f"{cond:>16s} {kind:6s}: n {s['n_items']:3d} dip"
+ f" {k['dip_db']:6.1f} dB (worst {k['dip_worst_db']:6.1f}) pre"
+ f" {k['pre_db']:5.1f} recovery {k['recovery_ms']:5.0f} ms (max"
+ f" {k['recovery_max_ms']:4.0f}, never {k['n_never_recovered']})"
+ f" leak {k['leak_db']:5.1f} dB steady delta"
+ f" {k['steady_delta_db']:5.1f}",
+ flush=True,
+ )
+ out = common.ops_path(a.model, "transitions", a.out)
+ os.makedirs(os.path.dirname(out), exist_ok=True)
+ with open(out, "w", encoding="utf-8") as fh:
+ json.dump(report, fh, indent=1)
+ print(f"wrote {out}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/bench/scripts/twicetest.py b/bench/scripts/twicetest.py
new file mode 100644
index 0000000..68cd8f7
--- /dev/null
+++ b/bench/scripts/twicetest.py
@@ -0,0 +1,192 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""A second pass over a processed file: its cost, idempotence, determinism.
+
+ twicetest.py --model voice-isolator-v1
+ [--conds babble@+4,ambience@+0,stationary@+0,wild@+0] [--limit 16]
+ [--no-speaker] [--out staging/ops/<tag>.twice.json]
+
+Files reach a denoiser that were denoised already (a re-export, a second tool in
+the chain), and nothing in the product stops a user from running one twice. Per
+paired item: y1 = run(mix), y2 = run(y1), then y1' = run(mix) again after that
+other work. Reports the voice kept (coherent projection on the reference, mean
+and 10th percentile of 100 ms blocks) and the residual after one and after two
+passes and what the second pass cost; idempotence, 10 log10 |y2 - y1|^2 / |y1|^2
+(0 dB: the second pass rewrote everything, -60: it changed nothing);
+determinism, |y1' - y1| the same way (a stateless model reads the floor); and
+speaker similarity after each pass. A pass that raises or returns NaN or the
+wrong length is a failure, counted and never averaged in.
+"""
+
+import argparse
+import json
+import os
+import sys
+
+import numpy as np
+import torch
+
+# pylint: disable=wrong-import-position
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import common
+
+FRAME = 4800
+DIFF_FLOOR_DB = -100.0
+
+
+def diff_db(a, b):
+ """10 log10 |a - b|^2 / |b|^2 over the common length, floored at -100 dB."""
+ n = min(len(a), len(b))
+ num = float((a[:n] - b[:n]).pow(2).mean())
+ den = float(b[:n].pow(2).mean())
+ return max(
+ DIFF_FLOOR_DB,
+ float(10 * np.log10(num / (den + 1e-14) + 10**(DIFF_FLOOR_DB / 10))),
+ )
+
+
+def _pass(run, x, n):
+ """One pass, or the failure it raised / produced."""
+ try:
+ y = run(x)
+ except Exception as e: # pylint: disable=broad-exception-caught
+ # a failure is a result here, not a crash
+ return None, f"raised: {e}"
+ y = torch.as_tensor(y).float()
+ if not bool(torch.isfinite(y).all()):
+ return None, "nan"
+ if len(y) != n:
+ return None, f"length {len(y)} != {n}"
+ return y, None
+
+
+def _voice(y, ref):
+ kept, resid, loud = common.coherent_blocks(y, ref, FRAME)
+ k = kept[loud]
+ return {
+ "kept_coh_mean_db": float(k.mean()) if len(k) else float("nan"),
+ "kept_coh_p10_db":
+ (float(torch.quantile(k, 0.1)) if len(k) else float("nan")),
+ "resid_db": float(resid[loud].mean()) if len(k) else float("nan"),
+ }
+
+
+def measure_item(run, mix, ref, spk=None, key=None):
+ """Returns one paired item's numbers over three passes through ``run(x)``.
+
+ A failed pass returns ``{"failure": reason}``. ``spk`` is a speaker
+ embedder with ``sim(a, b, key_b=...)``.
+ """
+ n = len(mix)
+ y1, err = _pass(run, mix, n)
+ if err:
+ return {"failure": f"pass 1 {err}"}
+ y2, err = _pass(run, y1, n)
+ if err:
+ return {"failure": f"pass 2 {err}"}
+ y1b, err = _pass(run, mix, n)
+ if err:
+ return {"failure": f"repeat {err}"}
+ one, two = _voice(y1, ref), _voice(y2, ref)
+ d = {f"pass1_{k}": v for k, v in one.items()}
+ d.update({f"pass2_{k}": v for k, v in two.items()})
+ d.update({
+ "second_pass_kept_delta_db":
+ (two["kept_coh_mean_db"] - one["kept_coh_mean_db"]),
+ "second_pass_p10_delta_db":
+ (two["kept_coh_p10_db"] - one["kept_coh_p10_db"]),
+ "second_pass_resid_delta_db": two["resid_db"] - one["resid_db"],
+ "idempotence_db": diff_db(y2, y1),
+ "determinism_db": diff_db(y1b, y1),
+ })
+ if spk is not None:
+ d["pass1_spk_sim"] = spk.sim(y1, ref, key_b=key)
+ d["pass2_spk_sim"] = spk.sim(y2, ref, key_b=key)
+ d["second_pass_spk_delta"] = d["pass2_spk_sim"] - d["pass1_spk_sim"]
+ return d
+
+
+def aggregate(items):
+ """Means over the items that did not fail, the failure count and reasons."""
+ ok = [d for d in items if "failure" not in d]
+ out = {"n_items": len(items), "n_failed": len(items) - len(ok)}
+ out["failures"] = [d["failure"] for d in items if "failure" in d]
+ keys = sorted({k for d in ok for k in d if k != "id"})
+ for k in keys:
+ vals = [d[k] for d in ok if k in d and d[k] == d[k]]
+ out[k] = float(np.mean(vals)) if vals else float("nan")
+ if ok:
+ out["determinism_max_db"] = max(d["determinism_db"] for d in ok)
+ out["idempotence_max_db"] = max(d["idempotence_db"] for d in ok)
+ return out
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ common.add_model_args(ap)
+ ap.set_defaults(model="voice-isolator-v1")
+ ap.add_argument("--conds",
+ default="babble@+4,ambience@+0,stationary@+0,wild@+0")
+ ap.add_argument("--limit",
+ type=int,
+ default=16,
+ help="items per condition (0: all)")
+ ap.add_argument(
+ "--no-speaker",
+ action="store_true",
+ help="skip the WavLM speaker similarity",
+ )
+ ap.add_argument("--out", default="")
+ a = ap.parse_args()
+ rows = common.manifest()
+ vi, run = common.isolator_runner(a)
+ spk = None if a.no_speaker else common.SpeakerEmbedder()
+ report = {
+ "check": "twice",
+ "model": common.model_tag(a.model),
+ "precision": a.precision,
+ "device": str(vi.device),
+ "mode": vi.mode,
+ "lookahead_frames": vi.lookahead_frames,
+ "set_id": common.set_id(),
+ "frame": FRAME,
+ "conditions": {},
+ }
+ for cond in [c for c in a.conds.split(",") if c]:
+ items = []
+ for r in common.pick_rows(rows, cond, a.limit, paired=True):
+ mix = common.load48(r["mix_path"])
+ ref = common.load48(r["clean_path"])
+ d = measure_item(run, mix, ref, spk, key=f"{r['id']}.ref")
+ d["id"] = r["id"]
+ items.append(d)
+ s = aggregate(items)
+ report["conditions"][cond] = {"summary": s, "items": items}
+ print(
+ f"{cond:>18s}: n {s['n_items']:3d} failed {s['n_failed']:d} "
+ f"kept p10 {s.get('pass1_kept_coh_p10_db', float('nan')):6.1f} -> "
+ f"{s.get('pass2_kept_coh_p10_db', float('nan')):6.1f} dB "
+ f"idempotence {s.get('idempotence_db', float('nan')):6.1f} dB "
+ f"determinism {s.get('determinism_db', float('nan')):6.1f} dB",
+ flush=True,
+ )
+ out = common.ops_path(a.model, "twice", a.out)
+ os.makedirs(os.path.dirname(out), exist_ok=True)
+ with open(out, "w", encoding="utf-8") as fh:
+ json.dump(report, fh, indent=1)
+ print(f"wrote {out}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/bench/scripts/validateset.py b/bench/scripts/validateset.py
new file mode 100644
index 0000000..23b96d3
--- /dev/null
+++ b/bench/scripts/validateset.py
@@ -0,0 +1,693 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Checks a built eval set for properties the scorer and leaderboard rely on.
+
+ python bench/scripts/validateset.py [--set ROOT] [--full]
+ [--json report.json]
+
+Every check prints PASS, WARN or FAIL with counts; the exit status is 1 when
+anything FAILs. WARN marks properties that do not break scoring but limit what
+the set can support (a condition below the leaderboard's item minimum, an uneven
+language spread). --full re-hashes every file against checksums.json instead of
+a sample.
+
+Checked: manifest schema and unique ids; every referenced file exists, is 48 kHz
+mono, finite, unclipped and paired to a reference of the same length;
+input waveforms are unique across the entire inventory, including quick runs;
+checksums.json covers every file and its set id reproduces; per-condition counts
+against the leaderboard minimum; language balance of the paired items; the
+scored region left by score_from; the realised SNR of additive conditions
+against the nominal one (mix minus reference is the corruptor, so the shared
+gain must have preserved the ratio); the measured bandwidth gate of the speech
+(items with ``score_policy: retention`` are exempt: their reference is a
+recording made in the wild); band-limited twins of the rate sweep.
+"""
+
+import argparse
+import collections
+import hashlib
+import json
+import math
+import os
+import random
+import sys
+
+import numpy as np
+import soundfile as sf
+
+# pylint: disable=wrong-import-position
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import common
+import ranking
+import scoreevents
+
+FIELDS = (
+ "id",
+ "condition",
+ "family",
+ "language",
+ "speaker",
+ "mix_path",
+ "clean_path",
+ "snr",
+ "score_from",
+ "effective_bandwidth_hz",
+)
+MIN_SCORED_SECONDS = 2.0
+# active-speech RMS; speech is set to -26 dBFS, the shared peak gain may lower
+# it
+REF_FLOOR_DBFS = -36.0
+PUBLIC_FIELDS = (
+ "id",
+ "condition",
+ "family",
+ "language",
+ "mix_path",
+ "clean_path",
+ "snr",
+ "score_from",
+) # the item semantics the set id binds
+REF_MIN_MARGIN_DB = 20.0
+# the condition inventory a complete build promises (--expect-inventory):
+# name -> minimum items
+EXPECTED_INVENTORY = {
+ **{
+ c: 72 for c in (
+ "babble@+10",
+ "babble@+4",
+ "babble@+0",
+ "babble@-5",
+ "ambience@-5",
+ "ambience@+0",
+ "ambience@+5",
+ "events@+5",
+ "music@-6",
+ "music_vocal@-6",
+ "music_vocal@+6",
+ "wind@+0",
+ "wind@+5",
+ "cheer@+5",
+ "cheer_tail",
+ "expressive_tail@-5",
+ "reverb_real",
+ "reverb_synth",
+ "clean",
+ "srsweep_8k",
+ "srsweep_16k",
+ "srsweep_24k",
+ "srsweep_44.1k",
+ "srsweep_48k",
+ "quiet@-30dBFS",
+ )
+ },
+ **{
+ c: 48 for c in (
+ "singer@-2",
+ "singer@-5",
+ "conversation@0",
+ "stationary@-5",
+ "stationary@+0",
+ "stationary@+5",
+ "household@+0",
+ "household@+5",
+ "rain@+0",
+ "animals@+0",
+ "animals@+5",
+ "water@+0",
+ "traffic@-5",
+ "traffic@+0",
+ "traffic@+5",
+ "appliance@+0",
+ "appliance@+5",
+ "tools@+5",
+ "nonverbal@+0",
+ "nonverbal_clean",
+ )
+ },
+ "long@+4": 16,
+ **{
+ c: 168 for c in ("wild@-10", "wild@-5", "wild@+0", "wild@+5")
+ },
+ "babble@-10": 72,
+ "ambience@-10": 72,
+ "events@-5": 72,
+ "stationary@-10": 48,
+ "traffic@-10": 48,
+ "soft@+5": 48,
+ "soft@+0": 48,
+ "soft@-5": 48,
+ "whisper@+5": 48,
+ "whisper@+0": 48,
+ "real_noisy": 48,
+ "real_dirty": 20,
+ "real_wild": 40,
+ "real_multi": 48,
+ # mild rungs, transitions, noise alone, one background talker, everyday
+ # speech with pauses, everyday real recordings
+ "babble@+20": 72,
+ "ambience@+20": 72,
+ "nonverbal@+20": 48,
+ "transition@+10": 48,
+ "noise_only": 96,
+ "talker@+5": 48,
+ "everyday@+10": 54,
+ "everyday@+20": 54,
+ "real_everyday": 200,
+ # the same-room block: speech and noise through one room and microphone
+ "coroom@pause": 127,
+ "coroom@speech": 121,
+ "coroom@floor": 127,
+ "coroom@both": 127,
+ # speech level over the reference's own floor (its quietest in-utterance
+ # frames)
+}
+SNR_TOLERANCE_DB = 1.0
+# the same-room block's labels, which its sidecar scores by: the event spans,
+# the pauses, the microphone chain, the split, and the room's share of the
+# voice's level on its loudest frames (a number)
+BLOCK_LABELS = ("events", "pauses", "chain", "split", "room_share_db",
+ "room_share_rule")
+BANDWIDTH_FLOOR_HZ = 20000
+# the bed of a transition item is present for part of the item only: its
+# nominal SNR is the bed's while it is on
+SKIP_SNR_FAMILIES = ("reverb", "clean", "srsweep", "policy", "real", "long",
+ "transition", "coroom")
+
+
+class Report:
+ """Collects check outcomes; ok is False once anything failed."""
+
+ def __init__(self):
+ self.rows = []
+ self.ok = True
+ self.failing = {}
+
+ def add(self, name, status, detail=""):
+ self.rows.append((name, status, detail))
+ if status == "FAIL":
+ self.ok = False
+ print(f"{status:4s} {name:34s} {detail}", flush=True)
+
+ def check(self, name, failures, total, warn_only=False, detail=""):
+ status = "PASS" if not failures else ("WARN" if warn_only else "FAIL")
+ self.add(
+ name,
+ status,
+ f"{len(failures)}/{total} flagged" +
+ (f"; {detail}" if detail else "") +
+ (f"; e.g. {failures[:3]}" if failures else ""),
+ )
+ # the complete list goes to the JSON report
+ self.failing[name] = [str(f) for f in failures]
+
+
+def _sha256(path):
+ h = hashlib.sha256()
+ with open(path, "rb") as fh:
+ for block in iter(lambda: fh.read(1 << 20), b""):
+ h.update(block)
+ return h.hexdigest()
+
+
+def audio_sha256(path: str) -> str:
+ """Hashes decoded samples and their layout, independent of WAV encoding."""
+ with sf.SoundFile(path) as audio:
+ layout = (audio.samplerate, audio.channels, len(audio))
+ digest = hashlib.sha256(json.dumps(layout).encode())
+ for block in audio.blocks(blocksize=65536,
+ dtype="float64",
+ always_2d=True):
+ block[block == 0] = 0.0 # signed zero has the same audio value
+ digest.update(block.astype("<f8", copy=False).tobytes())
+ return digest.hexdigest()
+
+
+def _read(root, rel):
+ x, sr = sf.read(os.path.join(root, rel), dtype="float32", always_2d=True)
+ return x, sr
+
+
+def _band_energy_ratio(x, sr, edge_hz):
+ """Energy above edge_hz relative to the total, in dB."""
+ spec = np.abs(np.fft.rfft(x.astype(np.float64)))**2
+ freqs = np.fft.rfftfreq(len(x), 1.0 / sr)
+ hi = spec[freqs >= edge_hz].sum()
+ return 10 * math.log10((hi + 1e-20) / (spec.sum() + 1e-20))
+
+
+def validate(root, full=False, sample=0.05, seed=0, expect_inventory=False):
+ rep = Report()
+ with open(os.path.join(root, "manifest.jsonl"), encoding="utf-8") as fh:
+ rows = [json.loads(line) for line in fh]
+ rng = random.Random(seed)
+
+ # ---- manifest schema
+ missing = [r.get("id") for r in rows if any(k not in r for k in FIELDS)]
+ rep.check("manifest fields", missing, len(rows))
+ ids = collections.Counter(r["id"] for r in rows)
+ rep.check("unique ids", [k for k, v in ids.items() if v > 1], len(rows))
+ block = [r for r in rows if r["condition"].startswith("coroom@")]
+ unlabelled = [
+ r["id"]
+ for r in block
+ if any(k not in (r.get("provenance") or {}) for k in BLOCK_LABELS) or
+ not isinstance((r.get("provenance") or {}).get("room_share_db"),
+ (int, float))
+ ]
+ rep.check("same-room labels",
+ unlabelled,
+ len(block),
+ detail=", ".join(BLOCK_LABELS) + " in the provenance")
+ other_rule = [
+ r["id"]
+ for r in block
+ if "room_share_rule" in (r.get("provenance") or {}) and
+ r["provenance"]["room_share_rule"] != scoreevents.ROOM_SHARE_RULE
+ ]
+ rep.check("same-room allowance rule",
+ other_rule,
+ len(block),
+ detail="room_share_db measured under the rule the scorer reads: "
+ f"{scoreevents.ROOM_SHARE_RULE!r}")
+ paired = [r for r in rows if r.get("clean_path")]
+ real = [r for r in rows if not r.get("clean_path")]
+ # a bed with no speech at all is reference-free by construction, as a
+ # real recording is
+ rep.check(
+ "real items are reference-free",
+ [
+ r["id"] for r in real if not (r["condition"].startswith("real") or
+ r["family"] == "noise_only")
+ ],
+ len(real),
+ )
+ rep.check(
+ "paired items carry a language",
+ [
+ r["id"] for r in paired if not r.get("language") or
+ r["language"] == "und" and r["family"] != "singer"
+ ],
+ len(paired),
+ )
+
+ # ---- files: existence, format, pairing, clipping, finiteness
+ bad_exist = []
+ bad_fmt = []
+ bad_pair = []
+ clipped = []
+ nonfinite = []
+ silent = []
+ peaks = []
+ for r in rows:
+ for key in ("mix_path", "clean_path"):
+ rel = r.get(key)
+ if not rel:
+ continue
+ p = os.path.join(root, rel)
+ if not os.path.exists(p):
+ bad_exist.append(rel)
+ continue
+ info = sf.info(p)
+ if info.samplerate != common.SR or info.channels != 1:
+ bad_fmt.append(rel)
+ if (r.get("clean_path") and
+ os.path.exists(os.path.join(root, r["clean_path"])) and
+ os.path.exists(os.path.join(root, r["mix_path"]))):
+ if (sf.info(os.path.join(root, r["mix_path"])).frames
+ != sf.info(os.path.join(root, r["clean_path"])).frames):
+ bad_pair.append(r["id"])
+ rep.check("files exist", bad_exist, 2 * len(paired) + len(real))
+ # every check below reads audio: a row whose files are missing was reported
+ # above and is skipped
+ rows = [
+ r for r in rows if os.path.exists(os.path.join(root, r["mix_path"])) and
+ (not r.get("clean_path") or
+ os.path.exists(os.path.join(root, r["clean_path"])))
+ ]
+ paired = [r for r in rows if r.get("clean_path")]
+ rep.check("48 kHz mono", bad_fmt, 2 * len(paired) + len(real))
+ rep.check("mix/ref lengths match", bad_pair, len(paired))
+ input_identities = collections.defaultdict(list)
+ for row in rows:
+ identity = audio_sha256(os.path.join(root, row["mix_path"]))
+ input_identities[identity].append(row["id"])
+ rep.check("unique input waveforms",
+ [ids for ids in input_identities.values() if len(ids) > 1],
+ len(rows),
+ detail="all inputs decoded; reference reuse is allowed")
+ audio_rows = (rows if full else rng.sample(rows,
+ max(1, int(sample * len(rows)))))
+ for r in audio_rows:
+ x, _ = _read(root, r["mix_path"])
+ peak = float(np.abs(x).max()) if len(x) else 0.0
+ peaks.append(peak)
+ if not np.isfinite(x).all():
+ nonfinite.append(r["id"])
+ if peak >= 0.999:
+ clipped.append(r["id"])
+ if 20 * math.log10(float(np.sqrt((x**2).mean())) + 1e-12) < -60:
+ silent.append(r["id"])
+ quiet_ref, noisy_ref, floors = [], [], []
+ for r in audio_rows:
+ # quiet@-30dBFS is quiet by design
+ if r.get("clean_path") and r["family"] != "level":
+ ref, _ = _read(root, r["clean_path"])
+ fr = 480
+ e = (ref[:len(ref) // fr * fr, 0].reshape(-1, fr)**2).mean(1)
+ # frames within 30 dB of the loudest: the speech itself
+ act = e > e.max() * 1e-3
+ speech_db = 10 * math.log10(float(e[act].mean()) + 1e-12)
+ if speech_db < REF_FLOOR_DBFS:
+ quiet_ref.append(r["id"])
+ # the reference's own noise floor: the quietest frames inside the
+ # utterance span (pauses between words), against the speech level; a
+ # noisy "clean" target defeats every reference metric, so a small
+ # margin is reported and a tiny one flagged
+ idx = np.nonzero(act)[0]
+ span = e[idx[0]:idx[-1] + 1]
+ if (len(span) >= 100 and r["family"] != "singer" and r.get(
+ # sung notes leave no pauses to measure; a
+ "score_policy") != "retention"):
+ # retention item's reference is a wild recording with a floor of
+ # its own
+
+ floor_db = 10 * math.log10(
+ float(np.percentile(span, 5)) + 1e-12)
+ floors.append(speech_db - floor_db)
+ if speech_db - floor_db < REF_MIN_MARGIN_DB:
+ noisy_ref.append(r["id"])
+ rep.check(
+ "references at speech level",
+ quiet_ref,
+ len(audio_rows),
+ detail=f"active-speech RMS >= {REF_FLOOR_DBFS} dBFS",
+ )
+ rep.check(
+ "references clean (speech over their own floor)",
+ noisy_ref,
+ len(floors),
+ warn_only=True,
+ detail=(
+ f"median margin {np.median(floors) if floors else float('nan'):.0f}"
+ f" dB; flagged below {REF_MIN_MARGIN_DB} dB"),
+ )
+ rep.check("finite samples", nonfinite, len(audio_rows))
+ rep.check(
+ "no clipping in mixes",
+ clipped,
+ len(audio_rows),
+ detail=f"peak median {np.median(peaks):.3f} max {max(peaks):.3f}",
+ )
+ rep.check("mixes are not silent", silent, len(audio_rows))
+
+ # ---- checksums and set id
+ ck_path = os.path.join(root, "checksums.json")
+ if not os.path.exists(ck_path):
+ rep.add("checksums.json", "FAIL", "missing")
+ else:
+ with open(ck_path, encoding="utf-8") as fh:
+ ck = json.load(fh)
+ expected = {
+ r[k] for r in rows for k in ("mix_path", "clean_path") if r.get(k)
+ }
+ rep.check(
+ "checksums cover every file",
+ sorted(expected - set(ck["files"])),
+ len(expected),
+ )
+ lines = "".join(f"{k}:{v}\n" for k, v in sorted(ck["files"].items()))
+ if ck.get("manifest_sha256"):
+ # the id binds the audio and the item semantics: a changed crop,
+ # target policy or scored region is a different set
+ # even when every file hash still matches
+ fields = ck.get("public_fields") or PUBLIC_FIELDS
+ h = hashlib.sha256()
+ for r in sorted(rows, key=lambda r: r["id"]):
+ public = {k: r.get(k) for k in fields}
+ h.update(json.dumps(public, sort_keys=True).encode())
+ h.update(b"\n")
+ semantics_ok = h.hexdigest() == ck["manifest_sha256"]
+ digest = hashlib.sha256(
+ (lines + f"manifest:{ck['manifest_sha256']}\n").encode())
+ rep.add(
+ "manifest semantics match checksums",
+ "PASS" if semantics_ok else "FAIL",
+ "public fields hashed: " + ", ".join(fields),
+ )
+ else:
+ digest = hashlib.sha256(lines.encode())
+ rep.add(
+ "set id reproduces from the hashes",
+ "PASS" if digest.hexdigest() == ck["set_id"] else "FAIL",
+ ck["set_id"][:16],
+ )
+ rehash = (list(ck["files"]) if full else rng.sample(
+ sorted(ck["files"]), max(1, int(sample * len(ck["files"])))))
+ stale = [
+ rel for rel in rehash
+ if not os.path.exists(os.path.join(root, rel)) or
+ _sha256(os.path.join(root, rel)) != ck["files"][rel]
+ ]
+ rep.check(
+ "file hashes match" + ("" if full else " (sample)"),
+ stale,
+ len(rehash),
+ )
+
+ # ---- counts and balance
+ counts = collections.Counter(r["condition"] for r in rows)
+ small = [
+ f"{c}={n}" for c, n in sorted(counts.items()) if n < ranking.MIN_ITEMS
+ ]
+ rep.check(
+ "conditions at the leaderboard minimum",
+ small,
+ len(counts),
+ warn_only=True,
+ detail=f"< {ranking.MIN_ITEMS} items cannot feed an axis",
+ )
+ if expect_inventory:
+ short = [
+ f"{c}={counts.get(c, 0)}<{m}"
+ for c, m in EXPECTED_INVENTORY.items()
+ if counts.get(c, 0) < m
+ ]
+ rep.check(
+ "condition inventory complete",
+ short,
+ len(EXPECTED_INVENTORY),
+ detail=("every promised condition present with at least its minimum"
+ " items"),
+ )
+ langs = collections.Counter(
+ r["language"]
+ for r in paired
+ if r["family"] != "singer" and r.get("language") not in (None, "und"))
+ top, top_n = max(langs.items(), key=lambda kv: kv[1]) if langs else ("?", 0)
+ others = [n for l, n in langs.items() if l != top]
+ lo, hi = (min(others), max(others)) if others else (top_n, top_n)
+ # one language may carry a designed share (the applications' first
+ # language); the others must be balanced among themselves so every language
+ # is covered comparably
+ rep.add(
+ "language balance (paired items)",
+ "PASS" if hi <= 1.25 * lo else "WARN",
+ f"{top} {top_n / max(1, sum(langs.values())):.0%} of paired items; "
+ f"{len(others)} other languages, {lo}-{hi} items each",
+ )
+
+ # ---- golden transcripts (an optional file; when it ships, every row must
+ # fit the manifest)
+ tpath = os.path.join(root, "transcripts.jsonl")
+ if os.path.exists(tpath):
+ by_id = {r["id"]: r for r in rows}
+ bad, seen, tiers, n_t = [], set(), collections.Counter(), 0
+ with open(tpath, encoding="utf-8") as fh:
+ for line in fh:
+ if not line.strip():
+ continue
+ t = json.loads(line)
+ n_t += 1
+ tid = t.get("id")
+ if tid in seen:
+ bad.append(f"{tid}: duplicate")
+ seen.add(tid)
+ r = by_id.get(tid)
+ if r is None:
+ bad.append(f"{tid}: not in the manifest")
+ continue
+ if not r.get("clean_path"):
+ bad.append(f"{tid}: a reference-free item")
+ if not (t.get("text") or "").strip():
+ bad.append(f"{tid}: empty text")
+ if t.get("language") != r.get("language"):
+ bad.append(f"{tid}: language {t.get('language')} !="
+ f" {r.get('language')}")
+ # optional: the language heard, where the label is wrong
+ spoken = t.get("spoken")
+ if spoken is not None and not (
+ isinstance(spoken, str) and 2 <= len(spoken) <= 3 and
+ spoken.isalpha() and spoken != t.get("language")):
+ bad.append(
+ f"{tid}: spoken {spoken!r} is not another language code"
+ )
+ if not t.get("tier"):
+ bad.append(f"{tid}: no tier")
+ tiers[t.get("tier")] += 1
+ rep.check(
+ "golden transcripts consistent",
+ bad,
+ n_t,
+ detail=f"{n_t} transcripts; tiers {dict(tiers)}",
+ )
+
+ # ---- scored region
+ short = []
+ for r in rows:
+ if r.get("score_from"):
+ n = sf.info(os.path.join(root, r["mix_path"])).frames
+ if n - int(r["score_from"]) < MIN_SCORED_SECONDS * common.SR:
+ short.append(r["id"])
+ rep.check(
+ "scored region after score_from",
+ short,
+ sum(1 for r in rows if r.get("score_from")),
+ detail=f">= {MIN_SCORED_SECONDS:.0f} s",
+ )
+
+ # ---- realised SNR of additive conditions
+ off, n_snr = [], 0
+ for r in (audio_rows if not full else rows):
+ if (r.get("snr") is None or not r.get("clean_path") or
+ r["family"] in SKIP_SNR_FAMILIES):
+ continue
+ if r["condition"].endswith("_tail") or "tail" in r["condition"]:
+ # the reference is tapered and padded: the nominal SNR refers to the
+ # untapered speech
+ continue
+ mix, _ = _read(root, r["mix_path"])
+ ref, _ = _read(root, r["clean_path"])
+ noise = mix[:, 0] - ref[:, 0]
+ p_ref, p_noise = float((ref**2).mean()), float((noise**2).mean())
+ if p_noise <= 0:
+ continue
+ n_snr += 1
+ realised = 10 * math.log10(p_ref / p_noise)
+ if abs(realised - float(r["snr"])) > SNR_TOLERANCE_DB:
+ off.append(f"{r['id']}:{realised:+.1f}dB")
+ rep.check(
+ "realised SNR within tolerance",
+ off,
+ n_snr,
+ detail=f"±{SNR_TOLERANCE_DB} dB of nominal",
+ )
+
+ # ---- bandwidth gate (field, plus a measured sample)
+ # a retention item's reference was recorded in the wild: phone bandwidth is
+ # the point
+ gated = [
+ r for r in paired
+ if r["family"] != "singer" and r.get("score_policy") != "retention"
+ ]
+ low = [
+ r["id"]
+ for r in gated
+ if (r.get("effective_bandwidth_hz") or 0) < BANDWIDTH_FLOOR_HZ
+ ]
+ rep.check("speech bandwidth field >= 20 kHz", low, len(gated))
+ try:
+ measured = []
+ for r in [
+ r for r in audio_rows
+ if r.get("clean_path") and r["family"] not in
+ ("singer", "srsweep") and r.get("score_policy") != "retention"
+ ][:40]:
+ ref, sr = _read(root, r["clean_path"])
+ # pylint: disable-next=import-outside-toplevel
+ import torch
+
+ bw = common.effective_bandwidth_hz(torch.from_numpy(ref[:, 0]), sr)
+ if bw < BANDWIDTH_FLOOR_HZ:
+ measured.append(f"{r['id']}:{bw:.0f}Hz")
+ rep.check("speech bandwidth measured (sample)",
+ measured,
+ 40,
+ warn_only=True)
+ except ImportError:
+ rep.add(
+ "speech bandwidth measured (sample)",
+ "WARN",
+ "builder not importable",
+ )
+
+ # ---- rate-sweep twins are band-limited identically
+ twin_bad, twin_n = [], 0
+ for r in [r for r in rows if r["family"] == "srsweep"]:
+ rate = r["condition"].split("_")[-1].replace("k", "")
+ edge = float(rate) * 1000 / 2
+ if edge >= common.SR / 2:
+ continue
+ mix, _ = _read(root, r["mix_path"])
+ ref, _ = _read(root, r["clean_path"])
+ twin_n += 1
+ a = _band_energy_ratio(mix[:, 0], common.SR, edge * 1.1)
+ b = _band_energy_ratio(ref[:, 0], common.SR, edge * 1.1)
+ if a > -40 or b > -40:
+ twin_bad.append(f"{r['id']}:{a:.0f}/{b:.0f}dB")
+ rep.check(
+ "rate-sweep twins band-limited",
+ twin_bad,
+ twin_n,
+ detail="energy above the band < -40 dB",
+ )
+ return rep
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--set", default=common.EVAL)
+ ap.add_argument(
+ "--full",
+ action="store_true",
+ help="hash and inspect every file, not a sample",
+ )
+ ap.add_argument(
+ "--expect-inventory",
+ action="store_true",
+ help=("require every promised condition with its minimum item count (a"
+ " complete build)"),
+ )
+ ap.add_argument("--json", default="", help="write the check table here")
+ a = ap.parse_args()
+ rep = validate(a.set, full=a.full, expect_inventory=a.expect_inventory)
+ if a.json:
+ with open(a.json, "w", encoding="utf-8") as fh:
+ json.dump(
+ [
+ dict(
+ check=n,
+ status=s,
+ detail=d,
+ failing=rep.failing.get(n, []),
+ ) for n, s, d in rep.rows
+ ],
+ fh,
+ indent=1,
+ )
+ print("\nRESULT:", "OK" if rep.ok else "FAILURES")
+ return 0 if rep.ok else 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/bench/wrappers/locks/clearvoice.txt b/bench/wrappers/locks/clearvoice.txt
new file mode 100644
index 0000000..6b67253
--- /dev/null
+++ b/bench/wrappers/locks/clearvoice.txt
@@ -0,0 +1,81 @@
+# The clearvoice venv (ClearVoice MossFormer2_SE_48K): Python 3.11, the exact packages that
+# rendered the board. setupfield.sh installs it with uv pip sync.
+anyio==4.14.2
+audioread==3.1.0
+beautifulsoup4==4.15.0
+certifi==2026.7.22
+cffi==2.1.0
+charset-normalizer==3.4.9
+clearvoice==0.1.2
+click==8.4.2
+cuda-bindings==13.3.1
+cuda-pathfinder==1.6.0
+cuda-toolkit==13.0.3.0
+decorator==5.3.1
+einops==0.8.2
+filelock==3.32.2
+fsspec==2026.7.0
+gdown==6.1.0
+h11==0.16.0
+hf-xet==1.5.2
+httpcore==1.0.9
+httpx==0.28.1
+huggingface-hub==1.25.1
+idna==3.18
+jinja2==3.1.6
+joblib==1.5.3
+lazy-loader==0.5
+librosa==0.10.2.post1
+llvmlite==0.48.0
+markupsafe==3.0.3
+mpmath==1.3.0
+msgpack==1.2.1
+narwhals==2.24.0
+networkx==3.6.1
+numba==0.66.0
+numpy==1.26.4
+nvidia-cublas==13.1.1.3
+nvidia-cuda-cupti==13.0.85
+nvidia-cuda-nvrtc==13.0.88
+nvidia-cuda-runtime==13.0.96
+nvidia-cudnn-cu13==9.20.0.48
+nvidia-cufft==12.0.0.61
+nvidia-cufile==1.15.1.6
+nvidia-curand==10.4.0.35
+nvidia-cusolver==12.0.4.66
+nvidia-cusparse==12.6.3.3
+nvidia-cusparselt-cu13==0.8.1
+nvidia-nccl-cu13==2.29.7
+nvidia-nvjitlink==13.3.33
+nvidia-nvshmem-cu13==3.4.5
+nvidia-nvtx==13.0.85
+opencv-python==4.10.0.84
+packaging==26.2
+pillow==12.3.0
+platformdirs==4.11.0
+pooch==1.9.0
+pycparser==3.0
+pydub==0.25.1
+pysocks==1.7.1
+python-speech-features==0.6
+pyyaml==6.0.3
+requests==2.34.2
+rotary-embedding-torch==0.8.3
+scenedetect==0.6.6
+scikit-learn==1.9.0
+scipy==1.17.1
+setuptools==83.0.0
+soundfile==0.12.1
+soupsieve==2.9.1
+soxr==1.1.0
+sympy==1.14.0
+threadpoolctl==3.6.0
+torch==2.13.0
+torchaudio==2.11.0
+torchinfo==1.8.0
+torchvision==0.28.0
+tqdm==4.70.0
+triton==3.7.1
+typing-extensions==4.16.0
+urllib3==2.7.0
+yamlargparse==1.31.1
diff --git a/bench/wrappers/locks/dfn3.txt b/bench/wrappers/locks/dfn3.txt
new file mode 100644
index 0000000..43f7596
--- /dev/null
+++ b/bench/wrappers/locks/dfn3.txt
@@ -0,0 +1,59 @@
+# The dfn3 venv (DeepFilterNet3): Python 3.11, the exact packages that
+# rendered the board. setupfield.sh installs it with uv pip sync.
+appdirs==1.4.4
+certifi==2026.7.22
+cffi==2.1.1
+charset-normalizer==3.5.1
+cuda-bindings==13.4.3
+cuda-pathfinder==1.8.2
+cuda-toolkit==13.0.3.0
+deepfilterlib==0.5.6
+deepfilternet==0.5.6
+filelock==4.0.3
+fsspec==2026.9.0
+idna==3.20
+jinja2==3.1.6
+loguru==0.7.3
+markupsafe==3.0.3
+mpmath==1.3.0
+networkx==3.6.1
+numpy==1.26.4
+nvidia-cublas==13.1.1.3
+nvidia-cublas-cu12==12.1.3.1
+nvidia-cuda-cupti==13.0.85
+nvidia-cuda-cupti-cu12==12.1.105
+nvidia-cuda-nvrtc==13.0.88
+nvidia-cuda-nvrtc-cu12==12.1.105
+nvidia-cuda-runtime==13.0.96
+nvidia-cuda-runtime-cu12==12.1.105
+nvidia-cudnn-cu12==9.1.0.70
+nvidia-cudnn-cu13==9.24.0.43
+nvidia-cufft==12.0.0.61
+nvidia-cufft-cu12==11.0.2.54
+nvidia-cufile==1.15.1.6
+nvidia-curand==10.4.0.35
+nvidia-curand-cu12==10.3.2.106
+nvidia-cusolver==12.0.4.66
+nvidia-cusolver-cu12==11.4.5.107
+nvidia-cusparse==12.6.3.3
+nvidia-cusparse-cu12==12.1.0.106
+nvidia-cusparselt-cu13==0.8.1
+nvidia-nccl-cu12==2.20.5
+nvidia-nccl-cu13==2.30.7
+nvidia-nvjitlink==13.4.92
+nvidia-nvjitlink-cu12==12.9.86
+nvidia-nvshmem-cu13==3.4.5
+nvidia-nvtx==13.0.85
+nvidia-nvtx-cu12==12.1.105
+packaging==23.2
+pycparser==3.0
+requests==2.34.2
+scipy==1.17.1
+setuptools==84.0.0
+soundfile==0.14.0
+sympy==1.14.0
+torch==2.4.1
+torchaudio==2.4.1
+triton==3.0.0
+typing-extensions==4.16.0
+urllib3==2.8.0
diff --git a/bench/wrappers/locks/fastenhancer.txt b/bench/wrappers/locks/fastenhancer.txt
new file mode 100644
index 0000000..d594ffa
--- /dev/null
+++ b/bench/wrappers/locks/fastenhancer.txt
@@ -0,0 +1,11 @@
+# The fastenhancer venv (FastEnhancer-L): Python 3.11, the exact packages that
+# rendered the board. setupfield.sh installs it with uv pip sync.
+cffi==2.1.0
+flatbuffers==25.12.19
+numpy==2.4.6
+onnxruntime==1.28.0
+packaging==26.2
+protobuf==6.31.1
+pycparser==3.0
+soundfile==0.14.0
+typing-extensions==4.16.0
diff --git a/bench/wrappers/locks/gap_urgenet.txt b/bench/wrappers/locks/gap_urgenet.txt
new file mode 100644
index 0000000..418f9e0
--- /dev/null
+++ b/bench/wrappers/locks/gap_urgenet.txt
@@ -0,0 +1,103 @@
+# The gap_urgenet venv (GAP-URGENet): Python 3.10, the exact packages that
+# rendered the board. setupfield.sh installs it with uv pip sync.
+aiohappyeyeballs==2.7.1
+aiohttp==3.14.3
+aiosignal==1.4.0
+antlr4-python3-runtime==4.9.3
+asteroid-filterbanks==0.4.0
+async-timeout==5.0.1
+attrs==26.1.0
+audioread==3.1.0
+certifi==2026.7.22
+cffi==2.1.1
+charset-normalizer==3.5.1
+ci-sdr==0.0.2
+click==8.5.0
+cloudpickle==3.1.2
+configargparse==1.7.7
+decorator==5.3.1
+defusedxml==0.7.1
+distance==0.1.3
+editdistance==0.8.1
+einops==0.8.2
+espnet==202511
+espnet-g2p-en==2.1.0.post1
+espnet-tts-frontend==0.0.4
+fast-bss-eval==0.1.3
+filelock==3.32.3
+frozenlist==1.8.0
+fsspec==2026.7.0
+h5py==3.16.0
+hf-xet==1.6.0
+huggingface-hub==0.36.0
+humanfriendly==10.0
+hydra-core==1.3.7
+idna==3.20
+importlib-metadata==4.13.0
+inflect==7.5.0
+jaconv==0.5.0
+jamo==0.4.1
+jinja2==3.1.6
+joblib==1.6.0
+kaldiio==2.18.1
+lazy-loader==0.6
+librosa==0.11.0
+lightning==2.6.6
+lightning-utilities==0.15.3
+llvmlite==0.49.0
+markupsafe==3.0.3
+more-itertools==11.1.0
+mpmath==1.3.0
+msgpack==1.2.2
+multidict==6.9.1
+networkx==3.4.2
+nltk==3.10.3
+numba==0.67.0
+numpy==2.2.6
+nvidia-cublas-cu11==11.11.3.6
+nvidia-cuda-cupti-cu11==11.8.87
+nvidia-cuda-nvrtc-cu11==11.8.89
+nvidia-cuda-runtime-cu11==11.8.89
+nvidia-cudnn-cu11==9.1.0.70
+nvidia-cufft-cu11==10.9.0.58
+nvidia-curand-cu11==10.3.0.86
+nvidia-cusolver-cu11==11.4.1.48
+nvidia-cusparse-cu11==11.7.5.86
+nvidia-nccl-cu11==2.21.5
+nvidia-nvtx-cu11==11.8.86
+omegaconf==2.3.0
+opt-einsum==3.4.0
+packaging==26.3
+platformdirs==4.11.14
+pooch==1.9.0
+propcache==0.5.4
+protobuf==7.36.2
+ptflops==0.7.5
+pycparser==3.0
+pypinyin==0.44.0
+pytorch-lightning==2.6.6
+pyworld==0.3.5
+pyyaml==6.0.3
+regex==2026.9.10
+requests==2.34.2
+scikit-learn==1.7.2
+scipy==1.15.3
+sentencepiece==0.2.0
+setuptools==73.0.1
+soundfile==0.13.1
+soxr==1.1.0
+sympy==1.13.1
+threadpoolctl==3.7.0
+toml==0.10.2
+torch @ https://download-r2.pytorch.org/whl/cu118/torch-2.6.0%2Bcu118-cp310-cp310-linux_x86_64.whl#sha256=715d3b039a629881f263c40d1fb65edac6786da13bfba221b353ef2371c4da86
+torch-complex==0.4.4
+torchaudio @ https://download-r2.pytorch.org/whl/cu118/torchaudio-2.6.0%2Bcu118-cp310-cp310-linux_x86_64.whl#sha256=c5f0ff8434766f2950d77261b119163dbe8a02bc5c18482d9c0d76c9b18dfd44
+torchmetrics==1.9.0
+tqdm==4.67.1
+triton==3.2.0
+typeguard==4.6.0
+typing-extensions==4.16.0
+unidecode==1.4.0
+urllib3==2.8.0
+yarl==1.25.1
+zipp==4.1.0
diff --git a/bench/wrappers/locks/resemble.txt b/bench/wrappers/locks/resemble.txt
new file mode 100644
index 0000000..ecc5b5f
--- /dev/null
+++ b/bench/wrappers/locks/resemble.txt
@@ -0,0 +1,118 @@
+# The resemble venv (resemble-enhance): Python 3.10, the exact packages that
+# rendered the board. setupfield.sh installs it with uv pip sync.
+aiofiles==23.2.1
+altair==5.5.0
+annotated-doc==0.0.4
+annotated-types==0.7.0
+antlr4-python3-runtime==4.9.3
+anyio==4.14.1
+attrs==26.1.0
+audioread==3.1.0
+celluloid==0.2.0
+certifi==2026.6.17
+cffi==2.0.0
+charset-normalizer==3.4.7
+click==8.4.2
+contourpy==1.3.2
+cycler==0.12.1
+decorator==5.3.1
+deepspeed==0.12.4
+exceptiongroup==1.3.1
+fastapi==0.139.0
+ffmpy==1.0.0
+filelock==3.29.4
+fonttools==4.63.0
+fsspec==2026.6.0
+gradio==4.8.0
+gradio-client==0.7.1
+h11==0.16.0
+hf-xet==1.5.1
+hjson==3.1.0
+httpcore==1.0.9
+httpx==0.28.1
+huggingface-hub==1.21.0
+idna==3.18
+importlib-resources==6.5.2
+jinja2==3.1.6
+joblib==1.5.3
+jsonschema==4.26.0
+jsonschema-specifications==2025.9.1
+kiwisolver==1.5.0
+lazy-loader==0.5
+librosa==0.10.1
+llvmlite==0.48.0
+markdown-it-py==4.2.0
+markupsafe==2.1.5
+matplotlib==3.8.1
+mdurl==0.1.2
+mpmath==1.3.0
+msgpack==1.2.1
+narwhals==2.23.0
+networkx==3.4.2
+ninja==1.13.0
+numba==0.66.0
+numpy==1.26.2
+nvidia-cublas-cu12==12.1.3.1
+nvidia-cuda-cupti-cu12==12.1.105
+nvidia-cuda-nvrtc-cu12==12.1.105
+nvidia-cuda-runtime-cu12==12.1.105
+nvidia-cudnn-cu12==8.9.2.26
+nvidia-cufft-cu12==11.0.2.54
+nvidia-curand-cu12==10.3.2.106
+nvidia-cusolver-cu12==11.4.5.107
+nvidia-cusparse-cu12==12.1.0.106
+nvidia-ml-py==13.610.43
+nvidia-nccl-cu12==2.18.1
+nvidia-nvjitlink-cu12==12.9.86
+nvidia-nvtx-cu12==12.1.105
+omegaconf==2.3.0
+orjson==3.11.9
+packaging==26.2
+pandas==2.1.3
+pillow==10.4.0
+platformdirs==4.10.0
+pooch==1.9.0
+psutil==7.2.2
+ptflops==0.7.1.2
+py-cpuinfo==9.0.0
+pycparser==3.0
+pydantic==2.13.4
+pydantic-core==2.46.4
+pydub==0.25.1
+pygments==2.20.0
+pynvml==13.0.1
+pyparsing==3.3.2
+python-dateutil==2.9.0.post0
+python-multipart==0.0.32
+pytz==2026.2
+pyyaml==6.0.3
+referencing==0.37.0
+requests==2.34.2
+resampy==0.4.2
+resemble-enhance==0.0.1
+rich==13.7.0
+rpds-py==0.30.0
+scikit-learn==1.7.2
+scipy==1.11.4
+semantic-version==2.10.0
+shellingham==1.5.4
+six==1.17.0
+soundfile==0.12.1
+soxr==1.1.0
+starlette==1.3.1
+sympy==1.14.0
+tabulate==0.8.10
+threadpoolctl==3.6.0
+tomlkit==0.12.0
+torch==2.1.1
+torchaudio==2.1.1
+torchvision==0.16.1
+tqdm==4.66.1
+triton==2.1.0
+typer==0.24.2
+typing-extensions==4.15.0
+typing-inspection==0.4.2
+tzdata==2026.2
+urllib3==2.7.0
+uvicorn==0.49.0
+websockets==11.0.3
diff --git a/bench/wrappers/locks/reuse.txt b/bench/wrappers/locks/reuse.txt
new file mode 100644
index 0000000..b0b642b
--- /dev/null
+++ b/bench/wrappers/locks/reuse.txt
@@ -0,0 +1,81 @@
+# The reuse venv (NVIDIA NemotronLabs RE-USE and RE-USE-laughter): Python 3.11, the
+# exact packages that rendered the board. setupfield.sh installs it with uv pip sync.
+# torch comes from the PyTorch CUDA 12.8 index; mamba-ssm and causal-conv1d are the
+# prebuilt wheels of their releases, pinned by URL.
+--extra-index-url https://download.pytorch.org/whl/cu128
+annotated-doc==0.0.5
+anyio==4.15.1
+audioread==3.1.0
+causal-conv1d @ https://github.com/Dao-AILab/causal-conv1d/releases/download/v1.7.0/causal_conv1d-1.7.0+cu12torch2.9cxx11abiTRUE-cp311-cp311-linux_x86_64.whl
+certifi==2026.10.23
+cffi==2.1.1
+charset-normalizer==3.5.2
+click==8.5.0
+cloudpickle==3.1.2
+decorator==5.3.1
+einops==0.8.2
+filelock==4.2.4
+fsspec==2026.9.0
+h11==0.16.0
+hf-xet==1.8.0
+httpcore==1.0.9
+httpx==0.28.1
+huggingface-hub==1.26.0
+idna==3.20
+jinja2==3.1.6
+joblib==1.6.0
+lazy-loader==0.6
+librosa==0.11.0
+llvmlite==0.50.0
+mamba-ssm @ https://github.com/state-spaces/mamba/releases/download/v2.3.2.post1/mamba_ssm-2.3.2.post1+cu12torch2.9cxx11abiTRUE-cp311-cp311-linux_x86_64.whl
+markdown-it-py==4.2.0
+markupsafe==3.0.3
+mdurl==0.1.2
+mpmath==1.3.0
+msgpack==1.2.4
+narwhals==2.28.0
+networkx==3.6.1
+ninja==1.13.0
+numba==0.68.1
+numpy==2.4.6
+nvidia-cublas-cu12==12.8.4.1
+nvidia-cuda-cupti-cu12==12.8.90
+nvidia-cuda-nvrtc-cu12==12.8.93
+nvidia-cuda-runtime-cu12==12.8.90
+nvidia-cudnn-cu12==9.10.2.21
+nvidia-cufft-cu12==11.3.3.83
+nvidia-cufile-cu12==1.13.1.3
+nvidia-curand-cu12==10.3.9.90
+nvidia-cusolver-cu12==11.7.3.90
+nvidia-cusparse-cu12==12.5.8.93
+nvidia-cusparselt-cu12==0.7.1
+nvidia-nccl-cu12==2.27.5
+nvidia-nvjitlink-cu12==12.8.93
+nvidia-nvshmem-cu12==3.3.20
+nvidia-nvtx-cu12==12.8.90
+packaging==26.3
+platformdirs==4.14.0
+pooch==1.9.0
+pycparser==3.12
+pygments==2.21.0
+pyyaml==6.0.3
+regex==2026.9.29
+requests==2.34.2
+rich==15.0.0
+safetensors==0.8.0
+scikit-learn==1.9.1
+scipy==1.17.1
+shellingham==1.5.4
+soundfile==0.14.0
+soxr==1.1.0
+sympy==1.14.0
+threadpoolctl==3.7.0
+tokenizers==0.22.2
+torch==2.9.1+cu128
+torchaudio==2.9.1+cu128
+tqdm==4.70.0
+transformers==5.14.1
+triton==3.5.1
+typer==0.27.3
+typing-extensions==4.16.0
+urllib3==2.8.0
diff --git a/bench/wrappers/locks/smule.txt b/bench/wrappers/locks/smule.txt
new file mode 100644
index 0000000..6be8b12
--- /dev/null
+++ b/bench/wrappers/locks/smule.txt
@@ -0,0 +1,46 @@
+# The smule venv (Smule Renaissance): Python 3.10, the exact packages that
+# rendered the board. setupfield.sh installs it with uv pip sync.
+anyio==4.15.1
+cffi==2.1.1
+click==8.5.0
+exceptiongroup==1.3.1
+filelock==4.0.4
+fsspec==2026.9.0
+h11==0.16.0
+hf-xet==1.6.0
+httpcore2==2.13.1
+httpx2==2.13.1
+huggingface-hub==2.0.0
+idna==3.20
+jinja2==3.1.6
+markupsafe==3.0.3
+mpmath==1.3.0
+networkx==3.4.2
+numpy==2.2.6
+nvidia-cublas-cu12==12.6.4.1
+nvidia-cuda-cupti-cu12==12.6.80
+nvidia-cuda-nvrtc-cu12==12.6.77
+nvidia-cuda-runtime-cu12==12.6.77
+nvidia-cudnn-cu12==9.5.1.17
+nvidia-cufft-cu12==11.3.0.4
+nvidia-cufile-cu12==1.11.1.6
+nvidia-curand-cu12==10.3.7.77
+nvidia-cusolver-cu12==11.7.1.2
+nvidia-cusparse-cu12==12.5.4.2
+nvidia-cusparselt-cu12==0.6.3
+nvidia-nccl-cu12==2.26.2
+nvidia-nvjitlink-cu12==12.6.85
+nvidia-nvtx-cu12==12.6.77
+packaging==26.3
+pycparser==3.0
+pyyaml==6.0.3
+setuptools==84.0.0
+soundfile==0.14.0
+sympy==1.14.0
+tomli==2.4.1
+torch==2.7.1
+torchaudio==2.7.1
+tqdm==4.70.1
+triton==3.3.1
+truststore==0.10.4
+typing-extensions==4.16.0
diff --git a/bench/wrappers/locks/unipase.txt b/bench/wrappers/locks/unipase.txt
new file mode 100644
index 0000000..ae41c62
--- /dev/null
+++ b/bench/wrappers/locks/unipase.txt
@@ -0,0 +1,102 @@
+# The unipase venv (UniPASE): Python 3.10, the exact packages that
+# rendered the board. setupfield.sh installs it with uv pip sync.
+aiohappyeyeballs==2.7.1
+aiohttp==3.14.3
+aiosignal==1.4.0
+antlr4-python3-runtime==4.9.3
+asteroid-filterbanks==0.4.0
+async-timeout==5.0.1
+attrs==26.1.0
+audioread==3.1.0
+certifi==2026.7.22
+cffi==2.1.1
+charset-normalizer==3.5.1
+ci-sdr==0.0.2
+click==8.5.0
+cloudpickle==3.1.2
+configargparse==1.7.7
+decorator==5.3.1
+defusedxml==0.7.1
+distance==0.1.3
+editdistance==0.8.1
+einops==0.8.2
+espnet==202511
+espnet-g2p-en==2.1.0.post1
+espnet-tts-frontend==0.0.4
+fast-bss-eval==0.1.3
+filelock==3.32.3
+frozenlist==1.8.0
+fsspec==2026.7.0
+h5py==3.16.0
+hf-xet==1.6.0
+huggingface-hub==0.36.0
+humanfriendly==10.0
+hydra-core==1.3.7
+idna==3.20
+importlib-metadata==4.13.0
+inflect==7.5.0
+jaconv==0.5.0
+jamo==0.4.1
+jinja2==3.1.6
+joblib==1.6.0
+kaldiio==2.18.1
+lazy-loader==0.6
+librosa==0.11.0
+lightning==2.6.6
+lightning-utilities==0.15.3
+llvmlite==0.49.0
+markupsafe==3.0.3
+more-itertools==11.1.0
+mpmath==1.3.0
+msgpack==1.2.2
+multidict==6.9.1
+networkx==3.4.2
+nltk==3.10.3
+numba==0.67.0
+numpy==2.2.6
+nvidia-cublas-cu11==11.11.3.6
+nvidia-cuda-cupti-cu11==11.8.87
+nvidia-cuda-nvrtc-cu11==11.8.89
+nvidia-cuda-runtime-cu11==11.8.89
+nvidia-cudnn-cu11==9.1.0.70
+nvidia-cufft-cu11==10.9.0.58
+nvidia-curand-cu11==10.3.0.86
+nvidia-cusolver-cu11==11.4.1.48
+nvidia-cusparse-cu11==11.7.5.86
+nvidia-nccl-cu11==2.21.5
+nvidia-nvtx-cu11==11.8.86
+omegaconf==2.3.0
+opt-einsum==3.4.0
+packaging==26.3
+platformdirs==4.12.0
+pooch==1.9.0
+propcache==0.5.4
+protobuf==7.36.2
+ptflops==0.7.5
+pycparser==3.0
+pypinyin==0.44.0
+pytorch-lightning==2.6.6
+pyworld==0.3.5
+pyyaml==6.0.3
+regex==2026.9.10
+requests==2.34.2
+scikit-learn==1.7.2
+scipy==1.15.3
+sentencepiece==0.2.0
+setuptools==73.0.1
+soundfile==0.13.1
+soxr==1.1.0
+sympy==1.13.1
+threadpoolctl==3.7.0
+torch @ https://download-r2.pytorch.org/whl/cu118/torch-2.6.0%2Bcu118-cp310-cp310-linux_x86_64.whl#sha256=715d3b039a629881f263c40d1fb65edac6786da13bfba221b353ef2371c4da86
+torch-complex==0.4.4
+torchaudio @ https://download-r2.pytorch.org/whl/cu118/torchaudio-2.6.0%2Bcu118-cp310-cp310-linux_x86_64.whl#sha256=c5f0ff8434766f2950d77261b119163dbe8a02bc5c18482d9c0d76c9b18dfd44
+torchmetrics==1.9.0
+tqdm==4.67.1
+triton==3.2.0
+typeguard==4.6.0
+typing-extensions==4.16.0
+unidecode==1.4.0
+urllib3==2.8.0
+yarl==1.25.1
+zipp==4.1.0
diff --git a/bench/wrappers/locks/urgent26.txt b/bench/wrappers/locks/urgent26.txt
new file mode 100644
index 0000000..8641233
--- /dev/null
+++ b/bench/wrappers/locks/urgent26.txt
@@ -0,0 +1,172 @@
+# The urgent26 venv (the URGENT 2026 baselines and the challenge's evaluation toolkit): Python 3.10, the exact packages that
+# rendered the board. setupfield.sh installs it with uv pip sync.
+aiohappyeyeballs==2.7.1
+aiohttp==3.14.3
+aiosignal==1.4.0
+annotated-types==0.8.0
+antlr4-python3-runtime==4.8
+asteroid-filterbanks==0.4.0
+async-timeout==5.0.1
+attrs==26.1.0
+audioread==3.1.0
+babel==2.18.0
+bitarray==3.11.0
+certifi==2026.7.22
+cffi==2.1.1
+charset-normalizer==3.5.1
+ci-sdr==0.0.2
+click==8.5.0
+cloudpickle==3.1.2
+colorama==0.4.6
+coloredlogs==15.0.1
+configargparse==1.7.7
+contourpy==1.3.2
+csvw==4.1.0
+ctc-segmentation==1.7.4
+cuda-bindings==13.3.1
+cuda-pathfinder==1.8.1
+cuda-toolkit==13.0.2
+cycler==0.12.1
+cython==3.3.0
+decorator==5.3.1
+defusedxml==0.7.1
+discrete-speech-metrics @ git+https://github.com/kohei0209/DiscreteSpeechMetrics.git@e7c2d365b289403e4a0afe3444147b96089b4664
+distance==0.1.3
+dlinfo==2.0.0
+editdistance==0.8.1
+einops==0.8.2
+emo2vec-versa @ git+https://github.com/ftshijt/emotion2vec.git@952bab359c2f4436bf5c202f218b04d5cf49a5ac
+espnet==202511
+espnet-g2p-en==2.1.0.post1
+espnet-model-zoo==0.1.7
+espnet-tts-frontend==0.0.4
+fairseq==0.12.2
+fast-bss-eval==0.1.3
+fastdtw==0.3.4
+filelock==3.32.5
+flatbuffers==25.12.19
+fonttools==4.64.0
+frozenlist==1.8.0
+fsspec==2026.7.0
+h5py==3.16.0
+hf-xet==1.6.0
+huggingface-hub==0.36.2
+humanfriendly==10.0
+hydra-core==1.0.7
+idna==3.19
+importlib-metadata==4.13.0
+inflect==7.0.0
+isodate==0.7.2
+jaconv==0.5.0
+jamo==0.4.1
+jellyfish==1.2.1
+jinja2==3.1.6
+joblib==1.6.0
+jsonschema==4.26.0
+jsonschema-specifications==2025.9.1
+kaldiio==2.18.1
+kiwisolver==1.5.1
+language-tags==1.3.1
+lazy-loader==0.5
+levenshtein==0.27.4
+librosa==0.11.0
+lightning==2.6.5
+lightning-utilities==0.15.3
+llvmlite==0.49.0
+lxml==6.1.3
+markupsafe==3.0.3
+matplotlib==3.10.9
+more-itertools==11.1.0
+mpmath==1.3.0
+msgpack==1.2.2
+multidict==6.7.1
+networkx==3.4.2
+nltk==3.10.3
+numba==0.67.0
+numpy==2.2.6
+nvidia-cublas==13.1.0.3
+nvidia-cuda-cupti==13.0.85
+nvidia-cuda-nvrtc==13.0.88
+nvidia-cuda-runtime==13.0.96
+nvidia-cudnn-cu13==9.19.0.56
+nvidia-cufft==12.0.0.61
+nvidia-cufile==1.15.1.6
+nvidia-curand==10.4.0.35
+nvidia-cusolver==12.0.4.66
+nvidia-cusparse==12.6.3.3
+nvidia-cusparselt-cu13==0.8.0
+nvidia-nccl-cu13==2.28.9
+nvidia-nvjitlink==13.0.88
+nvidia-nvshmem-cu13==3.4.5
+nvidia-nvtx==13.0.85
+omegaconf==2.0.6
+onnxruntime==1.23.2
+openai-whisper==20250625
+opt-einsum==3.4.0
+packaging==26.3
+pandas==2.3.2
+pesq==0.0.4
+phonemizer==3.3.0
+pillow==12.3.0
+platformdirs==4.11.7
+pooch==1.9.0
+portalocker==4.3.0
+propcache==0.5.2
+protobuf==3.20.1
+pycparser==3.0
+pydantic==2.13.5
+pydantic-core==2.46.5
+pyparsing==3.3.2
+pypinyin==0.44.0
+pysptk==1.0.1
+pystoi==0.4.1
+python-dateutil==2.9.0.post0
+pytorch-lightning==2.6.5
+pytorch-wpe==0.0.1
+pytz==2026.3.post1
+pyworld==0.3.5
+pyyaml==6.0.3
+rapidfuzz==3.14.5
+rdflib==7.6.0
+referencing==0.37.0
+regex==2026.9.3
+requests==2.34.2
+resampy==0.4.3
+rfc3986==1.5.0
+rpds-py==0.30.0
+sacrebleu==2.6.0
+safetensors==0.8.0
+scikit-learn==1.7.2
+scipy==1.15.3
+segments==2.4.0
+sentencepiece==0.2.0
+setuptools==73.0.1
+six==1.17.0
+soundfile==0.14.0
+soxr==1.1.0
+sympy==1.14.0
+tabulate==0.10.0
+termcolor==3.3.0
+threadpoolctl==3.6.0
+tiktoken==0.14.0
+timm==1.0.29
+tokenizers==0.19.1
+torch==2.11.0
+torch-complex==0.4.4
+torch-ema==0.3
+torchaudio==2.11.0
+torchcodec==0.16.0
+torchmetrics==1.9.0
+torchvision==0.26.0
+tqdm==4.70.0
+transformers==4.41.0
+triton==3.6.0
+typeguard==2.13.3
+typing-extensions==4.16.0
+typing-inspection==0.4.4
+tzdata==2026.3
+unidecode==1.4.0
+uritemplate==4.2.0
+urllib3==2.7.0
+yarl==1.24.5
+zipp==4.1.0
diff --git a/bench/wrappers/meta/clearvoice_mf2_48k.json b/bench/wrappers/meta/clearvoice_mf2_48k.json
new file mode 100644
index 0000000..26dcec5
--- /dev/null
+++ b/bench/wrappers/meta/clearvoice_mf2_48k.json
@@ -0,0 +1,22 @@
+{
+ "renormalizes": false,
+ "display": "ClearerVoice MossFormer2_SE_48K",
+ "mechanism": "masking",
+ "native_sr": 48000,
+ "fullband": true,
+ "license_code": "Apache-2.0",
+ "license_weights": "Apache-2.0",
+ "commercial_ok": true,
+ "repo": "https://github.com/modelscope/ClearerVoice-Studio",
+ "weights": "alibabasglab/MossFormer2_SE_48K (Hugging Face): last_best_checkpoint.pt",
+ "notes": "MossFormer2 mask estimation on a 48 kHz STFT, through the clearvoice package's own API. Inputs over 20 s are decoded in 4 s windows, as the release's configuration sets. The filterbank dither the package draws at random is seeded per file, so renders are reproducible.",
+ "source_dir": "clearvoice",
+ "weight_globs": [
+ "checkpoints/MossFormer2_SE_48K/last_best_checkpoint.pt"
+ ],
+ "package_dirs": [
+ "clearvoice"
+ ],
+ "path_switch_seconds": 20.0,
+ "precision": "fp32"
+}
diff --git a/bench/wrappers/meta/dfn3.json b/bench/wrappers/meta/dfn3.json
new file mode 100644
index 0000000..24533a0
--- /dev/null
+++ b/bench/wrappers/meta/dfn3.json
@@ -0,0 +1,21 @@
+{
+ "renormalizes": false,
+ "display": "DeepFilterNet3",
+ "mechanism": "masking and deep filtering",
+ "native_sr": 48000,
+ "fullband": true,
+ "license_code": "MIT or Apache-2.0",
+ "license_weights": "MIT or Apache-2.0",
+ "commercial_ok": true,
+ "repo": "https://github.com/Rikorose/DeepFilterNet",
+ "weights": "models/DeepFilterNet3.zip of the release (tag v0.5.6)",
+ "notes": "ERB-band gains plus per-bin complex filters across neighbouring frames, at 48 kHz, two frames of look-ahead; run through the deepfilternet package with the model folder given explicitly.",
+ "source_dir": "deepfilternet",
+ "weight_globs": [
+ "DeepFilterNet3/checkpoints/*"
+ ],
+ "package_dirs": [
+ "df"
+ ],
+ "precision": "fp32"
+}
diff --git a/bench/wrappers/meta/fastenhancer_l_48k.json b/bench/wrappers/meta/fastenhancer_l_48k.json
new file mode 100644
index 0000000..71ea334
--- /dev/null
+++ b/bench/wrappers/meta/fastenhancer_l_48k.json
@@ -0,0 +1,18 @@
+{
+ "renormalizes": false,
+ "display": "FastEnhancer-L 48k",
+ "mechanism": "masking",
+ "native_sr": 48000,
+ "fullband": true,
+ "license_code": "MIT",
+ "license_weights": "MIT (the repository's licence)",
+ "commercial_ok": true,
+ "repo": "https://github.com/aask1357/fastenhancer",
+ "weights": "fastenhancer_l.onnx of the GitHub release onnx-48khz-v1",
+ "notes": "The release's own ONNX export driven frame by frame (200-sample hops) with its recurrent state carried between frames, as the release's test script runs it; onnxruntime on the CPU.",
+ "source_dir": "fastenhancer_onnx",
+ "weight_globs": [
+ "fastenhancer_l.onnx"
+ ],
+ "precision": "fp32"
+}
diff --git a/bench/wrappers/meta/gap_urgenet.json b/bench/wrappers/meta/gap_urgenet.json
new file mode 100644
index 0000000..62d2e9e
--- /dev/null
+++ b/bench/wrappers/meta/gap_urgenet.json
@@ -0,0 +1,19 @@
+{
+ "renormalizes": true,
+ "display": "GAP-URGENet (URGENT 2026 Track 1, 1st objective)",
+ "mechanism": "generative + predictive fusion",
+ "native_sr": 48000,
+ "fullband": true,
+ "license_code": "MIT",
+ "license_weights": "Apache-2.0",
+ "commercial_ok": true,
+ "repo": "https://github.com/Xiaobin-Rong/gap-urgenet",
+ "weights": "Xiaobin-Rong/gap-urgenet (Hugging Face): DeWavLM-Omni, Adapter, Vocoder, Predictor, PostNet",
+ "notes": "Two 16 kHz branches (a generative one, DeWavLM-Omni features to a neural vocoder; a predictive spectral one) fused by a post-net that generates the band up to 24 kHz; input content above 8 kHz does not reach the output. Run through the release's inference modules (whole files up to 20 s, segmented beyond), checkpoints passed by path. The release scales every output to the input's peak, which adds more gain the noisier the input; its packet-loss concealment, on by default, fills runs of exact digital zeros. Re-synthesises the waveform: the coherent retention metrics may read it as deleted speech (see bench/METRICS.md, \"How to read it\"). Not bit-reproducible: the release's GPU kernels vary from run to run, so two renders of an item differ slightly.",
+ "source_dir": "gap-urgenet",
+ "weight_globs": [
+ "ckpts/*.pt"
+ ],
+ "path_switch_seconds": 20.0,
+ "precision": "fp32"
+}
diff --git a/bench/wrappers/meta/resemble_dn.json b/bench/wrappers/meta/resemble_dn.json
new file mode 100644
index 0000000..1f5c476
--- /dev/null
+++ b/bench/wrappers/meta/resemble_dn.json
@@ -0,0 +1,22 @@
+{
+ "renormalizes": false,
+ "display": "resemble-enhance (denoise)",
+ "mechanism": "masking (the denoiser stage)",
+ "native_sr": 44100,
+ "fullband": true,
+ "license_code": "MIT",
+ "license_weights": "see upstream",
+ "commercial_ok": null,
+ "repo": "https://github.com/resemble-ai/resemble-enhance",
+ "weights": "ResembleAI/resemble-enhance (Hugging Face): enhancer_stage2",
+ "notes": "The denoiser stage alone, without the enhancer (the release's --denoise_only), at 44.1 kHz; inputs over 30 s are processed in 30 s chunks overlapping by 1 s. The weights folder is given explicitly; without one the package pulls the repository's main branch on every start.",
+ "source_dir": "resemble-enhance",
+ "weight_globs": [
+ "enhancer_stage2/ds/G/default/mp_rank_00_model_states.pt"
+ ],
+ "package_dirs": [
+ "resemble_enhance"
+ ],
+ "path_switch_seconds": 30.0,
+ "precision": "fp32"
+}
diff --git a/bench/wrappers/meta/reuse_nemotron.json b/bench/wrappers/meta/reuse_nemotron.json
new file mode 100644
index 0000000..b18af54
--- /dev/null
+++ b/bench/wrappers/meta/reuse_nemotron.json
@@ -0,0 +1,19 @@
+{
+ "renormalizes": false,
+ "display": "NVIDIA NemotronLabs RE-USE (9.6M, 2026-10)",
+ "mechanism": "spectral mapping",
+ "native_sr": 48000,
+ "fullband": true,
+ "license_code": "OpenMDW-1.1",
+ "license_weights": "OpenMDW-1.1",
+ "commercial_ok": true,
+ "repo": "https://huggingface.co/nvidia/NVIDIA-NemotronLabs-RE-USE",
+ "weights": "nvidia/NVIDIA-NemotronLabs-RE-USE (Hugging Face): model.safetensors",
+ "params_m": 9.6,
+ "notes": "The 2026-10 NemotronLabs release of RE-USE (new weights, same 9.6M USEMamba, OpenMDW-1.1): the release's inference.py, its magnitude decompression and blanked frames included, on whole files.",
+ "source_dir": "reuse_nemotron",
+ "weight_globs": [
+ "model.safetensors"
+ ],
+ "precision": "fp32"
+}
diff --git a/bench/wrappers/meta/reuse_nemotron_laughter.json b/bench/wrappers/meta/reuse_nemotron_laughter.json
new file mode 100644
index 0000000..dd53e86
--- /dev/null
+++ b/bench/wrappers/meta/reuse_nemotron_laughter.json
@@ -0,0 +1,19 @@
+{
+ "renormalizes": false,
+ "display": "NVIDIA NemotronLabs RE-USE-laughter (9.6M, 2026-10)",
+ "mechanism": "spectral mapping",
+ "native_sr": 48000,
+ "fullband": true,
+ "license_code": "OpenMDW-1.1",
+ "license_weights": "OpenMDW-1.1",
+ "commercial_ok": true,
+ "repo": "https://huggingface.co/nvidia/NVIDIA-NemotronLabs-RE-USE-laughter",
+ "weights": "nvidia/NVIDIA-NemotronLabs-RE-USE-laughter (Hugging Face): model.safetensors",
+ "params_m": 9.6,
+ "notes": "The 2026-10 NemotronLabs release of RE-USE (new weights, same 9.6M USEMamba, OpenMDW-1.1): the release's inference.py, its magnitude decompression and blanked frames included, on whole files. The variant trained to keep laughter.",
+ "source_dir": "reuse_nemotron_laughter",
+ "weight_globs": [
+ "model.safetensors"
+ ],
+ "precision": "fp32"
+}
diff --git a/bench/wrappers/meta/smule.json b/bench/wrappers/meta/smule.json
new file mode 100644
index 0000000..806392b
--- /dev/null
+++ b/bench/wrappers/meta/smule.json
@@ -0,0 +1,18 @@
+{
+ "renormalizes": false,
+ "display": "Smule Renaissance Small (10.4M)",
+ "mechanism": "generative, complex STFT (single stage)",
+ "native_sr": 48000,
+ "fullband": true,
+ "license_code": "MIT",
+ "license_weights": "MIT",
+ "commercial_ok": true,
+ "repo": "https://github.com/smulelabs/smule-renaissance",
+ "weights": "smulelabs/Smule-Renaissance-Small (Hugging Face): smule-renaissance-small.pt",
+ "notes": "Vocal restoration (arXiv 2510.21659): one complex-STFT model (4096-point window, hop 2048) trained for degraded vocals, singing included, at 48 kHz. The release's processing is reproduced step by step: mono, a 60 Hz high-pass, peak normalisation to full scale, the model in half precision on the GPU, the inverse STFT and the inverse of the normalisation, so the level returns to the input's peak. Whole items are processed at once, as the release does. Its inverse STFT takes no target length, so outputs end with up to 2047 zero samples (43 ms).",
+ "source_dir": "smule-renaissance",
+ "weight_globs": [
+ "smule-renaissance-small.pt"
+ ],
+ "precision": "fp16"
+}
diff --git a/bench/wrappers/meta/unipase.json b/bench/wrappers/meta/unipase.json
new file mode 100644
index 0000000..29f5b2b
--- /dev/null
+++ b/bench/wrappers/meta/unipase.json
@@ -0,0 +1,19 @@
+{
+ "renormalizes": true,
+ "display": "UniPASE (TASLP 2026, 16 kHz core, post-net to 48 kHz)",
+ "mechanism": "generative (phonetic representation to adapter to vocoder, post-net to 48 kHz)",
+ "native_sr": 48000,
+ "fullband": true,
+ "license_code": "MIT",
+ "license_weights": "Apache-2.0",
+ "commercial_ok": true,
+ "repo": "https://github.com/Xiaobin-Rong/unipase",
+ "weights": "Xiaobin-Rong/unipase (Hugging Face): DeWavLM-Omni, Adapter, Vocoder_DWO-L1, PostNet",
+ "notes": "The PASE family's universal member (arXiv 2604.14606) and the generative branch of GAP-URGENet: DeWavLM-Omni phonetic representations, an adapter, a 16 kHz vocoder and a post-net that generates the band up to 24 kHz before resampling to the input rate; input content above 8 kHz does not reach the output. Run through the release's inference modules (whole files up to 20 s, segmented beyond), checkpoints passed by path. The release scales every output to the input's peak; its packet-loss concealment, on by default, fills runs of exact digital zeros. Re-synthesises the waveform without exact sample alignment to the input (a few samples, differing from item to item), so the residual-based readings (suppression, SI-SDR, the fidelity axis) read the misalignment as noise and loss, unlike GAP-URGENet, whose predictive branch keeps it aligned; read NISQA, speaker similarity, the deletion rate, downstream ASR and the content check for this row.",
+ "source_dir": "unipase",
+ "weight_globs": [
+ "ckpts/*.pt"
+ ],
+ "path_switch_seconds": 20.0,
+ "precision": "fp32"
+}
diff --git a/bench/wrappers/meta/urgent26_bsrnn.json b/bench/wrappers/meta/urgent26_bsrnn.json
new file mode 100644
index 0000000..3d88b9e
--- /dev/null
+++ b/bench/wrappers/meta/urgent26_bsrnn.json
@@ -0,0 +1,18 @@
+{
+ "renormalizes": true,
+ "display": "URGENT26 BSRNN baseline (official, 48k, shipped peak normalisation)",
+ "mechanism": "masking",
+ "native_sr": 48000,
+ "fullband": true,
+ "license_code": "Apache-2.0",
+ "license_weights": "see upstream",
+ "commercial_ok": null,
+ "repo": "https://github.com/urgent-challenge/urgent2026_challenge_track1",
+ "weights": "lichenda/icassp_2026_urgent_baseline (Hugging Face): bsrnn.ckpt",
+ "notes": "Sampling-frequency independent; fed 48 kHz here. The model's own output is at a scale of its own (peaks past full scale: a scale-invariant training loss), so the official script's peak normalisation to 0.9 is kept as the level the shipped baseline delivers. VIBE measures that level change on clean speech, reports it in fidelity's level term and undoes it before reading suppression, the high-band error and deletion. The FlowSE baseline's model keeps the input's scale, so its script step is left out.",
+ "source_dir": "urgent26",
+ "weight_globs": [
+ "ckpts/bsrnn.ckpt"
+ ],
+ "precision": "fp32"
+}
diff --git a/bench/wrappers/meta/urgent26_bsrnn_flow.json b/bench/wrappers/meta/urgent26_bsrnn_flow.json
new file mode 100644
index 0000000..18d322f
--- /dev/null
+++ b/bench/wrappers/meta/urgent26_bsrnn_flow.json
@@ -0,0 +1,18 @@
+{
+ "renormalizes": false,
+ "display": "URGENT26 FlowSE baseline (official, 48k, without final peak normalisation)",
+ "mechanism": "generative (conditional flow matching)",
+ "native_sr": 48000,
+ "fullband": true,
+ "license_code": "Apache-2.0",
+ "license_weights": "see upstream",
+ "commercial_ok": null,
+ "repo": "https://github.com/urgent-challenge/urgent2026_challenge_track1",
+ "weights": "lichenda/icassp_2026_urgent_baseline (Hugging Face): flow_bsrnn.ckpt",
+ "notes": "Conditional flow matching on an improved BSRNN backbone, Euler solver with 15 steps, EMA weights; per-file deterministic prior noise. Sampling-frequency independent; fed 48 kHz here. The official script's peak normalisation to 0.9 (a convention of the challenge's scale-invariant evaluation) is left out: the model's own output keeps the input's scale. Generative: see bench/METRICS.md, \"How to read it\". The prior noise is seeded per file name, so a cut of an item draws different noise from the item.",
+ "source_dir": "urgent26",
+ "weight_globs": [
+ "ckpts/flow_bsrnn.ckpt"
+ ],
+ "precision": "fp32"
+}
diff --git a/bench/wrappers/pase.py b/bench/wrappers/pase.py
new file mode 100644
index 0000000..bb06825
--- /dev/null
+++ b/bench/wrappers/pase.py
@@ -0,0 +1,124 @@
+"""Runs a release of the PASE family (GAP-URGENet, UniPASE) as its README says.
+
+Both releases ship ``inference.inference`` for files up to 20 s and
+``inference.inference_long`` (8 s segments, 4 s hop) beyond, take every
+checkpoint by path, and write with soundfile's default WAV subtype, 16-bit
+PCM. ``render`` drives the release's own modules, code untouched, with three
+things set around them:
+
+* every write is float32: a 16-bit write would quantise the model's output
+ before anything of ours reads it;
+* every checkpoint is passed by path from the pinned download under
+ <BENCH_SRC>, with the Hugging Face hub offline, so nothing is fetched while
+ rendering and the receipt's hashes name the weights that ran;
+* each group of files renders in a temporary folder, and its outputs are then
+ fitted to the input's length and written by ``writer``.
+
+Packet-loss concealment stays at the release's default (on): it treats runs of
+exact digital zeros as lost packets and fills them.
+"""
+import os
+import shutil
+import subprocess
+import sys
+import tempfile
+
+import soundfile as sf
+
+import writer # the shared render loop, beside this file
+
+LONG_SECONDS = 20.0
+MODULES = ("inference.inference", "inference.inference_long")
+
+# Runs ``python -m <module> <args>`` with soundfile.write forced to float32.
+RUNNER = ("import runpy, sys, soundfile as sf\n"
+ "_write = sf.write\n"
+ "def _float_write(file, data, samplerate, *args, **kwargs):\n"
+ " if not args and 'subtype' not in kwargs:\n"
+ " kwargs['subtype'] = 'FLOAT'\n"
+ " return _write(file, data, samplerate, *args, **kwargs)\n"
+ "sf.write = _float_write\n"
+ "module = sys.argv.pop(1)\n"
+ "runpy.run_module(module, run_name='__main__', alter_sys=True)\n")
+
+
+def run_module(repo: str, module: str, in_dir: str, out_dir: str, device: str,
+ checkpoints: dict) -> None:
+ """Runs one inference module of the release over ``in_dir``.
+
+ Args:
+ repo: The release's checkout.
+ module: ``inference.inference`` or ``inference.inference_long``.
+ in_dir: Inputs; out_dir: where the release writes.
+ device: The device to compute on.
+ checkpoints: {argument: path}, every checkpoint the release takes.
+ """
+ env = dict(os.environ,
+ HF_HUB_OFFLINE="1",
+ PYTHONPATH=repo + os.pathsep + os.environ.get("PYTHONPATH", ""))
+ cmd = [
+ sys.executable, "-c", RUNNER, module, "-I", in_dir, "-O", out_dir, "-D",
+ device
+ ]
+ for argument, path in checkpoints.items():
+ if not os.path.isfile(path):
+ raise FileNotFoundError(f"{path} is missing: run setupfield.sh")
+ cmd += [argument, path]
+ subprocess.run(cmd, cwd=repo, env=env, check=True)
+
+
+def render(repo: str, files: list, out_dir: str, device: str,
+ checkpoints: dict) -> int:
+ """Renders every file of ``files`` that ``out_dir`` does not hold yet.
+
+ Returns:
+ 0 when every file is present at the end, 1 otherwise.
+ """
+ os.makedirs(out_dir, exist_ok=True)
+ todo = [
+ p for p in files
+ if not os.path.exists(os.path.join(out_dir, os.path.basename(p)))
+ ]
+ groups = {m: [] for m in MODULES}
+ for path in todo:
+ long_file = sf.info(path).duration > LONG_SECONDS
+ groups[MODULES[1] if long_file else MODULES[0]].append(path)
+ done = len(files) - len(todo)
+ work = tempfile.mkdtemp(prefix="pase_")
+ try:
+ for module, paths in groups.items():
+ if paths:
+ done += render_group(repo, module, paths, out_dir, device,
+ checkpoints, os.path.join(work, module))
+ finally:
+ shutil.rmtree(work, ignore_errors=True)
+ print(f"DONE {done}/{len(files)}", flush=True)
+ return 0 if done == len(files) else 1
+
+
+def render_group(repo: str, module: str, paths: list, out_dir: str, device: str,
+ checkpoints: dict, work: str) -> int:
+ """Renders one group through one module; returns how many succeeded."""
+ in_dir, raw_dir = os.path.join(work, "in"), os.path.join(work, "out")
+ os.makedirs(in_dir)
+ for path in paths:
+ os.symlink(os.path.abspath(path),
+ os.path.join(in_dir, os.path.basename(path)))
+ try:
+ run_module(repo, module, in_dir, raw_dir, device, checkpoints)
+ except subprocess.CalledProcessError as e:
+ print(f"FAIL {module}: {e}", flush=True)
+ done = 0
+ for path in paths:
+ name = os.path.basename(path)
+ try:
+ samples, rate = writer.read(path)
+ out, out_rate = writer.read(os.path.join(raw_dir, name))
+ if out_rate != rate:
+ raise ValueError(f"output rate {out_rate}, input rate {rate}")
+ writer.save(os.path.join(out_dir, name),
+ writer.fit(out, len(samples), rate), rate)
+ done += 1
+ except Exception as e: # pylint: disable=broad-exception-caught
+ print(f"FAIL {name} {e}", flush=True)
+ return done
diff --git a/bench/wrappers/receipt.py b/bench/wrappers/receipt.py
new file mode 100644
index 0000000..905e9c5
--- /dev/null
+++ b/bench/wrappers/receipt.py
@@ -0,0 +1,430 @@
+"""What a render depends on, written by the process that made it.
+
+Every renderer calls ``receipt.begin(...)`` once its arguments are parsed,
+and each process (each shard) writes ``<out_dir>/.receipt-<host>-<pid>.json``
+before it renders anything. The identity it records:
+
+* the renderer's own sha256 and that of every sibling module it imports;
+* the upstream release it runs (``source_dir`` in ``meta/<system>.json``,
+ under ``BENCH_SRC``): its git commit when there is one, and a digest of
+ every source file in it (code and configuration, never weights), so an
+ edited checkout or another snapshot is another identity;
+* a digest of the code of every installed package the description names
+ (``package_dirs``), for releases that run from an installed package;
+* the sha256 of every weight file the description names (``weight_globs``);
+ a pattern that matches nothing is an error, never an empty record;
+* the interpreter and every installed distribution with its version;
+* the device it computes on: ``cpu``, or ``cuda`` with the GPU's name,
+ because kernels and precisions differ between devices;
+* the inference arguments: the command line minus the work selection
+ (paths, shards, limits), with every path reduced to its basename;
+* the inputs it is handed: the set build (``checksums.json`` beside the input
+ folder), the streaming probe (``probe.json``), or a digest of the files.
+
+``digest(identity)`` is the sha256 of the whole canonical identity and
+``environment_digest(identity)`` that of everything but the inputs, so a
+render of the streaming probe can be matched to the environment that rendered
+the board. ``bench/scripts/stamprender.py`` stamps a render only when every
+receipt carries the digest of the environment and inputs it is stamping.
+
+Standard library only (torch is consulted for the GPU's name when the venv
+has it): this module runs inside every system's own venv.
+
+ python receipt.py probe <system> <renderer.py> --in-dir DIR \\
+ [--device cuda:0] [--weights path ...] [-- renderer arguments]
+"""
+import argparse
+import datetime
+import glob
+import hashlib
+import importlib.metadata
+import importlib.util
+import json
+import os
+import re
+import socket
+import subprocess
+import sys
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+META_DIR = os.path.join(HERE, "meta")
+SRC = os.environ.get("BENCH_SRC",
+ os.path.expanduser("~/.cache/voice-isolation-bench/src"))
+# options that select work or hardware, not the computation, with a value;
+# the device is recorded on its own, resolved to what it is
+VOLATILE = ("--in-dir", "--out-dir", "--inputs", "--shard", "--device",
+ "--limit", "--threads")
+VOLATILE_FLAGS = ("--overwrite",) # the same, without a value
+# files of a release that hold its code and configuration
+SOURCE_SUFFIXES = (".py", ".pyx", ".c", ".cc", ".cpp", ".cu", ".h", ".yaml",
+ ".yml", ".json", ".toml", ".cfg", ".ini", ".sh")
+SKIPPED_DIRS = frozenset(
+ (".git", "__pycache__", ".cache", ".ipynb_checkpoints", "node_modules"))
+
+
+def sha256_file(path: str, chunk: int = 1 << 22) -> str:
+ """Returns the sha256 of a file, read in chunks."""
+ hasher = hashlib.sha256()
+ with open(path, "rb") as fh:
+ for block in iter(lambda: fh.read(chunk), b""):
+ hasher.update(block)
+ return hasher.hexdigest()
+
+
+def description(system: str) -> dict:
+ """Returns ``meta/<system>.json``, or an empty description."""
+ path = os.path.join(META_DIR, f"{system}.json")
+ if not os.path.exists(path):
+ return {}
+ with open(path, encoding="utf-8") as fh:
+ return json.load(fh)
+
+
+def helpers(renderer_path: str) -> dict:
+ """Returns {file name: sha256} of the sibling modules a renderer imports.
+
+ Directly or through each other.
+ """
+ here = os.path.dirname(os.path.abspath(renderer_path))
+ out, pending = {}, [renderer_path]
+ while pending:
+ with open(pending.pop(), encoding="utf-8") as fh:
+ text = fh.read()
+ for name in re.findall(r"^\s*(?:import|from)\s+([A-Za-z_]\w*)", text,
+ re.M):
+ sibling = os.path.join(here, name + ".py")
+ if (name != "receipt" and os.path.exists(sibling) and
+ name + ".py" not in out):
+ out[name + ".py"] = sha256_file(sibling)
+ pending.append(sibling)
+ return out
+
+
+def tree_digest(root: str, excluded: frozenset = frozenset()) -> str:
+ """Returns a digest of every source file under ``root``.
+
+ Args:
+ root: The directory to walk.
+ excluded: Absolute paths of files to leave out (the weights).
+ """
+ entries = []
+ for top, dirs, files in os.walk(root):
+ dirs[:] = sorted(d for d in dirs if d not in SKIPPED_DIRS)
+ for name in sorted(files):
+ path = os.path.join(top, name)
+ if name.endswith(SOURCE_SUFFIXES) and path not in excluded:
+ rel = os.path.relpath(path, root)
+ entries.append(f"{rel} {sha256_file(path)}")
+ return hashlib.sha256("\n".join(entries).encode()).hexdigest()
+
+
+def weight_paths(desc: dict) -> dict:
+ """Returns {relative path: absolute path} of a description's weights.
+
+ Raises:
+ FileNotFoundError: A declared pattern matches no file.
+ """
+ rel = desc.get("source_dir")
+ root = os.path.join(SRC, rel) if rel else SRC
+ out = {}
+ for pattern in desc.get("weight_globs", []):
+ matched = [
+ p for p in sorted(
+ glob.glob(os.path.join(root, pattern), recursive=True))
+ if os.path.isfile(p)
+ ]
+ if not matched:
+ raise FileNotFoundError(
+ f"no weights match {pattern!r} under {root}: install them "
+ "with setupfield.sh")
+ for path in matched:
+ out[os.path.relpath(path, root)] = path
+ return out
+
+
+def source(desc: dict) -> dict | None:
+ """Returns the upstream release: directory, git commit and source digest.
+
+ None when the description names none.
+
+ Raises:
+ FileNotFoundError: The release's directory is missing.
+ """
+ rel = desc.get("source_dir")
+ if not rel:
+ return None
+ path = os.path.join(SRC, rel)
+ if not os.path.isdir(path):
+ raise FileNotFoundError(f"{path} is missing: run setupfield.sh")
+ commit = None
+ if os.path.isdir(os.path.join(path, ".git")):
+ try:
+ command = ["git", "-C", path, "rev-parse", "HEAD"]
+ commit = subprocess.check_output(command, text=True).strip()
+ except (OSError, subprocess.CalledProcessError):
+ commit = None
+ excluded = frozenset(weight_paths(desc).values())
+ return {
+ "dir": rel,
+ "git_commit": commit,
+ "files_sha256": tree_digest(path, excluded)
+ }
+
+
+def package_code(desc: dict) -> dict:
+ """Returns {package: digest of its source files} for the release's packages.
+
+ The installed packages whose code the release runs (``package_dirs``).
+
+ Raises:
+ ModuleNotFoundError: A named package is not installed.
+ """
+ out = {}
+ for name in desc.get("package_dirs", []):
+ spec = importlib.util.find_spec(name)
+ if spec is None or not spec.submodule_search_locations:
+ raise ModuleNotFoundError(f"package {name!r} is not installed")
+ out[name] = tree_digest(list(spec.submodule_search_locations)[0])
+ return out
+
+
+def packages() -> list:
+ """Returns every installed distribution, ``name==version``, sorted."""
+ names = set()
+ for dist in importlib.metadata.distributions():
+ name = dist.metadata["Name"]
+ if name:
+ names.add(f"{name}=={dist.version}")
+ return sorted(names)
+
+
+def resolve_device(device: str) -> str:
+ """Returns ``cpu`` or ``cuda:<GPU name>`` for a requested device.
+
+ Raises:
+ RuntimeError: CUDA is requested and not available: a render never
+ falls back to the CPU silently.
+ """
+ if not device or not str(device).startswith("cuda"):
+ return "cpu"
+ try:
+ import torch # pylint: disable=import-outside-toplevel
+ except ImportError as e:
+ raise RuntimeError(f"{device} requested; this venv has no torch") from e
+ if not torch.cuda.is_available():
+ raise RuntimeError(f"{device} requested; CUDA is not available")
+ index = int(str(device).split(":")[1]) if ":" in str(device) else 0
+ return f"cuda:{torch.cuda.get_device_name(index)}"
+
+
+def inference_args(argv: list) -> list:
+ """Returns a command line minus the work selection.
+
+ Paths are reduced to their basenames.
+ """
+ out, skip = [], False
+ for token in (argv or [])[1:]:
+ if skip:
+ skip = False
+ elif token in VOLATILE:
+ skip = True
+ elif token in VOLATILE_FLAGS or any(
+ token.startswith(v + "=") for v in VOLATILE):
+ continue
+ else:
+ out.append(os.path.basename(token) if os.sep in token else token)
+ return out
+
+
+def inputs(in_dir: str) -> dict:
+ """Returns what an input folder is.
+
+ A set build, the streaming probe, or a digest of its files.
+ """
+ parent = os.path.dirname(os.path.abspath(in_dir.rstrip(os.sep)))
+ for name, key, field in (("checksums.json", "set_id", "set_id"),
+ ("probe.json", "identity", "probe")):
+ path = os.path.join(parent, name)
+ if os.path.exists(path):
+ with open(path, encoding="utf-8") as fh:
+ value = json.load(fh).get(key)
+ if value:
+ return {field: value}
+ entries = [
+ f"{n} {sha256_file(os.path.join(in_dir, n))}"
+ for n in sorted(os.listdir(in_dir))
+ if n.endswith(".wav")
+ ]
+ digest_ = hashlib.sha256("\n".join(entries).encode()).hexdigest()
+ return {"files_sha256": digest_}
+
+
+def identity(system: str,
+ renderer_path: str,
+ argv: list,
+ in_dir: str,
+ device: str,
+ weights: tuple = (),
+ desc: dict | None = None,
+ code: tuple | None = None) -> dict:
+ """Returns the identity of this environment rendering ``in_dir``.
+
+ Args:
+ system: The system's name.
+ renderer_path: The script that renders.
+ argv: Its command line.
+ in_dir: The folder of inputs it renders.
+ device: The device it was asked to compute on.
+ weights: Further weight files by path (a checkpoint given on the
+ command line), hashed beside the declared ones.
+ desc: The description; ``meta/<system>.json`` when None.
+ code: The files besides the renderer whose code computes, when the
+ renderer's sibling imports are not that (they select work).
+ """
+ desc = description(system) if desc is None else desc
+ declared = {k: sha256_file(p) for k, p in weight_paths(desc).items()}
+ declared.update({os.path.basename(p): sha256_file(p) for p in weights})
+ pkgs = packages()
+ if code is None:
+ code_sha256 = helpers(renderer_path)
+ else:
+ code_sha256 = {os.path.basename(p): sha256_file(p) for p in code}
+ return {
+ "system": system,
+ "wrapper": os.path.basename(renderer_path),
+ "wrapper_sha256": sha256_file(renderer_path),
+ "helpers_sha256": code_sha256,
+ "source": source(desc),
+ "package_code_sha256": package_code(desc),
+ "weights_sha256": declared,
+ "python": sys.version.split()[0],
+ "packages_sha256": hashlib.sha256("\n".join(pkgs).encode()).hexdigest(),
+ "n_packages": len(pkgs),
+ "device": resolve_device(device),
+ "inference_args": inference_args(argv),
+ "inputs": inputs(in_dir),
+ }
+
+
+def digest(ident: dict) -> str:
+ """Returns the sha256 of an identity in canonical form."""
+ text = json.dumps(ident, sort_keys=True, separators=(",", ":"))
+ return hashlib.sha256(text.encode()).hexdigest()
+
+
+def environment_digest(ident: dict) -> str:
+ """Returns the digest of an identity without its inputs."""
+ return digest({k: v for k, v in ident.items() if k != "inputs"})
+
+
+def process_start(pid: int) -> str | None:
+ """Returns the start time of ``pid`` as the kernel records it (Linux:
+ ``/proc/<pid>/stat``, in clock ticks since boot), or None where it cannot
+ be read; with the pid it names one process, since a pid alone can be
+ reused."""
+ try:
+ with open(f"/proc/{int(pid)}/stat", encoding="utf-8") as fh:
+ stat = fh.read()
+ except (OSError, ValueError):
+ return None
+ fields = stat[stat.rfind(")") + 2:].split()
+ return fields[19] if len(fields) > 19 else None
+
+
+def own_path(out_dir: str) -> str:
+ """Returns the path of this process's receipt in ``out_dir``."""
+ return os.path.join(out_dir,
+ f".receipt-{socket.gethostname()}-{os.getpid()}.json")
+
+
+def write(out_dir: str, ident: dict, argv: list | None = None) -> str:
+ """Writes this process's receipt into ``out_dir``; returns its digest."""
+ os.makedirs(out_dir, exist_ok=True)
+ host = socket.gethostname()
+ path = own_path(out_dir)
+ doc = {
+ "identity":
+ ident,
+ "digest":
+ digest(ident),
+ "environment_digest":
+ environment_digest(ident),
+ "argv":
+ inference_args(argv),
+ "packages":
+ packages(),
+ "host":
+ host,
+ "pid":
+ os.getpid(),
+ "process_start":
+ process_start(os.getpid()),
+ "time":
+ datetime.datetime.now(datetime.timezone.utc
+ ).strftime("%Y-%m-%dT%H:%M:%SZ"),
+ }
+ tmp = f"{path}.tmp"
+ with open(tmp, "w", encoding="utf-8") as fh:
+ json.dump(doc, fh, indent=1, sort_keys=True)
+ os.replace(tmp, path)
+ return doc["digest"]
+
+
+def begin(system: str, renderer_file: str, out_dir: str, argv: list,
+ in_dir: str, device: str, **kwargs) -> str:
+ """Writes this process's receipt before it renders anything.
+
+ Args:
+ system, renderer_file, argv, in_dir, device: As for ``identity``.
+ out_dir: Where the render's outputs go.
+ **kwargs: ``weights``, ``desc`` and ``code``, as for ``identity``.
+
+ Returns:
+ The identity's digest.
+ """
+ ident = identity(system, renderer_file, argv, in_dir, device, **kwargs)
+ return write(out_dir, ident, argv)
+
+
+def read_all(out_dir: str) -> list:
+ """Returns every receipt in ``out_dir``."""
+ docs = []
+ for path in sorted(glob.glob(os.path.join(out_dir, ".receipt-*.json"))):
+ with open(path, encoding="utf-8") as fh:
+ docs.append(json.load(fh))
+ return docs
+
+
+def main(argv: list) -> int:
+ """Prints the identity this environment would record, and its digests.
+
+ Args:
+ argv: ``receipt.py probe <system> <renderer> --in-dir DIR [options]``,
+ then ``--`` and the renderer's own arguments.
+ """
+ own, rest = argv[1:], []
+ if "--" in own:
+ own, rest = own[:own.index("--")], own[own.index("--") + 1:]
+ ap = argparse.ArgumentParser(prog="receipt.py")
+ ap.add_argument("command", choices=("probe",))
+ ap.add_argument("system")
+ ap.add_argument("renderer")
+ ap.add_argument("--in-dir", required=True)
+ ap.add_argument("--device", default="cpu")
+ ap.add_argument("--weights", nargs="*", default=())
+ a = ap.parse_args(own)
+ ident = identity(a.system, a.renderer, [a.renderer] + rest, a.in_dir,
+ a.device, tuple(a.weights))
+ print(
+ json.dumps(
+ {
+ "identity": ident,
+ "digest": digest(ident),
+ "environment_digest": environment_digest(ident)
+ },
+ sort_keys=True))
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv))
diff --git a/bench/wrappers/runclearvoice.py b/bench/wrappers/runclearvoice.py
new file mode 100644
index 0000000..b56192d
--- /dev/null
+++ b/bench/wrappers/runclearvoice.py
@@ -0,0 +1,81 @@
+"""ClearerVoice-Studio MossFormer2_SE_48K: 48 kHz speech enhancement.
+
+Release: github.com/modelscope/ClearerVoice-Studio (the ``clearvoice``
+package, Apache-2.0) with the checkpoint alibabasglab/MossFormer2_SE_48K
+(Hugging Face, the revision setupfield.sh pins), read from
+<BENCH_SRC>/clearvoice/checkpoints. MossFormer2 (gated single-head transformer
+with convolutional recurrence) estimates a mask on a 48 kHz STFT; inputs over
+20 s are decoded in 4 s windows, as the release's configuration sets.
+
+Run through the package's own API, with three things set around it: the
+checkpoint must be present before the model is built (the package would
+otherwise download it, or run with random weights when that fails, warning
+only); the hub is offline; and the filterbank dither the package draws from
+torch's global generator is seeded per file (crc32 of its name), so a render
+is reproducible without changing the computation's distribution.
+
+Usage: <BENCH_VENVS>/clearvoice_venv/bin/python runclearvoice.py --in-dir IN
+ --out-dir OUT [--limit N] [--shard i/k] [--device cuda:0]
+"""
+import argparse
+import os
+import sys
+import zlib
+
+import numpy as np
+import torch
+
+import receipt # the render's provenance, beside this file
+import writer # the shared render loop, beside this file
+
+SRC = os.path.join(receipt.SRC, "clearvoice")
+MODEL = "MossFormer2_SE_48K"
+SR = 48000
+
+
+def load(device: str) -> writer.Enhance:
+ """Returns ``enhance(path, samples, rate)`` running the release."""
+ if device != "cuda:0":
+ raise ValueError("the package computes on the first visible GPU; "
+ "choose it with CUDA_VISIBLE_DEVICES")
+ checkpoints = os.path.join(SRC, "checkpoints", MODEL)
+ for name in ("last_best_checkpoint", "last_best_checkpoint.pt"):
+ if not os.path.isfile(os.path.join(checkpoints, name)):
+ raise FileNotFoundError(f"{checkpoints}/{name} is missing: run "
+ "setupfield.sh clearvoice")
+ os.environ["HF_HUB_OFFLINE"] = "1" # before the package imports the hub
+ os.chdir(SRC) # the package reads ./checkpoints/<model>
+ # pylint: disable=import-outside-toplevel
+ from clearvoice import ClearVoice, networks
+ # the package picks the physical GPU with the most free memory and fails
+ # under CUDA_VISIBLE_DEVICES; the harness assigns GPUs through that
+ networks.SpeechModel.get_free_gpu = lambda self: 0
+ model = ClearVoice(task="speech_enhancement", model_names=[MODEL])
+
+ def enhance(path, samples, rate): # pylint: disable=unused-argument
+ torch.manual_seed(zlib.crc32(os.path.basename(path).encode()))
+ out = model(input_path=os.path.abspath(path), online_write=False)
+ return np.asarray(out, dtype=np.float32).reshape(-1), SR
+
+ return enhance
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--in-dir", required=True)
+ ap.add_argument("--out-dir", required=True)
+ ap.add_argument("--limit", type=int, default=None)
+ ap.add_argument("--shard", default="")
+ ap.add_argument("--device", default="cuda:0")
+ args = ap.parse_args()
+ in_dir = os.path.abspath(args.in_dir)
+ out_dir = os.path.abspath(args.out_dir)
+ receipt.begin("clearvoice_mf2_48k", __file__, out_dir, sys.argv, in_dir,
+ args.device)
+ files = writer.inputs(in_dir, args.shard, args.limit)
+ enhance = load(args.device)
+ return writer.render(files, out_dir, enhance, expect_rate=SR)
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/bench/wrappers/rundfn3.py b/bench/wrappers/rundfn3.py
new file mode 100644
index 0000000..6e076f7
--- /dev/null
+++ b/bench/wrappers/rundfn3.py
@@ -0,0 +1,69 @@
+"""DeepFilterNet3: 48 kHz real-time speech enhancement by deep filtering.
+
+Paper: Schröter et al., "DeepFilterNet: Perceptually Motivated Real-Time Speech
+Enhancement" (Interspeech 2023). Code MIT or Apache-2.0
+(github.com/Rikorose/DeepFilterNet, the ``deepfilternet`` package), model from
+the release's ``models/DeepFilterNet3.zip`` at the tag setupfield.sh pins,
+unpacked into <BENCH_SRC>/deepfilternet. Per-bin complex filters across
+neighbouring frames, two frames of look-ahead.
+
+Run through the package's ``init_df`` and ``enhance`` with the model folder
+given explicitly (the package would otherwise download the zip from the
+project's main branch into a user cache) and no log file written into it.
+
+Usage: <BENCH_VENVS>/dfn3_venv/bin/python rundfn3.py --in-dir IN --out-dir OUT
+ [--limit N] [--shard i/k] [--device cuda:0]
+"""
+import argparse
+import os
+import sys
+
+import torch
+
+import receipt # the render's provenance, beside this file
+import writer # the shared render loop, beside this file
+
+MODEL_DIR = os.path.join(receipt.SRC, "deepfilternet", "DeepFilterNet3")
+SR = 48000
+
+
+def load(device: str) -> writer.Enhance:
+ """Returns ``enhance(path, samples, rate)`` running the release."""
+ if not os.path.isdir(os.path.join(MODEL_DIR, "checkpoints")):
+ raise FileNotFoundError(
+ f"{MODEL_DIR} is missing: run setupfield.sh dfn3")
+ # pylint: disable=import-outside-toplevel
+ from df.enhance import enhance as df_enhance
+ from df.enhance import init_df
+ from df.utils import get_device
+ model, state, _ = init_df(model_base_dir=MODEL_DIR, log_file=None)
+ # the package computes on the first visible GPU whenever there is one
+ if get_device() != torch.device(device):
+ raise ValueError(
+ f"the package computes on {get_device()}, not {device}: "
+ "choose the GPU with CUDA_VISIBLE_DEVICES")
+
+ def enhance(path, samples, rate): # pylint: disable=unused-argument
+ out = df_enhance(model, state, torch.from_numpy(samples).unsqueeze(0))
+ return out.squeeze(0).cpu().numpy(), rate
+
+ return enhance
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--in-dir", required=True)
+ ap.add_argument("--out-dir", required=True)
+ ap.add_argument("--limit", type=int, default=None)
+ ap.add_argument("--shard", default="")
+ ap.add_argument("--device", default="cuda:0")
+ args = ap.parse_args()
+ receipt.begin("dfn3", __file__, args.out_dir, sys.argv, args.in_dir,
+ args.device)
+ files = writer.inputs(args.in_dir, args.shard, args.limit)
+ enhance = load(args.device)
+ return writer.render(files, args.out_dir, enhance, expect_rate=SR)
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/bench/wrappers/runfastenhancer.py b/bench/wrappers/runfastenhancer.py
new file mode 100644
index 0000000..906323f
--- /dev/null
+++ b/bench/wrappers/runfastenhancer.py
@@ -0,0 +1,97 @@
+"""FastEnhancer-L at 48 kHz: a streaming enhancer, driven frame by frame.
+
+Paper: arXiv 2509.21867. Code MIT (github.com/aask1357/fastenhancer); the
+model is the release's own ONNX export, ``fastenhancer_l.onnx`` of the GitHub
+release onnx-48khz-v1, fetched and hash-checked by setupfield.sh into
+<BENCH_SRC>/fastenhancer_onnx. The export consumes 200-sample frames (its hop)
+with a 1024-sample window and carries its recurrent state as explicit inputs
+and outputs: the speed-optimised streaming corner of the design space.
+
+Each file runs the way the release's test script does: padded on the right by
+one window, fed frame by frame until the padding has passed (which flushes the
+state, so the last window of speech is emitted), and read from N_FFT - HOP
+samples in, which removes the algorithmic delay; the state starts fresh for
+every file. onnxruntime on the CPU; its default thread pool spins more than it
+computes on a large machine, so two intra-op threads run several times faster,
+and shards of one folder run side by side for throughput.
+
+Usage: <BENCH_VENVS>/fastenhancer_venv/bin/python runfastenhancer.py
+ --in-dir IN --out-dir OUT [--limit N] [--shard i/k] [--threads 2]
+"""
+import argparse
+import os
+import sys
+
+import numpy as np
+
+import receipt # the render's provenance, beside this file
+import writer # the shared render loop, beside this file
+
+ONNX = os.path.join(receipt.SRC, "fastenhancer_onnx", "fastenhancer_l.onnx")
+SR = 48000
+HOP = 200 # the export's frame, which its input shape carries
+N_FFT = 1024 # the 48 kHz models' window; the delay is N_FFT - HOP
+
+
+def stream(session, x: np.ndarray) -> np.ndarray:
+ """Runs one file through the streaming export, state fresh, delay removed.
+
+ Returns:
+ Exactly ``len(x)`` samples.
+ """
+ inputs = session.get_inputs()
+ names = [i.name for i in inputs]
+ outputs = [o.name for o in session.get_outputs()]
+ caches = [np.zeros(i.shape, dtype=np.float32) for i in inputs[1:]]
+ padded = np.pad(x.astype(np.float32), (0, N_FFT))
+ chunks = []
+ for start in range(0, len(x) + N_FFT - HOP, HOP):
+ frame = padded[start:start + HOP]
+ frame = np.pad(frame, (0, HOP - len(frame)))
+ feeds = {names[0]: frame.reshape(1, HOP)}
+ feeds.update(zip(names[1:], caches))
+ result = session.run(outputs, feeds)
+ chunks.append(result[0].reshape(-1))
+ caches = [np.asarray(c, dtype=np.float32) for c in result[1:]]
+ y = np.concatenate(chunks)[N_FFT - HOP:N_FFT - HOP + len(x)]
+ return np.pad(y, (0, len(x) - len(y)))
+
+
+def load(threads: int) -> writer.Enhance:
+ """Returns ``enhance(path, samples, rate)`` running the export."""
+ import onnxruntime # pylint: disable=import-outside-toplevel
+ options = onnxruntime.SessionOptions()
+ options.intra_op_num_threads = threads
+ options.inter_op_num_threads = 1
+ session = onnxruntime.InferenceSession(ONNX,
+ options,
+ providers=["CPUExecutionProvider"])
+ frame = session.get_inputs()[0].shape[-1]
+ if frame != HOP:
+ raise ValueError(
+ f"the export consumes {frame}-sample frames, not {HOP}")
+
+ def enhance(path, samples, rate): # pylint: disable=unused-argument
+ return stream(session, samples), rate
+
+ return enhance
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--in-dir", required=True)
+ ap.add_argument("--out-dir", required=True)
+ ap.add_argument("--limit", type=int, default=None)
+ ap.add_argument("--shard", default="")
+ ap.add_argument("--threads", type=int, default=2)
+ ap.add_argument("--device", default="cpu", choices=("cpu",))
+ args = ap.parse_args()
+ receipt.begin("fastenhancer_l_48k", __file__, args.out_dir, sys.argv,
+ args.in_dir, args.device)
+ files = writer.inputs(args.in_dir, args.shard, args.limit)
+ enhance = load(args.threads)
+ return writer.render(files, args.out_dir, enhance, expect_rate=SR)
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/bench/wrappers/rungapurgenet.py b/bench/wrappers/rungapurgenet.py
new file mode 100644
index 0000000..d256a44
--- /dev/null
+++ b/bench/wrappers/rungapurgenet.py
@@ -0,0 +1,56 @@
+"""GAP-URGENet: first in the objective evaluation of URGENT 2026, Track 1.
+
+Paper: Rong, Wang, Wang, Lu, ICASSP 2026. Two parallel 16 kHz branches, a
+generative one (DeWavLM-Omni features to a neural vocoder, the UniPASE
+paradigm) and a predictive spectral one, fused by a post-net that generates
+the band up to 24 kHz before resampling to the input rate; content above
+8 kHz in the input does not reach the output. Code MIT
+(github.com/Xiaobin-Rong/gap-urgenet), checkpoints Apache-2.0
+(Xiaobin-Rong/gap-urgenet on Hugging Face, the revision setupfield.sh pins).
+
+``pase.render`` runs the release's own inference modules as its README
+prescribes (whole files up to 20 s, segmented beyond), checkpoints passed by
+path, writes made float32. The release scales every output to the input's
+peak (renormalizes=true), and its packet-loss concealment, on by default,
+fills runs of exact digital zeros.
+
+Usage: <BENCH_VENVS>/gap_urgenet_venv/bin/python rungapurgenet.py --in-dir IN
+ --out-dir OUT [--limit N] [--shard i/k] [--device cuda:0]
+"""
+import argparse
+import os
+import sys
+
+import pase # the PASE family's release runner, beside this file
+import receipt # the render's provenance, beside this file
+import writer # the shared render loop, beside this file
+
+REPO = os.path.join(receipt.SRC, "gap-urgenet")
+CHECKPOINTS = {
+ "--dewavlm_ckpt": "DeWavLM-Omni.pt",
+ "--adapter_ckpt": "Adapter.pt",
+ "--vocoder_ckpt": "Vocoder.pt",
+ "--predictor_ckpt": "Predictor.pt",
+ "--postnet_ckpt": "PostNet.pt",
+}
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--in-dir", required=True)
+ ap.add_argument("--out-dir", required=True)
+ ap.add_argument("--limit", type=int, default=None)
+ ap.add_argument("--shard", default="")
+ ap.add_argument("--device", default="cuda:0")
+ args = ap.parse_args()
+ receipt.begin("gap_urgenet", __file__, args.out_dir, sys.argv, args.in_dir,
+ args.device)
+ files = writer.inputs(args.in_dir, args.shard, args.limit)
+ checkpoints = {
+ k: os.path.join(REPO, "ckpts", v) for k, v in CHECKPOINTS.items()
+ }
+ return pase.render(REPO, files, args.out_dir, args.device, checkpoints)
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/bench/wrappers/runresembledn.py b/bench/wrappers/runresembledn.py
new file mode 100644
index 0000000..573bfa4
--- /dev/null
+++ b/bench/wrappers/runresembledn.py
@@ -0,0 +1,86 @@
+"""resemble-enhance, the denoiser stage alone (the release's --denoise_only).
+
+Release: github.com/resemble-ai/resemble-enhance (the ``resemble_enhance``
+package, MIT) with the weights of the Hugging Face repository
+ResembleAI/resemble-enhance at the revision setupfield.sh pins, cloned into
+<BENCH_SRC>/resemble-enhance. The denoiser predicts a mask at 44.1 kHz; the
+package resamples the input to that rate, processes inputs over 29 s in 30 s
+chunks, and returns 44.1 kHz audio, which is resampled back to the input rate
+with the package's own resampler settings. An input whose length leaves a final
+chunk under a second is padded with silence to a one-second remainder first
+(the package's padding crashes on such a chunk) and trimmed afterwards.
+
+Run through the package's ``denoise`` with the weights folder given explicitly:
+called without one, the package clones or pulls the repository's main branch
+into its own install on every start.
+
+Usage: <BENCH_VENVS>/resemble_venv/bin/python runresembledn.py --in-dir IN
+ --out-dir OUT [--limit N] [--shard i/k] [--device cuda:0]
+"""
+import argparse
+import os
+import pathlib
+import sys
+
+import torch
+import torchaudio
+
+import receipt # the render's provenance, beside this file
+import writer # the shared render loop, beside this file
+
+RUN_DIR = os.path.join(receipt.SRC, "resemble-enhance", "enhancer_stage2")
+
+
+def load(device: str) -> writer.Enhance:
+ """Returns ``enhance(path, samples, rate)`` running the release."""
+ if not os.path.isfile(os.path.join(RUN_DIR, "hparams.yaml")):
+ raise FileNotFoundError(
+ f"{RUN_DIR} is missing: run setupfield.sh resemble")
+ # pylint: disable=import-outside-toplevel
+ from resemble_enhance.enhancer.inference import denoise
+ run_dir = pathlib.Path(RUN_DIR)
+
+ def enhance(path, samples, rate): # pylint: disable=unused-argument
+ # The package cuts the input into 30 s chunks every 29 s and crashes
+ # on a final chunk shorter than its own padding; an input whose length
+ # leaves a remainder under a second gets silence appended to make the
+ # remainder one second, and the output is trimmed to the input again.
+ hop = 29 * rate
+ remainder = samples.shape[-1] % hop
+ pad = rate - remainder if 0 < remainder < rate else 0
+ x = torch.from_numpy(samples)
+ if pad:
+ x = torch.nn.functional.pad(x, (0, pad))
+ out, out_rate = denoise(x, rate, device, run_dir=run_dir)
+ out = out.cpu().float()
+ if out_rate != rate:
+ out = torchaudio.functional.resample(
+ out,
+ orig_freq=out_rate,
+ new_freq=rate,
+ lowpass_filter_width=64,
+ rolloff=0.9475937167399596,
+ resampling_method="sinc_interp_kaiser",
+ beta=14.769656459379492)
+ return out[:samples.shape[-1]].numpy(), rate
+
+ return enhance
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--in-dir", required=True)
+ ap.add_argument("--out-dir", required=True)
+ ap.add_argument("--limit", type=int, default=None)
+ ap.add_argument("--shard", default="")
+ ap.add_argument("--device", default="cuda:0")
+ args = ap.parse_args()
+ receipt.begin("resemble_dn", __file__, args.out_dir, sys.argv, args.in_dir,
+ args.device)
+ files = writer.inputs(args.in_dir, args.shard, args.limit)
+ enhance = load(args.device)
+ return writer.render(files, args.out_dir, enhance)
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/bench/wrappers/runreusenemotron.py b/bench/wrappers/runreusenemotron.py
new file mode 100644
index 0000000..f99c782
--- /dev/null
+++ b/bench/wrappers/runreusenemotron.py
@@ -0,0 +1,60 @@
+"""NVIDIA NemotronLabs RE-USE: universal speech enhancement at any input rate.
+
+The 2026-10 release of RE-USE (USEMamba, 9.6M): new weights, the same code.
+Paper: "Rethinking Training Targets, Architectures and Data Quality for
+Universal Speech Enhancement" (arXiv 2603.02641, 2026). Licence: OpenMDW-1.1
+(code and weights). Release: the Hugging Face repository
+nvidia/NVIDIA-NemotronLabs-RE-USE, fetched as is into
+<BENCH_SRC>/reuse_nemotron at the revision setupfield.sh pins; code, recipe
+and weights load from there.
+
+Its STFT is defined at an 8 kHz base (window 320, hop 40) and every window
+scales with the input rate, so at 48 kHz it runs a 1920/240 STFT over the full
+band. ``semamba.enhancer`` follows the release's inference.py. Whole files,
+as the release prescribes; its chunked script is for inputs that do not fit
+in GPU memory (a 45 s item needs about 25 GiB).
+
+Usage: <BENCH_VENVS>/reuse_venv/bin/python runreusenemotron.py
+ --in-dir IN --out-dir OUT [--limit N] [--shard i/k] [--device cuda:0]
+"""
+import argparse
+import importlib
+import os
+import sys
+
+import receipt # the render's provenance, beside this file
+import semamba # the SEMamba family's release runner, beside this file
+import writer # the shared render loop, beside this file
+
+SRC = os.path.join(receipt.SRC, "reuse_nemotron")
+RECIPE = ("USEMamba_30x1_lr_00002_norm_05_vq_065_nfft_320_hop_40_NRIR_012_"
+ "pha_0005_com_04_early_001.yaml")
+SR = 48000
+
+
+def load(device: str) -> writer.Enhance:
+ """Returns ``enhance(path, samples, rate)`` running the release."""
+ util, stfts = semamba.bind(SRC)
+ generator = importlib.import_module("models.generator_SEMamba_time_d4")
+ cfg = util.load_config(os.path.join(SRC, "recipes", RECIPE))
+ model = generator.SEMamba.from_pretrained(SRC, cfg=cfg).to(device).eval()
+ return semamba.enhancer(model, util, stfts, cfg, device)
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--in-dir", required=True)
+ ap.add_argument("--out-dir", required=True)
+ ap.add_argument("--limit", type=int, default=None)
+ ap.add_argument("--shard", default="")
+ ap.add_argument("--device", default="cuda:0")
+ args = ap.parse_args()
+ receipt.begin("reuse_nemotron", __file__, args.out_dir, sys.argv,
+ args.in_dir, args.device)
+ files = writer.inputs(args.in_dir, args.shard, args.limit)
+ enhance = load(args.device)
+ return writer.render(files, args.out_dir, enhance, expect_rate=SR)
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/bench/wrappers/runreusenemotronlaughter.py b/bench/wrappers/runreusenemotronlaughter.py
new file mode 100644
index 0000000..d3bfa6a
--- /dev/null
+++ b/bench/wrappers/runreusenemotronlaughter.py
@@ -0,0 +1,61 @@
+"""NVIDIA NemotronLabs RE-USE-laughter: RE-USE trained to keep laughter.
+
+The 2026-10 release of RE-USE (USEMamba, 9.6M) that better preserves
+laughter: new weights, the same code.
+Paper: "Rethinking Training Targets, Architectures and Data Quality for
+Universal Speech Enhancement" (arXiv 2603.02641, 2026). Licence: OpenMDW-1.1
+(code and weights). Release: the Hugging Face repository
+nvidia/NVIDIA-NemotronLabs-RE-USE-laughter, fetched as is into
+<BENCH_SRC>/reuse_nemotron_laughter at the revision setupfield.sh pins;
+code, recipe and weights load from there.
+
+Its STFT is defined at an 8 kHz base (window 320, hop 40) and every window
+scales with the input rate, so at 48 kHz it runs a 1920/240 STFT over the full
+band. ``semamba.enhancer`` follows the release's inference.py. Whole files,
+as the release prescribes; its chunked script is for inputs that do not fit
+in GPU memory (a 45 s item needs about 25 GiB).
+
+Usage: <BENCH_VENVS>/reuse_venv/bin/python runreusenemotronlaughter.py
+ --in-dir IN --out-dir OUT [--limit N] [--shard i/k] [--device cuda:0]
+"""
+import argparse
+import importlib
+import os
+import sys
+
+import receipt # the render's provenance, beside this file
+import semamba # the SEMamba family's release runner, beside this file
+import writer # the shared render loop, beside this file
+
+SRC = os.path.join(receipt.SRC, "reuse_nemotron_laughter")
+RECIPE = ("USEMamba_30x1_lr_00002_norm_05_vq_065_nfft_320_hop_40_NRIR_012_"
+ "pha_0005_com_04_early_001.yaml")
+SR = 48000
+
+
+def load(device: str) -> writer.Enhance:
+ """Returns ``enhance(path, samples, rate)`` running the release."""
+ util, stfts = semamba.bind(SRC)
+ generator = importlib.import_module("models.generator_SEMamba_time_d4")
+ cfg = util.load_config(os.path.join(SRC, "recipes", RECIPE))
+ model = generator.SEMamba.from_pretrained(SRC, cfg=cfg).to(device).eval()
+ return semamba.enhancer(model, util, stfts, cfg, device)
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--in-dir", required=True)
+ ap.add_argument("--out-dir", required=True)
+ ap.add_argument("--limit", type=int, default=None)
+ ap.add_argument("--shard", default="")
+ ap.add_argument("--device", default="cuda:0")
+ args = ap.parse_args()
+ receipt.begin("reuse_nemotron_laughter", __file__, args.out_dir, sys.argv,
+ args.in_dir, args.device)
+ files = writer.inputs(args.in_dir, args.shard, args.limit)
+ enhance = load(args.device)
+ return writer.render(files, args.out_dir, enhance, expect_rate=SR)
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/bench/wrappers/runsmule.py b/bench/wrappers/runsmule.py
new file mode 100644
index 0000000..92665a7
--- /dev/null
+++ b/bench/wrappers/runsmule.py
@@ -0,0 +1,85 @@
+"""Smule Renaissance Small: 48 kHz complex-STFT vocal restoration.
+
+Release: github.com/smulelabs/smule-renaissance (MIT) at the commit
+setupfield.sh pins, weights smulelabs/Smule-Renaissance-Small (Hugging Face,
+MIT, the pinned revision) in <BENCH_SRC>/smule-renaissance. 10.4M parameters.
+
+Runs the way the release's main.py does: a 60 Hz high-pass, the input scaled
+to unit peak, the model on a 4096/2048 STFT (half precision under autocast on
+a GPU, full precision on the CPU), the inverse STFT, the peak scaling undone.
+The release's inverse STFT takes no target length, so its output ends up to
+2047 samples (43 ms) short; the remainder is filled with zeros.
+
+Usage: <BENCH_VENVS>/smule_venv/bin/python runsmule.py --in-dir IN
+ --out-dir OUT [--limit N] [--shard i/k] [--device cuda:0]
+"""
+import argparse
+import os
+import sys
+
+import torch
+import torchaudio
+
+import receipt # the render's provenance, beside this file
+import writer # the shared render loop, beside this file
+
+REPO = os.path.join(receipt.SRC, "smule-renaissance")
+CHECKPOINT = os.path.join(REPO, "smule-renaissance-small.pt")
+SR = 48000
+N_FFT, HOP = 4096, 2048
+HIGHPASS_HZ = 60.0
+
+
+def load(device: str) -> writer.Enhance:
+ """Returns ``enhance(path, samples, rate)`` running the release."""
+ sys.path.insert(0, REPO)
+ # pylint: disable=import-outside-toplevel
+ from model import Renaissance # the release's own modules
+ from spectral_ops import STFT, iSTFT
+ dev = torch.device(device)
+ dtype = torch.float16 if dev.type == "cuda" else torch.float32
+ model = Renaissance().to(dev).to(dtype)
+ model.load_state_dict(
+ torch.load(CHECKPOINT, map_location=dev, weights_only=True))
+ model.eval()
+ stft = STFT(n_fft=N_FFT, hop_length=HOP, win_length=N_FFT)
+ istft = iSTFT(n_fft=N_FFT, hop_length=HOP, win_length=N_FFT)
+
+ def enhance(path, samples, rate): # pylint: disable=unused-argument
+ wav = torch.from_numpy(samples).unsqueeze(0)
+ wav = torchaudio.functional.highpass_biquad(wav,
+ SR,
+ cutoff_freq=HIGHPASS_HZ)
+ wav = wav.to(dev).to(dtype)
+ peak = torch.max(torch.abs(wav))
+ if peak > 0:
+ wav = wav / peak
+ with torch.no_grad():
+ spec = stft(wav)
+ with torch.autocast(device_type="cuda", enabled=dev.type == "cuda"):
+ spec = model(spec)
+ out = istft(spec)
+ if peak > 0:
+ out = out * peak
+ return out.squeeze(0).float().cpu().numpy(), rate
+
+ return enhance
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--in-dir", required=True)
+ ap.add_argument("--out-dir", required=True)
+ ap.add_argument("--limit", type=int, default=None)
+ ap.add_argument("--shard", default="")
+ ap.add_argument("--device", default="cuda:0")
+ args = ap.parse_args()
+ receipt.begin("smule", __file__, args.out_dir, sys.argv, args.in_dir,
+ args.device)
+ files = writer.inputs(args.in_dir, args.shard, args.limit)
+ enhance = load(args.device)
+ return writer.render(files, args.out_dir, enhance, expect_rate=SR)
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/bench/wrappers/rununipase.py b/bench/wrappers/rununipase.py
new file mode 100644
index 0000000..6ea3c34
--- /dev/null
+++ b/bench/wrappers/rununipase.py
@@ -0,0 +1,55 @@
+"""UniPASE: the PASE family's universal speech enhancer at 48 kHz output.
+
+Paper: Rong, Wang, Wang, Gao, Lu, IEEE TASLP 2026 (arXiv 2604.14606), the
+generative branch of GAP-URGENet: DeWavLM-Omni phonetic representations, an
+adapter, a 16 kHz neural vocoder and a post-net that generates the band up to
+24 kHz before resampling to the input rate; content above 8 kHz in the input
+does not reach the output. Code MIT (github.com/Xiaobin-Rong/unipase),
+checkpoints Apache-2.0 (Xiaobin-Rong/unipase on Hugging Face, the revision
+setupfield.sh pins).
+
+``pase.render`` runs the release's own inference modules as its README
+prescribes (whole files up to 20 s, segmented beyond), checkpoints passed by
+path, writes made float32. The release scales every output to the input's
+peak (renormalizes=true), and its packet-loss concealment, on by default,
+fills runs of exact digital zeros.
+
+Usage: <BENCH_VENVS>/unipase_venv/bin/python rununipase.py --in-dir IN
+ --out-dir OUT [--limit N] [--shard i/k] [--device cuda:0]
+"""
+import argparse
+import os
+import sys
+
+import pase # the PASE family's release runner, beside this file
+import receipt # the render's provenance, beside this file
+import writer # the shared render loop, beside this file
+
+REPO = os.path.join(receipt.SRC, "unipase")
+CHECKPOINTS = {
+ "--dewavlm_ckpt": "DeWavLM-Omni.pt",
+ "--adapter_ckpt": "Adapter.pt",
+ "--vocoder_ckpt": "Vocoder_DWO-L1.pt",
+ "--postnet_ckpt": "PostNet.pt",
+}
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--in-dir", required=True)
+ ap.add_argument("--out-dir", required=True)
+ ap.add_argument("--limit", type=int, default=None)
+ ap.add_argument("--shard", default="")
+ ap.add_argument("--device", default="cuda:0")
+ args = ap.parse_args()
+ receipt.begin("unipase", __file__, args.out_dir, sys.argv, args.in_dir,
+ args.device)
+ files = writer.inputs(args.in_dir, args.shard, args.limit)
+ checkpoints = {
+ k: os.path.join(REPO, "ckpts", v) for k, v in CHECKPOINTS.items()
+ }
+ return pase.render(REPO, files, args.out_dir, args.device, checkpoints)
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/bench/wrappers/runurgent26bsrnn.py b/bench/wrappers/runurgent26bsrnn.py
new file mode 100644
index 0000000..1766f53
--- /dev/null
+++ b/bench/wrappers/runurgent26bsrnn.py
@@ -0,0 +1,86 @@
+"""URGENT 2026 Track-1 baseline, discriminative: BSRNN complex masking.
+
+Release: github.com/urgent-challenge/urgent2026_challenge_track1 (Apache-2.0)
+at the commit setupfield.sh pins, checkpoint ``bsrnn.ckpt`` from the
+organisers' Hugging Face repository lichenda/icassp_2026_urgent_baseline at
+the pinned revision, in <BENCH_SRC>/urgent26. Sampling-frequency independent:
+an adaptive STFT (espnet STFTEncoder, default_fs 48000) runs at the input's
+own rate, so 48 kHz input is processed over the full band.
+
+Follows the release's baseline_code/inference.py: SEModel.load_from_checkpoint,
+then model.se_model(wav, length, sr), then the script's peak normalisation to
+0.9, kept on purpose: trained with a scale-invariant loss, the model returns
+audio at a scale of its own (about 17 dB above the input on this set, peaks
+past full scale), so that step is how the shipped baseline sets its level
+(renormalizes=true). The FlowSE baseline, whose model keeps the input's scale,
+leaves the step out.
+
+Usage: <BENCH_VENVS>/urgent26_venv/bin/python runurgent26bsrnn.py --in-dir IN
+ --out-dir OUT [--limit N] [--shard i/k] [--device cuda:0]
+ [--native-rate]
+"""
+import argparse
+import os
+import sys
+
+import soxr
+import torch
+
+import receipt # the render's provenance, beside this file
+import writer # the shared render loop, beside this file
+
+REPO = os.path.join(receipt.SRC, "urgent26")
+CHECKPOINT = os.path.join(REPO, "ckpts", "bsrnn.ckpt")
+SR = 48000
+
+
+def load(device: str, native_rate: bool) -> writer.Enhance:
+ """Returns ``enhance(path, samples, rate)`` running the release."""
+ # torch >= 2.6 loads checkpoints with weights_only=True and refuses the
+ # config class the organisers' checkpoints pickle; the switch, read when
+ # torch.load is called, lets the release load them as it was built to
+ os.environ["TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD"] = "1"
+ sys.path.insert(0, REPO)
+ # pylint: disable-next=import-outside-toplevel
+ from baseline_code.d_model import SEModel
+ dev = torch.device(device)
+ model = SEModel.load_from_checkpoint(CHECKPOINT, map_location=str(dev))
+ model.eval()
+ model.to(dev)
+
+ def enhance(path, samples, rate): # pylint: disable=unused-argument
+ wav = torch.from_numpy(samples).to(dev).view(1, -1)
+ length = torch.tensor([wav.shape[-1]], device=dev)
+ with torch.no_grad():
+ out, _ = model.se_model(wav, length, rate)
+ out = out / out.abs().max().clamp(min=1e-8) * 0.9
+ out = out.cpu().numpy().reshape(-1)
+ out_rate = rate if native_rate else SR
+ if out_rate != rate:
+ out = soxr.resample(out, rate, out_rate)
+ return out, out_rate
+
+ return enhance
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--in-dir", required=True)
+ ap.add_argument("--out-dir", required=True)
+ ap.add_argument("--limit", type=int, default=None)
+ ap.add_argument("--shard", default="")
+ ap.add_argument("--device", default="cuda:0")
+ ap.add_argument("--native-rate",
+ action="store_true",
+ help="write each output at its input's rate (the URGENT "
+ "view) instead of 48 kHz")
+ args = ap.parse_args()
+ receipt.begin("urgent26_bsrnn", __file__, args.out_dir, sys.argv,
+ args.in_dir, args.device)
+ files = writer.inputs(args.in_dir, args.shard, args.limit)
+ enhance = load(args.device, args.native_rate)
+ return writer.render(files, args.out_dir, enhance)
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/bench/wrappers/runurgent26bsrnnflow.py b/bench/wrappers/runurgent26bsrnnflow.py
new file mode 100644
index 0000000..3faafc9
--- /dev/null
+++ b/bench/wrappers/runurgent26bsrnnflow.py
@@ -0,0 +1,100 @@
+"""URGENT 2026 Track-1 baseline, generative: flow matching on a BSRNN backbone.
+
+Release: github.com/urgent-challenge/urgent2026_challenge_track1 (Apache-2.0)
+at the commit setupfield.sh pins, checkpoint ``flow_bsrnn.ckpt`` from the
+organisers' Hugging Face repository lichenda/icassp_2026_urgent_baseline at
+the pinned revision, in <BENCH_SRC>/urgent26. The FlowSE recipe: conditional
+flow matching, an Euler solver with 15 steps, EMA weights. Sampling-frequency
+independent, so 48 kHz input is processed over the full band.
+
+Follows the release's baseline_code/inference.py with three differences:
+FlowSEModel.enhance() hard-codes ``.cuda()``, so the identical sampler call is
+made with the device given; the prior noise is seeded per file (crc32 of its
+name), so a render is reproducible, where the script leaves it unseeded (a
+cut of an item and the item draw different noise); and the script's final peak
+normalisation to 0.9, a convention of the challenge's scale-invariant metrics,
+is left out because the model's output keeps the input's scale
+(renormalizes=false).
+
+Usage: <BENCH_VENVS>/urgent26_venv/bin/python runurgent26bsrnnflow.py
+ --in-dir IN --out-dir OUT [--limit N] [--shard i/k] [--device cuda:0]
+ [--native-rate]
+"""
+import argparse
+import os
+import sys
+import zlib
+
+import soxr
+import torch
+
+import receipt # the render's provenance, beside this file
+import writer # the shared render loop, beside this file
+
+REPO = os.path.join(receipt.SRC, "urgent26")
+CHECKPOINT = os.path.join(REPO, "ckpts", "flow_bsrnn.ckpt")
+SR = 48000
+STEPS = 15 # the release's FlowSEModel.enhance() default
+
+
+def load(device: str, native_rate: bool) -> writer.Enhance:
+ """Returns ``enhance(path, samples, rate)`` running the release."""
+ # torch >= 2.6 loads checkpoints with weights_only=True and refuses the
+ # config class the organisers' checkpoints pickle; the switch, read when
+ # torch.load is called, lets the release load them as it was built to
+ os.environ["TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD"] = "1"
+ sys.path.insert(0, REPO)
+ # pylint: disable=import-outside-toplevel
+ from baseline_code.flow_model import FlowSEModel
+ from baseline_code.sampling import get_white_box_solver
+ dev = torch.device(device)
+ model = FlowSEModel.load_from_checkpoint(CHECKPOINT, map_location=str(dev))
+ # eval() copies the EMA weights over the parameters, as the release does
+ model.eval()
+ model.to(dev)
+
+ def enhance(path, samples, rate):
+ wav = torch.from_numpy(samples).to(dev).view(1, -1)
+ length = torch.tensor([wav.shape[-1]], device=dev)
+ torch.manual_seed(zlib.crc32(os.path.basename(path).encode()))
+ with torch.no_grad():
+ features = model.speech_to_feature(wav, rate, length)
+ sampler = get_white_box_solver("euler",
+ model.ode,
+ model,
+ features,
+ T_rev=model.T_rev,
+ t_eps=model.t_eps,
+ N=STEPS)
+ sample, _ = sampler()
+ out = model.feature_to_speech(sample, rate, length)
+ out = out.cpu().numpy().reshape(-1)
+ out_rate = rate if native_rate else SR
+ if out_rate != rate:
+ out = soxr.resample(out, rate, out_rate)
+ return out, out_rate
+
+ return enhance
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--in-dir", required=True)
+ ap.add_argument("--out-dir", required=True)
+ ap.add_argument("--limit", type=int, default=None)
+ ap.add_argument("--shard", default="")
+ ap.add_argument("--device", default="cuda:0")
+ ap.add_argument("--native-rate",
+ action="store_true",
+ help="write each output at its input's rate (the URGENT "
+ "view) instead of 48 kHz")
+ args = ap.parse_args()
+ receipt.begin("urgent26_bsrnn_flow", __file__, args.out_dir, sys.argv,
+ args.in_dir, args.device)
+ files = writer.inputs(args.in_dir, args.shard, args.limit)
+ enhance = load(args.device, args.native_rate)
+ return writer.render(files, args.out_dir, enhance)
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/bench/wrappers/semamba.py b/bench/wrappers/semamba.py
new file mode 100644
index 0000000..ef3c7f0
--- /dev/null
+++ b/bench/wrappers/semamba.py
@@ -0,0 +1,79 @@
+"""Runs a release of NVIDIA's SEMamba family as its inference script does.
+
+RE-USE and Real-time RE-USE (NSCLv1, research and development only) ship
+their code as plain ``models`` and ``utils`` directories beside the weights,
+define the STFT at an 8 kHz base that scales with the input rate, and
+post-process alike. ``bind`` points the two package names at a release's
+directories (the venv's packages of the same names would otherwise shadow
+them); ``enhancer`` returns the release's processing of one file: the STFT
+sizes scaled to the input rate and made even, magnitude and phase in and out,
+frames whose magnitude is more than half zeros blanked (the releases' guard
+against a sweep artefact), the inverse STFT, the length matched to the input.
+"""
+import importlib
+import os
+import sys
+import types
+
+import torch
+
+import writer # the shared render loop, beside this file
+
+
+def bind(src: str) -> tuple:
+ """Binds ``models`` and ``utils`` to the release under ``src``.
+
+ Returns:
+ The release's ``utils.util`` and ``models.stfts`` modules.
+ """
+ for package in ("models", "utils"):
+ namespace = types.ModuleType(package)
+ namespace.__path__ = [os.path.join(src, package)]
+ sys.modules[package] = namespace
+ return (importlib.import_module("utils.util"),
+ importlib.import_module("models.stfts"))
+
+
+def make_even(value: float) -> int:
+ """Returns ``value`` rounded, then raised to the next even integer."""
+ value = int(round(value))
+ return value if value % 2 == 0 else value + 1
+
+
+def enhancer(model_call, util, stfts, cfg: dict, device: str) -> writer.Enhance:
+ """Returns ``enhance(path, samples, rate)`` for a loaded release.
+
+ Args:
+ model_call: ``(magnitude, phase) -> (amplitude, phase, ...)``.
+ util: The release's ``utils.util``.
+ stfts: The release's ``models.stfts``.
+ cfg: The release's configuration.
+ device: The device the model computes on.
+ """
+ stft = cfg["stft_cfg"]
+ compress = cfg["model_cfg"]["compress_factor"]
+ relu = torch.nn.ReLU()
+
+ def enhance(path, samples, rate): # pylint: disable=unused-argument
+ scale = rate / stft["sampling_rate"]
+ n_fft = make_even(stft["n_fft"] * scale)
+ hop = make_even(stft["hop_size"] * scale)
+ win = make_even(stft["win_size"] * scale)
+ x = torch.from_numpy(samples).unsqueeze(0).to(device)
+ with torch.no_grad():
+ mag, pha, _ = stfts.mag_phase_stft(x,
+ n_fft=n_fft,
+ hop_size=hop,
+ win_size=win,
+ compress_factor=compress,
+ center=True,
+ addeps=False)
+ amp, pha_out, _ = model_call(mag, pha)
+ linear = torch.expm1(relu(amp))
+ mostly_zero = (linear == 0).sum(1) / linear.shape[1] > 0.5
+ amp[:, :, mostly_zero[0]] = 0
+ y = stfts.mag_phase_istft(amp, pha_out, n_fft, hop, win, compress)
+ y = util.pad_or_trim_to_match(x, y, pad_value=1e-8)
+ return y.squeeze(0).float().cpu().numpy(), rate
+
+ return enhance
diff --git a/bench/wrappers/writer.py b/bench/wrappers/writer.py
new file mode 100644
index 0000000..502206b
--- /dev/null
+++ b/bench/wrappers/writer.py
@@ -0,0 +1,126 @@
+"""The loop every wrapper runs: pick its inputs, render each once, write safely.
+
+``inputs`` lists the files one process renders. ``render`` calls an
+``Enhance`` function, ``(path, samples, rate) -> (samples, rate)``, on every
+file not yet rendered, brings each result to the input's duration with
+``fit``, writes it with ``save``, prints progress and ``DONE n/N``, and
+returns the process's exit status: zero only when every file it was given is
+present. ``save`` writes a 32-bit float WAV under a temporary name and renames
+it into place, so an interrupted run leaves nothing a later run would take as
+done; it refuses NaN and inf. ``fit`` absorbs a release's frame rounding, up
+to ``TOLERANCE_SECONDS``, and refuses a larger difference: a cut-off output is
+a failure, not something to pad.
+
+Standard library, NumPy and soundfile only: every system's venv has them.
+"""
+import collections.abc
+import glob
+import os
+import tempfile
+
+import numpy as np
+import soundfile as sf
+
+TOLERANCE_SECONDS = 0.05 # the most a release's framing may change a length
+Enhance = collections.abc.Callable[[str, np.ndarray, int], tuple[np.ndarray,
+ int]]
+
+
+def inputs(in_dir: str, shard: str = "", limit: int | None = None) -> list:
+ """Returns the WAV files of ``in_dir`` one process renders.
+
+ Args:
+ in_dir: The folder of inputs.
+ shard: ``i/k`` to take every k-th file from the i-th, or empty.
+ limit: At most this many files, or None.
+ """
+ files = sorted(glob.glob(os.path.join(in_dir, "*.wav")))
+ if shard:
+ index, count = (int(v) for v in shard.split("/"))
+ if count < 1 or not 0 <= index < count:
+ raise ValueError(f"--shard {shard}: need 0 <= i < k")
+ files = files[index::count]
+ return files[:limit] if limit else files
+
+
+def fit(samples: np.ndarray, n: int, rate: int) -> np.ndarray:
+ """Returns ``samples`` padded or trimmed to exactly ``n``.
+
+ Raises:
+ ValueError: The length is off by more than ``TOLERANCE_SECONDS``.
+ """
+ samples = np.asarray(samples, dtype=np.float32).reshape(-1)
+ if abs(len(samples) - n) > TOLERANCE_SECONDS * rate:
+ raise ValueError(f"the release returned {len(samples)} samples for "
+ f"{n}: a failed or cut-off output")
+ if len(samples) >= n:
+ return samples[:n]
+ return np.pad(samples, (0, n - len(samples)))
+
+
+def save(path: str, samples: np.ndarray, rate: int) -> None:
+ """Writes ``samples`` to ``path`` as a 32-bit float WAV, atomically.
+
+ Raises:
+ ValueError: The samples hold NaN or inf.
+ """
+ samples = np.asarray(samples, dtype=np.float32).reshape(-1)
+ if not np.isfinite(samples).all():
+ raise ValueError("the output holds NaN or inf")
+ fd, tmp = tempfile.mkstemp(dir=os.path.dirname(os.path.abspath(path)),
+ prefix=".partial-",
+ suffix=".wav")
+ os.close(fd)
+ try:
+ sf.write(tmp, samples, rate, subtype="FLOAT", format="WAV")
+ os.replace(tmp, path)
+ finally:
+ if os.path.exists(tmp):
+ os.unlink(tmp)
+
+
+def read(path: str) -> tuple[np.ndarray, int]:
+ """Returns the file's samples as a mono float32 array, and its rate."""
+ samples, rate = sf.read(path, dtype="float32", always_2d=True)
+ return samples.mean(axis=1), rate
+
+
+def render(files: list,
+ out_dir: str,
+ enhance: Enhance,
+ expect_rate: int | None = None) -> int:
+ """Renders every file of ``files`` that ``out_dir`` does not hold yet.
+
+ Args:
+ files: The input files.
+ out_dir: Where the outputs go, under the inputs' names.
+ enhance: ``(path, samples, rate) -> (samples, rate)``, one file.
+ expect_rate: The only input rate accepted, or None for any.
+
+ Returns:
+ 0 when every file is present at the end, 1 otherwise.
+ """
+ os.makedirs(out_dir, exist_ok=True)
+ done = 0
+ for count, path in enumerate(files, 1):
+ name = os.path.basename(path)
+ target = os.path.join(out_dir, name)
+ if os.path.exists(target):
+ done += 1
+ continue
+ try:
+ samples, rate = read(path)
+ if expect_rate and rate != expect_rate:
+ raise ValueError(f"input rate {rate}, expected {expect_rate}")
+ out, out_rate = enhance(path, samples, rate)
+ n = int(round(len(samples) * out_rate / rate))
+ save(target, fit(out, n, out_rate), out_rate)
+ done += 1
+ except Exception as e: # pylint: disable=broad-exception-caught
+ # one file's failure is reported and the rest continue: the
+ # exit status and stamprender's inventory check catch it
+ print(f"FAIL {name} {e}", flush=True)
+ if count % 25 == 0:
+ print(f" {count}/{len(files)}", flush=True)
+ print(f"DONE {done}/{len(files)}", flush=True)
+ return 0 if done == len(files) else 1
diff --git a/demo/README.md b/demo/README.md
new file mode 100644
index 0000000..65bb168
--- /dev/null
+++ b/demo/README.md
@@ -0,0 +1,71 @@
+# Voice Isolator demo
+
+Two tabs share one page, with both models loaded before the demo opens:
+
+- **Offline:** upload a file, choose a sample or record a clip, then isolate its
+ voice and background. Each output has a player, spectrogram and download.
+- **Online:** start the microphone and watch input and isolated-voice waveforms
+ and spectrograms update as you speak. Each take lasts up to 60 seconds.
+ **Pause & listen** stops capture and plays the completed clean recording;
+ **Stop** finishes it without playback. Below the panel, the microphone input
+ as recorded and the voice isolated from it play side by side, sample-aligned,
+ each with a download. Start a new recording for another take.
+ Playing audio on either tab pauses capture first to avoid recording playback.
+
+The header names the device inference runs on: CPU, Metal GPU (Apple
+silicon) or CUDA GPU. The speed readouts on both tabs repeat it.
+
+The offline background is the aligned 48 kHz mono input minus the isolated
+voice. It can contain voice leakage. Downloads save the players' 16-bit WAVs
+without normalizing their level; peaks above full scale are clipped. The CLI
+writes float32 voice/background WAVs when those peaks need to be preserved.
+
+## Run locally
+
+From a repository checkout:
+
+```bash
+pip install -e ".[demo]" # includes Gradio 6.31.0
+python demo/app.py
+```
+
+Open `http://127.0.0.1:7860`. Microphone access requires localhost or HTTPS.
+The default models download from `inworld/voice-isolator` on first use.
+Offline uses `voice-isolator-v1`; Online uses `voice-isolator-v1-realtime`
+with 20 ms of look-ahead. Each tab keeps its own model loaded in its fixed mode
+and names it: they are different models, so the same audio gives slightly
+different results on the two tabs.
+
+To use local checkpoints:
+
+```bash
+python demo/app.py --offline-model offline.safetensors --online-model realtime.safetensors
+```
+
+These options also accept registry names and `hf://` locations. Each checkpoint
+must support its tab's mode. `--device` and `--precision` apply to both models.
+Live operation needs a device that processes audio faster than it arrives.
+If the device or connection falls behind, capture pauses at roughly four
+seconds of pending audio and finishes the recording. Startup runs half a second
+of silence through both models, so the first take does not wait for the GPU to
+compile its kernels.
+
+Limits, for a demo shared with a few people:
+
+- The Offline tab takes up to 10 minutes of audio per input and uploads up to
+ 300 MB.
+- At most two live takes run at once; a third is asked to try again shortly.
+ Closing or reloading a tab releases its take at once.
+- On an Apple GPU both models share the device, which runs one task at a time.
+ While an Offline isolation runs, a new live take is refused and a take in
+ progress waits; a take kept waiting more than about 45 seconds stops.
+See the [model card](../MODEL_CARD.md) for model details.
+
+- `--examples ''` hides samples; uploads and recording remain available.
+- `--port 7861` changes the port. The default host is loopback; use
+ `--server-name 0.0.0.0` for access from other machines.
+- `--share` creates a temporary public Gradio URL. `--url-file staging/demo_url.txt`
+ records the local and share URLs; create `staging/` first.
+- `VOICE_ISOLATION_DEMO_AUTH=user:password` enables authentication.
+- `VOICE_ISOLATION_OFFLINE_MODEL` and `VOICE_ISOLATION_ONLINE_MODEL` set the two
+ default checkpoints; `VOICE_ISOLATION_EXAMPLES` sets the samples directory.
diff --git a/demo/app.py b/demo/app.py
new file mode 100644
index 0000000..703c9fc
--- /dev/null
+++ b/demo/app.py
@@ -0,0 +1,716 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Offline files and a live microphone, each using its own loaded model.
+
+ pip install -e ".[demo]"
+ python demo/app.py
+ python demo/app.py --offline-model offline.safetensors \
+ --online-model realtime.safetensors
+"""
+
+import argparse
+from collections import abc
+import dataclasses
+import functools
+import html
+import math
+import os
+import pathlib
+import platform
+import subprocess
+import sys
+import threading
+import time
+
+import gradio as gr
+import numpy as np
+import soundfile as sf
+import torch
+
+import example_audio
+from inworld import voice_isolation
+from inworld.voice_isolation import registry
+import online
+
+ASSETS = pathlib.Path(__file__).resolve().parent / "assets"
+LOGO = ASSETS.parent.parent / "docs" / "assets" / "inworld-logo-black.svg"
+DEFAULT_LOOKAHEAD = 2
+SAMPLE_RATE = 48000
+SPEC_HEIGHT = 220
+# One Offline request holds the model (and on an Apple GPU the live takes)
+# for its whole length: about a quarter of the audio's duration on a GPU.
+MAX_OFFLINE_SECONDS = 600
+MAX_UPLOAD_SIZE = "300mb"
+# Gradio sizes its container to the content, so each tab would set its own
+# width; a fixed width keeps both tabs' edges in place. The Offline outputs
+# form one grid (players in a row, spectrograms in the next) so the three
+# columns line up; narrow screens stack each player above its spectrogram.
+CSS = """
+.show-api-divider { display: none !important; }
+.gradio-container { width: 100% !important; max-width: 1200px !important;
+ margin: 0 auto !important; }
+#studio-tabs { width: 100%; }
+#studio-tabs > div:first-child { margin-bottom: 20px; }
+.demo-header { text-align: center; padding: 20px 0 18px; }
+.demo-header .logo { width: 170px; margin: 0 auto 14px; }
+.demo-header h1 { font-size: 32px; letter-spacing: -1px; margin: 0; }
+.demo-header p { opacity: .65; margin: 8px 0 14px; }
+.device-badges { display: flex; justify-content: center; gap: 8px;
+ flex-wrap: wrap; }
+.device-badge { display: inline-flex; align-items: center; gap: 2px 8px;
+ flex-wrap: wrap; justify-content: center;
+ padding: 5px 14px; border-radius: 999px; font-size: 13px;
+ border: 1px solid var(--border-color-primary);
+ background: var(--background-fill-secondary); }
+.device-badge > span { white-space: nowrap; }
+.device-badge strong { font-weight: 600; }
+.device-dot { width: 8px; height: 8px; border-radius: 50%; flex: none; }
+.device-gpu .device-dot { background: #22c55e; box-shadow: 0 0 0 4px #22c55e26; }
+.device-metal .device-dot { background: #38bdf8; box-shadow: 0 0 0 4px #38bdf826; }
+.device-cpu .device-dot { background: #f59e0b; box-shadow: 0 0 0 4px #f59e0b26; }
+.device-detail { opacity: .7; }
+/* Gradio nests an HTML component's own CSS inside one rule, which drops
+ @keyframes there; the live panel's status dot animates with this one. */
+@keyframes breathe { 50% { box-shadow: 0 0 0 8px #75f1c508; } }
+#offline-grid { display: grid !important; gap: 16px;
+ grid-template-columns: repeat(3, minmax(0, 1fr));
+ grid-template-rows: auto auto; grid-auto-flow: column;
+ align-items: stretch !important; }
+#offline-grid > .column { display: contents !important; }
+#offline-grid .spectrogram .image-frame { width: 100% !important; }
+#offline-grid .spectrogram .icon-button-wrapper { display: none !important; }
+#offline-grid .spectrogram img { width: 100% !important; height: 100% !important;
+ object-fit: fill !important; border-radius: 6px; }
+#offline-run { min-height: 48px; }
+#live-studio { padding: 0 !important; border: 0 !important;
+ background: none !important; box-shadow: none !important; }
+#live-studio > .html-container { padding: 0 !important; }
+#online-results { margin-top: 16px; gap: 16px; }
+@media (max-width: 860px) {
+ #offline-grid { grid-template-columns: minmax(0, 1fr);
+ grid-template-rows: none; grid-auto-flow: row; }
+ #offline-run { position: sticky; bottom: 12px; z-index: 5; }
+}
+"""
+
+
+class DemoModels:
+ """Separate, fixed-mode models reused for all requests.
+
+ Each model's calls hold its lock. PyTorch's Apple GPU backend cannot run
+ work from two threads at once (an offline isolation during a live take
+ aborts the process), so two models on that GPU share one lock; an offline
+ isolation then holds live takes until it ends.
+ """
+
+ offline: voice_isolation.VoiceIsolator
+ realtime: voice_isolation.VoiceIsolator
+ offline_lock: threading.RLock = dataclasses.field(
+ default_factory=threading.RLock)
+ realtime_lock: threading.RLock = dataclasses.field(
+ default_factory=threading.RLock)
+ offline_name: str = registry.MODE_MODELS["offline"]
+ realtime_name: str = registry.MODE_MODELS["streaming"]
+
+ def __post_init__(self):
+ if self.offline.device.type == self.realtime.device.type == "mps":
+ self.realtime_lock = self.offline_lock
+
+
+def model_name(spec: str, mode: str) -> str:
+ """Names a checkpoint as the tabs show it.
+
+ The Hub repository and registry names give the release name (the mode
+ picks the repository's checkpoint); any other checkpoint shows its file
+ name.
+ """
+ if spec == registry.REPO_ID:
+ return registry.MODE_MODELS[mode]
+ if spec in registry.MODELS or spec in registry.PINNED:
+ return spec
+ if spec.startswith(registry.HF_SCHEME):
+ return registry.parse_hf(spec)[1]
+ return pathlib.Path(spec).name
+
+
+def load_models(offline_model: str = registry.REPO_ID,
+ online_model: str = registry.REPO_ID,
+ device: str | None = None,
+ precision: str = "auto") -> DemoModels:
+ """Loads both checkpoints once; an incompatible checkpoint fails startup."""
+ offline = voice_isolation.VoiceIsolator.load(offline_model,
+ device=device,
+ mode="offline",
+ precision=precision)
+ realtime = voice_isolation.VoiceIsolator.load(online_model,
+ device=device,
+ mode="streaming",
+ precision=precision,
+ lookahead_frames=2,
+ block_frames=4)
+ if offline.mode != "offline" or realtime.mode != "streaming":
+ raise ValueError("The demo needs an offline and a realtime checkpoint.")
+ if offline.model is realtime.model:
+ raise ValueError("Each tab needs a separate model instance.")
+ return DemoModels(offline,
+ realtime,
+ offline_name=model_name(offline_model, "offline"),
+ realtime_name=model_name(online_model, "streaming"))
+
+
+def warm_up(models: DemoModels) -> None:
+ """Runs half a second of silence through both models before serving.
+
+ A GPU compiles its kernels on first use: on Apple's GPU the first live
+ push takes seconds, long enough for the browser to end the first take as
+ falling behind. Short windows make the warm-up stream cross several
+ crossfades, so the two-lane path is compiled too.
+ """
+ silence = np.zeros(SAMPLE_RATE // 2, dtype=np.float32)
+ with models.offline_lock:
+ models.offline.isolate(silence, SAMPLE_RATE)
+ with models.realtime_lock:
+ stream = models.realtime.stream(window_frames=8, crossfade_frames=4)
+ stream.push(silence)
+ stream.flush()
+
+
[email protected]_cache(maxsize=1)
+def processor_name() -> str:
+ """The processor's name where the system reports one, else its type.
+
+ Read once: on macOS it runs ``sysctl``.
+ """
+ name = ""
+ try:
+ if sys.platform == "darwin":
+ name = subprocess.run(["sysctl", "-n", "machdep.cpu.brand_string"],
+ capture_output=True,
+ text=True,
+ timeout=2,
+ check=True).stdout.strip()
+ elif sys.platform.startswith("linux"):
+ with open("/proc/cpuinfo", encoding="utf-8") as cpuinfo:
+ name = next((line.split(":", 1)[1].strip()
+ for line in cpuinfo
+ if line.startswith("model name")), "")
+ else:
+ name = platform.processor()
+ except (OSError, subprocess.SubprocessError):
+ name = ""
+ return name or platform.machine() or "unknown processor"
+
+
[email protected](frozen=True)
+class DeviceInfo:
+ """Where inference runs, as the header and speed readouts show it.
+
+ ``kind`` is "gpu" (CUDA), "metal" (Apple's GPU) or "cpu"; ``name`` is
+ the short label, for example "Metal GPU"; ``detail`` names the hardware.
+ """
+
+ kind: str
+ name: str
+ detail: str
+
+
+def describe_device(device: torch.device | str) -> DeviceInfo:
+ """Describes an inference device for people rather than for PyTorch."""
+ device = torch.device(device)
+ if device.type == "cuda":
+ return DeviceInfo("gpu", "CUDA GPU", torch.cuda.get_device_name(device))
+ if device.type == "mps":
+ return DeviceInfo("metal", "Metal GPU", processor_name())
+ if device.type == "cpu":
+ threads = torch.get_num_threads()
+ return DeviceInfo(
+ "cpu", "CPU",
+ f"{processor_name()} · {threads} thread{'s' * (threads != 1)}")
+ return DeviceInfo("gpu", device.type.upper(), str(device))
+
+
+def device_badges_html(models: DemoModels) -> str:
+ """One badge naming the device both models run on, or one per model."""
+ devices = [("", describe_device(models.offline.device))]
+ realtime = describe_device(models.realtime.device)
+ if realtime != devices[0][1]:
+ devices = [("Offline: ", devices[0][1]), ("Online: ", realtime)]
+ badges = []
+ for prefix, info in devices:
+ badges.append(
+ f'<span class="device-badge device-{html.escape(info.kind)}"'
+ f' title="Inference device: {html.escape(info.name)},'
+ f' {html.escape(info.detail)}">'
+ '<span class="device-dot"></span>'
+ f"<span>{html.escape(prefix)}Running on"
+ f" <strong>{html.escape(info.name)}</strong></span>"
+ f'<span class="device-detail">· {html.escape(info.detail)}</span>'
+ "</span>")
+ return f'<div class="device-badges">{"".join(badges)}</div>'
+
+
+def header_html(models: DemoModels | None = None) -> str:
+ """Returns the shared header: logo, title and where inference runs."""
+ logo = ""
+ if LOGO.exists():
+ svg = LOGO.read_text(encoding="utf-8").replace(
+ "<svg ", '<svg fill="currentColor" ', 1)
+ logo = f'<div class="logo">{svg}</div>'
+ badges = device_badges_html(models) if models is not None else ""
+ return (f'<div class="demo-header">{logo}<h1>Voice Isolator</h1>'
+ "<p>Your voice, with the background removed.</p>"
+ f"{badges}</div>")
+
+
+def mono_float(audio):
+ """Converts browser PCM to finite mono without normalizing its level."""
+ rate, x = audio
+ x = np.asarray(x)
+ if x.dtype.kind in "iu":
+ maximum = np.iinfo(x.dtype).max
+ x = x.astype(np.float32) / maximum
+ x = x.astype(np.float32)
+ if x.ndim == 2:
+ x = x.mean(axis=1)
+ if x.ndim != 1 or not np.isfinite(x).all() or x.size == 0:
+ raise gr.Error("Please provide a non-empty audio recording.")
+ return rate, x
+
+
+def needs_soxr(rate: int) -> bool:
+ """Whether the library's resampler would need a huge kernel for ``rate``.
+
+ Its kernel is sized by the reduced ratio of the two rates: small for the
+ usual rates, gigabytes for one that shares few factors with 48 kHz
+ (44101 Hz, 7993 Hz).
+ """
+ return SAMPLE_RATE // math.gcd(int(rate), SAMPLE_RATE) > 1000
+
+
+def _soxr_48k(x: np.ndarray, rate: int) -> np.ndarray:
+ # pylint: disable-next=import-outside-toplevel
+ import soxr # in the demo extra, beside Gradio
+
+ return soxr.resample(x, rate, SAMPLE_RATE).astype(np.float32)
+
+
+def to_48k(x: np.ndarray, rate: int) -> np.ndarray:
+ """Resamples mono float32 audio to 48 kHz as the library does.
+
+ Rates for which ``needs_soxr`` go through soxr instead.
+ """
+ x = np.asarray(x, dtype=np.float32)
+ if rate == SAMPLE_RATE:
+ return x
+ if needs_soxr(rate):
+ return _soxr_48k(x, rate)
+ return voice_isolation.resample(torch.from_numpy(x), rate,
+ SAMPLE_RATE).numpy()
+
+
+def spectrogram_png(wav, sr=SAMPLE_RATE):
+ """Builds a bounded 0-24 kHz spectrogram image without plotting figures.
+
+ Audio at another rate is resampled to 48 kHz first (soxr: fast enough
+ for a preview of any length), so every panel shares one frequency axis.
+ """
+ wav = np.asarray(wav, dtype=np.float32)
+ if sr != SAMPLE_RATE:
+ wav = _soxr_48k(wav, sr)
+ size = 1024
+ wav = np.pad(wav, (0, max(0, size - len(wav))))
+ # At most 640 columns, regardless of the uploaded recording's duration.
+ starts = np.linspace(0,
+ len(wav) - size,
+ min(640, max(1,
+ len(wav) // 256)),
+ dtype=int)
+ frames = wav[starts[:, None] + np.arange(size)] * np.hanning(size)
+ amplitude = np.abs(np.fft.rfft(frames, axis=1)) / (size / 2)
+ db = 20 * np.log10(np.maximum(amplitude, 1e-5))
+ values = np.clip((db + 100) / 100, 0, 1)
+ palette = np.array([[7, 13, 27], [44, 34, 99], [121, 53, 137],
+ [225, 98, 107], [255, 210, 125]])
+ index = np.minimum((values * 4).astype(int), 3)
+ fraction = (values * 4 - index)[..., None]
+ rgb = palette[index] * (1 - fraction) + palette[index + 1] * fraction
+ return np.flip(rgb.transpose(1, 0, 2), axis=0).astype(np.uint8)
+
+
+def pcm16(wav) -> np.ndarray:
+ """Returns a preview at the original level, clipping above full scale."""
+ return np.round(np.clip(wav, -1, 1) * 32767).astype(np.int16)
+
+
+def load_input(audio) -> tuple[int, np.ndarray]:
+ """Decodes the Offline input to mono float32 at its own rate and level.
+
+ ``audio`` is a file path, as the input delivers uploads, samples and
+ recordings, or a (rate, samples) pair. libsndfile reads WAV (float and
+ extensible headers included), FLAC, OGG and MP3 without converting them;
+ other formats go through Gradio's decoder. Inputs longer than
+ ``MAX_OFFLINE_SECONDS`` are refused before decoding where the header
+ says how long they are.
+ """
+ if audio is None:
+ raise gr.Error(
+ "Upload a file, pick a sample or record some audio first.")
+ if isinstance(audio, (str, os.PathLike)):
+ try:
+ info = sf.info(audio)
+ _check_duration(info.frames / info.samplerate)
+ data, rate = sf.read(audio, dtype="float32", always_2d=True)
+ except sf.LibsndfileError:
+ try:
+ rate, data = gr.processing_utils.audio_from_file(str(audio))
+ except Exception as error: # pylint: disable=broad-exception-caught
+ # Gradio's decoder raises whatever its backends raise.
+ raise gr.Error(
+ "This audio format could not be read.") from error
+ audio = (rate, data)
+ rate, x = mono_float(audio)
+ _check_duration(x.size / rate)
+ return rate, x
+
+
+def _check_duration(seconds: float) -> None:
+ if seconds > MAX_OFFLINE_SECONDS:
+ raise gr.Error(
+ f"The Offline tab takes up to {MAX_OFFLINE_SECONDS // 60}"
+ " minutes of audio; this input is longer.")
+
+
+class LatestRequests:
+ """The latest Offline request of each browser.
+
+ Gradio's cancellation cannot stop a request whose thread already runs:
+ an isolation superseded by a newer one from the same browser should give
+ way when it gets the model, instead of running anyway.
+ """
+
+ def __init__(self) -> None:
+ self._lock = threading.Lock()
+ self._latest = {}
+
+ def begin(self, request: gr.Request | None) -> abc.Callable[[], bool]:
+ """Records a new request; returns whether it has been superseded."""
+ browser = getattr(request, "session_hash", None)
+ with self._lock:
+ token = self._latest.get(browser, 0) + 1
+ self._latest[browser] = token
+ return lambda: self._latest.get(browser) != token
+
+ def forget(self, request: gr.Request | None = None) -> None:
+ """Drops a closed browser's entry."""
+ with self._lock:
+ self._latest.pop(getattr(request, "session_hash", None), None)
+
+
+def run_offline(audio,
+ models: DemoModels,
+ superseded: abc.Callable[[], bool] | None = None):
+ """Isolates a recording once and derives its aligned background residual.
+
+ A request ``superseded`` by the time the model is free returns no change.
+ """
+ rate, x = load_input(audio)
+ if rate != SAMPLE_RATE and needs_soxr(rate):
+ x, rate = to_48k(x, rate), SAMPLE_RATE
+ start = time.perf_counter()
+ with models.offline_lock:
+ if superseded is not None and superseded():
+ return (gr.skip(),) * 5
+ voice = models.offline.isolate(x, rate, output_sample_rate=48000)
+ aligned = to_48k(x, rate)
+ if voice.shape != aligned.shape:
+ raise gr.Error(
+ "The isolated voice and input must have the same length.")
+ background = aligned - voice
+ seconds = len(voice) / 48000
+ elapsed = time.perf_counter() - start
+ device = describe_device(models.offline.device).name
+ return ((48000, pcm16(voice)), spectrogram_png(voice, 48000),
+ (48000, pcm16(background)), spectrogram_png(background, 48000),
+ f"{seconds:.1f} s processed in {elapsed:.2f} s · "
+ f"{seconds / max(elapsed, 1e-6):.1f}× real time on {device}")
+
+
+def input_changed(audio):
+ """Clears the previous outputs when the input changes.
+
+ An input that cannot be isolated still clears them, with a warning.
+ """
+ image = None
+ if audio is not None:
+ try:
+ rate, x = load_input(audio)
+ image = spectrogram_png(x, rate)
+ except gr.Error as error:
+ gr.Warning(error.message)
+ return image, None, None, None, None, ""
+
+
+def _auth(spec):
+ """'user:password' -> (user, password); None when empty."""
+ if not spec:
+ return None
+ user, sep, password = spec.partition(":")
+ if not sep or not user or not password:
+ raise SystemExit(
+ "--auth / VOICE_ISOLATION_DEMO_AUTH must be 'user:password'.")
+ return (user, password)
+
+
+def build_demo(models: DemoModels,
+ examples: example_audio.Examples | None = None) -> gr.Blocks:
+ """Builds offline file isolation and a stateful live microphone tab."""
+ realtime_device = describe_device(models.realtime.device)
+ controller = online.Online(models.realtime, models.realtime_lock,
+ realtime_device.name)
+ latest = LatestRequests()
+
+ def isolate_offline(audio, request: gr.Request):
+ return run_offline(audio, models, superseded=latest.begin(request))
+
+ with gr.Blocks(title="Inworld Voice Isolator",
+ analytics_enabled=False,
+ delete_cache=(600, 3600)) as demo:
+ gr.HTML(header_html(models))
+ with gr.Tabs(elem_id="studio-tabs"):
+ with gr.Tab("Offline", id="offline"):
+ gr.Markdown(
+ "Upload or record audio, then isolate the voice and"
+ f" background. Model: `{models.offline_name}`, the"
+ " offline model. It reads each window of audio whole,"
+ " before and after every moment, for the best quality."
+ " The Online tab runs a different model.")
+ # The file as uploaded, unconverted: load_input decodes it.
+ inp = gr.Audio(sources=["upload", "microphone"],
+ type="filepath",
+ format=None,
+ label="Input",
+ render=False,
+ elem_id="offline-input")
+ if examples and examples.rows:
+ with gr.Column(variant="panel"):
+ gr.Markdown("### Samples")
+ picker = gr.Examples(examples=examples.rows,
+ inputs=inp,
+ label=None,
+ example_labels=examples.labels,
+ examples_per_page=max(
+ 10, len(examples.rows)))
+ picker.dataset.show_label = False
+ with gr.Row(elem_id="offline-grid"):
+ with gr.Column():
+ inp.render()
+ spec_in = gr.Image(label="Input spectrogram",
+ show_label=False,
+ height=SPEC_HEIGHT,
+ buttons=[],
+ interactive=False,
+ elem_classes=["spectrogram"])
+ with gr.Column():
+ out = gr.Audio(label="Isolated voice",
+ interactive=False,
+ format="wav",
+ buttons=["download"],
+ elem_id="offline-voice")
+ spec_out = gr.Image(label="Voice spectrogram",
+ show_label=False,
+ height=SPEC_HEIGHT,
+ buttons=[],
+ interactive=False,
+ elem_classes=["spectrogram"])
+ with gr.Column():
+ background = gr.Audio(label="Background",
+ interactive=False,
+ format="wav",
+ buttons=["download"],
+ elem_id="offline-background")
+ spec_background = gr.Image(
+ label="Background spectrogram",
+ show_label=False,
+ height=SPEC_HEIGHT,
+ buttons=[],
+ interactive=False,
+ elem_classes=["spectrogram"])
+ btn = gr.Button("Isolate voice & background",
+ variant="primary",
+ elem_id="offline-run")
+ info = gr.Markdown("")
+ outputs = [out, spec_out, background, spec_background, info]
+ isolation = btn.click(isolate_offline,
+ inputs=inp,
+ outputs=outputs,
+ concurrency_id="offline-model",
+ concurrency_limit=1,
+ api_name="isolate_offline")
+ # A new input cancels this browser's isolation in flight, so
+ # its stale result cannot land after the outputs were
+ # cleared; the preview itself never waits for the model.
+ inp.change(input_changed,
+ inputs=inp,
+ outputs=[spec_in, *outputs],
+ cancels=[isolation],
+ concurrency_id="offline-preview",
+ concurrency_limit=4,
+ api_name=False)
+ with gr.Tab("Online", id="online"):
+ lookahead_ms = round(models.realtime.lookahead_frames *
+ models.realtime.frame_seconds * 1000)
+ intro = (
+ "Watch the clean voice update as you speak. Model:"
+ f" `{models.realtime_name}`, a separate model trained for"
+ " live audio. It hears what came before and"
+ f" {lookahead_ms} ms ahead, so on the same audio its"
+ " result differs from the Offline tab's. Pause to listen"
+ " without echo. Each take lasts up to 60 seconds.")
+ if realtime_device.kind == "cpu":
+ intro += (" This demo runs on the CPU, which is usually"
+ " slower than live audio: capture then pauses"
+ " early and the take finishes.")
+ gr.Markdown(intro)
+ state = gr.State(None,
+ time_to_live=120,
+ delete_callback=online.close_recording)
+ studio = gr.HTML(
+ value={},
+ html_template=(ASSETS /
+ "online.html").read_text(encoding="utf-8"),
+ css_template=(ASSETS /
+ "online.css").read_text(encoding="utf-8"),
+ js_on_load=(ASSETS /
+ "online.js").read_text(encoding="utf-8"),
+ elem_id="live-studio")
+ # Below the panel's two cards, in the same order: what the
+ # microphone heard, then the voice isolated from it.
+ with gr.Row(elem_id="online-results", equal_height=True):
+ original = gr.Audio(label="Microphone input",
+ interactive=False,
+ format="wav",
+ buttons=["download"],
+ elem_id="online-input")
+ player = gr.Audio(label="Isolated voice",
+ interactive=False,
+ format="wav",
+ buttons=["download"],
+ elem_id="online-result")
+ # Outside the queue, so a live take never waits behind
+ # Offline jobs; the model's lock alone orders device work.
+ studio.record_start(controller.start,
+ inputs=state,
+ outputs=[state, studio, player, original],
+ api_name=False,
+ queue=False,
+ show_progress="hidden")
+ studio.audio_chunk(controller.push,
+ trigger_mode="multiple",
+ inputs=state,
+ outputs=[state, studio],
+ api_name=False,
+ queue=False,
+ show_progress="hidden")
+ studio.record_finish(controller.finish,
+ inputs=state,
+ outputs=[state, studio, player, original],
+ api_name=False,
+ queue=False,
+ show_progress="hidden")
+ demo.unload(controller.release)
+ demo.unload(latest.forget)
+ # Gradio copies each sample into its cache once, here, and keeps
+ # serving that copy; the hourly cache sweep must not delete it.
+ inp.keep_in_cache.update(set().union(*demo.temp_file_sets))
+ return demo
+
+
+def main():
+ """Loads both models before accepting any offline or online requests."""
+ ap = argparse.ArgumentParser(description=__doc__)
+ ap.add_argument("--offline-model",
+ default=os.environ.get("VOICE_ISOLATION_OFFLINE_MODEL",
+ registry.REPO_ID))
+ ap.add_argument("--online-model",
+ default=os.environ.get("VOICE_ISOLATION_ONLINE_MODEL",
+ registry.REPO_ID))
+ ap.add_argument("--device", default=None)
+ ap.add_argument("--precision",
+ default="auto",
+ choices=("auto", "fp32", "fp16", "bf16"))
+ ap.add_argument("--share", action="store_true")
+ ap.add_argument("--port", type=int, default=7860)
+ ap.add_argument("--server-name", default="127.0.0.1")
+ ap.add_argument("--url-file", default="")
+ ap.add_argument("--examples",
+ default=os.environ.get(
+ "VOICE_ISOLATION_EXAMPLES",
+ str(example_audio.DEFAULT_DIRECTORY)))
+ ap.add_argument("--auth",
+ default=os.environ.get("VOICE_ISOLATION_DEMO_AUTH", ""))
+ args = ap.parse_args()
+ auth = _auth(args.auth)
+ examples = None
+ if args.examples:
+ directory = pathlib.Path(args.examples).resolve()
+ caches = (gr.utils.get_upload_folder(), gr.utils.get_cache_folder())
+ if any(
+ directory.is_relative_to(pathlib.Path(cache).resolve())
+ for cache in caches):
+ ap.error("Example audio must be outside Gradio's upload "
+ "and examples cache directories.")
+ try:
+ examples = example_audio.load_examples(directory)
+ except ValueError as error:
+ ap.error(str(error))
+ if "OMP_NUM_THREADS" not in os.environ:
+ torch.set_num_threads(min(torch.get_num_threads(), 4))
+ print("Loading offline and realtime models…", flush=True)
+ models = load_models(args.offline_model, args.online_model, args.device,
+ args.precision)
+ warm_up(models)
+ offline_device = describe_device(models.offline.device)
+ realtime_device = describe_device(models.realtime.device)
+ print(
+ f"Offline ready on {offline_device.name} ({offline_device.detail}); "
+ f"online ready on {realtime_device.name} ({realtime_device.detail}).",
+ flush=True)
+ demo = build_demo(models, examples)
+ _, local_url, share_url = demo.launch(
+ share=args.share,
+ server_name=args.server_name,
+ server_port=args.port,
+ auth=auth,
+ prevent_thread_lock=True,
+ allowed_paths=[row[0] for row in examples.rows] if examples else [],
+ footer_links=["gradio", "settings"],
+ max_file_size=MAX_UPLOAD_SIZE,
+ css=CSS,
+ # The Soft theme's colours with the default theme's typeface.
+ theme=gr.themes.Soft(primary_hue="emerald",
+ neutral_hue="slate",
+ font=(gr.themes.LocalFont("Source Sans Pro"),
+ "ui-sans-serif", "system-ui", "sans-serif")))
+ lines = [f"local: {local_url}"
+ ] + ([f"share: {share_url}"] if share_url else [])
+ print("\n".join(lines), flush=True)
+ if args.url_file:
+ pathlib.Path(args.url_file).write_text("\n".join(lines) + "\n",
+ encoding="utf-8")
+ demo.block_thread()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/demo/assets/online.css b/demo/assets/online.css
new file mode 100644
index 0000000..285461d
--- /dev/null
+++ b/demo/assets/online.css
@@ -0,0 +1,175 @@
+.live-studio {
+ --ink: #eef2ff;
+ --muted: #9aa6c0;
+ --mint: #75f1c5;
+ color: var(--ink);
+ background: linear-gradient(135deg, #131c31, #101625 65%, #142b2c);
+ border: 1px solid #2b3850;
+ border-radius: 22px;
+ padding: 26px;
+ box-shadow: 0 14px 50px #00000018;
+}
+.studio-bar {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 20px;
+}
+.studio-bar strong {
+ font-size: 20px;
+ letter-spacing: -0.4px;
+}
+.studio-bar p {
+ color: var(--muted);
+ margin: 7px 0 0;
+ font-size: 14px;
+}
+.status-dot {
+ display: inline-block;
+ width: 9px;
+ height: 9px;
+ border-radius: 50%;
+ background: #75839a;
+ margin-right: 10px;
+}
+.live-studio[data-capturing="true"] .status-dot {
+ background: var(--mint);
+ box-shadow: 0 0 0 5px #75f1c520;
+ animation: breathe 1.6s infinite;
+}
+.live-clock {
+ font-size: 27px;
+ font-variant-numeric: tabular-nums;
+ letter-spacing: -1px;
+ white-space: nowrap;
+}
+.live-clock span {
+ font-size: 13px;
+ color: var(--muted);
+ letter-spacing: 0;
+}
+.studio-controls {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ flex-wrap: wrap;
+ margin: 24px 0;
+}
+.studio-controls button {
+ border: 1px solid #3c4b65;
+ border-radius: 10px;
+ background: #202d43;
+ padding: 11px 16px;
+ color: var(--ink);
+ font-weight: 600;
+ cursor: pointer;
+ transition:
+ background 0.15s,
+ transform 0.15s;
+}
+.studio-controls button:hover:enabled {
+ background: #2e3e58;
+ transform: translateY(-1px);
+}
+.studio-controls button:focus-visible {
+ outline: 2px solid var(--mint);
+ outline-offset: 3px;
+}
+.studio-controls button:disabled {
+ opacity: 0.4;
+ cursor: default;
+}
+.studio-controls .record-button {
+ background: var(--mint);
+ color: #102722;
+ border-color: var(--mint);
+}
+.studio-controls .record-button:hover:enabled {
+ background: #a4fbdc;
+}
+.echo-note {
+ color: var(--muted);
+ font-size: 12px;
+ margin-left: auto;
+}
+.signal-grid {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 18px;
+}
+.signal-card {
+ background: #090f1d99;
+ border: 1px solid #293650;
+ border-radius: 14px;
+ overflow: hidden;
+ padding: 15px;
+}
+.output-signal {
+ border-color: #75f1c542;
+}
+.signal-heading {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ margin-bottom: 12px;
+}
+.signal-heading strong {
+ font-size: 15px;
+}
+.signal-heading span {
+ color: var(--muted);
+ font-size: 11px;
+ text-transform: uppercase;
+ letter-spacing: 1px;
+}
+.signal-card canvas {
+ display: block;
+ width: 100%;
+ height: 94px;
+ border-radius: 6px;
+}
+.signal-card canvas[data-spec] {
+ height: 170px;
+ margin-top: 10px;
+ background: #080e1c;
+}
+.studio-caption {
+ display: flex;
+ justify-content: space-between;
+ gap: 10px;
+ color: var(--muted);
+ font-size: 11px;
+ margin-top: 12px;
+}
+.studio-error {
+ color: #ffb3ac;
+ margin: 8px 0 0;
+ font-size: 13px;
+}
+@media (max-width: 700px) {
+ .live-studio {
+ padding: 18px;
+ }
+ .signal-grid {
+ grid-template-columns: 1fr;
+ }
+ .echo-note {
+ width: 100%;
+ margin: 5px 0 0;
+ }
+ .studio-bar strong {
+ font-size: 17px;
+ }
+ .live-clock {
+ font-size: 22px;
+ }
+}
+
+/* Gradio assigns text colors directly to semantic elements. */
+.live-studio strong,
+.live-studio .live-clock {
+ color: var(--ink);
+}
+.live-studio .studio-caption span {
+ color: var(--muted);
+}
diff --git a/demo/assets/online.html b/demo/assets/online.html
new file mode 100644
index 0000000..e6bc4b1
--- /dev/null
+++ b/demo/assets/online.html
@@ -0,0 +1,39 @@
+<section class="live-studio" aria-label="Live voice isolation">
+ <div class="studio-bar">
+ <div>
+ <span class="status-dot"></span
+ ><strong data-status>Ready to record</strong>
+ <p data-detail>Speak naturally. Watch your voice emerge in real time.</p>
+ </div>
+ <div class="live-clock" data-clock>00:00<span> / 01:00</span></div>
+ </div>
+ <div class="studio-controls">
+ <button class="record-button" data-action="record">
+ ● Start recording
+ </button>
+ <button data-action="listen" disabled>▶ Pause & listen</button>
+ <button data-action="stop" disabled>■ Stop</button>
+ <span class="echo-note">Your microphone pauses while you listen.</span>
+ </div>
+ <div class="signal-grid">
+ <div class="signal-card input-signal">
+ <div class="signal-heading">
+ <strong>What you hear</strong><span>Microphone</span>
+ </div>
+ <canvas data-wave="input" aria-label="Input waveform"></canvas
+ ><canvas data-spec="input" aria-label="Input spectrogram"></canvas>
+ </div>
+ <div class="signal-card output-signal">
+ <div class="signal-heading">
+ <strong>Your voice</strong><span>Live isolation</span>
+ </div>
+ <canvas data-wave="output" aria-label="Clean voice waveform"></canvas
+ ><canvas data-spec="output" aria-label="Clean voice spectrogram"></canvas>
+ </div>
+ </div>
+ <div class="studio-caption">
+ <span>Last 6 seconds · frequency 0–24 kHz</span
+ ><span data-speed>Waiting for audio</span>
+ </div>
+ <p class="studio-error" role="alert" data-error></p>
+</section>
diff --git a/demo/assets/online.js b/demo/assets/online.js
new file mode 100644
index 0000000..15c57b2
--- /dev/null
+++ b/demo/assets/online.js
@@ -0,0 +1,621 @@
+// Copyright 2026 Inworld AI — Apache-2.0
+const state = {
+ take: null,
+ sequence: 0,
+ queue: [],
+ flight: false,
+ capturing: false,
+ stopping: false,
+ finishing: false,
+ flushing: false,
+ starting: false,
+ listen: false,
+ context: null,
+ stream: null,
+ node: null,
+ source: null,
+ gain: null,
+ timer: null,
+ samples: 0,
+ error: "",
+ audioSeconds: 0,
+ generation: 0,
+ disposed: false,
+ device: "",
+ rate: 0,
+};
+const $ = (selector) => element.querySelector(selector);
+// Gradio may mount the app, and WaveSurfer its native players, in open shadows.
+const appRoot = element.getRootNode();
+const mediaPlayers = new Set(),
+ mediaRoots = new Set(),
+ playedEvents = new WeakSet();
+let observer = null,
+ discoveryTimer = null;
+const panel = () => $(".live-studio");
+const current = (generation) =>
+ !state.disposed && element.isConnected && generation === state.generation;
+function discoverPlayers() {
+ const pending = [document],
+ roots = new Set(),
+ players = new Set();
+ if (appRoot !== document) pending.push(appRoot);
+ // Bound traversal work even when this demo is embedded in a larger page.
+ let remaining = 10000;
+ while (pending.length && remaining > 0 && roots.size < 128) {
+ const root = pending.pop();
+ if (roots.has(root)) continue;
+ roots.add(root);
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT);
+ let node;
+ while (remaining > 0 && (node = walker.nextNode())) {
+ remaining -= 1;
+ if (node instanceof HTMLMediaElement) players.add(node);
+ if (node.shadowRoot) pending.push(node.shadowRoot);
+ }
+ }
+ observer?.disconnect();
+ for (const player of mediaPlayers)
+ if (!players.has(player)) player.removeEventListener("play", onPlay, true);
+ for (const root of mediaRoots)
+ if (!roots.has(root)) root.removeEventListener("play", onPlay, true);
+ for (const player of players)
+ if (!mediaPlayers.has(player))
+ player.addEventListener("play", onPlay, true);
+ for (const root of roots) {
+ if (!mediaRoots.has(root)) root.addEventListener("play", onPlay, true);
+ observer?.observe(root, { childList: true, subtree: true });
+ }
+ mediaPlayers.clear();
+ players.forEach((player) => mediaPlayers.add(player));
+ mediaRoots.clear();
+ roots.forEach((root) => mediaRoots.add(root));
+ return players;
+}
+function insidePlayer(player, id) {
+ for (
+ let node = player, depth = 0;
+ node && depth < 64;
+ node = node.parentNode || node.host, depth++
+ ) {
+ if (node.id === id) return true;
+ }
+ return false;
+}
+function forgetPlayers() {
+ clearTimeout(discoveryTimer);
+ discoveryTimer = null;
+ observer?.disconnect();
+ mediaPlayers.forEach((player) =>
+ player.removeEventListener("play", onPlay, true),
+ );
+ mediaRoots.forEach((root) => root.removeEventListener("play", onPlay, true));
+ mediaPlayers.clear();
+ mediaRoots.clear();
+}
+const pausePlayers = () => discoverPlayers().forEach((audio) => audio.pause());
+const status = (title, detail) => {
+ if ($("[data-status]")) $("[data-status]").textContent = title;
+ if (detail && $("[data-detail]")) $("[data-detail]").textContent = detail;
+};
+function controls() {
+ if (!panel()) return;
+ panel().dataset.capturing = String(state.capturing);
+ $("[data-action=record]").disabled =
+ state.capturing || state.starting || state.stopping || state.flight;
+ $("[data-action=record]").textContent = state.take
+ ? "● New recording"
+ : "● Start recording";
+ $("[data-action=listen]").disabled = !state.capturing;
+ $("[data-action=stop]").disabled = !state.capturing;
+ $("[data-error]").textContent = state.error;
+}
+function clearFlight() {
+ state.flight = false;
+ clearTimeout(state.timer);
+}
+function send(name, payload) {
+ state.flight = true;
+ const generation = state.generation;
+ // A broken connection must release the microphone instead of recording forever.
+ state.timer = setTimeout(() => {
+ if (current(generation))
+ fail("The server stopped responding. Please start a new recording.");
+ }, 45000);
+ trigger(name, payload);
+}
+// Little-endian 16-bit PCM in base64: about a tenth of the same samples as
+// JSON numbers, so a take keeps up over an ordinary uplink.
+function encodePcm(pieces, total) {
+ const bytes = new Uint8Array(total * 2),
+ view = new DataView(bytes.buffer);
+ let offset = 0;
+ for (const piece of pieces)
+ for (let i = 0; i < piece.length; i++, offset += 2)
+ view.setInt16(
+ offset,
+ Math.max(-32768, Math.min(32767, Math.round(piece[i] * 32768))),
+ true,
+ );
+ let binary = "";
+ for (let i = 0; i < bytes.length; i += 0x8000)
+ binary += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000));
+ return btoa(binary);
+}
+function pump() {
+ if (state.flight || !state.take || state.finishing) return;
+ if (state.queue.length) {
+ // Everything waiting, up to one second (the server's limit per event):
+ // a slow answer is caught up in one round trip.
+ const rate = state.queue[0].rate,
+ pieces = [];
+ let total = 0;
+ while (
+ state.queue.length &&
+ state.queue[0].rate === rate &&
+ (!pieces.length || total + state.queue[0].samples.length <= rate)
+ ) {
+ const piece = state.queue.shift().samples;
+ pieces.push(piece);
+ total += piece.length;
+ }
+ state.sequence += 1;
+ send("audio_chunk", {
+ take: state.take,
+ sequence: state.sequence,
+ rate,
+ pcm: encodePcm(pieces, total),
+ });
+ } else if (state.stopping && !state.flushing) {
+ state.finishing = true;
+ send("record_finish", {
+ take: state.take,
+ sequence: state.sequence,
+ listen: state.listen,
+ });
+ }
+ controls();
+}
+async function release() {
+ const { stream, node, source, gain, context } = state;
+ // Detach before awaiting close: an older teardown must not clear a new take.
+ state.context = state.stream = state.node = state.source = state.gain = null;
+ stream?.getTracks().forEach((track) => track.stop());
+ node?.disconnect();
+ source?.disconnect();
+ gain?.disconnect();
+ if (context && context.state !== "closed")
+ await context.close().catch(() => {});
+}
+async function fail(message) {
+ const generation = ++state.generation;
+ state.error = message;
+ state.capturing = false;
+ state.stopping = false;
+ state.finishing = false;
+ state.starting = false;
+ state.flushing = false;
+ state.queue = [];
+ state.take = null;
+ clearFlight();
+ await release();
+ if (current(generation)) {
+ controls();
+ status("Recording paused", "Start again when you are ready.");
+ }
+}
+async function stop(listen = false) {
+ if (!state.capturing) return;
+ const generation = state.generation;
+ state.capturing = false;
+ state.stopping = true;
+ state.flushing = true;
+ state.listen = listen;
+ // Stop acquisition now, before awaiting the worklet's already captured tail.
+ state.stream?.getTracks().forEach((track) => track.stop());
+ status(
+ "Finishing your audio…",
+ "Microphone paused. Processing the last samples.",
+ );
+ controls();
+ // The worklet sends its partial final block before acknowledging this flush.
+ if (state.node) {
+ const flushed = await new Promise((resolve) => {
+ const timeout = setTimeout(() => resolve(false), 1000);
+ state.flushed = () => {
+ clearTimeout(timeout);
+ resolve(true);
+ };
+ state.node.port.postMessage("flush");
+ });
+ if (!flushed && current(generation))
+ state.error =
+ "The microphone did not return its final audio block. Your recording may be slightly shortened.";
+ }
+ if (!current(generation)) return;
+ await release();
+ if (!current(generation)) return;
+ state.flushing = false;
+ pump();
+}
+async function startCapture() {
+ const generation = state.generation,
+ context = state.context,
+ stream = state.stream,
+ take = state.take;
+ if (
+ !current(generation) ||
+ !state.starting ||
+ !context ||
+ !stream ||
+ state.node
+ )
+ return;
+ const worklet = `class Capture extends AudioWorkletProcessor {
+ constructor() { super(); this.size=Math.round(sampleRate*.2); this.buffer=new Float32Array(this.size); this.offset=0;
+ this.port.onmessage=()=>{this.emit();this.port.postMessage({flushed:true});}; }
+ emit(){if(this.offset){const block=this.buffer.slice(0,this.offset);this.port.postMessage({samples:block},[block.buffer]);this.offset=0;}}
+ process(inputs){const x=inputs[0]?.[0];if(x){let i=0;while(i<x.length){const n=Math.min(this.size-this.offset,x.length-i);
+ this.buffer.set(x.subarray(i,i+n),this.offset);this.offset+=n;i+=n;if(this.offset===this.size)this.emit();}}return true;}}
+ registerProcessor('voice-capture',Capture);`;
+ const url = URL.createObjectURL(
+ new Blob([worklet], { type: "application/javascript" }),
+ );
+ try {
+ await context.audioWorklet.addModule(url);
+ } finally {
+ URL.revokeObjectURL(url);
+ }
+ if (
+ !current(generation) ||
+ state.context !== context ||
+ state.stream !== stream
+ )
+ return;
+ const node = new AudioWorkletNode(context, "voice-capture");
+ state.node = node;
+ node.port.onmessage = ({ data }) => {
+ if (!current(generation) || state.node !== node || state.take !== take)
+ return;
+ if (data.flushed) {
+ state.flushed?.();
+ state.flushed = null;
+ return;
+ }
+ if (!data.samples || !state.take) return;
+ const rate = context.sampleRate;
+ const remaining = Math.max(0, Math.round(rate * 60) - state.samples);
+ const samples = data.samples.subarray(0, remaining);
+ if (samples.length) {
+ state.samples += samples.length;
+ state.queue.push({ rate, samples });
+ }
+ if (state.queue.length > 20) {
+ state.error =
+ "This device or connection is falling behind. Capture paused so the remaining audio can finish.";
+ stop(false);
+ }
+ if (state.samples >= rate * 60 && state.capturing) stop(false);
+ pump();
+ };
+ // A player may have started while permission or the server was pending.
+ pausePlayers();
+ // An unplugged microphone ends its track (stop() does not fire "ended").
+ stream.getAudioTracks().forEach((track) =>
+ track.addEventListener("ended", () => {
+ if (!current(generation) || !state.capturing) return;
+ state.error =
+ "The microphone was disconnected. The recording up to that point is kept.";
+ stop(false);
+ }),
+ );
+ state.source = context.createMediaStreamSource(stream);
+ state.gain = context.createGain();
+ state.gain.gain.value = 0;
+ state.source.connect(node).connect(state.gain).connect(context.destination);
+ state.starting = false;
+ state.capturing = true;
+ status("Recording live", "Your voice is being isolated as you speak.");
+ controls();
+}
+function microphoneMessage(error) {
+ switch (error?.name) {
+ case "NotAllowedError":
+ case "SecurityError":
+ return "Microphone access is blocked. Allow it for this site (the icon in the address bar), then start again.";
+ case "NotFoundError":
+ case "OverconstrainedError":
+ return "No microphone was found. Connect one, then start again.";
+ case "NotReadableError":
+ case "AbortError":
+ return "The microphone could not be opened. Another application may be using it.";
+ default:
+ return error?.message || "Please allow microphone access and try again.";
+ }
+}
+async function start() {
+ if (
+ state.disposed ||
+ !element.isConnected ||
+ state.flight ||
+ state.starting ||
+ state.capturing ||
+ state.stopping
+ )
+ return;
+ const generation = ++state.generation;
+ state.starting = true;
+ controls();
+ state.error = "";
+ state.sequence = 0;
+ state.samples = 0;
+ state.rate = 0;
+ state.audioSeconds = 0;
+ state.queue = [];
+ state.finishing = false;
+ state.listen = false;
+ state.take = null;
+ pausePlayers();
+ try {
+ if (!navigator.mediaDevices?.getUserMedia)
+ throw new Error("Microphone access needs HTTPS or localhost.");
+ const Context = window.AudioContext || window.webkitAudioContext;
+ // The device's own rate: Firefox refuses a microphone whose rate differs
+ // from a forced one, and the server resamples whatever arrives.
+ const context = new Context({ latencyHint: "interactive" });
+ state.context = context;
+ // Kept past the take's end, when the context is closed, for the readout.
+ state.rate = context.sampleRate;
+ await context.resume();
+ if (!current(generation)) return;
+ const stream = await navigator.mediaDevices.getUserMedia({
+ audio: {
+ channelCount: 1,
+ echoCancellation: true,
+ noiseSuppression: false,
+ autoGainControl: false,
+ },
+ });
+ if (!current(generation)) {
+ stream.getTracks().forEach((track) => track.stop());
+ return;
+ }
+ state.stream = stream;
+ state.take = crypto.randomUUID();
+ status("Preparing your recording…", "Both models are already loaded.");
+ send("record_start", { take: state.take });
+ controls();
+ } catch (error) {
+ if (current(generation)) await fail(microphoneMessage(error));
+ }
+}
+const palette = Array.from({ length: 256 }, (_, i) => {
+ const t = i / 255;
+ const stops = [
+ [7, 13, 27],
+ [44, 34, 99],
+ [121, 53, 137],
+ [225, 98, 107],
+ [255, 210, 125],
+ ];
+ const s = Math.min(3, Math.floor(t * 4)),
+ u = t * 4 - s;
+ return stops[s].map((v, k) => Math.round(v * (1 - u) + stops[s + 1][k] * u));
+});
+function drawWave(canvas, points, color) {
+ if (!canvas) return;
+ const width = Math.max(
+ 100,
+ Math.round(canvas.clientWidth * devicePixelRatio),
+ ),
+ height = 94 * devicePixelRatio;
+ canvas.width = width;
+ canvas.height = height;
+ const ctx = canvas.getContext("2d");
+ ctx.fillStyle = "#0c1425";
+ ctx.fillRect(0, 0, width, height);
+ ctx.strokeStyle = "#26344d";
+ ctx.beginPath();
+ ctx.moveTo(0, height / 2);
+ ctx.lineTo(width, height / 2);
+ ctx.stroke();
+ if (!points?.length) return;
+ ctx.strokeStyle = color;
+ ctx.lineWidth = Math.max(1, (width / points.length) * 0.65);
+ ctx.beginPath();
+ points.forEach((p, i) => {
+ const x = (i * width) / points.length;
+ ctx.moveTo(x, height * (0.5 - Math.max(-1, p[0]) * 0.46));
+ ctx.lineTo(x, height * (0.5 - Math.min(1, p[1]) * 0.46));
+ });
+ ctx.stroke();
+}
+function drawSpec(canvas, bins) {
+ if (!canvas) return;
+ const rows = bins?.length || 96,
+ cols = bins?.[0]?.length || 80;
+ canvas.width = cols;
+ canvas.height = rows;
+ const ctx = canvas.getContext("2d"),
+ data = ctx.createImageData(cols, rows);
+ for (let y = 0; y < rows; y++)
+ for (let x = 0; x < cols; x++) {
+ const rgb = palette[bins?.[rows - 1 - y]?.[x] || 0],
+ p = (y * cols + x) * 4;
+ data.data.set([...rgb, 255], p);
+ }
+ ctx.putImageData(data, 0, 0);
+}
+function render(value = {}) {
+ const viz = value.visualization || {};
+ for (const name of ["input", "output"]) {
+ drawWave(
+ $(`[data-wave=${name}]`),
+ viz[name]?.waveform,
+ name === "output" ? "#75f1c5" : "#91a5d5",
+ );
+ drawSpec($(`[data-spec=${name}]`), viz[name]?.spectrogram);
+ }
+ const seconds = value.input_seconds || 0,
+ whole = Math.floor(seconds);
+ $("[data-clock]").innerHTML =
+ `${String(Math.floor(whole / 60)).padStart(2, "0")}:${String(whole % 60).padStart(2, "0")}<span> / 01:00</span>`;
+ // Error responses carry no device; keep the last one the server named.
+ if (typeof value.device === "string" && value.device)
+ state.device = value.device;
+ if (value.processing_seconds > 0)
+ $("[data-speed]").textContent =
+ `${(seconds / value.processing_seconds).toFixed(1)}× real time${state.device ? ` on ${state.device}` : ""} · ${Math.max(0, state.samples / (state.rate || 48000) - seconds).toFixed(1)} s pending`;
+ controls();
+}
+// Resolves true if the player stops rewound to the start within two seconds:
+// Gradio's player stops itself (pause, then seek to 0) once its waveform is
+// ready, which can land just after playback started. A listener's own pause
+// leaves the position where it was, and is respected.
+function rewoundSoon(audio) {
+ return new Promise((resolve) => {
+ const done = (value) => {
+ clearTimeout(timer);
+ audio.removeEventListener("pause", onPause);
+ resolve(value);
+ };
+ // The seek follows the pause in the same call; read the position after it.
+ const onPause = () =>
+ setTimeout(() => done(audio.currentTime === 0 && !audio.ended), 0);
+ const timer = setTimeout(() => done(false), 2000);
+ audio.addEventListener("pause", onPause);
+ });
+}
+async function playCleanRecording() {
+ const generation = state.generation;
+ const wanted = () =>
+ current(generation) && !state.starting && !state.capturing;
+ // The HTML response arrives before the Audio component finishes loading its WAV.
+ for (let attempt = 0; attempt < 100; attempt++) {
+ if (!wanted()) return;
+ const audio = Array.from(discoverPlayers()).find(
+ (player) =>
+ insidePlayer(player, "online-result") &&
+ player.currentSrc &&
+ player.readyState >= 1,
+ );
+ if (audio) {
+ for (let tries = 0; tries < 3 && wanted(); tries++) {
+ try {
+ await audio.play();
+ } catch {
+ if (current(generation))
+ status(
+ "Ready to listen",
+ "Press play below to hear your clean recording.",
+ );
+ return;
+ }
+ if (!(await rewoundSoon(audio))) return;
+ }
+ return;
+ }
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ }
+}
+watch("value", async () => {
+ const value = props.value || {};
+ if (state.disposed || value.take !== state.take || !state.take) return;
+ if (
+ ["active", "finished"].includes(value.phase) &&
+ value.sequence !== state.sequence
+ )
+ return;
+ render(value);
+ clearFlight();
+ if (value.phase === "error") {
+ await fail(value.message);
+ return;
+ }
+ if (value.phase === "ready") {
+ const generation = state.generation;
+ try {
+ await startCapture();
+ } catch (error) {
+ if (current(generation)) await fail(error.message);
+ }
+ } else if (value.phase === "finished") {
+ state.stopping = false;
+ state.finishing = false;
+ status(
+ "Ready to listen",
+ "Microphone paused. Play your clean voice below, or start a new recording.",
+ );
+ controls();
+ if (state.listen) playCleanRecording();
+ } else {
+ if (value.limit_reached) await stop(false);
+ pump();
+ }
+});
+element.addEventListener("click", (event) => {
+ const action = event.target.closest("[data-action]")?.dataset.action;
+ if (action === "record") start();
+ if (action === "listen") stop(true);
+ if (action === "stop") stop(false);
+});
+// Pause capture before any player on either tab can feed speakers into the mic.
+const onPlay = async (event) => {
+ const audio =
+ event.composedPath?.().find((node) => node instanceof HTMLMediaElement) ||
+ event.target;
+ if (!(audio instanceof HTMLMediaElement) || playedEvents.has(event)) return;
+ playedEvents.add(event);
+ if (audio instanceof HTMLMediaElement && state.capturing) {
+ const generation = state.generation;
+ audio.pause();
+ await stop(false);
+ // Track release has completed before the speaker is allowed to resume.
+ if (current(generation)) audio.play().catch(() => {});
+ }
+};
+function dispose() {
+ state.disposed = true;
+ state.generation += 1;
+ state.take = null;
+ state.capturing =
+ state.starting =
+ state.stopping =
+ state.finishing =
+ state.flushing =
+ false;
+ state.queue = [];
+ clearFlight();
+ release();
+}
+const onLeave = () => dispose();
+const onReturn = () => {
+ if (element.isConnected && state.disposed) {
+ state.disposed = false;
+ controls();
+ status("Ready to record", "Start a new recording when you are ready.");
+ }
+};
+window.addEventListener("pagehide", onLeave);
+window.addEventListener("pageshow", onReturn);
+observer = new MutationObserver((records) => {
+ if (!element.isConnected) {
+ dispose();
+ forgetPlayers();
+ window.removeEventListener("pagehide", onLeave);
+ window.removeEventListener("pageshow", onReturn);
+ return;
+ }
+ // Canvas/clock updates do not change the player inventory.
+ if (
+ discoveryTimer === null &&
+ records.some((record) => !element.contains(record.target))
+ ) {
+ discoveryTimer = setTimeout(() => {
+ discoveryTimer = null;
+ discoverPlayers();
+ }, 0);
+ }
+});
+discoverPlayers();
+render(props.value || {});
diff --git a/demo/build_examples.py b/demo/build_examples.py
new file mode 100644
index 0000000..d5b00a9
--- /dev/null
+++ b/demo/build_examples.py
@@ -0,0 +1,128 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Rebuilds the two generated demo examples from their checked-in sources.
+
+ python demo/build_examples.py [--out DIRECTORY]
+
+Each one is a LibriSpeech utterance mixed with noise generated here. The other
+examples are finished recordings and are not touched.
+"""
+
+import argparse
+import hashlib
+import pathlib
+
+import numpy as np
+import soundfile as sf
+import torch
+
+from inworld import voice_isolation
+
+EXAMPLES = pathlib.Path(__file__).resolve().parent / "examples"
+SAMPLE_RATE = 48000
+RECIPES = (
+ {
+ "file":
+ "sample_14.wav",
+ "source":
+ "sources/2277-149896-0032.flac",
+ "source_sha256":
+ "56b640a079f27f9473478a20f068b8bd8af3afa7030d7a07cbbc7b3f19211689",
+ "noise":
+ "hiss",
+ "seed":
+ 7,
+ "snr_db":
+ 6,
+ },
+ {
+ "file":
+ "sample_15.wav",
+ "source":
+ "sources/2035-147960-0000.flac",
+ "source_sha256":
+ "0ee6731694bcc55349cf4f70123aaff81a7779c782c4a3ec4579b243b1552748",
+ "noise":
+ "hum_taps",
+ "seed":
+ 11,
+ "snr_db":
+ 9,
+ },
+)
+
+
+def _noise(kind: str, size: int, rate: int, seed: int) -> np.ndarray:
+ rng = np.random.Generator(np.random.PCG64(seed))
+ if kind == "hiss":
+ return rng.standard_normal(size)
+ if kind != "hum_taps":
+ raise ValueError(f"Unknown generated noise: {kind}")
+ time = np.arange(size) / rate
+ noise = sum(
+ np.sin(2 * np.pi * frequency * time) / harmonic
+ for harmonic, frequency in enumerate((50, 100, 150), 1))
+ for start in (2.0, 4.5, 7.0):
+ begin = int(start * rate)
+ length = min(int(0.2 * rate), size - begin)
+ if length > 0:
+ noise[begin:begin + length] += (8 * rng.standard_normal(length) *
+ np.exp(-np.arange(length) /
+ (0.025 * rate)))
+ return noise
+
+
+def build_examples(destination: pathlib.Path) -> None:
+ """Writes the generated examples, checking their sources first.
+
+ Args:
+ destination: Directory receiving the WAVs.
+
+ Raises:
+ ValueError: A source recording differs from its recorded checksum.
+ """
+ for recipe in RECIPES:
+ source = EXAMPLES / recipe["source"]
+ if hashlib.sha256(
+ source.read_bytes()).hexdigest() != recipe["source_sha256"]:
+ raise ValueError(f"Source SHA-256 mismatch: {recipe['source']}")
+ destination.mkdir(parents=True, exist_ok=True)
+ for recipe in RECIPES:
+ speech, rate = sf.read(EXAMPLES / recipe["source"], dtype="float32")
+ speech = voice_isolation.resample(torch.from_numpy(speech), rate,
+ SAMPLE_RATE).numpy()
+ speech = speech.astype(np.float64)
+ speech *= 0.08 / np.sqrt(np.mean(speech**2))
+ noise = _noise(recipe["noise"], len(speech), SAMPLE_RATE,
+ recipe["seed"])
+ noise *= 0.08 / (10**(recipe["snr_db"] / 20) *
+ np.sqrt(np.mean(noise**2)))
+ mixture = speech + noise
+ mixture *= min(1.0, 0.95 / np.max(np.abs(mixture)))
+ sf.write(destination / recipe["file"],
+ mixture,
+ SAMPLE_RATE,
+ subtype="PCM_16")
+
+
+def main() -> None:
+ """Rebuilds the generated examples at the requested output path."""
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--out", type=pathlib.Path, default=EXAMPLES)
+ args = parser.parse_args()
+ build_examples(args.out)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/demo/example_audio.py b/demo/example_audio.py
new file mode 100644
index 0000000..56d8234
--- /dev/null
+++ b/demo/example_audio.py
@@ -0,0 +1,102 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Lists the demo's example audio: the audio files of one folder."""
+
+import dataclasses
+import pathlib
+import re
+
+import numpy as np
+import soundfile as sf
+
+DEFAULT_DIRECTORY = pathlib.Path(__file__).resolve().parent / "examples"
+AUDIO_FORMATS = {
+ ".wav": frozenset(("WAV", "WAVEX", "RF64")),
+ ".flac": frozenset(("FLAC",)),
+ ".mp3": frozenset(("MP3",)),
+ ".ogg": frozenset(("OGG",)),
+}
+
+
[email protected](frozen=True)
+class Examples:
+ """The audio files and the label each one is shown with."""
+
+ rows: list[list[str]]
+ labels: list[str]
+
+
+def _validate_audio(path):
+ try:
+ with sf.SoundFile(path) as audio:
+ if audio.format not in AUDIO_FORMATS[path.suffix.lower()]:
+ raise ValueError(
+ "Example audio format does not match its filename: "
+ f"{path.name}")
+ if audio.frames < 1 or audio.channels < 1 or audio.samplerate < 1:
+ raise ValueError(
+ f"Example audio is empty or invalid: {path.name}")
+ frames = 0
+ for block in audio.blocks(blocksize=65536, dtype="float32"):
+ if not np.isfinite(block).all():
+ raise ValueError(
+ "Example audio contains non-finite samples: "
+ f"{path.name}")
+ frames += len(block)
+ if frames == 0:
+ raise ValueError(
+ f"Example audio has no decodable frames: {path.name}")
+ except (OSError, RuntimeError) as error:
+ raise ValueError(f"Cannot decode example audio: {path.name}") from error
+
+
+def _name_order(path):
+ return [(0, int(part), "") if part.isdigit() else (1, 0, part)
+ for part in re.split(r"(\d+)", path.name)]
+
+
+def load_examples(directory: str | pathlib.Path) -> Examples:
+ """Returns the audio files of a folder and their labels, in name order.
+
+ Numbers in names sort by value (``sample_2`` before ``sample_10``). A label
+ is the file name without its extension. Other files and subfolders are
+ left out.
+
+ Args:
+ directory: The folder of example audio.
+
+ Returns:
+ Gradio rows and display labels. Only these individual files may be
+ passed to Gradio's allowed_paths, never the directory.
+
+ Raises:
+ ValueError: The folder is missing or holds no audio, or an audio file
+ is a link or is not the audio its name says.
+ """
+ root = pathlib.Path(directory).resolve()
+ if not root.is_dir():
+ raise ValueError(f"No examples folder at {root}.")
+ examples, labels = [], []
+ for path in sorted(root.iterdir(), key=_name_order):
+ if path.suffix.lower() not in AUDIO_FORMATS:
+ continue
+ if path.is_symlink() or not path.is_file():
+ raise ValueError(
+ f"Example must be a regular, non-symlink file: {path.name}")
+ _validate_audio(path)
+ examples.append([str(path)])
+ labels.append(path.stem)
+ if not examples:
+ raise ValueError(f"No example audio in {root}.")
+ return Examples(examples, labels)
diff --git a/demo/examples/sample_1.wav b/demo/examples/sample_1.wav
new file mode 100644
index 0000000..c33672d
Binary files /dev/null and b/demo/examples/sample_1.wav differ
diff --git a/demo/examples/sample_10.wav b/demo/examples/sample_10.wav
new file mode 100644
index 0000000..5bf45a8
Binary files /dev/null and b/demo/examples/sample_10.wav differ
diff --git a/demo/examples/sample_11.wav b/demo/examples/sample_11.wav
new file mode 100644
index 0000000..6d3c5b0
Binary files /dev/null and b/demo/examples/sample_11.wav differ
diff --git a/demo/examples/sample_12.wav b/demo/examples/sample_12.wav
new file mode 100644
index 0000000..767f53a
Binary files /dev/null and b/demo/examples/sample_12.wav differ
diff --git a/demo/examples/sample_13.wav b/demo/examples/sample_13.wav
new file mode 100644
index 0000000..6b43625
Binary files /dev/null and b/demo/examples/sample_13.wav differ
diff --git a/demo/examples/sample_14.wav b/demo/examples/sample_14.wav
new file mode 100644
index 0000000..67554f4
Binary files /dev/null and b/demo/examples/sample_14.wav differ
diff --git a/demo/examples/sample_15.wav b/demo/examples/sample_15.wav
new file mode 100644
index 0000000..8724f52
Binary files /dev/null and b/demo/examples/sample_15.wav differ
diff --git a/demo/examples/sample_2.wav b/demo/examples/sample_2.wav
new file mode 100644
index 0000000..df01d15
Binary files /dev/null and b/demo/examples/sample_2.wav differ
diff --git a/demo/examples/sample_3.wav b/demo/examples/sample_3.wav
new file mode 100644
index 0000000..def9248
Binary files /dev/null and b/demo/examples/sample_3.wav differ
diff --git a/demo/examples/sample_4.wav b/demo/examples/sample_4.wav
new file mode 100644
index 0000000..41c923b
Binary files /dev/null and b/demo/examples/sample_4.wav differ
diff --git a/demo/examples/sample_5.wav b/demo/examples/sample_5.wav
new file mode 100644
index 0000000..1d4e4f6
Binary files /dev/null and b/demo/examples/sample_5.wav differ
diff --git a/demo/examples/sample_6.wav b/demo/examples/sample_6.wav
new file mode 100644
index 0000000..fdc8e3e
Binary files /dev/null and b/demo/examples/sample_6.wav differ
diff --git a/demo/examples/sample_7.wav b/demo/examples/sample_7.wav
new file mode 100644
index 0000000..93fccb2
Binary files /dev/null and b/demo/examples/sample_7.wav differ
diff --git a/demo/examples/sample_8.wav b/demo/examples/sample_8.wav
new file mode 100644
index 0000000..b790001
Binary files /dev/null and b/demo/examples/sample_8.wav differ
diff --git a/demo/examples/sample_9.wav b/demo/examples/sample_9.wav
new file mode 100644
index 0000000..12f0cda
Binary files /dev/null and b/demo/examples/sample_9.wav differ
diff --git a/demo/examples/sources/2035-147960-0000.flac b/demo/examples/sources/2035-147960-0000.flac
new file mode 100644
index 0000000..9e76522
Binary files /dev/null and b/demo/examples/sources/2035-147960-0000.flac differ
diff --git a/demo/examples/sources/2277-149896-0032.flac b/demo/examples/sources/2277-149896-0032.flac
new file mode 100644
index 0000000..dbad06d
Binary files /dev/null and b/demo/examples/sources/2277-149896-0032.flac differ
diff --git a/demo/examples/sources/LICENSE.txt b/demo/examples/sources/LICENSE.txt
new file mode 100644
index 0000000..389d558
--- /dev/null
+++ b/demo/examples/sources/LICENSE.txt
@@ -0,0 +1,6 @@
+LibriSpeech (c) 2014 by Vassil Panayotov
+
+LibriSpeech ASR corpus is licensed under a
+Creative Commons Attribution 4.0 International License.
+
+See <http://creativecommons.org/licenses/by/4.0/>.
diff --git a/demo/live.py b/demo/live.py
new file mode 100644
index 0000000..99bd047
--- /dev/null
+++ b/demo/live.py
@@ -0,0 +1,316 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""One bounded microphone recording through a persistent realtime stream."""
+
+import dataclasses
+import threading
+import time
+import typing
+
+import numpy as np
+
+from inworld import voice_isolation
+
+SAMPLE_RATE = 48000
+BLOCK_FRAMES = 4
+LOOKAHEAD_FRAMES = 2
+WAVEFORM_BINS = 480
+FREQUENCY_BINS = 96
+TIME_BINS = 80
+FFT_SAMPLES = 2048
+MIN_DECIBELS = -100.0
+
+
[email protected](frozen=True)
+class LiveUpdate:
+ """Progress and bounded, JSON-compatible plots for one recording.
+
+ ``visualization`` contains ``sample_rate``, ``start_seconds``,
+ ``end_seconds``, ``frequency_hz`` and ``decibels``. Its ``input`` and
+ ``output`` each contain a ``waveform`` list of [minimum, maximum] pairs
+ and a ``spectrogram`` matrix indexed [frequency][time]. Frequencies run
+ low to high and times run oldest to newest; intensity 0 means -100 dBFS
+ and 255 means 0 dBFS. Both signals share the same finalized time window.
+ """
+
+ input_seconds: float
+ output_seconds: float
+ processing_seconds: float
+ finished: bool
+ limit_reached: bool
+ visualization: dict[str, typing.Any]
+
+
+def _mono_float(samples: np.ndarray) -> np.ndarray:
+ """Converts browser PCM to mono float32 without adjusting its level."""
+ if samples.ndim not in (1, 2) or (samples.ndim == 2 and
+ samples.shape[1] == 0):
+ raise ValueError("Microphone audio must have samples and channels.")
+ if samples.dtype.kind not in "iuf":
+ raise ValueError("Microphone audio must contain numeric PCM samples.")
+ if samples.dtype.kind in "iu":
+ info = np.iinfo(samples.dtype)
+ midpoint = float(info.max) + 1.0
+ if samples.dtype.kind == "u":
+ midpoint /= 2.0
+ samples = (samples.astype(np.float32) - midpoint) / midpoint
+ else:
+ samples = samples.astype(np.float32) / midpoint
+ else:
+ samples = samples.astype(np.float32, copy=False)
+ if not np.isfinite(samples).all():
+ raise ValueError("Microphone audio must contain finite samples.")
+ if samples.ndim == 2:
+ samples = samples.mean(axis=1, dtype=np.float32)
+ return np.ascontiguousarray(samples, dtype=np.float32)
+
+
+def _plot(samples: np.ndarray) -> dict[str, list]:
+ """Returns fixed-scale amplitude and spectral previews of one window."""
+ if samples.size == 0:
+ return {"waveform": [], "spectrogram": []}
+ boundaries = np.linspace(0,
+ samples.size,
+ min(samples.size, WAVEFORM_BINS) + 1,
+ dtype=np.int64)
+ waveform = [[float(samples[a:b].min()),
+ float(samples[a:b].max())]
+ for a, b in zip(boundaries[:-1], boundaries[1:])]
+ centers = np.linspace(0,
+ samples.size - 1,
+ min(TIME_BINS, samples.size),
+ dtype=np.int64)
+ padded = np.pad(samples, (FFT_SAMPLES // 2, FFT_SAMPLES // 2))
+ frames = padded[centers[:, None] + np.arange(FFT_SAMPLES)[None]]
+ window = np.hanning(FFT_SAMPLES).astype(np.float32)
+ magnitude = np.abs(np.fft.rfft(frames * window, axis=1))
+ magnitude *= 2.0 / window.sum()
+ edges = np.linspace(0,
+ magnitude.shape[1],
+ FREQUENCY_BINS + 1,
+ dtype=np.int64)
+ bands = np.stack(
+ [magnitude[:, a:b].max(axis=1) for a, b in zip(edges[:-1], edges[1:])])
+ decibels = 20.0 * np.log10(np.maximum(bands, 1e-8))
+ intensity = np.rint(
+ np.clip((decibels - MIN_DECIBELS) / -MIN_DECIBELS, 0, 1) * 255).astype(
+ np.uint8)
+ return {"waveform": waveform, "spectrogram": intensity.tolist()}
+
+
+class LiveSession:
+ """Owns one browser's resampler, model stream and bounded recording.
+
+ The injected isolator must already use streaming mode and the released
+ two-frame look-ahead. Its mode must remain fixed while sessions exist.
+ Pass the same ``model_lock`` to sessions sharing a model to serialize
+ device inference. Each session independently serializes its own events.
+
+ ``push`` accepts only newly recorded chunks, never a growing recording.
+ ``finish`` flushes once and returns mono float32 audio at 48 kHz, and
+ ``recorded`` returns the unprocessed input it was isolated from. At the
+ recording limit, the session finishes automatically; later chunks are
+ ignored. ``reset`` releases the recording and stream; start a new instance
+ for the next recording. No audio is written to disk by this class.
+ """
+
+ def __init__(
+ self,
+ model: voice_isolation.VoiceIsolator,
+ *,
+ max_seconds: float = 60.0,
+ window_seconds: float = 6.0,
+ model_lock: typing.ContextManager | None = None,
+ ) -> None:
+ setting = (model.mode, model.lookahead_frames)
+ if setting != ("streaming", LOOKAHEAD_FRAMES):
+ raise ValueError("Live audio needs the realtime model in streaming"
+ " mode with two look-ahead frames.")
+ if model.sample_rate != SAMPLE_RATE:
+ raise ValueError("Live audio needs a 48 kHz model.")
+ if not np.isfinite(max_seconds) or not 0 < max_seconds <= 60:
+ raise ValueError("The recording limit must be between 0 and 60 s.")
+ if not np.isfinite(window_seconds) or not 0 < window_seconds <= 8:
+ raise ValueError("The visualization window must be at most 8 s.")
+ self._lock = threading.RLock()
+ self._model_lock = (model_lock
+ if model_lock is not None else threading.RLock())
+ with self._model_lock:
+ self._stream = model.stream(block_frames=BLOCK_FRAMES)
+ self._max_seconds = float(max_seconds)
+ self._capacity = max(1, int(max_seconds * SAMPLE_RATE))
+ self._window = max(1, int(window_seconds * SAMPLE_RATE))
+ self._input = np.empty(self._capacity, dtype=np.float32)
+ self._output = np.empty(self._capacity, dtype=np.float32)
+ self._input_count = 0
+ self._output_count = 0
+ self._source_rate = None
+ self._source_count = 0
+ self._resampler = None
+ self._processing_seconds = 0.0
+ self._finished = False
+ self._limit_reached = False
+
+ def _append_output(self, samples: np.ndarray) -> None:
+ if samples.ndim != 1 or not np.isfinite(samples).all():
+ raise RuntimeError("The live model returned invalid audio.")
+ count = samples.size
+ if self._output_count + count > self._input_count:
+ raise RuntimeError(
+ "The live model returned more audio than received.")
+ end = self._output_count + count
+ self._output[self._output_count:end] = samples
+ self._output_count = end
+
+ def _feed(self, samples: np.ndarray) -> None:
+ samples = samples[:self._capacity - self._input_count]
+ if samples.size == 0:
+ return
+ end = self._input_count + samples.size
+ self._input[self._input_count:end] = samples
+ self._input_count = end
+ with self._model_lock:
+ start = time.perf_counter()
+ output = self._stream.push(samples)
+ self._processing_seconds += time.perf_counter() - start
+ self._append_output(output)
+
+ def push(self, audio: tuple[int, np.ndarray] | None) -> LiveUpdate:
+ """Processes new browser samples and returns a rolling visualization.
+
+ Integer PCM is converted at its fixed full-scale level. The browser
+ rate may differ from 48 kHz but must stay constant for the recording;
+ a stateful resampler retains fractional positions across chunks.
+ """
+ with self._lock:
+ if self._finished or audio is None:
+ return self.snapshot()
+ rate, raw = audio
+ valid_rate = (isinstance(rate, (int, np.integer)) and
+ not isinstance(rate, bool))
+ if not valid_rate or rate <= 0:
+ raise ValueError("The microphone sample rate must be positive.")
+ if self._source_rate is not None and rate != self._source_rate:
+ raise ValueError("The microphone sample rate changed; start a"
+ " new recording.")
+ raw = np.asarray(raw)
+ if raw.ndim not in (1, 2):
+ raise ValueError(
+ "Microphone audio must have samples and channels.")
+ remaining = max(0,
+ int(self._max_seconds * rate) - self._source_count)
+ samples = _mono_float(raw[:remaining])
+ if samples.size == 0:
+ return self.snapshot()
+ if self._source_rate is None:
+ if rate != SAMPLE_RATE:
+ try:
+ # Resampling belongs to the optional demo extra.
+ # pylint: disable-next=import-outside-toplevel
+ import soxr
+ except ImportError as error:
+ raise ImportError("Live microphone resampling needs"
+ " the demo extra (soxr).") from error
+ self._resampler = soxr.ResampleStream(rate,
+ SAMPLE_RATE,
+ 1,
+ dtype="float32")
+ self._source_rate = int(rate)
+ self._source_count += samples.size
+ converted = (samples if self._resampler is None else
+ self._resampler.resample_chunk(samples))
+ self._feed(converted)
+ if self._source_count >= int(self._max_seconds * rate):
+ self._limit_reached = True
+ self._finish()
+ return self.snapshot()
+
+ def _finish(self) -> None:
+ if self._finished:
+ return
+ if self._resampler is not None:
+ self._feed(
+ self._resampler.resample_chunk(np.empty(0, dtype=np.float32),
+ last=True))
+ self._resampler = None
+ if self._input_count:
+ with self._model_lock:
+ start = time.perf_counter()
+ output = self._stream.flush(as_numpy=True)
+ self._processing_seconds += time.perf_counter() - start
+ self._append_output(output)
+ self._stream = None
+ self._finished = True
+ if self._output_count != self._input_count:
+ raise RuntimeError(
+ "The live model did not return the full recording.")
+
+ def finish(self) -> tuple[int, np.ndarray]:
+ """Flushes once and returns the complete isolated recording."""
+ with self._lock:
+ self._finish()
+ return SAMPLE_RATE, self._output[:self._output_count].copy()
+
+ @property
+ def finished(self) -> bool:
+ """Whether the take has ended: finished, capped at the limit or reset.
+
+ Cheap, unlike ``snapshot``, which also builds the plots.
+ """
+ return self._finished
+
+ def recorded(self) -> tuple[int, np.ndarray]:
+ """Returns the microphone input so far, mono float32 at 48 kHz.
+
+ This is the audio the stream received, sample-aligned with the
+ isolated recording ``finish`` returns: after ``finish`` both have the
+ same length, and the input minus the voice is the removed background.
+ """
+ with self._lock:
+ return SAMPLE_RATE, self._input[:self._input_count].copy()
+
+ def snapshot(self) -> LiveUpdate:
+ """Returns progress and plots of the latest finalized audio window."""
+ with self._lock:
+ end = self._output_count
+ start = max(0, end - self._window)
+ visualization = {
+ "sample_rate": SAMPLE_RATE,
+ "start_seconds": start / SAMPLE_RATE,
+ "end_seconds": end / SAMPLE_RATE,
+ "frequency_hz": [0, SAMPLE_RATE // 2],
+ "decibels": [MIN_DECIBELS, 0],
+ "input": _plot(self._input[start:end]),
+ "output": _plot(self._output[start:end]),
+ }
+ return LiveUpdate(
+ input_seconds=(self._source_count /
+ self._source_rate if self._source_rate else 0.0),
+ output_seconds=end / SAMPLE_RATE,
+ processing_seconds=self._processing_seconds,
+ finished=self._finished,
+ limit_reached=self._limit_reached,
+ visualization=visualization)
+
+ def reset(self) -> None:
+ """Discards the recording and releases the session's inference state."""
+ with self._lock:
+ self._stream = None
+ self._resampler = None
+ self._input = np.empty(0, dtype=np.float32)
+ self._output = np.empty(0, dtype=np.float32)
+ self._input_count = self._output_count = self._source_count = 0
+ self._source_rate = None
+ self._processing_seconds = 0.0
+ self._finished = True
diff --git a/demo/online.py b/demo/online.py
new file mode 100644
index 0000000..2a35868
--- /dev/null
+++ b/demo/online.py
@@ -0,0 +1,299 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Per-browser callbacks for the live microphone tab.
+
+The browser sends each piece of microphone audio as ``pcm``: base64 of
+little-endian 16-bit PCM, at most one second per event, with its sample
+rate. Every answer is a value for the panel; a failure is an "error" phase
+naming the take it belongs to, which the browser acts on at once.
+"""
+
+import base64
+import dataclasses
+import math
+import threading
+import time
+
+import gradio as gr
+import numpy as np
+
+import live
+
+# Live takes running at once: each holds about 1.3 GB on the device, and on
+# an Apple M4 Max a third concurrent take already falls behind.
+MAX_LIVE_TAKES = 2
+# A take whose browser sent nothing for this long has failed on its side (a
+# lost connection, a closed microphone): the next take to start releases it.
+IDLE_SECONDS = 10.0
+MIN_RATE, MAX_RATE = 8000, 192000
+_EXPIRED = (f"This recording stopped after {IDLE_SECONDS:g} seconds without"
+ " audio. Please start a new recording.")
+
+
+def _now() -> float:
+ """The clock that times takes, looked up when called."""
+ return time.monotonic()
+
+
+class Recording:
+ """One browser take, its ordered audio and its streaming state."""
+
+ take: str
+ session: live.LiveSession
+ sequence: int = 0
+ touched: float = dataclasses.field(default_factory=_now)
+ pushing: int = 0
+ expired: bool = False
+
+ @property
+ def idle(self) -> bool:
+ """Unfinished, with no audio in flight and none for IDLE_SECONDS."""
+ return (not self.session.finished and not self.pushing and
+ time.monotonic() - self.touched >= IDLE_SECONDS)
+
+ @property
+ def active(self) -> bool:
+ """Whether the take holds a place: unfinished and not idle."""
+ return not self.session.finished and not self.idle
+
+
+def close_recording(recording):
+ """Releases a browser's stream when its state expires."""
+ if recording is not None:
+ recording.session.reset()
+
+
+def _player(rate, audio):
+ """A player value at the recording's own level, or None when empty."""
+ # Integer audio prevents Gradio from raising quiet output to full scale.
+ preview = np.round(np.clip(audio, -1, 1) * 32767).astype(np.int16)
+ return gr.Audio(value=(rate, preview) if len(preview) else None)
+
+
+def _error(take, message):
+ """An error answer for ``take``; the browser ends that take with it."""
+ return dict(take=take if isinstance(take, str) else None,
+ phase="error",
+ message=message)
+
+
+def _decode(pcm, rate) -> tuple[int, np.ndarray]:
+ """Checks one browser event's audio; raises ValueError when invalid."""
+ if (not isinstance(rate, (int, float)) or isinstance(rate, bool) or
+ not math.isfinite(rate) or rate != int(rate) or
+ not MIN_RATE <= rate <= MAX_RATE):
+ raise ValueError("Invalid microphone rate.")
+ rate = int(rate)
+ # Base64 of one second of 16-bit samples, rounded up to whole groups.
+ if not isinstance(pcm, str) or len(pcm) > 4 * math.ceil(2 * rate / 3):
+ raise ValueError("Invalid microphone audio.")
+ raw = base64.b64decode(pcm, validate=True)
+ if len(raw) % 2:
+ raise ValueError("Invalid microphone audio.")
+ return rate, np.frombuffer(raw, dtype="<i2")
+
+
+class Online:
+ """Shares model weights while giving each browser its own audio state.
+
+ ``device`` names where the model runs (for example "Metal GPU"); every
+ answer carries it for the panel's speed readout. At most ``max_takes``
+ browsers record at once. A browser's take is released when its state
+ expires, when it starts another, and when its tab closes (``release``,
+ registered as the page's unload event). A take starts only if the model
+ is free within ``start_wait`` seconds (on an Apple GPU an Offline
+ isolation holds it for its whole length).
+ """
+
+ def __init__(self,
+ model,
+ model_lock: threading.RLock,
+ device: str = "",
+ max_takes: int = MAX_LIVE_TAKES,
+ start_wait: float = 2.0):
+ self.model = model
+ self.model_lock = model_lock
+ self.device = device
+ self.max_takes = max_takes
+ self.start_wait = start_wait
+ self._takes = {}
+ self._starting = 0
+ # browsers with a start in flight, and those that closed meanwhile
+ self._pending = {}
+ self._closed = set()
+ self._takes_lock = threading.Lock()
+
+ def _response(self, recording, phase, message="", update=None):
+ if update is None:
+ update = recording.session.snapshot()
+ return dict(take=recording.take,
+ sequence=recording.sequence,
+ phase=phase,
+ message=message,
+ device=self.device,
+ input_seconds=update.input_seconds,
+ output_seconds=update.output_seconds,
+ processing_seconds=update.processing_seconds,
+ limit_reached=update.limit_reached,
+ visualization=update.visualization)
+
+ def start(self,
+ recording,
+ event: gr.EventData,
+ request: gr.Request | None = None):
+ """Starts a fresh take after the browser grants microphone access.
+
+ Returns the state, the panel's value and both players cleared.
+ """
+ take = getattr(event, "take", None)
+ if not isinstance(take, str) or not 1 <= len(take) <= 80:
+ return recording, _error(
+ None, "Invalid recording. Please start again."), None, None
+ browser = getattr(request, "session_hash", None)
+ with self._takes_lock:
+ released = [self._takes.pop(browser, None)]
+ # Idle takes give their place up for good: an expired take is
+ # refused if its browser comes back.
+ for key, other in list(self._takes.items()):
+ if other.idle:
+ other.expired = True
+ released.append(self._takes.pop(key))
+ # Outside the registry's lock: a session's own lock may be held by a
+ # push that waits for the model.
+ for old in (recording, *released):
+ close_recording(old)
+ with self._takes_lock:
+ busy = self._starting + sum(
+ other.active for other in self._takes.values())
+ if busy >= self.max_takes:
+ return None, _error(
+ take, "The live demo is busy with other recordings."
+ " Please try again in a minute."), None, None
+ self._starting += 1
+ self._pending[browser] = self._pending.get(browser, 0) + 1
+ closed = False
+ try:
+ if not self.model_lock.acquire(timeout=self.start_wait):
+ return None, _error(
+ take, "The model is busy with other work."
+ " Please try again in a moment."), None, None
+ try:
+ session = live.LiveSession(self.model,
+ model_lock=self.model_lock)
+ except (RuntimeError, ValueError) as error:
+ return None, _error(
+ take, f"The recording could not start: {error}"), None, None
+ finally:
+ self.model_lock.release()
+ recording = Recording(take, session)
+ with self._takes_lock:
+ closed = browser in self._closed
+ if browser is not None and not closed:
+ self._takes[browser] = recording
+ finally:
+ with self._takes_lock:
+ self._starting -= 1
+ self._pending[browser] -= 1
+ if not self._pending[browser]:
+ del self._pending[browser]
+ self._closed.discard(browser)
+ if closed:
+ # The tab closed while the take was starting: nobody will use it.
+ close_recording(recording)
+ return None, _error(take, "The page was closed."), None, None
+ return recording, self._response(recording, "ready"), None, None
+
+ def release(self, request: gr.Request | None = None) -> None:
+ """Releases a closed or reloaded tab's take at once.
+
+ Gradio keeps a closed tab's state for an hour; the stream it holds
+ (about 1.3 GB on the device) should not outlive the page.
+ """
+ browser = getattr(request, "session_hash", None)
+ with self._takes_lock:
+ recording = self._takes.pop(browser, None)
+ if browser in self._pending:
+ self._closed.add(browser)
+ close_recording(recording)
+
+ def push(self, recording, event: gr.EventData):
+ """Consumes each browser event's audio once, in order."""
+ take = getattr(event, "take", None)
+ if recording is None or take != recording.take:
+ # A take this server does not hold (a restart, an expired state
+ # or a late answer for an older take): the browser ends it, and
+ # ignores the answer if it has moved on.
+ return recording, _error(
+ take, "This recording is no longer on the server."
+ " Please start a new recording.")
+ if recording.expired:
+ return recording, _error(recording.take, _EXPIRED)
+ recording.touched = time.monotonic()
+ recording.pushing += 1
+ try:
+ return self._push(recording, event)
+ finally:
+ recording.pushing -= 1
+ recording.touched = time.monotonic()
+
+ def _push(self, recording, event: gr.EventData):
+ sequence = getattr(event, "sequence", None)
+ if (not isinstance(sequence, int) or isinstance(sequence, bool) or
+ sequence != recording.sequence + 1):
+ recording.session.reset()
+ return recording, _error(
+ recording.take,
+ "Audio arrived out of order. Start a new recording.")
+ try:
+ audio = _decode(getattr(event, "pcm", None),
+ getattr(event, "rate", None))
+ update = recording.session.push(audio)
+ except (ValueError, RuntimeError, TypeError, OverflowError):
+ recording.session.reset()
+ return recording, _error(
+ recording.take,
+ "Microphone processing stopped. Please start a new recording.")
+ recording.sequence = sequence
+ return recording, self._response(recording, "active", update=update)
+
+ def finish(self, recording, event: gr.EventData):
+ """Flushes the final samples after capture and queued audio stop.
+
+ Returns the state, the panel's value, the isolated voice and the
+ unprocessed microphone input it came from, sample-aligned.
+ """
+ take = getattr(event, "take", None)
+ if recording is None or take != recording.take:
+ return recording, _error(
+ take, "This recording is no longer on the server."
+ " Please start a new recording."), gr.skip(), gr.skip()
+ if recording.expired:
+ return recording, _error(recording.take,
+ _EXPIRED), gr.skip(), gr.skip()
+ if getattr(event, "sequence", None) != recording.sequence:
+ return recording, _error(
+ recording.take,
+ "Some microphone audio did not reach the server."
+ " Please start a new recording."), gr.skip(), gr.skip()
+ try:
+ rate, audio = recording.session.finish()
+ except (RuntimeError, ValueError) as error:
+ recording.session.reset()
+ return recording, _error(
+ recording.take, f"The recording could not be finished: {error}"
+ ), gr.skip(), gr.skip()
+ _, original = recording.session.recorded()
+ return (recording, self._response(recording, "finished"),
+ _player(rate, audio), _player(rate, original))
diff --git a/docs/assets/architecture-dark.svg b/docs/assets/architecture-dark.svg
new file mode 100644
index 0000000..dae96eb
--- /dev/null
+++ b/docs/assets/architecture-dark.svg
@@ -0,0 +1,115 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="1040" height="551" viewBox="0 0 1040 551" role="img" aria-label="Inworld Voice Isolator architecture">
+<desc>Input x(t), 48 kHz mono. STFT with N = 2048 and hop H = 480 (10 ms) gives X in C^(F x T), F = 1025 bins. Band split into B = 46 bands, 100 Hz to 2 kHz wide, each projected to D = 512, gives Z in R^(B x T x D). Seven dual-path blocks, alternating A, M, A, M, A, M, A: block A is time attention (rotary positions, exclusive self-attention, 8 heads) then band attention; block M is time Mamba (state 16, expand 2, conv 4) then band Mamba; the time path runs along time within each band, the band path across bands within each frame; every sub-layer has a residual connection. Per-band linear heads produce a bounded complex mask M and a bounded residual R, both in C^(F x T). Output spectrum X_hat = X + M (.) X + R, from the input spectrum X through a skip connection; iSTFT gives the isolated voice s_hat(t). The realtime checkpoint runs the same blocks causally with a look-ahead of 0, 2 or 4 frames as a learned embedding; the offline checkpoint is two-sided and renders 8 s chunks.</desc>
+<rect width="100%" height="100%" fill="#0D1117"/>
+<path d="M24.0,124.0 L72.7,124.0" fill="none" stroke="#A6AFBA" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M78.0,124.0 L69.5,127.2 L71.9,124.0 L69.5,120.8 Z" fill="#A6AFBA"/>
+<text x="47.0" y="114.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="19" fill="#F0F6FC" text-anchor="middle"><tspan font-style="italic">x</tspan>(<tspan font-style="italic">t</tspan>)</text>
+<text x="47.0" y="148.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="13.5" fill="#A6AFBA" text-anchor="middle">48 kHz</text>
+<path d="M962.0,124.0 L1010.7,124.0" fill="none" stroke="#A6AFBA" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M1016.0,124.0 L1007.5,127.2 L1009.9,124.0 L1007.5,120.8 Z" fill="#A6AFBA"/>
+<text x="991.0" y="114.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="19" fill="#F0F6FC" text-anchor="middle"><tspan font-style="italic">ŝ</tspan>(<tspan font-style="italic">t</tspan>)</text>
+<text x="991.0" y="148.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="13.5" fill="#A6AFBA" text-anchor="middle">48 kHz</text>
+<rect x="78.0" y="66" width="132.5" height="116" rx="8" fill="#1C3554"/>
+<text x="144.2" y="97.5" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="17.5" fill="#F0F6FC" font-weight="600" text-anchor="middle">STFT</text>
+<text x="144.2" y="121.5" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="15" fill="#D1D7E0" text-anchor="middle"><tspan font-style="italic">N</tspan> = 2048</text>
+<text x="144.2" y="142.5" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="15" fill="#D1D7E0" text-anchor="middle"><tspan font-style="italic">H</tspan> = 480 (10 ms)</text>
+<text x="144.2" y="163.5" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="15" fill="#D1D7E0" text-anchor="middle"><tspan font-style="italic">F</tspan> = 1025 bins</text>
+<rect x="242.4" y="66" width="154.6" height="116" rx="8" fill="#17442F"/>
+<text x="319.7" y="97.5" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="17.5" fill="#F0F6FC" font-weight="600" text-anchor="middle">Band split</text>
+<text x="319.7" y="121.5" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="15" fill="#D1D7E0" text-anchor="middle"><tspan font-style="italic">B</tspan> = 46 bands</text>
+<text x="319.7" y="142.5" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="15" fill="#D1D7E0" text-anchor="middle">100 Hz–2 kHz wide</text>
+<text x="319.7" y="163.5" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="15" fill="#D1D7E0" text-anchor="middle">linear to <tspan font-style="italic">D</tspan> = 512</text>
+<rect x="428.9" y="66" width="180.9" height="116" rx="8" fill="#17442F"/>
+<text x="519.4" y="108.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="17.5" fill="#F0F6FC" font-weight="600" text-anchor="middle">7 dual-path blocks</text>
+<text x="519.4" y="132.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="15" fill="#D1D7E0" text-anchor="middle">A M A M A M A</text>
+<text x="519.4" y="153.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="15" fill="#D1D7E0" text-anchor="middle">attention, Mamba</text>
+<rect x="641.7" y="66" width="157.8" height="116" rx="8" fill="#4A3511"/>
+<text x="720.6" y="108.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="17.5" fill="#F0F6FC" font-weight="600" text-anchor="middle">Per-band heads</text>
+<text x="720.6" y="132.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="15" fill="#D1D7E0" text-anchor="middle">mask <tspan font-style="italic">M</tspan>, bounded</text>
+<text x="720.6" y="153.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="15" fill="#D1D7E0" text-anchor="middle">residual <tspan font-style="italic">R</tspan>, |<tspan font-style="italic">R</tspan>| ≤ 0.5</text>
+<rect x="889.4" y="66" width="72.6" height="116" rx="8" fill="#1C3554"/>
+<text x="925.7" y="129.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="17.5" fill="#F0F6FC" font-weight="600" text-anchor="middle">iSTFT</text>
+<path d="M211.5,124.0 L236.1,124.0" fill="none" stroke="#A6AFBA" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M241.4,124.0 L232.9,127.2 L235.3,124.0 L232.9,120.8 Z" fill="#A6AFBA"/>
+<text x="226.5" y="50.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="16" fill="#F0F6FC" text-anchor="middle"><tspan font-style="italic">X</tspan> ∈ ℂ<tspan dy="-6.40" font-size="11.52" font-style="italic">F</tspan><tspan font-size="11.52">×</tspan><tspan font-size="11.52" font-style="italic">T</tspan></text>
+<path d="M398.0,124.0 L422.7,124.0" fill="none" stroke="#A6AFBA" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M427.9,124.0 L419.4,127.2 L421.8,124.0 L419.4,120.8 Z" fill="#A6AFBA"/>
+<text x="413.0" y="50.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="16" fill="#F0F6FC" text-anchor="middle"><tspan font-style="italic">Z</tspan> ∈ ℝ<tspan dy="-6.40" font-size="11.52" font-style="italic">B</tspan><tspan font-size="11.52">×</tspan><tspan font-size="11.52" font-style="italic">T</tspan><tspan font-size="11.52">×</tspan><tspan font-size="11.52" font-style="italic">D</tspan></text>
+<path d="M610.8,124.0 L635.4,124.0" fill="none" stroke="#A6AFBA" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M640.7,124.0 L632.2,127.2 L634.6,124.0 L632.2,120.8 Z" fill="#A6AFBA"/>
+<text x="625.7" y="50.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="16" fill="#F0F6FC" text-anchor="middle"><tspan font-style="italic">Z</tspan>′ ∈ ℝ<tspan dy="-6.40" font-size="11.52" font-style="italic">B</tspan><tspan font-size="11.52">×</tspan><tspan font-size="11.52" font-style="italic">T</tspan><tspan font-size="11.52">×</tspan><tspan font-size="11.52" font-style="italic">D</tspan></text>
+<path d="M800.5,124.0 L825.2,124.0" fill="none" stroke="#A6AFBA" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M830.5,124.0 L822.0,127.2 L824.3,124.0 L822.0,120.8 Z" fill="#A6AFBA"/>
+<path d="M858.5,124.0 L883.1,124.0" fill="none" stroke="#A6AFBA" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M888.4,124.0 L879.9,127.2 L882.3,124.0 L879.9,120.8 Z" fill="#A6AFBA"/>
+<circle cx="844.5" cy="124.0" r="13" fill="#0D1117" stroke="#A6AFBA" stroke-width="1.4"/>
+<path d="M837.7,124.0 H851.2 M844.5,117.2 V130.8" stroke="#A6AFBA" stroke-width="1.4" stroke-linecap="round"/>
+<text x="844.5" y="50.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="16" fill="#F0F6FC" text-anchor="middle"><tspan font-style="italic">X̂</tspan> = <tspan font-style="italic">X</tspan> + <tspan font-style="italic">M</tspan> ⊙ <tspan font-style="italic">X</tspan> + <tspan font-style="italic">R</tspan></text>
+<circle cx="226.5" cy="124.0" r="3.4" fill="#A6AFBA"/>
+<path d="M226.5,124.0 L226.5,196.0 Q226.5,206.0 236.5,206.0 L834.5,206.0 Q844.5,206.0 844.5,196.0 L844.5,142.3" fill="none" stroke="#A6AFBA" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="5 4"/>
+<path d="M844.5,137.0 L847.7,145.5 L844.5,143.1 L841.2,145.5 Z" fill="#A6AFBA"/>
+<text x="535.5" y="226.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="13.5" fill="#A6AFBA" text-anchor="middle">skip: the input spectrum <tspan font-style="italic">X</tspan></text>
+<rect x="24" y="256" width="992" height="214" rx="12" fill="#161B22"/>
+<text x="46.0" y="288.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="15.5" fill="#F0F6FC" font-weight="600" text-anchor="start">Inside each dual-path block</text>
+<text x="261.5" y="288.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="15.5" fill="#A6AFBA" text-anchor="start">· every sub-layer is residual</text>
+<text x="64.0" y="356.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="21" fill="#F0F6FC" font-weight="600" text-anchor="middle">A</text>
+<text x="64.0" y="374.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="12.5" fill="#A6AFBA" text-anchor="middle">attention</text>
+<path d="M94.0,354.0 L124.7,354.0" fill="none" stroke="#A6AFBA" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M130.0,354.0 L121.5,357.2 L123.9,354.0 L121.5,350.8 Z" fill="#A6AFBA"/>
+<rect x="130.0" y="328.0" width="173.8" height="52" rx="7" fill="#17442F"/>
+<text x="216.9" y="351.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="15.5" fill="#F0F6FC" font-weight="600" text-anchor="middle">time attention</text>
+<text x="216.9" y="370.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="13.5" fill="#D1D7E0" text-anchor="middle">along <tspan font-style="italic">T</tspan>, in each band</text>
+<path d="M303.8,354.0 L315.5,354.0" fill="none" stroke="#A6AFBA" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M320.8,354.0 L312.3,357.2 L314.7,354.0 L312.3,350.8 Z" fill="#A6AFBA"/>
+<circle cx="112.0" cy="354.0" r="2.6" fill="#A6AFBA"/>
+<path d="M112.0,354.0 L112.0,322.0 Q112.0,315.0 119.0,315.0 L324.8,315.0 Q331.8,315.0 331.8,322.0 L331.8,337.7" fill="none" stroke="#A6AFBA" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M331.8,343.0 L328.6,334.5 L331.8,336.9 L335.1,334.5 Z" fill="#A6AFBA"/>
+<circle cx="331.8" cy="354.0" r="11" fill="#0D1117" stroke="#A6AFBA" stroke-width="1.4"/>
+<path d="M326.1,354.0 H337.5 M331.8,348.3 V359.7" stroke="#A6AFBA" stroke-width="1.4" stroke-linecap="round"/>
+<path d="M342.8,354.0 L371.5,354.0" fill="none" stroke="#A6AFBA" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M376.8,354.0 L368.3,357.2 L370.7,354.0 L368.3,350.8 Z" fill="#A6AFBA"/>
+<rect x="376.8" y="328.0" width="173.8" height="52" rx="7" fill="#17442F"/>
+<text x="463.7" y="351.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="15.5" fill="#F0F6FC" font-weight="600" text-anchor="middle">band attention</text>
+<text x="463.7" y="370.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="13.5" fill="#D1D7E0" text-anchor="middle">across <tspan font-style="italic">B</tspan>, in each frame</text>
+<path d="M550.6,354.0 L562.3,354.0" fill="none" stroke="#A6AFBA" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M567.6,354.0 L559.1,357.2 L561.5,354.0 L559.1,350.8 Z" fill="#A6AFBA"/>
+<circle cx="358.8" cy="354.0" r="2.6" fill="#A6AFBA"/>
+<path d="M358.8,354.0 L358.8,322.0 Q358.8,315.0 365.8,315.0 L571.6,315.0 Q578.6,315.0 578.6,322.0 L578.6,337.7" fill="none" stroke="#A6AFBA" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M578.6,343.0 L575.4,334.5 L578.6,336.9 L581.9,334.5 Z" fill="#A6AFBA"/>
+<circle cx="578.6" cy="354.0" r="11" fill="#0D1117" stroke="#A6AFBA" stroke-width="1.4"/>
+<path d="M572.9,354.0 H584.3 M578.6,348.3 V359.7" stroke="#A6AFBA" stroke-width="1.4" stroke-linecap="round"/>
+<path d="M589.6,354.0 L614.3,354.0" fill="none" stroke="#A6AFBA" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M619.6,354.0 L611.1,357.2 L613.5,354.0 L611.1,350.8 Z" fill="#A6AFBA"/>
+<text x="631.6" y="359.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="14.5" fill="#D1D7E0" text-anchor="start">rotary positions · exclusive self-attention · 8 heads</text>
+<text x="64.0" y="434.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="21" fill="#F0F6FC" font-weight="600" text-anchor="middle">M</text>
+<text x="64.0" y="452.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="12.5" fill="#A6AFBA" text-anchor="middle">Mamba</text>
+<path d="M94.0,432.0 L124.7,432.0" fill="none" stroke="#A6AFBA" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M130.0,432.0 L121.5,435.2 L123.9,432.0 L121.5,428.8 Z" fill="#A6AFBA"/>
+<rect x="130.0" y="406.0" width="173.8" height="52" rx="7" fill="#17442F"/>
+<text x="216.9" y="429.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="15.5" fill="#F0F6FC" font-weight="600" text-anchor="middle">time Mamba</text>
+<text x="216.9" y="448.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="13.5" fill="#D1D7E0" text-anchor="middle">along <tspan font-style="italic">T</tspan>, in each band</text>
+<path d="M303.8,432.0 L315.5,432.0" fill="none" stroke="#A6AFBA" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M320.8,432.0 L312.3,435.2 L314.7,432.0 L312.3,428.8 Z" fill="#A6AFBA"/>
+<circle cx="112.0" cy="432.0" r="2.6" fill="#A6AFBA"/>
+<path d="M112.0,432.0 L112.0,400.0 Q112.0,393.0 119.0,393.0 L324.8,393.0 Q331.8,393.0 331.8,400.0 L331.8,415.7" fill="none" stroke="#A6AFBA" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M331.8,421.0 L328.6,412.5 L331.8,414.9 L335.1,412.5 Z" fill="#A6AFBA"/>
+<circle cx="331.8" cy="432.0" r="11" fill="#0D1117" stroke="#A6AFBA" stroke-width="1.4"/>
+<path d="M326.1,432.0 H337.5 M331.8,426.3 V437.7" stroke="#A6AFBA" stroke-width="1.4" stroke-linecap="round"/>
+<path d="M342.8,432.0 L371.5,432.0" fill="none" stroke="#A6AFBA" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M376.8,432.0 L368.3,435.2 L370.7,432.0 L368.3,428.8 Z" fill="#A6AFBA"/>
+<rect x="376.8" y="406.0" width="173.8" height="52" rx="7" fill="#17442F"/>
+<text x="463.7" y="429.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="15.5" fill="#F0F6FC" font-weight="600" text-anchor="middle">band Mamba</text>
+<text x="463.7" y="448.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="13.5" fill="#D1D7E0" text-anchor="middle">across <tspan font-style="italic">B</tspan>, in each frame</text>
+<path d="M550.6,432.0 L562.3,432.0" fill="none" stroke="#A6AFBA" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M567.6,432.0 L559.1,435.2 L561.5,432.0 L559.1,428.8 Z" fill="#A6AFBA"/>
+<circle cx="358.8" cy="432.0" r="2.6" fill="#A6AFBA"/>
+<path d="M358.8,432.0 L358.8,400.0 Q358.8,393.0 365.8,393.0 L571.6,393.0 Q578.6,393.0 578.6,400.0 L578.6,415.7" fill="none" stroke="#A6AFBA" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M578.6,421.0 L575.4,412.5 L578.6,414.9 L581.9,412.5 Z" fill="#A6AFBA"/>
+<circle cx="578.6" cy="432.0" r="11" fill="#0D1117" stroke="#A6AFBA" stroke-width="1.4"/>
+<path d="M572.9,432.0 H584.3 M578.6,426.3 V437.7" stroke="#A6AFBA" stroke-width="1.4" stroke-linecap="round"/>
+<path d="M589.6,432.0 L614.3,432.0" fill="none" stroke="#A6AFBA" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M619.6,432.0 L611.1,435.2 L613.5,432.0 L611.1,428.8 Z" fill="#A6AFBA"/>
+<text x="631.6" y="437.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="14.5" fill="#D1D7E0" text-anchor="start">selective scan · state 16 · expand 2 · conv 4</text>
+<text x="24.0" y="506.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="14.5" fill="#D1D7E0" text-anchor="start"><tspan font-weight="600">Realtime checkpoint:</tspan> the same blocks run causally, with a look-ahead <tspan font-style="italic">ℓ</tspan> ∈ {0, 2, 4} frames as a learned embedding.</text>
+<text x="24.0" y="529.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="14.5" fill="#D1D7E0" text-anchor="start"><tspan font-weight="600">Offline checkpoint:</tspan> two-sided, 8 s chunks.</text>
+</svg>
diff --git a/docs/assets/architecture-light.svg b/docs/assets/architecture-light.svg
new file mode 100644
index 0000000..5779b56
--- /dev/null
+++ b/docs/assets/architecture-light.svg
@@ -0,0 +1,115 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="1040" height="551" viewBox="0 0 1040 551" role="img" aria-label="Inworld Voice Isolator architecture">
+<desc>Input x(t), 48 kHz mono. STFT with N = 2048 and hop H = 480 (10 ms) gives X in C^(F x T), F = 1025 bins. Band split into B = 46 bands, 100 Hz to 2 kHz wide, each projected to D = 512, gives Z in R^(B x T x D). Seven dual-path blocks, alternating A, M, A, M, A, M, A: block A is time attention (rotary positions, exclusive self-attention, 8 heads) then band attention; block M is time Mamba (state 16, expand 2, conv 4) then band Mamba; the time path runs along time within each band, the band path across bands within each frame; every sub-layer has a residual connection. Per-band linear heads produce a bounded complex mask M and a bounded residual R, both in C^(F x T). Output spectrum X_hat = X + M (.) X + R, from the input spectrum X through a skip connection; iSTFT gives the isolated voice s_hat(t). The realtime checkpoint runs the same blocks causally with a look-ahead of 0, 2 or 4 frames as a learned embedding; the offline checkpoint is two-sided and renders 8 s chunks.</desc>
+<rect width="100%" height="100%" fill="#FFFFFF"/>
+<path d="M24.0,124.0 L72.7,124.0" fill="none" stroke="#59636E" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M78.0,124.0 L69.5,127.2 L71.9,124.0 L69.5,120.8 Z" fill="#59636E"/>
+<text x="47.0" y="114.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="19" fill="#1F2328" text-anchor="middle"><tspan font-style="italic">x</tspan>(<tspan font-style="italic">t</tspan>)</text>
+<text x="47.0" y="148.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="13.5" fill="#59636E" text-anchor="middle">48 kHz</text>
+<path d="M962.0,124.0 L1010.7,124.0" fill="none" stroke="#59636E" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M1016.0,124.0 L1007.5,127.2 L1009.9,124.0 L1007.5,120.8 Z" fill="#59636E"/>
+<text x="991.0" y="114.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="19" fill="#1F2328" text-anchor="middle"><tspan font-style="italic">ŝ</tspan>(<tspan font-style="italic">t</tspan>)</text>
+<text x="991.0" y="148.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="13.5" fill="#59636E" text-anchor="middle">48 kHz</text>
+<rect x="78.0" y="66" width="132.5" height="116" rx="8" fill="#DCE8F6"/>
+<text x="144.2" y="97.5" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="17.5" fill="#1F2328" font-weight="600" text-anchor="middle">STFT</text>
+<text x="144.2" y="121.5" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="15" fill="#3D444D" text-anchor="middle"><tspan font-style="italic">N</tspan> = 2048</text>
+<text x="144.2" y="142.5" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="15" fill="#3D444D" text-anchor="middle"><tspan font-style="italic">H</tspan> = 480 (10 ms)</text>
+<text x="144.2" y="163.5" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="15" fill="#3D444D" text-anchor="middle"><tspan font-style="italic">F</tspan> = 1025 bins</text>
+<rect x="242.4" y="66" width="154.6" height="116" rx="8" fill="#D7EEDF"/>
+<text x="319.7" y="97.5" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="17.5" fill="#1F2328" font-weight="600" text-anchor="middle">Band split</text>
+<text x="319.7" y="121.5" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="15" fill="#3D444D" text-anchor="middle"><tspan font-style="italic">B</tspan> = 46 bands</text>
+<text x="319.7" y="142.5" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="15" fill="#3D444D" text-anchor="middle">100 Hz–2 kHz wide</text>
+<text x="319.7" y="163.5" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="15" fill="#3D444D" text-anchor="middle">linear to <tspan font-style="italic">D</tspan> = 512</text>
+<rect x="428.9" y="66" width="180.9" height="116" rx="8" fill="#D7EEDF"/>
+<text x="519.4" y="108.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="17.5" fill="#1F2328" font-weight="600" text-anchor="middle">7 dual-path blocks</text>
+<text x="519.4" y="132.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="15" fill="#3D444D" text-anchor="middle">A M A M A M A</text>
+<text x="519.4" y="153.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="15" fill="#3D444D" text-anchor="middle">attention, Mamba</text>
+<rect x="641.7" y="66" width="157.8" height="116" rx="8" fill="#F8E5C2"/>
+<text x="720.6" y="108.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="17.5" fill="#1F2328" font-weight="600" text-anchor="middle">Per-band heads</text>
+<text x="720.6" y="132.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="15" fill="#3D444D" text-anchor="middle">mask <tspan font-style="italic">M</tspan>, bounded</text>
+<text x="720.6" y="153.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="15" fill="#3D444D" text-anchor="middle">residual <tspan font-style="italic">R</tspan>, |<tspan font-style="italic">R</tspan>| ≤ 0.5</text>
+<rect x="889.4" y="66" width="72.6" height="116" rx="8" fill="#DCE8F6"/>
+<text x="925.7" y="129.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="17.5" fill="#1F2328" font-weight="600" text-anchor="middle">iSTFT</text>
+<path d="M211.5,124.0 L236.1,124.0" fill="none" stroke="#59636E" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M241.4,124.0 L232.9,127.2 L235.3,124.0 L232.9,120.8 Z" fill="#59636E"/>
+<text x="226.5" y="50.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="16" fill="#1F2328" text-anchor="middle"><tspan font-style="italic">X</tspan> ∈ ℂ<tspan dy="-6.40" font-size="11.52" font-style="italic">F</tspan><tspan font-size="11.52">×</tspan><tspan font-size="11.52" font-style="italic">T</tspan></text>
+<path d="M398.0,124.0 L422.7,124.0" fill="none" stroke="#59636E" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M427.9,124.0 L419.4,127.2 L421.8,124.0 L419.4,120.8 Z" fill="#59636E"/>
+<text x="413.0" y="50.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="16" fill="#1F2328" text-anchor="middle"><tspan font-style="italic">Z</tspan> ∈ ℝ<tspan dy="-6.40" font-size="11.52" font-style="italic">B</tspan><tspan font-size="11.52">×</tspan><tspan font-size="11.52" font-style="italic">T</tspan><tspan font-size="11.52">×</tspan><tspan font-size="11.52" font-style="italic">D</tspan></text>
+<path d="M610.8,124.0 L635.4,124.0" fill="none" stroke="#59636E" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M640.7,124.0 L632.2,127.2 L634.6,124.0 L632.2,120.8 Z" fill="#59636E"/>
+<text x="625.7" y="50.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="16" fill="#1F2328" text-anchor="middle"><tspan font-style="italic">Z</tspan>′ ∈ ℝ<tspan dy="-6.40" font-size="11.52" font-style="italic">B</tspan><tspan font-size="11.52">×</tspan><tspan font-size="11.52" font-style="italic">T</tspan><tspan font-size="11.52">×</tspan><tspan font-size="11.52" font-style="italic">D</tspan></text>
+<path d="M800.5,124.0 L825.2,124.0" fill="none" stroke="#59636E" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M830.5,124.0 L822.0,127.2 L824.3,124.0 L822.0,120.8 Z" fill="#59636E"/>
+<path d="M858.5,124.0 L883.1,124.0" fill="none" stroke="#59636E" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M888.4,124.0 L879.9,127.2 L882.3,124.0 L879.9,120.8 Z" fill="#59636E"/>
+<circle cx="844.5" cy="124.0" r="13" fill="#FFFFFF" stroke="#59636E" stroke-width="1.4"/>
+<path d="M837.7,124.0 H851.2 M844.5,117.2 V130.8" stroke="#59636E" stroke-width="1.4" stroke-linecap="round"/>
+<text x="844.5" y="50.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="16" fill="#1F2328" text-anchor="middle"><tspan font-style="italic">X̂</tspan> = <tspan font-style="italic">X</tspan> + <tspan font-style="italic">M</tspan> ⊙ <tspan font-style="italic">X</tspan> + <tspan font-style="italic">R</tspan></text>
+<circle cx="226.5" cy="124.0" r="3.4" fill="#59636E"/>
+<path d="M226.5,124.0 L226.5,196.0 Q226.5,206.0 236.5,206.0 L834.5,206.0 Q844.5,206.0 844.5,196.0 L844.5,142.3" fill="none" stroke="#59636E" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="5 4"/>
+<path d="M844.5,137.0 L847.7,145.5 L844.5,143.1 L841.2,145.5 Z" fill="#59636E"/>
+<text x="535.5" y="226.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="13.5" fill="#59636E" text-anchor="middle">skip: the input spectrum <tspan font-style="italic">X</tspan></text>
+<rect x="24" y="256" width="992" height="214" rx="12" fill="#F6F8FA"/>
+<text x="46.0" y="288.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="15.5" fill="#1F2328" font-weight="600" text-anchor="start">Inside each dual-path block</text>
+<text x="261.5" y="288.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="15.5" fill="#59636E" text-anchor="start">· every sub-layer is residual</text>
+<text x="64.0" y="356.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="21" fill="#1F2328" font-weight="600" text-anchor="middle">A</text>
+<text x="64.0" y="374.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="12.5" fill="#59636E" text-anchor="middle">attention</text>
+<path d="M94.0,354.0 L124.7,354.0" fill="none" stroke="#59636E" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M130.0,354.0 L121.5,357.2 L123.9,354.0 L121.5,350.8 Z" fill="#59636E"/>
+<rect x="130.0" y="328.0" width="173.8" height="52" rx="7" fill="#D7EEDF"/>
+<text x="216.9" y="351.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="15.5" fill="#1F2328" font-weight="600" text-anchor="middle">time attention</text>
+<text x="216.9" y="370.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="13.5" fill="#3D444D" text-anchor="middle">along <tspan font-style="italic">T</tspan>, in each band</text>
+<path d="M303.8,354.0 L315.5,354.0" fill="none" stroke="#59636E" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M320.8,354.0 L312.3,357.2 L314.7,354.0 L312.3,350.8 Z" fill="#59636E"/>
+<circle cx="112.0" cy="354.0" r="2.6" fill="#59636E"/>
+<path d="M112.0,354.0 L112.0,322.0 Q112.0,315.0 119.0,315.0 L324.8,315.0 Q331.8,315.0 331.8,322.0 L331.8,337.7" fill="none" stroke="#59636E" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M331.8,343.0 L328.6,334.5 L331.8,336.9 L335.1,334.5 Z" fill="#59636E"/>
+<circle cx="331.8" cy="354.0" r="11" fill="#FFFFFF" stroke="#59636E" stroke-width="1.4"/>
+<path d="M326.1,354.0 H337.5 M331.8,348.3 V359.7" stroke="#59636E" stroke-width="1.4" stroke-linecap="round"/>
+<path d="M342.8,354.0 L371.5,354.0" fill="none" stroke="#59636E" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M376.8,354.0 L368.3,357.2 L370.7,354.0 L368.3,350.8 Z" fill="#59636E"/>
+<rect x="376.8" y="328.0" width="173.8" height="52" rx="7" fill="#D7EEDF"/>
+<text x="463.7" y="351.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="15.5" fill="#1F2328" font-weight="600" text-anchor="middle">band attention</text>
+<text x="463.7" y="370.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="13.5" fill="#3D444D" text-anchor="middle">across <tspan font-style="italic">B</tspan>, in each frame</text>
+<path d="M550.6,354.0 L562.3,354.0" fill="none" stroke="#59636E" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M567.6,354.0 L559.1,357.2 L561.5,354.0 L559.1,350.8 Z" fill="#59636E"/>
+<circle cx="358.8" cy="354.0" r="2.6" fill="#59636E"/>
+<path d="M358.8,354.0 L358.8,322.0 Q358.8,315.0 365.8,315.0 L571.6,315.0 Q578.6,315.0 578.6,322.0 L578.6,337.7" fill="none" stroke="#59636E" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M578.6,343.0 L575.4,334.5 L578.6,336.9 L581.9,334.5 Z" fill="#59636E"/>
+<circle cx="578.6" cy="354.0" r="11" fill="#FFFFFF" stroke="#59636E" stroke-width="1.4"/>
+<path d="M572.9,354.0 H584.3 M578.6,348.3 V359.7" stroke="#59636E" stroke-width="1.4" stroke-linecap="round"/>
+<path d="M589.6,354.0 L614.3,354.0" fill="none" stroke="#59636E" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M619.6,354.0 L611.1,357.2 L613.5,354.0 L611.1,350.8 Z" fill="#59636E"/>
+<text x="631.6" y="359.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="14.5" fill="#3D444D" text-anchor="start">rotary positions · exclusive self-attention · 8 heads</text>
+<text x="64.0" y="434.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="21" fill="#1F2328" font-weight="600" text-anchor="middle">M</text>
+<text x="64.0" y="452.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="12.5" fill="#59636E" text-anchor="middle">Mamba</text>
+<path d="M94.0,432.0 L124.7,432.0" fill="none" stroke="#59636E" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M130.0,432.0 L121.5,435.2 L123.9,432.0 L121.5,428.8 Z" fill="#59636E"/>
+<rect x="130.0" y="406.0" width="173.8" height="52" rx="7" fill="#D7EEDF"/>
+<text x="216.9" y="429.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="15.5" fill="#1F2328" font-weight="600" text-anchor="middle">time Mamba</text>
+<text x="216.9" y="448.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="13.5" fill="#3D444D" text-anchor="middle">along <tspan font-style="italic">T</tspan>, in each band</text>
+<path d="M303.8,432.0 L315.5,432.0" fill="none" stroke="#59636E" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M320.8,432.0 L312.3,435.2 L314.7,432.0 L312.3,428.8 Z" fill="#59636E"/>
+<circle cx="112.0" cy="432.0" r="2.6" fill="#59636E"/>
+<path d="M112.0,432.0 L112.0,400.0 Q112.0,393.0 119.0,393.0 L324.8,393.0 Q331.8,393.0 331.8,400.0 L331.8,415.7" fill="none" stroke="#59636E" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M331.8,421.0 L328.6,412.5 L331.8,414.9 L335.1,412.5 Z" fill="#59636E"/>
+<circle cx="331.8" cy="432.0" r="11" fill="#FFFFFF" stroke="#59636E" stroke-width="1.4"/>
+<path d="M326.1,432.0 H337.5 M331.8,426.3 V437.7" stroke="#59636E" stroke-width="1.4" stroke-linecap="round"/>
+<path d="M342.8,432.0 L371.5,432.0" fill="none" stroke="#59636E" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M376.8,432.0 L368.3,435.2 L370.7,432.0 L368.3,428.8 Z" fill="#59636E"/>
+<rect x="376.8" y="406.0" width="173.8" height="52" rx="7" fill="#D7EEDF"/>
+<text x="463.7" y="429.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="15.5" fill="#1F2328" font-weight="600" text-anchor="middle">band Mamba</text>
+<text x="463.7" y="448.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="13.5" fill="#3D444D" text-anchor="middle">across <tspan font-style="italic">B</tspan>, in each frame</text>
+<path d="M550.6,432.0 L562.3,432.0" fill="none" stroke="#59636E" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M567.6,432.0 L559.1,435.2 L561.5,432.0 L559.1,428.8 Z" fill="#59636E"/>
+<circle cx="358.8" cy="432.0" r="2.6" fill="#59636E"/>
+<path d="M358.8,432.0 L358.8,400.0 Q358.8,393.0 365.8,393.0 L571.6,393.0 Q578.6,393.0 578.6,400.0 L578.6,415.7" fill="none" stroke="#59636E" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M578.6,421.0 L575.4,412.5 L578.6,414.9 L581.9,412.5 Z" fill="#59636E"/>
+<circle cx="578.6" cy="432.0" r="11" fill="#FFFFFF" stroke="#59636E" stroke-width="1.4"/>
+<path d="M572.9,432.0 H584.3 M578.6,426.3 V437.7" stroke="#59636E" stroke-width="1.4" stroke-linecap="round"/>
+<path d="M589.6,432.0 L614.3,432.0" fill="none" stroke="#59636E" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M619.6,432.0 L611.1,435.2 L613.5,432.0 L611.1,428.8 Z" fill="#59636E"/>
+<text x="631.6" y="437.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="14.5" fill="#3D444D" text-anchor="start">selective scan · state 16 · expand 2 · conv 4</text>
+<text x="24.0" y="506.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="14.5" fill="#3D444D" text-anchor="start"><tspan font-weight="600">Realtime checkpoint:</tspan> the same blocks run causally, with a look-ahead <tspan font-style="italic">ℓ</tspan> ∈ {0, 2, 4} frames as a learned embedding.</text>
+<text x="24.0" y="529.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="14.5" fill="#3D444D" text-anchor="start"><tspan font-weight="600">Offline checkpoint:</tspan> two-sided, 8 s chunks.</text>
+</svg>
diff --git a/docs/assets/board-dark.svg b/docs/assets/board-dark.svg
new file mode 100644
index 0000000..3de78cc
--- /dev/null
+++ b/docs/assets/board-dark.svg
@@ -0,0 +1,34 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="1040" height="356" viewBox="0 0 1040 356" role="img" aria-label="Inworld VIBE full-band tier, denoising score per system">
+<rect width="100%" height="100%" fill="#0D1117"/>
+<text x="28.0" y="36.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="16" font-weight="normal" fill="#B4AFA3" text-anchor="start">Denoising score, higher is better. Gaps under 0.03 are ties.</text>
+<line x1="330.0" y1="66.0" x2="330.0" y2="290.0" stroke="#30363D" stroke-width="1"/>
+<text x="330.0" y="308.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="13.5" font-weight="normal" fill="#89857C" text-anchor="middle">0</text>
+<line x1="486.5" y1="66.0" x2="486.5" y2="290.0" stroke="#30363D" stroke-width="1"/>
+<text x="486.5" y="308.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="13.5" font-weight="normal" fill="#89857C" text-anchor="middle">0.25</text>
+<line x1="643.0" y1="66.0" x2="643.0" y2="290.0" stroke="#30363D" stroke-width="1"/>
+<text x="643.0" y="308.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="13.5" font-weight="normal" fill="#89857C" text-anchor="middle">0.5</text>
+<line x1="799.5" y1="66.0" x2="799.5" y2="290.0" stroke="#30363D" stroke-width="1"/>
+<text x="799.5" y="308.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="13.5" font-weight="normal" fill="#89857C" text-anchor="middle">0.75</text>
+<line x1="956.0" y1="66.0" x2="956.0" y2="290.0" stroke="#30363D" stroke-width="1"/>
+<text x="956.0" y="308.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="13.5" font-weight="normal" fill="#89857C" text-anchor="middle">1</text>
+<path d="M330.0,81.0 h476.5 a4,4 0 0 1 4,4 v14 a4,4 0 0 1 -4,4 h-476.5 z" fill="#1A9B58"/>
+<text x="316.0" y="98.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="16" font-weight="normal" fill="#EEEAE0" text-anchor="end">Inworld Voice Isolator</text>
+<text x="818.5" y="98.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="15" font-weight="600" fill="#EEEAE0" text-anchor="start">0.768</text>
+<path d="M330.0,117.0 h445.3 a4,4 0 0 1 4,4 v14 a4,4 0 0 1 -4,4 h-445.3 z" fill="#1A9B58"/>
+<text x="316.0" y="134.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="16" font-weight="normal" fill="#EEEAE0" text-anchor="end">Inworld Voice Isolator realtime*</text>
+<text x="787.3" y="134.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="15" font-weight="600" fill="#EEEAE0" text-anchor="start">0.718</text>
+<path d="M330.0,153.0 h430.9 a4,4 0 0 1 4,4 v14 a4,4 0 0 1 -4,4 h-430.9 z" fill="#9A9089"/>
+<text x="316.0" y="170.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="16" font-weight="normal" fill="#EEEAE0" text-anchor="end">ClearerVoice MossFormer2_SE_48K</text>
+<text x="772.9" y="170.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="15" font-weight="600" fill="#EEEAE0" text-anchor="start">0.695</text>
+<path d="M330.0,189.0 h400.5 a4,4 0 0 1 4,4 v14 a4,4 0 0 1 -4,4 h-400.5 z" fill="#9A9089"/>
+<text x="316.0" y="206.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="16" font-weight="normal" fill="#EEEAE0" text-anchor="end">resemble-enhance</text>
+<text x="742.5" y="206.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="15" font-weight="600" fill="#EEEAE0" text-anchor="start">0.646</text>
+<path d="M330.0,225.0 h365.0 a4,4 0 0 1 4,4 v14 a4,4 0 0 1 -4,4 h-365.0 z" fill="#9A9089"/>
+<text x="316.0" y="242.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="16" font-weight="normal" fill="#EEEAE0" text-anchor="end">FastEnhancer-L 48k*</text>
+<text x="707.0" y="242.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="15" font-weight="600" fill="#EEEAE0" text-anchor="start">0.589</text>
+<path d="M330.0,261.0 h315.1 a4,4 0 0 1 4,4 v14 a4,4 0 0 1 -4,4 h-315.1 z" fill="#9A9089"/>
+<text x="316.0" y="278.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="16" font-weight="normal" fill="#EEEAE0" text-anchor="end">DeepFilterNet3*</text>
+<text x="657.1" y="278.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="15" font-weight="600" fill="#EEEAE0" text-anchor="start">0.510</text>
+<text x="28.0" y="334.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="13.5" font-weight="normal" fill="#89857C" text-anchor="start">* streaming</text>
+<text x="1012.0" y="334.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="13" font-weight="normal" fill="#89857C" text-anchor="end">Inworld VIBE v0 · set build f5a6420d67b7ef45…</text>
+</svg>
diff --git a/docs/assets/board-light.svg b/docs/assets/board-light.svg
new file mode 100644
index 0000000..20109b4
--- /dev/null
+++ b/docs/assets/board-light.svg
@@ -0,0 +1,34 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="1040" height="356" viewBox="0 0 1040 356" role="img" aria-label="Inworld VIBE full-band tier, denoising score per system">
+<rect width="100%" height="100%" fill="#FFFFFF"/>
+<text x="28.0" y="36.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="16" font-weight="normal" fill="#57534B" text-anchor="start">Denoising score, higher is better. Gaps under 0.03 are ties.</text>
+<line x1="330.0" y1="66.0" x2="330.0" y2="290.0" stroke="#D7D2CC" stroke-width="1"/>
+<text x="330.0" y="308.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="13.5" font-weight="normal" fill="#69665E" text-anchor="middle">0</text>
+<line x1="486.5" y1="66.0" x2="486.5" y2="290.0" stroke="#D7D2CC" stroke-width="1"/>
+<text x="486.5" y="308.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="13.5" font-weight="normal" fill="#69665E" text-anchor="middle">0.25</text>
+<line x1="643.0" y1="66.0" x2="643.0" y2="290.0" stroke="#D7D2CC" stroke-width="1"/>
+<text x="643.0" y="308.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="13.5" font-weight="normal" fill="#69665E" text-anchor="middle">0.5</text>
+<line x1="799.5" y1="66.0" x2="799.5" y2="290.0" stroke="#D7D2CC" stroke-width="1"/>
+<text x="799.5" y="308.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="13.5" font-weight="normal" fill="#69665E" text-anchor="middle">0.75</text>
+<line x1="956.0" y1="66.0" x2="956.0" y2="290.0" stroke="#D7D2CC" stroke-width="1"/>
+<text x="956.0" y="308.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="13.5" font-weight="normal" fill="#69665E" text-anchor="middle">1</text>
+<path d="M330.0,81.0 h476.5 a4,4 0 0 1 4,4 v14 a4,4 0 0 1 -4,4 h-476.5 z" fill="#02793D"/>
+<text x="316.0" y="98.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="16" font-weight="normal" fill="#151613" text-anchor="end">Inworld Voice Isolator</text>
+<text x="818.5" y="98.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="15" font-weight="600" fill="#151613" text-anchor="start">0.768</text>
+<path d="M330.0,117.0 h445.3 a4,4 0 0 1 4,4 v14 a4,4 0 0 1 -4,4 h-445.3 z" fill="#02793D"/>
+<text x="316.0" y="134.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="16" font-weight="normal" fill="#151613" text-anchor="end">Inworld Voice Isolator realtime*</text>
+<text x="787.3" y="134.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="15" font-weight="600" fill="#151613" text-anchor="start">0.718</text>
+<path d="M330.0,153.0 h430.9 a4,4 0 0 1 4,4 v14 a4,4 0 0 1 -4,4 h-430.9 z" fill="#9A9089"/>
+<text x="316.0" y="170.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="16" font-weight="normal" fill="#151613" text-anchor="end">ClearerVoice MossFormer2_SE_48K</text>
+<text x="772.9" y="170.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="15" font-weight="600" fill="#151613" text-anchor="start">0.695</text>
+<path d="M330.0,189.0 h400.5 a4,4 0 0 1 4,4 v14 a4,4 0 0 1 -4,4 h-400.5 z" fill="#9A9089"/>
+<text x="316.0" y="206.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="16" font-weight="normal" fill="#151613" text-anchor="end">resemble-enhance</text>
+<text x="742.5" y="206.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="15" font-weight="600" fill="#151613" text-anchor="start">0.646</text>
+<path d="M330.0,225.0 h365.0 a4,4 0 0 1 4,4 v14 a4,4 0 0 1 -4,4 h-365.0 z" fill="#9A9089"/>
+<text x="316.0" y="242.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="16" font-weight="normal" fill="#151613" text-anchor="end">FastEnhancer-L 48k*</text>
+<text x="707.0" y="242.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="15" font-weight="600" fill="#151613" text-anchor="start">0.589</text>
+<path d="M330.0,261.0 h315.1 a4,4 0 0 1 4,4 v14 a4,4 0 0 1 -4,4 h-315.1 z" fill="#9A9089"/>
+<text x="316.0" y="278.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="16" font-weight="normal" fill="#151613" text-anchor="end">DeepFilterNet3*</text>
+<text x="657.1" y="278.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="15" font-weight="600" fill="#151613" text-anchor="start">0.510</text>
+<text x="28.0" y="334.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="13.5" font-weight="normal" fill="#69665E" text-anchor="start">* streaming</text>
+<text x="1012.0" y="334.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="13" font-weight="normal" fill="#69665E" text-anchor="end">Inworld VIBE v0 · set build f5a6420d67b7ef45…</text>
+</svg>
diff --git a/docs/assets/board-restoration-dark.svg b/docs/assets/board-restoration-dark.svg
new file mode 100644
index 0000000..249470c
--- /dev/null
+++ b/docs/assets/board-restoration-dark.svg
@@ -0,0 +1,36 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="1040" height="392" viewBox="0 0 1040 392" role="img" aria-label="Inworld VIBE full-band tier, restoration score per system">
+<rect width="100%" height="100%" fill="#0D1117"/>
+<text x="28.0" y="36.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="16" font-weight="normal" fill="#B4AFA3" text-anchor="start">Restoration score, higher is better. Gaps under 0.03 are ties.</text>
+<line x1="330.0" y1="66.0" x2="330.0" y2="326.0" stroke="#30363D" stroke-width="1"/>
+<text x="330.0" y="344.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="13.5" font-weight="normal" fill="#89857C" text-anchor="middle">0</text>
+<line x1="486.5" y1="66.0" x2="486.5" y2="326.0" stroke="#30363D" stroke-width="1"/>
+<text x="486.5" y="344.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="13.5" font-weight="normal" fill="#89857C" text-anchor="middle">0.25</text>
+<line x1="643.0" y1="66.0" x2="643.0" y2="326.0" stroke="#30363D" stroke-width="1"/>
+<text x="643.0" y="344.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="13.5" font-weight="normal" fill="#89857C" text-anchor="middle">0.5</text>
+<line x1="799.5" y1="66.0" x2="799.5" y2="326.0" stroke="#30363D" stroke-width="1"/>
+<text x="799.5" y="344.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="13.5" font-weight="normal" fill="#89857C" text-anchor="middle">0.75</text>
+<line x1="956.0" y1="66.0" x2="956.0" y2="326.0" stroke="#30363D" stroke-width="1"/>
+<text x="956.0" y="344.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="13.5" font-weight="normal" fill="#89857C" text-anchor="middle">1</text>
+<path d="M330.0,81.0 h583.3 a4,4 0 0 1 4,4 v14 a4,4 0 0 1 -4,4 h-583.3 z" fill="#9A9089"/>
+<text x="316.0" y="98.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="16" font-weight="normal" fill="#EEEAE0" text-anchor="end">NVIDIA NemotronLabs RE-USE-laughter</text>
+<text x="925.3" y="98.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="15" font-weight="600" fill="#EEEAE0" text-anchor="start">0.938</text>
+<path d="M330.0,117.0 h582.9 a4,4 0 0 1 4,4 v14 a4,4 0 0 1 -4,4 h-582.9 z" fill="#9A9089"/>
+<text x="316.0" y="134.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="16" font-weight="normal" fill="#EEEAE0" text-anchor="end">NVIDIA NemotronLabs RE-USE</text>
+<text x="924.9" y="134.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="15" font-weight="600" fill="#EEEAE0" text-anchor="start">0.937</text>
+<path d="M330.0,153.0 h541.9 a4,4 0 0 1 4,4 v14 a4,4 0 0 1 -4,4 h-541.9 z" fill="#9A9089"/>
+<text x="316.0" y="170.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="16" font-weight="normal" fill="#EEEAE0" text-anchor="end">UniPASE</text>
+<text x="883.9" y="170.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="15" font-weight="600" fill="#EEEAE0" text-anchor="start">0.872</text>
+<path d="M330.0,189.0 h366.7 a4,4 0 0 1 4,4 v14 a4,4 0 0 1 -4,4 h-366.7 z" fill="#9A9089"/>
+<text x="316.0" y="206.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="16" font-weight="normal" fill="#EEEAE0" text-anchor="end">GAP-URGENet</text>
+<text x="708.7" y="206.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="15" font-weight="600" fill="#EEEAE0" text-anchor="start">0.592</text>
+<path d="M330.0,225.0 h265.5 a4,4 0 0 1 4,4 v14 a4,4 0 0 1 -4,4 h-265.5 z" fill="#9A9089"/>
+<text x="316.0" y="242.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="16" font-weight="normal" fill="#EEEAE0" text-anchor="end">URGENT 2026 FlowSE baseline</text>
+<text x="607.5" y="242.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="15" font-weight="600" fill="#EEEAE0" text-anchor="start">0.431</text>
+<path d="M330.0,261.0 h183.0 a4,4 0 0 1 4,4 v14 a4,4 0 0 1 -4,4 h-183.0 z" fill="#9A9089"/>
+<text x="316.0" y="278.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="16" font-weight="normal" fill="#EEEAE0" text-anchor="end">URGENT 2026 BSRNN baseline</text>
+<text x="525.0" y="278.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="15" font-weight="600" fill="#EEEAE0" text-anchor="start">0.299</text>
+<path d="M330.0,297.0 h123.8 a4,4 0 0 1 4,4 v14 a4,4 0 0 1 -4,4 h-123.8 z" fill="#9A9089"/>
+<text x="316.0" y="314.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="16" font-weight="normal" fill="#EEEAE0" text-anchor="end">Smule Renaissance Small</text>
+<text x="465.8" y="314.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="15" font-weight="600" fill="#EEEAE0" text-anchor="start">0.204</text>
+<text x="1012.0" y="370.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="13" font-weight="normal" fill="#89857C" text-anchor="end">Inworld VIBE v0 · set build f5a6420d67b7ef45…</text>
+</svg>
diff --git a/docs/assets/board-restoration-light.svg b/docs/assets/board-restoration-light.svg
new file mode 100644
index 0000000..17a95cf
--- /dev/null
+++ b/docs/assets/board-restoration-light.svg
@@ -0,0 +1,36 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="1040" height="392" viewBox="0 0 1040 392" role="img" aria-label="Inworld VIBE full-band tier, restoration score per system">
+<rect width="100%" height="100%" fill="#FFFFFF"/>
+<text x="28.0" y="36.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="16" font-weight="normal" fill="#57534B" text-anchor="start">Restoration score, higher is better. Gaps under 0.03 are ties.</text>
+<line x1="330.0" y1="66.0" x2="330.0" y2="326.0" stroke="#D7D2CC" stroke-width="1"/>
+<text x="330.0" y="344.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="13.5" font-weight="normal" fill="#69665E" text-anchor="middle">0</text>
+<line x1="486.5" y1="66.0" x2="486.5" y2="326.0" stroke="#D7D2CC" stroke-width="1"/>
+<text x="486.5" y="344.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="13.5" font-weight="normal" fill="#69665E" text-anchor="middle">0.25</text>
+<line x1="643.0" y1="66.0" x2="643.0" y2="326.0" stroke="#D7D2CC" stroke-width="1"/>
+<text x="643.0" y="344.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="13.5" font-weight="normal" fill="#69665E" text-anchor="middle">0.5</text>
+<line x1="799.5" y1="66.0" x2="799.5" y2="326.0" stroke="#D7D2CC" stroke-width="1"/>
+<text x="799.5" y="344.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="13.5" font-weight="normal" fill="#69665E" text-anchor="middle">0.75</text>
+<line x1="956.0" y1="66.0" x2="956.0" y2="326.0" stroke="#D7D2CC" stroke-width="1"/>
+<text x="956.0" y="344.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="13.5" font-weight="normal" fill="#69665E" text-anchor="middle">1</text>
+<path d="M330.0,81.0 h583.3 a4,4 0 0 1 4,4 v14 a4,4 0 0 1 -4,4 h-583.3 z" fill="#9A9089"/>
+<text x="316.0" y="98.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="16" font-weight="normal" fill="#151613" text-anchor="end">NVIDIA NemotronLabs RE-USE-laughter</text>
+<text x="925.3" y="98.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="15" font-weight="600" fill="#151613" text-anchor="start">0.938</text>
+<path d="M330.0,117.0 h582.9 a4,4 0 0 1 4,4 v14 a4,4 0 0 1 -4,4 h-582.9 z" fill="#9A9089"/>
+<text x="316.0" y="134.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="16" font-weight="normal" fill="#151613" text-anchor="end">NVIDIA NemotronLabs RE-USE</text>
+<text x="924.9" y="134.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="15" font-weight="600" fill="#151613" text-anchor="start">0.937</text>
+<path d="M330.0,153.0 h541.9 a4,4 0 0 1 4,4 v14 a4,4 0 0 1 -4,4 h-541.9 z" fill="#9A9089"/>
+<text x="316.0" y="170.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="16" font-weight="normal" fill="#151613" text-anchor="end">UniPASE</text>
+<text x="883.9" y="170.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="15" font-weight="600" fill="#151613" text-anchor="start">0.872</text>
+<path d="M330.0,189.0 h366.7 a4,4 0 0 1 4,4 v14 a4,4 0 0 1 -4,4 h-366.7 z" fill="#9A9089"/>
+<text x="316.0" y="206.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="16" font-weight="normal" fill="#151613" text-anchor="end">GAP-URGENet</text>
+<text x="708.7" y="206.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="15" font-weight="600" fill="#151613" text-anchor="start">0.592</text>
+<path d="M330.0,225.0 h265.5 a4,4 0 0 1 4,4 v14 a4,4 0 0 1 -4,4 h-265.5 z" fill="#9A9089"/>
+<text x="316.0" y="242.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="16" font-weight="normal" fill="#151613" text-anchor="end">URGENT 2026 FlowSE baseline</text>
+<text x="607.5" y="242.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="15" font-weight="600" fill="#151613" text-anchor="start">0.431</text>
+<path d="M330.0,261.0 h183.0 a4,4 0 0 1 4,4 v14 a4,4 0 0 1 -4,4 h-183.0 z" fill="#9A9089"/>
+<text x="316.0" y="278.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="16" font-weight="normal" fill="#151613" text-anchor="end">URGENT 2026 BSRNN baseline</text>
+<text x="525.0" y="278.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="15" font-weight="600" fill="#151613" text-anchor="start">0.299</text>
+<path d="M330.0,297.0 h123.8 a4,4 0 0 1 4,4 v14 a4,4 0 0 1 -4,4 h-123.8 z" fill="#9A9089"/>
+<text x="316.0" y="314.0" font-family="Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif" font-size="16" font-weight="normal" fill="#151613" text-anchor="end">Smule Renaissance Small</text>
+<text x="465.8" y="314.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="15" font-weight="600" fill="#151613" text-anchor="start">0.204</text>
+<text x="1012.0" y="370.0" font-family="Geist Mono, SFMono-Regular, Menlo, Consolas, monospace" font-size="13" font-weight="normal" fill="#69665E" text-anchor="end">Inworld VIBE v0 · set build f5a6420d67b7ef45…</text>
+</svg>
diff --git a/docs/assets/inworld-logo-black.svg b/docs/assets/inworld-logo-black.svg
new file mode 100644
index 0000000..00285c3
--- /dev/null
+++ b/docs/assets/inworld-logo-black.svg
@@ -0,0 +1 @@
+<?xml version="1.0" encoding="UTF-8"?><svg id="Layer_2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1588.11 311.45"><g id="Layer_1"><path d="M404.96,52.02l1.61.32c16.07,3.21,19.99,7.3,19.99,20.84v180.29c0,13.54-3.92,17.62-19.99,20.84l-1.61.32v17.64h83.6v-17.64l-1.61-.32c-15.56-3.11-19.59-7.48-19.59-21.24V73.18c0-13.6,3.85-17.69,19.59-20.84l1.61-.32v-17.64h-83.6v17.64Z"/><path d="M689.48,254.67v-79.2c0-44.99-20.99-70.8-57.6-70.8-27.32,0-48.05,12.13-64.8,24.75v-21.95l-1.68.72c-11.35,4.84-23.21,8.4-35.35,10.6l-22.56,4.1v17.06l1.65.29c12.96,2.29,18.75,5.61,18.75,19.23v95.2c0,13.21-5.56,16.61-18.85,19.65l-1.55.36v17.59h80.8v-17.67l-1.64-.3c-12.17-2.21-17.96-5.77-17.96-20.03v-107.57c13.97-7.01,28.24-10.43,43.6-10.43,25.45,0,36.8,13.82,36.8,44.8v73.2c0,14.2-5.92,17.77-18.36,20.03l-1.64.3v17.67h80.8v-17.59l-1.55-.36c-13.29-3.04-18.84-6.44-18.84-19.65Z"/><path d="M998.03,125.37v-17.89h-64.8v18.2l1.79.19c7.2.78,11.76,2.76,13.94,6.06,1.98,2.99,2.09,7.23.36,12.97l-32.54,107.46-45.69-142.48h-28.51l-46.84,142.47-31.78-108.21c-1.58-5.61-1.53-9.43.15-12.03,1.98-3.07,6.63-5.05,14.62-6.25l1.7-.26v-18.12h-79.6v17.74l1.24.51c10.99,4.55,13.78,8.73,17.67,20.8l50.06,145.75h37.66l41.76-122.19,41.37,122.19h38.07l49.26-145.77c4.09-12.28,9.15-17.89,18.67-20.71l1.43-.42Z"/><path d="M1083.59,104.68c-24.63,0-46.97,9.5-62.92,26.74-16.41,17.74-25.08,41.97-25.08,70.06s8.43,50.7,24.39,67.72c15.65,16.69,37.96,25.88,62.81,25.88s48.32-9.64,64.66-27.13c16.34-17.49,25.34-42.09,25.34-69.26,0-54.47-37.51-94-89.2-94ZM1090.68,275.52c-27.62,2.15-47.87-27.35-51.6-75.17-1.67-21.38.88-39.81,7.38-53.28,6.58-13.64,16.97-21.4,30.05-22.42,27.86-2.17,48.24,26.99,51.93,74.29,2.76,35.38-5.71,74.07-37.76,76.58Z"/><path d="M1373.43,254.67V20.38c-19.51,7.58-39.79,12.24-60.8,14.17v17.11l1.65.29c12.96,2.29,18.75,5.61,18.75,19.23v183.5c0,13.21-5.56,16.61-18.84,19.65l-1.55.36v17.59h81.2v-17.58l-1.54-.36c-13.3-3.13-18.86-6.55-18.86-19.65Z"/><path d="M1586.37,262.29c-14.61-1.97-19.07-6.56-19.07-19.62V20.38c-18.99,7.62-39.34,12.48-61.2,14.32v17.06l1.65.29c12.96,2.29,18.75,5.61,18.75,19.23v38.89c-4.88-2.43-11.12-4.31-18.4-4.91-27.97-2.3-54.65,10.1-74.85,28.43-20.66,18.75-32.04,43.96-32.04,70.98,0,58.82,45.21,90.14,77.84,90.14,0,0,30.66,1.38,52.11-28.03l.17,5.58v21.1c13.52-5.32,27.58-9.16,41.93-11.45l14.85-2.37v-17.13l-1.73-.23ZM1496.89,264.94c-12.43-.2-25.05-6.77-34.64-18.01-7.97-9.35-17.48-26.3-17.48-53.96,0-64.42,38.86-65.18,46.99-65.2,8.04-.02,32.37,4.95,36,31.38l.17-.99,2.59,86.84c-7.53,11.51-20.96,19.93-33.62,19.93Z"/><path d="M1290.97,104.75c-16.08-.02-38.4,13.67-47.95,41.46l-.42-38.73-1.68.72c-11.35,4.84-23.21,8.4-35.35,10.6l-22.56,4.1v17.06l1.65.29c12.96,2.29,18.75,5.61,18.75,19.23v95.2c0,13.21-5.56,16.61-18.84,19.65l-1.55.36v17.59h81.6v-17.67l-1.64-.3c-12.44-2.26-18.76-5.98-18.76-20.03l-.55-49.45c.41-31.69,25.88-63.44,46.62-63.44,12.76,0,17.4,2.39,17.4,2.39v-36.29s-1.75-2.72-16.69-2.74Z"/><path d="M56.49,198.32c44.37,29.83,107.02,15.58,140.22-25.02,40.88-49.56,28.68-120.12-14.06-152.37-11.09-7.7-23.21-13.78-36.29-17.26C140.26,1.87,131.77.13,127.87,0c-5.98-.19-3.99,4.73-5.05,5.94s-12.01,1.7.38,6.05c7.33,2.57,2.87,2.72-2.72,7.78-4.95,4.48-.63,9.5-2.34,11.26-7.34,7.56,3.9,10.88,9.7,14.18,28.1,15,43.58,42,38.46,73.79-7.19,42-69.74,60.14-97.42,26.93-21.29-25.18-13.24-67.1,17.07-80.77,4.2-2.03,13.68-4.99,9.61-4.65-15.69,1.31-27.94,9.66-31.9,12.69-.34.26-.79-.14-.58-.51,2.87-5.05,19.5-16.83,52.22-20.97,5.85-1.26-16.16-5.87-42.3-.02-.49.11-.53-.36-.23-.53,9.63-5.63,23.34-6.97,24.36-7.74.92-1.29-6.27-1.22-8.77-1.21-18.19.63-33.9,7.4-46.93,19.7-20.02,17.06-26.58,45.13-23.81,70.37,3.24,26.1,17.58,50.62,38.87,66.04Z"/><path d="M217.54,270.08c-3.73-5.27-5.6-12.46-11.94-15.31-11.43-5.01-23.18-4.48-35.83-6.01-23.81-2.11-49.1-3.66-71.23-3.96-20.65.3-57.13,1.65-75.91,3.32-33.36,2.97-17.83,8.26-18.88,17.62-.38,3.45-4.15,3.17-3.73,6.55.7,4.9,9.89,11.03,14.51,12.27,20.35,5.44-6.65,6.25-3.63,11.69,2.51,4.53,13.71,3.23,18.28,5.03l57.22,2.97c1.78-.02,3.55.24,5.21.41,4.27.13,9.07-.36,13.76.25,10.2.58,20.48,2.87,30.71,3.12,7.05.52,13.78.2,20.98.47,5.43.7,11.88.27,16.75,1,3.04.35,5.83.2,8.88.65,8.07,1.15,16.11,1.32,24.28,1.21,3.11.1,6.3.16,9.4-.04,3.31-.19,6.92-.05,9.58-2.17,1.58-.93,1.5-2.82,1.83-4.12.41-.71,1.27-1.09,1.65-1.81.42-1.24.69-2.53.71-3.8v-.08c.09-4.32-1.98-8.57-3.56-12.58-2.63-5.81-5.72-11.24-9.06-16.68Z"/></g></svg>
\ No newline at end of file
diff --git a/docs/assets/inworld-logo-white.svg b/docs/assets/inworld-logo-white.svg
new file mode 100644
index 0000000..5eb155d
--- /dev/null
+++ b/docs/assets/inworld-logo-white.svg
@@ -0,0 +1 @@
+<?xml version="1.0" encoding="UTF-8"?><svg id="Layer_3" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1588.11 311.45"><defs><style>.cls-1{fill:#fff;}</style></defs><g id="Layer_1"><path class="cls-1" d="M404.96,52.02l1.61.32c16.07,3.21,19.99,7.3,19.99,20.84v180.29c0,13.54-3.92,17.62-19.99,20.84l-1.61.32v17.64h83.6v-17.64l-1.61-.32c-15.56-3.11-19.59-7.48-19.59-21.24V73.18c0-13.6,3.85-17.69,19.59-20.84l1.61-.32v-17.64h-83.6v17.64Z"/><path class="cls-1" d="M689.48,254.67v-79.2c0-44.99-20.99-70.8-57.6-70.8-27.32,0-48.05,12.13-64.8,24.75v-21.95l-1.68.72c-11.35,4.84-23.21,8.4-35.35,10.6l-22.56,4.1v17.06l1.65.29c12.96,2.29,18.75,5.61,18.75,19.23v95.2c0,13.21-5.56,16.61-18.85,19.65l-1.55.36v17.59h80.8v-17.67l-1.64-.3c-12.17-2.21-17.96-5.77-17.96-20.03v-107.57c13.97-7.01,28.24-10.43,43.6-10.43,25.45,0,36.8,13.82,36.8,44.8v73.2c0,14.2-5.92,17.77-18.36,20.03l-1.64.3v17.67h80.8v-17.59l-1.55-.36c-13.29-3.04-18.84-6.44-18.84-19.65Z"/><path class="cls-1" d="M998.03,125.37v-17.89h-64.8v18.2l1.79.19c7.2.78,11.76,2.76,13.94,6.06,1.98,2.99,2.09,7.23.36,12.97l-32.54,107.46-45.69-142.48h-28.51l-46.84,142.47-31.78-108.21c-1.58-5.61-1.53-9.43.15-12.03,1.98-3.07,6.63-5.05,14.62-6.25l1.7-.26v-18.12h-79.6v17.74l1.24.51c10.99,4.55,13.78,8.73,17.67,20.8l50.06,145.75h37.66l41.76-122.19,41.37,122.19h38.07l49.26-145.77c4.09-12.28,9.15-17.89,18.67-20.71l1.43-.42Z"/><path class="cls-1" d="M1083.59,104.68c-24.63,0-46.97,9.5-62.92,26.74-16.41,17.74-25.08,41.97-25.08,70.06s8.43,50.7,24.39,67.72c15.65,16.69,37.96,25.88,62.81,25.88s48.32-9.64,64.66-27.13c16.34-17.49,25.34-42.09,25.34-69.26,0-54.47-37.51-94-89.2-94ZM1090.68,275.52c-27.62,2.15-47.87-27.35-51.6-75.17-1.67-21.38.88-39.81,7.38-53.28,6.58-13.64,16.97-21.4,30.05-22.42,27.86-2.17,48.24,26.99,51.93,74.29,2.76,35.38-5.71,74.07-37.76,76.58Z"/><path class="cls-1" d="M1373.43,254.67V20.38c-19.51,7.58-39.79,12.24-60.8,14.17v17.11l1.65.29c12.96,2.29,18.75,5.61,18.75,19.23v183.5c0,13.21-5.56,16.61-18.84,19.65l-1.55.36v17.59h81.2v-17.58l-1.54-.36c-13.3-3.13-18.86-6.55-18.86-19.65Z"/><path class="cls-1" d="M1586.37,262.29c-14.61-1.97-19.07-6.56-19.07-19.62V20.38c-18.99,7.62-39.34,12.48-61.2,14.32v17.06l1.65.29c12.96,2.29,18.75,5.61,18.75,19.23v38.89c-4.88-2.43-11.12-4.31-18.4-4.91-27.97-2.3-54.65,10.1-74.85,28.43-20.66,18.75-32.04,43.96-32.04,70.98,0,58.82,45.21,90.14,77.84,90.14,0,0,30.66,1.38,52.11-28.03l.17,5.58v21.1c13.52-5.32,27.58-9.16,41.93-11.45l14.85-2.37v-17.13l-1.73-.23ZM1496.89,264.94c-12.43-.2-25.05-6.77-34.64-18.01-7.97-9.35-17.48-26.3-17.48-53.96,0-64.42,38.86-65.18,46.99-65.2,8.04-.02,32.37,4.95,36,31.38l.17-.99,2.59,86.84c-7.53,11.51-20.96,19.93-33.62,19.93Z"/><path class="cls-1" d="M1290.97,104.75c-16.08-.02-38.4,13.67-47.95,41.46l-.42-38.73-1.68.72c-11.35,4.84-23.21,8.4-35.35,10.6l-22.56,4.1v17.06l1.65.29c12.96,2.29,18.75,5.61,18.75,19.23v95.2c0,13.21-5.56,16.61-18.84,19.65l-1.55.36v17.59h81.6v-17.67l-1.64-.3c-12.44-2.26-18.76-5.98-18.76-20.03l-.55-49.45c.41-31.69,25.88-63.44,46.62-63.44,12.76,0,17.4,2.39,17.4,2.39v-36.29s-1.75-2.72-16.69-2.74Z"/><path class="cls-1" d="M56.49,198.32c44.37,29.83,107.02,15.58,140.22-25.02,40.88-49.56,28.68-120.12-14.06-152.37-11.09-7.7-23.21-13.78-36.29-17.26C140.26,1.87,131.77.13,127.87,0c-5.98-.19-3.99,4.73-5.05,5.94s-12.01,1.7.38,6.05c7.33,2.57,2.87,2.72-2.72,7.78-4.95,4.48-.63,9.5-2.34,11.26-7.34,7.56,3.9,10.88,9.7,14.18,28.1,15,43.58,42,38.46,73.79-7.19,42-69.74,60.14-97.42,26.93-21.29-25.18-13.24-67.1,17.07-80.77,4.2-2.03,13.68-4.99,9.61-4.65-15.69,1.31-27.94,9.66-31.9,12.69-.34.26-.79-.14-.58-.51,2.87-5.05,19.5-16.83,52.22-20.97,5.85-1.26-16.16-5.87-42.3-.02-.49.11-.53-.36-.23-.53,9.63-5.63,23.34-6.97,24.36-7.74.92-1.29-6.27-1.22-8.77-1.21-18.19.63-33.9,7.4-46.93,19.7-20.02,17.06-26.58,45.13-23.81,70.37,3.24,26.1,17.58,50.62,38.87,66.04Z"/><path class="cls-1" d="M217.54,270.08c-3.73-5.27-5.6-12.46-11.94-15.31-11.43-5.01-23.18-4.48-35.83-6.01-23.81-2.11-49.1-3.66-71.23-3.96-20.65.3-57.13,1.65-75.91,3.32-33.36,2.97-17.83,8.26-18.88,17.62-.38,3.45-4.15,3.17-3.73,6.55.7,4.9,9.89,11.03,14.51,12.27,20.35,5.44-6.65,6.25-3.63,11.69,2.51,4.53,13.71,3.23,18.28,5.03l57.22,2.97c1.78-.02,3.55.24,5.21.41,4.27.13,9.07-.36,13.76.25,10.2.58,20.48,2.87,30.71,3.12,7.05.52,13.78.2,20.98.47,5.43.7,11.88.27,16.75,1,3.04.35,5.83.2,8.88.65,8.07,1.15,16.11,1.32,24.28,1.21,3.11.1,6.3.16,9.4-.04,3.31-.19,6.92-.05,9.58-2.17,1.58-.93,1.5-2.82,1.83-4.12.41-.71,1.27-1.09,1.65-1.81.42-1.24.69-2.53.71-3.8v-.08c.09-4.32-1.98-8.57-3.56-12.58-2.63-5.81-5.72-11.24-9.06-16.68Z"/></g></svg>
\ No newline at end of file
diff --git a/docs/build_figures.py b/docs/build_figures.py
new file mode 100644
index 0000000..d1d4207
--- /dev/null
+++ b/docs/build_figures.py
@@ -0,0 +1,604 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Draws the README's figures as SVG, in a light and a dark variant each.
+
+ docs/assets/board-{light,dark}.svg the denoising board's scores,
+ one bar per system, read from the
+ board that
+ bench/scripts/leaderboard.py
+ --json-out writes: numbers are
+ generated, never typed
+ docs/assets/board-restoration-{light,dark}.svg the restoration board's,
+ the same way
+ docs/assets/architecture-{light,dark}.svg the network, from the STFT to the
+ isolated voice, with the two
+ checkpoints' serving modes
+
+ python docs/build_figures.py [--leaderboard <board.json>]
+ [--out docs/assets]
+
+Without --leaderboard only the architecture figures are drawn.
+
+The README shows each pair through a <picture> element, so GitHub picks the
+variant that matches the reader's theme.
+"""
+
+import argparse
+import html
+import json
+import math
+import os
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+FONT = "Instrument Sans, Helvetica Neue, Helvetica, Arial, sans-serif"
+MONO = "Geist Mono, SFMono-Regular, Menlo, Consolas, monospace"
+# The brand's paper and dark layouts; the two bar hues passed the colour checks
+# (lightness band, chroma, colour-vision separation, contrast) in each theme.
+PALETTES = {
+ # GitHub's light and dark canvases; the text and bar colours are the
+ # tokens of inworld.ai: its ink scale, its teal accent, its gray scale.
+ "light": {
+ "surface": "#FFFFFF",
+ "text": "#151613",
+ "body": "#57534B",
+ "muted": "#69665E",
+ "rule": "#D7D2CC",
+ "ours": "#02793D",
+ "others": "#9A9089",
+ },
+ "dark": {
+ "surface": "#0D1117",
+ "text": "#EEEAE0",
+ "body": "#B4AFA3",
+ "muted": "#89857C",
+ "rule": "#30363D",
+ "ours": "#1A9B58",
+ "others": "#9A9089",
+ },
+}
+OURS_PREFIX = "voice_isolator"
+BAR = 22 # px; thinner than the slot, the slot's rest is air
+SLOT = 36
+
+
+def _e(text: str) -> str:
+ return html.escape(str(text), quote=True)
+
+
+def _text(x, y, s, size, fill, weight="normal", anchor="start", mono=False):
+ return (
+ f'<text x="{x:.1f}" y="{y:.1f}" font-family="{MONO if mono else FONT}"'
+ f' font-size="{size}" font-weight="{weight}" fill="{fill}"'
+ f' text-anchor="{anchor}">{_e(s)}</text>')
+
+
+def board_rows(board: dict, which: str | None = None) -> list:
+ """The full-band tier in board order: (short label, score, ours).
+
+ The score is the composite, or the score of the board ``which`` when the
+ registry publishes boards side by side (then in that board's own order).
+ The short label is the roster's display name before its parenthesis; the
+ table carries the full names.
+ """
+ order = board["order"]
+ boards = board.get("boards") or {}
+ first = board.get("ranking_board") or (next(iter(boards))
+ if boards else None)
+ if which and which != first and which in order:
+ # the board's own systems, in its order
+ names = list(order[which])
+ else:
+ names = list(order["full"])
+ if which and which != first:
+ # a board JSON without that board's order: every system by that
+ # score
+ names = sorted(
+ (n for n in names
+ if isinstance((board["systems"][n].get("board_scores") or {}
+ ).get(which), (int, float))),
+ key=lambda n: -board["systems"][n]["board_scores"][which])
+ rows = []
+ for name in names:
+ system = board["systems"][name]
+ value = (system.get("board_scores") or
+ {}).get(which) if which else system.get("composite")
+ if not isinstance(value, (int, float)):
+ continue
+ label = system.get("label", name).split(" (")[0]
+ # the mark after a name: the streaming probe says yes
+ if (system.get("streaming") or {}).get("verdict") == "yes":
+ label += "*"
+ rows.append((label, float(value), name.startswith(OURS_PREFIX)))
+ return rows
+
+
+def board_svg(board: dict, mode: str, which: str | None = None) -> str:
+ """One horizontal bar per ranked system, the score at its tip: the
+ composite, or the score of the board ``which``."""
+ p = PALETTES[mode]
+ rows = board_rows(board, which)
+ what = f"{which.capitalize()} score" if which else "Composite score"
+ left, right, top = 330.0, 84.0, 74.0
+ width = 1040.0
+ plot_w = width - left - right
+ height = top + SLOT * len(rows) + 66
+ out = [
+ f'<svg xmlns="http://www.w3.org/2000/svg" width="{width:.0f}"'
+ f' height="{height:.0f}" viewBox="0 0 {width:.0f} {height:.0f}"'
+ f' role="img" aria-label="Inworld VIBE full-band tier, {what.lower()}'
+ f' per system">',
+ f'<rect width="100%" height="100%" fill="{p["surface"]}"/>',
+ _text(
+ 28, 36, f"{what}, higher is better. Gaps under "
+ f"{board['tie_bands']['composite']:g} are ties.", 16, p["body"]),
+ ]
+ for tick in (0.0, 0.25, 0.5, 0.75, 1.0):
+ x = left + plot_w * tick
+ out.append(f'<line x1="{x:.1f}" y1="{top - 8}" x2="{x:.1f}"'
+ f' y2="{top + SLOT * len(rows)}" stroke="{p["rule"]}"'
+ ' stroke-width="1"/>')
+ out.append(
+ _text(x,
+ top + SLOT * len(rows) + 18,
+ f"{tick:g}",
+ 13.5,
+ p["muted"],
+ anchor="middle",
+ mono=True))
+ for i, (label, value, ours) in enumerate(rows):
+ y = top + SLOT * i + (SLOT - BAR) / 2
+ w = max(plot_w * value, 4.0)
+ fill = p["ours"] if ours else p["others"]
+ # square at the baseline, 4 px rounded at the data end
+ out.append(
+ f'<path d="M{left:.1f},{y:.1f} h{w - 4:.1f} a4,4 0 0 1 4,4'
+ f' v{BAR - 8} a4,4 0 0 1 -4,4 h-{w - 4:.1f} z" fill="{fill}"/>')
+ out.append(
+ _text(left - 14, y + BAR - 5, label, 16, p["text"], anchor="end"))
+ out.append(
+ _text(left + w + 8,
+ y + BAR - 5,
+ f"{value:.3f}",
+ 15,
+ p["text"],
+ "600",
+ mono=True))
+ if any(label.endswith("*") for label, _, _ in rows):
+ # the one note: the mark after a name means streaming
+ out.append(_text(28, height - 22, "* streaming", 13.5, p["muted"]))
+ out.append(
+ _text(width - 28,
+ height - 22,
+ f"Inworld VIBE v0 · set build {board['set_id'][:16]}…",
+ 13,
+ p["muted"],
+ anchor="end",
+ mono=True))
+ out.append("</svg>")
+ return "\n".join(out)
+
+
+ARCH_DESC = (
+ "Input x(t), 48 kHz mono. STFT with N = 2048 and hop H = 480 (10 ms) gives"
+ " X in C^(F x T), F = 1025 bins. Band split into B = 46 bands, 100 Hz to"
+ " 2 kHz wide, each projected to D = 512, gives Z in R^(B x T x D). Seven"
+ " dual-path blocks, alternating A, M, A, M, A, M, A: block A is time"
+ " attention (rotary positions, exclusive self-attention, 8 heads) then"
+ " band attention; block M is time Mamba (state 16, expand 2, conv 4) then"
+ " band Mamba; the time path runs along time within each band, the band"
+ " path across bands within each frame; every sub-layer has a residual"
+ " connection. Per-band linear heads produce a bounded complex mask M and"
+ " a bounded residual R, both in C^(F x T). Output spectrum"
+ " X_hat = X + M (.) X + R, from the input spectrum X through a skip"
+ " connection; iSTFT gives the isolated voice s_hat(t). The realtime"
+ " checkpoint runs the same blocks causally with a look-ahead of 0, 2 or 4"
+ " frames as a learned embedding; the offline checkpoint is two-sided and"
+ " renders 8 s chunks.")
+# The figure's words, in a small markup: *x* italic, **x** bold, ^{x} raised.
+ARCH_STAGES = ( # title, parameter lines, role
+ ("STFT", ("*N* = 2048", "*H* = 480 (10 ms)", "*F* = 1025 bins"), "dsp"),
+ ("Band split", ("*B* = 46 bands", "100 Hz–2 kHz wide",
+ "linear to *D* = 512"), "net"),
+ ("7 dual-path blocks", ("A M A M A M A", "attention, Mamba"), "net"),
+ ("Per-band heads", ("mask *M*, bounded", "residual *R*, |*R*| ≤ 0.5"),
+ "head"),
+ ("iSTFT", (), "dsp"),
+)
+ARCH_SHAPES = ("*X* ∈ ℂ^{*F*×*T*}", "*Z* ∈ ℝ^{*B*×*T*×*D*}",
+ "*Z*′ ∈ ℝ^{*B*×*T*×*D*}")
+ARCH_SUM = "*X\u0302* = *X* + *M* ⊙ *X* + *R*"
+ARCH_SKIP = "skip: the input spectrum *X*"
+ARCH_BLOCK_TYPES = ( # tag, kind, (sub-layer, its axis) twice, settings
+ ("A", "attention", (("time attention", "along *T*, in each band"),
+ ("band attention", "across *B*, in each frame")),
+ "rotary positions · exclusive self-attention · 8 heads"),
+ ("M", "Mamba", (("time Mamba", "along *T*, in each band"),
+ ("band Mamba", "across *B*, in each frame")),
+ "selective scan · state 16 · expand 2 · conv 4"),
+)
+ARCH_NOTES = (
+ ("Realtime checkpoint", "the same blocks run causally, with a look-ahead"
+ " *ℓ* ∈ {0, 2, 4} frames as a learned embedding."),
+ ("Offline checkpoint", "two-sided, 8 s chunks."),
+)
+ARCH_WIDTH = 1040 # the board's width, so both figures display at one scale
+ARCH_MARGIN = 24
+# GitHub's canvases. Fills say a stage's role: fixed signal processing (dsp),
+# learned layers (net), the heads. Body text keeps at least 7.5:1 contrast on
+# every fill, captions at least 5.5:1.
+ARCH_PALETTES = {
+ "light": {
+ "bg": "#FFFFFF",
+ "ink": "#1F2328",
+ "ink2": "#3D444D",
+ "ink3": "#59636E",
+ "line": "#59636E",
+ "panel": "#F6F8FA",
+ "dsp": "#DCE8F6",
+ "net": "#D7EEDF",
+ "head": "#F8E5C2",
+ },
+ "dark": {
+ "bg": "#0D1117",
+ "ink": "#F0F6FC",
+ "ink2": "#D1D7E0",
+ "ink3": "#A6AFBA",
+ "line": "#A6AFBA",
+ "panel": "#161B22",
+ "dsp": "#1C3554",
+ "net": "#17442F",
+ "head": "#4A3511",
+ },
+}
+# Advance widths in 1/1000 em of " " to "~", regular and bold: for each glyph
+# the wider of Helvetica and Helvetica Neue (Arial shares Helvetica's
+# metrics), so a box sized from them holds its text in whichever font of the
+# stack the reader has.
+_ADVANCE = {
+ False:
+ (278, 278, 426, 556, 556, 1000, 667, 278, 333, 333, 389, 600, 278, 389,
+ 278, 333, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 278, 278,
+ 600, 600, 600, 556, 1015, 667, 685, 722, 722, 667, 611, 778, 722, 278,
+ 519, 667, 556, 871, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944,
+ 667, 667, 611, 278, 333, 278, 600, 556, 222, 556, 593, 537, 593, 556,
+ 296, 574, 556, 222, 222, 519, 222, 853, 556, 574, 593, 593, 333, 500,
+ 315, 556, 500, 759, 518, 500, 500, 334, 260, 334, 600),
+ True: (278, 333, 481, 556, 556, 1000, 722, 278, 333, 333, 407, 600, 278,
+ 407, 278, 389, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 333,
+ 333, 600, 600, 600, 611, 975, 722, 722, 741, 741, 667, 611, 778, 741,
+ 296, 556, 722, 611, 907, 741, 778, 667, 778, 722, 667, 611, 741, 667,
+ 944, 667, 667, 648, 333, 389, 333, 600, 556, 278, 574, 611, 574, 611,
+ 574, 352, 611, 611, 278, 278, 574, 278, 907, 611, 611, 611, 611, 389,
+ 556, 370, 611, 556, 815, 556, 556, 519, 389, 280, 389, 600),
+}
+_ADVANCE_SYMBOLS = {
+ "×": 600,
+ "–": 556,
+ "·": 278,
+ "′": 333,
+ "≤": 600,
+ "∈": 667,
+ "ℂ": 722,
+ "ℝ": 722,
+ "⊙": 778,
+ "ℓ": 444,
+ "ŝ": 556,
+ "\u0302": 0, # the hat of X-hat, a combining mark
+}
+_SCRIPT = 0.72 # a superscript's size relative to its text
+_LINE_PITCH = 21
+
+
+def _runs(markup: str) -> list:
+ """Splits figure markup into (text, italic, bold, raised) runs."""
+ runs, text, italic, bold, raised, i = [], "", False, False, False, 0
+ while i < len(markup):
+ if markup.startswith("**", i):
+ runs.append((text, italic, bold, raised))
+ text, bold, i = "", not bold, i + 2
+ elif markup[i] == "*":
+ runs.append((text, italic, bold, raised))
+ text, italic, i = "", not italic, i + 1
+ elif markup.startswith("^{", i):
+ runs.append((text, italic, bold, raised))
+ text, raised, i = "", True, i + 2
+ elif markup[i] == "}" and raised:
+ runs.append((text, italic, bold, raised))
+ text, raised, i = "", False, i + 1
+ else:
+ text, i = text + markup[i], i + 1
+ runs.append((text, italic, bold, raised))
+ return [run for run in runs if run[0]]
+
+
+def _text_width(markup: str, size: float, bold: bool = False) -> float:
+ """The width ``markup`` takes at ``size`` px."""
+ total = 0.0
+ for text, _, run_bold, raised in _runs(markup):
+ advances = _ADVANCE[bold != run_bold]
+ em = sum(
+ advances[ord(ch) -
+ 32] if " " <= ch <= "~" else _ADVANCE_SYMBOLS.get(ch, 600)
+ for ch in text)
+ total += em / 1000 * size * (_SCRIPT if raised else 1)
+ return total
+
+
+def _rich(x, y, markup, size, fill, bold=False, anchor="middle"):
+ """A text element from markup: italic, bold and raised runs as tspans."""
+ spans, shift = [], 0.0
+ for text, italic, run_bold, raised in _runs(markup):
+ attrs = []
+ target = -0.4 * size if raised else 0.0
+ if target != shift:
+ attrs.append(f'dy="{target - shift:.2f}"')
+ shift = target
+ if raised:
+ attrs.append(f'font-size="{size * _SCRIPT:.2f}"')
+ if italic:
+ attrs.append('font-style="italic"')
+ if run_bold: # **x** flips the element's weight
+ attrs.append(f'font-weight="{400 if bold else 600}"')
+ body = html.escape(text, quote=False)
+ spans.append(
+ f"<tspan {' '.join(attrs)}>{body}</tspan>" if attrs else body)
+ weight = ' font-weight="600"' if bold else ""
+ return (f'<text x="{x:.1f}" y="{y:.1f}" font-family="{FONT}"'
+ f' font-size="{size}" fill="{fill}"{weight}'
+ f' text-anchor="{anchor}">{"".join(spans)}</text>')
+
+
+def _rounded(points, radius):
+ """Path data through ``points``, the corners rounded by ``radius``."""
+ d = f"M{points[0][0]:.1f},{points[0][1]:.1f}"
+ for (x0, y0), (x1, y1), (x2, y2) in zip(points, points[1:], points[2:]):
+ before = math.hypot(x1 - x0, y1 - y0)
+ after = math.hypot(x2 - x1, y2 - y1)
+ r = min(radius, before / 2, after / 2)
+ ax, ay = x1 - (x1 - x0) / before * r, y1 - (y1 - y0) / before * r
+ bx, by = x1 + (x2 - x1) / after * r, y1 + (y2 - y1) / after * r
+ d += f" L{ax:.1f},{ay:.1f} Q{x1:.1f},{y1:.1f} {bx:.1f},{by:.1f}"
+ return d + f" L{points[-1][0]:.1f},{points[-1][1]:.1f}"
+
+
+def _arrow(points, color, dash=None, radius=10.0):
+ """A line through ``points`` whose last point is the tip of its head."""
+ length, width = 8.5, 6.5
+ (x1, y1), (x2, y2) = points[-2], points[-1]
+ cos, sin = math.cos(math.atan2(y2 - y1, x2 - x1)), math.sin(
+ math.atan2(y2 - y1, x2 - x1))
+ # the line stops inside the head, so its end never shows past the tip
+ body = list(
+ points[:-1]) + [(x2 - 0.62 * length * cos, y2 - 0.62 * length * sin)]
+ dashes = f' stroke-dasharray="{dash}"' if dash else ""
+ head = [(0, 0), (-length, width / 2), (-0.72 * length, 0),
+ (-length, -width / 2)]
+ tip = " L".join(f"{x2 + u * cos - v * sin:.1f},{y2 + u * sin + v * cos:.1f}"
+ for u, v in head)
+ return (f'<path d="{_rounded(body, radius)}" fill="none" stroke="{color}"'
+ f' stroke-width="1.4" stroke-linecap="round"'
+ f' stroke-linejoin="round"{dashes}/>\n'
+ f'<path d="M{tip} Z" fill="{color}"/>')
+
+
+def _sum_node(x, y, r, palette):
+ """The sum: a circle with a plus, drawn rather than typeset."""
+ k = r * 0.52
+ return (f'<circle cx="{x:.1f}" cy="{y:.1f}" r="{r}" fill="{palette["bg"]}"'
+ f' stroke="{palette["line"]}" stroke-width="1.4"/>\n'
+ f'<path d="M{x - k:.1f},{y:.1f} H{x + k:.1f} M{x:.1f},{y - k:.1f}'
+ f' V{y + k:.1f}" stroke="{palette["line"]}" stroke-width="1.4"'
+ ' stroke-linecap="round"/>')
+
+
+def _dot(x, y, r, palette):
+ return (f'<circle cx="{x:.1f}" cy="{y:.1f}" r="{r}"'
+ f' fill="{palette["line"]}"/>')
+
+
+def _stage(x, top, w, h, title, lines, fill, palette):
+ """A filled box with its title and parameters centred in it."""
+ out = [
+ f'<rect x="{x:.1f}" y="{top}" width="{w:.1f}" height="{h}" rx="8"'
+ f' fill="{fill}"/>'
+ ]
+ y = top + h / 2 - _LINE_PITCH * len(lines) / 2 + 5
+ out.append(_rich(x + w / 2, y, title, 17.5, palette["ink"], bold=True))
+ for k, line in enumerate(lines):
+ out.append(
+ _rich(x + w / 2, y + 24 + _LINE_PITCH * k, line, 15,
+ palette["ink2"]))
+ return out
+
+
+def _block_rows(x, y, palette):
+ """The two block types as rows of residual sub-layers; (x, y) is the left
+ edge and the first row's centre line."""
+ out = []
+ box_h = 52
+ box_w = max(
+ max(_text_width(name, 15.5, bold=True), _text_width(axis, 13.5))
+ for _, _, sublayers, _ in ARCH_BLOCK_TYPES
+ for name, axis in sublayers) + 30
+ for row, (tag, kind, sublayers, settings) in enumerate(ARCH_BLOCK_TYPES):
+ mid = y + 78 * row
+ out.append(_rich(x + 18, mid + 2, tag, 21, palette["ink"], bold=True))
+ out.append(_rich(x + 18, mid + 20, kind, 12.5, palette["ink3"]))
+ bx = x + 84
+ out.append(_arrow([(x + 48, mid), (bx, mid)], palette["line"]))
+ for k, (name, axis) in enumerate(sublayers):
+ out.append(f'<rect x="{bx:.1f}" y="{mid - box_h / 2:.1f}"'
+ f' width="{box_w:.1f}" height="{box_h}" rx="7"'
+ f' fill="{palette["net"]}"/>')
+ out.append(
+ _rich(bx + box_w / 2,
+ mid - 3,
+ name,
+ 15.5,
+ palette["ink"],
+ bold=True))
+ out.append(
+ _rich(bx + box_w / 2, mid + 16, axis, 13.5, palette["ink2"]))
+ px = bx + box_w + 28
+ out.append(
+ _arrow([(bx + box_w, mid), (px - 11, mid)], palette["line"]))
+ # the residual: the sub-layer's input goes around it to the sum
+ fork = bx - 18
+ over = mid - box_h / 2 - 13
+ out.append(_dot(fork, mid, 2.6, palette))
+ out.append(
+ _arrow([(fork, mid), (fork, over), (px, over), (px, mid - 11)],
+ palette["line"],
+ radius=7))
+ out.append(_sum_node(px, mid, 11, palette))
+ nxt = px + 11 + (34 if k == 0 else 30)
+ out.append(_arrow([(px + 11, mid), (nxt, mid)], palette["line"]))
+ bx = nxt
+ out.append(
+ _rich(bx + 12,
+ mid + 5,
+ settings,
+ 14.5,
+ palette["ink2"],
+ anchor="start"))
+ return out
+
+
+def architecture_svg(mode: str) -> str:
+ """The network as a layer diagram: the pipeline with its tensor shapes,
+ then the insides of the two block types, then the two checkpoints."""
+ p = ARCH_PALETTES[mode]
+ left, right = ARCH_MARGIN, ARCH_WIDTH - ARCH_MARGIN
+ top, h, stub, sum_r = 66, 116, 54, 13
+ mid = top + h / 2
+ widths = [
+ _text_width(title, 17.5, bold=True)
+ if not lines else max([_text_width(title, 17.5, bold=True)] +
+ [_text_width(line, 15)
+ for line in lines])
+ for title, lines, _ in ARCH_STAGES
+ ]
+ widths = [w + 24 for w in widths]
+ widths[-1] = max(widths[-1], 72)
+ # input stub, four stages, the sum, the iSTFT, output stub; the stubs sit
+ # flush against their stages and the other gaps share what is left
+ items = [stub] + widths[:4] + [2 * sum_r, widths[4], stub]
+ gap = (right - left - sum(items)) / 5
+ xs, x = [], left
+ for i, w in enumerate(items):
+ xs.append(x)
+ x += w + (0 if i in (0, 6) else gap)
+ out = []
+ for x0, symbol, dx in ((xs[0], "*x*(*t*)", -4), (xs[7], "*ŝ*(*t*)", 2)):
+ out.append(_arrow([(x0, mid), (x0 + stub, mid)], p["line"]))
+ out.append(_rich(x0 + stub / 2 + dx, mid - 10, symbol, 19, p["ink"]))
+ out.append(
+ _rich(x0 + stub / 2 + dx, mid + 24, "48 kHz", 13.5, p["ink3"]))
+ for (title, lines, role), j in zip(ARCH_STAGES, (1, 2, 3, 4, 6)):
+ out.extend(_stage(xs[j], top, items[j], h, title, lines, p[role], p))
+ sx = xs[5] + sum_r
+ ends = [(xs[a] + items[a], xs[a + 1]) for a in range(1, 6)]
+ ends[3] = (ends[3][0], sx - sum_r)
+ ends[4] = (sx + sum_r, ends[4][1])
+ for k, (x1, x2) in enumerate(ends):
+ out.append(_arrow([(x1 + 1, mid), (x2 - 1, mid)], p["line"]))
+ if k < len(ARCH_SHAPES):
+ out.append(
+ _rich((x1 + x2) / 2, top - 16, ARCH_SHAPES[k], 16, p["ink"]))
+ out.append(_sum_node(sx, mid, sum_r, p))
+ out.append(_rich(sx, top - 16, ARCH_SUM, 16, p["ink"]))
+ # the skip: X leaves the STFT's arrow and reaches the sum unchanged
+ fork = sum(ends[0]) / 2
+ under = top + h + 24
+ out.append(_dot(fork, mid, 3.4, p))
+ out.append(
+ _arrow([(fork, mid), (fork, under), (sx, under), (sx, mid + sum_r)],
+ p["line"],
+ dash="5 4"))
+ out.append(_rich((fork + sx) / 2, under + 20, ARCH_SKIP, 13.5, p["ink3"]))
+ # the block, opened
+ panel = under + 50
+ out.append(f'<rect x="{left}" y="{panel}" width="{right - left}"'
+ f' height="214" rx="12" fill="{p["panel"]}"/>')
+ heading = "Inside each dual-path block"
+ out.append(
+ _rich(left + 22, panel + 32, heading, 15.5, p["ink"], True, "start"))
+ out.append(
+ _rich(left + 30 + _text_width(heading, 15.5, bold=True),
+ panel + 32,
+ "· every sub-layer is residual",
+ 15.5,
+ p["ink3"],
+ anchor="start"))
+ out.extend(_block_rows(left + 22, panel + 98, p))
+ y = panel + 214 + 36
+ for k, (lead, rest) in enumerate(ARCH_NOTES):
+ out.append(
+ _rich(left,
+ y + 23 * k,
+ f"**{lead}:** {rest}",
+ 14.5,
+ p["ink2"],
+ anchor="start"))
+ height = y + 23 * (len(ARCH_NOTES) - 1) + 22
+ return "\n".join([
+ f'<svg xmlns="http://www.w3.org/2000/svg" width="{ARCH_WIDTH}"'
+ f' height="{height:.0f}" viewBox="0 0 {ARCH_WIDTH} {height:.0f}"'
+ ' role="img" aria-label="Inworld Voice Isolator architecture">',
+ f"<desc>{html.escape(ARCH_DESC)}</desc>",
+ f'<rect width="100%" height="100%" fill="{p["bg"]}"/>',
+ ] + out + ["</svg>"])
+
+
+def write(path: str, text: str) -> None:
+ """Writes one figure and says so."""
+ with open(path, "w", encoding="utf-8") as fh:
+ fh.write(text + "\n")
+ print(f"wrote {path}")
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser()
+ ap.add_argument(
+ "--leaderboard",
+ default=None,
+ help=("the board bench/scripts/leaderboard.py --json-out wrote; without"
+ " it only the architecture figures are drawn"),
+ )
+ ap.add_argument("--out", default=os.path.join(HERE, "assets"))
+ a = ap.parse_args()
+ board = None
+ if a.leaderboard:
+ with open(a.leaderboard, encoding="utf-8") as fh:
+ board = json.load(fh)
+ os.makedirs(a.out, exist_ok=True)
+ boards = list((board or {}).get("boards") or {})
+ first = (board or
+ {}).get("ranking_board") or (boards[0] if boards else None)
+ for mode in ("light", "dark"):
+ if board is not None:
+ # the first board is the headline chart; every other board gets
+ # its own
+ write(os.path.join(a.out, f"board-{mode}.svg"),
+ board_svg(board, mode, first))
+ for other in boards:
+ if other != first:
+ write(os.path.join(a.out, f"board-{other}-{mode}.svg"),
+ board_svg(board, mode, other))
+ write(os.path.join(a.out, f"architecture-{mode}.svg"),
+ architecture_svg(mode))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/README.md b/examples/README.md
new file mode 100644
index 0000000..bd82833
--- /dev/null
+++ b/examples/README.md
@@ -0,0 +1,40 @@
+# Examples
+
+## Audio cleanup notebook
+
+[audio_cleanup.ipynb](audio_cleanup.ipynb) is a guided first run of the offline model, for evaluating it on your own audio:
+
+1. Install the package and check the machine.
+2. Load the offline model; its weights (256 MB) download from Hugging Face on first use.
+3. Clean a bundled noisy sample: speech over a hum and sharp taps.
+4. Play the original, the cleaned voice and the removed background side by side.
+5. Swap in your own recording and save the output.
+
+Run it from a clone:
+
+```bash
+git clone https://github.com/inworld-ai/voice-isolator && cd voice-isolator
+pip install jupyterlab
+jupyter lab examples/audio_cleanup.ipynb
+```
+
+It also runs in Colab or any other Jupyter environment without a clone: it then installs the package from PyPI and downloads the sample.
+
+A GPU is optional. See [Hardware](../README.md#hardware) for what the model is tested on.
+
+## The smallest reusable code
+
+To clean a file from your own code:
+
+```python
+from inworld import voice_isolation
+
+isolator = voice_isolation.VoiceIsolator("inworld/voice-isolator") # load once, reuse
+wav, sample_rate = voice_isolation.load_audio("noisy.wav")
+voice = isolator.isolate(wav, sample_rate)
+voice_isolation.save_audio("clean.wav", voice, sample_rate)
+```
+
+From a terminal, `voice-isolate noisy.wav clean.wav` does the same and also writes the removed background.
+
+For live audio, see [Streaming](../README.md#streaming) and the [interactive demo](../demo/README.md).
diff --git a/examples/audio_cleanup.ipynb b/examples/audio_cleanup.ipynb
new file mode 100644
index 0000000..b65beb4
--- /dev/null
+++ b/examples/audio_cleanup.ipynb
@@ -0,0 +1,294 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "id": "cell-00",
+ "metadata": {},
+ "source": [
+ "# Clean up a noisy recording with Inworld Voice Isolator\n",
+ "\n",
+ "This notebook takes a noisy speech recording, removes what is around the voice, and lets you hear the result next to the original. It then does the same for a recording of your own.\n",
+ "\n",
+ "You will:\n",
+ "\n",
+ "1. Install the package and check this machine.\n",
+ "2. Load the offline model (its weights download on first use).\n",
+ "3. Run the bundled noisy sample through it.\n",
+ "4. Listen to the original and the cleaned audio side by side.\n",
+ "5. Swap in your own recording and save the output.\n",
+ "\n",
+ "**What you need**\n",
+ "\n",
+ "- Python 3.10 or later and PyTorch 2.1 or later.\n",
+ "- About 260 MB of disk for the offline model.\n",
+ "- A GPU is optional. The model is tested on NVIDIA A100, H100, B200 and B300 GPUs and on CPU; smaller GPUs are not tested yet. On an Apple-silicon Mac it uses the Metal GPU with PyTorch 2.6 or later. On CPU it works, more slowly.\n",
+ "\n",
+ "This notebook covers offline cleanup of recorded audio. For live audio, see the streaming section of the [README](https://github.com/inworld-ai/voice-isolator#streaming)."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "cell-01",
+ "metadata": {},
+ "source": [
+ "## 1. Install and check the machine\n",
+ "\n",
+ "Inside a clone of the repository this installs the checkout. Anywhere else (Colab, for example) it installs the release from PyPI. If the package is already installed in this environment, the cell leaves it alone."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "cell-02",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import pathlib\n",
+ "\n",
+ "REPO = pathlib.Path.cwd().parent\n",
+ "IN_CLONE = (REPO / \"src\" / \"inworld\" / \"voice_isolation\").is_dir()\n",
+ "\n",
+ "try:\n",
+ " from inworld import voice_isolation\n",
+ " print(f\"inworld-voice-isolation {voice_isolation.__version__} is already installed.\")\n",
+ "except ImportError:\n",
+ " if IN_CLONE:\n",
+ " %pip install -q \"{REPO}\"\n",
+ " else:\n",
+ " %pip install -q inworld-voice-isolation"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "cell-03",
+ "metadata": {},
+ "source": [
+ "`voice-isolate-doctor` reports the Python and PyTorch versions and the device inference will use. It prints one line per check, starting with `OK`, `INFO`, `WARN` or `FAIL`; a `FAIL` line names what to fix. This quick form uses no network and loads no model."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "cell-04",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import sys\n",
+ "\n",
+ "!\"{sys.executable}\" -m inworld.voice_isolation.doctor"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "cell-05",
+ "metadata": {},
+ "source": [
+ "## 2. Load the model\n",
+ "\n",
+ "The first run downloads the offline model, `voice-isolator-v1` (256 MB), from [huggingface.co/inworld/voice-isolator](https://huggingface.co/inworld/voice-isolator) into the Hugging Face cache and verifies its checksum. No account or sign-in is needed. Later runs load it from the cache.\n",
+ "\n",
+ "Code and weights are Apache-2.0."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "cell-06",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import time\n",
+ "\n",
+ "import torch\n",
+ "from IPython.display import Audio, display\n",
+ "\n",
+ "from inworld import voice_isolation\n",
+ "\n",
+ "isolator = voice_isolation.VoiceIsolator(\"inworld/voice-isolator\")\n",
+ "print(f\"Model loaded on: {isolator.device}\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "cell-07",
+ "metadata": {},
+ "source": [
+ "## 3. Clean the bundled sample\n",
+ "\n",
+ "The sample is 9 seconds of read speech (from LibriSpeech, CC BY 4.0) mixed with a low electrical hum and three sharp taps.\n",
+ "\n",
+ "`isolate` returns the voice at the input's sample rate, length and level. Subtracting it from the input gives what the model removed."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "cell-08",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "SAMPLE_URL = (\"https://raw.githubusercontent.com/inworld-ai/voice-isolator/\"\n",
+ " \"main/demo/examples/sample_15.wav\")\n",
+ "\n",
+ "sample = REPO / \"demo\" / \"examples\" / \"sample_15.wav\"\n",
+ "if not sample.is_file():\n",
+ " import urllib.request\n",
+ " sample = pathlib.Path(\"sample_15.wav\")\n",
+ " urllib.request.urlretrieve(SAMPLE_URL, sample)\n",
+ "\n",
+ "\n",
+ "def clean(path):\n",
+ " \"\"\"Returns (original, voice, background, sample_rate) for one file.\"\"\"\n",
+ " wav, sample_rate = voice_isolation.load_audio(str(path))\n",
+ " start = time.perf_counter()\n",
+ " voice = isolator.isolate(wav, sample_rate).cpu()\n",
+ " elapsed = time.perf_counter() - start\n",
+ " seconds = len(wav) / sample_rate\n",
+ " print(f\"{pathlib.Path(path).name}: {seconds:.1f} s of audio cleaned in \"\n",
+ " f\"{elapsed:.1f} s ({seconds / elapsed:.1f}x real time)\")\n",
+ " return wav, voice, wav - voice, sample_rate\n",
+ "\n",
+ "\n",
+ "original, voice, background, sample_rate = clean(sample)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "cell-09",
+ "metadata": {},
+ "source": [
+ "The first call on a GPU includes one-time warm-up, so run the cell again for a representative speed.\n",
+ "\n",
+ "## 4. Listen side by side\n",
+ "\n",
+ "The players keep the true levels (no normalization), so loudness is comparable between them.\n",
+ "\n",
+ "What to listen for:\n",
+ "\n",
+ "- **Noise.** Are the hum and the taps gone, including in the pauses between words?\n",
+ "- **Speech.** Does the voice still sound natural? Check consonants and word endings. Breaths and other non-verbal sounds are kept on purpose.\n",
+ "- **Removed background.** It should hold the noise and little or no voice. Voice you hear here is voice the model took out."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "cell-10",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def play(label, wav):\n",
+ " \"\"\"Shows a player at the waveform's own level, without normalization.\"\"\"\n",
+ " print(label)\n",
+ " display(Audio(wav.clamp(-1, 1).numpy(), rate=sample_rate, normalize=False))\n",
+ "\n",
+ "\n",
+ "play(\"Original\", original)\n",
+ "play(\"Cleaned voice\", voice)\n",
+ "play(\"Removed background\", background)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "cell-11",
+ "metadata": {},
+ "source": [
+ "## 5. Try your own recording\n",
+ "\n",
+ "Set `MY_RECORDING` to a file on this machine and run the cell. In Colab, upload the file with the folder icon on the left first.\n",
+ "\n",
+ "- **Formats:** WAV, FLAC, OGG and MP3 (anything the `soundfile` library reads). Convert other formats first, for example `ffmpeg -i input.m4a input.wav`.\n",
+ "- **Sample rate and channels:** any sample rate works. Stereo is mixed down to mono, and the output is mono.\n",
+ "- **Length:** long files are processed in 8-second chunks that overlap by 2 seconds and are crossfaded.\n",
+ "\n",
+ "The cell writes two float32 WAVs beside your file: `<name>_clean.wav` and `<name>_clean_background.wav`. Your audio stays on this machine."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "cell-12",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "MY_RECORDING = \"\" # for example \"recordings/call.wav\"\n",
+ "\n",
+ "if MY_RECORDING:\n",
+ " source = pathlib.Path(MY_RECORDING).expanduser()\n",
+ " original, voice, background, sample_rate = clean(source)\n",
+ "\n",
+ " voice_path = source.with_name(f\"{source.stem}_clean.wav\")\n",
+ " background_path = source.with_name(f\"{source.stem}_clean_background.wav\")\n",
+ " voice_isolation.save_audio(str(voice_path), voice, sample_rate,\n",
+ " subtype=\"FLOAT\")\n",
+ " voice_isolation.save_audio(str(background_path), background, sample_rate,\n",
+ " subtype=\"FLOAT\")\n",
+ " print(f\"Saved {voice_path} and {background_path}\")\n",
+ "\n",
+ " play(\"Original\", original)\n",
+ " play(\"Cleaned voice\", voice)\n",
+ " play(\"Removed background\", background)\n",
+ "else:\n",
+ " print(\"Set MY_RECORDING to the path of an audio file, then run this cell.\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "cell-13",
+ "metadata": {},
+ "source": [
+ "## Use it in your own code\n",
+ "\n",
+ "The whole pipeline is a few lines:\n",
+ "\n",
+ "```python\n",
+ "from inworld import voice_isolation\n",
+ "\n",
+ "isolator = voice_isolation.VoiceIsolator(\"inworld/voice-isolator\") # load once, reuse\n",
+ "wav, sample_rate = voice_isolation.load_audio(\"noisy.wav\")\n",
+ "voice = isolator.isolate(wav, sample_rate)\n",
+ "voice_isolation.save_audio(\"clean.wav\", voice, sample_rate)\n",
+ "```\n",
+ "\n",
+ "Or from a terminal, for one file or a whole folder:\n",
+ "\n",
+ "```bash\n",
+ "voice-isolate noisy.wav clean.wav\n",
+ "voice-isolate recordings/ cleaned/\n",
+ "```\n",
+ "\n",
+ "**Cleaning audio before speech-to-text?** Ask for the rate your STT model expects, and the voice comes back resampled:\n",
+ "\n",
+ "```python\n",
+ "voice_16k = isolator.isolate(wav, sample_rate, output_sample_rate=16000)\n",
+ "```\n",
+ "\n",
+ "Where to go next:\n",
+ "\n",
+ "- [README](https://github.com/inworld-ai/voice-isolator#quick-start): CLI options and the streaming model for live audio.\n",
+ "- [Interactive demo](https://github.com/inworld-ai/voice-isolator/blob/main/demo/README.md): a browser page with file upload and live microphone.\n",
+ "- [Model card](https://github.com/inworld-ai/voice-isolator/blob/main/MODEL_CARD.md): what the model does and does not do, benchmark results and training data."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "99b362f3-0b23-4e3f-8aee-a13b22f609cc",
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/pyproject.toml b/pyproject.toml
new file mode 100644
index 0000000..792f600
--- /dev/null
+++ b/pyproject.toml
@@ -0,0 +1,81 @@
+[build-system]
+requires = ["hatchling==1.33.0", "hatch-fancy-pypi-readme==25.1.0"]
+build-backend = "hatchling.build"
+
+[project]
+name = "inworld-voice-isolation"
+version = "1.0.0"
+description = "Inworld Voice Isolator: 48 kHz full-band voice isolation, offline or streaming, that preserves speaker timbre."
+dynamic = ["readme"]
+license = "Apache-2.0"
+license-files = ["LICENSE", "NOTICE"]
+requires-python = ">=3.10"
+authors = [{ name = "Inworld AI" }]
+keywords = ["speech-enhancement", "denoising", "voice-isolation", "audio", "48khz"]
+classifiers = [
+ "Development Status :: 5 - Production/Stable",
+ "Intended Audience :: Developers",
+ "Programming Language :: Python :: 3",
+ "Topic :: Multimedia :: Sound/Audio :: Speech",
+]
+dependencies = [
+ "numpy",
+ "soundfile",
+ "safetensors",
+ "torch>=2.1",
+ "torchaudio>=2.1",
+ "huggingface-hub",
+]
+
+[project.optional-dependencies]
+fast = ["mamba-ssm>=2.2", "causal-conv1d>=1.4"]
+demucs = ["demucs==4.0.1"]
+docs = ["matplotlib"]
+# silero-vad is pinned to the releases whose segmentation cut the frozen deletion
+# cohort: 6.2.3 moves two borderline recordings and makes every new row incomplete
+eval = ["torchmetrics[audio]>=1.4", "transformers>=4.40", "librosa", "requests", "silero-vad>=6.2.0,<6.2.3", "scipy"]
+asr = ["faster-whisper>=1.0"]
+demo = ["gradio==6.31.0", "soundfile>=0.12.1", "soxr>=0.3.7"]
+dev = ["pytest", "yapf==0.43.0", "isort==9.0.2", "pylint==4.1.1"]
+
+[project.scripts]
+voice-isolate = "inworld.voice_isolation.cli:main"
+voice-isolate-doctor = "inworld.voice_isolation.doctor:main"
+
+[project.urls]
+Homepage = "https://github.com/inworld-ai/voice-isolator"
+Benchmark = "https://github.com/inworld-ai/voice-isolator/blob/main/bench/README.md"
+
+# Keep image paths local on GitHub; only the package description uses public URLs.
+[tool.hatch.metadata.hooks.fancy-pypi-readme]
+content-type = "text/markdown"
+fragments = [{ path = "README.md" }]
+
+[[tool.hatch.metadata.hooks.fancy-pypi-readme.substitutions]]
+pattern = '(src|srcset)="docs/assets/'
+replacement = '\1="https://raw.githubusercontent.com/inworld-ai/voice-isolator/main/docs/assets/'
+
+[tool.hatch.build.targets.wheel]
+packages = ["src/inworld"]
+
+# Source distributions contain the inference package and its public documentation.
+[tool.hatch.build.targets.sdist]
+only-include = ["src", "pyproject.toml", "README.md", "MODEL_CARD.md", "LICENSE", "NOTICE",
+ "docs/assets"]
+
+[tool.yapf]
+based_on_style = "google"
+column_limit = 80
+
+[tool.isort]
+profile = "google"
+# where the local modules live, so their imports group apart from third-party ones
+src_paths = ["src", "bench/scripts", "bench/wrappers", "docs", "demo",
+ "tests", "tests/bench/scripts", "tests/bench/wrappers"]
+# a wrapper's bytes are part of every receipt of its renders, so it changes only
+# with a re-render; it imports its upstream the way upstream documents it
+skip_glob = ["bench/wrappers/*"]
+
+[tool.pytest.ini_options]
+testpaths = ["tests"]
+python_files = ["test_*.py"]
diff --git a/src/inworld/voice_isolation/__init__.py b/src/inworld/voice_isolation/__init__.py
new file mode 100644
index 0000000..9c1d9e8
--- /dev/null
+++ b/src/inworld/voice_isolation/__init__.py
@@ -0,0 +1,45 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Inworld Voice Isolator: the public API of inworld.voice_isolation.
+
+ from inworld import voice_isolation
+ isolator = voice_isolation.VoiceIsolator("inworld/voice-isolator")
+ voice = isolator.isolate(wav, sample_rate)
+"""
+
+from inworld.voice_isolation.audio import load_audio
+from inworld.voice_isolation.audio import resample
+from inworld.voice_isolation.audio import save_audio
+from inworld.voice_isolation.audio import SR
+from inworld.voice_isolation.isolator import load_model
+from inworld.voice_isolation.isolator import VoiceIsolator
+from inworld.voice_isolation.model import VoiceIsolatorConfig
+from inworld.voice_isolation.model import VoiceIsolatorNetwork
+from inworld.voice_isolation.registry import MODELS
+from inworld.voice_isolation.streaming import Stream
+
+__version__ = "1.0.0"
+
+__all__ = [
+ "SR",
+ "MODELS",
+ "VoiceIsolator",
+ "VoiceIsolatorConfig",
+ "VoiceIsolatorNetwork",
+ "Stream",
+ "load_audio",
+ "load_model",
+ "resample",
+ "save_audio",
+]
diff --git a/src/inworld/voice_isolation/audio.py b/src/inworld/voice_isolation/audio.py
new file mode 100644
index 0000000..13ae09c
--- /dev/null
+++ b/src/inworld/voice_isolation/audio.py
@@ -0,0 +1,139 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Audio I/O and high-quality resampling shared by the package."""
+
+import os
+import secrets
+
+import numpy as np
+import soundfile as sf
+import torch
+import torchaudio
+
+SR = 48000
+
+KAISER_BEST = {
+ "resampling_method": "sinc_interp_kaiser",
+ "lowpass_filter_width": 64,
+ "rolloff": 0.9475937167399596,
+ "beta": 14.769656459379492,
+}
+
+
+def resample(wav: torch.Tensor, orig_freq: int, new_freq: int) -> torch.Tensor:
+ """kaiser_best resampling; identity when the rates match."""
+ if orig_freq == new_freq:
+ return wav
+ return torchaudio.functional.resample(wav, orig_freq, new_freq,
+ **KAISER_BEST)
+
+
+def fit_length(wav: torch.Tensor, n: int) -> torch.Tensor:
+ """Trims the last axis to ``n`` samples or pads it with trailing zeros."""
+ if wav.shape[-1] >= n:
+ return wav[..., :n]
+ return torch.nn.functional.pad(wav, (0, n - wav.shape[-1]))
+
+
+def to_mono(audio) -> torch.Tensor:
+ """Converts [T], [C, T] or [T, C] audio to a float32 tensor [T] in [-1, 1].
+
+ Integer PCM (int16/int32/uint8) is scaled by its dtype range; floats pass
+ through. Up to eight channels are averaged.
+
+ Raises:
+ ValueError: The dtype has no PCM scale (int64), or both dimensions
+ exceed eight, so the channel axis cannot be told from the time axis.
+ """
+ x = torch.as_tensor(
+ np.asarray(audio) if not isinstance(audio, torch.Tensor) else audio)
+ if x.dtype == torch.int64:
+ raise ValueError(
+ "int64 samples have no PCM scale: pass float, int16, int32 or"
+ " uint8.")
+ if not torch.is_floating_point(x):
+ info = torch.iinfo(x.dtype)
+ x = x.float()
+ if info.min < 0:
+ x = x / -float(info.min)
+ else:
+ x = (x - (info.max + 1) / 2) / ((info.max + 1) / 2)
+ x = x.detach().float()
+ if x.ndim == 2:
+ if min(x.shape) > 8:
+ raise ValueError(
+ f"Expected at most eight channels, got shape {tuple(x.shape)}.")
+ x = (x.mean(0)
+ if x.shape[0] <= 8 and x.shape[0] < x.shape[1] else x.mean(1))
+ elif x.ndim != 1:
+ raise ValueError(
+ f"Expected 1-D or 2-D audio, got shape {tuple(x.shape)}.")
+ return x
+
+
+def load_audio(path: str) -> tuple[torch.Tensor, int]:
+ """Reads a soundfile-readable file as (mono float32 tensor [T], rate)."""
+ x, sr = sf.read(path, dtype="float32", always_2d=True)
+ return torch.from_numpy(x.mean(1)), int(sr)
+
+
+def create_staging_file(destination: str, prefix: str = ".partial-") -> str:
+ """Creates an empty hidden file beside ``destination`` to write it under.
+
+ The name keeps the destination's extension, from which soundfile takes the
+ format. The file has the permissions of any new file (0o666 less the
+ umask, applied by the system as it creates the file), which renaming it
+ into place keeps; ``tempfile.mkstemp`` would give 0o600.
+
+ Raises:
+ FileExistsError: Every random name tried was taken.
+ """
+ folder = os.path.dirname(os.path.abspath(destination))
+ suffix = os.path.splitext(destination)[1]
+ for _ in range(100):
+ path = os.path.join(folder, f"{prefix}{secrets.token_hex(4)}{suffix}")
+ try:
+ os.close(os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o666))
+ except FileExistsError:
+ continue
+ return path
+ raise FileExistsError(f"No free staging name beside {destination}")
+
+
+def save_audio(path: str,
+ wav: np.ndarray | torch.Tensor,
+ sample_rate: int,
+ subtype: str = "PCM_16") -> None:
+ """Writes a mono waveform.
+
+ Integer subtypes cannot hold samples beyond full scale, so a waveform
+ peaking above 1.0 is scaled down to peak at 1.0 instead of being clipped
+ (isolated speech overshoots the input peak on roughly a quarter of loud
+ inputs). Float subtypes are written unchanged. The file is written under a
+ temporary name and renamed into place, so an interrupted write never leaves
+ a partial file that a resumed run would take as done; it gets the
+ permissions of any new file.
+ """
+ y = torch.as_tensor(wav).detach().float().cpu()
+ if subtype.startswith("PCM") and y.numel():
+ peak = float(y.abs().max())
+ if peak > 1.0:
+ y = y / peak
+ tmp = create_staging_file(path)
+ try:
+ sf.write(tmp, y.numpy(), sample_rate, subtype=subtype)
+ os.replace(tmp, path)
+ finally:
+ if os.path.exists(tmp):
+ os.unlink(tmp)
diff --git a/src/inworld/voice_isolation/cli.py b/src/inworld/voice_isolation/cli.py
new file mode 100644
index 0000000..05d7a30
--- /dev/null
+++ b/src/inworld/voice_isolation/cli.py
@@ -0,0 +1,492 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""`voice-isolate`: isolate one file or a whole directory.
+
+A file input always writes its output (an existing output folder receives
+``<stem>.wav``). Offline also writes ``<output-stem>_background.wav`` as the
+input minus the isolated voice. Both are float WAVs at the same sample rate
+and level. Directory inputs resume only when every requested output exists.
+"""
+
+import argparse
+import os
+import stat
+import string
+import sys
+import tempfile
+import time
+import unicodedata
+
+import torch
+
+from inworld.voice_isolation import audio as audio_lib
+from inworld.voice_isolation import isolator
+from inworld.voice_isolation import registry
+
+_EXTS = (".wav", ".flac", ".mp3", ".ogg", ".opus")
+# the probe for a case-insensitive folder swaps ASCII letters only, which every
+# such file system folds alike
+_SWAP_CASE = str.maketrans(string.ascii_lowercase + string.ascii_uppercase,
+ string.ascii_uppercase + string.ascii_lowercase)
+# on macOS the CPU path runs about 4x faster on two threads than on PyTorch's
+# default (one per core): the network is many small ops, and the threads spend
+# their time synchronising rather than computing
+_MACOS_CPU_THREADS = 2
+
+
+def _limit_macos_cpu_threads(device):
+ """Caps PyTorch's CPU threads on macOS unless the user chose a count."""
+ if (sys.platform == "darwin" and device.type == "cpu" and
+ "OMP_NUM_THREADS" not in os.environ and
+ torch.get_num_threads() > _MACOS_CPU_THREADS):
+ torch.set_num_threads(_MACOS_CPU_THREADS)
+
+
+def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
+ """Parses the audio paths and model options for the command line."""
+ p = argparse.ArgumentParser(
+ prog="voice-isolate",
+ description="Inworld Voice Isolator: 48 kHz full-band voice isolation.",
+ )
+ p.add_argument("input", help="Audio file, or a directory of audio files.")
+ p.add_argument("output",
+ help="Output file, or directory for a directory input.")
+ background = p.add_mutually_exclusive_group()
+ background.add_argument(
+ "--background",
+ help=("Offline, single-file input: background WAV path. The default"
+ " is <output-stem>_background.wav. Both outputs are float WAVs"
+ " whose sum is the mono input at the output sample rate."),
+ )
+ background.add_argument(
+ "--no-background",
+ action="store_true",
+ help=
+ "Offline: save only the isolated voice. Streaming saves only voice.",
+ )
+ p.add_argument(
+ "--model",
+ default=registry.REPO_ID,
+ help=("The Hub repository inworld/voice-isolator (the default: --mode"
+ " picks its checkpoint), a registry name (voice-isolator-v1, or"
+ " voice-isolator-v1-realtime, which streams),"
+ " hf://<org>/<repo>/<file>[@<revision>], or a local checkpoint"
+ " (.safetensors / .pt)."),
+ )
+ p.add_argument(
+ "--mode",
+ default="offline",
+ choices=isolator.MODES,
+ help=("offline: every frame sees its whole chunk (best quality, the"
+ " default; voice-isolator-v1). streaming: causal, as a live"
+ " stream runs (voice-isolator-v1-realtime)."),
+ )
+ p.add_argument(
+ "--lookahead",
+ type=int,
+ default=0,
+ help=("Streaming mode: frames of look-ahead (10 ms each for the"
+ " released model), one of the checkpoint's trained positions."),
+ )
+ p.add_argument(
+ "--block-frames",
+ type=int,
+ default=4,
+ help="Streaming mode: maximum frames processed together; tunes"
+ " throughput without changing the stream's latency.",
+ )
+ p.add_argument(
+ "--window-frames",
+ type=int,
+ default=None,
+ help="Streaming mode: the time attention never looks back across a"
+ " window of this many frames (a second lane crossfades in before"
+ " each boundary, --crossfade-frames). Default: 600 frames (6 s);"
+ " 0 turns the windows off.",
+ )
+ p.add_argument(
+ "--crossfade-frames",
+ type=int,
+ default=None,
+ help="Streaming mode: frames over which the two lanes blend before"
+ " a window boundary. Default: 200 frames (2 s).",
+ )
+ p.add_argument(
+ "--output-sr",
+ type=int,
+ default=48000,
+ help="Output sample rate (default 48000; 0 = keep each input's rate).",
+ )
+ p.add_argument(
+ "--device",
+ default=None,
+ help=("cuda | mps | cpu (default: cuda if available, else mps on an"
+ " Apple-silicon Mac with PyTorch 2.6 or later, else cpu)."),
+ )
+ p.add_argument(
+ "--precision",
+ default="auto",
+ choices=("auto", "fp32", "fp16", "bf16"),
+ help=("Network precision: auto runs bf16 on a CUDA GPU, the precision"
+ " the model was trained in, and float32 elsewhere (CPU, mps);"
+ " the others force one."),
+ )
+ p.add_argument(
+ "--offline-passes",
+ type=int,
+ default=None,
+ help=("Offline mode: passes of the model over its own output (default:"
+ " the checkpoint's own count, 1 for the released files); each"
+ " pass costs one offline render."),
+ )
+ p.add_argument(
+ "--chunk-seconds",
+ type=float,
+ default=None,
+ help=("Offline mode: seconds per render chunk (default: the"
+ " checkpoint's, 8 s for voice-isolator-v1); streaming ignores"
+ " it."),
+ )
+ p.add_argument(
+ "--overlap-seconds",
+ type=float,
+ default=None,
+ help=("Offline mode: seconds two chunks overlap and crossfade"
+ " (default: the checkpoint's, 2 s)."),
+ )
+ p.add_argument(
+ "--shard",
+ type=int,
+ default=0,
+ help="With a directory input: this worker's shard.",
+ )
+ p.add_argument(
+ "--num-shards",
+ type=int,
+ default=1,
+ help="With a directory input: total workers.",
+ )
+ p.add_argument(
+ "--float32",
+ action="store_true",
+ help=("With voice-only output, write float32 WAV instead of PCM_16."
+ " Offline voice/background pairs always use float32 to preserve"
+ " their original levels; PCM_16 voice-only output scales down"
+ " peaks above full scale."),
+ )
+ return p.parse_args(argv)
+
+
+def _outputs(inp,
+ out,
+ shard,
+ num_shards,
+ include_background=False,
+ background=None):
+ """Returns (input, voice, optional background) jobs and whether to resume.
+
+ Refuses outputs that would collide or overwrite an input.
+ """
+ if os.path.isdir(inp):
+ if background:
+ sys.exit("--background needs a single input file.")
+ if os.path.lexists(out) and not os.path.isdir(out):
+ sys.exit(f"A directory input needs an output directory, and {out}"
+ " is not one.")
+ if _inside(out, inp):
+ sys.exit(
+ "The output directory must be outside the input directory.")
+ files = _audio_files(inp)
+ pairs = [(
+ f,
+ os.path.join(out,
+ os.path.splitext(os.path.relpath(f, inp))[0] + ".wav"),
+ ) for f in files]
+ resume = True
+ else:
+ if os.path.isdir(out):
+ out = os.path.join(
+ out,
+ os.path.splitext(os.path.basename(inp))[0] + ".wav")
+ pairs, resume = [(inp, out)], False
+ jobs = [(src, dst,
+ (background or os.path.splitext(dst)[0] + "_background.wav")
+ if include_background else None) for src, dst in pairs]
+ if include_background and any(not path.lower().endswith(".wav")
+ for _, voice, noise in jobs
+ for path in (voice, noise)):
+ sys.exit("Voice/background outputs must be WAV files; use"
+ " --no-background for a voice-only output in another format.")
+ _check_destinations(jobs) # all shards share the same collision check
+ if resume:
+ try:
+ os.makedirs(out, exist_ok=True)
+ except OSError as error:
+ sys.exit(f"Cannot create the output directory {out}:"
+ f" {error.strerror}.")
+ return jobs[shard::num_shards] if resume else jobs, resume
+
+
+def _audio_files(folder):
+ """Lists the audio files below a folder, sorted, skipping hidden names.
+
+ The folder's path is taken literally (brackets, ``*`` and ``?`` in it are
+ not patterns); symlinked folders below it are followed.
+ """
+ found = []
+ for root, folders, names in os.walk(folder, followlinks=True):
+ folders[:] = [name for name in folders if not name.startswith(".")]
+ found += [
+ os.path.join(root, name)
+ for name in names
+ if not name.startswith(".") and name.lower().endswith(_EXTS)
+ ]
+ return sorted(path for path in found if os.path.isfile(path))
+
+
+def _inside(path, folder):
+ """Whether a path, existing or not, is an existing folder or lies in it.
+
+ The folders on the path are compared by identity, so ``folder`` spelled
+ another way counts: through a symlink, or in other case where the file
+ system ignores case.
+ """
+ current = os.path.realpath(path)
+ while True:
+ if os.path.exists(current) and os.path.samefile(current, folder):
+ return True
+ parent = os.path.dirname(current)
+ if parent == current:
+ return False
+ current = parent
+
+
+def _probe_paths(folder):
+ """Yields existing paths whose lookups follow a folder's rule on case.
+
+ First the folder's entries; then the folder itself and its ancestors, while
+ the parent each is looked up in is on the folder's device (a mount point
+ can change the rule).
+ """
+ try:
+ with os.scandir(folder) as entries:
+ yield from (entry.path for entry in entries)
+ except OSError:
+ pass
+ path, device = folder, os.stat(folder).st_dev
+ parent = os.path.dirname(path)
+ while parent != path and os.stat(parent).st_dev == device:
+ yield path
+ path, parent = parent, os.path.dirname(parent)
+
+
+def _ignores_case(folder):
+ """Whether an existing folder finds names whatever their case.
+
+ Looks the first name with an ASCII letter up again in the other case. A
+ folder with no such name to try (an empty volume root) gets a probe file
+ of its own; where none can be made, case is taken as ignored, so that
+ names differing only in case are refused rather than overwritten.
+ """
+ for path in _probe_paths(folder):
+ parent, name = os.path.split(path)
+ swapped = name.translate(_SWAP_CASE)
+ if swapped == name:
+ continue
+ try:
+ entry = os.lstat(path)
+ except OSError: # removed since it was listed
+ continue
+ if not stat.S_ISDIR(entry.st_mode) and entry.st_nlink > 1:
+ continue # a hard link may live under the swapped name too
+ try:
+ return os.path.samestat(entry,
+ os.lstat(os.path.join(parent, swapped)))
+ except OSError:
+ return False
+ try:
+ handle, probe = tempfile.mkstemp(dir=folder, prefix=".case-probe-")
+ os.close(handle)
+ except OSError:
+ return True
+ try:
+ parent, name = os.path.split(probe)
+ return os.path.lexists(os.path.join(parent, name.translate(_SWAP_CASE)))
+ finally:
+ os.unlink(probe)
+
+
+def _path_keys(path, folders):
+ """Identifies a path's aliases: symlinks, hard links and other cases.
+
+ A path is named below its deepest existing folder, its names folded when
+ that folder ignores case (folders created in it inherit the rule).
+ ``folders`` caches each such folder's identity and rule, so each folder is
+ probed once.
+ """
+ folder, names = os.path.realpath(path), ()
+ while True:
+ folder, name = os.path.split(folder)
+ names = (name,) + names
+ if folder in folders or os.path.isdir(folder) or not name:
+ break
+ if folder not in folders:
+ info = os.stat(folder)
+ folders[folder] = (info.st_dev, info.st_ino), _ignores_case(folder)
+ identity, ignores_case = folders[folder]
+ if ignores_case:
+ # where case is ignored, so is the Unicode form of an accent (APFS,
+ # HFS+); case-sensitive APFS ignores the form too, which this misses
+ names = tuple(
+ unicodedata.normalize("NFC", name).casefold() for name in names)
+ keys = {(identity, names)}
+ if os.path.exists(path):
+ info = os.stat(path)
+ keys.add((info.st_dev, info.st_ino))
+ return keys
+
+
+def _check_destinations(jobs):
+ """Refuses output collisions and writes over any input, across all jobs.
+
+ Either would silently lose audio (same.wav and same.flac, for example, or
+ a.wav and A.flac where the file system ignores case).
+ """
+ folders = {}
+ inputs = {
+ key: src for src, _, _ in jobs for key in _path_keys(src, folders)
+ }
+ seen = {}
+ for src, voice, background in jobs:
+ for dst in (voice, background):
+ if dst is None:
+ continue
+ if os.path.isdir(dst):
+ sys.exit(f"Output path is a directory: {dst}")
+ keys = _path_keys(dst, folders)
+ sources = keys & inputs.keys()
+ if sources:
+ original = inputs[next(iter(sources))]
+ sys.exit(f"{original} would be overwritten by an output"
+ f" ({dst}): choose another output path.")
+ shared = keys & seen.keys()
+ if shared:
+ previous, other = seen[next(iter(shared))]
+ writers = (f"The voice and the background of {src}"
+ if previous == src else f"{previous} and {src}")
+ alias = f" (the same file as {other})" if other != dst else ""
+ sys.exit(f"{writers} would both be written to {dst}{alias}:"
+ " choose different output names.")
+ seen.update(dict.fromkeys(keys, (src, dst)))
+
+
+def _save_pair(voice_path, background_path, voice, background, sample_rate):
+ """Stages both float WAVs before replacing outputs, keeping resume safe."""
+ staged = []
+ try:
+ for destination, signal in ((voice_path, voice), (background_path,
+ background)):
+ os.makedirs(os.path.dirname(os.path.abspath(destination)),
+ exist_ok=True)
+ staged.append(audio_lib.create_staging_file(destination, ".pair-"))
+ audio_lib.save_audio(staged[-1],
+ signal,
+ sample_rate,
+ subtype="FLOAT")
+ # A previous background must not make an interrupted replacement look
+ # complete after the new voice has been committed.
+ if os.path.lexists(background_path):
+ os.unlink(background_path)
+ os.replace(staged[0], voice_path)
+ os.replace(staged[1], background_path)
+ finally:
+ for path in staged:
+ if os.path.exists(path):
+ os.unlink(path)
+
+
+def _isolate(vi, x, sr, out_sr, args):
+ """Isolates one file at the output rate."""
+ kw = dict(
+ output_sample_rate=out_sr,
+ chunk_seconds=args.chunk_seconds,
+ overlap_seconds=args.overlap_seconds,
+ )
+ return vi.isolate(x, sr, **kw)
+
+
+def main(argv: list[str] | None = None) -> int:
+ """Isolates the requested audio and returns the command's exit status."""
+ args = parse_args(sys.argv[1:] if argv is None else argv)
+ if args.num_shards < 1 or not 0 <= args.shard < args.num_shards:
+ sys.exit(f"--shard must be in [0, --num-shards); got {args.shard} of"
+ f" {args.num_shards}.")
+ if args.output_sr < 0:
+ sys.exit("--output-sr must be positive, or 0 to keep the input rate.")
+ if args.background and args.mode != "offline":
+ sys.exit("--background is available only in offline mode.")
+ include_background = args.mode == "offline" and not args.no_background
+ jobs, resume = _outputs(args.input, args.output, args.shard,
+ args.num_shards, include_background,
+ args.background)
+ todo = [(src, voice, background)
+ for src, voice, background in jobs
+ if not (resume and os.path.isfile(voice) and
+ (background is None or os.path.isfile(background)))]
+ print(f"{len(jobs)} file(s), {len(todo)} to do", flush=True)
+ if not todo:
+ return 0
+ device = (torch.device(args.device)
+ if args.device else isolator.default_device())
+ _limit_macos_cpu_threads(device)
+ vi = isolator.VoiceIsolator.load(
+ args.model,
+ device=device,
+ precision=args.precision,
+ mode=args.mode,
+ lookahead_frames=args.lookahead,
+ block_frames=args.block_frames,
+ window_frames=args.window_frames,
+ crossfade_frames=args.crossfade_frames,
+ offline_passes=args.offline_passes,
+ )
+ subtype = "FLOAT" if args.float32 else "PCM_16"
+ t0, ok = time.time(), 0
+ for i, (src, dst, background) in enumerate(todo):
+ try:
+ x, sr = audio_lib.load_audio(src)
+ out_sr = sr if args.output_sr == 0 else args.output_sr
+ y = _isolate(vi, x, sr, out_sr, args)
+ if background is not None:
+ aligned = audio_lib.resample(x, sr, out_sr)
+ aligned = audio_lib.fit_length(aligned, y.shape[-1])
+ _save_pair(dst, background, y, aligned - y, out_sr)
+ else:
+ os.makedirs(os.path.dirname(os.path.abspath(dst)),
+ exist_ok=True)
+ audio_lib.save_audio(dst, y, out_sr, subtype=subtype)
+ ok += 1
+ # one bad file must not stop a batch; the exit status reports it
+ except Exception as e: # pylint: disable=broad-exception-caught
+ print(f"FAIL {src} {e}", flush=True)
+ if (i + 1) % 25 == 0:
+ el = time.time() - t0
+ print(f" {i + 1}/{len(todo)} {el / (i + 1):.2f}s/file",
+ flush=True)
+ print(f"DONE {ok}/{len(todo)} ({time.time() - t0:.0f}s)", flush=True)
+ return 0 if ok == len(todo) else 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/src/inworld/voice_isolation/doctor.py b/src/inworld/voice_isolation/doctor.py
new file mode 100644
index 0000000..9c5b6ec
--- /dev/null
+++ b/src/inworld/voice_isolation/doctor.py
@@ -0,0 +1,282 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""`voice-isolate-doctor`: whether this machine is ready to isolate voices.
+
+The default level reads only this machine: versions, the device inference
+would use and the weights already in the Hugging Face cache. ``--full`` also
+fetches both released models (or the given checkpoints) and runs half a second
+of silence through each. Every line carries a level, OK, INFO, WARN or FAIL,
+and the report ends with one summary line; the exit status is 1 when any line
+failed. ``--json`` prints the same report as one JSON object.
+
+Running this module imports the package, so it cannot diagnose an install that
+failed; it reports the versions an install produced.
+"""
+
+import argparse
+import dataclasses
+import importlib.util
+import json
+import platform
+import sys
+
+import numpy as np
+import torch
+import torchaudio
+
+from inworld import voice_isolation
+from inworld.voice_isolation import isolator
+from inworld.voice_isolation import registry
+
+OK, INFO, WARN, FAIL = "OK", "INFO", "WARN", "FAIL"
+# what the realtime model is run with: the README's 20 ms of look-ahead
+STREAM_LOOKAHEAD_FRAMES = 2
+# short windows make half a second of audio cross several crossfades, so the
+# stream's two-lane path runs too
+STREAM_WINDOW_FRAMES = 8
+STREAM_CROSSFADE_FRAMES = 4
+
+
+class Check:
+ """One line of the report."""
+ level: str
+ name: str
+ message: str
+
+
+def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
+ """Parses the doctor's options."""
+ p = argparse.ArgumentParser(
+ prog="voice-isolate-doctor",
+ description=("Checks whether this machine is ready to run the Inworld"
+ " Voice Isolator."),
+ )
+ p.add_argument(
+ "--full",
+ action="store_true",
+ help=("Also fetch both models (downloading them on first use) and run"
+ " half a second of silence through each."),
+ )
+ p.add_argument(
+ "--offline-model",
+ default=registry.REPO_ID,
+ help=("With --full: the offline checkpoint, as a registry name, an"
+ " hf:// location or a local file (default: the released"
+ " voice-isolator-v1)."),
+ )
+ p.add_argument(
+ "--online-model",
+ default=registry.REPO_ID,
+ help=("With --full: the streaming checkpoint, as a registry name, an"
+ " hf:// location or a local file (default: the released"
+ " voice-isolator-v1-realtime)."),
+ )
+ p.add_argument(
+ "--device",
+ default=None,
+ help="cpu, mps or cuda[:N] (default: the one inference would pick).",
+ )
+ p.add_argument("--json",
+ action="store_true",
+ help="Print the report as one JSON object.")
+ return p.parse_args(argv)
+
+
+def _environment() -> list[Check]:
+ return [
+ Check(INFO, "package",
+ f"inworld-voice-isolation {voice_isolation.__version__}"),
+ Check(INFO, "python",
+ f"Python {platform.python_version()} on {platform.platform()}"),
+ Check(
+ INFO, "torch",
+ f"torch {torch.__version__}, torchaudio {torchaudio.__version__}"),
+ ]
+
+
+def _device_check(device: torch.device, chosen: bool) -> Check:
+ """Reports the device; warns on an Apple-silicon Mac left on the CPU."""
+ old_torch = torch.torch_version.TorchVersion(
+ torch.__version__) < isolator.MPS_MIN_TORCH
+ if (not chosen and device.type == "cpu" and sys.platform == "darwin" and
+ platform.machine() == "arm64" and old_torch):
+ return Check(
+ WARN, "device",
+ f"cpu: upgrade torch to {isolator.MPS_MIN_TORCH} or later to use"
+ " the Metal GPU")
+ return Check(INFO, "device", f"inference runs on {device}")
+
+
+def _kernels_check() -> Check:
+ if importlib.util.find_spec("mamba_ssm") is not None:
+ return Check(INFO, "kernels", "optional CUDA kernels installed")
+ return Check(INFO, "kernels",
+ "optional CUDA kernels not installed (CUDA only, not needed)")
+
+
+def _cached_path(entry: dict) -> str | None:
+ """The cached file of a registry entry, or None when it is not cached."""
+ # pylint: disable-next=import-outside-toplevel
+ import huggingface_hub
+
+ found = huggingface_hub.try_to_load_from_cache(entry["repo_id"],
+ entry["filename"],
+ revision=entry["revision"])
+ return found if isinstance(found, str) else None
+
+
+def _cache_checks() -> tuple[list[Check], bool]:
+ """Checks each released model's cached file; also says whether all are."""
+ checks, all_cached = [], True
+ for name, entry in registry.MODELS.items():
+ if not entry["sha256"]:
+ checks.append(Check(INFO, name, "not released yet"))
+ continue
+ path = _cached_path(entry)
+ if path is None:
+ all_cached = False
+ checks.append(
+ Check(INFO, name, "not downloaded yet; run with --full"))
+ elif registry.sha256_file(path) != entry["sha256"]:
+ checks.append(
+ Check(FAIL, name,
+ f"checksum mismatch: delete {path} and run again"))
+ else:
+ checks.append(Check(OK, name, f"cached at {path}"))
+ return checks, all_cached
+
+
+def _hub_failure(name: str, spec: str, error: Exception) -> str:
+ """Says why ``registry.resolve`` could not fetch a model from the Hub.
+
+ For a released model ``registry.resolve`` wraps the Hub's error in a
+ RuntimeError; for an ``hf://`` location the Hub's own error arrives as it
+ was raised. Both are told apart here by the Hub error underneath.
+ """
+ # pylint: disable-next=import-outside-toplevel
+ from huggingface_hub import errors as hub_errors
+
+ if str(error).startswith("Checksum mismatch"):
+ entry = registry.MODELS.get(name) or {}
+ path = _cached_path(entry) if entry else None
+ return f"checksum mismatch: delete {path or 'the cached file'} and run again"
+ cause = error.__cause__ if isinstance(error, RuntimeError) else error
+ if isinstance(cause, hub_errors.HfHubHTTPError):
+ if spec.startswith(registry.HF_SCHEME):
+ return ("not reachable: check the location and your access to it,"
+ " or pass a local .safetensors file")
+ return (f"{registry.REPO_ID} is not reachable: pass --offline-model and"
+ " --online-model with local .safetensors files")
+ # what the Hub client raises when it has no connection and no cached copy
+ if isinstance(cause, hub_errors.LocalEntryNotFoundError):
+ return ("cannot reach huggingface.co: check the network, or pass a"
+ " local file")
+ return f"could not fetch {spec}: {cause or error}"
+
+
+def _run_model(path: str, mode: str, device: torch.device) -> None:
+ """Loads a checkpoint and runs half a second of silence through it."""
+ silence = np.zeros(voice_isolation.SR // 2, dtype=np.float32)
+ if mode == "offline":
+ model = isolator.VoiceIsolator.load(path, device=device, mode=mode)
+ model.isolate(silence, voice_isolation.SR)
+ return
+ model = isolator.VoiceIsolator.load(
+ path,
+ device=device,
+ mode=mode,
+ lookahead_frames=STREAM_LOOKAHEAD_FRAMES)
+ session = model.stream(window_frames=STREAM_WINDOW_FRAMES,
+ crossfade_frames=STREAM_CROSSFADE_FRAMES)
+ session.push(silence)
+ session.flush()
+
+
+def _model_check(spec: str, mode: str, device: torch.device) -> Check:
+ """Fetches one model and runs it; reports it under its release name."""
+ name = registry.MODE_MODELS[mode] if spec == registry.REPO_ID else spec
+ try:
+ path = registry.resolve(spec, mode)
+ # RuntimeError: a released model; OSError: the Hub's own error, raised
+ # as it is for an hf:// location
+ except (RuntimeError, OSError) as error:
+ return Check(FAIL, name, _hub_failure(name, spec, error))
+ except ValueError as error:
+ return Check(FAIL, name, str(error))
+ try:
+ _run_model(path, mode, device)
+ # any failure to load or run is reported as this model's FAIL line
+ except Exception as error: # pylint: disable=broad-exception-caught
+ hint = "" if device.type == "cpu" else ": try --device cpu"
+ return Check(FAIL, name, f"failed on {device}: {error}{hint}")
+ return Check(OK, name, f"loads and runs on {device}")
+
+
+def _summary(checks: list[Check], full: bool, all_cached: bool,
+ names: tuple[str, str], device: torch.device) -> str:
+ failed = sum(check.level == FAIL for check in checks)
+ if failed:
+ noun = "problem" if failed == 1 else "problems"
+ return f"{failed} {noun}: see the FAIL lines above"
+ if full:
+ return (f"All set: {names[0]} and {names[1]} on {device}"
+ f" (torch {torch.__version__})")
+ if not all_cached:
+ return "Ready to install weights: run voice-isolate-doctor --full"
+ return "Ready: run voice-isolate-doctor --full to run both models"
+
+
+def diagnose(args: argparse.Namespace) -> tuple[list[Check], str]:
+ """Runs the checks the options ask for; returns them and the summary."""
+ device = (torch.device(args.device)
+ if args.device else isolator.default_device())
+ checks = _environment()
+ checks.append(_device_check(device, chosen=args.device is not None))
+ checks.append(_kernels_check())
+ cache, all_cached = _cache_checks()
+ checks.extend(cache)
+ names = []
+ for spec, mode in ((args.offline_model, "offline"), (args.online_model,
+ "streaming")):
+ names.append(registry.MODE_MODELS[mode] if spec ==
+ registry.REPO_ID else spec)
+ if args.full:
+ checks.append(_model_check(spec, mode, device))
+ return checks, _summary(checks, args.full, all_cached, tuple(names), device)
+
+
+def main(argv: list[str] | None = None) -> int:
+ """Prints the report and returns 1 when any check failed, else 0."""
+ args = parse_args(sys.argv[1:] if argv is None else argv)
+ checks, summary = diagnose(args)
+ failed = any(check.level == FAIL for check in checks)
+ if args.json:
+ print(
+ json.dumps(
+ {
+ "checks": [dataclasses.asdict(c) for c in checks],
+ "summary": summary,
+ "ok": not failed,
+ },
+ indent=2))
+ else:
+ for check in checks:
+ print(f"{check.level:<4} {check.name}: {check.message}")
+ print(summary)
+ return 1 if failed else 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/src/inworld/voice_isolation/isolator.py b/src/inworld/voice_isolation/isolator.py
new file mode 100644
index 0000000..0971365
--- /dev/null
+++ b/src/inworld/voice_isolation/isolator.py
@@ -0,0 +1,603 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""VoiceIsolator, the public inference API, in offline or streaming mode."""
+
+from collections import abc
+import contextlib
+import dataclasses
+import functools
+import json
+
+import numpy as np
+import torch
+
+from inworld.voice_isolation import audio as audio_lib
+from inworld.voice_isolation import model as modeling
+from inworld.voice_isolation import registry
+from inworld.voice_isolation import streaming
+
+MODES = ("offline", "streaming")
+PRECISIONS = {"fp32": None, "fp16": torch.float16, "bf16": torch.bfloat16}
+# "auto": the training precision, bfloat16 autocast, on a CUDA device; float32
+# elsewhere, where bfloat16 autocast is slow or unsupported
+DEFAULT_PRECISION = "auto"
+STREAM_PIECE_SECONDS = 0.5
+STREAM_BATCH = 16
+STREAM_WINDOW_FRAMES = 600
+STREAM_CROSSFADE_FRAMES = 200
+
+# the first PyTorch whose MPS backend runs both released models and matches the
+# CPU: 2.2 lacks the FFT ops, 2.3 streams wrong output, 2.4 and 2.5 fail
+# offline (unsupported dtype, missing unfold_backward)
+MPS_MIN_TORCH = "2.6"
+
+
+def _mps_fft_matches_cpu() -> bool:
+ """Whether an FFT round trip on MPS runs and agrees with the CPU.
+
+ Catches the macOS releases whose Metal backend lacks the FFT.
+ """
+ x = torch.linspace(-1.0, 1.0, 64)
+ try:
+ y = torch.fft.irfft(torch.fft.rfft(x.to("mps")), n=64).cpu()
+ except (RuntimeError, NotImplementedError):
+ return False
+ return bool(torch.allclose(y, x, atol=1e-5))
+
+
+def default_device() -> torch.device:
+ """Returns the device a VoiceIsolator uses when none is given.
+
+ CUDA when available; else Apple's Metal backend (MPS) when available on
+ PyTorch ``MPS_MIN_TORCH`` or later and its FFT works; else the CPU. An
+ explicit ``device="mps"`` is honoured on any version.
+ """
+ if torch.cuda.is_available():
+ return torch.device("cuda")
+ if (torch.backends.mps.is_available() and torch.torch_version.TorchVersion(
+ torch.__version__) >= MPS_MIN_TORCH and _mps_fft_matches_cpu()):
+ return torch.device("mps")
+ return torch.device("cpu")
+
+
+def _windows(window_frames: int | None, crossfade_frames: int | None,
+ default: tuple) -> tuple:
+ """Resolves the stream's windowing: None takes the default, 0 turns it off.
+
+ Returns ``(window, crossfade)`` in frames, or ``(None, None)`` for the
+ plain stream whose attention looks back over its whole cache.
+ """
+ window = default[0] if window_frames is None else int(window_frames)
+ if not window:
+ return None, None
+ crossfade = default[1] if crossfade_frames is None else int(
+ crossfade_frames)
+ if not 0 < crossfade < window:
+ raise ValueError(
+ "crossfade_frames must be positive and shorter than window_frames.")
+ return window, crossfade
+
+
+_STATE_PREFIXES = ("_forward_module.", "module.", "model.", "isolator.")
+_TRAINING_ONLY_PREFIXES = (
+ "discriminator.",
+ "disc.",
+ "ema.",
+ "optimizer.",
+ "scheduler.",
+ "enhance_decoder.",
+ # the auxiliary decision head, trained beside the output and never served
+ "decision_head.",
+)
+
+
+def _strip_prefixes(state: dict) -> dict:
+ for p in _STATE_PREFIXES:
+ if any(k.startswith(p) for k in state):
+ state = {
+ (k[len(p):] if k.startswith(p) else k): v
+ for k, v in state.items()
+ }
+ return state
+
+
+def _architecture(raw: dict, path: str) -> dict:
+ """Finds the architecture dictionary inside a checkpoint's config."""
+ config = raw.get("config")
+ if isinstance(config, dict) and "modeling" in config:
+ config = config["modeling"].get("compact_family")
+ if not isinstance(config, dict) or "width" not in config:
+ raise ValueError(
+ f"{path}: no embedded architecture config; refusing to guess the"
+ " architecture.")
+ return config
+
+
+def read_checkpoint(path: str) -> tuple[dict, dict]:
+ """The architecture dictionary and the weights of a checkpoint.
+
+ Supported: a ``.safetensors`` file whose metadata carries the config JSON
+ (the release format), or a training checkpoint ``.pt``
+ holding plain tensors and the embedded architecture config. The weights
+ come with training wrapper prefixes stripped and training-side extras
+ still among them; ``build_model`` sorts those out.
+ """
+ if path.endswith(".safetensors"):
+ # pylint: disable-next=import-outside-toplevel
+ import safetensors.torch
+
+ with safetensors.safe_open(path, framework="pt") as f:
+ meta = f.metadata() or {}
+ if "config" not in meta:
+ raise ValueError(
+ f"{path}: safetensors metadata lacks the 'config' entry.")
+ return json.loads(meta["config"]), _strip_prefixes(
+ safetensors.torch.load_file(path))
+ try:
+ raw = torch.load(path, map_location="cpu", weights_only=True)
+ # torch raises several types here
+ except Exception as e: # pylint: disable=broad-exception-caught
+ raise ValueError(
+ f"{path}: not loadable as plain tensors ({type(e).__name__}); "
+ "checkpoints are never unpickled with code execution enabled; "
+ "export the weights to safetensors instead.") from e
+ if not isinstance(raw, dict):
+ raise ValueError(f"{path}: unsupported checkpoint object {type(raw)}.")
+ state = raw.get("model") or raw.get("state_dict") or raw
+ return _architecture(raw, path), _strip_prefixes(state)
+
+
+def build_model(
+ architecture: dict,
+ state: dict,
+ path: str,
+ device: str | torch.device = "cpu") -> modeling.VoiceIsolatorNetwork:
+ """The isolator of ``architecture`` carrying ``state``, in eval mode.
+
+ ``path`` names the checkpoint in error messages. Every learned weight must
+ be present; only training-side extras may be spare.
+ """
+ config = modeling.VoiceIsolatorConfig.from_dict(architecture)
+ model = modeling.VoiceIsolatorNetwork(config)
+ missing, unexpected = model.load_state_dict(state, strict=False)
+ _check_state_keys(path, missing, unexpected)
+ return model.to(device).eval()
+
+
+def load_model(
+ path: str,
+ device: str | torch.device = "cpu") -> modeling.VoiceIsolatorNetwork:
+ """Builds the isolator's network from a checkpoint, with its architecture.
+
+ The architecture is always taken from the checkpoint (see
+ ``read_checkpoint``), never from arguments.
+ """
+ architecture, state = read_checkpoint(path)
+ return build_model(architecture, state, path, device)
+
+
+def _check_state_keys(path: str, missing: list[str],
+ unexpected: list[str]) -> None:
+ """Requires every learned weight; only training-side extras may be spare."""
+ spare = [k for k in unexpected if not k.startswith(_TRAINING_ONLY_PREFIXES)]
+ if missing or spare:
+ raise RuntimeError(
+ f"{path}: checkpoint does not match the architecture: "
+ f"{len(missing)} missing key(s) {missing[:4]}, "
+ f"{len(spare)} unexpected key(s) {spare[:4]}.")
+
+
+class VoiceIsolator:
+ """Isolates voices at 48 kHz, offline for best quality or streaming.
+
+ Example:
+ from inworld import voice_isolation
+ isolator = voice_isolation.VoiceIsolator("inworld/voice-isolator")
+ voice = isolator.isolate(wav, sample_rate)
+
+ The constructor takes the Hub repository id (``mode`` picks its
+ checkpoint), a registry name, an ``hf://`` spec, a local checkpoint path
+ or a loaded network; ``load`` is the same call with the arguments
+ documented.
+
+ ``mode="streaming"`` runs a causal checkpoint such as
+ ``voice-isolator-v1-realtime``
+ (or a dual-mode one, the same weights run causally) with a trained
+ look-ahead of ``lookahead_frames`` frames: ``isolate`` then runs the
+ stream itself over the clip, exactly what a live session gives, and
+ ``stream()`` returns such a session for audio that arrives in pieces.
+ Offline, ``offline_passes`` runs the model again over its own output, in
+ the same chunks and precision: the checkpoint's own count unless one is
+ passed, one for the released files.
+ """
+
+ def __init__(
+ self,
+ model: modeling.VoiceIsolatorNetwork | str = registry.REPO_ID,
+ stage2: None = None,
+ device: str | torch.device | None = None,
+ precision: str = DEFAULT_PRECISION,
+ mode: str = "offline",
+ lookahead_frames: int = 0,
+ block_frames: int = 4,
+ cache_frames: int | None = None,
+ window_frames: int | None = None,
+ crossfade_frames: int | None = None,
+ offline_passes: int | None = None,
+ ) -> None:
+ # The digest-bound benchmark helpers still pass stage2=None.
+ if stage2 is not None:
+ raise ValueError("Stage-2 restoration is not supported; use"
+ " isolate() with a released model.")
+ if precision != "auto" and precision not in PRECISIONS:
+ raise ValueError(
+ f"precision must be 'auto' or one of {sorted(PRECISIONS)},"
+ f" got {precision!r}")
+ self.device = torch.device(device) if device else default_device()
+ if isinstance(model, str):
+ model = load_model(registry.resolve(model, mode), self.device)
+ if precision == "auto":
+ precision = "bf16" if self.device.type == "cuda" else "fp32"
+ self.precision = precision
+ self.model = model.to(self.device).eval()
+ self.offline_passes = _passes(offline_passes, self.model.config, mode)
+ if block_frames < 1:
+ raise ValueError("block_frames must be at least 1.")
+ self.block_frames = block_frames
+ if cache_frames is not None and cache_frames < 1:
+ raise ValueError("cache_frames must be at least 1.")
+ self.cache_frames = cache_frames
+ self.window_frames, self.crossfade_frames = _windows(
+ window_frames, crossfade_frames,
+ (STREAM_WINDOW_FRAMES, STREAM_CROSSFADE_FRAMES))
+ self._mode = None
+ self._lookahead = 0
+ self.lookahead_frames = lookahead_frames
+ self.mode = mode
+
+ @classmethod
+ def load(
+ cls,
+ model: str = registry.REPO_ID,
+ stage2: None = None,
+ device: str | torch.device | None = None,
+ precision: str = DEFAULT_PRECISION,
+ mode: str = "offline",
+ lookahead_frames: int = 0,
+ block_frames: int = 4,
+ cache_frames: int | None = None,
+ window_frames: int | None = None,
+ crossfade_frames: int | None = None,
+ offline_passes: int | None = None,
+ ) -> "VoiceIsolator":
+ """Loads a released model, an ``hf://`` spec or a local checkpoint.
+
+ The Hub repository id, ``inworld/voice-isolator``, loads the
+ checkpoint for ``mode``; a registry name loads one directly.
+ An ``hf://<org>/<repo>/<file>[@<revision>]`` spec names any file on the
+ Hub; local
+ checkpoints may be a ``.safetensors`` file or a training ``.pt``.
+ ``mode`` is "offline" (every frame sees its whole chunk) or
+ "streaming" (causal, with ``lookahead_frames`` frames of look-ahead,
+ one of the checkpoint's trained positions, processed ``block_frames``
+ frames at a time, the time attention remembering ``cache_frames``
+ frames, by default the checkpoint's attention window, else its
+ training chunk). In streaming
+ mode the time attention never looks back across a window of
+ ``window_frames`` frames: a second lane starts ``crossfade_frames``
+ before each boundary and the outputs blend over the crossfade
+ (``streaming.Stream`` has the semantics), which keeps a long session
+ from drifting. None takes the defaults (600 and 200 frames: 6 s
+ windows with a 2 s crossfade); 0 turns the
+ windows off, the attention then looking back over its whole cache.
+ ``precision``
+ "auto" (the default) runs the
+ network under bfloat16 autocast on a CUDA device, the precision it
+ was trained in, and in float32 elsewhere; "fp32", "fp16" or "bf16"
+ force one. The STFT, the iSTFT and the selective scan stay in
+ float32 in every case. ``offline_passes`` runs the offline model
+ again over its own output: None takes the checkpoint's own count (one
+ for the released files); each pass costs one offline render, so two
+ double the time. Above one it applies to offline mode only.
+ """
+ return cls(model,
+ stage2,
+ device,
+ precision=precision,
+ mode=mode,
+ lookahead_frames=lookahead_frames,
+ block_frames=block_frames,
+ cache_frames=cache_frames,
+ window_frames=window_frames,
+ crossfade_frames=crossfade_frames,
+ offline_passes=offline_passes)
+
+ @property
+ def sample_rate(self) -> int:
+ """The sample rate expected by the model, in Hz."""
+ return self.model.config.sample_rate
+
+ @property
+ def frame_seconds(self) -> float:
+ """The duration of one model frame, the unit of the look-ahead."""
+ return self.model.config.hop_length / self.sample_rate
+
+ @property
+ def lookahead_choices(self) -> tuple[int, ...]:
+ """The look-ahead positions, in frames, the checkpoint trained at."""
+ config = self.model.config
+ if config.lookahead_frames_choices:
+ return config.lookahead_frames_choices
+ return (config.lookahead_frames,) if config.causal else ()
+
+ @property
+ def mode(self) -> str:
+ """The active inference mode: offline or streaming."""
+ return self._mode
+
+ @mode.setter
+ def mode(self, mode: str) -> None:
+ """Selects an inference mode supported by the loaded checkpoint."""
+ if mode not in MODES:
+ raise ValueError(f"mode must be one of {MODES}, got {mode!r}.")
+ config = self.model.config
+ if mode == "offline":
+ if config.dual_mode:
+ self.model.set_offline()
+ elif config.causal:
+ raise ValueError("This checkpoint only streams; load it with"
+ " mode='streaming'.")
+ else:
+ if not self.lookahead_choices:
+ raise ValueError(
+ "This checkpoint has no streaming mode: it was trained"
+ " offline only.")
+ self.model.set_lookahead(self._lookahead)
+ self._mode = mode
+
+ @property
+ def lookahead_frames(self) -> int:
+ """The look-ahead of the streaming mode, in frames."""
+ return self._lookahead
+
+ @lookahead_frames.setter
+ def lookahead_frames(self, frames: int) -> None:
+ """Selects a trained look-ahead position for streaming inference."""
+ if self.lookahead_choices and frames not in self.lookahead_choices:
+ raise ValueError(
+ f"lookahead_frames must be one of {self.lookahead_choices}"
+ f" ({self.frame_seconds * 1000:g} ms each), got {frames}.")
+ self._lookahead = frames
+ if self._mode == "streaming":
+ self.model.set_lookahead(frames)
+
+ def latency_samples(self, block_frames: int | None = None) -> int:
+ """The streaming mode's algorithmic latency in samples.
+
+ The analysis window plus the look-ahead frames. ``block_frames`` is
+ accepted for compatibility and changes nothing: a frame is computed
+ as soon as its window is complete, so the block sets throughput, not
+ latency.
+ """
+ del block_frames
+ config = self.model.config
+ return config.n_fft + config.hop_length * self._lookahead
+
+ def _autocast(self):
+ if PRECISIONS[self.precision] is None:
+ return contextlib.nullcontext()
+ return torch.autocast(self.device.type,
+ dtype=PRECISIONS[self.precision])
+
+ def _stream_render(self, inp: torch.Tensor, lengths=None) -> torch.Tensor:
+ """The stream over ``inp`` [batch, samples] in half-second pieces."""
+ session = self.stream(lengths=lengths) # the session's own defaults
+ piece = int(STREAM_PIECE_SECONDS * self.sample_rate)
+ pieces = [
+ session.push(inp[:, i:i + piece])
+ for i in range(0, inp.shape[1], piece)
+ ]
+ pieces.append(session.flush())
+ return torch.cat(pieces, dim=1).to(inp.device)
+
+ def _prepare(self, audio, sample_rate) -> "_Prepared":
+ """Makes a clip mono, at the model rate and on the device."""
+ x = audio_lib.to_mono(audio)
+ if not x.numel():
+ raise ValueError("The audio is empty: there is nothing to isolate.")
+ if not torch.isfinite(x).all():
+ raise ValueError("The audio contains NaN or infinite samples.")
+ a = audio_lib.resample(x, sample_rate, self.sample_rate).to(self.device)
+ return _Prepared(a, x.shape[-1], isinstance(audio, np.ndarray))
+
+ def _finish(self, y, p: "_Prepared", sample_rate, output_sample_rate):
+ y = audio_lib.fit_length(y.float(), p.a.shape[-1])
+ out_sr = output_sample_rate or sample_rate
+ y = audio_lib.resample(y.cpu(), self.sample_rate, out_sr)
+ if out_sr == sample_rate:
+ y = audio_lib.fit_length(y, p.n_in)
+ return y.numpy() if p.as_numpy else y
+
+ def _separate(self, inp, chunk_kwargs):
+ """Runs the model over the prepared audio.
+
+ In streaming mode the stream itself runs over the clip; the chunks
+ of the offline render do not apply.
+ """
+ if self._mode == "streaming":
+ batched = inp.ndim == 2
+ out = self._stream_render(inp if batched else inp[None],
+ chunk_kwargs.get("lengths"))
+ return out if batched else out[0]
+ windows = {k: v for k, v in chunk_kwargs.items() if k != "lengths"}
+ with torch.inference_mode(), self._autocast():
+ out = self.model.enhance(inp, **windows)
+ # Each further pass reads the previous pass's output, in the
+ # same chunks and precision.
+ for _ in range(self.offline_passes - 1):
+ out = self.model.enhance(out, **windows)
+ return out
+
+ def _run(self, audio, sample_rate, output_sample_rate, chunk_kwargs):
+ p = self._prepare(audio, sample_rate)
+ y = self._separate(p.a, chunk_kwargs)
+ return self._finish(y, p, sample_rate, output_sample_rate)
+
+ def isolate_many(
+ self,
+ clips: abc.Sequence[np.ndarray | torch.Tensor],
+ sample_rate: int,
+ output_sample_rate: int | None = None,
+ chunk_seconds: float | None = None,
+ overlap_seconds: float | None = None,
+ ) -> list[np.ndarray | torch.Tensor]:
+ """Isolates several clips, one pass per group of equal lengths.
+
+ Offline nothing is padded, so each result matches ``isolate`` up to the
+ rounding of batched kernels. In streaming mode clips of similar length
+ stream in lockstep, padded with silence at their ends, which a causal
+ stream cannot see before it arrives; batching there multiplies
+ throughput. Returns the outputs in input order. Every prepared clip
+ sits on the device at once, so bound the list by the device's memory.
+ """
+ kw = _chunk_kwargs(chunk_seconds, overlap_seconds,
+ self.model.config.hop_length)
+ prepared = [self._prepare(c, sample_rate) for c in clips]
+ out = [None] * len(clips)
+ if self._mode == "streaming":
+ order = sorted(range(len(prepared)),
+ key=lambda i: -prepared[i].a.shape[-1])
+ batches = [
+ order[k:k + STREAM_BATCH]
+ for k in range(0, len(order), STREAM_BATCH)
+ ]
+ else:
+ groups: dict[int, list[int]] = {}
+ for i, p in enumerate(prepared):
+ groups.setdefault(p.a.shape[-1], []).append(i)
+ batches = list(groups.values())
+ for idx in batches:
+ longest = max(prepared[i].a.shape[-1] for i in idx)
+ inp = torch.stack(
+ [audio_lib.fit_length(prepared[i].a, longest) for i in idx])
+ lengths = [prepared[i].a.shape[-1] for i in idx]
+ y = self._separate(inp, dict(kw, lengths=lengths))
+ for j, i in enumerate(idx):
+ out[i] = self._finish(y[j], prepared[i], sample_rate,
+ output_sample_rate)
+ return out
+
+ def isolate(
+ self,
+ audio: np.ndarray | torch.Tensor,
+ sample_rate: int,
+ output_sample_rate: int | None = None,
+ chunk_seconds: float | None = None,
+ overlap_seconds: float | None = None,
+ ) -> np.ndarray | torch.Tensor:
+ """Isolates the voice, at the input rate unless overridden.
+
+ Offline, long audio runs in overlapping chunks (``chunk_seconds``,
+ ``overlap_seconds``); in streaming mode the stream itself runs over the
+ clip and the chunks do not apply.
+ """
+ return self._run(
+ audio,
+ sample_rate,
+ output_sample_rate,
+ _chunk_kwargs(chunk_seconds, overlap_seconds,
+ self.model.config.hop_length),
+ )
+
+ def stream(self,
+ block_frames: int | None = None,
+ cache_frames: int | None = None,
+ lengths: list[int] | None = None,
+ window_frames: int | None = None,
+ crossfade_frames: int | None = None) -> streaming.Stream:
+ """Starts a streaming session (``mode="streaming"`` only).
+
+ Push mono float samples at ``sample_rate`` in pieces of any size and
+ receive the output samples that became final; ``flush`` returns the
+ rest. Up to ``block_frames`` frames are computed together, a
+ throughput knob: a frame is computed as soon as its analysis window
+ is complete, so the block adds no latency. ``cache_frames`` bounds the
+ time attention's past (the session's default, else the checkpoint's
+ attention window, else its training chunk); a checkpoint with an
+ attention window never looks further back than that, and for any
+ other a longer memory than the model was trained with is outside its
+ training distribution. ``window_frames`` and
+ ``crossfade_frames`` bound the attention to windows with a crossfaded
+ second lane: None keeps the session's, 0 turns the windows off. A
+ batch of clips padded to one length passes ``lengths``, each clip's
+ own.
+ """
+ if self._mode != "streaming":
+ raise RuntimeError(
+ "stream() needs mode='streaming'; set the isolator's mode"
+ " first.")
+ window, crossfade = _windows(
+ window_frames, crossfade_frames,
+ (self.window_frames or 0, self.crossfade_frames or
+ STREAM_CROSSFADE_FRAMES))
+ return streaming.Stream(self.model,
+ block_frames=block_frames or self.block_frames,
+ cache_frames=cache_frames or self.cache_frames,
+ autocast_dtype=PRECISIONS[self.precision],
+ lengths=lengths,
+ window_frames=window,
+ crossfade_frames=crossfade)
+
+
+class _Prepared:
+ """A clip ready for the model: audio on the device, length and type."""
+
+ a: torch.Tensor
+ n_in: int
+ as_numpy: bool
+
+
+def _passes(requested, config, mode: str) -> int:
+ """Returns the offline passes: the checkpoint's own count unless one is
+ requested, a requested count checked against the checkpoint and the
+ mode."""
+ if requested is None:
+ return config.offline_passes
+ if (isinstance(requested, bool) or not isinstance(requested, int) or
+ requested < 1):
+ raise ValueError("offline_passes must be a whole number of passes, at"
+ f" least 1, got {requested!r}.")
+ if requested > 1 and (config.causal or mode == "streaming"):
+ raise ValueError(
+ "offline_passes above 1 applies to the offline mode of a"
+ " two-sided or dual-mode checkpoint.")
+ return requested
+
+
+def _chunk_kwargs(chunk_seconds, overlap_seconds, min_samples: int) -> dict:
+ """Returns the window settings to pass on, checked before any audio."""
+ kw = {}
+ if chunk_seconds is not None:
+ kw["chunk_seconds"] = chunk_seconds
+ if overlap_seconds is not None:
+ kw["overlap_seconds"] = overlap_seconds
+ modeling.window_samples(
+ kw.get("chunk_seconds", 1.0),
+ kw.get("overlap_seconds", 0.0),
+ audio_lib.SR,
+ min_samples,
+ )
+ return {k: float(v) for k, v in kw.items()}
diff --git a/src/inworld/voice_isolation/model.py b/src/inworld/voice_isolation/model.py
new file mode 100644
index 0000000..5580491
--- /dev/null
+++ b/src/inworld/voice_isolation/model.py
@@ -0,0 +1,798 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The isolator: a band-split dual-path network over the 48 kHz STFT.
+
+Each frame's spectrum is cut into bands, every band becomes one token, and
+blocks of time attention (rotary positions, exclusive self attention) and
+dual-path Mamba (along time, then across bands) refine the tokens before
+per-band heads predict a bounded complex mask and a bounded residual per
+bin. A checkpoint is either two-sided (offline: every frame sees its whole
+chunk; a dual-mode one also runs causally with the same weights) or causal
+only (streaming: attention and the time scan are causal and the decoder's
+output for a frame is read a trained number of frames later, the
+look-ahead). A causal checkpoint may bound its time attention to a window of
+frames (``attention_window_frames``); the stream keeps the same bound.
+"""
+
+import dataclasses
+import math
+
+import torch
+
+from inworld.voice_isolation import scan
+
+TRANSFORMER = "transformer"
+MAMBA = "mamba"
+BLOCK_TYPES = (TRANSFORMER, MAMBA)
+EXCLUSIVE_AXES = ("both", "time", "band")
+DEFAULT_BAND_PLAN = ((100, 1000), (250, 4000), (500, 8000), (1000, 16000),
+ (2000, 24000))
+TRAINING_ONLY_FIELDS = frozenset({
+ "activation_checkpointing",
+ "checkpoint_every",
+ "attention_backend",
+ "offline_mode_prob",
+ "dual_distill",
+ "hint_sha256",
+ "hint_bf16",
+ "grid_width",
+ "grid_hidden",
+ "grid_kernel",
+ "grid_stride",
+ "grid_heads",
+ "grid_qk_channels",
+ "grid_output",
+ "grid_normalize_input",
+ "decision_head",
+})
+
+REQUIRED_VALUES = {
+ "representation": "bands",
+ "decoder_type": "complex_mask_residual",
+ "hint_checkpoint": None,
+}
+
+
[email protected](frozen=True)
+class VoiceIsolatorConfig:
+ """Architecture of a checkpoint; always read from the checkpoint."""
+
+ width: int = 320
+ block_types: tuple[str, ...] = (TRANSFORMER, MAMBA, TRANSFORMER, MAMBA,
+ TRANSFORMER, MAMBA, TRANSFORMER)
+ num_heads: int = 8
+ n_fft: int = 2048
+ hop_length: int = 480
+ sample_rate: int = 48000
+ band_plan: tuple[tuple[int, int], ...] = DEFAULT_BAND_PLAN
+ correction_bound: float = 0.5
+ chunk_seconds: float = 12.0
+ overlap_seconds: float = 2.0
+ exclusive_self_attention: bool = True
+ exclusive_axes: str = "time"
+ mamba_state: int = 16
+ mamba_conv: int = 4
+ mamba_expand: int = 2
+ causal: bool = False
+ lookahead_frames: int = 0
+ lookahead_frames_choices: tuple[int, ...] = ()
+ dual_mode: bool = False
+ mode_film: bool = False
+ attention_window_frames: int = 0
+ offline_passes: int = 1
+
+ def __post_init__(self) -> None:
+ object.__setattr__(self, "block_types", tuple(self.block_types))
+ object.__setattr__(self, "band_plan",
+ tuple(tuple(pair) for pair in self.band_plan))
+ object.__setattr__(self, "lookahead_frames_choices",
+ tuple(self.lookahead_frames_choices))
+ if self.width < 1 or self.num_heads < 1 or self.width % (
+ 2 * self.num_heads):
+ raise ValueError(
+ "width must be a positive multiple of twice num_heads.")
+ if not self.block_types or any(
+ kind not in BLOCK_TYPES for kind in self.block_types):
+ raise ValueError(f"block_types must be drawn from {BLOCK_TYPES}.")
+ if self.n_fft < 4 or self.n_fft % 2 or not (0 < self.hop_length <=
+ self.n_fft // 2):
+ raise ValueError(
+ "n_fft must be even and hop_length within (0, n_fft / 2].")
+ if self.sample_rate < 1 or not self.band_plan or any(
+ width < 1 or upto < 1 for width, upto in self.band_plan):
+ raise ValueError("band_plan needs positive widths and limits.")
+ if not 0 < self.correction_bound < 1:
+ raise ValueError("correction_bound must lie in (0, 1).")
+ if (self.chunk_seconds * self.sample_rate < self.n_fft or
+ not 0 < self.overlap_seconds <= self.chunk_seconds / 2):
+ raise ValueError(
+ "chunk_seconds must cover one window and overlap_seconds lie"
+ " in (0, chunk_seconds / 2].")
+ if self.exclusive_axes not in EXCLUSIVE_AXES:
+ raise ValueError(f"exclusive_axes must be one of {EXCLUSIVE_AXES}.")
+ if min(self.mamba_state, self.mamba_conv, self.mamba_expand) < 1:
+ raise ValueError("Mamba dimensions must be positive.")
+ choices = self.lookahead_frames_choices
+ if list(choices) != sorted(set(choices)) or (choices and
+ choices[0] < 0):
+ raise ValueError(
+ "lookahead_frames_choices must be distinct non-negative frame"
+ " counts in ascending order.")
+ if self.lookahead_frames < 0:
+ raise ValueError("lookahead_frames cannot be negative.")
+ if choices and self.lookahead_frames not in choices:
+ raise ValueError(
+ "lookahead_frames must be one of lookahead_frames_choices.")
+ if (self.lookahead_frames > 0 or
+ choices) and not (self.causal or self.dual_mode):
+ raise ValueError("A look-ahead needs a causal or dual-mode model.")
+ if self.dual_mode and (self.causal or not choices):
+ raise ValueError(
+ "dual_mode builds a two-sided model switched per forward:"
+ " leave causal off and list the streaming positions.")
+ if self.mode_film and not choices:
+ raise ValueError("mode_film needs lookahead_frames_choices.")
+ if self.attention_window_frames < 0 or (self.attention_window_frames and
+ not self.causal):
+ raise ValueError(
+ "attention_window_frames needs a causal model and cannot be"
+ " negative.")
+ if (isinstance(self.offline_passes, bool) or
+ not isinstance(self.offline_passes, int) or
+ self.offline_passes < 1):
+ raise ValueError(
+ "offline_passes must be a whole number of passes, at least 1.")
+ if self.offline_passes > 1 and self.causal:
+ raise ValueError(
+ "A causal model streams in one pass: offline_passes above 1"
+ " needs a two-sided or dual-mode model.")
+
+ @classmethod
+ def from_dict(cls, raw: dict) -> "VoiceIsolatorConfig":
+ """Builds the config from a checkpoint's architecture dictionary.
+
+ Training-only fields are ignored; a value this package does not
+ implement is refused rather than guessed.
+ """
+ known = {f.name for f in dataclasses.fields(cls)}
+ for name, value in REQUIRED_VALUES.items():
+ if raw.get(name, value) != value:
+ raise ValueError(
+ f"This package implements {name}={value!r}, not"
+ f" {raw[name]!r}.")
+ unknown = sorted(
+ name for name, value in raw.items()
+ if name not in known and name not in TRAINING_ONLY_FIELDS and
+ name not in REQUIRED_VALUES and value not in (0, False, None, "",
+ [], {}))
+ if unknown:
+ raise ValueError(
+ "Checkpoint config uses fields this package does not"
+ f" implement: {unknown}. Upgrade inworld-voice-isolation.")
+ return cls(**{name: raw[name] for name in known if name in raw})
+
+ def to_dict(self) -> dict:
+ """The config as plain JSON-ready values."""
+ return dataclasses.asdict(self)
+
+
+def band_edges(config: VoiceIsolatorConfig) -> list[tuple[int, int]]:
+ """Bin ranges [start, end) of the bands, covering every bin once."""
+ n_bins = config.n_fft // 2 + 1
+ hz_per_bin = config.sample_rate / config.n_fft
+ edges: list[tuple[int, int]] = []
+ start = 0
+ for width_hz, upto_hz in config.band_plan:
+ width = max(1, round(width_hz / hz_per_bin))
+ upto = min(n_bins, round(upto_hz / hz_per_bin))
+ while start < upto:
+ end = min(start + width, upto)
+ edges.append((start, end))
+ start = end
+ if start < n_bins:
+ edges.append((start, n_bins))
+ return edges
+
+
+def rope_tables(frames: int, head_dim: int, device,
+ dtype) -> tuple[torch.Tensor, torch.Tensor]:
+ """Cosine and sine tables [frames, head_dim / 2] of rotary positions."""
+ half = head_dim // 2
+ inv = 10000.0**(-torch.arange(0, half, device=device, dtype=torch.float32) /
+ half)
+ pos = torch.arange(frames, device=device, dtype=torch.float32)
+ angles = torch.outer(pos, inv)
+ return angles.cos().to(dtype), angles.sin().to(dtype)
+
+
+def apply_rope(x: torch.Tensor, cos: torch.Tensor,
+ sin: torch.Tensor) -> torch.Tensor:
+ """Rotates ``x`` [batch, heads, frames, head_dim] by the tables."""
+ half = x.shape[-1] // 2
+ x1, x2 = x[..., :half], x[..., half:]
+ c, s = cos[None, None], sin[None, None]
+ return torch.cat((x1 * c - x2 * s, x1 * s + x2 * c), dim=-1)
+
+
+def exclusive(output: torch.Tensor, value: torch.Tensor) -> torch.Tensor:
+ """Removes each token's component along its own value, in float32."""
+ o32, v32 = output.float(), value.float()
+ coefficient = (o32 * v32).sum(-1, keepdim=True) / (v32 * v32).sum(
+ -1, keepdim=True).clamp_min(1e-6)
+ return (o32 - coefficient * v32).to(output.dtype)
+
+
+def bounded_correction(raw: torch.Tensor, reference: torch.Tensor,
+ bound: float) -> torch.Tensor:
+ """Bounds each complex correction's magnitude relative to its bin."""
+ components = torch.tanh(raw.float())
+ norm = torch.linalg.vector_norm(components, dim=-1,
+ keepdim=True).clamp(min=1)
+ return components / norm * (bound * reference.abs()[..., None])
+
+
+def window_mask(frames: int, window: int, device) -> torch.Tensor:
+ """[frames, frames] causal mask that also drops keys ``window`` or more
+ frames behind the query: each frame sees itself and the ``window - 1``
+ frames before it."""
+ positions = torch.arange(frames, device=device)
+ lag = positions[:, None] - positions[None, :]
+ return (lag >= 0) & (lag < window)
+
+
+class _TimeAttention(torch.nn.Module):
+ """Self attention along time with rotary positions.
+
+ ``window`` > 0 (causal only) bounds every frame's past to that many
+ frames, itself included, the attention window the checkpoint was trained
+ with; streaming keeps the same bound over its cache.
+ """
+
+ def __init__(self,
+ width: int,
+ num_heads: int,
+ exclusive_attention: bool,
+ window: int = 0):
+ super().__init__()
+ self.num_heads = num_heads
+ self.head_dim = width // num_heads
+ self.exclusive = exclusive_attention
+ self.window = window
+ self.qkv = torch.nn.Linear(width, 3 * width)
+ self.proj = torch.nn.Linear(width, width)
+
+ def forward(self, x: torch.Tensor, causal: bool) -> torch.Tensor:
+ batch, frames, width = x.shape
+ qkv = self.qkv(x).view(batch, frames, 3, self.num_heads,
+ self.head_dim).permute(2, 0, 3, 1, 4)
+ query, key, value = qkv.unbind(0)
+ cos, sin = rope_tables(frames, self.head_dim, x.device, query.dtype)
+ query, key = apply_rope(query, cos, sin), apply_rope(key, cos, sin)
+ if causal and 0 < self.window < frames:
+ output = torch.nn.functional.scaled_dot_product_attention(
+ query,
+ key,
+ value,
+ attn_mask=window_mask(frames, self.window, x.device))
+ else:
+ output = torch.nn.functional.scaled_dot_product_attention(
+ query, key, value, is_causal=causal)
+ if self.exclusive:
+ output = exclusive(output, value)
+ return self.proj(output.transpose(1, 2).reshape(batch, frames, width))
+
+
+class _TimeBlock(torch.nn.Module):
+ """A pre-norm transformer layer along time."""
+
+ def __init__(self, config: VoiceIsolatorConfig, exclusive_attention: bool):
+ super().__init__()
+ width = config.width
+ self.norm1 = torch.nn.LayerNorm(width)
+ self.attn = _TimeAttention(width, config.num_heads, exclusive_attention,
+ config.attention_window_frames)
+ self.norm2 = torch.nn.LayerNorm(width)
+ self.ffn = torch.nn.Sequential(
+ torch.nn.Linear(width, 4 * width),
+ torch.nn.GELU(),
+ torch.nn.Identity(),
+ torch.nn.Linear(4 * width, width),
+ )
+
+ def forward(self, x: torch.Tensor, causal: bool) -> torch.Tensor:
+ x = x + self.attn(self.norm1(x), causal)
+ return x + self.ffn(self.norm2(x))
+
+
+class _BandTransformer(torch.nn.Module):
+ """A pre-norm transformer layer across the bands of one frame."""
+
+ def __init__(self, config: VoiceIsolatorConfig, exclusive_attention: bool):
+ super().__init__()
+ width = config.width
+ self.exclusive = exclusive_attention
+ self.self_attn = torch.nn.MultiheadAttention(width,
+ config.num_heads,
+ batch_first=True)
+ self.linear1 = torch.nn.Linear(width, 4 * width)
+ self.linear2 = torch.nn.Linear(4 * width, width)
+ self.norm1 = torch.nn.LayerNorm(width)
+ self.norm2 = torch.nn.LayerNorm(width)
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ batch, bands, width = x.shape
+ heads = self.self_attn.num_heads
+ qkv = torch.nn.functional.linear(self.norm1(x),
+ self.self_attn.in_proj_weight,
+ self.self_attn.in_proj_bias)
+ qkv = qkv.view(batch, bands, 3, heads,
+ width // heads).permute(2, 0, 3, 1, 4)
+ query, key, value = qkv.unbind(0)
+ output = torch.nn.functional.scaled_dot_product_attention(
+ query, key, value)
+ if self.exclusive:
+ output = exclusive(output, value)
+ x = x + self.self_attn.out_proj(
+ output.transpose(1, 2).reshape(batch, bands, width))
+ return x + self.linear2(
+ torch.nn.functional.gelu(self.linear1(self.norm2(x))))
+
+
+class DualPathAttention(torch.nn.Module):
+ """Attention along time within each band, then across bands."""
+
+ def __init__(self, config: VoiceIsolatorConfig):
+ super().__init__()
+ on_time = config.exclusive_self_attention and config.exclusive_axes in (
+ "both", "time")
+ on_band = config.exclusive_self_attention and config.exclusive_axes in (
+ "both", "band")
+ self.time_transformer = _TimeBlock(config, on_time)
+ self.band_transformer = _BandTransformer(config, on_band)
+
+ def forward(self, x: torch.Tensor, causal: bool) -> torch.Tensor:
+ batch, bands, frames, width = x.shape
+ x = self.time_transformer(x.reshape(batch * bands, frames, width),
+ causal)
+ x = x.reshape(batch, bands, frames, width).permute(0, 2, 1, 3)
+ x = self.band_transformer(x.reshape(batch * frames, bands, width))
+ return x.reshape(batch, frames, bands, width).permute(0, 2, 1, 3)
+
+
+class Mamba(torch.nn.Module):
+ """One selective state-space layer, with a carried state for streams."""
+
+ def __init__(self, width: int, state: int, convolution: int, expand: int):
+ super().__init__()
+ inner = expand * width
+ self.d_state = state
+ self.dt_rank = math.ceil(width / 16)
+ self.in_proj = torch.nn.Linear(width, 2 * inner, bias=False)
+ self.conv1d = torch.nn.Conv1d(inner,
+ inner,
+ convolution,
+ groups=inner,
+ padding=convolution - 1)
+ self.x_proj = torch.nn.Linear(inner,
+ self.dt_rank + 2 * state,
+ bias=False)
+ self.dt_proj = torch.nn.Linear(self.dt_rank, inner)
+ self.A_log = torch.nn.Parameter(
+ torch.log(torch.arange(1, state + 1,
+ dtype=torch.float32)).repeat(inner, 1))
+ self.D = torch.nn.Parameter(torch.ones(inner))
+ self.out_proj = torch.nn.Linear(inner, width, bias=False)
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ state: tuple[torch.Tensor, torch.Tensor] | None = None,
+ ) -> tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor]]:
+ frames = x.shape[1]
+ xz = self.in_proj(x)
+ u, z = xz.chunk(2, dim=-1)
+ history = u.transpose(1, 2)
+ if state is not None:
+ history = torch.cat((state[0].to(history.dtype), history), dim=-1)
+ convolved = torch.nn.functional.conv1d(
+ history,
+ self.conv1d.weight.to(history.dtype),
+ self.conv1d.bias.to(history.dtype),
+ padding=0 if state is not None else self.conv1d.padding[0],
+ groups=self.conv1d.groups,
+ )[..., :frames]
+ needed = self.conv1d.kernel_size[0] - 1
+ padded = torch.nn.functional.pad(history, (needed, 0))
+ tail = padded[..., padded.shape[-1] - needed:]
+ u = torch.nn.functional.silu(convolved).transpose(1, 2)
+ dt, b, c = torch.split(self.x_proj(u),
+ [self.dt_rank, self.d_state, self.d_state],
+ dim=-1)
+ delta = torch.nn.functional.softplus(
+ torch.nn.functional.linear(dt, self.dt_proj.weight).float() +
+ self.dt_proj.bias.float())
+ y, ssm = scan.selective_scan(u, delta, -torch.exp(self.A_log.float()),
+ b, c, self.D, z,
+ None if state is None else state[1])
+ return self.out_proj(y.to(xz.dtype)), (tail, ssm)
+
+
+class BidirectionalMamba(torch.nn.Module):
+ """Forward and backward scans projected together; forward only if causal."""
+
+ def __init__(self, width: int, state: int, convolution: int, expand: int,
+ causal: bool):
+ super().__init__()
+ self.causal = causal
+ self.forward_blocks = Mamba(width, state, convolution, expand)
+ self.backward_blocks = None if causal else Mamba(
+ width, state, convolution, expand)
+ self.output_proj = torch.nn.Linear(width if causal else 2 * width,
+ width)
+ self.norm = torch.nn.LayerNorm(width)
+
+ def forward(self, x: torch.Tensor, causal: bool = False) -> torch.Tensor:
+ forward, _ = self.forward_blocks(x)
+ if self.causal:
+ return self.norm(self.output_proj(forward + x))
+ if causal:
+ return self.norm(
+ self.output_proj(
+ torch.cat((forward + x, torch.zeros_like(x)), dim=-1)))
+ backward, _ = self.backward_blocks(x.flip(1))
+ return self.norm(
+ self.output_proj(
+ torch.cat((forward + x, backward.flip(1) + x), dim=-1)))
+
+
+class DualPathMamba(torch.nn.Module):
+ """Mamba along time within each band, then across bands."""
+
+ def __init__(self, config: VoiceIsolatorConfig):
+ super().__init__()
+ arguments = (config.width, config.mamba_state, config.mamba_conv,
+ config.mamba_expand)
+ self.time_mamba = BidirectionalMamba(*arguments, causal=config.causal)
+ self.freq_mamba = BidirectionalMamba(*arguments, causal=False)
+
+ def forward(self, x: torch.Tensor, causal: bool) -> torch.Tensor:
+ batch, bands, frames, width = x.shape
+ time = x.reshape(batch * bands, frames, width)
+ time = time + self.time_mamba(time, causal)
+ frequency = time.reshape(batch, bands, frames,
+ width).transpose(1, 2).reshape(
+ batch * frames, bands, width)
+ frequency = frequency + self.freq_mamba(frequency)
+ return frequency.reshape(batch, frames, bands,
+ width).transpose(1, 2).contiguous()
+
+
+class _Decoder(torch.nn.Module):
+ """Per-band heads: a complex mask and a residual for every bin."""
+
+ def __init__(self, width: int, edges: list[tuple[int, int]]):
+ super().__init__()
+ self.edges = edges
+ self.condition = torch.nn.Linear(2, 2 * width)
+ self.register_buffer("controls",
+ torch.tensor([1.0, 0.0]),
+ persistent=False)
+ torch.nn.init.zeros_(self.condition.weight)
+ torch.nn.init.zeros_(self.condition.bias)
+ self.heads = torch.nn.ModuleList()
+ for start, end in edges:
+ head = torch.nn.Sequential(
+ torch.nn.LayerNorm(width),
+ torch.nn.Linear(width, width),
+ torch.nn.GELU(),
+ torch.nn.Linear(width, 4 * (end - start)),
+ )
+ torch.nn.init.zeros_(head[-1].weight)
+ torch.nn.init.zeros_(head[-1].bias)
+ self.heads.append(head)
+
+ def forward(self, features: torch.Tensor) -> torch.Tensor:
+ batch, _, frames, _ = features.shape
+ scale, shift = self.condition(self.controls).chunk(2, dim=-1)
+ features = features * (1 + scale) + shift
+ return torch.cat([
+ head(features[:, index]).float().reshape(batch, frames, end - start,
+ 4)
+ for index, ((start, end),
+ head) in enumerate(zip(self.edges, self.heads))
+ ],
+ dim=2).permute(0, 2, 1, 3)
+
+
+def read_ahead(raw: torch.Tensor, frames: int) -> torch.Tensor:
+ """The decoder's output for frame t taken from frame t + ``frames``.
+
+ The last frame serves every frame beyond it.
+ """
+ total = raw.shape[2]
+ index = (torch.arange(total, device=raw.device) + frames).clamp(max=total -
+ 1)
+ return raw[:, :, index]
+
+
+def window_samples(
+ chunk_seconds: float,
+ overlap_seconds: float,
+ sample_rate: int,
+ min_samples: int = 1,
+) -> tuple[int, int]:
+ """Returns the window and its crossfade in samples.
+
+ The crossfade is capped at half the window.
+
+ Raises:
+ ValueError: A length is not a finite number, the window is shorter than
+ ``min_samples``, or the crossfade is negative. Such settings would
+ drop or blank audio.
+ """
+ lengths = {}
+ for name, value in (
+ ("chunk_seconds", chunk_seconds),
+ ("overlap_seconds", overlap_seconds),
+ ):
+ try:
+ lengths[name] = float(value)
+ except (TypeError, ValueError):
+ raise ValueError(
+ f"{name} must be a number of seconds, not {value!r}") from None
+ if not math.isfinite(lengths[name]):
+ raise ValueError(f"{name} must be finite, not {value!r}")
+ chunk = int(lengths["chunk_seconds"] * sample_rate)
+ if chunk < min_samples:
+ raise ValueError(f"chunk_seconds={chunk_seconds!r} is shorter than "
+ f"{1000 * min_samples / sample_rate:g} ms")
+ if lengths["overlap_seconds"] < 0:
+ raise ValueError(
+ f"overlap_seconds must not be negative, not {overlap_seconds!r}")
+ return chunk, min(int(lengths["overlap_seconds"] * sample_rate), chunk // 2)
+
+
+class VoiceIsolatorNetwork(torch.nn.Module):
+ """The isolator's network over one chunk of audio, in either of its modes.
+
+ ``forward`` takes a batch of equally long mono clips at the model rate
+ and returns the isolated voice; ``enhance`` renders clips of any length
+ in overlapping chunks. A dual-mode checkpoint starts offline;
+ ``set_lookahead`` moves it to one of its trained streaming positions and
+ ``set_offline`` back.
+ """
+
+ def __init__(self, config: VoiceIsolatorConfig) -> None:
+ super().__init__()
+ self.config = config
+ self.edges = band_edges(config)
+ self.encoders = torch.nn.ModuleList([
+ torch.nn.Sequential(
+ torch.nn.LayerNorm(2 * (end - start)),
+ torch.nn.Linear(2 * (end - start), config.width))
+ for start, end in self.edges
+ ])
+ self.band_embedding = torch.nn.Parameter(
+ torch.randn(len(self.edges), config.width) * 0.02)
+ choices = config.lookahead_frames_choices
+ if choices:
+ positions = len(choices) + (1 if config.dual_mode else 0)
+ self.lookahead_embedding = torch.nn.Embedding(
+ positions, config.width)
+ torch.nn.init.zeros_(self.lookahead_embedding.weight)
+ self.register_buffer("lookahead_choices",
+ torch.tensor(choices),
+ persistent=False)
+ default = (len(choices) if config.dual_mode else choices.index(
+ config.lookahead_frames))
+ self.register_buffer("lookahead_index",
+ torch.tensor(default),
+ persistent=False)
+ if config.mode_film:
+ self.mode_film = torch.nn.Embedding(
+ positions, 2 * len(config.block_types) * config.width)
+ torch.nn.init.zeros_(self.mode_film.weight)
+ self.blocks = torch.nn.ModuleList([
+ DualPathAttention(config)
+ if kind == TRANSFORMER else DualPathMamba(config)
+ for kind in config.block_types
+ ])
+ self.denoise_decoder = _Decoder(config.width, self.edges)
+ self.register_buffer("window",
+ torch.hann_window(config.n_fft),
+ persistent=False)
+
+ @property
+ def num_params(self) -> int:
+ """The number of learned parameters in the network."""
+ return sum(p.numel() for p in self.parameters())
+
+ @property
+ def offline(self) -> bool:
+ """Whether every frame sees its whole chunk now."""
+ if self.config.dual_mode:
+ return int(self.lookahead_index) == len(
+ self.config.lookahead_frames_choices)
+ return not self.config.causal
+
+ @property
+ def lookahead_frames(self) -> int:
+ """The look-ahead in force, zero offline."""
+ if not self.config.lookahead_frames_choices:
+ return self.config.lookahead_frames
+ if self.offline:
+ return 0
+ return self.config.lookahead_frames_choices[int(self.lookahead_index)]
+
+ def set_lookahead(self, frames: int) -> int:
+ """Moves to the trained streaming position with this look-ahead."""
+ choices = self.config.lookahead_frames_choices
+ if not choices:
+ if frames != self.config.lookahead_frames or not self.config.causal:
+ raise ValueError(
+ "This checkpoint has no streaming positions to choose from."
+ )
+ return frames
+ if frames not in choices:
+ raise ValueError(
+ f"Look-ahead {frames} is not among the trained positions"
+ f" {choices}.")
+ self.lookahead_index.fill_(choices.index(frames))
+ return frames
+
+ def set_offline(self) -> None:
+ """Returns a dual-mode checkpoint to its two-sided mode."""
+ if not self.config.dual_mode:
+ raise ValueError(
+ "Only a dual-mode checkpoint switches between offline and"
+ " streaming.")
+ self.lookahead_index.fill_(len(self.config.lookahead_frames_choices))
+
+ def default_window(self) -> tuple[float, float]:
+ """The render window and crossfade in seconds: the checkpoint's own."""
+ return (self.config.chunk_seconds, self.config.overlap_seconds)
+
+ def stft(self, audio: torch.Tensor) -> torch.Tensor:
+ """Complex spectra [batch, bins, frames] of audio [batch, samples]."""
+ with torch.autocast(device_type=audio.device.type, enabled=False):
+ return torch.stft(
+ audio.float(),
+ n_fft=self.config.n_fft,
+ hop_length=self.config.hop_length,
+ window=self.window.float(),
+ center=True,
+ pad_mode="reflect" if audio.shape[-1] > self.config.n_fft //
+ 2 else "constant",
+ return_complex=True,
+ )
+
+ def istft(self, spectrum: torch.Tensor, length: int) -> torch.Tensor:
+ """Audio [batch, length] of complex spectra [batch, bins, frames]."""
+ with torch.autocast(device_type=spectrum.device.type, enabled=False):
+ return torch.istft(
+ spectrum,
+ n_fft=self.config.n_fft,
+ hop_length=self.config.hop_length,
+ window=self.window.float(),
+ center=True,
+ length=length,
+ )
+
+ def encode(self, spectrum: torch.Tensor) -> torch.Tensor:
+ """Band tokens [batch, bands, frames, width] of the spectra."""
+ components = torch.view_as_real(spectrum).permute(0, 2, 1, 3)
+ features = torch.stack([
+ encoder(components[:, :, start:end].flatten(2))
+ for (start, end), encoder in zip(self.edges, self.encoders)
+ ],
+ dim=1)
+ features = features + self.band_embedding[None, :, None]
+ if self.config.lookahead_frames_choices:
+ features = features + self.lookahead_embedding(
+ self.lookahead_index)[None, None, None]
+ return features
+
+ def film(self) -> torch.Tensor | None:
+ """Per-block scale and shift [blocks, 2, width] of the position."""
+ if not self.config.mode_film:
+ return None
+ return self.mode_film(self.lookahead_index).view(
+ len(self.blocks), 2, self.config.width)
+
+ def features(self, spectrum: torch.Tensor) -> torch.Tensor:
+ """Backbone features [batch, bands, frames, width] of the spectra."""
+ causal = not self.offline
+ features = self.encode(spectrum)
+ film = self.film()
+ for index, block in enumerate(self.blocks):
+ features = block(features, causal)
+ if film is not None:
+ features = features * (1 + film[index, 0]) + film[index, 1]
+ return features
+
+ def correction(self, raw: torch.Tensor,
+ spectrum: torch.Tensor) -> torch.Tensor:
+ """The complex change of the spectrum the decoder's output encodes."""
+ mask_delta = torch.view_as_complex(
+ (2 * torch.tanh(raw[..., :2])).contiguous())
+ residual = bounded_correction(raw[..., 2:], spectrum,
+ self.config.correction_bound)
+ return spectrum * mask_delta + torch.view_as_complex(
+ residual.contiguous())
+
+ def forward(self, audio: torch.Tensor) -> torch.Tensor:
+ """Isolates floating-point mono audio shaped [batch, samples]."""
+ if (audio.ndim != 2 or not audio.shape[-1] or
+ not audio.is_floating_point()):
+ raise ValueError(
+ "Expected nonempty floating-point mono audio [batch, samples].")
+ spectrum = self.stft(audio)
+ raw = self.denoise_decoder(self.features(spectrum))
+ if not self.offline and self.lookahead_frames:
+ raw = read_ahead(raw, self.lookahead_frames)
+ return audio + self.istft(self.correction(raw, spectrum),
+ audio.shape[-1])
+
+ @torch.inference_mode()
+ def enhance(
+ self,
+ audio: torch.Tensor,
+ chunk_seconds: float | None = None,
+ overlap_seconds: float | None = None,
+ ) -> torch.Tensor:
+ """Isolates ``[samples]`` or ``[batch, samples]`` of any length.
+
+ Windows of ``chunk_seconds`` overlap by ``overlap_seconds`` with a
+ linear crossfade; a clip no longer than one window is a single pass.
+ Every window of a longer clip is a full one: the last ends at the
+ clip's end, reaching back over the window before it, and fades in
+ where that window fades out, so the tail keeps a whole window of
+ context.
+ """
+ default_chunk, default_overlap = self.default_window()
+ chunk, overlap = window_samples(
+ default_chunk if chunk_seconds is None else chunk_seconds,
+ default_overlap if overlap_seconds is None else overlap_seconds,
+ self.config.sample_rate,
+ self.config.hop_length,
+ )
+ squeeze = audio.ndim == 1
+ if squeeze:
+ audio = audio[None]
+ n = audio.shape[-1]
+ if n <= chunk:
+ out = self(audio)
+ else:
+ out = audio.new_zeros(audio.shape[0], n, dtype=torch.float32)
+ weight = audio.new_zeros(n, dtype=torch.float32)
+ starts = list(range(0, n - chunk, chunk - overlap)) + [n - chunk]
+ for index, start in enumerate(starts):
+ end = start + chunk
+ w = torch.ones(chunk, device=audio.device)
+ if index > 0:
+ fade_in = starts[index - 1] + chunk - overlap - start
+ w[:fade_in] = 0.0
+ if overlap > 0:
+ w[fade_in:fade_in + overlap] = torch.linspace(
+ 0.0, 1.0, overlap, device=audio.device)
+ if overlap > 0 and end < n:
+ w[-overlap:] = torch.linspace(1.0,
+ 0.0,
+ overlap,
+ device=audio.device)
+ out[:, start:end] += self(audio[:, start:end]) * w
+ weight[start:end] += w
+ out = out / weight.clamp(min=1e-6)
+ out = out.float()
+ return out[0] if squeeze else out
diff --git a/src/inworld/voice_isolation/registry.py b/src/inworld/voice_isolation/registry.py
new file mode 100644
index 0000000..e10f9ba
--- /dev/null
+++ b/src/inworld/voice_isolation/registry.py
@@ -0,0 +1,182 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Named model registry: release names, Hub locations and checksums."""
+
+import hashlib
+import os
+
+MODELS = {
+ "voice-isolator-v1": {
+ "repo_id":
+ "inworld/voice-isolator",
+ "filename":
+ "denoiser.safetensors",
+ "sha256":
+ "647335a6aeb4dc706b895532c209d51e0e84a4849d17b339f00d4392a050ae53",
+ "revision":
+ "9b0285b3fe8403aa8e2f1dbb2165a80a4294c970",
+ "stage":
+ 1,
+ "description":
+ ("Voice Isolator v1 for recorded audio, 48 kHz: offline only,"
+ " keeps the foreground voice, 8 s chunks overlapping by 2 s."),
+ },
+ "voice-isolator-v1-realtime": {
+ "repo_id":
+ "inworld/voice-isolator",
+ "filename":
+ "denoiser_realtime.safetensors",
+ "sha256":
+ "76598f05523c0669e76562a8b2f31c9d395fca316e80c907ee11775e7497ae0f",
+ "revision":
+ "9b0285b3fe8403aa8e2f1dbb2165a80a4294c970",
+ "stage":
+ 1,
+ "description":
+ ("Voice Isolator v1 for live audio, 48 kHz: streaming only, keeps"
+ " the foreground voice, look-ahead 0, 20 or 40 ms."),
+ },
+}
+
+# the weights the published v0 board rows were rendered from (their render
+# stamps record these checksums), not part of the registry: the benchmark's
+# digest-bound helper (bench/scripts/common.py) passes voice-isolator-v0 as its
+# default, so these names stay on exactly those files until the next full
+# re-score. v1 ships the same files today, but these are not aliases of v1 and
+# never take its checksums: a later v1 is another file and fails theirs instead
+# of standing in for the v0 rows.
+PINNED = {
+ "voice-isolator-v0": {
+ "repo_id":
+ "inworld/voice-isolator",
+ "filename":
+ "denoiser.safetensors",
+ "sha256":
+ "647335a6aeb4dc706b895532c209d51e0e84a4849d17b339f00d4392a050ae53",
+ "revision":
+ "9b0285b3fe8403aa8e2f1dbb2165a80a4294c970",
+ "stage":
+ 1,
+ "description":
+ "The weights of the published v0 offline board row.",
+ },
+ "voice-isolator-v0-realtime": {
+ "repo_id":
+ "inworld/voice-isolator",
+ "filename":
+ "denoiser_realtime.safetensors",
+ "sha256":
+ "76598f05523c0669e76562a8b2f31c9d395fca316e80c907ee11775e7497ae0f",
+ "revision":
+ "9b0285b3fe8403aa8e2f1dbb2165a80a4294c970",
+ "stage":
+ 1,
+ "description":
+ "The weights of the published v0 realtime board row.",
+ },
+}
+
+HF_SCHEME = "hf://"
+# the Hub repository of the released models names them all, and the inference
+# mode picks its checkpoint
+REPO_ID = "inworld/voice-isolator"
+MODE_MODELS = {
+ "offline": "voice-isolator-v1",
+ "streaming": "voice-isolator-v1-realtime"
+}
+
+
+def parse_hf(spec: str) -> tuple[str, str, str | None]:
+ """Splits ``hf://<org>/<repo>/<file>[@<revision>]`` into its parts.
+
+ Returns:
+ (repo_id, filename, revision or None).
+ """
+ body = spec[len(HF_SCHEME):]
+ body, _, revision = body.partition("@")
+ parts = body.split("/")
+ if len(parts) < 3 or not all(parts):
+ raise ValueError(
+ f"'{spec}' must look like hf://<org>/<repo>/<file>[@<revision>].")
+ return "/".join(parts[:2]), "/".join(parts[2:]), revision or None
+
+
+def sha256_file(path: str) -> str:
+ """Returns the sha256 of a file, read in 16 MiB blocks."""
+ digest = hashlib.sha256()
+ with open(path, "rb") as fh:
+ for block in iter(lambda: fh.read(1 << 24), b""):
+ digest.update(block)
+ return digest.hexdigest()
+
+
+def resolve(name_or_path: str, mode: str = "offline") -> str:
+ """Returns a local file for a released model, an ``hf://`` spec or a path.
+
+ The repository id, ``inworld/voice-isolator``, names the released models
+ and ``mode`` picks its checkpoint: ``voice-isolator-v1`` offline and
+ ``voice-isolator-v1-realtime`` for streaming. A registry name picks one
+ directly, whatever the mode. Both come first: they download the pinned
+ file from the Hub and verify its sha256; a name whose file is not released
+ yet is refused, and a Hub failure says to load the file by its path.
+ ``hf://<org>/<repo>/<file>[@<revision>]`` downloads any Hub file (no
+ checksum: pin a revision instead). Anything else that exists on disk is
+ returned as is; a local file that shares a registry name is loaded by its
+ path (``./voice-isolator-v1``).
+ """
+ if name_or_path == REPO_ID:
+ if mode not in MODE_MODELS:
+ raise ValueError(
+ f"mode must be one of {tuple(MODE_MODELS)}, got {mode!r}.")
+ name_or_path = MODE_MODELS[mode]
+ entry = MODELS.get(name_or_path) or PINNED.get(name_or_path)
+ if entry is not None:
+ if not entry["sha256"]:
+ raise ValueError(
+ f"'{name_or_path}' is not released yet; load a local checkpoint"
+ " by its path instead.")
+ # pylint: disable-next=import-outside-toplevel
+ import huggingface_hub
+
+ try:
+ path = huggingface_hub.hf_hub_download(
+ repo_id=entry["repo_id"],
+ filename=entry["filename"],
+ revision=entry["revision"],
+ )
+ except OSError as error:
+ raise RuntimeError(
+ f"'{name_or_path}' could not be fetched from the Hub "
+ f"({entry['repo_id']}/{entry['filename']}): the weights are "
+ "not published there yet, or this machine has no access or no "
+ "network. Load the checkpoint by its path instead.") from error
+ digest = sha256_file(path)
+ if digest != entry["sha256"]:
+ raise RuntimeError(
+ f"Checksum mismatch for {name_or_path}: expected "
+ f"{entry['sha256']}, got {digest}.")
+ return path
+ if name_or_path.startswith(HF_SCHEME):
+ # pylint: disable-next=import-outside-toplevel
+ import huggingface_hub
+
+ repo_id, filename, revision = parse_hf(name_or_path)
+ return huggingface_hub.hf_hub_download(repo_id=repo_id,
+ filename=filename,
+ revision=revision)
+ if os.path.exists(name_or_path):
+ return name_or_path
+ raise ValueError(
+ f"'{name_or_path}' is neither a local file, an hf:// spec, nor a known "
+ f"model ({REPO_ID}, {', '.join(sorted(MODELS))}).")
diff --git a/src/inworld/voice_isolation/scan.py b/src/inworld/voice_isolation/scan.py
new file mode 100644
index 0000000..db00667
--- /dev/null
+++ b/src/inworld/voice_isolation/scan.py
@@ -0,0 +1,241 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The selective state-space scan behind every Mamba block, in plain torch.
+
+The recurrence ``h_t = exp(delta_t a) h_{t-1} + delta_t b_t u_t`` and its
+readout ``y_t = c_t . h_t + d u_t`` run frame by frame in float32, the
+per-frame factors prepared a block of frames at a time. The same function
+serves whole clips and a stream's few new frames, which pass the state they
+carry. When the ``mamba_ssm`` kernels are installed and the audio is on a
+GPU, a whole clip's scan runs through them instead; the result is the same to
+float32 rounding. On Apple's GPU (``mps``) every scan runs as one Metal
+kernel compiled on first use: each thread keeps one channel's state in
+registers, where the plain recurrence would write every frame's state to
+memory and spend several GPU operations per frame.
+"""
+
+import torch
+
+BLOCK = 64
+METAL_STATES = 16
+_KERNEL: dict = {}
+_METAL_SOURCE = """
+#include <metal_stdlib>
+using namespace metal;
+
+kernel void selective_scan(
+ device float* y [[buffer(0)]],
+ device float* last [[buffer(1)]],
+ device const float* u [[buffer(2)]],
+ device const float* delta [[buffer(3)]],
+ device const float* a [[buffer(4)]],
+ device const float* b [[buffer(5)]],
+ device const float* c [[buffer(6)]],
+ device const float* d [[buffer(7)]],
+ device const float* z [[buffer(8)]],
+ device const float* carried [[buffer(9)]],
+ constant uint& batch [[buffer(10)]],
+ constant uint& frames [[buffer(11)]],
+ constant uint& channels [[buffer(12)]],
+ constant uint& states [[buffer(13)]],
+ constant uint& gated [[buffer(14)]],
+ constant uint& carrying [[buffer(15)]],
+ uint index [[thread_position_in_grid]]) {
+ if (index >= batch * channels) {
+ return;
+ }
+ const uint row = index / channels;
+ const uint channel = index % channels;
+ float h[16];
+ float rate[16];
+ for (uint n = 0; n < states; ++n) {
+ rate[n] = a[channel * states + n];
+ h[n] = carrying ? carried[index * states + n] : 0.0f;
+ }
+ const float skip = d[channel];
+ for (uint t = 0; t < frames; ++t) {
+ const uint at = (row * frames + t) * channels + channel;
+ const uint bt = (row * frames + t) * states;
+ const float step = delta[at];
+ const float x = u[at];
+ const float drive = step * x;
+ float out = 0.0f;
+ for (uint n = 0; n < states; ++n) {
+ h[n] = precise::exp(step * rate[n]) * h[n] + drive * b[bt + n];
+ out += h[n] * c[bt + n];
+ }
+ out += x * skip;
+ if (gated) {
+ const float g = z[at];
+ out *= precise::divide(g, 1.0f + precise::exp(-g));
+ }
+ y[at] = out;
+ }
+ for (uint n = 0; n < states; ++n) {
+ last[index * states + n] = h[n];
+ }
+}
+"""
+
+
+def kernel():
+ """The fused selective scan of ``mamba_ssm`` when installed, else None."""
+ if "scan" not in _KERNEL:
+ try:
+ # pylint: disable-next=import-outside-toplevel
+ from mamba_ssm.ops import selective_scan_interface
+ _KERNEL["scan"] = selective_scan_interface.selective_scan_fn
+ except ImportError:
+ _KERNEL["scan"] = None
+ return _KERNEL["scan"]
+
+
+def metal_kernel():
+ """The scan compiled for Apple's GPU, or None where it cannot be."""
+ if "metal" not in _KERNEL:
+ try:
+ _KERNEL["metal"] = torch.mps.compile_shader(_METAL_SOURCE)
+ except (AttributeError, RuntimeError):
+ _KERNEL["metal"] = None
+ return _KERNEL["metal"]
+
+
+def _metal(u, delta, a, b, c, d, z, state, library):
+ batch, frames, channels = u.shape
+ states = a.shape[-1]
+ y = u.new_empty(batch, frames, channels)
+ last = u.new_empty(batch, channels, states)
+ if batch * channels:
+ u, delta, b, c = (t.contiguous() for t in (u, delta, b, c))
+ library.selective_scan(
+ y,
+ last,
+ u,
+ delta,
+ a.contiguous(),
+ b,
+ c,
+ d.contiguous(),
+ u if z is None else z.float().contiguous(),
+ u if state is None else state.float().contiguous(),
+ batch,
+ frames,
+ channels,
+ states,
+ int(z is not None),
+ int(state is not None),
+ threads=batch * channels)
+ return y, last
+
+
+def _channels_first(t: torch.Tensor) -> torch.Tensor:
+ return t.transpose(1, 2).contiguous()
+
+
+def _fused(u, delta, a, b, c, d, z, fused):
+ y, last = fused(_channels_first(u),
+ _channels_first(delta),
+ a,
+ _channels_first(b),
+ _channels_first(c),
+ d,
+ z=None if z is None else _channels_first(z.float()),
+ delta_bias=None,
+ delta_softplus=False,
+ return_last_state=True)
+ return y.transpose(1, 2), last
+
+
+def selective_scan(
+ u: torch.Tensor,
+ delta: torch.Tensor,
+ a: torch.Tensor,
+ b: torch.Tensor,
+ c: torch.Tensor,
+ d: torch.Tensor,
+ z: torch.Tensor | None = None,
+ state: torch.Tensor | None = None,
+) -> tuple[torch.Tensor, torch.Tensor]:
+ """Runs the scan over ``u`` and returns its output and final state.
+
+ Args:
+ u: Inputs [batch, frames, channels].
+ delta: Step sizes [batch, frames, channels], already positive.
+ a: State decay rates [channels, state], negative.
+ b: Input projections [batch, frames, state].
+ c: Output projections [batch, frames, state].
+ d: Skip gains [channels].
+ z: Optional gate [batch, frames, channels]; the output is multiplied
+ by its SiLU.
+ state: The state [batch, channels, state] carried in, zeros when
+ None.
+
+ Returns:
+ The output [batch, frames, channels] in float32 and the state after
+ the last frame.
+ """
+ u, delta, b, c = (t.float() for t in (u, delta, b, c))
+ a, d = a.float(), d.float()
+ fused = kernel() if state is None and u.is_cuda else None
+ if fused is not None:
+ return _fused(u, delta, a, b, c, d, z, fused)
+ if u.device.type == "mps" and a.shape[-1] <= METAL_STATES:
+ library = metal_kernel()
+ if library is not None:
+ return _metal(u, delta, a, b, c, d, z, state, library)
+ batch, frames, channels = u.shape
+ h = (u.new_zeros(batch, channels, a.shape[-1])
+ if state is None else state.float())
+ outputs = []
+ for start in range(0, frames, BLOCK):
+ stop = min(start + BLOCK, frames)
+ step = delta[:, start:stop]
+ decay = torch.exp(step[..., None] * a)
+ driven = (step * u[:, start:stop])[..., None] * b[:, start:stop,
+ None, :]
+ readout = c[:, start:stop, None, :]
+ for t in range(stop - start):
+ h = decay[:, t] * h + driven[:, t]
+ outputs.append((h * readout[:, t]).sum(-1))
+ y = torch.stack(outputs, 1) + u * d
+ if z is not None:
+ y = y * torch.nn.functional.silu(z.float())
+ return y, h
+
+
+def selective_scan_reference(
+ u: torch.Tensor,
+ delta: torch.Tensor,
+ a: torch.Tensor,
+ b: torch.Tensor,
+ c: torch.Tensor,
+ d: torch.Tensor,
+ z: torch.Tensor | None = None,
+ state: torch.Tensor | None = None,
+) -> tuple[torch.Tensor, torch.Tensor]:
+ """The scan one frame at a time: what ``selective_scan`` must match."""
+ u, delta, b, c = (t.float() for t in (u, delta, b, c))
+ a, d = a.float(), d.float()
+ batch, frames, channels = u.shape
+ h = (u.new_zeros(batch, channels, a.shape[-1])
+ if state is None else state.float())
+ ys = []
+ for t in range(frames):
+ h = (torch.exp(delta[:, t, :, None] * a) * h +
+ delta[:, t, :, None] * b[:, t, None, :] * u[:, t, :, None])
+ ys.append((h * c[:, t, None, :]).sum(-1) + d * u[:, t])
+ y = torch.stack(ys, 1)
+ if z is not None:
+ y = y * torch.nn.functional.silu(z.float())
+ return y, h
diff --git a/src/inworld/voice_isolation/streaming.py b/src/inworld/voice_isolation/streaming.py
new file mode 100644
index 0000000..3f62dfa
--- /dev/null
+++ b/src/inworld/voice_isolation/streaming.py
@@ -0,0 +1,829 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Streaming inference: the isolated voice leaves as the audio arrives.
+
+Samples are pushed in pieces of any size. Every block of new frames runs
+once with the state carried (time attention over a sliding cache of past
+keys, the time Mamba's recurrence, the STFT's overlap-add), and output
+samples are released as soon as every frame that touches them has been
+synthesized. The state is never reset within a session: only ``flush`` ends
+it. Several clips stream in lockstep as a batch, each with its own state:
+padded with silence to one length and given their own lengths, each ends
+exactly as it would alone, since nothing looks ahead of the look-ahead. The
+latency is the STFT's window plus the look-ahead frames. Partial blocks run
+immediately; the maximum block size controls throughput, not latency.
+
+With ``window_frames`` and ``crossfade_frames`` set, the time attention never
+looks back across a window boundary: a second lane starts before each
+boundary with the Mamba states cloned and the attention empty, the two
+decoder outputs blend over the crossfade, and the new lane carries on. The
+recurrence is kept throughout; only the attention's past is bounded.
+"""
+
+import contextlib
+import weakref
+
+import numpy as np
+import torch
+
+from inworld.voice_isolation import model as modeling
+
+# Every stream of a model reads the same packed band weights (about 100 MB on
+# the device for the released realtime model), so they are packed once per
+# model rather than once per session.
+_PACKED_BANDS = weakref.WeakKeyDictionary()
+# A lane's attention buffers start with this many slots (frames) and double.
+_FIRST_SLOTS = 64
+
+
+class _AttentionState:
+ """One lane's time attention past for one attention block.
+
+ Keys and values sit in buffers [rows, heads, capacity, head_dim] written
+ in place, and a key is rotated once, when it is written, at its slot: a
+ slot's index is its rotary position. ``end`` counts the slots in use.
+ """
+
+ def __init__(self):
+ self.keys = None
+ self.values = None
+ self.end = 0
+
+
+class _AttentionCache:
+ """What every attention block of a stream shares: the past each block
+ may see (``frames``), the buffers' capacity, the rotary tables of every
+ slot and the masks by block and past size.
+
+ A lane that never outgrows ``frames`` plus a block (a windowed lane
+ within its window and crossfade) keeps every key in the slot it was
+ written to, so its rotations are those of positions counted from the
+ lane's first frame, as the cache's own positions were. Beyond that, the
+ buffer is compacted when full: the last ``frames`` keys move to the
+ front and are rotated back by the distance they moved.
+ """
+
+ def __init__(self, frames: int, capacity: int, head_dim: int, window: int,
+ device) -> None:
+ self.frames, self.capacity, self.window = frames, capacity, window
+ self.cos, self.sin = modeling.rope_tables(capacity, head_dim, device,
+ torch.float32)
+ self.masks = {}
+
+ def tables(self, start: int, stop: int,
+ dtype) -> tuple[torch.Tensor, torch.Tensor]:
+ """Rotary tables of slots [start, stop) in ``dtype``."""
+ return (self.cos[start:stop].to(dtype), self.sin[start:stop].to(dtype))
+
+ def mask(self, frames: int, past: int) -> torch.Tensor:
+ """Which of ``past`` earlier and ``frames`` new keys each new frame
+ sees: itself and what precedes it, within the trained window."""
+ key = (frames, past)
+ if key not in self.masks:
+ device = self.cos.device
+ positions = torch.arange(past + frames, device=device)
+ queries = (past + torch.arange(frames, device=device))[:, None]
+ mask = positions[None, :] <= queries
+ if self.window:
+ # The training bound: a frame sees itself and window - 1
+ # before it, whatever the block holds and the cache keeps.
+ mask &= positions[None, :] > queries - self.window
+ self.masks[key] = mask
+ return self.masks[key]
+
+
+class _MambaState:
+
+ def __init__(self):
+ self.carried = None
+
+
+def _clone_states(states: list) -> list:
+ """Lane B's start: the Mamba states cloned (the recurrence does not
+ drift), the attention caches empty."""
+ out = []
+ for state in states:
+ if isinstance(state, _MambaState):
+ fresh = _MambaState()
+ if state.carried is not None:
+ fresh.carried = tuple(part.clone() for part in state.carried)
+ out.append(fresh)
+ else:
+ out.append(_AttentionState())
+ return out
+
+
+def _compact(state: _AttentionState, cache: _AttentionCache) -> None:
+ """Moves the last ``cache.frames`` keys and values to the front, the
+ keys rotated back by the distance they moved."""
+ keep = min(state.end, cache.frames)
+ shift = state.end - keep
+ if not shift:
+ return
+ cos, sin = cache.tables(shift, shift + 1, state.keys.dtype)
+ kept = state.keys[:, :, shift:state.end].clone()
+ state.keys[:, :, :keep] = modeling.apply_rope(kept, cos, -sin)
+ state.values[:, :, :keep] = state.values[:, :, shift:state.end].clone()
+ state.end = keep
+
+
+def _reserve(state: _AttentionState, slots: int, capacity: int,
+ key: torch.Tensor, value: torch.Tensor) -> None:
+ """Makes a lane's buffers hold at least ``slots`` slots.
+
+ Buffers start at ``_FIRST_SLOTS`` and double, up to ``capacity``, as the
+ lane's past grows, so a short stream, or a batch of them, holds only what
+ it uses. Used slots keep their index, which is their rotary position.
+ """
+ held = 0 if state.keys is None else state.keys.shape[2]
+ if slots <= held:
+ return
+ rows, _, heads, size = key.shape
+ shape = (rows, heads, min(capacity, max(slots, 2 * held,
+ _FIRST_SLOTS)), size)
+ keys, values = key.new_empty(shape), value.new_empty(shape)
+ if state.end:
+ keys[:, :, :state.end] = state.keys[:, :, :state.end]
+ values[:, :, :state.end] = state.values[:, :, :state.end]
+ state.keys, state.values = keys, values
+
+
+def _attend_lane(state: _AttentionState, cache: _AttentionCache,
+ query: torch.Tensor, key: torch.Tensor,
+ value: torch.Tensor) -> torch.Tensor:
+ """One lane's attention for its new frames [rows, frames, heads, dim]:
+ writes the new keys and values, returns [rows, heads, frames, dim]."""
+ frames = key.shape[1]
+ if state.end + frames > cache.capacity:
+ _compact(state, cache)
+ _reserve(state, state.end + frames, cache.capacity, key, value)
+ first = state.end
+ cos, sin = cache.tables(first, first + frames, query.dtype)
+ state.keys[:, :, first:first + frames] = modeling.apply_rope(
+ key.transpose(1, 2), cos, sin)
+ state.values[:, :, first:first + frames] = value.transpose(1, 2)
+ state.end = first + frames
+ past = min(first, cache.frames)
+ return torch.nn.functional.scaled_dot_product_attention(
+ modeling.apply_rope(query.transpose(1, 2), cos, sin),
+ state.keys[:, :, first - past:state.end],
+ state.values[:, :, first - past:state.end],
+ attn_mask=cache.mask(frames, past))
+
+
+def _attend(block: modeling.DualPathAttention, features: torch.Tensor,
+ states: list, cache: _AttentionCache) -> torch.Tensor:
+ """One attention block over the new frames [batch, bands, frames, width].
+
+ ``features`` stacks one batch per lane in ``states``. Each new frame sees
+ the last ``cache.frames`` keys of its own lane before the block and the
+ block's keys up to itself; a checkpoint's attention window bounds each
+ query exactly as in training. Rotary positions are relative, so a key
+ rotated at its slot needs no rotating again. Only the attention itself
+ runs lane by lane; every layer around it runs once for all of them.
+ """
+ time_block = block.time_transformer
+ attn = time_block.attn
+ batch, bands, frames, width = features.shape
+ rows = features.reshape(batch * bands, frames, width)
+ qkv = attn.qkv(time_block.norm1(rows)).view(batch * bands, frames, 3,
+ attn.num_heads, attn.head_dim)
+ query, key, value = qkv.unbind(2)
+ if len(states) == 1:
+ output = _attend_lane(states[0], cache, query, key, value)
+ else:
+ output = torch.cat([
+ _attend_lane(state, cache, *parts) for state, parts in zip(
+ states, zip(
+ *(t.chunk(len(states)) for t in (query, key, value))))
+ ])
+ if attn.exclusive:
+ output = modeling.exclusive(output, value.transpose(1, 2))
+ rows = rows + attn.proj(
+ output.transpose(1, 2).reshape(batch * bands, frames, width))
+ rows = rows + time_block.ffn(time_block.norm2(rows))
+ banded = block.band_transformer(
+ rows.view(batch, bands, frames,
+ width).permute(0, 2, 1, 3).reshape(batch * frames, bands,
+ width))
+ return banded.view(batch, frames, bands, width).permute(0, 2, 1, 3)
+
+
+class _PackedBands:
+ """The per-band encoders and decoder heads as a few batched operations.
+
+ The model runs one small layer per band, 46 of them, for each of the
+ encoder and the decoder; in a stream's block of a few frames each is a
+ separate GPU dispatch. Here the bands' weights are stacked, zero-padded
+ to the widest band, so each step is one batched operation over every
+ band, and the valid outputs are gathered back in the bands' order. The
+ results equal the modules' to float32 rounding.
+ """
+
+ def __init__(self, model: modeling.VoiceIsolatorNetwork) -> None:
+ edges = model.edges
+ widths = [end - start for start, end in edges]
+ inputs, outputs = 2 * max(widths), 4 * max(widths)
+ bins = edges[-1][1]
+ device = model.window.device
+ self.bands = len(edges)
+ gather = torch.full((self.bands, inputs), 2 * bins, dtype=torch.long)
+ valid = torch.zeros(self.bands, inputs)
+ keep = []
+ for band, (start, end) in enumerate(edges):
+ gather[band, :2 * (end - start)] = torch.arange(2 * start, 2 * end)
+ valid[band, :2 * (end - start)] = 1.0
+ keep.append(band * outputs + torch.arange(4 * (end - start)))
+ self.gather = gather.to(device)
+ self.valid = valid.to(device)
+ self.counts = torch.tensor([2.0 * w for w in widths],
+ device=device)[:, None]
+ self.keep = torch.cat(keep).to(device)
+
+ def stack(tensors, size):
+ padded = torch.zeros(self.bands,
+ size,
+ *tensors[0].shape[1:],
+ device=device)
+ for band, tensor in enumerate(tensors):
+ padded[band, :tensor.shape[0]] = tensor.detach()
+ return padded
+
+ encoders = [(encoder[0], encoder[1]) for encoder in model.encoders]
+ self.encoder_eps = encoders[0][0].eps
+ self.encoder_norm_weight = stack([n.weight for n, _ in encoders],
+ inputs)
+ self.encoder_norm_bias = stack([n.bias for n, _ in encoders], inputs)
+ self.encoder_weight = stack([l.weight.t() for _, l in encoders], inputs)
+ self.encoder_bias = torch.stack([l.bias.detach() for _, l in encoders
+ ])[:, None]
+ heads = model.denoise_decoder.heads
+ self.decoder = model.denoise_decoder
+ self.head_norm = heads[0][0]
+ self.head_norm_weight = torch.stack(
+ [h[0].weight.detach() for h in heads])[:, None]
+ self.head_norm_bias = torch.stack([h[0].bias.detach() for h in heads
+ ])[:, None]
+ self.head_weight = torch.stack(
+ [h[1].weight.detach().t() for h in heads])
+ self.head_bias = torch.stack([h[1].bias.detach() for h in heads])[:,
+ None]
+ self.out_weight = torch.stack([
+ torch.nn.functional.pad(h[3].weight.detach().t(),
+ (0, outputs - h[3].weight.shape[0]))
+ for h in heads
+ ])
+ self.out_bias = torch.stack([
+ torch.nn.functional.pad(h[3].bias.detach(),
+ (0, outputs - h[3].bias.shape[0]))
+ for h in heads
+ ])[:, None]
+
+ def encode(self, model: modeling.VoiceIsolatorNetwork,
+ spectrum: torch.Tensor) -> torch.Tensor:
+ """``model.encode``: band tokens [batch, bands, frames, width]."""
+ batch, bins, frames = spectrum.shape
+ components = torch.view_as_real(spectrum).permute(0, 2, 1, 3).reshape(
+ batch * frames, 2 * bins)
+ components = torch.nn.functional.pad(components, (0, 1))
+ x = components[:, self.gather].transpose(0, 1)
+ mean = x.sum(-1, keepdim=True) / self.counts[:, None]
+ centered = (x - mean) * self.valid[:, None]
+ variance = (centered * centered).sum(
+ -1, keepdim=True) / self.counts[:, None]
+ x = centered * torch.rsqrt(variance + self.encoder_eps)
+ x = x * self.encoder_norm_weight[:, None] + self.encoder_norm_bias[:,
+ None]
+ x = torch.baddbmm(self.encoder_bias, x, self.encoder_weight)
+ features = x.view(self.bands, batch, frames, -1).transpose(0, 1)
+ features = features + model.band_embedding[None, :, None]
+ if model.config.lookahead_frames_choices:
+ features = features + model.lookahead_embedding(
+ model.lookahead_index)[None, None, None]
+ return features
+
+ def decode(self, features: torch.Tensor) -> torch.Tensor:
+ """``model.denoise_decoder``: [batch, bins, frames, 4] in float32."""
+ batch, bands, frames, width = features.shape
+ scale, shift = self.decoder.condition(self.decoder.controls).chunk(
+ 2, dim=-1)
+ x = (features * (1 + scale) + shift).transpose(0, 1).reshape(
+ bands, batch * frames, width)
+ x = torch.nn.functional.layer_norm(x, (width,), None, None,
+ self.head_norm.eps)
+ x = x * self.head_norm_weight + self.head_norm_bias
+ x = torch.nn.functional.gelu(
+ torch.baddbmm(self.head_bias, x, self.head_weight))
+ x = torch.baddbmm(self.out_bias, x, self.out_weight)
+ x = x.transpose(0, 1).reshape(batch * frames, -1)[:, self.keep]
+ return x.float().view(batch, frames, -1, 4).permute(0, 2, 1, 3)
+
+
+def _packed_bands(model: modeling.VoiceIsolatorNetwork) -> _PackedBands:
+ """The model's band layers packed once and shared by all its streams.
+
+ The packed copy is rebuilt when a band weight is replaced, moves to
+ another device or dtype, or changes in place (``load_state_dict`` copies
+ into the existing tensors, which only their version counter records).
+ """
+ key = []
+ for module in (*model.encoders, *model.denoise_decoder.heads):
+ for tensor in module.parameters():
+ if tensor.is_inference():
+ # Weights made under torch.inference_mode() keep no version
+ # counter, so a change in place could go unseen: pack them
+ # for this stream alone.
+ return _PackedBands(model)
+ # pylint: disable-next=protected-access
+ version = tensor._version
+ key.append(
+ (tensor.data_ptr(), version, tensor.device, tensor.dtype))
+ key = tuple(key)
+ cached = _PACKED_BANDS.get(model)
+ if cached is None or cached[0] != key:
+ cached = (key, _PackedBands(model))
+ _PACKED_BANDS[model] = cached
+ return cached[1]
+
+
+def _time_mamba(mamba: modeling.BidirectionalMamba, inputs: torch.Tensor,
+ states: list) -> torch.Tensor:
+ """The time Mamba at its streaming position: the forward scan carried,
+ each lane's state for its own rows of ``inputs``."""
+ if len(states) == 1:
+ carried = states[0].carried
+ elif states[0].carried is None:
+ carried = None
+ else:
+ carried = tuple(
+ torch.cat(parts)
+ for parts in zip(*(state.carried for state in states)))
+ forward, carried = mamba.forward_blocks(inputs, carried)
+ if len(states) == 1:
+ states[0].carried = carried
+ else:
+ for state, parts in zip(
+ states, zip(*(part.chunk(len(states)) for part in carried))):
+ state.carried = parts
+ if mamba.causal:
+ return mamba.norm(mamba.output_proj(forward + inputs))
+ return mamba.norm(
+ mamba.output_proj(
+ torch.cat((forward + inputs, torch.zeros_like(inputs)), dim=-1)))
+
+
+def _scan(block: modeling.DualPathMamba, features: torch.Tensor,
+ states: list) -> torch.Tensor:
+ """One dual-path Mamba block over the new frames of every lane's batch."""
+ batch, bands, frames, width = features.shape
+ rows = features.reshape(batch * bands, frames, width)
+ time = rows + _time_mamba(block.time_mamba, rows, states)
+ frequency = time.view(batch, bands, frames, width).permute(0, 2, 1, 3)
+ frequency = frequency.reshape(batch * frames, bands, width)
+ frequency = frequency + block.freq_mamba(frequency)
+ return frequency.view(batch, frames, bands, width).permute(0, 2, 1, 3)
+
+
+class Stream:
+ """Runs a model at its streaming position over audio in pieces.
+
+ ``push`` takes new mono samples at the model's rate, ``[samples]`` or a
+ batch ``[clips, samples]`` of clips streamed in lockstep, and returns the
+ output samples that became final; ``flush`` ends the stream and returns
+ the rest. Up to ``block_frames`` frames are computed together, a
+ throughput knob: a frame is computed as soon as its analysis window is
+ complete, so the block adds no latency; ``cache_frames`` bounds the time
+ attention's past (by
+ default the checkpoint's attention window, else its training chunk). The
+ cache is trimmed after each block and a block ends where a push ends, so
+ once a session's past exceeds the cache a frame's context, and with it the
+ plain stream's output, varies slightly with how the audio was pushed;
+ within the cache it does not. A checkpoint trained with an attention
+ window keeps that exact bound in the stream (each frame sees itself and
+ the ``window - 1`` frames before it), so with a cache of at least
+ ``window - 1`` frames its output equals the whole-clip forward and does
+ not depend on the pushes at all. A batch of clips padded with silence to
+ one length passes ``lengths``, each clip's own, so every clip ends as it
+ would alone. A NumPy array in gives a NumPy array out; a tensor gives a CPU
+ tensor, of the rank that was pushed. The band encoders and decoder heads
+ are packed when the stream starts (shared with the model's other
+ streams): weights loaded into the model during a session apply from the
+ next one.
+
+ Windowed attention (``window_frames`` and ``crossfade_frames``, both None
+ by default: the plain stream, bit-exact). The time attention never looks
+ back across a window boundary, which removes the drift of the cached past
+ on long inputs while the recurrent state is kept. The semantics:
+
+ 1. Lanes and blocks. Lane A carries the output. Frame positions count
+ from the session's first analysis frame; the first crossfade starts at
+ frame ``window_frames - crossfade_frames`` and the first boundary is
+ frame ``window_frames``. Blocks are cut where a crossfade starts and
+ where a window ends, so no block crosses either frame and, with a
+ cache that never trims (point 4), the output does not depend on how
+ the audio was pushed. Lane B starts with the
+ block that begins at the crossfade's first frame: its Mamba states are
+ clones of lane A's after the frame before, its attention caches start
+ empty.
+ 2. What is blended. The raw decoder output per frame (complex mask delta
+ and bounded residual), linearly: lane B's weight is
+ ``(f - crossfade_start + 1) / crossfade_frames`` for the frames of the
+ crossfade and lane A's the rest. The correction (the mask's tanh and
+ the residual's bound) is applied to the blend, so this is a blend of
+ the two lanes' decoder outputs, close to but not exactly a blend of
+ their output spectra; synthesis then overlap-adds the corrected frames
+ with the single envelope.
+ 3. The swap. Frame ``k * window_frames - 1`` is the last frame of window
+ ``k`` (lane B's weight is 1 there); after it, lane B becomes lane A and
+ the old lane is dropped, so every frame from the boundary on is the new
+ lane's; ``boundaries`` records ``k * window_frames``. The next
+ crossfade starts ``window_frames - crossfade_frames`` frames into the
+ new window. An input that ends inside a crossfade flushes the blended
+ frames computed so far; no swap is forced.
+ 4. ``cache_frames`` bounds the attention cache within each lane; a lane's
+ context never exceeds ``window_frames + crossfade_frames`` frames, so
+ a cache at or above that is a no-op and a smaller one bounds further,
+ with the plain stream's dependence on the pushes.
+ """
+
+ def __init__(
+ self,
+ model: modeling.VoiceIsolatorNetwork,
+ block_frames: int = 4,
+ cache_frames: int | None = None,
+ autocast_dtype: torch.dtype | None = None,
+ lengths: list[int] | None = None,
+ window_frames: int | None = None,
+ crossfade_frames: int | None = None,
+ ) -> None:
+ if model.offline:
+ raise ValueError(
+ "Streaming needs the model at a streaming position: call"
+ " set_lookahead first (or load with mode='streaming').")
+ if block_frames < 1:
+ raise ValueError("Process at least one frame per block.")
+ config = model.config
+ self.model = model
+ self.block_frames = block_frames
+ self.cache_frames = (cache_frames or config.attention_window_frames or
+ max(
+ 1,
+ round(config.chunk_seconds *
+ config.sample_rate / config.hop_length)))
+ self.lookahead = model.lookahead_frames
+ self.n_fft, self.hop = config.n_fft, config.hop_length
+ self.sample_rate = config.sample_rate
+ self.autocast_dtype = autocast_dtype
+ self.states = [
+ _AttentionState()
+ if isinstance(block, modeling.DualPathAttention) else _MambaState()
+ for block in model.blocks
+ ]
+ if (window_frames is None) != (crossfade_frames is None):
+ raise ValueError("window_frames and crossfade_frames go together.")
+ if window_frames is not None and not (0 < crossfade_frames <
+ window_frames):
+ raise ValueError("crossfade_frames must be positive and shorter"
+ " than window_frames.")
+ self.window_frames, self.crossfade_frames = (window_frames,
+ crossfade_frames)
+ self.states_b = None
+ self._spare = [None] * len(self.states)
+ self.boundaries = []
+ device = model.window.device
+ # A windowed lane lasts its window and the crossfade before it; one
+ # that never outgrows the cache plus a block needs no compacting.
+ lane = (None if window_frames is None else window_frames +
+ crossfade_frames)
+ if lane is not None and lane <= self.cache_frames + block_frames:
+ capacity = lane
+ else:
+ capacity = self.cache_frames + max(self.cache_frames // 2,
+ block_frames)
+ self._bands = _packed_bands(model)
+ self._attention = _AttentionCache(self.cache_frames, capacity,
+ config.width // config.num_heads,
+ config.attention_window_frames,
+ device)
+ self._rank = None
+ self._audio = torch.zeros(1, 0, device=device)
+ self._audio_base = 0
+ self._frames = 0
+ self._emitted = 0
+ self._raw = []
+ self._spectra = []
+ self._pending_base = 0
+ self._ola = torch.zeros(1, self.n_fft, device=device)
+ self._envelope = torch.zeros(1, self.n_fft, device=device)
+ self._ola_base = 0
+ self._released = 0
+ self._closed = False
+ self._limits = (None if lengths is None else
+ [int(n) // self.hop + 1 for n in lengths])
+
+ @property
+ def latency_samples(self) -> int:
+ """Input samples that must follow an output sample before its release.
+
+ The analysis window of the last frame that touches it and the
+ look-ahead frames, to within one hop of frame rounding; the block
+ adds nothing, since a frame is computed as soon as its window is
+ complete.
+ """
+ return self.n_fft + self.hop * self.lookahead
+
+ @property
+ def latency_seconds(self) -> float:
+ """The stream's algorithmic latency in seconds."""
+ return self.latency_samples / self.sample_rate
+
+ def _context(self):
+ if self.autocast_dtype is None:
+ return contextlib.nullcontext()
+ return torch.autocast(device_type=self._audio.device.type,
+ dtype=self.autocast_dtype)
+
+ def _analyze(self, first: int, count: int) -> torch.Tensor:
+ """Spectra [count, clips, bins] of frames from ``first``, together:
+ each frame's window of the audio, zeros where there is none."""
+ start = first * self.hop - self.n_fft // 2
+ stop = (first + count - 1) * self.hop - self.n_fft // 2 + self.n_fft
+ total = self._audio_base + self._audio.shape[1]
+ lo, hi = max(start, self._audio_base), min(stop, total)
+ if hi > lo:
+ audio = self._audio[:, lo - self._audio_base:hi - self._audio_base]
+ else:
+ lo = hi = start
+ audio = self._audio[:, :0]
+ if lo > start or hi < stop:
+ audio = torch.nn.functional.pad(audio, (lo - start, stop - hi))
+ segments = audio.unfold(1, self.n_fft, self.hop)
+ return torch.fft.rfft(segments * self.model.window.float()).transpose(
+ 0, 1)
+
+ def _run_block(self, spectra: torch.Tensor) -> torch.Tensor:
+ """The backbone and decoder over spectra [frames, batch, bins]."""
+ model = self.model
+ with self._context():
+ features = self._bands.encode(model, spectra.permute(1, 2, 0))
+ film = model.film()
+ if self.window_frames is None:
+ raw = self._bands.decode(
+ self._backbone(features, [self.states], film))
+ else:
+ raw = self._windowed(features, film, spectra.shape[0])
+ return raw.permute(2, 0, 1, 3)
+
+ def _backbone(self, features: torch.Tensor, lanes: list,
+ film: torch.Tensor | None) -> torch.Tensor:
+ """The blocks over the new frames for each lane's states, the lanes
+ stacked into one batch: [lanes * batch, bands, frames, width]."""
+ if len(lanes) > 1:
+ features = features.repeat(len(lanes), 1, 1, 1)
+ for index, block in enumerate(self.model.blocks):
+ states = [lane[index] for lane in lanes]
+ if isinstance(block, modeling.DualPathAttention):
+ features = _attend(block, features, states, self._attention)
+ else:
+ features = _scan(block, features, states)
+ if film is not None:
+ features = features * (1 + film[index, 0]) + film[index, 1]
+ return features
+
+ def _next_cut(self) -> int:
+ """The first frame after the current one that a block may not cross
+ into: the next crossfade start or window boundary (none without
+ windows)."""
+ if self.window_frames is None:
+ return self._frames + self.block_frames
+ start = self._frames - self._frames % self.window_frames
+ crossfade_start = start + self.window_frames - self.crossfade_frames
+ if self._frames < crossfade_start:
+ return crossfade_start
+ return start + self.window_frames
+
+ def _windowed(self, features: torch.Tensor, film: torch.Tensor | None,
+ frames: int) -> torch.Tensor:
+ """Two lanes across a window boundary (the class docstring's
+ semantics): lane B starts at the crossfade's first frame with the
+ Mamba states cloned and the attention empty, the decoder outputs blend
+ linearly over the crossfade, and lane B carries on from the boundary.
+ Blocks never cross a crossfade start or a boundary (``_next_cut``)."""
+ first = self._frames % self.window_frames
+ crossfade_start = self.window_frames - self.crossfade_frames
+ if first + frames > self.window_frames or (first < crossfade_start <
+ first + frames):
+ raise RuntimeError("a block crossed a crossfade start or a window"
+ " boundary")
+ decoder = self._bands.decode
+ if first >= crossfade_start and self.states_b is None:
+ # cloned before lane A consumes this block: lane B starts from the
+ # frame before the crossfade
+ self.states_b = _clone_states(self.states)
+ # the last lane's attention buffers, rather than new ones: a lane
+ # reads only the slots it has written
+ for state, spare in zip(self.states_b, self._spare):
+ if spare is not None:
+ state.keys, state.values = spare
+ self._spare = [None] * len(self.states)
+ if first < crossfade_start:
+ return decoder(self._backbone(features, [self.states], film))
+ # both lanes in one pass: the same features, each lane's own states
+ raw, raw_b = decoder(
+ self._backbone(features, [self.states, self.states_b],
+ film)).chunk(2)
+ offsets = torch.arange(first, first + frames, device=features.device)
+ weight = ((offsets - crossfade_start + 1).float() /
+ self.crossfade_frames).clamp(0.0, 1.0)
+ weight = weight.view(1, 1, -1, 1).to(raw.dtype)
+ raw = raw * (1 - weight) + raw_b * weight
+ if first + frames == self.window_frames:
+ self.boundaries.append(self._frames + frames)
+ self._spare = [
+ (state.keys,
+ state.values) if isinstance(state, _AttentionState) and
+ state.keys is not None else None for state in self.states
+ ]
+ self.states, self.states_b = self.states_b, None
+ return raw
+
+ def _synthesize(self) -> None:
+ """Synthesizes the next frame from the decoder's output read
+ ``lookahead`` frames later; the last computed frame serves every frame
+ beyond it, and a clip's own last frame once the clip has ended."""
+ index = self._emitted
+ rows = []
+ for clip in range(self._audio.shape[0]):
+ last = (self._frames if self._limits is None else min(
+ self._frames, self._limits[clip])) - 1
+ source = min(index +
+ self.lookahead, last) if index <= last else index
+ rows.append(self._raw[source - self._pending_base][clip])
+ raw = torch.stack(rows)
+ spectrum = self._spectra[index - self._pending_base]
+ delta = self.model.correction(raw, spectrum)
+ frame = torch.fft.irfft(delta, n=self.n_fft) * self.model.window.float()
+ active = torch.ones(self._audio.shape[0], 1, device=frame.device)
+ if self._limits is not None:
+ active = torch.tensor(
+ [[float(index < limit)] for limit in self._limits],
+ device=frame.device)
+ start = index * self.hop - self._ola_base
+ needed = start + self.n_fft
+ if needed > self._ola.shape[1]:
+ grow = needed - self._ola.shape[1]
+ self._ola = torch.cat(
+ (self._ola, self._ola.new_zeros(self._ola.shape[0], grow)),
+ dim=1)
+ self._envelope = torch.cat(
+ (self._envelope,
+ self._envelope.new_zeros(self._envelope.shape[0], grow)),
+ dim=1)
+ self._ola[:, start:needed] += frame * active
+ self._envelope[:,
+ start:needed] += (self.model.window.float()**2 * active)
+ self._emitted += 1
+
+ def _advance(self, limit: int) -> None:
+ """Computes every frame below ``limit`` in blocks, then synthesizes."""
+ while self._frames < limit:
+ count = min(self.block_frames, limit - self._frames,
+ self._next_cut() - self._frames)
+ spectra = self._analyze(self._frames, count)
+ raw = self._run_block(spectra)
+ self._raw.extend(raw.unbind(0))
+ self._spectra.extend(spectra.unbind(0))
+ self._frames += count
+ if self._limits is None:
+ self._synthesize_ready()
+ while self._emitted + self.lookahead < self._frames:
+ self._synthesize()
+ self._trim()
+
+ def _synthesize_ready(self) -> None:
+ """Synthesizes, together, every frame whose look-ahead frame has been
+ computed, as ``_synthesize`` would one by one: the correction and the
+ inverse transforms run once, the overlap-add frame by frame in order.
+ """
+ count = self._frames - self.lookahead - self._emitted
+ if count <= 0:
+ return
+ first = self._emitted - self._pending_base
+ raw = torch.stack(self._raw[first + self.lookahead:first +
+ self.lookahead + count])
+ spectrum = torch.stack(self._spectra[first:first + count])
+ window = self.model.window.float()
+ frames = torch.fft.irfft(self.model.correction(raw, spectrum),
+ n=self.n_fft) * window
+ start = self._emitted * self.hop - self._ola_base
+ needed = start + (count - 1) * self.hop + self.n_fft
+ if needed > self._ola.shape[1]:
+ grow = needed - self._ola.shape[1]
+ self._ola = torch.nn.functional.pad(self._ola, (0, grow))
+ self._envelope = torch.nn.functional.pad(self._envelope, (0, grow))
+ squared = window**2
+ for k in range(count):
+ at = start + k * self.hop
+ self._ola[:, at:at + self.n_fft] += frames[k]
+ self._envelope[:, at:at + self.n_fft] += squared
+ self._emitted += count
+
+ def _trim(self) -> None:
+ """Drops what no frame still needs."""
+ drop = self._emitted - self._pending_base
+ self._raw, self._spectra = self._raw[drop:], self._spectra[drop:]
+ self._pending_base = self._emitted
+ keep_from = self._released - self._ola_base
+ if keep_from > 0:
+ self._ola = self._ola[:, keep_from:]
+ self._envelope = self._envelope[:, keep_from:]
+ self._ola_base = self._released
+ needed_from = min(self._released,
+ max(0, self._frames * self.hop - self.n_fft // 2))
+ drop_audio = needed_from - self._audio_base
+ if drop_audio > 0:
+ self._audio = self._audio[:, drop_audio:]
+ self._audio_base = needed_from
+
+ def _release(self, upto: int) -> torch.Tensor:
+ """Output samples [released, upto): input plus synthesized change."""
+ total = self._audio_base + self._audio.shape[1]
+ start, stop = self._released, min(upto, total)
+ if stop <= start:
+ return self._audio.new_zeros(self._audio.shape[0], 0)
+ offset = self.n_fft // 2 - self._ola_base
+ envelope = self._envelope[:, start + offset:stop + offset]
+ delta = self._ola[:, start + offset:stop +
+ offset] / envelope.clamp(min=1e-11)
+ self._released = stop
+ return self._audio[:, start - self._audio_base:stop -
+ self._audio_base] + delta
+
+ def _accept(self, audio) -> tuple[torch.Tensor, bool]:
+ as_numpy = isinstance(audio, np.ndarray)
+ samples = torch.as_tensor(audio)
+ if samples.ndim not in (1, 2) or not samples.is_floating_point():
+ raise ValueError(
+ "Push mono float samples [samples] or a batch [clips, samples]."
+ )
+ rank = samples.ndim
+ if self._rank is None:
+ self._rank = rank
+ clips = samples.shape[0] if rank == 2 else 1
+ if self._limits is not None and len(self._limits) != clips:
+ raise ValueError("lengths names every clip of the batch.")
+ if rank == 2:
+ self._audio = self._audio.new_zeros(clips, 0)
+ self._ola = self._ola.new_zeros(clips, self.n_fft)
+ self._envelope = self._envelope.new_zeros(clips, self.n_fft)
+ if rank != self._rank or (rank == 2 and
+ samples.shape[0] != self._audio.shape[0]):
+ raise ValueError(
+ "Every push of a session has the same rank and batch.")
+ samples = samples.detach().to(self._audio.device, torch.float32)
+ return samples if rank == 2 else samples[None], as_numpy
+
+ def _deliver(self, released: torch.Tensor, as_numpy: bool):
+ released = released.detach().cpu()
+ if self._rank != 2:
+ released = released[0]
+ return released.numpy() if as_numpy else released
+
+ @torch.inference_mode()
+ def push(self,
+ audio: np.ndarray | torch.Tensor) -> np.ndarray | torch.Tensor:
+ """Feeds new samples; returns the output samples that became final."""
+ if self._closed:
+ raise RuntimeError("The stream was flushed.")
+ samples, as_numpy = self._accept(audio)
+ self._audio = torch.cat((self._audio, samples), dim=1)
+ total = self._audio_base + self._audio.shape[1]
+ computable = (total - self.n_fft // 2) // self.hop + 1
+ self._advance(max(0, computable))
+ released = self._release(self._emitted * self.hop - self.n_fft // 2)
+ self._trim()
+ return self._deliver(released, as_numpy)
+
+ @torch.inference_mode()
+ def flush(self, as_numpy: bool = False) -> np.ndarray | torch.Tensor:
+ """Ends the stream and returns every remaining output sample."""
+ if self._closed:
+ return self._deliver(self._audio.new_zeros(self._audio.shape[0], 0),
+ as_numpy)
+ self._closed = True
+ total = self._audio_base + self._audio.shape[1]
+ self._advance(total // self.hop + 1)
+ while self._emitted < self._frames:
+ self._synthesize()
+ return self._deliver(self._release(total), as_numpy)
diff --git a/tests/bench/scripts/anchor_rows.py b/tests/bench/scripts/anchor_rows.py
new file mode 100644
index 0000000..8bec06a
--- /dev/null
+++ b/tests/bench/scripts/anchor_rows.py
@@ -0,0 +1,87 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Synthetic board rows placed by the anchor policy.
+
+INPUT, REF and systems a, b and c sit at 0, 1, 0.7, 0.4 and 0.9 of every
+declared gap (INPUT and REF on the endpoint each verifies) and at the same
+fractions of a fixed scale where a metric declares none; b deletes one of the
+deletion cohort's 20 segments.
+"""
+
+import anchors
+import scorefiles
+
+
+def scores() -> dict[str, dict]:
+ """Returns the score dicts of INPUT, REF and systems a, b and c."""
+ policy = anchors.definitions()
+ systems = {}
+ for name, value in (
+ ("INPUT", 0),
+ ("REF", 1),
+ ("a", 0.7),
+ ("b", 0.4),
+ ("c", 0.9),
+ ):
+ data = {
+ "_set_id": "set",
+ "_subset": "all",
+ **anchors.stamp(policy),
+ "_deletion": {
+ "items": {
+ "r0": [0, 8],
+ "r1": [int(name == "b"), 12]
+ }
+ },
+ }
+ for rule in policy["rules"]:
+ for condition in rule["conditions"]:
+ d = data.setdefault(condition, {"n": 24})
+ for metric in rule["metrics"]:
+ low = rule["floor"].get("value")
+ high = rule["ceiling"].get("value")
+ # INPUT on the floor, REF on the ceiling, and each on
+ # the endpoint it verifies
+ if low is not None and high is not None:
+ v = low + value * (high - low)
+ for side in ("floor", "ceiling"):
+ verify = rule[side].get("verify") or {}
+ if verify.get("source") == name:
+ v = rule[side]["value"]
+ elif "spk_sim" in metric:
+ v = 0.5 + value * 0.5
+ elif "nisqa" in metric:
+ v = 2 + value * 2
+ elif "kept" in metric:
+ v = -10 + value * 10
+ elif metric == "_hf_err":
+ v = 1 - value
+ else:
+ v = value * 20 * rule["direction"]
+ d[metric] = v
+ # the band-limited rows as a denoiser's, which the registry's rule
+ # ranks on the denoising board: under its threshold, with the per-band
+ # levels the row derives from; the input stays on its anchor
+ for condition, first in scorefiles.BAND_LIMITED_ROWS:
+ d = data.get(condition)
+ if d is None or "band_added_db" not in d:
+ continue
+ if name != "INPUT":
+ low = anchors.rule_for(policy, condition,
+ "band_added_db")["floor"]["value"]
+ d["band_added_db"] = low + value * (8.0 - low)
+ d["band_kept_db"] = [0.0] * first + [d["band_added_db"]
+ ] * (7 - first)
+ systems[name] = data
+ return systems
diff --git a/tests/bench/scripts/conftest.py b/tests/bench/scripts/conftest.py
new file mode 100644
index 0000000..5c90e0f
--- /dev/null
+++ b/tests/bench/scripts/conftest.py
@@ -0,0 +1,290 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Bench-script tests import the scripts as plain modules."""
+
+import os
+import sys
+
+import pytest
+
+REPO = os.path.dirname(
+ os.path.dirname(os.path.dirname(os.path.dirname(
+ os.path.abspath(__file__)))))
+sys.path.insert(0, os.path.join(REPO, "bench", "scripts"))
+# the wrappers' receipt module, which the scripts read render receipts with
+sys.path.insert(0, os.path.join(REPO, "bench", "wrappers"))
+
+
+def suppression_energies(value_db, scale=1e6):
+ """Returns per-item energies whose suppression is ``value_db``.
+
+ |o|^2, <o, r>, |r|^2 and |m - r|^2 of an output that is the voice plus the
+ chatter scaled to ``value_db`` (orthogonal, of equal energy), with no
+ output gain: both the suppression row (levels.suppression_db) and the
+ residual row (scoreresidual.babble_metrics) read ``value_db`` from them,
+ and the unchanged mixture reads zero. Large enough that the epsilons do
+ not show.
+ """
+ return [scale * (1.0 + 10**(value_db / 10)), scale, scale, scale]
+
+
+def composite_case():
+ """Small complete score/observation bundles.
+
+ Their checkpoints differ in known ways.
+ """
+
+ def create(root, set_id="public", sealed=False):
+ # pylint: disable-next=import-outside-toplevel
+ import anchors
+ # pylint: disable-next=import-outside-toplevel
+ import observations
+ # pylint: disable-next=import-outside-toplevel
+ import ranking
+ # pylint: disable-next=import-outside-toplevel
+ import scorefiles
+ # pylint: disable-next=import-outside-toplevel
+ import scoreresidual
+
+ policy = anchors.definitions()
+ scores, systems = {}, {}
+ for name, fraction in (
+ ("INPUT", 0.0),
+ ("REF", 1.0),
+ ("candidate", 0.7),
+ ("baseline", 0.5),
+ ):
+ score = {
+ "_set_id": set_id,
+ "_subset": "all",
+ **anchors.stamp(policy),
+ }
+ for rule in policy["rules"]:
+ for condition in rule["conditions"]:
+ if condition.startswith("_"):
+ continue
+ cell = score.setdefault(condition, {
+ "n": 24,
+ "n_missing": 0
+ })
+ for metric in rule["metrics"]:
+ low = rule["floor"].get("value")
+ high = rule["ceiling"].get("value")
+ # declared endpoints: INPUT sits on the floor, REF on
+ # the ceiling, and each on the endpoint it verifies
+ if low is not None and high is not None:
+ value = low + fraction * (high - low)
+ for side in ("floor", "ceiling"):
+ verify = rule[side].get("verify") or {}
+ if verify.get("source") == name:
+ value = rule[side]["value"]
+ elif "spk_sim" in metric:
+ value = 0.5 + fraction * 0.5
+ elif "nisqa" in metric:
+ value = 2 + fraction * 2
+ elif "kept" in metric:
+ value = -10 + fraction * 10
+ elif metric == "_hf_err":
+ value = 1 - fraction
+ elif condition == "clean":
+ value = 10 + fraction * 30
+ elif rule["direction"] == -1:
+ value = -20 * fraction
+ else:
+ value = -5 + 25 * fraction
+ cell[metric] = value
+ # the band-limited rows: denoisers, as the registry's assignment
+ # reads them (under its threshold), with the per-band levels the
+ # row derives from; the input stays on its anchor
+ for condition, first in scorefiles.BAND_LIMITED_ROWS:
+ cell = score.get(condition)
+ if cell is None or "band_added_db" not in cell:
+ continue
+ if name != "INPUT":
+ low = anchors.rule_for(policy, condition,
+ "band_added_db")["floor"]["value"]
+ cell["band_added_db"] = low + fraction * (8.0 - low)
+ cell["band_kept_db"] = ([0.0] * first +
+ [cell["band_added_db"]] * (7 - first))
+ # the real recordings' pooled rows: every family between the
+ # pooled row's endpoints, so the pooled value sits there too
+ quality = anchors.rule_for(policy, "_real_quality", "nisqa_mos")
+ cleanup = anchors.rule_for(policy, "_real_cleanup",
+ "pause_resid_db")
+ level = anchors.rule_for(policy, "_real_cleanup", "pause_level_db")
+ for family in ("real_dirty", "real_multi", "real_noisy",
+ "real_wild"):
+ cell = score.setdefault(family, {"n": 24, "n_missing": 0})
+ low, high = (quality["floor"]["value"],
+ quality["ceiling"]["value"])
+ cell["nisqa_mos"] = low + fraction * (high - low)
+ low, high = (cleanup["floor"]["value"],
+ cleanup["ceiling"]["value"])
+ cell["pause_resid_db"] = low + fraction * (high - low)
+ cell["pause_resid_db_nb"] = cell["pause_resid_db"]
+ low, high = level["floor"]["value"], level["ceiling"]["value"]
+ cell["pause_level_db"] = low + fraction * (high - low)
+ score["_real_quality"] = {
+ "n": 24,
+ "nisqa_mos": score["real_noisy"]["nisqa_mos"],
+ }
+ score["_real_cleanup"] = {
+ "n": 96,
+ "pause_resid_db": score["real_noisy"]["pause_resid_db"],
+ "pause_resid_db_nb": score["real_noisy"]["pause_resid_db"],
+ "pause_level_db": score["real_noisy"]["pause_level_db"],
+ }
+ # the same-room block pooled (scoreevents), once the policy
+ # declares it: between its endpoints, the anchor rows on theirs
+ try:
+ voice = anchors.rule_for(policy, "_coroom", "voice_level_db")
+ except ValueError:
+ voice = None
+ if voice is not None:
+ low, high = voice["floor"]["value"], voice["ceiling"]["value"]
+ value = low + fraction * (high - low)
+ for side in ("floor", "ceiling"):
+ if (voice[side].get("verify") or {}).get("source") == name:
+ value = voice[side]["value"]
+ score["_coroom"] = {
+ "n": 96,
+ "n_missing": 0,
+ "voice_level_db": value,
+ }
+ # every item of the block carries the row it pools
+ for condition in voice.get(
+ "pooled_from", ()) or ("coroom@pause", "coroom@speech",
+ "coroom@floor", "coroom@both"):
+ if condition in score:
+ score[condition]["voice_level_db"] = value
+ rows, cohort = [], {}
+ for condition, cell in sorted(score.items()):
+ if condition.startswith("_"):
+ continue
+ for i in range(24):
+ uid = f"{condition}_{i}.wav"
+ metrics = {
+ k: v
+ for k, v in cell.items()
+ if k not in ("n", "n_missing")
+ }
+ if condition == "clean":
+ hf_err = cell["_hf_err"]
+ metrics["band_kept_db"] = [0] * 4 + [hf_err] * 3
+ metrics["out_in_rms_db"] = -cell["_level_err"]
+ if "band_added_db" in cell:
+ # the per-band levels the band row derives from: the
+ # bands above the input hold the cell's value, those
+ # inside it nothing
+ first = dict(scorefiles.BAND_LIMITED_ROWS)[condition]
+ metrics["band_kept_db"] = ([0] * first +
+ [cell["band_added_db"]] *
+ (7 - first))
+ # pooled on the board: counts per item
+ if "nv_lost_pct" in metrics:
+ metrics.update(
+ nv_blocks=100,
+ nv_lost=int(round(metrics["nv_lost_pct"])),
+ )
+ # read from energies: the suppression row by the energies
+ # that give its value, the residual row by what those
+ # energies read as (scoreresidual.babble_metrics)
+ for key in ("babble_supp_db", "babble_supp_db_nb"):
+ if key in metrics:
+ energy = suppression_energies(metrics[key])
+ metrics[key.replace("supp_db", "energy")] = energy
+ resid = key.replace("supp_db", "resid_db")
+ metrics[resid] = scoreresidual.babble_metrics(
+ energy)
+ cell[resid] = metrics[resid]
+ if condition == "real_noisy":
+ deleted = int(name == "baseline" and i == 0)
+ cohort[uid] = [deleted, 1]
+ metrics.update(
+ primary_drops=[-30.0 if deleted else 0.0],
+ primary_segments=1,
+ )
+ rows.append({
+ "id": uid,
+ "condition": condition,
+ "language": "en",
+ "speech_source": f"{set_id}-speech-{i}",
+ "bed_source": (None if condition == "clean" else
+ f"{set_id}-bed-{i % 6}"),
+ "groups_verified": True,
+ "output_status": "ok",
+ # what the record measured, as every scorer stamps it
+ "identity": {
+ "output": f"{name}-{uid}",
+ "mix": f"mix-{uid}",
+ "ref": (None if condition.startswith("real") else
+ f"ref-{uid}"),
+ "semantics": {
+ "condition": condition
+ },
+ },
+ "metrics": metrics,
+ })
+ score["_deletion"] = {"items": cohort, "primary_anchored": True}
+ score["_level_cal_db"] = 0.0
+ scores[name] = score
+ metadata = {
+ "system": name,
+ "set_id": set_id,
+ "subset": "all",
+ "sealed": sealed,
+ "anchors_version": policy["version"],
+ "anchors_sha256": anchors.digest(policy),
+ "scorer_sha256": "fixture",
+ "level_cal_db": 0,
+ "n_expected": len(rows),
+ "render_identity": {
+ "weights_sha256": anchors.digest(name),
+ "precision": "fp32",
+ },
+ }
+ systems[name] = metadata, rows
+ observations.write(root / f"{name}.items.jsonl", rows, metadata)
+ calibration = anchors.resolve(policy, scores, ranking.AXES_BY_TIER,
+ sealed)
+ anchors.atomic_json(root / anchors.RESOLVED, calibration)
+ return scores, calibration, systems
+
+ return create
+
+
+def saturate():
+ """Rewrites a system's per-item header with a saturated level calibration.
+
+ Takes the folder ``composite_case`` wrote, the system and the calibration in
+ dB (12 by default).
+ """
+
+ def rewrite(root, system, level_cal_db=12.0):
+ # pylint: disable-next=import-outside-toplevel
+ import observations
+
+ path = root / f"{system}.items.jsonl"
+ metadata, rows = observations.read(path)
+ metadata = {
+ k: v
+ for k, v in metadata.items()
+ if k not in ("type", "schema_version")
+ }
+ metadata["level_cal_db"] = level_cal_db
+ observations.write(path, rows, metadata)
+
+ return rewrite
diff --git a/tests/bench/scripts/test_admission.py b/tests/bench/scripts/test_admission.py
new file mode 100644
index 0000000..6061a21
--- /dev/null
+++ b/tests/bench/scripts/test_admission.py
@@ -0,0 +1,689 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Known regressions, null controls and listening evidence for admission.
+
+Admissions are replayable.
+"""
+
+# pylint: disable=redefined-outer-name
+
+import copy
+import math
+
+import pytest
+
+import admission
+import anchors
+
+
+def panel():
+ registry = {
+ "schema_version": 1,
+ "version": "1",
+ "policy": {
+ "min_items": 20,
+ "min_source_groups": 2,
+ "min_human_items": 20,
+ "max_redundancy": 0.9,
+ },
+ "baseline": {
+ "all": {
+ "full": {
+ "suppression": [["speech", "old", 1]]
+ }
+ }
+ },
+ "history": [{
+ "version": "1",
+ "action": "baseline"
+ }],
+ }
+ policy = anchors.definitions()
+ policy["rules"].append({
+ "conditions": ["speech"],
+ "metrics": ["new"],
+ "direction": 1,
+ "floor": {
+ "value": 0,
+ "rationale": "test floor"
+ },
+ "ceiling": {
+ "value": 10,
+ "rationale": "test ceiling"
+ },
+ })
+ systems = {}
+ for name, shift in (("baseline", 0), ("regression", -1), ("null", 0)):
+ metadata = {
+ "set_id": "set",
+ "subset": "all",
+ "anchors_version": policy["version"],
+ "anchors_sha256": anchors.digest(policy),
+ "scorer_sha256": "same",
+ "render_identity": {
+ "weights_sha256": anchors.digest(name)
+ },
+ }
+ rows = [{
+ "id": str(i),
+ "condition": "speech",
+ "language": "en",
+ "output_status": "ok",
+ "speech_source": f"source-{i}",
+ "bed_source": f"bed-{i % 5}",
+ "groups_verified": True,
+ "metrics": {
+ "new": math.sin(i) + shift,
+ "old": math.cos(i)
+ },
+ } for i in range(40)]
+ systems[name] = metadata, rows
+ config = {
+ "baseline": "baseline",
+ "regression": "regression",
+ "null": "null",
+ "ranked_systems": list(systems),
+ "roster": {
+ "sha256": "published",
+ "systems": list(systems)
+ },
+ }
+ proposal = {
+ "view": "all",
+ "tier": "full",
+ "axis": "suppression",
+ "condition": "speech",
+ "metric": "new",
+ "direction": 1,
+ }
+ study = {
+ "set_id":
+ "set",
+ "condition":
+ "speech",
+ "baseline_sha256":
+ anchors.digest("baseline"),
+ "regression_sha256":
+ anchors.digest("regression"),
+ "ratings": [{
+ "item_id": str(i),
+ "listener": str(j),
+ "preference": -1
+ } for i in range(40) for j in range(3)],
+ }
+ return config, systems, proposal, registry, policy, study
+
+
+def test_regression_null_and_human_evidence_admit_and_replay(panel):
+ report = admission.evaluate(*panel, n_boot=100)
+ assert report["admitted"] and all(report["checks"].values())
+ registry = admission.record_change(panel[3], report, "2",
+ "Validated additional sensitivity")
+ assert admission.replay(registry)["all"]["full"]["suppression"] == [
+ ["speech", "old", 1],
+ ["speech", "new", 1],
+ ]
+ assert registry["history"][-1]["study_id"] == report["study_id"]
+
+
+def test_e1_without_a_listening_study_cannot_admit(panel):
+ report = admission.evaluate(*panel[:-1], study=None, n_boot=100)
+ assert report["checks"]["E1"] and not report["checks"]["E2"]
+ assert not report["admitted"]
+ with pytest.raises(ValueError, match="not admitted"):
+ admission.record_change(panel[3], report, "2", "No human study")
+
+
+def test_null_separation_and_wrong_human_sign_block_admission(panel):
+ for row in panel[1]["null"][1]:
+ row["metrics"]["new"] += 0.5
+ assert not admission.evaluate(*panel, n_boot=100)["checks"]["E1"]
+ for rating in panel[-1]["ratings"]:
+ rating["preference"] = 1
+ assert not admission.evaluate(*panel, n_boot=100)["checks"]["E2"]
+
+
+def test_redundant_rows_must_replace_instead_of_gaining_weight(panel):
+ for _, rows in panel[1].values():
+ for row in rows:
+ row["metrics"]["old"] = row["metrics"]["new"]
+ assert not admission.evaluate(*panel, n_boot=100)["checks"]["E3"]
+ panel[2]["replaces"] = ["speech", "old", 1]
+ report = admission.evaluate(*panel, n_boot=100)
+ assert report["admitted"]
+ registry = admission.record_change(panel[3], report, "2",
+ "Replace a redundant row")
+ assert admission.replay(registry)["all"]["full"]["suppression"] == [[
+ "speech", "new", 1
+ ]]
+
+
+def test_unknown_groups_or_absent_anchors_block_admission(panel):
+ for row in panel[1]["regression"][1]:
+ row["groups_verified"] = False
+ report = admission.evaluate(*panel, n_boot=100)
+ assert not report["checks"]["E1"] and not report["checks"]["E4"]
+ panel[4]["rules"].pop()
+ for metadata, _ in panel[1].values():
+ metadata["anchors_sha256"] = anchors.digest(panel[4])
+ assert not admission.evaluate(*panel, n_boot=100)["checks"]["E4"]
+
+
+def test_stale_study_and_modified_admission_evidence_are_refused(panel):
+ report = admission.evaluate(*panel, n_boot=100)
+ changed = copy.deepcopy(report)
+ changed["human"] = None
+ changed["evidence_sha256"] = anchors.digest({
+ k: v for k, v in changed.items() if k != "evidence_sha256"
+ })
+ with pytest.raises(ValueError):
+ admission.record_change(panel[3], changed, "2", "Invalid")
+ panel[-1]["baseline_sha256"] = "other"
+ with pytest.raises(ValueError, match="checkpoint identity"):
+ admission.evaluate(*panel, n_boot=100)
+
+
+def test_changelog_cannot_reuse_a_version(panel):
+ report = admission.evaluate(*panel, n_boot=100)
+ with pytest.raises(ValueError, match="unique version"):
+ admission.record_change(panel[3], report, "1", "Changed membership")
+
+
+def test_cherry_picked_roster_cannot_admit(panel):
+ panel[0]["ranked_systems"] = ["baseline"]
+ with pytest.raises(ValueError, match="entire pinned"):
+ admission.evaluate(*panel, n_boot=100)
+
+
+def test_removal_requires_two_intact_consecutive_failed_panels(panel):
+ panel[2]["metric"] = "old"
+ registry = panel[3]
+ registry["baseline"]["all"]["full"]["suppression"].append(
+ ["speech", "remaining", 1])
+ panel[0]["sequence"] = 1
+ first = admission.evaluate(*panel, n_boot=100, review_existing=True)
+ panel[0]["sequence"] = 2
+ second = admission.evaluate(*panel, n_boot=100, review_existing=True)
+ result = admission.record_removal(
+ registry,
+ [first, second],
+ "older-set",
+ "2",
+ "Repeated loss of sensitivity",
+ )
+ assert admission.replay(result)["all"]["full"]["suppression"] == [[
+ "speech", "remaining", 1
+ ]]
+ second["sequence"] = 3
+ with pytest.raises(ValueError, match="consecutive"):
+ admission.record_removal(registry, [first, second], "older-set", "2",
+ "Invalid")
+
+
+def test_changing_metric_coverage_between_panel_arms_blocks_admission(panel):
+ panel[1]["regression"][1][0]["metrics"]["new"] = None
+ report = admission.evaluate(*panel, n_boot=100)
+ assert report["regression"]["ci95"][1] < 0
+ assert not report["checks"]["E1"] and not report["admitted"]
+
+
+def test_a_redefinition_is_recorded_as_the_maintainers_and_replays(panel):
+ registry = panel[3]
+ rows = {"full": [["speech", "kept", 1], ["speech", "level", -1]]}
+ staged = admission.record_redefinition(
+ registry,
+ "suppression",
+ rows,
+ "2",
+ "Score what is audible",
+ "bench/METRICS.md",
+ )
+ replayed = admission.replay(staged)
+ assert replayed["all"]["full"]["suppression"] == rows["full"]
+ assert admission.replay(registry)["all"]["full"]["suppression"] == [[
+ "speech", "old", 1
+ ]]
+ change = staged["history"][-1]
+ assert change["decided_by"] == "maintainer" and change["study_id"] is None
+
+ def broken(edit):
+ bad = copy.deepcopy(staged)
+ edit(bad["history"][-1])
+ with pytest.raises(ValueError):
+ admission.replay(bad)
+
+ # never dressed up as evidence
+ broken(lambda c: c.update(decided_by="panel"))
+ broken(lambda c: c.update(note=""))
+ broken(lambda c: c.update(axis="absent"))
+ # changes nothing
+ broken(lambda c: c.update(rows={"full": [["speech", "old", 1]]}))
+ broken(lambda c: c.update(
+ rows={"full": [["speech", "kept", 1], ["speech", "kept", -1]]}))
+ broken(lambda c: c.update(rows={
+ "full": rows["full"],
+ "nb": rows["full"]
+ })) # a tier the views lack
+ # made against another registry
+ broken(lambda c: c.update(axis_sha256="0" * 64))
+ with pytest.raises(ValueError, match="unique version"):
+ admission.record_redefinition(registry, "suppression", rows, "1",
+ "reason", "bench/METRICS.md")
+
+
+def test_a_revision_adds_an_axis_states_every_view_and_replays(panel):
+ registry = panel[3]
+ axes = {
+ "all": {
+ "full": {
+ "suppression": [["speech", "kept", 1]],
+ "room": [["reverb", "spk", 1]],
+ }
+ }
+ }
+ members = {"removes": ["suppression", "room"]}
+ staged = admission.record_revision(registry, axes, "2", "Cover rooms",
+ "bench/METRICS.md", members)
+ assert admission.replay(staged)["all"]["full"] == axes["all"]["full"]
+ assert (admission.parts(staged) == members and
+ admission.parts(registry) is None)
+ change = staged["history"][-1]
+ assert change["action"] == "revise" and change["decided_by"] == "maintainer"
+
+ def broken(edit):
+ bad = copy.deepcopy(staged)
+ edit(bad["history"][-1])
+ with pytest.raises(ValueError):
+ admission.replay(bad)
+
+ broken(lambda c: c.update(decided_by="panel"))
+ broken(lambda c: c.update(note=""))
+ broken(lambda c: c.update(reason=""))
+ broken(lambda c: c.update(axis_sha256="0" * 64))
+ # a view the registry lacks
+ broken(lambda c: c.update(axes={"core": axes["all"]}))
+ # and a tier
+ broken(lambda c: c.update(axes={"all": {"nb": axes["all"]["full"]}}))
+ broken(lambda c: c.update(
+ axes={"all": {
+ "full": {
+ "suppression": [["speech", "old", 1]]
+ }
+ }}))
+ broken(lambda c: c.update(
+ axes={"all": {
+ "full": {
+ "room": [["reverb", "spk", 0]]
+ }
+ }}))
+ # an axis left out
+ broken(lambda c: c.update(parts={"removes": ["suppression"]}))
+ broken(lambda c: c.update(parts={
+ "removes": ["suppression", "room"],
+ "keeps": ["room"]
+ }))
+ # beside the composite: a scored axis
+ broken(lambda c: c.update(outside=["absent"]))
+ # and never all of them
+ broken(lambda c: c.update(outside=["suppression", "room"]))
+ # the parts then hold the axes inside alone
+ broken(lambda c: c.update(outside=["room"]))
+ with pytest.raises(ValueError, match="unique version"):
+ admission.record_revision(registry, axes, "1", "reason",
+ "bench/METRICS.md")
+ beside = admission.record_revision(
+ registry,
+ axes,
+ "2",
+ "Cover rooms",
+ "bench/METRICS.md",
+ {"removes": ["suppression"]},
+ None,
+ ["room"],
+ )
+ assert (admission.outside(beside) == ["room"] and
+ not admission.outside(registry))
+ assert admission.parts(beside) == {"removes": ["suppression"]}
+
+
+def test_views_of_a_revision_score_the_same_axes(panel):
+ registry = copy.deepcopy(panel[3])
+ registry["baseline"]["core"] = copy.deepcopy(registry["baseline"]["all"])
+ room = {"full": {"room": [["reverb", "spk", 1]]}}
+ with pytest.raises(ValueError, match="same axes"):
+ admission.record_revision(
+ registry,
+ {
+ "all": room,
+ "core": {
+ "full": {
+ "suppression": [["speech", "kept", 1]]
+ }
+ },
+ },
+ "2",
+ "reason",
+ "bench/METRICS.md",
+ )
+ staged = admission.record_revision(registry, {
+ "all": room,
+ "core": room
+ }, "2", "reason", "note.md")
+ core = admission.replay(staged)["core"]["full"]
+ assert set(core) == {"suppression", "room"}
+ # a revision of one view's rows leaves the other view as it was
+ wider = {
+ "full": {
+ "suppression": [["speech", "kept", 1], ["crowd", "kept", 1]]
+ }
+ }
+ narrowed = admission.record_revision(staged, {"core": wider}, "3", "reason",
+ "note.md")
+ views = admission.replay(narrowed)
+ assert views["core"]["full"]["suppression"] == wider["full"]["suppression"]
+ assert views["all"] == admission.replay(staged)["all"]
+
+
+def test_bench_axes_selects_another_registry_file(tmp_path, monkeypatch):
+ # pylint: disable-next=import-outside-toplevel
+ import importlib
+ live = admission.DEFAULT
+ copied = tmp_path / "axes.json"
+ copied.write_text(live.read_text(encoding="utf-8"), encoding="utf-8")
+ monkeypatch.setenv("BENCH_AXES", str(copied))
+ try:
+ reloaded = importlib.reload(admission)
+ assert reloaded.DEFAULT == copied
+ assert reloaded.load()["version"] == admission.load(copied)["version"]
+ finally:
+ # the environment as it was (the live file, or the registry BENCH_AXES
+ # named for this run), then the module as it was: a reload under
+ # another file would leave every later test on a registry of its own
+ monkeypatch.undo()
+ importlib.reload(admission)
+ assert admission.DEFAULT == live and live != copied
+
+
+def _beside(panel):
+ """The fixture's registry with a new axis scored beside the composite."""
+ registry = admission.record_revision(
+ panel[3], {"all": {
+ "full": {
+ "voices": [["speech", "new", 1]]
+ }
+ }}, "2", "Show the voices beside the board", "bench/METRICS.md",
+ {"removes": ["suppression"]}, None, ["voices"])
+ proposal = dict(panel[2], axis="voices")
+ return registry, proposal
+
+
+def test_an_axis_beside_the_composite_is_promoted_on_a_passing_review(panel):
+ registry, proposal = _beside(panel)
+ config, systems, _, _, policy, study = panel
+ report = admission.evaluate(config,
+ systems,
+ proposal,
+ registry,
+ policy,
+ study,
+ n_boot=100,
+ review_existing=True,
+ redundancy_rows=[["speech", "old", 1]])
+ assert not report["admitted"] and all(report["checks"].values())
+ staged = admission.record_promotion(registry, report, "removes", "3",
+ "Listeners prefer the removal",
+ "bench/METRICS.md")
+ assert not admission.outside(staged)
+ assert admission.parts(staged) == {"removes": ["suppression", "voices"]}
+ assert admission.replay(staged)["all"]["full"]["voices"] == [[
+ "speech", "new", 1
+ ]]
+ assert staged["history"][-1]["study_id"] == report["study_id"]
+
+
+def test_a_promotion_without_passing_or_intact_evidence_is_refused(panel):
+ registry, proposal = _beside(panel)
+ config, systems, _, _, policy, study = panel
+ # reviewed against its own axis alone, the row has nothing to be compared
+ # with: redundancy (E3) does not pass
+ alone = admission.evaluate(config,
+ systems,
+ proposal,
+ registry,
+ policy,
+ study,
+ n_boot=100,
+ review_existing=True)
+ assert not alone["checks"]["E3"]
+ with pytest.raises(ValueError, match="every check"):
+ admission.record_promotion(registry, alone, "removes", "3", "r",
+ "bench/METRICS.md")
+ report = admission.evaluate(config,
+ systems,
+ proposal,
+ registry,
+ policy,
+ study,
+ n_boot=100,
+ review_existing=True,
+ redundancy_rows=[["speech", "old", 1]])
+ # evidence edited after the review is not intact
+ changed = dict(report, human=dict(report["human"], ci95=[-0.5, -0.1]))
+ with pytest.raises(ValueError, match="every check"):
+ admission.record_promotion(registry, changed, "removes", "3", "r",
+ "bench/METRICS.md")
+ with pytest.raises(ValueError, match="existing part"):
+ admission.record_promotion(registry, report, "keeps", "3", "r",
+ "bench/METRICS.md")
+ with pytest.raises(ValueError, match="note"):
+ admission.record_promotion(registry, report, "removes", "3", "r", "")
+ # a hand-edited promotion that also moves another axis does not replay
+ staged = admission.record_promotion(registry, report, "removes", "3", "r",
+ "bench/METRICS.md")
+ staged["history"][-1]["parts"] = {"removes": ["voices"]}
+ with pytest.raises(ValueError, match="changes nothing else"):
+ admission.replay(staged)
+
+
+def test_a_revision_moves_an_axis_into_the_composite_without_restating_rows(
+ panel):
+ registry, _ = _beside(panel)
+ staged = admission.record_revision(registry, {}, "3", "Count the voices",
+ "bench/METRICS.md",
+ {"removes": ["suppression", "voices"]},
+ None, [])
+ assert not admission.outside(staged)
+ assert admission.parts(staged) == {"removes": ["suppression", "voices"]}
+ assert admission.replay(staged)["all"]["full"]["voices"] == [[
+ "speech", "new", 1
+ ]]
+ assert staged["history"][-1]["action"] == "revise"
+
+
+def test_a_revision_that_restates_nothing_and_moves_nothing_is_refused(panel):
+ registry, _ = _beside(panel)
+ with pytest.raises(ValueError, match="moves"):
+ admission.record_revision(registry, {}, "3", "r", "bench/METRICS.md",
+ {"removes": ["suppression"]}, None,
+ ["voices"])
+ with pytest.raises(ValueError, match="moves"):
+ admission.record_revision(registry, {}, "3", "r", "bench/METRICS.md")
+
+
+def test_a_revision_that_moves_an_axis_beside_states_where_the_rest_sit(panel):
+ registry, _ = _beside(panel)
+ # clearing `outside` with the parts inherited from before would leave
+ # voices in neither: no place on the board
+ with pytest.raises(ValueError, match="every axis inside it"):
+ admission.record_revision(registry, {}, "3", "Count the voices",
+ "bench/METRICS.md", None, None, [])
+ # moving suppression beside the composite with parts that still list it
+ # and leave voices out
+ with pytest.raises(ValueError, match="every axis inside it"):
+ admission.record_revision(registry, {}, "3", "r", "bench/METRICS.md",
+ None, None, ["suppression"])
+
+
+def test_a_promotion_sees_the_same_measurement_in_another_axis(panel):
+ registry, proposal = _beside(panel)
+ # the composite already reads the voices row inside suppression
+ doubled = admission.record_revision(
+ registry, {
+ "all": {
+ "full": {
+ "suppression": [["speech", "old", 1], ["speech", "new", 1]]
+ }
+ }
+ }, "3", "Read the new row in suppression too", "bench/METRICS.md")
+ config, systems, _, _, policy, study = panel
+ against = [[axis, row]
+ for part in admission.parts(doubled).values()
+ for axis in part
+ for row in admission.replay(doubled)["all"]["full"][axis]]
+ report = admission.evaluate(config,
+ systems,
+ proposal,
+ doubled,
+ policy,
+ study,
+ n_boot=100,
+ review_existing=True,
+ redundancy_rows=against)
+ # identical to a row the composite reads: redundancy 1, E3 fails
+ assert not report["checks"]["E3"]
+ assert any(r["abs_correlation"] == pytest.approx(1.0)
+ for r in report["redundancy"])
+ with pytest.raises(ValueError, match="every check"):
+ admission.record_promotion(doubled, report, "removes", "4", "r",
+ "bench/METRICS.md")
+
+
+def test_a_revision_declares_the_boards_over_every_part_exactly_once(panel):
+ registry = panel[3]
+ axes = {
+ "all": {
+ "full": {
+ "suppression": [["speech", "kept", 1]],
+ "room": [["reverb", "spk", 1]],
+ }
+ }
+ }
+ members = {"removes": ["suppression"], "restores": ["room"]}
+ # a part in no board
+ with pytest.raises(ValueError, match="boards"):
+ admission.record_revision(registry, axes, "2", "r", "n.md", members,
+ None, None, {"denoising": ["removes"]})
+ staged = admission.record_revision(registry, axes, "2", "Two boards",
+ "n.md", members, None, None, {
+ "denoising": ["removes"],
+ "restoration": ["restores"]
+ })
+ assert admission.boards(staged) == {
+ "denoising": ["removes"],
+ "restoration": ["restores"]
+ }
+ assert admission.boards(registry) is None
+ # a part twice, with the parts inherited
+ with pytest.raises(ValueError, match="boards"):
+ admission.record_revision(staged, {}, "3", "r", "n.md", None, None,
+ None, {
+ "denoising": ["removes", "removes"],
+ "restoration": ["restores"]
+ })
+ # a hand-edited board that drops a part does not replay
+ broken = copy.deepcopy(staged)
+ broken["history"][-1]["boards"] = {"denoising": ["removes"]}
+ with pytest.raises(ValueError, match="boards"):
+ admission.replay(broken)
+
+
+def test_a_revision_states_the_rule_that_assigns_each_system_a_board(panel):
+ axes = {
+ "all": {
+ "full": {
+ "suppression": [["speech", "kept", 1]],
+ "room": [["reverb", "spk", 1]],
+ }
+ }
+ }
+ members = {"removes": ["suppression"], "restores": ["room"]}
+ staged = admission.record_revision(panel[3], axes, "2", "Two boards",
+ "n.md", members, None, None, {
+ "denoising": ["removes"],
+ "restoration": ["restores"]
+ })
+ rule = {
+ "by": "band_above_input_db",
+ "above_db": 10.0,
+ "board": "restoration",
+ "otherwise": "denoising",
+ }
+ assert admission.assignment(staged) is None
+ assigned = admission.record_revision(staged, {},
+ "3",
+ "Each board ranks its own systems",
+ "n.md",
+ assign=rule)
+ assert admission.assignment(assigned) == rule
+ assert assigned["version"] == "3"
+ # the same rule again changes nothing
+ with pytest.raises(ValueError, match="moves"):
+ admission.record_revision(assigned, {},
+ "4",
+ "r",
+ "n.md",
+ assign=dict(rule))
+ # a board not in force, an undeclared diagnostic, one board for both, a
+ # flag for a threshold, a missing field
+ for bad in (dict(rule, board="enhancement"), dict(rule, by="nisqa_mos"),
+ dict(rule,
+ otherwise="restoration"), dict(rule, above_db=True), {
+ k: v for k, v in rule.items() if k != "above_db"
+ }):
+ with pytest.raises(ValueError, match="assignment"):
+ admission.record_revision(staged, {}, "3", "r", "n.md", assign=bad)
+ # boards renamed under an inherited rule that no longer names them
+ with pytest.raises(ValueError, match="assignment"):
+ admission.record_revision(assigned, {}, "4", "r", "n.md", None, None,
+ None, {
+ "isolation": ["removes"],
+ "restoration": ["restores"]
+ })
+
+
+def test_the_live_registry_is_one_published_baseline():
+ live = admission.load()
+ assert live["version"] == "0" and len(live["history"]) == 1
+ # the baseline states the layout, and is checked as a revision would be
+ assert admission.assignment(live)["board"] == "restoration"
+ assert admission.boards(live) and admission.parts(live)
+ broken = copy.deepcopy(live)
+ broken["history"][0]["assign"] = dict(admission.assignment(live),
+ otherwise="enhancement")
+ with pytest.raises(ValueError, match="assignment"):
+ admission.replay(broken)
+
+
+def test_the_command_line_needs_the_board_named(tmp_path, monkeypatch):
+ # the published board is an input, never a path the tool assumes
+ monkeypatch.setattr("sys.argv", [
+ "admission.py", "--panel",
+ str(tmp_path / "panel.json"), "--row",
+ str(tmp_path / "row.json"), "--out",
+ str(tmp_path / "decision.json")
+ ])
+ with pytest.raises(SystemExit):
+ admission.main()
+ assert not (tmp_path / "decision.json").exists()
diff --git a/tests/bench/scripts/test_anchors.py b/tests/bench/scripts/test_anchors.py
new file mode 100644
index 0000000..8ae24be
--- /dev/null
+++ b/tests/bench/scripts/test_anchors.py
@@ -0,0 +1,402 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Anchor endpoints, immutable identities, and roster-independent composites."""
+
+# pylint: disable=redefined-outer-name
+
+import copy
+import json
+import math
+
+import pytest
+
+import anchor_rows
+import anchors
+import ranking
+
+
+def test_removing_every_row_including_input_and_reference_leaves_bitwise_scores(
+):
+ systems = anchor_rows.scores()
+ ref_tier = ("INPUT", "REF")
+ tiers = {n: ("ref" if n in ref_tier else "full", n) for n in systems}
+ calibration = anchors.resolve(anchors.definitions(), systems,
+ ranking.AXES_BY_TIER)
+ _, before, _ = ranking.rank(copy.deepcopy(systems), tiers, calibration)
+ for removed in systems:
+ reduced = {
+ n: copy.deepcopy(v) for n, v in systems.items() if n != removed
+ }
+ _, after, _ = ranking.rank(reduced, tiers, calibration)
+ for name in ("a", "b", "c"):
+ if name != removed:
+ assert before[name].hex() == after[name].hex()
+
+
+def test_endpoints_constants_and_monotonicity():
+ policy, scores = anchors.definitions(), anchor_rows.scores()
+ calibration = anchors.resolve(policy, scores, ranking.AXES_BY_TIER)
+ for key, point in calibration["points"].items():
+ assert anchors.normalize(point["floor"], point) == 0
+ assert anchors.normalize(point["ceiling"], point) == 1
+ condition, metric = json.loads(key)
+ rule = anchors.rule_for(policy, condition, metric)
+ for side, expected in (("floor", 0), ("ceiling", 1)):
+ if "source" in rule[side] and side not in point["fallbacks"]:
+ source = rule[side]["source"]
+ assert (anchors.normalize(scores[source][condition][metric],
+ point) == expected)
+ middle = (point["floor"] + point["ceiling"]) / 2
+ assert anchors.normalize(middle + point["direction"] * 0.01,
+ point) >= anchors.normalize(middle, point)
+
+
+def test_missing_deletion_item_cannot_shrink_the_cohort():
+ systems = anchor_rows.scores()
+ calibration = anchors.resolve(anchors.definitions(), systems,
+ ranking.AXES_BY_TIER)
+ tiers = {n: ("full", n) for n in ("a", "b", "c")}
+ _, before, _ = ranking.rank(copy.deepcopy(systems), tiers, calibration)
+ del systems["c"]["_deletion"]["items"]["r1"]
+ _, after, order = ranking.rank(systems, tiers, calibration)
+ assert math.isnan(after["c"]) and "c" not in order["full"]
+ assert before["a"].hex() == after["a"].hex()
+ assert before["b"].hex() == after["b"].hex()
+
+
+def test_changed_segment_denominator_is_incomplete():
+ systems = anchor_rows.scores()
+ calibration = anchors.resolve(anchors.definitions(), systems,
+ ranking.AXES_BY_TIER)
+ systems["a"]["_deletion"]["items"]["r0"] = [0, 7]
+ ranking.pool_deletion(systems, calibration["deletion_cohort"])
+ assert math.isnan(systems["a"]["_deletion"]["pct"])
+
+
+def test_version_definition_and_content_mismatches_are_refused(tmp_path):
+ policy, systems = anchors.definitions(), anchor_rows.scores()
+ calibration = anchors.resolve(policy, systems, ranking.AXES_BY_TIER)
+ path = tmp_path / anchors.RESOLVED
+ anchors.atomic_json(path, calibration)
+ assert anchors.load(path, policy) == calibration
+ changed = copy.deepcopy(policy)
+ changed["rules"][0]["ceiling"]["value"] = -21
+ with pytest.raises(ValueError, match="version/definition"):
+ anchors.load(path, changed)
+ systems["a"]["_anchors_version"] = "older"
+ with pytest.raises(ValueError, match="version"):
+ anchors.validate_scores(calibration, systems)
+ calibration["deletion_cohort"]["r0"] = 9
+ anchors.atomic_json(path, calibration)
+ with pytest.raises(ValueError, match="digest"):
+ anchors.load(path, policy)
+
+
+def _measured_policy():
+ """Returns the shipped policy with a speaker row measured, not declared.
+
+ The speaker-similarity row is measured from INPUT and REF, as a policy may
+ still declare it: the fallback path stays covered although version 2
+ declares it.
+ """
+ policy = copy.deepcopy(anchors.definitions())
+ for rule in policy["rules"]:
+ if "spk_sim" in rule["metrics"]:
+ rule["floor"] = {
+ "source": "INPUT",
+ "fallback": 0,
+ "rationale": "measured",
+ }
+ rule["ceiling"] = {
+ "source": "REF",
+ "fallback": 1,
+ "rationale": "measured",
+ }
+ return policy
+
+
+def test_degenerate_gap_uses_only_declared_fallback_and_missing_reference_fails(
+):
+ policy, systems = _measured_policy(), anchor_rows.scores()
+ for data in systems.values():
+ data.update(anchors.stamp(policy))
+ systems["INPUT"]["babble@+4"]["spk_sim"] = 1.0
+ result = anchors.resolve(policy, systems, ranking.AXES_BY_TIER)
+ point = result["points"][anchors.row_key("babble@+4", "spk_sim")]
+ assert point["floor"] == 0 and point["fallbacks"] == ["floor"]
+ del systems["REF"]["babble@+4"]["spk_sim"]
+ with pytest.raises(ValueError, match="missing measured anchor"):
+ anchors.resolve(policy, systems, ranking.AXES_BY_TIER)
+
+
+def test_declared_endpoints_are_verified_against_the_set_and_never_moved_by_it(
+):
+ policy, systems = anchors.definitions(), anchor_rows.scores()
+ base = anchors.resolve(policy, systems, ranking.AXES_BY_TIER)
+ key = anchors.row_key("babble@+4", "nisqa_mos")
+ declared = next(
+ r for r in policy["rules"]
+ if "nisqa_mos" in r["metrics"] and "babble@+4" in r["conditions"])
+ assert base["points"][key]["floor"] == declared["floor"]["value"]
+ tolerance = declared["floor"]["verify"]["tolerance"]
+ systems["INPUT"]["babble@+4"]["nisqa_mos"] += (
+ 0.9 * tolerance) # a build whose input differs a little
+ moved = anchors.resolve(policy, systems, ranking.AXES_BY_TIER)
+ # the scale does not follow the set
+ assert moved["points"] == base["points"]
+ systems["INPUT"]["babble@+4"]["nisqa_mos"] += (
+ 0.2 * tolerance) # past the tolerance: a stale policy
+ with pytest.raises(ValueError, match="declare a new anchor version"):
+ anchors.resolve(policy, systems, ranking.AXES_BY_TIER)
+ # a verified endpoint still needs its measurement
+ del systems["REF"]["babble@+4"]["nisqa_mos"]
+ systems["INPUT"]["babble@+4"]["nisqa_mos"] = declared["floor"]["value"]
+ with pytest.raises(ValueError, match="missing measured anchor"):
+ anchors.resolve(policy, systems, ranking.AXES_BY_TIER)
+
+
+def test_reference_conditions_cover_measured_and_verified_endpoints(tmp_path):
+ """The REF row is scored wherever the policy reads it.
+
+ As a measured endpoint or as the check on a declared one. A policy that only
+ declares values still needs REF for its verification.
+ """
+ assert ("babble@+4" in anchors.reference_conditions()
+ ) # shipped policy: declared, verified against REF
+ measured = _measured_policy()
+ declared = copy.deepcopy(anchors.definitions())
+ for rule in declared["rules"]:
+ for side in ("floor", "ceiling"):
+ if (rule[side].get("verify") or {}).get("source") == "REF":
+ del rule[side]["verify"]
+ for name, policy, expected in (
+ ("measured", measured, True),
+ ("declared", declared, False),
+ ):
+ path = tmp_path / f"{name}.json"
+ path.write_text(json.dumps(policy))
+ assert ("babble@+4" in anchors.reference_conditions(path)) is expected
+ assert anchors.reference_conditions(tmp_path / "declared.json") == set()
+
+
+def test_verify_and_range_declarations_are_validated(tmp_path):
+ policy = anchors.definitions()
+ assert all("source" not in side
+ for r in policy["rules"]
+ for side in (r["floor"], r["ceiling"]))
+
+ def broken(edit):
+ bad = copy.deepcopy(policy)
+ edit(
+ next(r for r in bad["rules"] if "nisqa_mos" in r["metrics"] and
+ "babble@+4" in r["conditions"]))
+ path = tmp_path / "bad.json"
+ path.write_text(json.dumps(bad))
+ with pytest.raises(ValueError):
+ anchors.definitions(path)
+
+ # a range that excludes the declared value
+ broken(lambda r: r["floor"].update(range=[3, 4]))
+ broken(lambda r: r["floor"].update(verify={
+ "source": "BEST",
+ "tolerance": 0.1
+ }))
+ broken(lambda r: r["floor"].update(verify={
+ "source": "INPUT",
+ "tolerance": 0
+ }))
+ broken(lambda r: r["floor"].update(range=[1, float("inf")]))
+
+
+def test_migration_restamps_scores_and_item_headers_and_drops_old_calibration(
+ tmp_path,):
+ policy = anchors.definitions()
+ # versions the live policy never carries, so the test holds at any version
+ old, other = "test-previous", "test-other"
+ previous = dict(_anchors_version=old, _anchors_sha256="old")
+ (tmp_path / "a.metrics.json").write_text(
+ json.dumps({
+ "clean": {
+ "si_sdr": 30.0
+ },
+ **previous
+ }))
+ # a missing measurement survives the re-stamp
+ (tmp_path / "b.nisqa.json").write_text(
+ json.dumps({
+ "clean": {
+ "nisqa_mos": float("nan")
+ },
+ **previous
+ }, indent=1))
+ (tmp_path / "a.nisqa.json").write_text(
+ json.dumps({
+ "x": 1,
+ "_anchors_version": other,
+ "_anchors_sha256": "older"
+ }))
+ (tmp_path / "a.meta.json").write_text(json.dumps({"mechanism": "m"}))
+ (tmp_path / "a.items.jsonl").write_text(
+ json.dumps({
+ "anchors_version": old,
+ "anchors_sha256": "old",
+ "n_expected": 1
+ }) + "\n" + json.dumps({
+ "id": "x.wav",
+ "measurements": {
+ "si_sdr": 30.0
+ }
+ }) + "\n")
+ (tmp_path / anchors.RESOLVED).write_text(
+ json.dumps({"anchors_version": old}))
+
+ migrated = anchors.migrate(tmp_path, old, policy)
+ migrated_again = anchors.migrate(tmp_path, old, policy)
+
+ assert migrated == 3
+ assert migrated_again == 0 # idempotent
+ kept = (tmp_path / "b.nisqa.json").read_text()
+ assert math.isnan(json.loads(kept)["clean"]["nisqa_mos"])
+ assert kept.startswith('{\n "clean"')
+ m = json.loads((tmp_path / "a.metrics.json").read_text())
+ assert m["_anchors_version"] == policy["version"]
+ assert m["_anchors_sha256"] == anchors.digest(policy)
+ assert m["_anchors_migrated_from"] == [old] and m["clean"] == {
+ "si_sdr": 30.0
+ } # raw values untouched
+ # another version: left
+ nisqa = json.loads((tmp_path / "a.nisqa.json").read_text())
+ assert nisqa["_anchors_version"] == other
+ assert "_anchors_version" not in json.loads(
+ (tmp_path / "a.meta.json").read_text())
+ head, row = (tmp_path / "a.items.jsonl").read_text().splitlines()
+ assert json.loads(head)["anchors_version"] == policy["version"]
+ assert (json.loads(head)["anchors_migrated_from"] == [old] and
+ json.loads(row)["id"] == "x.wav")
+ assert not (tmp_path / anchors.RESOLVED).exists()
+
+
+def test_input_and_ref_must_share_their_scorers_but_ref_has_no_deletion_sidecar(
+ composite_case, tmp_path):
+ scores, _, _ = composite_case(tmp_path)
+ scores["INPUT"]["_scorers"] = {
+ "metrics": "m1",
+ "nisqa": "n1",
+ "realx": "r1"
+ }
+ # the clean references hold no real recording, so no deletion sidecar
+ scores["REF"]["_scorers"] = {"metrics": "m1", "nisqa": "n1"}
+ resolved = anchors.resolve(anchors.definitions(), scores,
+ ranking.AXES_BY_TIER)
+ assert resolved["scorers"] == scores["INPUT"]["_scorers"]
+ scores["REF"]["_scorers"] = {"metrics": "m2", "nisqa": "n1"}
+ with pytest.raises(ValueError,
+ match=r"different implementations \(metrics\)"):
+ anchors.resolve(anchors.definitions(), scores, ranking.AXES_BY_TIER)
+
+
+def test_private_scores_force_private_calibration_without_a_cli_flag(
+ composite_case, tmp_path):
+
+ scores, _, _ = composite_case(tmp_path)
+ scores["INPUT"]["_sealed"] = True
+ scores["REF"]["_sealed"] = True
+ resolved = anchors.resolve(anchors.definitions(), scores,
+ ranking.AXES_BY_TIER)
+ assert resolved["sealed"] is True
+ scores["REF"]["_sealed"] = False
+ with pytest.raises(ValueError, match="private/public scope"):
+ anchors.resolve(anchors.definitions(), scores, ranking.AXES_BY_TIER)
+
+
+def test_a_panel_inherits_the_whole_set_verification_instead_of_repeating_it():
+ policy, systems = anchors.definitions(), anchor_rows.scores()
+ parent = anchors.resolve(policy, systems, ranking.AXES_BY_TIER)
+ panel = copy.deepcopy(systems)
+ for data in panel.values():
+ data["_subset"] = "gate"
+ declared = next(
+ r for r in policy["rules"]
+ if "nisqa_mos" in r["metrics"] and "babble@+4" in r["conditions"])
+ # a mean over the panel's 24 items sits further from the declared value than
+ # the set-wide tolerance allows: sampling, not a stale policy
+ panel["INPUT"]["babble@+4"]["nisqa_mos"] += (
+ 2 * declared["floor"]["verify"]["tolerance"])
+ with pytest.raises(ValueError, match="declare a new anchor version"):
+ anchors.resolve(policy, panel, ranking.AXES_BY_TIER)
+ cal = anchors.resolve(policy, panel, ranking.AXES_BY_TIER, parent=parent)
+ assert cal["points"] == parent["points"] and cal["subset"] == "gate"
+ assert cal["inherits"] == parent["calibration_sha256"]
+ assert cal["calibration_sha256"] == anchors.digest({
+ k: v for k, v in cal.items() if k != "calibration_sha256"
+ })
+ # only the whole-set calibration of the same build, policy and scope can be
+ # inherited
+ for other in (
+ dict(parent, set_id="another"),
+ dict(parent, sealed=True),
+ cal,
+ ):
+ with pytest.raises(ValueError, match="inherits only"):
+ anchors.resolve(policy, panel, ranking.AXES_BY_TIER, parent=other)
+
+
+def test_the_composite_is_the_mean_of_its_parts_or_of_its_axes():
+ scores = {
+ "suppression": 0.6,
+ "music": 0.9,
+ "room": 0.0,
+ "preservation": 0.8,
+ "quality": 0.4,
+ }
+ assert anchors.composite(scores, None) == pytest.approx(0.54)
+ members = {
+ "removes": ["suppression", "music", "room"],
+ "keeps": ["preservation"],
+ "sounds": ["quality"],
+ }
+ assert anchors.composite(scores, members) == pytest.approx(
+ (0.5 + 0.8 + 0.4) / 3)
+ assert anchors.part_scores(scores, members) == pytest.approx({
+ "removes": 0.5,
+ "keeps": 0.8,
+ "sounds": 0.4
+ })
+ # an added removal axis takes nothing from what is kept
+ wider = dict(scores, tones=0.5)
+ more = dict(members, removes=members["removes"] + ["tones"])
+ assert anchors.composite(wider, more) == pytest.approx(
+ (0.5 + 0.8 + 0.4) / 3)
+ assert math.isnan(
+ anchors.composite(dict(scores, room=float("nan")), members))
+ assert math.isnan(anchors.composite({}, members))
+ # an axis beside the composite is present but not read
+ aside = {
+ "removes": ["suppression", "music"],
+ "keeps": ["preservation"],
+ "sounds": ["quality"],
+ }
+ assert anchors.composite(scores, aside, ("room",)) == pytest.approx(
+ (0.75 + 0.8 + 0.4) / 3)
+ assert anchors.composite(dict(scores, room=0.9), aside,
+ ("room",)) == pytest.approx((0.75 + 0.8 + 0.4) / 3)
+ room_aside = anchors.composite({"room": 0.9}, None, ("room",))
+ assert room_aside != anchors.composite({"room": 0.9}, None, ())
+ assert math.isnan(anchors.composite({"room": 0.9}, None, ("room",)))
+ assert math.isnan(
+ anchors.composite(dict(scores, room=float("nan")), aside, ("room",)))
+ parts = anchors.part_scores(dict(scores, room=float("nan")), members)
+ assert math.isnan(parts["removes"])
+ with pytest.raises(ValueError, match="parts"):
+ anchors.composite(scores, {"removes": ["suppression"]})
diff --git a/tests/bench/scripts/test_anchorsweep.py b/tests/bench/scripts/test_anchorsweep.py
new file mode 100644
index 0000000..6dd71aa
--- /dev/null
+++ b/tests/bench/scripts/test_anchorsweep.py
@@ -0,0 +1,194 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The anchor sensitivity sweep on synthetic systems.
+
+The systems' dependence on one constant is known.
+"""
+
+import copy
+
+import pytest
+
+import anchor_rows
+import anchors
+import anchorsweep
+import ranking
+
+
+def _case():
+ """Returns two ranked systems that differ on clean passthrough only.
+
+ ``keeper`` returns the recording, ``rewriter`` audibly harms it, and
+ ``rewriter`` is a little better everywhere else.
+ """
+ policy, scores = anchors.definitions(), anchor_rows.scores()
+ systems = {k: scores[k] for k in ("INPUT", "REF")}
+ systems["keeper"] = copy.deepcopy(scores["a"])
+ systems["rewriter"] = copy.deepcopy(scores["c"])
+ systems["keeper"]["clean"].update(
+ kept_coh_p10=0.0,
+ _level_err=0.0,
+ _hf_err=0.05,
+ spk_sim=1.0,
+ nisqa_mos=4.5,
+ )
+ systems["rewriter"]["clean"].update(
+ kept_coh_p10=-7.0,
+ _level_err=4.0,
+ _hf_err=2.0,
+ spk_sim=0.96,
+ nisqa_mos=4.1,
+ )
+ tiers = {
+ "keeper": ("full", "Keeper"),
+ "rewriter": ("full", "Rewriter"),
+ "INPUT": ("ref", "in"),
+ "REF": ("ref", "ref"),
+ }
+ calibration = anchors.resolve(policy, systems, ranking.AXES_BY_TIER)
+ return policy, systems, tiers, calibration
+
+
+def test_ranged_lists_every_declared_constant_with_a_range_and_nothing_else():
+ policy = anchors.definitions()
+ knobs = anchorsweep.ranged(policy)
+ assert knobs and all(low <= policy["rules"][i][side]["value"] <= high
+ for i, side, low, high, _ in knobs)
+ ranged_count = sum(1 for r in policy["rules"] for s in ("floor", "ceiling")
+ if "range" in r[s])
+ assert len(knobs) == ranged_count
+ # zero by definition: no range
+ assert not any("babble_supp_db floor" in label for *_, label in knobs)
+
+
+def test_with_constants_moves_only_the_named_rows_and_refuses_crossed_endpoints(
+):
+ policy, _, _, calibration = _case()
+ i = next(k for k, r in enumerate(policy["rules"])
+ if r["conditions"] == ["clean"] and "_level_err" in r["metrics"])
+ cal = anchorsweep.with_constants(calibration, policy, {(i, "floor"): 8.0})
+ key = anchors.row_key("clean", "_level_err")
+ assert (cal["points"][key]["floor"] == 8.0 and
+ calibration["points"][key]["floor"] == 6.0)
+ other = anchors.row_key("babble@+4", "nisqa_mos")
+ assert cal["points"][other] == calibration["points"][other]
+ with pytest.raises(ValueError, match="cross"):
+ # under the ceiling of 1 dB
+ anchorsweep.with_constants(calibration, policy, {(i, "floor"): 0.5})
+
+
+def test_the_sweep_finds_the_constant_the_order_depends_on():
+ policy, systems, tiers, calibration = _case()
+ report = anchorsweep.sweep(systems,
+ tiers,
+ calibration,
+ policy,
+ draws=300,
+ seed=1)
+ base = report["joint"]
+ assert set(base) == {"keeper", "rewriter"}
+ assert (report["joint"]["keeper"]["p05"] <= base["keeper"]["declared"] <=
+ report["joint"]["keeper"]["p95"])
+ keeper_first = base["keeper"]["first_fraction"]
+ rewriter_first = base["rewriter"]["first_fraction"]
+ assert keeper_first + rewriter_first == pytest.approx(1.0)
+ clean = [r for r in report["single"] if r["constant"].startswith("clean ")]
+ # every clean constant bites
+ assert len(clean) >= 5 and all(r["max_shift"] > 0 for r in clean)
+ floor = next(
+ r for r in clean if r["constant"] == "clean kept_coh_p10 floor")
+
+ # a lower floor forgives the rewriter's deleted quiet voice, a higher one
+ # punishes it
+ def gap(e):
+ return e["composites"]["keeper"] - e["composites"]["rewriter"]
+
+ assert gap(floor["ends"]["high"]) > gap(floor["ends"]["low"])
+ pair = report["pairs"]["keeper"]["rewriter"]
+ assert (0.0 <= pair["above_fraction"] <= 1.0 and
+ 0.0 <= pair["tie_fraction"] <= 1.0)
+ mirror = report["pairs"]["rewriter"]["keeper"]
+ assert mirror["above_fraction"] == pytest.approx(1 - pair["above_fraction"])
+
+
+def test_the_sweep_is_seeded_and_leaves_its_inputs_alone():
+ policy, systems, tiers, calibration = _case()
+ before = copy.deepcopy(calibration)
+ a = anchorsweep.sweep(systems, tiers, calibration, policy, draws=50, seed=3)
+ b = anchorsweep.sweep(systems, tiers, calibration, policy, draws=50, seed=3)
+ c = anchorsweep.sweep(systems, tiers, calibration, policy, draws=50, seed=4)
+ assert a["joint"] == b["joint"] and a["joint"] != c["joint"]
+ assert calibration == before
+
+
+def test_markdown_reports_the_joint_table_and_the_order_changing_constants():
+ policy, systems, tiers, calibration = _case()
+ report = anchorsweep.sweep(systems,
+ tiers,
+ calibration,
+ policy,
+ draws=50,
+ seed=0)
+ md = anchorsweep.markdown(report, label=lambda n: n)
+ assert "| system | declared | 5th to 95th percentile | ranked first |" in md
+ assert md.count("\n| keeper |") + md.count("\n| rewriter |") == 2
+ assert "Single constants whose range alone reverses a pair" in md
+ quiet = copy.deepcopy(report)
+ for r in quiet["single"]:
+ for e in r["ends"].values():
+ e["order_changed"] = False
+ quiet_md = anchorsweep.markdown(quiet, label=lambda n: n)
+ assert "None: no single constant" in quiet_md
+ ends = [e for r in report["single"] for e in r["ends"].values()]
+ assert all(e["order_changed"] == bool(e["reversed_pairs"]) for e in ends)
+
+
+def test_axis_sensitivity_names_the_axis_a_lead_rests_on():
+ policy, systems, tiers, calibration = _case()
+ ax = anchorsweep.axis_sensitivity(systems,
+ tiers,
+ calibration,
+ draws=400,
+ seed=2)
+ board = ranking.BOARDS[ranking.ranking_board()] if ranking.BOARDS else list(
+ ranking.PARTS or {})
+ inside = {
+ a for part in board for a in ranking.PARTS[part]
+ if a not in ranking.OUTSIDE
+ }
+ # an axis beside the composite, or on the other board, has no weight to
+ # relax: the report describes the score that orders the table
+ assert set(ax["leave_one_out"]) == inside
+ assert set(ax["axis_scores"]["keeper"]) == inside
+ with_fidelity = ax["leave_one_out"]["music"]["composites"]
+ without = ax["leave_one_out"]["fidelity"]["composites"]
+ # the keeper's only advantage is clean passthrough: leaving fidelity out can
+ # only hurt it
+ assert (without["keeper"] -
+ without["rewriter"]) < (with_fidelity["keeper"] -
+ with_fidelity["rewriter"])
+ assert ax["leave_one_out"]["fidelity"]["order"][0] == "rewriter"
+ fractions = ax["random_weights_first_fraction"]
+ assert (sum(fractions.values()) == pytest.approx(1.0) and
+ 0 < fractions["keeper"] < 1)
+ report = anchorsweep.sweep(systems,
+ tiers,
+ calibration,
+ policy,
+ draws=20,
+ seed=0)
+ report["axes"] = ax
+ md = anchorsweep.markdown(report, label=lambda n: n)
+ assert ("| axis left out | order |" in md and
+ "ranked first under random axis weights" in md)
diff --git a/tests/bench/scripts/test_asrtable.py b/tests/bench/scripts/test_asrtable.py
new file mode 100644
index 0000000..ed0fa07
--- /dev/null
+++ b/tests/bench/scripts/test_asrtable.py
@@ -0,0 +1,263 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The downstream-ASR table from synthetic sidecars."""
+
+import json
+import math
+import os
+
+import pytest
+
+import asrtable
+
+
+def _block(wer, n=10):
+ return {"wer_pct": wer, "ci95": [wer - 1.0, wer + 1.0], "n": n, "items": {}}
+
+
+def _sidecar(results, system, tag, conds, set_id="s1", **extra):
+ doc = {
+ "_system": system,
+ "_set_id": set_id,
+ "_scorer_sha256": "scorer",
+ "_selection": {
+ "conds": ",".join(conds),
+ "limit": 0
+ },
+ "_outputs": {
+ f"{c}.wav": f"{system}-{c}" for c in conds
+ },
+ "asr": {
+ tag: {
+ "identity": {
+ "model": tag
+ },
+ "conditions": {
+ c: _block(w) for c, w in conds.items()
+ },
+ }
+ },
+ }
+ doc.update(extra)
+ json.dump(
+ doc,
+ open(os.path.join(results, f"{system}.asr.json"), "w",
+ encoding="utf-8"))
+
+
+def test_load_collects_one_recogniser_and_refuses_mixed_builds(tmp_path):
+ _sidecar(tmp_path, "INPUT", "large-v3", {"clean": 0.0, "babble@-10": 40.0})
+ _sidecar(
+ tmp_path,
+ "voice_isolator_v0",
+ "large-v3",
+ {
+ "clean": 0.5,
+ "babble@-10": 20.0
+ },
+ )
+ # another recogniser: not in this view
+ _sidecar(tmp_path, "other", "small", {"clean": 1.0})
+ scores = asrtable.load(str(tmp_path), "large-v3")
+ assert set(scores) == {"INPUT", "voice_isolator_v0"}
+ _sidecar(tmp_path, "stale", "large-v3", {"clean": 9.0}, set_id="s0")
+ with pytest.raises(SystemExit):
+ asrtable.load(str(tmp_path), "large-v3")
+
+
+def test_table_marks_the_best_and_the_relative_change():
+ scores = {
+ "INPUT": {
+ "clean": _block(0.0),
+ "babble@-10": _block(40.0)
+ },
+ "voice_isolator_v0": {
+ "clean": _block(0.5),
+ "babble@-10": _block(20.0)
+ },
+ "reuse": {
+ "babble@-10": _block(25.0)
+ },
+ }
+ md = asrtable.table(
+ scores,
+ ["voice_isolator_v0", "reuse"],
+ "voice_isolator_v0",
+ "large-v3",
+ label=lambda n: n,
+ )
+ lines = md.splitlines()
+ assert lines[2].startswith(
+ "| condition | unprocessed input | voice_isolator_v0 | reuse |"
+ " voice_isolator_v0 vs input |")
+ row = [l for l in lines if l.startswith("| `babble@-10`")][0]
+ assert ("**20.0 ± 1.0**" in row and "40.0 ± 1.0" in row and
+ row.rstrip().endswith("| -50 % |"))
+ clean = [l for l in lines if l.startswith("| `clean`")][0]
+ # no change against zero
+ assert "**0.0 ± 1.0**" in clean and clean.rstrip().endswith("| - |")
+ assert "| - |" in clean or "| - " in clean # reuse has no clean row: a dash
+ assert math.isnan(asrtable.relative_change(None, _block(1.0)))
+ assert asrtable.relative_change(_block(30.0),
+ _block(40.0)) == pytest.approx(-25.0)
+
+
+def test_cell_without_interval_shows_the_rate_alone():
+ b = {"wer_pct": 12.34, "ci95": [float("nan"), float("nan")]}
+ assert asrtable.cell(b) == "12.3" and asrtable.cell(None) == "-"
+
+
+def test_reference_phrase_says_what_the_transcripts_were_scored_against():
+ golden = {
+ "clean": {
+ "reference_tiers": {
+ "corpus-verified": 6,
+ "recognisers-agree": 3
+ }
+ }
+ }
+ mixed = {
+ "clean": {
+ "reference_tiers": {
+ "corpus-verified": 6
+ }
+ },
+ "wild@-5": {
+ "reference_tiers": {
+ "recognisers-agree": 2,
+ asrtable.FALLBACK_TIER: 2
+ }
+ },
+ }
+ fallback = {"clean": {"reference_tiers": {asrtable.FALLBACK_TIER: 4}}}
+ assert asrtable.reference_phrase(golden) == "the set's golden transcripts"
+ assert "8 of 10 items" in asrtable.reference_phrase(
+ mixed) and "other 2" in asrtable.reference_phrase(mixed)
+ # no golden text anywhere: say so
+ for conditions in (fallback, {"clean": {}}, {}):
+ assert (asrtable.reference_phrase(conditions) ==
+ "the same recogniser's transcript of the clean reference")
+ scored = {c: _block(1.0) | tiers for c, tiers in mixed.items()}
+ md = asrtable.table({"INPUT": scored}, [], "x", "large-v3")
+ assert "golden transcripts (8 of 10 items" in md.splitlines()[0]
+
+
+def test_slices_keep_the_two_contracts_apart_and_pair_by_source():
+ rows, golden = [], {}
+ for cond in ("babble@+4", "babble@-5", "conversation@0"):
+ for i in range(6):
+ rid = f"{cond.replace('@', 'AT')}_{i:03d}.wav"
+ rows.append({
+ "id": rid,
+ "condition": cond,
+ "language": "en",
+ "clean_path": "x",
+ "provenance": {
+ "speech": f"s{i % 3}",
+ "corruptor": f"b{i % 2}",
+ },
+ })
+ scores = {}
+ for name, factor in (("INPUT", 4), ("voice_isolator_v0", 1), ("other", 2)):
+ scores[name] = {}
+ for cond in ("babble@+4", "babble@-5", "conversation@0"):
+ items = {
+ r["id"]: [factor * (1 + i % 2), 20]
+ for i, r in enumerate(rows)
+ if r["condition"] == cond
+ }
+ scores[name][cond] = {"items": items}
+ md = asrtable.slices(
+ {"large-v3": scores},
+ rows,
+ golden,
+ ["voice_isolator_v0", "other"],
+ "voice_isolator_v0",
+ min_items=6,
+ )
+ assert "| a conversation" not in asrtable.slices(
+ {"large-v3": scores},
+ rows,
+ golden,
+ ["other"],
+ "other",
+ # six items: under the floor, not
+ # shown
+ min_items=7,
+ )
+ lines = [
+ l for l in md.splitlines()
+ if l.startswith("| background") or l.startswith("| a conversation")
+ ]
+ assert len(lines) == 2 # one recogniser, English only: words
+ chatter, conversation = lines
+ # the babble ladder's items, the conversation's
+ assert "| 12 |" in chatter and "| 6 |" in conversation
+ assert "**7.5**" in chatter # the isolator: 1.5 edits per 20 tokens
+ # paired change against the input: 30.0 down to 7.5 points
+ assert "-22.5 [" in chatter
+ assert "conversation@0" not in chatter
+
+
+def test_load_refuses_partial_unbound_or_mixed_scorer_sidecars(tmp_path):
+ _sidecar(tmp_path, "INPUT", "large-v3", {"clean": 0.0})
+ asrtable.load(str(tmp_path), "large-v3")
+ _sidecar(
+ tmp_path,
+ "sys",
+ "large-v3",
+ {"clean": 1.0},
+ _selection={
+ "conds": "clean",
+ "limit": 5
+ },
+ )
+ with pytest.raises(SystemExit, match="--limit"):
+ asrtable.load(str(tmp_path), "large-v3")
+ _sidecar(tmp_path, "sys", "large-v3", {"clean": 1.0}, _outputs=None)
+ with pytest.raises(SystemExit, match="no audio identity"):
+ asrtable.load(str(tmp_path), "large-v3")
+ _sidecar(tmp_path,
+ "sys",
+ "large-v3", {"clean": 1.0},
+ _scorer_sha256="another")
+ with pytest.raises(SystemExit, match="different implementations"):
+ asrtable.load(str(tmp_path), "large-v3")
+
+
+def test_row_missing_items_or_on_other_items_reads_incomplete_and_never_best():
+ full = dict(_block(40.0), items={"a.wav": [4, 10], "b.wav": [4, 10]})
+ scores = {
+ "INPUT": {
+ "babble@-10": full
+ },
+ "voice_isolator_v0": {
+ "babble@-10": dict(full, wer_pct=30.0)
+ },
+ "reuse": {
+ "babble@-10": dict(full, wer_pct=10.0, items={"a.wav": [1, 10]})
+ },
+ "dfn3": {
+ "babble@-10": dict(full, wer_pct=5.0, n_missing=1)
+ },
+ }
+ md = asrtable.table(
+ scores,
+ ["voice_isolator_v0", "reuse", "dfn3"],
+ "voice_isolator_v0",
+ "large-v3",
+ )
+ row = next(l for l in md.splitlines() if l.startswith("| `babble@-10`"))
+ # the best of the complete rows
+ assert row.count("incomplete") == 2 and "**30.0" in row
diff --git a/tests/bench/scripts/test_common.py b/tests/bench/scripts/test_common.py
new file mode 100644
index 0000000..0178b26
--- /dev/null
+++ b/tests/bench/scripts/test_common.py
@@ -0,0 +1,608 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Metric primitives and shared helpers of the benchmark.
+
+The tests use synthetic signals and no models.
+"""
+
+# pylint: disable=protected-access,unused-argument
+
+import argparse
+import json
+import math
+import os
+
+import numpy as np
+import pytest
+import soundfile as sf
+import torch
+
+import common
+from inworld import voice_isolation
+
+SR = common.SR
+HALF_DB = 20 * math.log10(0.5) # -6.02 dB
+
+
+def speechlike(n, seed=0, level=0.1):
+ """Zero-mean noise under a slow amplitude envelope.
+
+ The envelope makes frame energies vary like speech.
+ """
+ g = torch.Generator().manual_seed(seed)
+ t = torch.linspace(0, 1, n)
+ env = 0.2 + 0.8 * (0.5 + 0.5 * torch.sin(2 * math.pi * 3 * t)).pow(2)
+ return torch.randn(n, generator=g) * env * level
+
+
+def white(n, seed=0, level=0.1):
+ return torch.randn(n, generator=torch.Generator().manual_seed(seed)) * level
+
+
+def delayed(ref, lag):
+ """ref delayed by lag samples (negative: advanced).
+
+ The result has the same length as ref and is zero-filled.
+ """
+ if lag >= 0:
+ return torch.cat([torch.zeros(lag), ref])[:len(ref)]
+ return torch.cat([ref[-lag:], torch.zeros(-lag)])
+
+
+def snr_db(signal, noise):
+ return float(10 * torch.log10(signal.pow(2).mean() / noise.pow(2).mean()))
+
+
+# Reference scorer implementations, retained to check the shared helpers.
+
+
+def _old_best_lag_fft(out, ref, max_lag=4800): # scorebench.py before the move
+ n = min(len(out), len(ref))
+ a, b = out[:n] - out[:n].mean(), ref[:n] - ref[:n].mean()
+ if float(a.abs().max()) < 1e-8 or float(b.abs().max()) < 1e-8:
+ return 0
+ size = 1 << int(np.ceil(np.log2(2 * n)))
+ cc = torch.fft.irfft(
+ torch.fft.rfft(a, size) * torch.fft.rfft(b, size).conj(), size)
+ cc = torch.cat([cc[-max_lag:], cc[:max_lag + 1]])
+ return int(cc.argmax()) - max_lag
+
+
+# a sidecar's own copy before the helpers moved here
+def _old_best_lag_conv(out, ref, max_lag=4800):
+ n = min(len(out), len(ref))
+ a, b = out[:n], ref[:n]
+ padded = torch.nn.functional.pad(a.view(1, 1, -1), (max_lag, max_lag))
+ c = torch.nn.functional.conv1d(padded, b.view(1, 1, -1)).view(-1)
+ return int(torch.argmax(c).item() - max_lag)
+
+
+def _old_apply_lag_cat(out, lag, n): # a sidecar's copy before the move
+ o = (out[lag:]
+ if lag > 0 else torch.cat([torch.zeros(-lag, dtype=out.dtype), out]))
+ return torch.nn.functional.pad(o, (0, max(0, n - len(o))))[:n]
+
+
+def _old_nb8k(x): # a sidecar's copy before the move
+ # pylint: disable-next=import-outside-toplevel
+ import torchaudio
+
+ y = torchaudio.functional.resample(x, common.SR, 16000)
+ return torchaudio.functional.resample(y, 16000, common.SR)[:len(x)]
+
+
+def test_alignment_undoes_a_flipped_sign_and_only_a_flipped_sign():
+ ref = white(SR, seed=21)
+ for lag in (0, 37, -20):
+ assert common.best_alignment(delayed(ref, lag), ref) == (lag, 1)
+ assert common.best_alignment(-delayed(ref, lag), ref) == (lag, -1)
+ t = torch.arange(SR) / SR
+ # strong negative lobes
+ voiced = torch.sin(2 * torch.pi * 120 * t) * torch.hann_window(SR)
+ assert common.best_alignment(voiced, voiced) == (0, 1)
+ # uncorrelated: never "flipped"
+ assert common.best_alignment(white(SR, seed=22), ref)[1] == 1
+ assert common.best_alignment(torch.zeros(SR), ref) == (0, 1)
+ assert common.best_lag(-delayed(ref, 37), ref) == 37
+
+
+def test_shared_alignment_helpers_match_the_scorers_previous_copies():
+ ref = white(SR, seed=11)
+ n = len(ref)
+ for lag in (0, 37, -20, 2400):
+ out = delayed(ref, lag)
+ assert common.best_lag(out, ref) == lag
+ assert _old_best_lag_fft(out, ref) == lag
+ assert _old_best_lag_conv(out, ref) == lag
+ back = common.apply_lag(out, lag, n)
+ assert torch.equal(back, _old_apply_lag_cat(out, lag, n))
+ m = abs(lag)
+ assert torch.allclose(back[m:n - m], ref[m:n - m])
+ x = white(SR, seed=12)
+ assert torch.allclose(common.nb8k(x), _old_nb8k(x))
+ assert common.MAX_LAG == 4800 and common.NB_RATE == 16000
+
+
+def test_best_lag_is_zero_for_silence_and_aligned_signals():
+ ref = speechlike(SR, seed=1)
+ assert common.best_lag(ref, ref) == 0
+ assert common.best_lag(torch.zeros(SR), ref) == 0
+ # a DC offset does not fool the mean-removed search
+ assert common.best_lag(ref + 0.3, ref) == 0
+
+
+def test_apply_lag_pads_or_trims_to_the_requested_length():
+ out = torch.arange(10.0)
+ assert torch.equal(common.apply_lag(out, 0, 12),
+ torch.cat([out, torch.zeros(2)]))
+ assert torch.equal(common.apply_lag(out, 3, 5), out[3:8])
+ assert torch.equal(common.apply_lag(out, -2, 5),
+ torch.tensor([0.0, 0.0, 0.0, 1.0, 2.0]))
+
+
+def test_nb8k_removes_everything_above_8_khz():
+ x = white(2 * SR, seed=3)
+ y = common.nb8k(x)
+ assert len(y) == len(x)
+ spec_x = torch.fft.rfft(x).abs().pow(2)
+ spec_y = torch.fft.rfft(y).abs().pow(2)
+ freqs = torch.fft.rfftfreq(len(x), 1 / SR)
+ hi, lo = freqs >= 9000, freqs <= 7000
+ assert float(spec_y[hi].sum() / spec_x[hi].sum()) < 1e-3 # > 30 dB down
+ # passband kept (< 0.5 dB droop)
+ passband = float(spec_y[lo].sum() / spec_x[lo].sum())
+ assert 0.9 < passband <= 1.01
+
+
+def test_mix_at_snr_realises_the_requested_snr_and_trims_to_common_length():
+ clean = speechlike(2 * SR, seed=1)
+ noise = white(3 * SR, seed=2, level=0.05)
+ for snr in (-5.0, 0.0, 10.0):
+ mix, ref = common.mix_at_snr(clean, noise, snr)
+ assert len(mix) == len(ref) == 2 * SR
+ assert torch.equal(ref, clean)
+ assert snr_db(ref, mix - ref) == pytest.approx(snr, abs=0.05)
+
+
+def test_si_sdr_scale_and_offset_invariant_ordered_by_noise_large_for_identity(
+):
+ ref = speechlike(SR, seed=2)
+ noise = white(SR, seed=3, level=0.1)
+ assert common.si_sdr(ref, ref) > 60
+ a, b, c = (common.si_sdr(ref + g * noise, ref) for g in (0.01, 0.1, 1.0))
+ assert a > b > c
+ scaled = 5 * (ref + 0.1 * noise)
+ assert common.si_sdr(scaled, ref) == pytest.approx(b, abs=1e-3)
+ shifted = ref + 0.1 * noise + 0.3
+ assert common.si_sdr(shifted, ref) == pytest.approx(b, abs=1e-3)
+
+
+def test_voice_kept_db_reads_a_gain_inside_active_frames():
+ clean = speechlike(2 * SR, seed=4)
+ assert common.voice_kept_db(clean, clean) == pytest.approx(0.0, abs=1e-6)
+ assert common.voice_kept_db(0.5 * clean, clean) == pytest.approx(HALF_DB,
+ abs=0.01)
+ quiet = (clean.reshape(-1, 960).pow(2).mean(1)
+ <= clean.reshape(-1, 960).pow(2).mean(1).median())
+ touched = clean.clone().reshape(-1, 960)
+ # damage confined to the frames below the median energy
+ touched[quiet] *= 0.1
+ assert common.voice_kept_db(touched.reshape(-1),
+ clean) == pytest.approx(0.0, abs=1e-6)
+
+
+def test_band_kept_db_reports_per_band_gain_and_invented_high_frequency():
+ assert (len(common.BANDS_HZ) == 7 and common.BANDS_HZ[0][0] == 0 and
+ common.BANDS_HZ[-1][1] == SR // 2)
+ assert all(common.BANDS_HZ[i][1] == common.BANDS_HZ[i + 1][0]
+ for i in range(len(common.BANDS_HZ) - 1))
+ ref = white(2 * SR, seed=5)
+ assert all(abs(v) < 1e-6 for v in common.band_kept_db(ref, ref))
+ assert all(v == pytest.approx(HALF_DB, abs=0.05)
+ for v in common.band_kept_db(0.5 * ref, ref))
+ t = torch.arange(2 * SR) / SR
+ invented = common.band_kept_db(
+ ref + 0.3 * torch.sin(2 * math.pi * 20000 * t), ref)
+ assert invented[-1] > 6 and all(abs(v) < 0.5 for v in invented[:-1])
+ dulled = common.band_kept_db(common.nb8k(ref), ref)
+ assert dulled[-1] < -30 and abs(dulled[0]) < 0.5
+
+
+def test_tercile_kept_db_gain_nans_and_explicit_mask():
+ ref = speechlike(2 * SR, seed=6) # 100 frames of 960 samples
+ assert all(v == pytest.approx(0.0, abs=1e-6)
+ for v in common.tercile_kept_db(ref, ref))
+ assert all(v == pytest.approx(HALF_DB, abs=0.02)
+ for v in common.tercile_kept_db(0.5 * ref, ref))
+ # under one frame
+ assert all(
+ math.isnan(v) for v in common.tercile_kept_db(ref[:500], ref[:500]))
+ # < 9 frames
+ assert all(
+ math.isnan(v)
+ for v in common.tercile_kept_db(ref[:960 * 5], ref[:960 * 5]))
+ act = torch.zeros(100, dtype=torch.bool)
+ act[:30] = True
+ out = ref.clone()
+ # destroyed outside the mask: invisible when the mask says so
+ out[30 * 960:] = 0
+ assert all(v == pytest.approx(0.0, abs=1e-6)
+ for v in common.tercile_kept_db(out, ref, act=act))
+ # without the mask every tercile mixes intact and destroyed frames: a
+ # mean-energy loss
+ assert all(v < -3 for v in common.tercile_kept_db(out, ref))
+
+
+def test_load48_resamples_to_48k_mono_float32_and_pads_or_trims(tmp_path):
+ n16 = 16000
+ mono = np.random.default_rng(0).standard_normal(n16)
+ stereo = np.stack([mono] * 2, 1).astype(np.float32)
+ p16 = str(tmp_path / "s16.wav")
+ sf.write(p16, 0.1 * stereo, 16000)
+ y = common.load48(p16)
+ assert (y.dtype == torch.float32 and y.ndim == 1 and
+ abs(len(y) - 3 * n16) <= 1)
+ assert len(common.load48(p16, secs=0.5)) == SR // 2
+ assert len(common.load48(p16, secs=2.0)) == 2 * SR
+ x48 = white(SR, seed=7)
+ p48 = str(tmp_path / "m48.wav")
+ sf.write(p48, x48.numpy(), SR, subtype="FLOAT")
+ assert torch.allclose(common.load48(p48), x48)
+
+
+def test_set_id_and_manifest_resolve_paths_under_the_set_root(tmp_path):
+ root = tmp_path / "set"
+ root.mkdir()
+ rows = [
+ {
+ "id": "a.wav",
+ "condition": "babble@+4",
+ "mix_path": "mix/a.wav",
+ "clean_path": "ref/a.wav",
+ },
+ {
+ "id": "r.wav",
+ "condition": "real_x",
+ "mix_path": "mix/r.wav",
+ "clean_path": None,
+ },
+ ]
+ with open(root / "manifest.jsonl", "w", encoding="utf-8") as fh:
+ fh.write(json.dumps(rows[0]) + "\n\n" + json.dumps(rows[1]) + "\n")
+ json.dump({
+ "set_id": "abc123",
+ "n_items": 2
+ }, open(root / "checksums.json", "w", encoding="utf-8"))
+ assert common.set_id(str(root)) == "abc123"
+ assert common.set_id(str(tmp_path / "nowhere")) is None
+ m = common.manifest(str(root))
+ assert [r["id"] for r in m] == ["a.wav", "r.wav"]
+ assert m[0]["mix_path"] == str(root / "mix" / "a.wav")
+ assert m[0]["clean_path"] == str(root / "ref" / "a.wav")
+ assert m[1]["clean_path"] is None
+
+
+def test_outputs_digest_reads_the_stamp_and_is_none_without_one(tmp_path):
+ json.dump({
+ "name": "sys",
+ "outputs_sha256": "ab" * 32
+ }, open(tmp_path / "sys.meta.json", "w", encoding="utf-8"))
+ json.dump({"name": "INPUT"},
+ open(tmp_path / "INPUT.meta.json", "w", encoding="utf-8"))
+ assert common.outputs_digest("sys", str(tmp_path)) == "ab" * 32
+ # the set's own mixtures, linked: nothing rendered, nothing to name
+ assert common.outputs_digest("INPUT", str(tmp_path)) is None
+ assert common.outputs_digest("unstamped", str(tmp_path)) is None
+
+
+def test_speaker_embedder_caches_reference_embeddings(tmp_path, monkeypatch):
+ calls = []
+
+ class _Model:
+
+ def __call__(self, x):
+ calls.append(x.shape)
+ return torch.ones(1, 4)
+
+ emb = common.SpeakerEmbedder.__new__(common.SpeakerEmbedder)
+ emb.m, emb.cache_dir, emb._mem = _Model(), str(tmp_path), {}
+ wav = torch.randn(common.SR)
+ a = emb.emb(wav, key="item.ref")
+ b = emb.emb(wav, key="item.ref") # memory hit
+ emb._mem.clear()
+ c = emb.emb(wav, key="item.ref") # disk hit
+ emb.emb(wav) # uncached call
+ assert len(calls) == 2 and torch.equal(a, b) and torch.equal(a, c)
+ assert (tmp_path / "item.ref.pt").exists()
+ assert emb.sim(wav, wav, key_b="item.ref") == pytest.approx(1.0)
+
+
+def _row(cond, idx, lang="en", paired=True, family=None):
+ r = {
+ "id": f"{cond.replace('@', 'AT').replace('+', 'p')}_{idx:03d}.wav",
+ "condition": cond,
+ "family": family or cond.split("@")[0].split("_")[0],
+ "language": lang,
+ }
+ if paired:
+ r["clean_path"] = f"ref/{r['id']}"
+ return r
+
+
+def test_subset_splits_the_multilingual_core_from_the_english_extension():
+ assert common.subset(_row("babble@+4", 7, "ta")) == "core"
+ # English share of the base draw
+ assert common.subset(_row("babble@+4", 23, "en")) == "core"
+ # added above the limit
+ assert common.subset(_row("babble@+4", 48, "en")) == "extension"
+ # a new level on the base utterances
+ assert common.subset(_row("babble@-5", 3, "de")) == "core"
+ # English-only family
+ assert common.subset(_row("stationary@-5", 3, "en")) == "extension"
+ # the softly spoken retention family
+ assert common.subset(_row("soft@+0", 3, "en")) == "extension"
+ # and the whispered one
+ assert common.subset(_row("whisper@+0", 3, "en")) == "extension"
+ assert (common.subset(
+ _row("nonverbal_clean", 3, "en",
+ family="nonverbal_clean")) == "extension")
+ assert (common.subset(_row("nonverbal@+0", 3, "en",
+ family="ambience")) == "extension")
+ # real: core throughout
+ assert common.subset(_row("real_multi", 90, "ko", paired=False)) == "core"
+ assert common.subset(_row("real_noisy", 60, "en", paired=False)) == "core"
+
+
+def test_manifest_filters_by_subset_from_the_argument_or_the_environment(
+ tmp_path, monkeypatch):
+ rows = [
+ _row("clean", 1, "fr"),
+ _row("clean", 50, "en"),
+ _row("traffic@+0", 1, "en"),
+ ]
+ with open(tmp_path / "manifest.jsonl", "w", encoding="utf-8") as fh:
+ for r in rows:
+ fh.write(json.dumps(r) + "\n")
+ ids = [r["id"] for r in common.manifest(str(tmp_path))]
+ assert ids == [r["id"] for r in rows]
+ core = [r["id"] for r in common.manifest(str(tmp_path), which="core")]
+ assert core == [rows[0]["id"]]
+ assert len(common.manifest(str(tmp_path), which="extension")) == 2
+ monkeypatch.setattr(common, "SUBSET", "core")
+ assert len(common.manifest(str(tmp_path))) == 1
+ assert common.manifest(str(tmp_path))[0]["clean_path"].startswith(
+ str(tmp_path))
+
+
+def test_coherent_kept_reads_zero_for_voice_and_very_negative_for_bed_alone():
+ g = torch.Generator().manual_seed(3)
+ n = 48000 * 2
+ voice = torch.sin(torch.linspace(0, 2 * math.pi * 220 * 2,
+ n)) * (torch.rand(n, generator=g) > 0.3)
+ # louder than the voice
+ bed = torch.randn(n, generator=g) * float(voice.pow(2).mean().sqrt()) * 1.8
+ assert abs(float(common.coherent_kept_db(voice, voice).mean())) < 0.01
+ # the voice is in there: ~0 dB
+ assert float(common.coherent_kept_db(voice + bed, voice).mean()) < 0.5
+ # a bed alone is not kept speech
+ assert float(common.coherent_kept_db(bed, voice).max()) < -20
+ kept = common.coherent_kept_db(0.1 * voice, voice)
+ assert float(kept.mean()) == pytest.approx(-20.0, abs=0.1)
+ # the energy ratio would have called it kept
+ assert float(common.voice_kept_db(bed, voice)) > 0
+
+
+def test_coherent_kept_follows_the_activity_mask_so_quiet_speech_counts():
+ n = 48000 * 2
+ voice = torch.sin(torch.linspace(0, 2 * math.pi * 200 * 2, n)) * 0.3
+ voice[n // 2:] *= 0.05 # the second half is quiet speech, 26 dB down
+ # a VAD that hears speech throughout
+ act16 = torch.ones(n // 3, dtype=torch.bool)
+ mask = common.block_mask(act16, n // 4800)
+ assert bool(mask.all())
+ gone = voice.clone()
+ gone[n // 2:] = 0 # the quiet half deleted
+ # seen with the mask
+ assert float(common.coherent_kept_db(gone, voice, act=mask).min()) < -60
+ faint = voice.clone()
+ # 66 dB down: under the 40 dB floor, so not measurable either way
+ faint[n // 2:] *= 0.01
+ gone2 = faint.clone()
+ gone2[n // 2:] = 0
+ assert float(common.coherent_kept_db(gone2, faint, act=mask).min()) > -1
+ kept = common.coherent_kept_db(voice, voice, act=mask)
+ assert abs(float(kept.min())) < 0.01
+ partial = torch.zeros(n // 3, dtype=torch.bool)
+ partial[:n // 6] = True
+ # half the blocks marked
+ assert common.block_mask(partial, n // 4800).sum() == n // 4800 // 2
+
+
+def test_coherent_blocks_split_the_voice_from_the_residual():
+ g = torch.Generator().manual_seed(7)
+ n = 48000 * 2
+ voice = torch.sin(torch.linspace(0, 2 * math.pi * 180 * 2, n)) * 0.3
+ # a bed 10 dB under the voice
+ bed = torch.randn(n, generator=g) * 0.3 * 10**(-10 / 20)
+ kept, resid, loud = common.coherent_blocks(0.5 * voice + bed, voice)
+ assert bool(loud.all()) and len(kept) == len(resid) == n // 4800
+ # the voice, halved
+ assert float(kept.mean()) == pytest.approx(20 * math.log10(0.5), abs=0.1)
+ bed_vs_voice = 10 * math.log10(
+ float(bed.pow(2).mean()) / float(voice.pow(2).mean()))
+ # the bed, as it is
+ assert float(resid.mean()) == pytest.approx(bed_vs_voice, abs=0.5)
+ k2, r2, _ = common.coherent_blocks(voice, voice)
+ # nothing but the voice
+ assert abs(float(k2.mean())) < 0.01 and float(r2.max()) < -70
+ empty = common.coherent_blocks(torch.zeros(100), torch.zeros(100))
+ assert all(len(t) == 0 for t in empty)
+ # one primitive
+ assert torch.equal(common.coherent_kept_db(0.5 * voice + bed, voice), kept)
+
+
+def test_pick_rows_by_name_prefix_pairing_and_limit():
+ rows = [
+ {
+ "id": "a",
+ "condition": "babble@+4",
+ "clean_path": "r/a"
+ },
+ {
+ "id": "b",
+ "condition": "babble@-5",
+ "clean_path": "r/b"
+ },
+ {
+ "id": "c",
+ "condition": "real_noisy",
+ "clean_path": None
+ },
+ {
+ "id": "d",
+ "condition": "real_wild",
+ "clean_path": None
+ },
+ ]
+
+ def ids(rs):
+ return [r["id"] for r in rs]
+
+ assert ids(common.pick_rows(rows, "babble@+4")) == ["a"]
+ assert ids(common.pick_rows(rows, "babble@+4,real_wild")) == ["a", "d"]
+ # a prefix when no exact name matches
+ assert ids(common.pick_rows(rows, "real")) == ["c", "d"]
+ assert ids(common.pick_rows(rows, "")) == ["a", "b", "c", "d"]
+ assert ids(common.pick_rows(rows, "", paired=True)) == ["a", "b"]
+ assert ids(common.pick_rows(rows, "", paired=False)) == ["c", "d"]
+ assert ids(common.pick_rows(rows, "", limit=3)) == ["a", "b", "c"]
+
+
+def test_model_tag_and_ops_path_stay_out_of_the_published_results():
+ assert common.model_tag("voice-isolator-v1") == "voice-isolator-v1"
+ assert common.model_tag("/x/y/export/model.safetensors") == "model"
+ assert common.model_tag("staging/sweeps/candidate_a.pt") == "candidate_a"
+ assert common.ops_path("m", "seams", "/tmp/x.json") == "/tmp/x.json"
+ p = common.ops_path("staging/a/b.safetensors", "seams")
+ assert (p.endswith(os.path.join("staging", "ops", "b.seams.json")) and
+ "results" not in p)
+
+
+def test_isolator_runner_routes_chunking_and_alpha(monkeypatch):
+ calls = []
+
+ class _Vi:
+ device = "cpu"
+
+ def isolate(self, x, sr, **kw):
+ calls.append(("isolate", sr, kw))
+ return x
+
+ def enhance(self, x, sr, alpha, **kw):
+ calls.append(("enhance", alpha, kw))
+ return x
+
+ seen = {}
+ monkeypatch.setattr(
+ voice_isolation.VoiceIsolator,
+ "load",
+ classmethod(lambda cls, m, **kw: seen.update(model=m, **kw) or _Vi()),
+ )
+ ap = argparse.ArgumentParser()
+ common.add_model_args(ap)
+ a = ap.parse_args([
+ "--model", "ckpt.pt", "--precision", "fp16", "--mode", "streaming",
+ "--lookahead", "2"
+ ])
+ _, run = common.isolator_runner(a)
+ assert seen == {
+ "model": "ckpt.pt",
+ "stage2": None,
+ "device": common.DEV,
+ "precision": "fp16",
+ "mode": "streaming",
+ "lookahead_frames": 2,
+ }
+ x = torch.zeros(10)
+ run(x, 4.0, 1.0)
+ assert calls[-1] == (
+ "isolate",
+ common.SR,
+ {
+ "output_sample_rate": common.SR,
+ "chunk_seconds": 4.0,
+ "overlap_seconds": 1.0,
+ },
+ )
+ a = ap.parse_args(["--alpha", "0.5"])
+ _, run = common.isolator_runner(a)
+ run(x)
+ assert calls[-1][:2] == ("enhance", 0.5)
+
+
+def test_the_voice_activity_detector_is_a_release_the_cohort_was_cut_with():
+ """The frozen deletion cohort counts the detector's usable segments.
+
+ silero-vad 6.2.3 segments two of the cohort's recordings differently from
+ 6.2.0 to 6.2.2, and a row whose counts differ from the cohort's is
+ incomplete; the ``eval`` extra pins the admissible releases and an
+ installed detector outside them must fail here rather than in a board.
+ """
+ pytest.importorskip("silero_vad")
+ # pylint: disable-next=import-outside-toplevel
+ import importlib.metadata
+ # pylint: disable-next=import-outside-toplevel
+ import re
+
+ # pylint: disable-next=import-outside-toplevel
+ from packaging import specifiers
+ repo = os.path.dirname(os.path.dirname(os.path.dirname(common.__file__)))
+ with open(os.path.join(repo, "pyproject.toml"), encoding="utf-8") as fh:
+ pin = re.search(r'^eval = \[.*"silero-vad([^"]*)".*\]', fh.read(), re.M)
+ assert pin, "the eval extra must pin silero-vad"
+ installed = importlib.metadata.version("silero-vad")
+ assert specifiers.SpecifierSet(pin.group(1)).contains(installed), (
+ f"silero-vad {installed} is installed; the cohort was cut with"
+ f" {pin.group(1)}")
+
+
+def test_alignment_of_a_clip_shorter_than_the_lag_window_reads_its_lag():
+ """A clip of at most 2048 samples read a lag of -4800 and aligned to
+ nothing; the lag window is capped at the clip's length."""
+ ref = white(2000, seed=3)
+
+ for lag in (0, 37):
+ out = delayed(ref, lag)
+ got, sign = common.best_alignment(out, ref)
+ aligned = common.apply_lag(out, got, len(ref))
+
+ assert (got, sign) == (lag, 1)
+ assert torch.allclose(aligned[:len(ref) - lag],
+ ref[:len(ref) - lag],
+ atol=1e-6)
+
+
+def test_the_private_results_guard_sees_through_a_symlinked_checkout(
+ tmp_path, monkeypatch):
+ repo = tmp_path / "checkout"
+ (repo / "bench" / "results").mkdir(parents=True)
+ link = tmp_path / "link"
+ link.symlink_to(repo)
+ monkeypatch.setattr(common, "REPO_DIR", str(link))
+ monkeypatch.setattr(common, "RESULTS", str(repo / "bench" / "results"))
+ monkeypatch.setattr(common, "OUT_ROOT", str(tmp_path / "out"))
+ monkeypatch.setattr(common, "is_sealed", lambda rows, root=None: True)
+
+ with pytest.raises(ValueError, match="private"):
+ common.guard_private_results([])
diff --git a/tests/bench/scripts/test_compare.py b/tests/bench/scripts/test_compare.py
new file mode 100644
index 0000000..574af49
--- /dev/null
+++ b/tests/bench/scripts/test_compare.py
@@ -0,0 +1,667 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Paired effects, source dependence, and nonlinear composite aggregation."""
+
+import copy
+import math
+
+import numpy as np
+import pytest
+
+import compare
+import scorefiles
+
+
+def dataset(shift=0):
+ rows = [{
+ "id": str(i),
+ "condition": "speech",
+ "language": "en",
+ "output_status": "ok",
+ "speech_source": f"source-{i // 3}",
+ "bed_source": f"bed-{i % 4}",
+ "groups_verified": True,
+ "metrics": {
+ "quality": i / 10 + shift
+ },
+ } for i in range(60)]
+ return {
+ "set_id": "same",
+ "subset": "all",
+ "anchors_version": "1",
+ "anchors_sha256": "same",
+ "scorer_sha256": "same",
+ "level_cal_db": 0,
+ }, rows
+
+
+def test_known_regression_and_null_have_expected_paired_intervals():
+ baseline, regression, null = dataset(), dataset(-1), dataset()
+ bad = compare.paired(regression, baseline, "speech", "quality", n_boot=200)
+ unchanged = compare.paired(null, baseline, "speech", "quality", n_boot=200)
+ assert bad["ci95"] == pytest.approx([-1, -1])
+ assert bad["excludes_zero"] and bad["cluster_counts"] == [20, 4]
+ assert unchanged["ci95"] == [0, 0] and not unchanged["excludes_zero"]
+
+
+def test_repeated_source_observations_do_not_create_fake_precision():
+ left, right = dataset(), dataset()
+ for i, row in enumerate(left[1]):
+ row["metrics"]["quality"] += (i // 3) / 10
+ before = compare.paired(left, right, "speech", "quality", n_boot=400)
+ for data in (left, right):
+ repeated = []
+ for record in data[1]:
+ for j in range(10):
+ repeated.append({**record, "id": f"{record['id']}-{j}"})
+ data[1][:] = repeated
+ after = compare.paired(left, right, "speech", "quality", n_boot=400)
+ assert before["ci95"] == pytest.approx(after["ci95"], abs=1e-12)
+
+
+def test_different_inventories_versions_and_source_groups_are_refused():
+ for mutation in ("inventory", "version", "group"):
+ left, right = dataset(), dataset()
+ if mutation == "inventory":
+ right[1].pop()
+ elif mutation == "version":
+ right[0]["anchors_version"] = "other"
+ else:
+ right[1][0]["bed_source"] = "other"
+ with pytest.raises(ValueError):
+ compare.paired(left, right, "speech", "quality", n_boot=100)
+
+
+def test_nonfinite_values_have_explicit_paired_coverage():
+ left, right = dataset(), dataset()
+ left[1][0]["metrics"]["quality"] = None
+ result = compare.paired(left, right, "speech", "quality", n_boot=100)
+ assert result["n_paired"] == 59 and result["n_expected"] == 60
+
+
+def test_single_source_cannot_claim_an_uncertainty_interval():
+ with pytest.raises(ValueError, match="independent"):
+ list(compare.weights([["one"] * 30, [None] * 30], 100))
+
+
+def test_clean_items_do_not_disappear_when_no_bed_is_sampled():
+ for weights in compare.weights(
+ [["a", "b", "c", "d"], [None, "x", "y", "z"]], 100):
+ assert weights.shape == (4,)
+
+
+def test_composite_matches_leaderboard_and_pools_deletion(
+ composite_case, tmp_path):
+ # pylint: disable-next=import-outside-toplevel
+ import ranking
+ case = composite_case(tmp_path)
+ scores, calibration, systems = case
+ _, expected, _ = ranking.rank(
+ copy.deepcopy(scores),
+ {n: ("full", n) for n in ("candidate", "baseline")},
+ calibration,
+ )
+ result = compare.composite_delta(
+ systems["candidate"],
+ systems["baseline"],
+ calibration,
+ ranking.AXES_FULL,
+ n_boot=100,
+ )
+ assert result["left"] == pytest.approx(expected["candidate"], abs=1e-12)
+ assert result["right"] == pytest.approx(expected["baseline"], abs=1e-12)
+ assert math.isfinite(result["delta"])
+
+
+def test_hf_error_is_the_mean_of_per_item_absolute_errors(
+ composite_case, tmp_path):
+ # pylint: disable-next=import-outside-toplevel
+ import ranking
+
+ scores, calibration, systems = composite_case(tmp_path)
+ for i, row in enumerate(
+ r for r in systems["candidate"][1] if r["condition"] == "clean"):
+ row["metrics"]["band_kept_db"] = [0] * 4 + [(-1)**i] * 3
+ scores["candidate"]["clean"]["_hf_err"] = 1.0 # opposite signs never cancel
+ _, expected, _ = ranking.rank(
+ copy.deepcopy(scores),
+ {n: ("full", n) for n in ("candidate", "baseline")},
+ calibration,
+ )
+ result = compare.composite_delta(
+ systems["candidate"],
+ systems["baseline"],
+ calibration,
+ ranking.AXES_FULL,
+ n_boot=100,
+ )
+ assert result["left"] == pytest.approx(expected["candidate"], abs=1e-12)
+
+
+def test_unused_diagnostics_do_not_enter_composite_uncertainty(
+ composite_case, tmp_path):
+ # pylint: disable-next=import-outside-toplevel
+ import ranking
+
+ _, calibration, systems = composite_case(tmp_path)
+ left = copy.deepcopy(systems["candidate"])
+ right = copy.deepcopy(systems["baseline"])
+ expected = compare.composite_delta(left,
+ right,
+ calibration,
+ ranking.AXES_FULL,
+ n_boot=100)
+ for _, rows in (left, right):
+ rows.append({
+ "id": "unused",
+ "condition": "long",
+ "language": "en",
+ "output_status": "ok",
+ "groups_verified": False,
+ "speech_source": "unknown",
+ "bed_source": None,
+ "metrics": {},
+ })
+ assert (compare.composite_delta(left,
+ right,
+ calibration,
+ ranking.AXES_FULL,
+ n_boot=100) == expected)
+
+
+def test_an_item_missing_a_high_band_is_left_out_as_on_the_board(
+ composite_case, tmp_path):
+ # pylint: disable-next=import-outside-toplevel
+ import levels
+ # pylint: disable-next=import-outside-toplevel
+ import ranking
+
+ scores, calibration, systems = composite_case(tmp_path)
+ for name in ("candidate", "baseline"):
+ clean = [r for r in systems[name][1] if r["condition"] == "clean"]
+ for i, row in enumerate(clean):
+ bands = row["metrics"]["band_kept_db"]
+ if i < 4:
+ bands[4] = None
+ bands[5] = 0.9
+ per_item = [
+ levels.hf_error_db(
+ [
+ float("nan") if v is None else v
+ for v in r["metrics"]["band_kept_db"]
+ ],
+ 0.0,
+ )
+ for r in clean
+ ]
+ scores[name]["clean"]["_hf_err"] = float(np.nanmean(per_item))
+ _, expected, _ = ranking.rank(
+ copy.deepcopy(scores),
+ {n: ("full", n) for n in ("candidate", "baseline")},
+ calibration,
+ )
+ result = compare.composite_delta(
+ systems["candidate"],
+ systems["baseline"],
+ calibration,
+ ranking.AXES_FULL,
+ n_boot=100,
+ )
+ assert result["left"] == pytest.approx(expected["candidate"], abs=1e-12)
+ assert result["right"] == pytest.approx(expected["baseline"], abs=1e-12)
+
+
+def test_a_saturated_level_calibration_has_no_composite_and_no_calibrated_pairs(
+ composite_case, saturate, tmp_path):
+ composite_case(tmp_path)
+ saturate(tmp_path, "candidate")
+ left = compare.load_system(tmp_path, "candidate")
+ right = compare.load_system(tmp_path, "baseline")
+ assert compare.level_saturated(12.0) and compare.level_saturated(-12.5)
+ assert not compare.level_saturated(11.9) and not compare.level_saturated(
+ None)
+ assert compare.saturated_systems(left[0], right[0]) == ["candidate"]
+ # pylint: disable-next=import-outside-toplevel
+ import anchors
+ # pylint: disable-next=import-outside-toplevel
+ import ranking
+
+ cal = anchors.load(tmp_path / anchors.RESOLVED, anchors.definitions())
+ with pytest.raises(ValueError, match="saturated"):
+ compare.composite_delta(left, right, cal, ranking.AXES_FULL)
+ with pytest.raises(ValueError, match="saturated"):
+ compare.paired(left, right, "babble@-10", "kept_coh_p10", +1)
+ # an uncalibrated metric of the same records stays comparable: the level
+ # does not enter it
+ rec = next(r for r in left[1] if any(
+ k not in compare.CALIBRATED and isinstance(v, (int, float))
+ for k, v in r["metrics"].items()))
+ metric = next(
+ k for k, v in rec["metrics"].items()
+ if k not in compare.CALIBRATED and isinstance(v, (int, float)))
+ assert math.isfinite(
+ compare.paired(left, right, rec["condition"], metric, +1)["delta"])
+
+
+def test_the_voice_outside_speech_is_pooled_over_blocks_as_on_the_board(
+ composite_case, tmp_path):
+ # pylint: disable-next=import-outside-toplevel
+ import ranking
+
+ scores, calibration, systems = composite_case(tmp_path)
+ for name in ("candidate", "baseline"):
+ rows = [r for r in systems[name][1] if r["condition"] == "nonverbal@+0"]
+ lost = total = 0
+ # long events and short ones: a mean of shares would differ
+ for i, row in enumerate(rows):
+ blocks = 1 + 3 * (i % 5)
+ gone = blocks if (name == "baseline" and i % 4 == 0) else (i % 2)
+ row["metrics"].update(
+ nv_blocks=blocks,
+ nv_lost=gone,
+ nv_lost_pct=100.0 * gone / blocks,
+ )
+ lost, total = lost + gone, total + blocks
+ scores[name]["nonverbal@+0"]["nv_lost_pct"] = 100.0 * lost / total
+ _, expected, _ = ranking.rank(
+ copy.deepcopy(scores),
+ {n: ("full", n) for n in ("candidate", "baseline")},
+ calibration,
+ )
+ result = compare.composite_delta(
+ systems["candidate"],
+ systems["baseline"],
+ calibration,
+ ranking.AXES_FULL,
+ n_boot=100,
+ )
+ assert result["left"] == pytest.approx(expected["candidate"], abs=1e-12)
+ assert result["right"] == pytest.approx(expected["baseline"], abs=1e-12)
+ # the blocks are the reference's: two systems that disagree on them were not
+ # scored alike
+ row = next(
+ r for r in systems["baseline"][1] if r["condition"] == "nonverbal@+0")
+ row["metrics"]["nv_blocks"] += 1
+ with pytest.raises(ValueError, match="pooled cohorts"):
+ compare.composite_delta(
+ systems["candidate"],
+ systems["baseline"],
+ calibration,
+ ranking.AXES_FULL,
+ n_boot=10,
+ )
+ del row["metrics"]["nv_blocks"]
+ with pytest.raises(ValueError, match="missing pooled counts"):
+ compare.composite_delta(
+ systems["candidate"],
+ systems["baseline"],
+ calibration,
+ ranking.AXES_FULL,
+ n_boot=10,
+ )
+
+
+def test_axis_subsets_read_their_plain_mean_and_the_whole_reads_the_parts(
+ composite_case, tmp_path):
+ # pylint: disable-next=import-outside-toplevel
+ import ranking
+
+ scores, calibration, systems = composite_case(tmp_path)
+ axis_scores, comp, _ = ranking.rank(
+ copy.deepcopy(scores),
+ {n: ("full", n) for n in ("candidate", "baseline")},
+ calibration,
+ )
+ pair = systems["candidate"], systems["baseline"]
+ whole = compare.composite_delta(*pair,
+ calibration,
+ ranking.AXES_FULL,
+ n_boot=100)
+ plain = compare.composite_delta(*pair,
+ calibration,
+ ranking.AXES_FULL,
+ n_boot=100,
+ parts=None)
+ one = compare.composite_delta(*pair,
+ calibration,
+ {"room": ranking.AXES_FULL["room"]},
+ n_boot=100)
+ assert compare.registry_parts() == (ranking.PARTS, ["band"])
+ # the board's own composite
+ assert whole["left"] == pytest.approx(comp["candidate"])
+ axes = axis_scores["candidate"]
+ # every axis, room too
+ assert plain["left"] == pytest.approx(sum(axes.values()) / len(axes))
+ # seven equal axes are another policy
+ assert plain["left"] != pytest.approx(whole["left"])
+ # one axis is no composite of parts
+ assert one["left"] == pytest.approx(axes["room"])
+
+
+def test_load_system_merges_the_kept_sidecar(composite_case, tmp_path):
+ # pylint: disable-next=import-outside-toplevel
+ import observations
+
+ composite_case(tmp_path)
+ metadata, rows = observations.read(tmp_path / "candidate.items.jsonl")
+ side = [
+ dict(r,
+ metrics={
+ "nv_blocks": 7,
+ "nv_lost": 1,
+ "nv_lost_pct": 100 / 7
+ },
+ measurements={"nv_kept_db": [-20.0] + [-1.0] * 6})
+ for r in rows
+ if r["condition"] == "nonverbal@+0"
+ ]
+ header = {
+ k: v for k, v in metadata.items() if k not in ("type", "schema_version")
+ }
+ observations.write(
+ tmp_path / "candidate.kept.items.jsonl",
+ side,
+ dict(header, scorer_sha256="kept", n_expected=len(side)),
+ )
+ loaded, merged = compare.load_system(tmp_path, "candidate")
+ assert loaded["sidecar_scorers"] == {"kept": "kept"}
+ picked = [r for r in merged if r["condition"] == "nonverbal@+0"]
+ assert picked and all(r["metrics"]["nv_blocks"] == 7 for r in picked)
+ assert compare.value(picked[0], "nv_lost_pct",
+ loaded) == pytest.approx(100 / 7)
+
+
+def test_lost_blocks_are_counted_again_at_the_base_scores_calibration(
+ composite_case, tmp_path):
+ """A lost-block count read at another gain never reaches a pairing."""
+ # pylint: disable-next=import-outside-toplevel
+ import observations
+
+ composite_case(tmp_path)
+ base = tmp_path / "candidate.items.jsonl"
+ metadata, rows = observations.read(base)
+ header = {
+ k: v for k, v in metadata.items() if k not in ("type", "schema_version")
+ }
+ nonverbal = [r for r in rows if r["condition"] == "nonverbal@+0"]
+ # the sidecar counted at 0 dB, where blocks 5 dB under the recording are
+ # kept; it stores none of them as lost
+ side = [
+ dict(r,
+ metrics={
+ "nv_blocks": 2,
+ "nv_lost": 0,
+ "nv_lost_pct": 0.0
+ },
+ measurements={"nv_kept_db": [-5.0, -5.0]}) for r in nonverbal
+ ]
+ observations.write(
+ tmp_path / "candidate.kept.items.jsonl",
+ side,
+ dict(header, scorer_sha256="kept", n_expected=len(side)),
+ )
+ # the base scores were made again and found a 6 dB gain: those blocks sit
+ # 11 dB under the recording once it is undone, so all of them are lost
+ observations.write(base, rows, dict(header, level_cal_db=6.0))
+ loaded, merged = compare.load_system(tmp_path, "candidate")
+ picked = [r for r in merged if r["condition"] == "nonverbal@+0"]
+ assert picked and all(r["metrics"]["nv_lost"] == 2 for r in picked)
+ assert compare.value(picked[0], "nv_lost_pct", loaded) == 100.0
+ # a record without its block levels cannot be counted again
+ del side[0]["measurements"]
+ observations.write(
+ tmp_path / "candidate.kept.items.jsonl",
+ side,
+ dict(header, scorer_sha256="kept", n_expected=len(side)),
+ )
+ with pytest.raises(ValueError, match="without its block levels"):
+ compare.load_system(tmp_path, "candidate")
+
+
+def test_a_sidecar_measured_on_other_audio_is_refused(composite_case, tmp_path):
+ # pylint: disable-next=import-outside-toplevel
+ import observations
+
+ composite_case(tmp_path)
+ metadata, rows = observations.read(tmp_path / "candidate.items.jsonl")
+ side = [
+ dict(r, metrics={"nisqa_mos": 3.0})
+ for r in rows
+ if r["condition"] == "babble@+4"
+ ]
+ header = {
+ k: v for k, v in metadata.items() if k not in ("type", "schema_version")
+ }
+ # a sidecar may add inputs of its own to the semantics (the segments it
+ # scored)
+ for r in side:
+ r["identity"] = dict(r["identity"],
+ semantics=dict(r["identity"]["semantics"],
+ segs="x"))
+ observations.write(
+ tmp_path / "candidate.nisqa.items.jsonl",
+ side,
+ dict(header, scorer_sha256="nisqa", n_expected=len(side)),
+ )
+ compare.load_system(tmp_path, "candidate")
+ # an earlier render of the same item is other audio
+ side[0]["identity"] = dict(side[0]["identity"], output="an earlier render")
+ observations.write(
+ tmp_path / "candidate.nisqa.items.jsonl",
+ side,
+ dict(header, scorer_sha256="nisqa", n_expected=len(side)),
+ )
+ with pytest.raises(ValueError, match="measured on other audio"):
+ compare.load_system(tmp_path, "candidate")
+ # a changed reference too, and a semantics field the base states differently
+ side[0]["identity"] = dict(rows[0]["identity"], ref="another reference")
+ with pytest.raises(ValueError, match="measured on other audio"):
+ compare.same_audio({rows[0]["id"]: rows[0]},
+ [dict(side[0], id=rows[0]["id"])], "x")
+ other = dict(
+ rows[0],
+ identity=dict(rows[0]["identity"], semantics={"condition": "clean"}),
+ )
+ with pytest.raises(ValueError, match="measured on other audio"):
+ compare.same_audio({rows[0]["id"]: rows[0]}, [other], "x")
+
+
+def test_the_band_row_is_derived_per_item_as_the_loader_derives_it():
+ record = {
+ "output_status": "ok",
+ "condition": "srsweep_8k",
+ "metrics": {
+ "band_kept_db": [1.0, 1.0, 1.0, 30.0, 21.0, 10.0, 0.0]
+ },
+ }
+ # the highest band above the input's less the mean inside: 30 - 1
+ assert compare.value(record, "band_added_db", {}) == pytest.approx(29.0)
+ assert math.isnan(
+ compare.value(dict(record, condition="clean"), "band_added_db", {}))
+
+
+def test_the_band_row_is_pooled_as_the_board_pools_it():
+ # the two systems' pooled per-band levels are the same, so the board reads
+ # the same band value for both: no difference, although every item's own
+ # maximum sits 15 dB higher on one side
+ left_meta, left = dataset()
+ right_meta, right = dataset()
+ for i, (a, b) in enumerate(zip(left, right)):
+ a["condition"] = b["condition"] = "srsweep_8k"
+ above = [30.0, 0.0, 0.0, 0.0] if i % 2 else [0.0, 30.0, 0.0, 0.0]
+ a["metrics"] = {"band_kept_db": [1.0, 1.0, 1.0] + above}
+ b["metrics"] = {"band_kept_db": [1.0, 1.0, 1.0, 15.0, 15.0, 0.0, 0.0]}
+ result = compare.paired((left_meta, left), (right_meta, right),
+ "srsweep_8k",
+ "band_added_db",
+ n_boot=200)
+ assert result["delta"] == pytest.approx(0.0)
+ assert result["n_paired"] == 60 and result["matched_cohort"]
+ # an item without its bands leaves both sides
+ left[0]["metrics"]["band_kept_db"][5] = float("nan")
+ result = compare.paired((left_meta, left), (right_meta, right),
+ "srsweep_8k",
+ "band_added_db",
+ n_boot=200)
+ assert result["n_paired"] == 59 and not result["matched_cohort"]
+
+
+def test_requested_axes_are_all_read(composite_case, tmp_path):
+ # pylint: disable-next=import-outside-toplevel
+ import ranking
+
+ scores, calibration, systems = composite_case(tmp_path)
+ axis_scores, _, _ = ranking.rank(
+ copy.deepcopy(scores),
+ {n: ("full", n) for n in ("candidate", "baseline")},
+ calibration,
+ )
+ pair = systems["candidate"], systems["baseline"]
+ axes = axis_scores["candidate"]
+ asked = {a: ranking.AXES_FULL[a] for a in ("preservation", "room")}
+ # one axis of each board: both are read, as the parts they belong to
+ two = compare.composite_delta(*pair, calibration, asked, n_boot=100)
+ assert two["left"] == pytest.approx(
+ (axes["preservation"] + axes["room"]) / 2)
+ # a custom grouping naming an axis that was not requested reads the
+ # requested ones
+ custom = compare.composite_delta(*pair,
+ calibration,
+ asked,
+ n_boot=100,
+ parts={
+ "keeps": ["preservation", "fidelity"],
+ "restores": ["room"],
+ })
+ assert custom["left"] == pytest.approx(two["left"])
+
+
+def _restorer(system):
+ """The system with the per-band levels of one that restores above every
+ band-limited input's band."""
+ out = copy.deepcopy(system)
+ for record in out[1]:
+ first = dict(scorefiles.BAND_LIMITED_ROWS).get(record["condition"])
+ if first is not None:
+ record["metrics"]["band_kept_db"] = ([0.0] * first + [40.0] *
+ (7 - first))
+ return out
+
+
+def test_the_compared_board_is_named_or_assigned_never_assumed(
+ composite_case, tmp_path):
+ # pylint: disable-next=import-outside-toplevel
+ import ranking
+
+ _, calibration, systems = composite_case(tmp_path)
+ whole = compare.composite_delta(systems["candidate"],
+ systems["baseline"],
+ calibration,
+ ranking.AXES_FULL,
+ n_boot=100)
+ # two denoisers: the whole registry reads the denoising board, and says so
+ assert whole["board"] == "denoising" and whole["delta"] > 0
+ # two restorers whose room falls to the input's while every other axis
+ # improves: the comparison reads the restoration board, and the loss
+ left, right = _restorer(systems["candidate"]), _restorer(
+ systems["baseline"])
+ floor = {r["id"]: r for r in systems["INPUT"][1]}
+ for record in left[1]:
+ if record["condition"] == "reverb_real":
+ for metric in ("spk_sim", "nisqa_mos"):
+ record["metrics"][metric] = floor[
+ record["id"]]["metrics"][metric]
+ lost = compare.composite_delta(left,
+ right,
+ calibration,
+ ranking.AXES_FULL,
+ n_boot=100)
+ assert lost["board"] == "restoration"
+ assert lost["delta"] < 0 and lost["ci95"][1] < 0
+ named = compare.composite_delta(left,
+ right,
+ calibration,
+ ranking.AXES_FULL,
+ n_boot=100,
+ board="denoising")
+ assert named["board"] == "denoising" and named["delta"] > 0
+ # a restorer against a denoiser: no board is assumed
+ with pytest.raises(ValueError, match="different boards"):
+ compare.composite_delta(left,
+ systems["baseline"],
+ calibration,
+ ranking.AXES_FULL,
+ n_boot=100)
+ # records without the band-limited rows, as on a development panel,
+ # cannot tell the board: it must be named
+ limited = dict(scorefiles.BAND_LIMITED_ROWS)
+
+ def panel(system):
+ return system[0], [
+ r for r in system[1] if r["condition"] not in limited
+ ]
+
+ with pytest.raises(ValueError, match="name the board"):
+ compare.composite_delta(panel(left),
+ panel(right),
+ calibration,
+ ranking.AXES_FULL,
+ n_boot=100)
+ assert compare.composite_delta(
+ panel(left),
+ panel(right),
+ calibration,
+ ranking.AXES_FULL,
+ n_boot=100,
+ board="restoration")["delta"] == pytest.approx(lost["delta"])
+ with pytest.raises(ValueError, match="no board"):
+ compare.composite_delta(left,
+ right,
+ calibration,
+ ranking.AXES_FULL,
+ n_boot=100,
+ board="enhancement")
+
+
+def test_an_axis_beside_every_part_is_read_when_requested(
+ composite_case, tmp_path):
+ # pylint: disable-next=import-outside-toplevel
+ import ranking
+
+ scores, calibration, systems = composite_case(tmp_path)
+ axis_scores, _, _ = ranking.rank(
+ copy.deepcopy(scores),
+ {n: ("full", n) for n in ("candidate", "baseline")},
+ calibration,
+ )
+ pair = systems["candidate"], systems["baseline"]
+ asked = {a: ranking.AXES_FULL[a] for a in ("room", "band")}
+ two = compare.composite_delta(*pair, calibration, asked, n_boot=100)
+ axes = axis_scores["candidate"]
+ # band sits beside every part: requested, it is read as a group of its own
+ assert two["left"] == pytest.approx((axes["room"] + axes["band"]) / 2)
+ assert two["board"] is None
+ # a custom grouping that drops or repeats a requested axis is refused
+ for grouping in ({
+ "restores": ["room"]
+ }, {
+ "restores": ["room", "band"],
+ "beside": ["band"]
+ }):
+ with pytest.raises(ValueError, match="exactly once"):
+ compare.composite_delta(*pair,
+ calibration,
+ asked,
+ n_boot=100,
+ parts=grouping)
diff --git a/tests/bench/scripts/test_contracts.py b/tests/bench/scripts/test_contracts.py
new file mode 100644
index 0000000..7c583c1
--- /dev/null
+++ b/tests/bench/scripts/test_contracts.py
@@ -0,0 +1,90 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Every condition has one contract.
+
+The composite scores what the contract states and no more.
+"""
+
+import os
+
+import pytest
+
+import contracts
+import ranking
+import validateset
+
+
+def test_every_family_has_exactly_one_profile_and_unknown_ones_have_none():
+ families = [f for group in contracts.FAMILIES.values() for f in group]
+ assert len(families) == len(set(families)) and set(
+ contracts.FAMILIES) == set(contracts.PROFILES)
+ assert (contracts.profile("babble@-5") == "denoise" and
+ contracts.profile("clean") == "denoise")
+ assert (contracts.profile("singer@-2") == "voice_policy" and
+ contracts.profile("reverb_real") == "restoration")
+ assert (contracts.profile("nonverbal@+0") == "denoise" and
+ contracts.profile("nonverbal_clean") == "denoise")
+ assert contracts.profile("_deletion") == "denoise"
+ with pytest.raises(KeyError):
+ # a new family needs a stated contract, never a default
+ contracts.profile("underwater@+0")
+
+
+def test_every_condition_the_validator_expects_has_a_contract():
+ for condition in validateset.EXPECTED_INVENTORY:
+ assert contracts.profile(condition) in contracts.PROFILES
+
+
+def test_composite_scores_denoising_and_the_room_axis_in_every_view_and_tier():
+ for view in ranking.AXES_VIEWS.values():
+ for axes in view.values():
+ contracts.check_axes(axes)
+ contracts.check_axes({"room": [("reverb_real", "spk_sim", 1)]})
+ # a laugh is the voice
+ contracts.check_axes(
+ {"preservation": [("nonverbal@+0", "nv_lost_pct", -1)]})
+ with pytest.raises(ValueError, match="restoration"):
+ contracts.check_axes({"fidelity": [("reverb_real", "si_sdr", 1)]})
+ with pytest.raises(ValueError, match="voice_policy"):
+ contracts.check_axes(
+ {"preservation": [("singer@-5", "kept_coh_p10", 1)]})
+ # the room axis is rooms only
+ with pytest.raises(ValueError, match="scores restoration"):
+ contracts.check_axes(
+ {"room": [("reverb_real", "spk_sim", 1), ("clean", "spk_sim", 1)]})
+ with pytest.raises(ValueError, match="denoise only"):
+ contracts.check_axes({"room": [("reverb_real", "spk_sim", 1)]},
+ {"denoise": None})
+ assert (contracts.axes_statement() ==
+ "the axes score denoise rows and restoration rows in the room "
+ "axis alone")
+
+
+def test_conventions_quote_scorers_own_bounds_and_the_readme_states_contracts():
+ text = " ".join(" ".join(row) for row in contracts.CONVENTIONS)
+ assert "100 ms" in text and "12 dB" in text and "polarity" in text
+ grouped = contracts.by_profile(
+ ["babble@+4", "singer@-5", "reverb_synth", "clean", "babble@+4"])
+ assert grouped == {
+ "denoise": ["babble@+4", "clean"],
+ "voice_policy": ["singer@-5"],
+ "restoration": ["reverb_synth"],
+ }
+ path = os.path.join(os.path.dirname(contracts.__file__), "..", "README.md")
+ with open(path, encoding="utf-8") as fh:
+ readme = fh.read()
+ section = readme.split("### Task contracts", 1)[1].split("\n## ", 1)[0]
+ families = contracts.FAMILIES
+ for family in families["voice_policy"] + families["restoration"]:
+ assert f"`{family}" in section, family
diff --git a/tests/bench/scripts/test_controls.py b/tests/bench/scripts/test_controls.py
new file mode 100644
index 0000000..72582ad
--- /dev/null
+++ b/tests/bench/scripts/test_controls.py
@@ -0,0 +1,380 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The control defects are what they claim to be, on a fixed slice.
+
+Every control is held to a declared expectation.
+"""
+
+# pylint: disable=protected-access
+
+import math
+
+import torch
+
+import anchors
+import common
+import controls
+import ranking
+
+SR = controls.SR
+
+
+def _voice(seconds=3.0, seed=0):
+ """Returns noise bursts with silence between them and a quiet floor.
+
+ Enough structure for a defect to land on "speech" and for a floor to be
+ removable.
+ """
+ gen = torch.Generator().manual_seed(seed)
+ n = int(seconds * SR)
+ x = 1e-4 * torch.randn(n, generator=gen)
+ for start in range(int(0.2 * SR), n - SR // 2, SR):
+ burst = 0.3 * torch.randn(SR // 2, generator=gen)
+ x[start:start + SR // 2] += burst
+ return x
+
+
+def test_a_deletion_removes_exactly_its_span_from_speech_and_is_frozen_per_item(
+):
+ ref = _voice()
+ for seconds in (0.020, 0.080, 0.320):
+ out = controls.delete(ref, seconds, "item_a.wav")
+ gone = torch.nonzero(out == 0).flatten()
+ # the span less its edges
+ assert abs(len(gone) - seconds * SR) <= 2 * int(0.002 * SR)
+ # it fell on a burst, not on the floor
+ assert float(ref[gone].pow(2).mean()) > 1e-3
+ assert torch.equal(out, controls.delete(ref, seconds, "item_a.wav"))
+ untouched = torch.ones(len(ref), dtype=torch.bool)
+ untouched[int(gone.min()) - 200:int(gone.max()) + 200] = False
+ assert torch.equal(out[untouched], ref[untouched])
+ assert not torch.equal(controls.delete(ref, 0.080, "item_a.wav"),
+ controls.delete(ref, 0.080, "item_b.wav"))
+ short = ref[:1000]
+ # nothing to delete from: unchanged
+ assert torch.equal(controls.delete(short, 0.320, "x"), short)
+
+
+def test_the_invented_high_band_keeps_the_energy_and_loses_the_waveform():
+ ref = _voice()
+ out = controls.invent_high_band(ref, "item.wav")
+
+ def high(x):
+ return controls.cut_high_band(x) - x
+
+ # below 8 kHz: the recording
+ assert common.si_sdr(controls.cut_high_band(out),
+ controls.cut_high_band(ref)) > 30
+ ratio = 10 * math.log10(
+ float(high(out).pow(2).mean() / high(ref).pow(2).mean()))
+ assert abs(ratio) < 1.0 # above: the same energy
+ assert common.si_sdr(high(out), high(ref)) < 0 # and another signal
+ cut = controls.cut_high_band(ref)
+ assert float(
+ high(cut).pow(2).mean()) < 1e-3 * float(high(ref).pow(2).mean())
+
+
+def test_resynthesis_is_another_waveform_with_the_same_spectrogram():
+ ref = _voice()
+ out = controls.resynthesise(ref, "item.wav")
+ assert 15 < common.si_sdr(out, ref) < 30
+
+ def spec(x):
+ return controls._stft(x).abs()
+
+ err = float((spec(out) - spec(ref)).pow(2).sum() / spec(ref).pow(2).sum())
+ assert err < 0.02
+ assert torch.equal(out, controls.resynthesise(ref, "item.wav"))
+
+
+def test_floor_removal_silences_the_gaps_and_leaves_the_speech():
+ ref = _voice()
+ out = controls.remove_floor(ref)
+ burst = slice(int(0.25 * SR), int(0.6 * SR))
+ gap = slice(int(0.8 * SR), int(1.1 * SR))
+ assert torch.equal(out[burst], ref[burst])
+ assert (float(out[gap].abs().max()) == 0.0 and
+ float(ref[gap].abs().max()) > 0.0)
+
+
+def test_delay_gain_and_polarity_are_the_named_transform():
+ ref = _voice(1.0)
+ late = controls.delay(ref, 0.020)
+ assert (len(late) == len(ref) and torch.equal(late[960:], ref[:-960]) and
+ not late[:960].any())
+
+ def build(name):
+ return controls.CONTROLS[name][1](ref, 2 * ref, "i")
+
+ assert torch.allclose(build("gainup6db"), ref * 1.9953, atol=1e-4)
+ assert torch.equal(build("polarity"), -ref) and torch.equal(
+ build("bedonly"), ref)
+ assert torch.equal(build("input"), 2 * ref) and not build("silence").any()
+
+
+def test_the_slice_is_fixed_and_heard_across_languages_before_any_twice():
+ rows = [{
+ "id": f"c_{lang}_{i}.wav",
+ "condition": "clean",
+ "language": lang,
+ "clean_path": "r",
+ }
+ for lang, count in (("en", 6), ("de", 2), ("ja", 1))
+ for i in range(count)]
+ rows += [{
+ "id": "real.wav",
+ "condition": "clean",
+ "language": "en"
+ }] # no reference: never picked
+ picked = controls.stratified(list(reversed(rows)), ("clean", "absent"), 5)
+ assert [r["language"] for r in picked] == ["de", "en", "ja", "de", "en"]
+ assert picked == controls.stratified(rows, ("clean", "absent"), 5)
+ assert len(controls.stratified(rows, ("clean",), 50)) == 9
+
+
+def test_every_control_is_held_to_an_expectation_over_known_columns():
+ assert set(controls.EXPECTED) == set(controls.CONTROLS)
+ for expectation in controls.EXPECTED.values():
+ assert expectation and set(expectation) <= set(controls.COLUMNS)
+ assert all(op in (">=", "<=") for op, _ in expectation.values())
+ for harmless in (
+ "reference",
+ "polarity",
+ "delay20ms",
+ "resynth",
+ "floorless",
+ ):
+ # inaudible: never read as damage
+ assert controls.EXPECTED[harmless]["fidelity"] == (">=", 0.95)
+ # stated, not hidden
+ assert (set(controls.BLIND) <= set(controls.CONTROLS) and
+ all(controls.BLIND.values()))
+
+
+def test_check_reports_the_expectations_a_table_misses():
+ good = {
+ "fidelity": 1.0,
+ "kept_coh_p10": 0.0,
+ "lost_pct": 0.0,
+ "nv_lost_pct": 0.0,
+ "spk_sim": 1.0,
+ "si_sdr": 100.0,
+ }
+ table = {
+ "reference": good,
+ "polarity": dict(good, kept_coh_p10=-80.0),
+ "delete320ms": {
+ "lost_pct": float("nan"),
+ "fidelity": 0.5
+ },
+ }
+ # a slice without the block holds no control to its columns
+ failures = controls.check(table, block=False)
+ assert set(failures) == {"polarity", "delete320ms"}
+ held = controls.check(table)
+ assert "event_resid_db nan" in held["reference"][0]
+ assert failures["polarity"] == ["kept_coh_p10 -80.00 should be >= -1"]
+ # unmeasured is not passed
+ assert "lost_pct nan" in failures["delete320ms"][0]
+ md = controls.markdown(
+ {
+ k: {
+ c: v.get(c, float("nan")) for c in controls.COLUMNS
+ } for k, v in table.items()
+ },
+ failures,
+ "0123456789abcdef0123",
+ 240,
+ ("clean",),
+ )
+ assert ("| `reference` |" in md and "| yes |" in md and
+ "no: kept_coh_p10 -80.00" in md)
+ assert "## Blind spots" in md and "- `hfinvented`:" in md
+
+
+def test_summarise_reads_the_published_fidelity_axis_on_the_clean_items():
+ policy = anchors.definitions()
+ points = {}
+ for cond, metric, sign in ranking.AXES_FULL["fidelity"]:
+ rule = anchors.rule_for(policy, cond, metric)
+ points[anchors.row_key(cond, metric)] = {
+ "floor": rule["floor"]["value"],
+ "ceiling": rule["ceiling"]["value"],
+ "direction": sign,
+ }
+ clean = {
+ "si_sdr": 99.0,
+ "kept_coh_p10": -6.0,
+ "kept_coh_lost_pct": 2.5,
+ "spk_sim": 1.0,
+ "nisqa_mos": 4.5,
+ "out_in_rms_db": -6.0,
+ "level_err_db": 6.0, # the scorer's mean absolute level change
+ "band_kept_db": [0, 0, 0, 0, 0.1, -0.1, 0.1],
+ "hf_err_db": 0.1, # and its high-band error, the gain undone
+ "mag_snr": 20.0,
+ }
+ metrics = {
+ "clean": clean,
+ "nonverbal_clean": {
+ "nv_lost_pct": 15.0
+ },
+ "_level_cal_db": -6.0,
+ "babble@+4": {
+ "babble_supp_db": -12.0
+ },
+ }
+ row = controls.summarise(metrics, {"points": points}, ranking.AXES_FULL)
+ assert row["lost_pct"] == 2.5
+ # a gain is level, not deletion
+ assert row["kept_coh_p10"] == 0.0 and row["level_err"] == 6.0
+ assert (math.isclose(row["hf_err"], 0.1, abs_tol=1e-9) and
+ row["babble_supp_db"] == -12.0)
+ assert row["mag_snr"] == 20.0 and row["nv_lost_pct"] == 15.0
+ # the block's rows, read from its pooled cell when the slice holds it
+ assert all(math.isnan(row[c]) for c in controls.BLOCK_COLUMNS)
+ metrics["_coroom"] = {
+ "event_resid_db": -20.0,
+ "floor_resid_db": -6.0,
+ "voice_level_db": -0.3,
+ }
+ pooled = controls.summarise(metrics, {"points": points}, ranking.AXES_FULL)
+ assert (pooled["event_resid_db"], pooled["floor_resid_db"],
+ pooled["voice_level_db"]) == (-20.0, -6.0, -0.3)
+ assert math.isclose(row["fidelity"], (1 + 0 + 1 + 1 + 1 + 0.5 + 0.5) / 7)
+ # a slice without the recordings has no fidelity to state
+ del metrics["nonverbal_clean"]
+ sliced = controls.summarise(metrics, {"points": points}, ranking.AXES_FULL)
+ assert math.isnan(sliced["fidelity"])
+ bare = controls.summarise({"clean": {}}, {"points": points},
+ ranking.AXES_FULL)
+ assert math.isnan(bare["fidelity"])
+
+
+def test_the_block_controls_tell_the_transients_from_the_floor_and_duck():
+ ref = _voice()
+ n = len(ref)
+ floor = torch.randn(
+ n, generator=torch.Generator().manual_seed(3)) * 10**(-55 / 20)
+ event = torch.zeros(n)
+ a = int(1.2 * controls.SR)
+ event[a:a + 4800] = torch.randn(
+ 4800, generator=torch.Generator().manual_seed(4)) * 10**(-15 / 20)
+ mix = ref + floor + event
+ kept = controls.transients(mix - ref)
+ # the event's frames stay whole, the floor's frames are silenced
+ assert torch.allclose(kept[a:a + 4800], (floor + event)[a:a + 4800],
+ atol=1e-6)
+ assert float(kept[:a - 480].abs().max()) == 0.0
+ assert torch.equal(controls.CONTROLS["transientsleft"][1](ref, mix, "i"),
+ ref + kept)
+ assert torch.equal(controls.CONTROLS["floorleft"][1](ref, mix, "i"),
+ mix - kept)
+ assert torch.allclose(controls.CONTROLS["halfnoise"][1](ref, mix, "i"),
+ ref + 0.5 * (floor + event),
+ atol=1e-6)
+ # the voice ducks only where something was added
+ assert torch.allclose(controls.ducked(ref, mix), ref * 10**(-3 / 20))
+ assert torch.equal(controls.ducked(ref, ref), ref)
+ assert controls.BLOCK_CONDS == tuple(
+ c for c in controls.DEFAULT_CONDS if c.startswith("coroom"))
+
+
+def test_controls_have_a_description_and_a_builder_and_notes_name_controls():
+ for name, entry in controls.CONTROLS.items():
+ assert isinstance(entry, tuple) and len(entry) == 2, name
+ assert isinstance(entry[0], str) and callable(entry[1]), name
+ assert set(controls.EXPECTED) <= set(controls.CONTROLS) and set(
+ controls.BLIND) <= set(controls.CONTROLS)
+
+
+def test_cached_control_is_trusted_only_under_the_same_scorers_slice_and_policy(
+ monkeypatch,):
+ rows = [{"id": "a.wav"}, {"id": "b.wav"}]
+ metrics = {"_controls_identity": controls.identity(rows), "clean": {}}
+ assert controls.cached(metrics, rows)
+ assert not controls.cached(metrics, rows[:1]) # another slice
+ # saved before the identity existed
+ assert not controls.cached({"clean": {}}, rows)
+ # pylint: disable-next=import-outside-toplevel
+ import scorekept
+
+ monkeypatch.setattr(scorekept, "SCORER_SHA256", "another sidecar")
+ assert not controls.cached(metrics, rows) # a scorer changed under it
+ monkeypatch.undo()
+ # pylint: disable-next=import-outside-toplevel
+ import scoreevents
+
+ monkeypatch.setattr(scoreevents, "SCORER_SHA256", "another sidecar")
+ assert not controls.cached(metrics, rows)
+ monkeypatch.undo()
+ # pylint: disable-next=import-outside-toplevel
+ import observations
+
+ digest = controls.identity(rows)["controls_sha256"]
+ assert digest == observations.implementation(controls.__file__)
+ # a corrected label of a same-room item makes the saved control stale
+ block = [{
+ "id": "coroomATboth_000.wav",
+ "condition": "coroom@both",
+ "provenance": {
+ "events": [[1.0, 1.1, "speech", "household", "src:a", -23.0]],
+ "room_share_db": 0.8
+ }
+ }]
+ saved = {"_controls_identity": controls.identity(block), "clean": {}}
+ assert controls.cached(saved, block)
+ moved = [
+ dict(block[0],
+ provenance=dict(block[0]["provenance"], room_share_db=1.2))
+ ]
+ assert not controls.cached(saved, moved)
+
+
+def _bursts():
+ """Half a second of silence, then speech-like bursts at known places."""
+ ref = torch.zeros(int(3.2 * controls.SR))
+ for start_s, end_s in ((0.5, 1.5), (1.9, 2.7)):
+ a, b = int(start_s * controls.SR), int(end_s * controls.SR)
+ t = torch.arange(b - a) / controls.SR
+ ref[a:b] = 0.3 * torch.sin(2 * math.pi * 220 * t)
+ return ref
+
+
+def test_boundaries_find_the_word_starts_and_trailing_ends():
+ onsets, offsets = controls.boundaries(_bursts())
+ frame = controls.SR // 100
+ assert [round(o / frame) for o in onsets] == [50, 190]
+ assert [round(o / frame) for o in offsets] == [150, 270]
+
+
+def test_onset_and_tail_cuts_sit_on_a_boundary_and_remove_only_their_span():
+ ref = _bursts()
+ onsets, offsets = controls.boundaries(ref)
+ span = int(0.08 * controls.SR)
+ edge = int(0.002 * controls.SR)
+ cut, start = controls.cut_onset(ref, 0.08, "item")
+ assert start in onsets
+ assert cut[start + edge:start + span - edge].abs().max() == 0
+ assert torch.equal(cut[start + span:], ref[start + span:])
+ assert torch.equal(cut[:start], ref[:start])
+ assert controls.cut_onset(ref, 0.08, "item")[1] == start # frozen per item
+ cut, start = controls.cut_tail(ref, 0.16, "item")
+ span = int(0.16 * controls.SR)
+ assert start + span in offsets
+ assert cut[start + edge:start + span - edge].abs().max() == 0
+ assert torch.equal(cut[start + span:], ref[start + span:])
+ # nothing fits: the reference comes back unchanged, with no position
+ same, none = controls.cut_onset(ref, 5.0, "item")
+ assert none is None and torch.equal(same, ref)
diff --git a/tests/bench/scripts/test_leaderboard.py b/tests/bench/scripts/test_leaderboard.py
new file mode 100644
index 0000000..7a4cd4a
--- /dev/null
+++ b/tests/bench/scripts/test_leaderboard.py
@@ -0,0 +1,105 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The board's command line: the checks it runs and the files it writes."""
+
+import json
+import sys
+
+import pytest
+
+import leaderboard
+import ranking
+import scorefiles
+import tiny_board
+
+
+def test_json_is_strict_and_incomplete_entrants_listed(tmp_path):
+ tiny_board.write(tmp_path, "a", tiny_board.metrics(10.0), deletion_pct=1.0)
+ tiny_board.write(
+ tmp_path,
+ "partial",
+ {
+ "music@-6": {
+ "n": 24,
+ "si_sdr": 1.0
+ },
+ "_level_cal_db": 0.0
+ },
+ )
+ tiers = {"a": ("full", "A"), "partial": ("full", "P")}
+ scores = scorefiles.load(str(tmp_path))
+ axis_scores, comp, _ = tiny_board.rank(scores, tiers)
+ payload = scorefiles.finite({
+ "comp": comp,
+ "incomplete": ranking.incomplete(scores, axis_scores, comp, tiers)
+ })
+ text = json.dumps(payload, allow_nan=False)
+ assert json.loads(text)["comp"]["partial"] is None
+ assert json.loads(text)["incomplete"]["full"]["partial"]
+
+
+def test_main_refuses_results_from_different_sets(tmp_path, monkeypatch):
+ for name, sid in (("a", "set-one"), ("b", "set-two")):
+ (tmp_path / f"{name}.metrics.json").write_text(
+ json.dumps({
+ "_set_id": sid,
+ "clean": {
+ "n": 48
+ }
+ }))
+ tiers = tmp_path / "tiers.json"
+ tiers.write_text(json.dumps({"a": ["full", "a"], "b": ["full", "b"]}))
+ monkeypatch.setattr(
+ sys,
+ "argv",
+ ["leaderboard.py", "--results",
+ str(tmp_path), "--tiers",
+ str(tiers)],
+ )
+ with pytest.raises(SystemExit, match="different eval sets"):
+ leaderboard.main()
+
+
+def test_scores_of_another_render_than_the_one_stamped_now_are_refused(
+ tmp_path, monkeypatch):
+ for name, scored, stamped in (("a", "one", "one"), ("b", "one", "two")):
+ (tmp_path / f"{name}.metrics.json").write_text(
+ json.dumps({
+ "_set_id": "tiny",
+ "_outputs_sha256": scored,
+ "clean": {
+ "n": 48
+ }
+ }))
+ (tmp_path / f"{name}.meta.json").write_text(
+ json.dumps({"outputs_sha256": stamped}))
+ # the set's own mixtures carry no digest on either side
+ (tmp_path / "INPUT.metrics.json").write_text(json.dumps({"_set_id": "tiny"
+ }))
+ scores = scorefiles.load(str(tmp_path))
+ assert scorefiles.render_problem({k: scores[k] for k in ("a", "INPUT")},
+ str(tmp_path)) is None
+ assert "the scores of b read other audio" in scorefiles.render_problem(
+ scores, str(tmp_path))
+ tiers = tmp_path / "tiers.json"
+ tiers.write_text(json.dumps({"a": ["full", "a"], "b": ["full", "b"]}))
+ monkeypatch.setattr(
+ sys,
+ "argv",
+ ["leaderboard.py", "--results",
+ str(tmp_path), "--tiers",
+ str(tiers)],
+ )
+ with pytest.raises(SystemExit, match="re-score them"):
+ leaderboard.main()
diff --git a/tests/bench/scripts/test_levels.py b/tests/bench/scripts/test_levels.py
new file mode 100644
index 0000000..90da191
--- /dev/null
+++ b/tests/bench/scripts/test_levels.py
@@ -0,0 +1,68 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The output-gain convention, read one raw measurement at a time."""
+
+import math
+
+import numpy as np
+import pytest
+
+import levels
+
+
+def test_the_gain_factor_undoes_a_level_given_in_db():
+ assert levels.gain(0.0) == 1.0
+ assert levels.gain(20.0) == pytest.approx(0.1)
+ assert levels.gain(-6.0) == pytest.approx(10**(6 / 20))
+
+
+def test_suppression_reads_the_residual_with_the_gain_undone():
+ r = np.array([1.0, -0.5, 0.25, 0.75])
+ m = r + np.array([0.3, 0.1, -0.2, 0.05])
+ louder = 2.0 * r
+ energies = [
+ np.mean(louder * louder),
+ np.mean(louder * r),
+ np.mean(r * r),
+ np.mean((m - r)**2),
+ ]
+ # the reference itself, 6 dB louder: nothing is left once the gain is
+ # undone, and the reference's own energy is left when it is not
+ assert levels.suppression_db(energies, 20 * math.log10(2.0)) < -60.0
+ raw = 10 * math.log10(np.mean(r * r) / np.mean((m - r)**2))
+ assert levels.suppression_db(energies, 0.0) == pytest.approx(raw, abs=1e-6)
+
+
+def test_energy_ratios_and_the_high_bands_read_the_gain_undone():
+ assert levels.energy_db(-3.0, 6.0) == -9.0
+ # the three high bands 6, 4 and 8 dB over the reference, under a 6 dB gain
+ bands = [0.0] * 4 + [6.0, 4.0, 8.0]
+ assert levels.hf_error_db(bands, 6.0) == pytest.approx(4 / 3)
+ assert math.isnan(levels.hf_error_db([0.0] * 4 + [math.nan] * 3, 0.0))
+
+
+def test_the_level_change_is_the_gain_itself_in_absolute_db():
+ assert levels.level_error_db(-2.5) == 2.5
+ assert levels.level_error_db(3.0) == 3.0
+
+
+def test_lost_blocks_and_deleted_segments_are_read_with_the_gain_undone():
+ kept = [-5.0, -5.0, -12.0]
+ assert levels.lost(kept, 0.0).tolist() == [False, False, True]
+ # the same levels read off an output 6 dB louder than its input: every
+ # block sits 11 dB or more under the recording once the gain is undone
+ assert levels.lost(kept, 6.0).tolist() == [True, True, True]
+ assert not levels.lost([], 0.0).size
+ assert levels.deleted([-5.0, -12.0], 0.0) == [0.0, 1.0]
+ assert levels.deleted([-5.0, -12.0], 6.0) == [1.0, 1.0]
diff --git a/tests/bench/scripts/test_observations.py b/tests/bench/scripts/test_observations.py
new file mode 100644
index 0000000..c9d53f5
--- /dev/null
+++ b/tests/bench/scripts/test_observations.py
@@ -0,0 +1,115 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Observation provenance, reproducible raw measurements, complete records."""
+
+import json
+
+import pytest
+
+import observations
+
+
+def test_windows_share_the_recording_group_without_disclosing_source_names():
+ row = {
+ "id": "a.wav",
+ "condition": "babble@0",
+ "clean_path": "ref/a.wav",
+ "family": "babble",
+ "provenance": {
+ "speech": "private:utterance",
+ "corruptor": "private:[email protected]",
+ },
+ }
+ a = observations.item(row)
+ row["provenance"]["corruptor"] = "private:[email protected]"
+ b = observations.item(row)
+ assert a["bed_source"] == b["bed_source"] and a["groups_verified"]
+ assert "private:" not in json.dumps(a)
+ del row["provenance"]
+ assert not observations.item(row)["groups_verified"]
+
+
+def test_rooms_group_by_response_and_bedless_conditions_by_recording_alone():
+ room = {
+ "id": "r.wav",
+ "condition": "reverb_real",
+ "clean_path": "ref/r.wav",
+ "provenance": {
+ "speech": "private:utterance",
+ "rir": "private:hall-3"
+ },
+ }
+ a, b = observations.item(room), observations.item(dict(room, id="s.wav"))
+ assert (a["groups_verified"] and a["bed_source"] and
+ a["bed_source"] == b["bed_source"])
+ other = observations.item(
+ dict(room, provenance=dict(room["provenance"], rir="private:hall-4")))
+ assert other["bed_source"] != a["bed_source"]
+ assert "private:" not in json.dumps(a)
+ no_rir = dict(room, provenance={"speech": "private:utterance"})
+ assert not observations.item(no_rir)["groups_verified"]
+ for condition in observations.BEDLESS:
+ rec = observations.item({
+ "id": "c.wav",
+ "condition": condition,
+ "clean_path": "ref/c.wav",
+ "provenance": {
+ "speech": "private:utterance"
+ },
+ })
+ assert rec["groups_verified"] and rec["bed_source"] is None
+ # a condition that mixes a bed in cannot pass without naming it
+ noisy = observations.item({
+ "id": "n.wav",
+ "condition": "nonverbal@+0",
+ "clean_path": "ref/n.wav",
+ "provenance": {
+ "speech": "private:utterance"
+ },
+ })
+ assert not noisy["groups_verified"]
+
+
+def test_capture_keeps_reducer_inputs_and_missing_values():
+ record = {}
+ observations.capture(
+ record,
+ {
+ "kept": [2.0, 3.0],
+ "seg_drop": [0.0, -30.0, 0.0],
+ "band": [[float("nan"), 0]],
+ },
+ {"kept": 1},
+ )
+ assert record["measurements"]["kept"] == [3.0]
+ # deletions are read at a calibration, later
+ assert record["metrics"]["n_segments"] == 3
+ assert record["metrics"]["band_kept_db"] == [None, 0]
+ json.dumps(record, allow_nan=False)
+
+
+def test_record_writer_is_private_and_reader_refuses_truncation_and_duplicates(
+ tmp_path,):
+ path = tmp_path / "items.jsonl"
+ meta = {"set_id": "set", "system": "system", "n_expected": 2}
+ observations.write(path, [{"id": "a"}, {"id": "b"}], meta)
+ assert path.stat().st_mode & 0o777 == 0o600
+ assert len(observations.read(path)[1]) == 2
+ lines = path.read_text().splitlines()
+ path.write_text("\n".join(lines[:-1]))
+ with pytest.raises(ValueError, match="truncated"):
+ observations.read(path)
+ observations.write(path, [{"id": "a"}, {"id": "a"}], meta)
+ with pytest.raises(ValueError, match="duplicated"):
+ observations.read(path)
diff --git a/tests/bench/scripts/test_ranking.py b/tests/bench/scripts/test_ranking.py
new file mode 100644
index 0000000..1b3d7bc
--- /dev/null
+++ b/tests/bench/scripts/test_ranking.py
@@ -0,0 +1,570 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Ranking rules: axes, deletion cohort, composite, ties.
+
+The tests use synthetic scores and no audio.
+"""
+
+import json
+import math
+import sys
+
+import pytest
+
+import anchors
+import common
+import leaderboard
+import ranking
+import scorefiles
+import tables
+import tiny_board
+
+
+def test_partial_entrant_is_not_ranked(tmp_path):
+ tiny_board.write(tmp_path,
+ "full_a",
+ tiny_board.metrics(10.0),
+ deletion_pct=1.0)
+ tiny_board.write(tmp_path,
+ "full_b",
+ tiny_board.metrics(5.0),
+ deletion_pct=2.0)
+ only_music = {"music@-6": {"n": 24, "si_sdr": 99.0}, "_level_cal_db": 0.0}
+ tiny_board.write(tmp_path, "partial", only_music)
+ tiers = {n: ("full", n) for n in ("full_a", "full_b", "partial")}
+ scores = scorefiles.load(str(tmp_path))
+ axis_scores, comp, order = tiny_board.rank(scores, tiers)
+ assert order["full"] == ["full_a", "full_b"]
+ assert math.isnan(comp["partial"])
+ incomplete = ranking.incomplete(scores, axis_scores, comp, tiers)
+ # without the band-limited rows no board can be assigned, and it says so
+ reasons = incomplete["full"]["partial"]
+ assert reasons[0].startswith("no board: the band-limited rows")
+ assert reasons[1].startswith("missing ")
+
+
+def test_a_saturated_level_calibration_is_not_ranked(tmp_path):
+ tiny_board.write(tmp_path,
+ "full_a",
+ tiny_board.metrics(10.0),
+ deletion_pct=1.0)
+ tiny_board.write(tmp_path,
+ "full_b",
+ tiny_board.metrics(5.0),
+ deletion_pct=2.0)
+ # the scorer's bound was hit
+ loud = dict(tiny_board.metrics(8.0), _level_cal_db=common.MAX_LEVEL_CAL_DB)
+ tiny_board.write(tmp_path, "loud", loud, deletion_pct=1.0)
+ tiers = {n: ("full", n) for n in ("full_a", "full_b", "loud")}
+ scores = scorefiles.load(str(tmp_path))
+ axis_scores, comp, order = tiny_board.rank(scores, tiers)
+ assert order["full"] == ["full_a", "full_b"] and math.isnan(comp["loud"])
+ # every axis present, yet not ranked
+ assert all(v == v for v in axis_scores["loud"].values())
+ incomplete = ranking.incomplete(scores, axis_scores, comp, tiers)
+ reasons = incomplete["full"]["loud"]
+ assert len(reasons) == 1 and reasons[0].startswith(
+ "level calibration saturated at 12 dB")
+ within = dict(
+ tiny_board.metrics(8.0),
+ # inside the bound: ranked
+ _level_cal_db=common.MAX_LEVEL_CAL_DB - 0.5,
+ )
+ tiny_board.write(tmp_path, "loud", within, deletion_pct=1.0)
+ scores = scorefiles.load(str(tmp_path))
+ axis_scores, comp, order = tiny_board.rank(scores, tiers)
+ assert "loud" in order["full"]
+
+
+def test_thin_condition_coverage_blocks_the_axis(tmp_path):
+ tiny_board.write(tmp_path, "a", tiny_board.metrics(10.0), deletion_pct=1.0)
+ thin = tiny_board.metrics(5.0)
+ thin["music@-6"]["n"] = 3
+ tiny_board.write(tmp_path, "b", thin, deletion_pct=1.0)
+ tiers = {n: ("full", n) for n in ("a", "b")}
+ scores = scorefiles.load(str(tmp_path))
+ axis_scores, comp, order = tiny_board.rank(scores, tiers)
+ assert math.isnan(axis_scores["b"]["music"]) and math.isnan(comp["b"])
+ assert order["full"] == ["a"]
+
+
+def test_deletion_comes_only_from_the_primary_anchored_sidecar(tmp_path):
+ m = tiny_board.metrics(10.0)
+ # unfiltered cohort: must not be used
+ m.setdefault("real_noisy", {"n": 24})["deleted_rate_pct"] = 7.0
+ tiny_board.write(tmp_path, "no_sidecar", m)
+ tiny_board.write(tmp_path,
+ "with_sidecar",
+ tiny_board.metrics(10.0),
+ deletion_pct=2)
+ scores = scorefiles.load(str(tmp_path))
+ ranking.pool_deletion(scores, {f"r{i:03d}": 1 for i in range(100)})
+ assert math.isnan(scores["no_sidecar"]["_deletion"]["pct"])
+ assert scores["with_sidecar"]["_deletion"]["pct"] == 2.0
+ assert scores["with_sidecar"]["_deletion"]["primary_anchored"]
+
+
+def test_deletion_is_pooled_over_the_common_cohort(tmp_path):
+ """A system with only part of the real items cannot be compared on them."""
+ full = {f"r{i:03d}": [0, 1] for i in range(100)}
+ # 1 % on all items
+ tiny_board.write(tmp_path,
+ "a",
+ tiny_board.metrics(10.0),
+ items=dict(full, r000=[1, 1]))
+ half = {f"r{i:03d}": [0, 1] for i in range(50)}
+ # covers 50 % of the items
+ tiny_board.write(tmp_path, "half", tiny_board.metrics(9.0), items=half)
+ tiny_board.write(tmp_path,
+ "b",
+ tiny_board.metrics(8.0),
+ items=dict(full, r099=[1, 1], r098=[1, 1]))
+ tiers = {n: ("full", n) for n in ("a", "half", "b")}
+ scores = scorefiles.load(str(tmp_path))
+ _, comp, order = tiny_board.rank(scores, tiers)
+ assert math.isnan(scores["half"]["_deletion"]["pct"]) and math.isnan(
+ comp["half"])
+ assert (scores["a"]["_deletion"]["cohort_items"] ==
+ scores["b"]["_deletion"]["cohort_items"] == 100)
+ assert (scores["a"]["_deletion"]["pct"] == 1.0 and
+ scores["b"]["_deletion"]["pct"] == 2.0)
+ assert order["full"] == ["a", "b"]
+
+
+def test_unranked_entrants_do_not_move_the_normalisation(tmp_path):
+ tiny_board.write(tmp_path, "a", tiny_board.metrics(10.0), deletion_pct=1)
+ tiny_board.write(tmp_path, "b", tiny_board.metrics(5.0), deletion_pct=2)
+ tiers = {n: ("full", n) for n in ("a", "b")}
+ scores = scorefiles.load(str(tmp_path))
+ _, comp_before, _ = tiny_board.rank(scores, tiers)
+ tiny_board.write(
+ tmp_path,
+ "partial",
+ {
+ "music@-6": {
+ "n": 24,
+ "si_sdr": 999.0
+ },
+ "_level_cal_db": 0.0
+ },
+ )
+ tiers["partial"] = ("full", "partial")
+ scores = scorefiles.load(str(tmp_path))
+ _, comp_after, order = tiny_board.rank(scores, tiers)
+ assert comp_after["a"] == pytest.approx(comp_before["a"])
+ assert comp_after["b"] == pytest.approx(comp_before["b"])
+ assert order["full"] == ["a", "b"]
+
+
+def test_ranking_requires_a_frozen_calibration():
+ with pytest.raises(ValueError, match="frozen"):
+ ranking.rank({})
+
+
+def test_incomplete_entrant_cannot_move_the_deletion_cohort():
+ items_ab = {f"r{i}": [0, 1] for i in range(20)}
+
+ def system(items, deleted_on=()):
+ d = {}
+ for c in tiny_board.FULL:
+ d[c] = {
+ "n": 48,
+ "babble_supp_db": -10.0,
+ "si_sdr": 10.0,
+ "kept_p10": 0.0,
+ "kept_coh_p10": 0.0,
+ "spk_sim": 0.9,
+ "nisqa_mos": 4.0,
+ "nv_lost_pct": 10.0,
+ "mag_snr": 20.0,
+ "_hf_err": 0.5,
+ "_level_err": 0.5,
+ "babble_resid_db": -10.0,
+ "event_resid_db": -10.0,
+ "floor_resid_db": -10.0,
+ "band_added_db": 10.0,
+ # a denoiser's per-band levels: nothing above the input's band
+ "band_kept_db": [0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0],
+ }
+ d["_real_cleanup"] = {
+ "n": 48,
+ "pause_resid_db": -10.0,
+ "pause_level_db": -30.0
+ }
+ d["_coroom"] = {"n": 48, "voice_level_db": -0.5}
+ d["_real_quality"] = {"n": 48, "nisqa_mos": 4.0}
+ d["_deletion"] = {
+ "items": {
+ k: [1, 1] if k in deleted_on else [0, 1] for k in items
+ }
+ }
+ return d
+
+ # A deletes on r0..r4, B deletes on r15..r19: on the full cohort they tie
+ scores = {
+ "A": system(items_ab, deleted_on=[f"r{i}" for i in range(5)]),
+ "B": system(items_ab, deleted_on=[f"r{i}" for i in range(15, 20)]),
+ }
+ tiers = {"A": ("full", "A"), "B": ("full", "B"), "C": ("full", "C")}
+ _, comp1, _ = tiny_board.rank(scores, tiers)
+ # C covers only r10..r19 (half the items) and lacks a metric: it must not
+ # rank and must not shrink the cohort to the items where only B deletes
+ third = system({f"r{i}": [0, 1] for i in range(10, 20)})
+ del third["clean"]
+ scores["C"] = third
+ _, comp2, order = tiny_board.rank(scores, tiers)
+ assert comp2["A"] == pytest.approx(
+ comp1["A"]) and comp2["B"] == pytest.approx(comp1["B"])
+ assert ("C" not in order["full"] and
+ scores["A"]["_deletion"]["cohort_items"] == 20)
+
+
+def test_core_view_drops_the_extension_conditions_and_needs_core_results(
+ tmp_path, monkeypatch):
+ try:
+ assert ranking.select_view("core") == "core"
+ for axes in ranking.AXES_BY_TIER.values():
+ conds = {c for subs in axes.values() for c, _, _ in subs}
+ # the registry's core axes leave out the whole set's rows of the
+ # English-only families, and read crowd chatter at -5 dB
+ assert conds.isdisjoint(("stationary@-5", "traffic@-5"))
+ assert {"babble@+4", "babble@-5", "clean"} <= conds
+ ranking.select_view("all")
+ assert any(c == "stationary@-5"
+ for c, _, _ in ranking.AXES_FULL["suppression"])
+ with pytest.raises(SystemExit, match="--view must be"):
+ ranking.select_view("sideways")
+ (tmp_path / "a.metrics.json").write_text(
+ json.dumps({
+ "_set_id": "s",
+ "_subset": "all",
+ "clean": {
+ "n": 48
+ }
+ }))
+ tiers = tmp_path / "tiers.json"
+ tiers.write_text(json.dumps({"a": ["full", "a"], "b": ["full", "b"]}))
+ monkeypatch.setattr(
+ sys,
+ "argv",
+ [
+ "leaderboard.py",
+ "--results",
+ str(tmp_path),
+ "--view",
+ "core",
+ "--tiers",
+ str(tiers),
+ ],
+ )
+ with pytest.raises(SystemExit, match="BENCH_SUBSET=core"):
+ leaderboard.main()
+ (tmp_path / "b.metrics.json").write_text(
+ json.dumps({
+ "_set_id": "s",
+ "_subset": "core",
+ "clean": {
+ "n": 48
+ }
+ }))
+ monkeypatch.setattr(
+ sys,
+ "argv",
+ [
+ "leaderboard.py",
+ "--results",
+ str(tmp_path),
+ "--tiers",
+ str(tiers),
+ ],
+ )
+ with pytest.raises(SystemExit, match="different subsets"):
+ leaderboard.main()
+ finally:
+ ranking.select_view("all")
+
+
+def test_missing_outputs_are_listed_per_system_and_condition(
+ tmp_path, monkeypatch, capsys):
+ full = tiny_board.metrics(10.0)
+ full["babble@+4"]["n_missing"] = 3
+ full["clean"]["n_missing"] = 0 # zero is not a report
+ full["_n_missing"] = 3
+ tiny_board.write(tmp_path, "full_a", full, deletion_pct=1.0)
+ tiny_board.write(tmp_path,
+ "full_b",
+ tiny_board.metrics(5.0),
+ deletion_pct=2.0)
+ scores = scorefiles.load(str(tmp_path))
+ assert ranking.missing_outputs(scores) == {"full_a": {"babble@+4": 3}}
+ anchors.atomic_json(tmp_path / anchors.RESOLVED,
+ tiny_board.calibration(scores))
+ out = tmp_path / "lb.json"
+ tiers = tmp_path / "tiers.json"
+ tiers.write_text(
+ json.dumps({
+ "full_a": ["full", "full_a"],
+ "full_b": ["full", "full_b"]
+ }))
+ # nobody registered it
+ (tmp_path / "stray.metrics.json").write_text(
+ json.dumps(tiny_board.metrics(1.0)))
+ monkeypatch.setattr(
+ sys,
+ "argv",
+ [
+ "leaderboard.py",
+ "--results",
+ str(tmp_path),
+ "--json-out",
+ str(out),
+ "--tiers",
+ str(tiers),
+ ],
+ )
+ leaderboard.main()
+ text = capsys.readouterr().out
+ assert "IGNORED (no tier registered" in text and "stray" in text
+ assert "MISSING OUTPUTS" in text and "babble@+4 3" in text
+ assert json.load(open(out, encoding="utf-8"))["missing_outputs"] == {
+ "full_a": {
+ "babble@+4": 3
+ }
+ }
+
+
+def test_the_composite_is_the_mean_of_the_registrys_parts(tmp_path):
+ assert ranking.PARTS == {
+ "removes": ["suppression", "music", "cleanup", "events", "voices"],
+ "keeps": ["preservation", "fidelity"],
+ "sounds": ["timbre", "quality"],
+ "restores": ["room"],
+ }
+ assert ranking.BOARDS == {
+ "denoising": ["removes", "keeps", "sounds"],
+ "restoration": ["restores"],
+ }
+ assert ranking.ranking_board() == "denoising"
+ # the band axis is a diagnostic beside both boards
+ assert ranking.OUTSIDE == ["band"]
+ assert ranking.axis_order(
+ ) == [a for part in ranking.PARTS.values() for a in part] + ["band"]
+ assert sorted(ranking.axis_order()) == sorted(ranking.AXES_FULL)
+ rule = ranking.composite_rule()
+ assert rule.startswith("two scores, each ranking the systems of its own")
+ assert "is ranked on restoration, every other on denoising" in rule
+ assert ("denoising = removes (suppression, music, cleanup, events, voices)"
+ in rule)
+ assert "restoration = restores (room)" in rule
+ assert rule.endswith("scored beside both, read by neither: band")
+ tiny_board.write(tmp_path, "a", tiny_board.metrics(10.0), deletion_pct=1.0)
+ tiny_board.write(tmp_path, "b", tiny_board.metrics(5.0), deletion_pct=2.0)
+ scores = scorefiles.load(str(tmp_path))
+ tiers = {"a": ("full", "a"), "b": ("full", "b")}
+ axis_scores, comp, _ = tiny_board.rank(scores, tiers)
+ for n in ("a", "b"):
+ parts = anchors.part_scores(axis_scores[n], ranking.PARTS)
+ boards = ranking.board_scores(axis_scores[n])
+ # the table ranks by the denoising board: the mean of three parts
+ assert comp[n] == pytest.approx(
+ (parts["removes"] + parts["keeps"] + parts["sounds"]) / 3)
+ assert boards["denoising"] == pytest.approx(comp[n])
+ assert boards["restoration"] == pytest.approx(parts["restores"])
+ assert parts["removes"] == pytest.approx(
+ (axis_scores[n]["suppression"] + axis_scores[n]["music"] +
+ axis_scores[n]["cleanup"] + axis_scores[n]["events"] +
+ axis_scores[n]["voices"]) / 5)
+ assert parts["restores"] == pytest.approx(axis_scores[n]["room"])
+ # a system that leaves rooms alone loses half of the restoration board and
+ # nothing of the denoising board
+ scores["a"]["reverb_real"].update(spk_sim=0.86, nisqa_mos=2.0)
+ axis_scores_after, comp2, _ = tiny_board.rank(scores, tiers)
+ assert axis_scores_after["a"]["room"] == 0.0
+ assert axis_scores["a"]["room"] > 0.0
+ assert comp2["a"] == pytest.approx(comp["a"])
+ before = ranking.board_scores(axis_scores["a"])["restoration"]
+ after = ranking.board_scores(axis_scores_after["a"])["restoration"]
+ assert before - after == pytest.approx(axis_scores["a"]["room"])
+ # each board needs its own evidence: without the room rows a system still
+ # ranks on denoising, and its restoration score is simply absent
+ del scores["a"]["reverb_real"]
+ axis_scores_3, comp3, order3 = tiny_board.rank(scores, tiers)
+ assert comp3["a"] == pytest.approx(
+ comp["a"]) and order3["full"] == ["a", "b"]
+ assert math.isnan(ranking.board_scores(axis_scores_3["a"])["restoration"])
+ assert "a" not in ranking.incomplete(scores, axis_scores_3, comp3,
+ tiers).get("full", {})
+ # without a denoising axis it is not ranked
+ del scores["a"]["babble@+4"]
+ _, comp4, order4 = tiny_board.rank(scores, tiers)
+ assert math.isnan(comp4["a"]) and order4["full"] == ["b"]
+ labels = {"a": ("full", "A"), "b": ("full", "B")}
+ # the band axis is scored beside both boards: its own table, its own order;
+ # a section can also list the board by any axis
+ beside = tables.markdown_outside(axis_scores, {"full": ["a", "b"]}, labels)
+ assert beside.startswith("| # | system | band |")
+ by_voices = tables.markdown_outside(axis_scores, {"full": ["a", "b"]},
+ labels,
+ axes=["voices"])
+ voices_table = by_voices[by_voices.index("| # | system | voices |"):]
+ assert (voices_table.count("\n| ") == 2 and "| A |" in voices_table and
+ "| B |" in voices_table)
+
+
+def test_axis_ties_name_the_systems_inside_a_declared_band():
+ assert ranking.TIE_BANDS == {"timbre": 0.05}
+ axis_scores = {
+ "a": {
+ "timbre": 0.76
+ },
+ "b": {
+ "timbre": 0.72
+ },
+ "c": {
+ "timbre": 0.70
+ },
+ "d": {
+ "timbre": float("nan")
+ },
+ }
+ tiers = {n: ("full", n.upper()) for n in axis_scores}
+ assert ranking.axis_ties(axis_scores, list(axis_scores), tiers) == {
+ "timbre": ["A", "B"]
+ }
+ # one system inside the band is no tie
+ assert not ranking.axis_ties(axis_scores, ["a", "c"], tiers)
+ assert not ranking.axis_ties(axis_scores, [], tiers)
+
+
+def test_pooled_rows_feed_an_axis_only_complete_and_with_their_counts():
+ # pylint: disable=protected-access
+ scores = {
+ "s": {
+ "_real_cleanup": {
+ "pause_resid_db": -10.0,
+ "n": 121,
+ "n_missing": 0
+ },
+ "_real_quality": {
+ "nisqa_mos": 3.0,
+ "n": 23,
+ "metric_counts": {
+ "nisqa_mos": 23
+ },
+ },
+ "_deletion": {
+ "pct": 0.2,
+ "n_segments": 452,
+ "cohort_items": 210,
+ "complete": True
+ },
+ }
+ }
+ assert ranking._covered(scores, "s", "_real_cleanup", "pause_resid_db")
+ assert ranking._covered(scores, "s", "_real_quality", "nisqa_mos")
+ assert ranking._covered(scores, "s", "_deletion", "pct")
+ # an item the sidecar did not get back: an incomplete row, not a mean
+ scores["s"]["_real_cleanup"]["n_missing"] = 1
+ assert not ranking._covered(scores, "s", "_real_cleanup", "pause_resid_db")
+ # too few items behind the pooled row
+ scores["s"]["_real_cleanup"].update(n_missing=0, n=ranking.MIN_ITEMS - 1)
+ assert not ranking._covered(scores, "s", "_real_cleanup", "pause_resid_db")
+ scores["s"]["_real_quality"]["metric_missing"] = {"nisqa_mos": 2}
+ assert not ranking._covered(scores, "s", "_real_quality", "nisqa_mos")
+ # the deletion row answers to its own completeness on the frozen cohort,
+ # and to the segments that cohort holds
+ scores["s"]["_deletion"]["n_segments"] = ranking.MIN_ITEMS - 1
+ assert not ranking._covered(scores, "s", "_deletion", "pct")
+ scores["s"]["_deletion"].update(n_segments=452, complete=False)
+ assert not ranking._covered(scores, "s", "_deletion", "pct")
+ assert ranking.MIN_ITEMS == 20
+
+
+def test_a_system_that_restores_above_the_band_is_ranked_on_restoration(
+ tmp_path):
+ tiny_board.write(tmp_path, "a", tiny_board.metrics(10.0), deletion_pct=1.0)
+ restorer = tiny_board.metrics(5.0)
+ for cond, _ in scorefiles.BAND_LIMITED_ROWS:
+ if cond in restorer:
+ restorer[cond]["band_kept_db"] = [0, 0, 0, 40.0, 40.0, 40.0, 40.0]
+ tiny_board.write(tmp_path, "r", restorer, deletion_pct=1.0)
+ tiers = {"a": ("full", "a"), "r": ("full", "r")}
+ scores = scorefiles.load(str(tmp_path))
+ assert ranking.board_of(scores["a"]) == "denoising"
+ assert ranking.board_of(scores["r"]) == "restoration"
+ axis_scores, comp, order = tiny_board.rank(scores, tiers)
+ # each board ranks its own systems by its own score; both are scored on
+ # both
+ assert order["full"] == ["a"] and order["restoration"] == ["r"]
+ assert comp["a"] == pytest.approx(
+ ranking.board_scores(axis_scores["a"])["denoising"])
+ assert comp["r"] == pytest.approx(
+ ranking.board_scores(axis_scores["r"])["restoration"])
+ assert ranking.board_scores(axis_scores["r"])["denoising"] > 0
+ assert "r" not in ranking.incomplete(scores, axis_scores, comp,
+ tiers).get("full", {})
+
+
+def test_a_system_without_band_limited_rows_is_ranked_on_no_board(tmp_path):
+ tiny_board.write(tmp_path, "a", tiny_board.metrics(10.0), deletion_pct=1.0)
+ blind = tiny_board.metrics(12.0)
+ for cond, _ in scorefiles.BAND_LIMITED_ROWS:
+ blind.pop(cond, None)
+ tiny_board.write(tmp_path, "blind", blind, deletion_pct=1.0)
+ tiers = {"a": ("full", "a"), "blind": ("full", "blind")}
+ scores = scorefiles.load(str(tmp_path))
+ axis_scores, comp, order = tiny_board.rank(scores, tiers)
+ # complete and better on denoising, yet missing evidence of the band it
+ # adds is not evidence that it adds none
+ assert ranking.board_of(scores["blind"]) is None
+ assert ranking.board_scores(axis_scores["blind"])["denoising"] > comp["a"]
+ assert order["full"] == ["a"] and order["restoration"] == []
+ assert math.isnan(comp["blind"])
+ reasons = ranking.incomplete(scores, axis_scores, comp,
+ tiers)["full"]["blind"]
+ assert reasons[0] == ("no board: the band-limited rows (srsweep_8k,"
+ " srsweep_16k, srsweep_24k) that assign one are"
+ " missing")
+
+
+def test_a_16k_system_the_rule_sends_to_restoration_is_reported_not_dropped(
+ tmp_path):
+ tiny_board.write(tmp_path, "a", tiny_board.metrics(10.0), deletion_pct=1.0)
+ restorer = tiny_board.metrics(10.0)
+ for cond, _ in scorefiles.BAND_LIMITED_ROWS:
+ if cond in restorer:
+ restorer[cond]["band_kept_db"] = [0, 0, 0, 40.0, 40.0, 40.0, 40.0]
+ tiny_board.write(tmp_path, "narrow", restorer, deletion_pct=1.0)
+ tiers = {"a": ("full", "a"), "narrow": ("nb", "N")}
+ scores = scorefiles.load(str(tmp_path))
+ axis_scores, comp, order = tiny_board.rank(scores, tiers)
+ assert ranking.board_of(scores["narrow"]) == "restoration"
+ assert "narrow" not in order["nb"] + order["restoration"]
+ reasons = ranking.incomplete(scores, axis_scores, comp,
+ tiers)["nb"]["narrow"]
+ assert reasons[0] == ("assigned to restoration, which ranks the full-band"
+ " tier only")
+
+
+def test_the_rule_that_assigns_a_board_is_the_registrys():
+ assert ranking.ASSIGN == {
+ "by": "band_above_input_db",
+ "above_db": 10.0,
+ "board": "restoration",
+ "otherwise": "denoising",
+ }
+ assert ranking.AXES_REGISTRY["version"] == "0"
+ rule = ranking.composite_rule()
+ assert ("is ranked on restoration, every other on denoising, one without"
+ " those rows on neither" in rule)
diff --git a/tests/bench/scripts/test_roster.py b/tests/bench/scripts/test_roster.py
new file mode 100644
index 0000000..beb96f0
--- /dev/null
+++ b/tests/bench/scripts/test_roster.py
@@ -0,0 +1,42 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The board's roster: every system in one tier, under a label of its own."""
+
+import roster
+
+
+def test_every_system_has_a_known_tier_and_a_label_of_its_own():
+ tiers = {tier for tier, _ in roster.TIERS.values()}
+ labels = [label for _, label in roster.TIERS.values()]
+ assert tiers <= {"full", "nb", "ref"}
+ assert len(set(labels)) == len(labels) and all(labels)
+ # the unprocessed input and the clean reference are shown, never ranked
+ assert roster.TIERS["INPUT"][0] == roster.TIERS["REF"][0] == "ref"
+
+
+def test_a_tiers_file_adds_systems_and_relabels_registered_ones(tmp_path):
+ path = tmp_path / "tiers.json"
+ path.write_text(
+ '{"candidate": ["full", "Candidate (1M)"], "dfn3": ["ref", "DFN3"]}',
+ encoding="utf-8")
+ tiers = roster.tiers(str(path))
+ assert tiers["candidate"] == ("full", "Candidate (1M)")
+ assert tiers["dfn3"] == ("ref", "DFN3")
+ assert roster.tiers() == roster.TIERS
+ assert roster.TIERS["dfn3"] == ("full", "DeepFilterNet3")
+
+
+def test_display_name_drops_the_parenthesised_details():
+ assert roster.display_name("voice_isolator_v0") == "Inworld Voice Isolator"
+ assert roster.display_name("unregistered") == "unregistered"
diff --git a/tests/bench/scripts/test_runsystem.py b/tests/bench/scripts/test_runsystem.py
new file mode 100644
index 0000000..73a3b4c
--- /dev/null
+++ b/tests/bench/scripts/test_runsystem.py
@@ -0,0 +1,563 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Our renderer is held to a wrapper's rules.
+
+Receipts before rendering, whole outputs, resume only under one identity, a
+stamp once the selection is complete; linked systems are links.
+"""
+
+# pylint: disable=redefined-outer-name
+
+import contextlib
+import dataclasses
+import hashlib
+import json
+import os
+import socket
+import sys
+
+import numpy as np
+import pytest
+import soundfile as sf
+import torch
+
+import common
+import receipt
+import runsystem
+import stamprender
+
+REPO = os.path.dirname(
+ os.path.dirname(os.path.dirname(os.path.dirname(
+ os.path.abspath(__file__)))))
+
+
+def test_public_path_is_repo_relative_inside_and_basename_outside(tmp_path):
+ inside = os.path.join(REPO, "models", "x.safetensors")
+ # registry names pass through
+ assert runsystem.public_path("voice-isolator-v1") == "voice-isolator-v1"
+ assert runsystem.public_path(None) is None
+ outside = tmp_path / "secret_dir" / "ckpt.safetensors"
+ outside.parent.mkdir()
+ outside.write_bytes(b"x")
+ assert runsystem.public_path(str(outside)) == "ckpt.safetensors"
+ if os.path.exists(inside):
+ assert runsystem.public_path(inside) == os.path.join(
+ "models", "x.safetensors")
+
+
+def test_weights_digest_matches_sha256_of_file_and_of_model_pt_in_dir(tmp_path):
+ f = tmp_path / "w.safetensors"
+ f.write_bytes(b"weights" * 1000)
+ digest = runsystem.weights_digest(str(f))
+ assert digest == hashlib.sha256(b"weights" * 1000).hexdigest()
+ d = tmp_path / "export"
+ d.mkdir()
+ (d / "model.pt").write_bytes(b"pt")
+ assert runsystem.weights_digest(str(d)) == hashlib.sha256(b"pt").hexdigest()
+
+
+def test_a_folder_is_resumed_only_under_its_own_identity(tmp_path, capsys):
+ out = tmp_path / "out"
+ ident = {"system": "x", "weights_sha256": {"w": "1"}, "inputs": {"s": 1}}
+ other = dict(ident, weights_sha256={"w": "2"})
+ # empty: this process's receipt is written, nothing else
+ assert runsystem.prepare(str(out), ident, [],
+ False) == receipt.digest(ident)
+ assert [d["digest"] for d in receipt.read_all(str(out))
+ ] == [receipt.digest(ident)]
+ (out / "0.wav").write_bytes(b"")
+ # the same identity resumes
+ runsystem.prepare(str(out), ident, [], overwrite=False)
+ assert (out / "0.wav").exists()
+ # another identity's outputs are discarded, what differed named
+ (out / ".partial-x.wav").write_bytes(b"")
+ runsystem.prepare(str(out), other, [], overwrite=False)
+ assert not (out / "0.wav").exists()
+ assert not (out / ".partial-x.wav").exists()
+ assert "the weights differ" in capsys.readouterr().out
+ assert {d["digest"] for d in receipt.read_all(str(out))
+ } == {receipt.digest(other)}
+ # outputs without a receipt are of unknown origin: nothing is removed
+ for path in out.glob(".receipt-*"):
+ path.unlink()
+ (out / "1.wav").write_bytes(b"")
+ with pytest.raises(SystemExit, match="without a receipt"):
+ runsystem.prepare(str(out), other, [], overwrite=False)
+ assert (out / "1.wav").exists()
+ # --overwrite clears outputs and receipts whatever their identity
+ runsystem.prepare(str(out), other, [], overwrite=True)
+ assert [p.name[:9] for p in out.iterdir()] == [".receipt-"]
+ assert not (out / ".prepare-lock").exists()
+
+
+def _tiny_set(tmp_path, n=3):
+ root = tmp_path / "set"
+ (root / "mix").mkdir(parents=True)
+ g = torch.Generator().manual_seed(0)
+ rows = []
+ for i in range(n):
+ x = (torch.randn(int(0.5 * 48000), generator=g) * 0.1).numpy()
+ sf.write(root / "mix" / f"clean_{i:03d}.wav", x, 48000, subtype="FLOAT")
+ rows.append({
+ "id": f"clean_{i:03d}.wav",
+ "condition": "clean",
+ "mix_path": f"mix/clean_{i:03d}.wav",
+ })
+ manifest = "\n".join(json.dumps(r) for r in rows) + "\n"
+ (root / "manifest.jsonl").write_text(manifest)
+ (root / "checksums.json").write_text(
+ json.dumps({
+ "set_id": "tiny-set-0001",
+ "n_items": n,
+ "files": {}
+ }))
+ return root
+
+
+def _tiny_checkpoint(tmp_path, model):
+ # pylint: disable-next=import-outside-toplevel
+ import safetensors.torch
+
+ cfg = dataclasses.asdict(model.config)
+ st = {k: v.contiguous() for k, v in model.state_dict().items()}
+ path = tmp_path / "tiny.safetensors"
+ safetensors.torch.save_file(st,
+ str(path),
+ metadata={"config": json.dumps(cfg)})
+ return str(path)
+
+
+def bench(tmp_path, monkeypatch, identity_model):
+ root = _tiny_set(tmp_path)
+ out_root, results = tmp_path / "out", tmp_path / "results"
+ monkeypatch.setattr(common, "EVAL", str(root))
+ monkeypatch.setattr(common, "OUT_ROOT", str(out_root))
+ monkeypatch.setattr(common, "RESULTS", str(results))
+ monkeypatch.setattr(common, "DEV", "cpu")
+ ckpt = _tiny_checkpoint(tmp_path, identity_model)
+ return root, out_root, results, ckpt
+
+
+def _run(monkeypatch, argv):
+ monkeypatch.setattr(sys, "argv", ["runsystem.py"] + argv)
+ return runsystem.main()
+
+
+def test_shards_render_once_each_and_the_last_one_stamps(
+ bench, monkeypatch, capsys):
+ _, out_root, results, ckpt = bench
+ base = ["--name", "tiny", "--model", ckpt]
+ assert _run(monkeypatch, base + ["--batch", "2", "--shard", "0/2"]) == 0
+ # one item still missing: no stamp yet
+ assert not (results / "tiny.meta.json").exists()
+ assert ("the run that completes the selection stamps it"
+ in capsys.readouterr().out)
+ assert _run(monkeypatch, base + ["--batch", "2", "--shard", "1/2"]) == 0
+ outs = sorted((out_root / "tiny").glob("*.wav"))
+ assert [p.name for p in outs] == [f"clean_{i:03d}.wav" for i in range(3)]
+ info = sf.info(str(outs[0]))
+ assert (info.subtype == "FLOAT" and info.frames == 24000 and
+ info.samplerate == 48000)
+ meta = json.load(open(results / "tiny.meta.json", encoding="utf-8"))
+ assert (meta["set_id"] == "tiny-set-0001" and meta["subset"] == "all" and
+ meta["batch"] == 2)
+ assert meta["weights"] == "tiny.safetensors"
+ assert meta["mode"] == "offline" and meta["lookahead_frames"] == 0
+ assert meta["window_frames"] is None and meta["crossfade_frames"] is None
+ with open(ckpt, "rb") as fh:
+ weights = fh.read()
+ assert meta["weights_sha256"] == hashlib.sha256(weights).hexdigest()
+ assert (meta["wrapper"] == "bench/scripts/runsystem.py" and
+ meta["n_files"] == 3)
+ ident = meta["render_receipt"]["identity"]
+ assert ident["weights_sha256"] == {
+ "tiny.safetensors": meta["weights_sha256"]
+ }
+ assert list(ident["package_code_sha256"]) == ["inworld.voice_isolation"]
+ # one per process: both shards ran here
+ assert meta["render_receipt"]["n_receipts"] == 1
+
+
+def test_a_rerun_resumes_and_another_identity_or_set_build_renders_again(
+ bench, monkeypatch, capsys):
+ root, out_root, _, ckpt = bench
+ base = ["--name", "tiny", "--model", ckpt]
+ assert _run(monkeypatch, base) == 0
+ outs = sorted((out_root / "tiny").glob("*.wav"))
+ before = {p.name: p.stat().st_mtime_ns for p in outs}
+ assert _run(monkeypatch, base) == 0
+ assert {p.name: p.stat().st_mtime_ns for p in outs} == before
+ assert "discarded" not in capsys.readouterr().out
+ # other arguments: the outputs are discarded and rendered again
+ assert _run(monkeypatch, base + ["--chunk-seconds", "0.25"]) == 0
+ again = {p.name: p.stat().st_mtime_ns for p in outs}
+ assert set(again) == set(before)
+ assert all(again[k] > before[k] for k in again)
+ assert "the arguments differ" in capsys.readouterr().out
+ # another build of the set likewise
+ checksums = {"set_id": "tiny-set-0002"}
+ (root / "checksums.json").write_text(json.dumps(checksums))
+ assert _run(monkeypatch, base + ["--chunk-seconds", "0.25"]) == 0
+ assert "the inputs" in capsys.readouterr().out
+ with pytest.raises(SystemExit):
+ _run(monkeypatch, base + ["--overwrite", "--shard", "0/2"])
+ assert _run(monkeypatch, base + ["--overwrite"]) == 0
+
+
+def test_batches_match_the_one_clip_path(bench, monkeypatch):
+ _, out_root, _, ckpt = bench
+ assert (_run(
+ monkeypatch,
+ [
+ "--name",
+ "batched",
+ "--model",
+ ckpt,
+ "--batch",
+ "3",
+ ],
+ ) == 0)
+ assert _run(monkeypatch, ["--name", "single", "--model", ckpt]) == 0
+ a = sf.read(str(out_root / "batched" / "clean_000.wav"), dtype="float32")[0]
+ b = sf.read(str(out_root / "single" / "clean_000.wav"), dtype="float32")[0]
+ assert abs(a - b).max() < 1e-5
+
+
+def test_explicit_zero_overlap_is_recorded_as_zero(bench, monkeypatch):
+ _, _, results, ckpt = bench
+ assert (_run(
+ monkeypatch,
+ [
+ "--name",
+ "z",
+ "--model",
+ ckpt,
+ "--overlap-seconds",
+ "0",
+ "--chunk-seconds",
+ "0.25",
+ ],
+ ) == 0)
+ meta = json.load(open(results / "z.meta.json", encoding="utf-8"))
+ assert meta["overlap_seconds"] == 0.0 and meta["chunk_seconds"] == 0.25
+
+
+def test_the_probe_folder_is_rendered_under_receipts_naming_its_inputs(
+ bench, monkeypatch, tmp_path):
+ _, out_root, results, ckpt = bench
+ probe = tmp_path / "probe"
+ (probe / "in").mkdir(parents=True)
+ (probe / "probe.json").write_text(json.dumps({"identity": "probe-1"}))
+ g = torch.Generator().manual_seed(1)
+ for name in ("longATp4_000__tail.wav", "longATp4_000__future.wav"):
+ sf.write(
+ probe / "in" / name,
+ (torch.randn(36000, generator=g) * 0.1).numpy(),
+ 48000,
+ subtype="FLOAT",
+ )
+ base = ["--name", "tiny", "--model", ckpt]
+ assert _run(monkeypatch, base + ["--inputs", str(probe / "in")]) == 0
+ outs = sorted(p.name for p in (out_root / "tiny").glob("*.wav"))
+ assert outs == ["longATp4_000__future.wav", "longATp4_000__tail.wav"]
+ # a probe render is never stamped
+ assert not (results / "tiny.meta.json").exists()
+ docs = receipt.read_all(str(out_root / "tiny"))
+ assert docs[0]["identity"]["inputs"] == {"probe": "probe-1"}
+ # another probe cut: the outputs are discarded and rendered again
+ (probe / "probe.json").write_text(json.dumps({"identity": "probe-2"}))
+ assert _run(monkeypatch, base + ["--inputs", str(probe / "in")]) == 0
+ docs = receipt.read_all(str(out_root / "tiny"))
+ assert [d["identity"]["inputs"] for d in docs] == [{"probe": "probe-2"}]
+ with pytest.raises(SystemExit): # only a model or the hint can be probed
+ _run(
+ monkeypatch,
+ ["--name", "INPUT", "--input", "--inputs",
+ str(probe / "in")],
+ )
+ with pytest.raises(SystemExit):
+ _run(monkeypatch, base + ["--inputs", str(tmp_path / "nowhere")])
+
+
+def test_reference_renderer_uses_only_refs_and_never_real_mixtures(
+ tmp_path, monkeypatch):
+ root = _tiny_set(tmp_path, n=2)
+ (root / "ref").mkdir()
+ rows = [
+ json.loads(line)
+ for line in (root / "manifest.jsonl").read_text().splitlines()
+ ]
+ rows[0]["clean_path"] = "ref/clean_000.wav"
+ (root / rows[0]["clean_path"]).write_bytes(b"reference bytes")
+ rows[1]["condition"] = "real_noisy"
+ (root / "manifest.jsonl").write_text("".join(
+ json.dumps(r) + "\n" for r in rows))
+ outputs = tmp_path / "outputs"
+ monkeypatch.setattr(common, "EVAL", str(root))
+ monkeypatch.setattr(common, "OUT_ROOT", str(outputs))
+ monkeypatch.setattr(common, "RESULTS", str(tmp_path / "results"))
+ assert _run(monkeypatch, ["--name", "REF", "--reference"]) == 0
+ assert (outputs / "REF" / rows[0]["id"]).read_bytes() == b"reference bytes"
+ assert not (outputs / "REF" / rows[1]["id"]).exists()
+ meta = json.load(
+ open(tmp_path / "results" / "REF.meta.json", encoding="utf-8"))
+ assert meta["reference"] is True and meta["n_files"] == 1
+ (root / rows[0]["clean_path"]).unlink()
+ with pytest.raises(SystemExit):
+ _run(monkeypatch, ["--name", "REF", "--reference"])
+
+
+def test_a_folder_of_outputs_is_linked_in_only_when_complete(
+ tmp_path, monkeypatch):
+ root = _tiny_set(tmp_path, n=2)
+ elsewhere = tmp_path / "elsewhere"
+ elsewhere.mkdir()
+ sf.write(elsewhere / "clean_000.wav", np.zeros(4800, dtype="float32"),
+ 48000)
+ outputs, results = tmp_path / "outputs", tmp_path / "results"
+ monkeypatch.setattr(common, "EVAL", str(root))
+ monkeypatch.setattr(common, "OUT_ROOT", str(outputs))
+ monkeypatch.setattr(common, "RESULTS", str(results))
+ argv = ["--name", "theirs", "--outputs", str(elsewhere)]
+ # one of two items missing: nothing is linked
+ with pytest.raises(SystemExit):
+ _run(monkeypatch, argv)
+ assert not (outputs / "theirs").exists() or not list(
+ (outputs / "theirs").glob("*.wav"))
+ sf.write(elsewhere / "clean_001.wav", np.zeros(4800, dtype="float32"),
+ 48000)
+ assert _run(monkeypatch, argv) == 0
+ assert sorted(p.name for p in (outputs / "theirs").glob("*.wav")) == [
+ "clean_000.wav",
+ "clean_001.wav",
+ ]
+ assert os.path.realpath(outputs / "theirs" / "clean_000.wav") == str(
+ elsewhere / "clean_000.wav")
+ meta = json.load(open(results / "theirs.meta.json", encoding="utf-8"))
+ assert (meta["mechanism"] == "rendered elsewhere" and
+ meta["source"] == "elsewhere")
+ assert meta["set_id"] == "tiny-set-0001"
+ assert meta["source_sha256"] == runsystem.folder_digest(str(elsewhere))
+ # the outputs digest a computed render's stamp records, over the same files
+ assert meta["outputs_sha256"] == stamprender.outputs_digest(
+ sorted((outputs / "theirs").glob("*.wav")), str(outputs / "theirs"))
+ # another folder of the same name cannot resume into the same system
+ other = tmp_path / "b" / "elsewhere"
+ other.mkdir(parents=True)
+ for name in ("clean_000.wav", "clean_001.wav"):
+ sf.write(other / name, np.full(4800, 0.5, dtype="float32"), 48000)
+ with pytest.raises(SystemExit, match="not links"):
+ _run(monkeypatch, ["--name", "theirs", "--outputs", str(other)])
+ assert os.path.realpath(outputs / "theirs" / "clean_000.wav") == str(
+ elsewhere / "clean_000.wav")
+ assert (_run(
+ monkeypatch,
+ ["--name", "theirs", "--outputs",
+ str(other), "--overwrite"],
+ ) == 0)
+ assert os.path.realpath(outputs / "theirs" / "clean_000.wav") == str(
+ other / "clean_000.wav")
+ with open(results / "theirs.meta.json", encoding="utf-8") as fh:
+ meta = json.load(fh)
+ assert meta["source_sha256"] == runsystem.folder_digest(str(other))
+
+
+def test_a_panel_subset_renders_only_its_items(tmp_path, monkeypatch):
+ root = _tiny_set(tmp_path, n=3)
+ outputs = tmp_path / "outputs"
+ monkeypatch.setattr(common, "EVAL", str(root))
+ monkeypatch.setattr(common, "OUT_ROOT", str(outputs))
+ monkeypatch.setattr(common, "RESULTS", str(tmp_path / "results"))
+ monkeypatch.setattr(common, "SUBSET", "gate")
+ monkeypatch.setattr(common,
+ "panel_members",
+ lambda name, root=None: {"clean_001.wav"})
+ assert _run(monkeypatch, ["--name", "INPUT", "--input"]) == 0
+ names = [p.name for p in (outputs / "INPUT").glob("*.wav")]
+ assert names == ["clean_001.wav"]
+ with open(tmp_path / "results" / "INPUT.meta.json", encoding="utf-8") as fh:
+ meta = json.load(fh)
+ assert meta["subset"] == "gate"
+
+
+def test_a_folder_another_identity_is_still_rendering_is_refused(
+ bench, monkeypatch, capsys):
+ """A live foreign render is never discarded under its process."""
+ _, out_root, _, ckpt = bench
+ base = ["--name", "tiny", "--model", ckpt]
+ assert _run(monkeypatch, base) == 0
+ out_dir = out_root / "tiny"
+ # a receipt of another identity whose process (this one's parent, alive
+ # for the test's duration) still runs
+ own = json.load(open(receipt.own_path(str(out_dir)), encoding="utf-8"))
+ own["digest"] = "0" * 64
+ own["identity"] = dict(own["identity"], system="other")
+ own["pid"] = os.getppid()
+ own["process_start"] = receipt.process_start(os.getppid())
+ (out_dir / ".receipt-elsewhere-424242.json").write_text(json.dumps(own))
+
+ with pytest.raises(SystemExit, match="still rendering"):
+ _run(monkeypatch, base + ["--chunk-seconds", "0.25"])
+ # --overwrite takes the folder regardless
+ assert _run(monkeypatch,
+ base + ["--chunk-seconds", "0.25", "--overwrite"]) == 0
+ assert "still rendering" not in capsys.readouterr().out
+
+
+def test_a_render_whose_receipt_is_gone_stops_before_writing(bench):
+ root, out_root, _, _ = bench
+ files = sorted(str(p) for p in (root / "mix").glob("*.wav"))
+ out_dir = out_root / "taken"
+ ident = {"system": "taken", "digest": "x"}
+ runsystem.prepare(str(out_dir), ident, [], False)
+ os.remove(receipt.own_path(str(out_dir))) # another identity took over
+
+ with pytest.raises(SystemExit, match="receipt is gone"):
+ runsystem.render(files, str(out_dir), lambda x: x, None, 1)
+ assert not list(out_dir.glob("*.wav"))
+
+
+def test_linking_the_input_over_a_render_leaves_no_receipt_to_resume(
+ bench, monkeypatch, capsys):
+ """After --input --overwrite, the model's command renders again instead of
+ stamping the linked mixtures as its own."""
+ _, out_root, results, ckpt = bench
+ model = ["--name", "tiny", "--model", ckpt]
+ assert _run(monkeypatch, model) == 0
+ assert _run(monkeypatch, ["--name", "tiny", "--input", "--overwrite"]) == 0
+ assert all(p.is_symlink() for p in (out_root / "tiny").glob("*.wav"))
+
+ assert _run(monkeypatch, model) == 0
+
+ outputs = sorted((out_root / "tiny").glob("*.wav"))
+ assert outputs and not any(p.is_symlink() for p in outputs)
+ meta = json.load(open(results / "tiny.meta.json", encoding="utf-8"))
+ assert meta["weights"].endswith("tiny.safetensors")
+ assert "3 to do" in capsys.readouterr().out
+
+
+def test_an_export_folder_renders_the_checkpoint_it_holds(
+ bench, monkeypatch, identity_model, tmp_path):
+ _, _, results, _ = bench
+ export = tmp_path / "export"
+ export.mkdir()
+ torch.save(
+ {
+ "model": identity_model.state_dict(),
+ "config": dataclasses.asdict(identity_model.config)
+ }, export / "model.pt")
+
+ assert _run(monkeypatch, ["--name", "exp", "--model", str(export)]) == 0
+
+ meta = json.load(open(results / "exp.meta.json", encoding="utf-8"))
+ assert meta["weights_sha256"] == runsystem.weights_digest(str(export))
+
+
+def test_the_stamp_names_the_window_the_render_used(bench, monkeypatch):
+ _, _, results, ckpt = bench
+
+ assert _run(monkeypatch, [
+ "--name", "tiny", "--model", ckpt, "--chunk-seconds", "0.25",
+ "--overlap-seconds", "0.05"
+ ]) == 0
+
+ meta = json.load(open(results / "tiny.meta.json", encoding="utf-8"))
+ assert "0.25 s windows, 0.05 s crossfades" in meta["mechanism"]
+ assert meta["chunk_seconds"] == 0.25
+
+
+def _watched_lock(monkeypatch):
+ """Wraps runsystem.taken so a test sees when the folder's lock is held."""
+ held, real = [], runsystem.taken
+
+ @contextlib.contextmanager
+ def taken(out_dir, wait=300.0):
+ with real(out_dir, wait):
+ held.append(out_dir)
+ try:
+ yield
+ finally:
+ held.pop()
+
+ monkeypatch.setattr(runsystem, "taken", taken)
+ return held
+
+
+def test_every_output_is_published_under_the_folders_lock(bench, monkeypatch):
+ """The receipt re-check and the write happen inside one hold of the lock
+ a takeover (prepare with another identity, or --overwrite) must take
+ first, so the takeover cannot slip in between them."""
+ root, out_root, _, _ = bench
+ files = sorted(str(p) for p in (root / "mix").glob("*.wav"))
+ out_dir = out_root / "locked"
+ runsystem.prepare(str(out_dir), {"system": "locked"}, [], False)
+ held = _watched_lock(monkeypatch)
+ real_save, seen = runsystem.writer.save, []
+
+ def save(path, samples, sr):
+ seen.append(
+ (bool(held), os.path.exists(receipt.own_path(str(out_dir)))))
+ real_save(path, samples, sr)
+
+ monkeypatch.setattr(runsystem.writer, "save", save)
+
+ assert runsystem.render(files, str(out_dir), lambda x: x, None, 1) == 3
+
+ assert seen == [(True, True)] * 3
+ assert not (out_dir / ".prepare-lock").exists()
+
+
+def test_linking_in_outputs_holds_the_folders_lock(bench, monkeypatch):
+ _, out_root, _, ckpt = bench
+ assert _run(monkeypatch, ["--name", "tiny", "--model", ckpt]) == 0
+ held = _watched_lock(monkeypatch)
+ real_symlink, seen = os.symlink, []
+
+ def symlink(src, dst):
+ seen.append(bool(held))
+ real_symlink(src, dst)
+
+ monkeypatch.setattr(os, "symlink", symlink)
+
+ assert _run(monkeypatch, ["--name", "tiny", "--input", "--overwrite"]) == 0
+
+ assert seen == [True] * 3
+ assert not (out_root / "tiny" / ".prepare-lock").exists()
+
+
+def test_a_live_process_is_known_by_its_pid_and_start_time(monkeypatch):
+ """A reused pid is another process; a process the signal may not reach is
+ alive; an old receipt without a start time is judged by its pid alone."""
+ host, parent = socket.gethostname(), os.getppid()
+ start = receipt.process_start(parent)
+ if start is None:
+ pytest.skip("needs a process's start time, which only Linux's /proc"
+ " gives")
+ live = {"host": host, "pid": parent, "process_start": start}
+ reused = {"host": host, "pid": parent, "process_start": "1"}
+ old = {"host": host, "pid": parent}
+ gone = {"host": host, "pid": 2**22 - 1, "process_start": start}
+
+ assert runsystem.process_alive(live)
+ assert runsystem.process_alive(old)
+ assert not runsystem.process_alive(reused)
+ assert not runsystem.process_alive(gone)
+ assert not runsystem.process_alive({"host": "elsewhere", "pid": parent})
+
+ def denied(pid, sig):
+ raise PermissionError
+
+ monkeypatch.setattr(os, "kill", denied)
+ assert runsystem.process_alive(live)
diff --git a/tests/bench/scripts/test_scoreasr.py b/tests/bench/scripts/test_scoreasr.py
new file mode 100644
index 0000000..1cb1176
--- /dev/null
+++ b/tests/bench/scripts/test_scoreasr.py
@@ -0,0 +1,747 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Downstream-ASR sidecar: edit distance, pooling, references and the cache.
+
+Golden references and their fallback, with a fake recogniser that reads its
+transcript from a text file next to the audio.
+"""
+
+# pylint: disable=redefined-outer-name,unused-argument
+
+import json
+import math
+import os
+import shutil
+import time
+import zlib
+
+import pytest
+import soundfile as sf
+import torch
+
+import common
+import scoreasr
+import scorebench
+
+SR = common.SR
+
+
+class _Norm:
+ """Stands in for Whisper's normaliser.
+
+ Lower case, no punctuation; characters for zh/ja.
+ """
+
+ def tokens(self, text, language):
+ clean = "".join(ch.lower() if ch.isalnum() or ch.isspace() else " "
+ for ch in text or "")
+ if language in scoreasr.CHAR_LANGS:
+ return [ch for ch in clean if not ch.isspace()]
+ return clean.split()
+
+
+class _Asr:
+ """Transcribes by reading ``<audio>.txt``.
+
+ Counts calls so the cache can be checked.
+ """
+
+ tag = "fake"
+ identity = {"engine": "fake", "model": "fake"}
+
+ def __init__(self):
+ self.calls = 0
+
+ def transcribe(self, path, language=None):
+ self.calls += 1
+ with open(path + ".txt", encoding="utf-8") as fh:
+ return fh.read()
+
+
+def test_edit_distance_on_words_and_characters():
+ assert scoreasr.edit_distance([], []) == 0
+ assert scoreasr.edit_distance("a b c".split(), "a b c".split()) == 0
+ # substitution
+ assert scoreasr.edit_distance("a b c".split(), "a x c".split()) == 1
+ # deletion
+ assert scoreasr.edit_distance("a b c".split(), "a c".split()) == 1
+ # insertion
+ assert scoreasr.edit_distance("a c".split(), "a b c".split()) == 1
+ # an empty hypothesis: every word lost
+ assert scoreasr.edit_distance([], "a b c".split()) == 3
+ assert scoreasr.edit_distance(list("kitten"), list("sitting")) == 3
+ assert (scoreasr.unit_for("zh") == "char" and
+ scoreasr.unit_for("en") == "word")
+
+
+def test_pooled_rate_and_bootstrap_interval():
+ items = {"a": [1, 10], "b": [0, 10], "c": [3, 10]}
+ rate, e, n = scoreasr.pooled(items)
+ assert (rate, e, n) == (pytest.approx(100 * 4 / 30), 4, 30)
+ lo, hi = scoreasr.bootstrap_ci(items, n_boot=200)
+ assert lo <= rate <= hi and lo >= 0
+ # one item: no interval
+ assert all(math.isnan(v) for v in scoreasr.bootstrap_ci({"a": [1, 10]}))
+ assert math.isnan(scoreasr.pooled({})[0])
+
+
+def _write(path, text, x=None, perturb=False):
+ """Audio plus its fake transcript.
+
+ Outputs are perturbed by a hash of their transcript, so two files that would
+ transcribe differently never share bytes (the cache keys on bytes) while two
+ systems saying the same thing do.
+ """
+ x = torch.zeros(SR // 4) if x is None else x
+ if perturb:
+ x = x * (1 + (zlib.crc32(text.encode()) % 997 + 1) * 1e-6) + 1e-7
+ sf.write(str(path), x.numpy(), SR, subtype="FLOAT")
+ with open(str(path) + ".txt", "w", encoding="utf-8") as fh:
+ fh.write(text)
+
+
+def asr_set(tmp_path, monkeypatch):
+ """A set with three conditions.
+
+ The outputs' transcripts are chosen per system by the test.
+ """
+ root, out_root = tmp_path / "set", tmp_path / "out"
+ (root / "mix").mkdir(parents=True)
+ (root / "ref").mkdir()
+ rows = []
+ specs = [
+ ("clean", "en", "The quick brown fox jumps over the lazy dog"),
+ ("clean", "en", "Hello there, General Kenobi!"),
+ ("babble@-10", "en", "We hold these truths to be self evident"),
+ ("babble@-10", "zh", "今天天气很好"),
+ ("wild@-5", "de", "Guten Morgen liebe Sorgen"),
+ ]
+ for i, (cond, lang, text) in enumerate(specs):
+ rid = f"{cond.replace('@', 'AT')}_{i:03d}.wav"
+ g = torch.Generator().manual_seed(i)
+ _write(root / "ref" / rid, text,
+ torch.randn(SR // 4, generator=g) * 0.1)
+ _write(
+ root / "mix" / rid,
+ text + " noise",
+ torch.randn(SR // 4, generator=g) * 0.2,
+ )
+ rows.append({
+ "id": rid,
+ "condition": cond,
+ "language": lang,
+ "mix_path": f"mix/{rid}",
+ "clean_path": f"ref/{rid}",
+ })
+ with open(root / "manifest.jsonl", "w", encoding="utf-8") as fh:
+ fh.write("".join(json.dumps(r) + "\n" for r in rows))
+ json.dump(
+ {
+ "set_id": "tiny",
+ "n_items": len(rows)
+ },
+ open(root / "checksums.json", "w", encoding="utf-8"),
+ )
+ monkeypatch.setattr(common, "EVAL", str(root))
+ monkeypatch.setattr(common, "OUT_ROOT", str(out_root))
+ monkeypatch.setattr(common, "RESULTS", str(tmp_path / "results"))
+ monkeypatch.setattr(scoreasr, "CACHE_ROOT", str(tmp_path / "cache"))
+ return root, out_root, common.manifest(str(root))
+
+
+def render(rows, out_root, name, fn):
+ """Writes each output as its reference audio.
+
+ Its transcript is ``fn(row)``.
+ """
+ d = out_root / name
+ d.mkdir(parents=True, exist_ok=True)
+ for r in rows:
+ x, _ = sf.read(r["clean_path"], dtype="float32")
+ _write(d / r["id"], fn(r), torch.from_numpy(x), perturb=True)
+
+
+def _golden(rows):
+ return {
+ r["id"]: {
+ "id": r["id"],
+ "text": open(r["clean_path"] + ".txt", encoding="utf-8").read(),
+ "tier": "corpus-verified",
+ } for r in rows
+ }
+
+
+def test_perfect_output_reads_zero_and_a_muted_one_reads_one_hundred(
+ asr_set, tmp_path):
+ _, out_root, rows = asr_set
+ render(
+ rows,
+ out_root,
+ "perfect",
+ lambda r: open(r["clean_path"] + ".txt", encoding="utf-8").read(),
+ )
+ render(rows, out_root, "mute", lambda r: "")
+ asr = _Asr()
+ cache = scoreasr.Cache(str(tmp_path / "cache"), "fake", _Asr.identity)
+ perfect = scoreasr.score_system("perfect", rows, asr, cache, _Norm(),
+ _golden(rows))
+ assert set(perfect) == {"clean", "babble@-10", "wild@-5"}
+ assert all(v["wer_pct"] == 0.0 for v in perfect.values())
+ # one English, one Chinese item
+ assert perfect["babble@-10"]["units"] == {"word": 1, "char": 1}
+ assert perfect["babble@-10"]["reference_tiers"] == {"corpus-verified": 2}
+ metrics = scoreasr.score_system("mute", rows, asr, cache, _Norm(),
+ _golden(rows))
+ assert all(v["wer_pct"] == 100.0 for v in metrics.values())
+ assert metrics["clean"]["ref_tokens"] == 9 + 4
+ assert metrics["clean"]["edits"] == 13
+
+
+def test_a_partly_wrong_output_is_pooled_over_reference_tokens(
+ asr_set, tmp_path):
+ _, out_root, rows = asr_set
+ render(
+ rows,
+ out_root,
+ "half",
+ lambda r: " ".join(
+ # every other word dropped
+ open(r["clean_path"] + ".txt", encoding="utf-8").read().split()[::2]
+ ),
+ )
+ asr = _Asr()
+ cache = scoreasr.Cache(str(tmp_path / "cache"), "fake", _Asr.identity)
+ metrics = scoreasr.score_system("half", rows, asr, cache, _Norm(),
+ _golden(rows))
+ c = metrics["clean"]
+ assert c["items"]["clean_000.wav"] == [
+ 4, 9
+ ] and c["items"]["clean_001.wav"] == [2, 4]
+ assert c["wer_pct"] == pytest.approx(100 * 6 / 13) and c["n"] == 2
+ lo, hi = c["ci95"]
+ assert lo <= c["wer_pct"] <= hi
+
+
+def test_without_golden_text_clean_transcript_is_the_reference_and_is_recorded(
+ asr_set, tmp_path):
+ root, out_root, rows = asr_set
+ render(
+ rows,
+ out_root,
+ "perfect",
+ lambda r: open(r["clean_path"] + ".txt", encoding="utf-8").read(),
+ )
+ asr = _Asr()
+ cache = scoreasr.Cache(str(tmp_path / "cache"), "fake", _Asr.identity)
+ golden = {
+ k: v for k, v in _golden(rows).items() if not k.startswith("wild")
+ }
+ metrics = scoreasr.score_system("perfect", rows, asr, cache, _Norm(),
+ golden)
+ assert metrics["clean"]["reference_tiers"] == {"corpus-verified": 2}
+ assert metrics["wild@-5"]["reference_tiers"] == {scoreasr.FALLBACK: 1}
+ assert metrics["wild@-5"]["wer_pct"] == 0.0
+ # no transcripts.jsonl in this set
+ assert not scoreasr.load_golden(str(root))
+ with open(root / scoreasr.GOLDEN, "w", encoding="utf-8") as fh:
+ fh.write(
+ json.dumps({
+ "id": "wildAT-5_004.wav",
+ "text": "Guten Morgen",
+ "tier": "t"
+ }) + "\n")
+ g = scoreasr.load_golden(str(root))
+ assert g["wildAT-5_004.wav"]["tier"] == "t"
+ metrics_again = scoreasr.score_system("perfect", rows, asr, cache, _Norm(),
+ g)
+ # two extra words against a 2-word gold
+ assert metrics_again["wild@-5"]["wer_pct"] == pytest.approx(100 * 2 / 2)
+
+
+def test_the_cache_transcribes_each_audio_once(asr_set, tmp_path):
+ _, out_root, rows = asr_set
+ render(
+ rows,
+ out_root,
+ "perfect",
+ lambda r: open(r["clean_path"] + ".txt", encoding="utf-8").read(),
+ )
+ asr = _Asr()
+ cache = scoreasr.Cache(str(tmp_path / "cache"), "fake", _Asr.identity)
+ # references + outputs
+ scoreasr.score_system("perfect", rows, asr, cache, _Norm(), {})
+ first = asr.calls
+ assert first == 2 * len(rows) and cache.misses == first and cache.hits == 0
+ scoreasr.score_system("perfect", rows, asr, cache, _Norm(), {})
+ # everything from the cache the second time
+ assert asr.calls == first and cache.hits == first
+ # the same audio under another system name is a hit too (outputs are keyed
+ # by content)
+ # Rebuilding a WAV can change header metadata even with identical samples.
+ shutil.copytree(out_root / "perfect", out_root / "twin")
+ scoreasr.score_system("twin", rows, asr, cache, _Norm(), {})
+ assert asr.calls == first
+
+
+def test_a_transcript_can_name_the_language_actually_spoken(asr_set, tmp_path):
+ """An item labelled German whose audio is English is decoded as English.
+
+ The golden row says so, and both the decoding language and the normaliser
+ follow it; the cache never serves the other decoding.
+ """
+ _, out_root, rows = asr_set
+ wild = [r for r in rows if r["condition"] == "wild@-5"]
+ render(wild, out_root, "sys",
+ lambda r: open(r["clean_path"] + ".txt", encoding="utf-8").read())
+
+ class _Langs(_Asr):
+
+ def __init__(self):
+ super().__init__()
+ self.asked = []
+
+ def transcribe(self, path, language=None):
+ self.asked.append(language)
+ return super().transcribe(path, language)
+
+ asr = _Langs()
+ cache = scoreasr.Cache(str(tmp_path / "cache"), "fake", _Asr.identity)
+ scoreasr.score_system("sys", wild, asr, cache, _Norm(), {})
+ # the manifest's label, as long as nothing says otherwise
+ assert set(asr.asked) == {"de"}
+ golden = {
+ wild[0]["id"]: {
+ "id": wild[0]["id"],
+ "language": "de",
+ "spoken": "en",
+ "text": "Guten Morgen liebe Sorgen",
+ "tier": "gemini-accepted",
+ }
+ }
+ assert (scoreasr.spoken_language(wild[0], golden) == "en" and
+ scoreasr.spoken_language(wild[0], {}) == "de")
+ asr.asked.clear()
+ out = scoreasr.score_system("sys", wild, asr, cache, _Norm(), golden)
+ # the output is decoded again in the spoken language, not served
+ assert asr.asked == ["en"]
+ assert out["wild@-5"]["wer_pct"] == 0.0
+ assert out["wild@-5"]["reference_tiers"] == {"gemini-accepted": 1}
+ asr.asked.clear()
+ scoreasr.score_system("sys", wild, asr, cache, _Norm(), golden)
+ assert not asr.asked # and that decoding is cached in turn
+
+
+def test_missing_and_empty_reference_items_are_counted_not_scored(
+ asr_set, tmp_path):
+ _, out_root, rows = asr_set
+ render(
+ [r for r in rows if r["condition"] != "clean"],
+ out_root,
+ "partial",
+ lambda r: open(r["clean_path"] + ".txt", encoding="utf-8").read(),
+ )
+ asr = _Asr()
+ cache = scoreasr.Cache(str(tmp_path / "cache"), "fake", _Asr.identity)
+ golden = _golden(rows)
+ # a golden entry with no text: fall back
+ golden["babbleAT-10_002.wav"]["text"] = ""
+ # normalises to nothing: unscorable
+ golden["wildAT-5_004.wav"]["text"] = "..."
+ metrics = scoreasr.score_system("partial", rows, asr, cache, _Norm(),
+ golden)
+ assert "clean" not in metrics # nothing rendered
+ assert metrics["babble@-10"]["reference_tiers"] == {
+ "corpus-verified": 1,
+ scoreasr.FALLBACK: 1,
+ }
+ # its only item had an empty reference
+ assert "wild@-5" not in metrics or metrics.get("wild@-5") is None
+
+
+SEL = {"conds": "clean", "limit": 0}
+
+
+def test_sidecar_merges_recognisers_and_replaces_another_build(
+ asr_set, tmp_path, monkeypatch):
+ path = tmp_path / "sys.asr.json"
+ scoreasr.write_sidecar(
+ str(path),
+ "sys",
+ "large-v3",
+ {"clean": {
+ "wer_pct": 1.0
+ }},
+ {"m": 1},
+ "4.57",
+ {"a.wav": "h"},
+ SEL,
+ )
+ scoreasr.write_sidecar(
+ str(path),
+ "sys",
+ "small",
+ {"clean": {
+ "wer_pct": 2.0
+ }},
+ {"m": 2},
+ "4.57",
+ {"a.wav": "h"},
+ SEL,
+ )
+ d = json.load(open(path, encoding="utf-8"))
+ assert set(d["asr"]) == {"large-v3", "small"} and d["_set_id"] == "tiny"
+ assert d["_reference"].startswith(scoreasr.GOLDEN)
+ monkeypatch.setattr(common, "set_id", lambda root=None: "other")
+ scoreasr.write_sidecar(
+ str(path),
+ "sys",
+ "small",
+ {"clean": {
+ "wer_pct": 3.0
+ }},
+ {"m": 2},
+ "4.57",
+ {"a.wav": "h"},
+ SEL,
+ )
+ d = json.load(open(path, encoding="utf-8"))
+ # another build: start over
+ assert set(d["asr"]) == {"small"} and d["_set_id"] == "other"
+ assert d["_outputs"] == {"a.wav": "h"}
+ assert d["_scorer_sha256"] == scoreasr.SCORER_SHA256
+ scoreasr.write_sidecar(
+ str(path),
+ "sys",
+ "large-v3",
+ {"clean": {
+ "wer_pct": 1.0
+ }},
+ {"m": 1},
+ "4.57",
+ {"a.wav": "h"},
+ SEL,
+ )
+ # the same audio: merged
+ with open(path, encoding="utf-8") as fh:
+ d = json.load(fh)
+ assert set(d["asr"]) == {"small", "large-v3"}
+ scoreasr.write_sidecar(
+ str(path),
+ "sys",
+ "large-v3",
+ {"clean": {
+ "wer_pct": 1.0
+ }},
+ {"m": 1},
+ "4.57",
+ {"a.wav": "re-rendered"},
+ SEL,
+ )
+ # other audio: never mixed
+ assert set(json.load(open(path, encoding="utf-8"))["asr"]) == {"large-v3"}
+ scoreasr.write_sidecar(
+ str(path),
+ "sys",
+ "small",
+ {"clean": {
+ "wer_pct": 1.0
+ }},
+ {"m": 1},
+ "4.57",
+ {"a.wav": "re-rendered"},
+ dict(SEL, limit=5),
+ )
+ # another selection: not merged either
+ assert set(json.load(open(path, encoding="utf-8"))["asr"]) == {"small"}
+
+
+def test_whisper_normaliser_when_its_tokenizer_is_cached():
+ try:
+ norm = scoreasr.Normalizer()
+ except Exception as e: # pylint: disable=broad-exception-caught
+ # no cached tokenizer and no network: whatever stops it, the test skips
+ pytest.skip(f"whisper tokenizer unavailable: {e}")
+ assert (norm.tokens("Hello, World! It's 5 o'clock.",
+ "en") == "hello world it is 50 clock".split())
+ assert norm.tokens("Ça va, l'ami ?", "fr") == ["ça", "va", "l", "ami"]
+ assert norm.tokens("今天 天气很好。", "zh") == list("今天天气很好")
+
+
+def test_main_writes_one_sidecar_per_system(asr_set, tmp_path, monkeypatch):
+ pytest.importorskip("transformers", reason="needs the eval extra")
+ root, out_root, rows = asr_set
+ render(
+ rows,
+ out_root,
+ "perfect",
+ lambda r: open(r["clean_path"] + ".txt", encoding="utf-8").read(),
+ )
+ (out_root / "INPUT").mkdir()
+ # INPUT: the mixtures, whose fake transcripts carry an extra word
+ for r in rows:
+ os.symlink(r["mix_path"], out_root / "INPUT" / r["id"])
+ os.symlink(r["mix_path"] + ".txt",
+ out_root / "INPUT" / (r["id"] + ".txt"))
+ with open(root / scoreasr.GOLDEN, "w", encoding="utf-8") as fh:
+ for g in _golden(rows).values():
+ fh.write(json.dumps(g) + "\n")
+ monkeypatch.setattr(scoreasr, "Normalizer", _Norm)
+ monkeypatch.setattr(scoreasr, "FasterWhisper",
+ lambda size, device, beam: _Asr())
+ monkeypatch.setattr(scorebench, "render_problem", lambda name: None)
+ monkeypatch.setattr(
+ "sys.argv",
+ ["scoreasr.py", "--systems", "INPUT,perfect", "--asr", "fake"],
+ )
+ scoreasr.main()
+ results = tmp_path / "results"
+ with open(results / "INPUT.asr.json", encoding="utf-8") as fh:
+ inp = json.load(fh)["asr"]["fake"]["conditions"]
+ with open(results / "perfect.asr.json", encoding="utf-8") as fh:
+ per = json.load(fh)["asr"]["fake"]["conditions"]
+ # one inserted word per item
+ assert inp["clean"]["wer_pct"] == pytest.approx(100 * 2 / 13)
+ assert per["clean"]["wer_pct"] == 0.0
+ assert inp["clean"]["reference_tiers"] == {"corpus-verified": 2}
+
+
+def test_inworld_backend_posts_16k_wav_and_reads_the_transcript(
+ asr_set, tmp_path, monkeypatch):
+ pytest.importorskip("requests", reason="needs the eval extra")
+ _, _, rows = asr_set
+ seen = []
+
+ class _Resp:
+ status_code = 200
+ headers = {"content-type": "application/json"}
+ text = ""
+
+ def json(self):
+ return {"transcription": {"transcript": " hello there "}}
+
+ def fake_post(url, headers, json, timeout):
+ seen.append((url, headers, json))
+ return _Resp()
+
+ # pylint: disable-next=import-outside-toplevel
+ import requests
+
+ monkeypatch.setattr(requests, "post", fake_post)
+ monkeypatch.setenv("INWORLD_API_KEY", "k3y")
+ asr = scoreasr.make_asr("inworld/inworld-stt-1")
+ assert (asr.concurrent and
+ scoreasr.cache_tag(asr) == "inworld-stt-api_inworld_inworld-stt-1")
+ assert asr.transcribe(rows[0]["clean_path"], "de") == "hello there"
+ url, headers, body = seen[0]
+ assert (url == scoreasr.InworldSTT.URL and
+ headers["Authorization"] == "Basic k3y")
+ cfg = body["transcribeConfig"]
+ assert cfg == {
+ "modelId": "inworld/inworld-stt-1",
+ "audioEncoding": "LINEAR16",
+ "sampleRateHertz": 16000,
+ "numberOfChannels": 1,
+ "language": "de-DE",
+ }
+ # pylint: disable-next=import-outside-toplevel
+ import base64
+ # pylint: disable-next=import-outside-toplevel
+ import io
+ # pylint: disable-next=import-outside-toplevel
+ import wave
+
+ with wave.open(io.BytesIO(base64.b64decode(
+ body["audioData"]["content"]))) as w:
+ assert (w.getnchannels(), w.getsampwidth(), w.getframerate()) == (
+ 1,
+ 2,
+ 16000,
+ )
+ # the quarter-second test clip
+ assert abs(w.getnframes() / 16000 - 0.25) < 0.01
+ asr.transcribe(rows[0]["clean_path"], "und")
+ # unknown language: let the API decide
+ assert "language" not in seen[1][2]["transcribeConfig"]
+
+
+def test_inworld_backend_retries_server_errors_and_fails_on_client_errors(
+ asr_set, monkeypatch):
+ pytest.importorskip("requests", reason="needs the eval extra")
+ _, _, rows = asr_set
+ # pylint: disable-next=import-outside-toplevel
+ import requests
+
+ calls = {"n": 0}
+
+ class _Resp:
+ headers = {"content-type": "application/json"}
+
+ def __init__(self, code, text=""):
+ self.status_code, self.text = code, text
+
+ def json(self):
+ return {"transcription": {"transcript": "ok"}}
+
+ def flaky(url, headers, json, timeout):
+ calls["n"] += 1
+ return _Resp(503, "busy") if calls["n"] < 3 else _Resp(200)
+
+ monkeypatch.setattr(requests, "post", flaky)
+ monkeypatch.setattr(time, "sleep", lambda s: None)
+ asr = scoreasr.InworldSTT("inworld/inworld-stt-1", key="k", tries=4)
+ assert (asr.transcribe(rows[0]["clean_path"], "en") == "ok" and
+ calls["n"] == 3)
+ monkeypatch.setattr(requests, "post",
+ lambda *a, **k: _Resp(400, "unsupported model"))
+ with pytest.raises(RuntimeError, match="HTTP 400"):
+ asr.transcribe(rows[0]["clean_path"], "en")
+ monkeypatch.delenv("INWORLD_API_KEY", raising=False)
+ with pytest.raises(SystemExit):
+ scoreasr.make_asr("inworld/x")
+
+
+def test_concurrent_prefill_fills_the_cache_once_per_file(asr_set, tmp_path):
+ _, out_root, rows = asr_set
+ render(
+ rows,
+ out_root,
+ "perfect",
+ lambda r: open(r["clean_path"] + ".txt", encoding="utf-8").read(),
+ )
+
+ class _Api(_Asr):
+ concurrent = True
+
+ asr = _Api()
+ cache = scoreasr.Cache(str(tmp_path / "cache"), "api", _Asr.identity)
+ metrics = scoreasr.score_system("perfect",
+ rows,
+ asr,
+ cache,
+ _Norm(),
+ _golden(rows),
+ workers=4)
+ # outputs only: refs have gold
+ assert asr.calls == len(rows) and cache.misses == asr.calls
+ # the scoring pass reads everything the prefill wrote
+ assert cache.hits == len(rows)
+ assert all(v["wer_pct"] == 0.0 for v in metrics.values())
+ golden = {
+ k: v for k, v in _golden(rows).items() if not k.startswith("wild")
+ }
+ asr2 = _Api()
+ cache2 = scoreasr.Cache(str(tmp_path / "cache2"), "api", _Asr.identity)
+ scoreasr.score_system("perfect",
+ rows,
+ asr2,
+ cache2,
+ _Norm(),
+ golden,
+ workers=4)
+ # plus the one reference without a golden text
+ assert asr2.calls == len(rows) + 1
+
+
+def test_cantonese_is_scored_per_character_and_decoded_as_chinese_if_no_model():
+ assert ("yue" in scoreasr.CHAR_LANGS and
+ scoreasr.unit_for("yue") == "char" and
+ scoreasr.NEAREST["yue"] == "zh")
+
+ class _Model:
+ supported_languages = ["en", "zh", "yue"]
+
+ def transcribe(self, path, **kw):
+ self.language = kw["language"]
+ return [], None
+
+ for tag, expected in (
+ ("large-v3", "yue"),
+ ("small", "zh"),
+ ("large-v2", "zh"),
+ ):
+ fw = scoreasr.FasterWhisper.__new__(scoreasr.FasterWhisper)
+ fw.tag, fw.beam_size, fw.model = tag, 5, _Model()
+ fw.transcribe("x.wav", "yue")
+ assert fw.model.language == expected
+ fw.transcribe("x.wav", "de")
+ assert fw.model.language == "de"
+
+
+def test_the_cache_never_serves_a_transcript_decoded_otherwise(
+ asr_set, tmp_path):
+ _, _, rows = asr_set
+ path = rows[0]["clean_path"]
+ asr = _Asr()
+ cache_dir = str(tmp_path / "cache")
+ beam5 = dict(_Asr.identity, beam_size=5)
+ scoreasr.Cache(cache_dir, "fake", beam5).get(asr, path, "en")
+ assert asr.calls == 1
+ scoreasr.Cache(cache_dir, "fake", beam5).get(asr, path, "en")
+ assert asr.calls == 1 # the same identity reads its entry
+ beam1 = dict(beam5, beam_size=1)
+ scoreasr.Cache(cache_dir, "fake", beam1).get(asr, path, "en")
+ # another beam size decodes again, into a directory of its own
+ assert asr.calls == 2
+ version2 = dict(beam5, version="2")
+ scoreasr.Cache(cache_dir, "fake", version2).get(asr, path, "en")
+ assert asr.calls == 3
+ dirs = sorted(p.name for p in (tmp_path / "cache" / "fake").iterdir())
+ assert len(dirs) == 3 and all(len(d) == 16 for d in dirs)
+ # an entry in the right place whose recorded identity differs is not read
+ cache = scoreasr.Cache(str(tmp_path / "cache"), "fake", beam5)
+ entry = os.path.join(cache.dir, scoreasr.audio_key(path) + ".json")
+ doc = json.load(open(entry, encoding="utf-8"))
+ json.dump(dict(doc, identity={"engine": "else"}),
+ open(entry, "w", encoding="utf-8"))
+ cache.get(asr, path, "en")
+ assert asr.calls == 4
+ with open(entry, encoding="utf-8") as fh:
+ doc = json.load(fh)
+ assert doc["identity"] == beam5
+
+
+def test_concurrent_requests_for_the_same_audio_decode_it_once(
+ asr_set, tmp_path):
+ # pylint: disable-next=import-outside-toplevel
+ import threading
+
+ _, _, rows = asr_set
+ path = rows[0]["clean_path"]
+
+ class _Slow(_Asr):
+
+ def transcribe(self, path, language=None):
+ time.sleep(0.05)
+ return super().transcribe(path, language)
+
+ asr = _Slow()
+ cache = scoreasr.Cache(str(tmp_path / "cache"), "fake", _Asr.identity)
+ errors = []
+
+ def ask():
+ try:
+ cache.get(asr, path, "en")
+ except Exception as e: # pylint: disable=broad-exception-caught
+ # the failure the test is about
+ errors.append(e)
+
+ threads = [threading.Thread(target=ask) for _ in range(8)]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join()
+ assert (not errors and asr.calls == 1 and cache.misses == 1 and
+ cache.hits == 7)
+ assert not list((tmp_path / "cache").rglob("*.tmp"))
diff --git a/tests/bench/scripts/test_scorebench.py b/tests/bench/scripts/test_scorebench.py
new file mode 100644
index 0000000..d921955
--- /dev/null
+++ b/tests/bench/scripts/test_scorebench.py
@@ -0,0 +1,1063 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The reference scorer end to end on a tiny synthetic set.
+
+Heavy models are stubbed, so the tests run on CPU in seconds.
+"""
+
+# pylint: disable=redefined-outer-name,unused-argument
+
+import json
+import math
+import sys
+
+import numpy as np
+import pytest
+import soundfile as sf
+import torch
+import torchaudio
+
+import common
+import levels
+import observations
+import scorebench
+import stamprender
+
+SR = common.SR
+SECS = 2
+HALF_DB = 20 * math.log10(0.5)
+
+
+def speechlike(n, seed, level=0.1):
+ g = torch.Generator().manual_seed(seed)
+ t = torch.linspace(0, 1, n)
+ env = 0.2 + 0.8 * (0.5 + 0.5 * torch.sin(2 * math.pi * 3 * t)).pow(2)
+ return torch.randn(n, generator=g) * env * level
+
+
+class _Spk:
+ """Stands in for the WavLM speaker embedder.
+
+ Its similarity is the cosine similarity of the raw waveforms.
+ """
+
+ def sim(self, a, b, key_b=None):
+ n = min(len(a), len(b))
+ return float(torch.nn.functional.cosine_similarity(a[:n], b[:n], dim=0))
+
+
+class _Vad:
+ """Stands in for Silero: the whole clip is one speech segment."""
+
+ def segments(self, wav48):
+ w16 = torchaudio.functional.resample(wav48, SR, 16000)
+ return w16, [{"start": 0, "end": len(w16)}]
+
+
+def _write(path, x):
+ sf.write(str(path), x.numpy(), SR, subtype="FLOAT")
+
+
+def tiny_set(tmp_path, monkeypatch):
+ """A four-condition set: clean, babble@+4, expressive_tail@-5 and real_x.
+
+ The expressive_tail@-5 items have a score_from.
+ """
+ root, out_root = tmp_path / "set", tmp_path / "out"
+ (root / "mix").mkdir(parents=True)
+ (root / "ref").mkdir()
+ n = SECS * SR
+ rows, seed = [], 0
+ for cond, snr, count in (
+ ("clean", None, 3),
+ ("babble@+4", 4.0, 3),
+ ("expressive_tail@-5", -5.0, 2),
+ ("real_x", 0.0, 2),
+ ):
+ for i in range(count):
+ seed += 1
+ clean = speechlike(n, seed)
+ noise = (torch.randn(
+ n, generator=torch.Generator().manual_seed(1000 + seed)) * 0.05)
+ if snr is None:
+ mix, ref = clean, clean
+ else:
+ mix, ref = common.mix_at_snr(clean, noise, snr)
+ rid = f"{cond.replace('@', 'AT')}_{i:03d}.wav"
+ _write(root / "mix" / rid, mix)
+ row = {
+ "id": rid,
+ "condition": cond,
+ "mix_path": f"mix/{rid}",
+ "clean_path": None,
+ }
+ if cond != "real_x":
+ _write(root / "ref" / rid, ref)
+ row["clean_path"] = f"ref/{rid}"
+ if cond.endswith("_tail@-5"):
+ row["score_from"] = n // 2
+ rows.append(row)
+ with open(root / "manifest.jsonl", "w", encoding="utf-8") as fh:
+ fh.write("".join(json.dumps(r) + "\n" for r in rows))
+ json.dump(
+ {
+ "set_id": "tiny",
+ "n_items": len(rows)
+ },
+ open(root / "checksums.json", "w", encoding="utf-8"),
+ )
+ monkeypatch.setattr(common, "EVAL", str(root))
+ monkeypatch.setattr(common, "OUT_ROOT", str(out_root))
+ monkeypatch.setattr(scorebench, "NISQA_ON", False)
+ return common.manifest(str(root)), out_root
+
+
+def render(rows, out_root, name, fn):
+ """Writes fn(row, mix, ref) for every row as system name.
+
+ fn may return None to skip.
+ """
+ d = out_root / name
+ d.mkdir(parents=True, exist_ok=True)
+ for r in rows:
+ mix = common.load48(r["mix_path"])
+ ref = common.load48(r["clean_path"]) if r.get("clean_path") else None
+ y = fn(r, mix, ref)
+ if y is not None:
+ _write(d / r["id"], y)
+
+
+def conditions(metrics):
+ return {k for k in metrics if not k.startswith("_")}
+
+
+def test_unprocessed_input_scores_as_the_identity_system(tiny_set):
+ rows, out_root = tiny_set
+ render(rows, out_root, "INPUT", lambda r, mix, ref: mix)
+ metrics = scorebench.score_system("INPUT", rows, _Spk(), _Vad(), None)
+ assert metrics["_set_id"] == "tiny"
+ assert metrics["_level_cal_db"] == pytest.approx(0.0, abs=1e-6)
+ assert metrics["_bands_hz"] == [list(b) for b in common.BANDS_HZ]
+ assert conditions(metrics) == {
+ "clean",
+ "babble@+4",
+ "expressive_tail@-5",
+ "real_x",
+ }
+ clean = metrics["clean"]
+ babble = metrics["babble@+4"]
+ real = metrics["real_x"]
+ assert (clean["n"] == 3 and clean["si_sdr"] > 60 and
+ clean["spk_sim"] == pytest.approx(1.0, abs=1e-4))
+ assert clean["kept_mean"] == pytest.approx(0.0, abs=1e-6)
+ assert all(v == pytest.approx(0.0, abs=1e-6) for v in clean["band_kept_db"])
+ assert clean["lag_median"] == 0 and clean["lag_max_abs"] == 0
+ assert babble["babble_supp_db"] == pytest.approx(0.0, abs=1e-6)
+ assert babble["babble_supp_db_nb"] == pytest.approx(0.0, abs=1e-3)
+ # the mix sits at its nominal SNR
+ assert babble["si_sdr"] == pytest.approx(4.0, abs=0.3)
+ assert babble["si_sdr_nb"] == pytest.approx(4.0, abs=0.6)
+ # cosine of a +4 dB mix against its clean
+ assert 0.8 < babble["spk_sim"] < 0.9
+ assert (real["n"] == 2 and real["n_segments"] == 2 and
+ real["deleted_rate_pct"] == 0.0)
+ assert real["median_drop_db"] == pytest.approx(0.0, abs=1e-6)
+ assert real["speech_rms_delta_db"] == pytest.approx(0.0, abs=1e-6)
+ # the stub VAD leaves no unvoiced samples
+ assert math.isnan(real["nonvoiced_supp_db"])
+ assert len(real["band_vs_in_db"]) == 7 and all(
+ abs(v) < 1e-6 for v in real["band_vs_in_db"])
+ assert "dnsmos_ovr" not in real and "nisqa_mos" not in real
+ assert "babble_supp_db" not in clean
+
+
+def test_a_global_gain_shows_up_in_level_calibration_and_every_kept_metric(
+ tiny_set,):
+ rows, out_root = tiny_set
+ render(rows, out_root, "half", lambda r, mix, ref: 0.5 * mix)
+ metrics = scorebench.score_system("half", rows, _Spk(), _Vad(), None)
+ assert metrics["_level_cal_db"] == pytest.approx(HALF_DB, abs=0.02)
+ clean, real = metrics["clean"], metrics["real_x"]
+ assert clean["out_in_rms_db"] == pytest.approx(HALF_DB, abs=0.02)
+ assert clean["kept_mean"] == pytest.approx(HALF_DB, abs=0.02)
+ assert clean["kept_p10"] == pytest.approx(HALF_DB, abs=0.02)
+ # a gain, not more voice
+ assert clean["kept_coh_p10"] == pytest.approx(HALF_DB, abs=0.05)
+ assert clean["kept_coh_nb_p10"] == pytest.approx(HALF_DB, abs=0.05)
+ for q in ("kept_q1", "kept_q2", "kept_q3"):
+ assert clean[q] == pytest.approx(HALF_DB, abs=0.05)
+ assert all(
+ v == pytest.approx(HALF_DB, abs=0.05) for v in clean["band_kept_db"])
+ assert clean["si_sdr"] > 60 and clean["spk_sim"] == pytest.approx(
+ 1.0,
+ # scale-invariant
+ abs=1e-4,
+ )
+ assert real["speech_rms_delta_db"] == pytest.approx(HALF_DB, abs=0.02)
+ # -6 dB is a level change, not a deletion
+ assert real["deleted_rate_pct"] == 0.0
+
+
+def test_score_from_restricts_reference_metrics_to_the_tail(tiny_set):
+ rows, out_root = tiny_set
+
+ def tail_only(r, mix, ref):
+ if r["condition"] != "expressive_tail@-5":
+ return mix
+ o = ref.clone()
+ s = r["score_from"]
+ # wrong before
+ o[:s] = torch.randn(s, generator=torch.Generator().manual_seed(7)) * 0.1
+ return o
+
+ render(rows, out_root, "tailonly", tail_only)
+ metrics = scorebench.score_system("tailonly", rows, _Spk(), _Vad(), None)
+ tail = metrics["expressive_tail@-5"]
+ assert (tail["n"] == 2 and tail["si_sdr"] > 60 and
+ tail["kept_mean"] == pytest.approx(0, abs=1e-6))
+ assert tail["lag_median"] == 0
+ ignoring = scorebench.score_system("tailonly",
+ [dict(r, score_from=0) for r in rows],
+ _Spk(), _Vad(), None)
+ # the wrong first half would count
+ assert ignoring["expressive_tail@-5"]["si_sdr"] < 15
+
+
+def test_algorithmic_delay_is_measured_and_undone(tiny_set):
+ rows, out_root = tiny_set
+ lag = 480 # 10 ms late
+
+ def late(r, mix, ref):
+ return torch.cat([torch.zeros(lag), mix])[:len(mix)]
+
+ render(rows, out_root, "late", late)
+ metrics = scorebench.score_system("late", rows, _Spk(), _Vad(), None)
+ assert metrics["clean"]["lag_median"] == lag
+ assert metrics["clean"]["lag_max_abs"] == lag
+ # aligned before scoring: only the 10 ms the delay pushed out of the clip is
+ # lost
+ assert metrics["clean"]["si_sdr"] > 20
+ first = next(r for r in rows if r["condition"] == "clean")
+ unaligned = common.si_sdr(
+ common.load48(str(out_root / "late" / first["id"])),
+ common.load48(first["clean_path"]),
+ )
+ # what the same output would score without the alignment
+ assert unaligned < 5
+ assert metrics["babble@+4"]["babble_supp_db"] == pytest.approx(0.0, abs=0.2)
+
+
+def test_a_polarity_flip_is_undone_like_a_delay_and_never_reads_as_damage(
+ tiny_set,):
+ rows, out_root = tiny_set
+ lag = 240
+
+ def upside_down_and_late(r, mix, ref):
+ return -torch.cat([torch.zeros(lag), mix])[:len(mix)]
+
+ render(rows, out_root, "flipped", upside_down_and_late)
+ metrics = scorebench.score_system("flipped", rows, _Spk(), _Vad(), None)
+ clean = metrics["clean"]
+ assert (clean["lag_median"] == lag and
+ clean["n_polarity_flipped"] == clean["n"])
+ assert clean["si_sdr"] > 20 and clean["kept_coh_p10"] == pytest.approx(
+ 0.0, abs=0.1)
+ assert clean["kept_coh_lost_pct"] == 0.0
+ assert metrics["babble@+4"]["babble_supp_db"] == pytest.approx(0.0, abs=0.2)
+ render(rows, out_root, "upright", lambda r, mix, ref: mix)
+ upright = scorebench.score_system("upright", rows, _Spk(), _Vad(), None)
+ assert upright["clean"]["n_polarity_flipped"] == 0
+
+
+def test_silence_cannot_calibrate_its_deleted_voice_back(tiny_set):
+ rows, out_root = tiny_set
+ render(rows, out_root, "mute", lambda r, mix, ref: torch.zeros_like(mix))
+ metrics = scorebench.score_system("mute", rows, _Spk(), _Vad(), None)
+ # bounded: a gain convention, not an output
+ assert metrics["_level_cal_db"] == -common.MAX_LEVEL_CAL_DB
+ assert metrics["clean"]["kept_coh_p10"] - metrics["_level_cal_db"] < -40
+ assert metrics["clean"]["kept_coh_lost_pct"] == 100.0
+
+
+def test_lost_speech_blocks_are_counted_where_a_percentile_is_blind(tiny_set):
+ rows, out_root = tiny_set
+
+ def one_gap(r, mix, ref): # 300 ms of the loudest second goes missing
+ y = mix.clone()
+ if ref is not None:
+ start = int(ref.abs().argmax()) // 4800 * 4800
+ y[start:start + 3 * 4800] = 0.0
+ return y
+
+ render(rows, out_root, "gap", one_gap)
+ clean = scorebench.score_system("gap", rows, _Spk(), _Vad(), None)["clean"]
+ assert clean["kept_coh_lost_pct"] > 0.0
+ # -12 dB everywhere is a gain: calibrated away, nothing lost
+ render(rows, out_root, "quieter", lambda r, mix, ref: 0.25 * mix)
+ quieter = scorebench.score_system("quieter", rows, _Spk(), _Vad(), None)
+ assert quieter["clean"]["kept_coh_lost_pct"] == 0.0
+
+
+def test_deletion_is_counted_on_reference_free_items(tiny_set):
+ rows, out_root = tiny_set
+ render(
+ rows,
+ out_root,
+ "muter",
+ lambda r, mix, ref: 0.01 * mix if r["condition"] == "real_x" else mix,
+ )
+ metrics = scorebench.score_system("muter", rows, _Spk(), _Vad(), None)
+ assert metrics["real_x"]["deleted_rate_pct"] == 100.0
+ assert metrics["real_x"]["median_drop_db"] == pytest.approx(-40.0, abs=0.1)
+ assert metrics["clean"]["si_sdr"] > 60 # untouched elsewhere
+
+
+def test_conditions_without_outputs_are_left_out(tiny_set):
+ rows, out_root = tiny_set
+ render(
+ rows,
+ out_root,
+ "partial",
+ lambda r, mix, ref: mix if r["condition"] == "clean" else None,
+ )
+ metrics = scorebench.score_system("partial", rows, _Spk(), _Vad(), None)
+ assert conditions(metrics) == {"clean"} and metrics["clean"]["n"] == 3
+
+
+def test_rms_db_of_a_known_sine():
+ t = torch.arange(SR) / SR
+ tone = 0.5 * torch.sin(2 * math.pi * 440 * t)
+ assert scorebench.rms_db(tone) == pytest.approx(
+ 20 * math.log10(0.5 / math.sqrt(2)), abs=0.01)
+ assert scorebench.rms_db(torch.zeros(1000)) < -200
+
+
+def test_systems_without_an_identity_on_this_set_are_not_scored(
+ tmp_path, monkeypatch):
+ monkeypatch.setattr(common, "RESULTS", str(tmp_path))
+ monkeypatch.setattr(common, "set_id", lambda root=None: "current-set")
+ (tmp_path / "old.meta.json").write_text(
+ json.dumps({"set_id": "previous-set"}))
+ (tmp_path / "same.meta.json").write_text(
+ json.dumps({"set_id": "current-set"}))
+ (tmp_path / "unstamped.meta.json").write_text(json.dumps({"mechanism": "x"
+ }))
+ assert "previous-set"[:12] in scorebench.render_problem("old")
+ assert scorebench.render_problem("same") is None
+ assert "no set_id" in scorebench.render_problem("unstamped")
+ assert "meta.json missing" in scorebench.render_problem(
+ "missing") # a bare output directory is not scored
+
+
+def test_retention_items_report_kept_speech_and_bed_residual_but_no_si_sdr(
+ tmp_path, monkeypatch):
+ root, out_root = tmp_path / "wildset", tmp_path / "out"
+ (root / "mix").mkdir(parents=True)
+ (root / "ref").mkdir()
+ n, rows = SECS * SR, []
+
+ # speech in the first half of the recording, its own floor after it
+ class _HalfVad(_Vad):
+
+ def segments(self, wav48):
+ w16 = torchaudio.functional.resample(wav48, SR, 16000)
+ return w16, [{"start": 0, "end": len(w16) // 2}]
+
+ vad = _HalfVad()
+ for i in range(2):
+ wild = speechlike(n, 50 + i) + 0.05 * torch.randn(
+ n, generator=torch.Generator().manual_seed(i))
+ wild[n // 2:] = 0.02 * torch.randn(
+ n - n // 2, generator=torch.Generator().manual_seed(7 + i))
+ bed = (
+ torch.randn(n, generator=torch.Generator().manual_seed(900 + i)) *
+ 0.05)
+ mix, ref = common.mix_at_snr(wild, bed, -5.0)
+ rid = f"wildAT-5_{i:03d}.wav"
+ _write(root / "mix" / rid, mix)
+ _write(root / "ref" / rid, ref)
+ rows.append({
+ "id": rid,
+ "condition": "wild@-5",
+ "family": "wild",
+ "mix_path": f"mix/{rid}",
+ "clean_path": f"ref/{rid}",
+ "snr": -5.0,
+ "score_policy": "retention",
+ })
+ with open(root / "manifest.jsonl", "w", encoding="utf-8") as fh:
+ fh.write("".join(json.dumps(r) + "\n" for r in rows))
+ json.dump({
+ "set_id": "wildtiny",
+ "n_items": 2
+ }, open(root / "checksums.json", "w", encoding="utf-8"))
+ monkeypatch.setattr(common, "EVAL", str(root))
+ monkeypatch.setattr(common, "OUT_ROOT", str(out_root))
+ monkeypatch.setattr(scorebench, "NISQA_ON", False)
+ rows = common.manifest(str(root))
+
+ def wild_scores(name):
+ return scorebench.score_system(name, rows, _Spk(), vad, None)["wild@-5"]
+
+ render(rows, out_root, "perfect", lambda r, mix, ref: ref)
+ metrics = wild_scores("perfect")
+ assert (metrics["score_policy"] == "retention" and
+ "si_sdr" not in metrics and "si_sdr_nb" not in metrics)
+ # voice kept, bed gone
+ assert abs(
+ metrics["kept_coh_p10"]) < 0.5 and metrics["nonvoiced_supp_db"] < -10
+ render(rows, out_root, "muter", lambda r, mix, ref: 0.01 * ref)
+ muted = wild_scores("muter")
+ # deleted speech shows up here
+ assert muted["kept_coh_p10"] == pytest.approx(-40.0, abs=0.5)
+ # returns the added bed alone
+ render(rows, out_root, "bedonly", lambda r, mix, ref: mix - ref)
+ bed_only = wild_scores("bedonly")
+ # coherent: deleted; energy: fooled
+ assert bed_only["kept_coh_p10"] < -20 and bed_only["kept_p10"] > 0
+ # and the bed is still there
+ assert bed_only["nonvoiced_supp_db"] > metrics["nonvoiced_supp_db"] + 10
+
+ # the quieter half of the speech blocks zeroed
+ def quiet_deleted(r, mix, ref):
+ y = ref.clone()
+ blocks = y[:len(y) // 4800 * 4800].reshape(-1, 4800)
+ e = blocks.pow(2).mean(1)
+ speech = torch.zeros(len(e), dtype=torch.bool)
+ # the VAD stub marks the first half as speech
+ speech[:len(e) // 2] = True
+ order = e.clone()
+ order[~speech] = float("inf")
+ idx = order.argsort()[:int(speech.sum()) // 2]
+ blocks[idx] = 0
+ return y
+
+ render(rows, out_root, "quietgone", quiet_deleted)
+ quiet_gone = scorebench.score_system("quietgone", rows, _Spk(), vad, None)
+ # deleted quiet speech is seen, the energy ratio barely moves
+ assert quiet_gone["wild@-5"]["kept_coh_p10"] < -30
+
+
+def test_missing_outputs_are_counted_per_condition_and_for_the_set(tiny_set):
+ rows, out_root = tiny_set
+ seen = []
+
+ def two_of_three_clean(r, mix, ref):
+ if r["condition"] != "clean":
+ return None
+ seen.append(r["id"])
+ return mix if len(seen) < 3 else None
+
+ render(rows, out_root, "flaky", two_of_three_clean)
+ metrics = scorebench.score_system("flaky", rows, _Spk(), _Vad(), None)
+ assert conditions(metrics) == {"clean"}
+ assert metrics["clean"]["n"] == 2 and metrics["clean"]["n_missing"] == 1
+ # the other conditions never rendered at all
+ assert metrics["_n_missing"] == len(rows) - 2
+ render(rows, out_root, "whole", lambda r, mix, ref: mix)
+ whole = scorebench.score_system("whole", rows, _Spk(), _Vad(), None)
+ assert whole["_n_missing"] == 0
+
+
+def test_observations_reproduce_condition_reducers_and_level_calibration(
+ tiny_set,):
+ rows, out_root = tiny_set
+ render(
+ rows,
+ out_root,
+ "varied",
+ lambda r, mix, ref: mix * (0.2 + int(r["id"][-7:-4]) * 0.1),
+ )
+ records = []
+ scores = scorebench.score_system("varied",
+ rows,
+ _Spk(),
+ _Vad(),
+ None,
+ records=records)
+ assert len(records) == len(rows)
+ for condition in conditions(scores):
+ raw = {}
+ for r in records:
+ if r["condition"] == condition:
+ for key, values in r["measurements"].items():
+ raw.setdefault(key, []).extend(values)
+ cell = scores[condition]
+ assert cell["out_in_rms_db"] == np.mean(raw["out_in_rms_db"])
+ if "kept" in raw:
+ assert cell["kept_mean"] == np.mean(raw["kept"])
+ assert cell["kept_p10"] == np.percentile(raw["kept"], 10)
+ assert cell["lag_median"] == np.median(raw["lag"])
+ assert cell["band_kept_db"] == pytest.approx(
+ np.nanmean(np.array(raw["band"], dtype=float), axis=0))
+ assert cell["kept_coh_p10"] == np.mean(raw["kept_coh_p10"])
+ else:
+ assert cell["n_segments"] == len(raw["seg_drop"])
+ assert cell["deleted_rate_pct"] == 100 * np.mean(
+ levels.deleted(raw["seg_drop"], scores["_level_cal_db"]))
+ clean_gains = [
+ r["metrics"]["out_in_rms_db"]
+ for r in records
+ if r["condition"] == "clean"
+ ]
+ assert scores["_level_cal_db"] == np.median(clean_gains)
+
+
+def test_invalid_audio_statuses_remain_in_per_item_inventory(tiny_set):
+ rows, out_root = tiny_set
+ render(rows, out_root, "broken", lambda r, mix, ref: mix)
+ directory = out_root / "broken"
+ (directory / rows[0]["id"]).write_bytes(b"invalid wav")
+ (directory / rows[1]["id"]).unlink()
+ _write(directory / rows[2]["id"], torch.zeros(12))
+ _write(
+ directory / rows[3]["id"],
+ torch.full_like(common.load48(rows[3]["mix_path"]), float("nan")),
+ )
+ records = []
+ scores = scorebench.score_system("broken",
+ rows,
+ _Spk(),
+ _Vad(),
+ None,
+ records=records)
+ statuses = {r["id"]: r["output_status"] for r in records}
+ assert [statuses[r["id"]] for r in rows[:4]] == [
+ "unreadable",
+ "missing",
+ "wrong_length",
+ "nonfinite",
+ ]
+ assert scores["_n_missing"] == 4
+
+
+def _same(a, b):
+ """Equality that treats nan as equal to nan.
+
+ A condition with no nonvoiced frames reads nan.
+ """
+
+ def canonical(x):
+ return json.dumps(observations.finite(x), sort_keys=True)
+
+ return canonical(a) == canonical(b)
+
+
+def _records_file(path, records, system="varied", scorer=None):
+ observations.write(
+ path,
+ records,
+ {
+ "system": system,
+ "set_id": "tiny",
+ "subset": "all",
+ "anchors_version": "t",
+ "anchors_sha256": "t",
+ "scorer_sha256": scorer or scorebench.SCORER_SHA256,
+ "n_expected": len(records),
+ "sealed": False,
+ "render_identity": {},
+ "level_cal_db": 0.0,
+ },
+ )
+
+
+def test_records_carry_a_content_identity_and_are_reused_only_while_it_holds(
+ tiny_set, tmp_path):
+ rows, out_root = tiny_set
+ render(
+ rows,
+ out_root,
+ "varied",
+ lambda r, mix, ref: mix * (0.2 + int(r["id"][-7:-4]) * 0.1),
+ )
+ first = []
+ scores = scorebench.score_system("varied",
+ rows,
+ _Spk(),
+ _Vad(),
+ None,
+ records=first)
+ assert all(r["identity"]["output"] and r["identity"]["mix"] for r in first)
+ assert all((r["identity"]["ref"] is None) == (r["condition"] == "real_x")
+ for r in first)
+ _records_file(tmp_path / "varied.items.jsonl", first)
+ index, why = scorebench.reuse_index(str(tmp_path / "varied.items.jsonl"),
+ "varied")
+ assert len(index) == len(rows) and "reusable" in why
+ # nothing changed: every record is reused and the file is reproduced
+ again = []
+ assert _same(
+ scorebench.score_system("varied",
+ rows,
+ _Spk(),
+ _Vad(),
+ None,
+ records=again,
+ reuse=index),
+ scores,
+ )
+ assert [r["metrics"] for r in again] == [r["metrics"] for r in first]
+ # one output changes: that item is scored afresh, the others keep their
+ # records
+ changed = rows[1]
+ _write(out_root / "varied" / changed["id"],
+ common.load48(changed["mix_path"]) * 0.5)
+ third = []
+ rescored = scorebench.score_system("varied",
+ rows,
+ _Spk(),
+ _Vad(),
+ None,
+ records=third,
+ reuse=index)
+ by_id = {r["id"]: r for r in third}
+ before = {r["id"]: r for r in first}[changed["id"]]
+ after = by_id[changed["id"]]
+ assert after["identity"]["output"] != before["identity"]["output"]
+ assert after["metrics"] != before["metrics"]
+ for r in first:
+ if r["id"] != changed["id"]:
+ assert by_id[r["id"]]["metrics"] == r["metrics"]
+ assert (rescored["_level_cal_db"] != scores["_level_cal_db"] or
+ changed["condition"] != "clean")
+ # another scorer's records are never reused
+ _records_file(tmp_path / "other.items.jsonl", first, scorer="someone-else")
+ index, why = scorebench.reuse_index(str(tmp_path / "other.items.jsonl"),
+ "varied")
+ assert index == {} and "another scorer" in why
+
+
+def test_a_view_aggregated_from_whole_set_records_equals_scoring_it_directly(
+ tiny_set, monkeypatch):
+ rows, out_root = tiny_set
+ render(
+ rows,
+ out_root,
+ "varied",
+ lambda r, mix, ref: mix * (0.2 + int(r["id"][-7:-4]) * 0.1),
+ )
+ whole = []
+ scorebench.score_system("varied", rows, _Spk(), _Vad(), None, records=whole)
+ view = [
+ r for i, r in enumerate(rows) if i % 2 == 0 or r["condition"] == "clean"
+ ]
+ assert 0 < len(view) < len(rows)
+ direct = scorebench.score_system("varied", view, _Spk(), _Vad(), None)
+ ids = {r["id"] for r in view}
+ derived = scorebench.aggregate([r for r in whole if r["id"] in ids], view)
+ # bit for bit, the lost-block share under the view's calibration
+ assert _same(derived, direct)
+ whole_cal = scorebench.aggregate(whole, rows)["_level_cal_db"]
+ n_clean = len([r for r in rows if r["condition"] == "clean"])
+ n_clean_view = len([r for r in view if r["condition"] == "clean"])
+ assert derived["_level_cal_db"] != whole_cal or n_clean == n_clean_view
+
+
+def test_aggregate_only_derives_a_subset_from_whole_set_records(
+ tiny_set, tmp_path, monkeypatch):
+ rows, out_root = tiny_set
+ render(rows, out_root, "varied", lambda r, mix, ref: mix * 0.7)
+ whole_dir, view_dir = tmp_path / "whole", tmp_path / "view"
+ whole_dir.mkdir()
+ # the stamp's digest of the outputs, which the scorer checks the bytes
+ # against
+ rendered = stamprender.outputs_digest([r["id"] for r in rows],
+ str(out_root / "varied"))
+ (whole_dir / "varied.meta.json").write_text(
+ json.dumps({
+ "set_id": "tiny",
+ "name": "varied",
+ "outputs_sha256": rendered
+ }))
+ (whole_dir / "INPUT.meta.json").write_text(
+ json.dumps({
+ "set_id": "tiny",
+ "name": "INPUT"
+ }))
+ monkeypatch.setattr(common, "RESULTS", str(whole_dir))
+ monkeypatch.setattr(common,
+ "SpeakerEmbedder",
+ lambda cache_dir=None: _Spk())
+ monkeypatch.setattr(common, "Vad", _Vad)
+ monkeypatch.setattr(sys, "argv", ["scorebench.py", "--systems", "varied"])
+ scorebench.main()
+ assert (whole_dir / "varied.items.jsonl").exists()
+ assert (whole_dir / "varied.metrics.json").exists()
+ with open(whole_dir / "varied.metrics.json", encoding="utf-8") as fh:
+ whole_metrics = json.load(fh)
+ assert whole_metrics["_outputs_sha256"] == rendered
+ # the view: a panel of three items, selected the way common.manifest selects
+ # one
+ members = {rows[0]["id"], rows[3]["id"], rows[-1]["id"]}
+ monkeypatch.setattr(common, "SUBSET", "gate")
+ monkeypatch.setattr(common,
+ "panel_members",
+ lambda name, root=None: members)
+ monkeypatch.setattr(common, "RESULTS", str(view_dir))
+ monkeypatch.setattr(
+ sys,
+ "argv",
+ [
+ "scorebench.py",
+ "--systems",
+ "varied",
+ "--aggregate-only",
+ str(whole_dir),
+ ],
+ )
+ scorebench.main()
+ derived = json.load(open(view_dir / "varied.metrics.json",
+ encoding="utf-8"))
+ assert (derived["_subset"] == "gate" and sum(
+ v["n"] for k, v in derived.items() if not k.startswith("_")) == 3)
+ # the view names the render its records read, with no stamp beside it
+ assert derived["_outputs_sha256"] == rendered
+ stamp = (view_dir / "varied.metrics.json").stat().st_mtime_ns
+ # a view is re-derived every time, never skipped as "already scored"
+ scorebench.main()
+ assert (view_dir / "varied.metrics.json").stat().st_mtime_ns > stamp
+ # the whole render's stamp cannot vouch for three of its outputs scored
+ # again; a render made and stamped on the panel's items can
+ direct_dir = tmp_path / "direct"
+ direct_dir.mkdir()
+ whole_stamp = {
+ "set_id": "tiny",
+ "name": "varied",
+ "outputs_sha256": rendered,
+ "n_files": len(rows),
+ }
+ (direct_dir / "varied.meta.json").write_text(json.dumps(whole_stamp))
+ monkeypatch.setattr(common, "RESULTS", str(direct_dir))
+ monkeypatch.setattr(sys, "argv", ["scorebench.py", "--systems", "varied"])
+ with pytest.raises(SystemExit, match="derived from its whole-set records"):
+ scorebench.main()
+ panel_stamp = dict(whole_stamp,
+ n_files=len(members),
+ outputs_sha256=stamprender.outputs_digest(
+ sorted(members), str(out_root / "varied")))
+ (direct_dir / "varied.meta.json").write_text(json.dumps(panel_stamp))
+ scorebench.main()
+ with open(direct_dir / "varied.metrics.json", encoding="utf-8") as fh:
+ direct = json.load(fh)
+ # each names the render it read; apart from that the two are one
+ assert direct["_outputs_sha256"] == panel_stamp["outputs_sha256"]
+ direct["_outputs_sha256"] = derived["_outputs_sha256"]
+ assert _same(direct, derived)
+ header = json.loads(
+ open(view_dir / "varied.items.jsonl", encoding="utf-8").readline())
+ assert header["subset"] == "gate" and header["n_expected"] == 3
+
+
+def test_a_system_is_never_skipped_as_scored(tiny_set, tmp_path, monkeypatch,
+ capsys):
+ """A changed output is re-scored and an unchanged one keeps its record.
+
+ A metrics file that already exists is never a reason to skip.
+ """
+ rows, out_root = tiny_set
+ render(rows, out_root, "varied", lambda r, mix, ref: mix * 0.7)
+ results = tmp_path / "results"
+ results.mkdir()
+ (results / "varied.meta.json").write_text(
+ json.dumps({
+ "set_id": "tiny",
+ "name": "varied"
+ }))
+ (results / "INPUT.meta.json").write_text(
+ json.dumps({
+ "set_id": "tiny",
+ "name": "INPUT"
+ }))
+ monkeypatch.setattr(common, "RESULTS", str(results))
+ monkeypatch.setattr(common,
+ "SpeakerEmbedder",
+ lambda cache_dir=None: _Spk())
+ monkeypatch.setattr(common, "Vad", _Vad)
+ monkeypatch.setattr(sys, "argv", ["scorebench.py", "--systems", "varied"])
+ scorebench.main()
+ with open(results / "varied.items.jsonl", encoding="utf-8") as fh:
+ records = [json.loads(line) for line in fh]
+ first = {r["id"]: r for r in records[1:]}
+ changed = rows[2]
+ _write(out_root / "varied" / changed["id"],
+ common.load48(changed["mix_path"]) * 0.3)
+ capsys.readouterr()
+ scorebench.main()
+ out = capsys.readouterr().out
+ assert ("already scored" not in out and "reused" in out and
+ "scored 1 items" in out)
+ with open(results / "varied.items.jsonl", encoding="utf-8") as fh:
+ records = [json.loads(line) for line in fh]
+ second = {r["id"]: r for r in records[1:]}
+ assert second[changed["id"]]["metrics"] != first[changed["id"]]["metrics"]
+ assert all(second[i]["metrics"] == first[i]["metrics"]
+ for i in first
+ if i != changed["id"])
+
+
+def test_scores_are_accepted_only_of_the_bytes_their_stamp_vouches_for(
+ tiny_set, tmp_path, monkeypatch):
+ """A render changed since its stamp is never scored under that stamp."""
+ rows, out_root = tiny_set
+ render(rows, out_root, "stamped", lambda r, mix, ref: mix * 0.7)
+ results = tmp_path / "results"
+ results.mkdir()
+ digest = stamprender.outputs_digest([r["id"] for r in rows],
+ str(out_root / "stamped"))
+ stamp = {"set_id": "tiny", "name": "stamped", "outputs_sha256": digest}
+ (results / "stamped.meta.json").write_text(json.dumps(stamp))
+ monkeypatch.setattr(common, "RESULTS", str(results))
+ monkeypatch.setattr(common,
+ "SpeakerEmbedder",
+ lambda cache_dir=None: _Spk())
+ monkeypatch.setattr(common, "Vad", _Vad)
+ monkeypatch.setattr(sys, "argv", ["scorebench.py", "--systems", "stamped"])
+ scorebench.main()
+ scores = json.loads((results / "stamped.metrics.json").read_text())
+ assert scores["_outputs_sha256"] == digest
+ _, records = observations.read(results / "stamped.items.jsonl")
+ hashes = {r["id"]: r["output_sha256"] for r in records}
+ assert stamprender.digest_of(hashes) == digest
+ # one output's samples change after the stamp: the scores it vouched for
+ # stay, and nothing is written under it
+ changed = rows[2]
+ _write(out_root / "stamped" / changed["id"],
+ common.load48(changed["mix_path"]) * 0.3)
+ with pytest.raises(SystemExit, match="not the render its stamp vouches"):
+ scorebench.main()
+ assert json.loads((results / "stamped.metrics.json").read_text()) == scores
+ # a filtered look reads too few outputs to vouch for the render
+ monkeypatch.setattr(
+ sys, "argv",
+ ["scorebench.py", "--systems", "stamped", "--conds", "clean"])
+ scorebench.main()
+ looked = json.loads((results / "stamped.metrics.json").read_text())
+ assert looked["_selection"] and looked["_outputs_sha256"] is None
+
+
+def test_an_output_gain_is_undone_everywhere_but_the_level_row(tiny_set):
+ """A perfect output made 6 dB louder reads as perfect but for its level.
+
+ It reads as the reference does on every row a gain is a convention for, and
+ as 6 dB on the one row that scores the gain.
+ """
+ rows, out_root = tiny_set
+ render(
+ rows,
+ out_root,
+ "REF2",
+ lambda r, mix, ref: 2 * (ref if ref is not None else mix),
+ )
+ render(
+ rows,
+ out_root,
+ "REF1",
+ lambda r, mix, ref: ref if ref is not None else mix,
+ )
+ loud = scorebench.score_system("REF2", rows, _Spk(), _Vad(), None)
+ plain = scorebench.score_system("REF1", rows, _Spk(), _Vad(), None)
+ six = 20 * math.log10(2)
+ assert loud["_level_cal_db"] == pytest.approx(six, abs=1e-4)
+ assert loud["clean"]["level_err_db"] == pytest.approx(six, abs=1e-4)
+ assert plain["clean"]["level_err_db"] == pytest.approx(0.0, abs=1e-4)
+ assert loud["clean"]["hf_err_db"] == pytest.approx(
+ plain["clean"]["hf_err_db"], abs=1e-3)
+ assert loud["babble@+4"]["babble_supp_db"] == pytest.approx(
+ plain["babble@+4"]["babble_supp_db"], abs=1.0)
+ assert (loud["babble@+4"]["babble_supp_raw_db"] > -10 >
+ plain["babble@+4"]["babble_supp_db"])
+ assert (loud["real_x"]["deleted_rate_pct"] ==
+ plain["real_x"]["deleted_rate_pct"] == 0)
+ assert loud["real_x"]["median_drop_db"] == pytest.approx(0.0, abs=1e-3)
+ a = loud["real_x"]["nonvoiced_supp_db"]
+ b = plain["real_x"]["nonvoiced_supp_db"]
+ assert (math.isnan(a) and math.isnan(b)) or a == pytest.approx(b, abs=1e-3)
+
+
+SPEECH_S = ((0.3, 0.6), (0.9, 1.9)) # a 0.3 s word, then a 1 s phrase
+
+
+class _WordVad(_Vad):
+ """Stands in for Silero: the two words of _real_set, the first short."""
+
+ def segments(self, wav48):
+ w16 = torchaudio.functional.resample(wav48, SR, 16000)
+ return w16, [{
+ "start": int(a * 16000),
+ "end": int(b * 16000)
+ } for a, b in SPEECH_S]
+
+
+def _real_set(tmp_path, monkeypatch, floor, tone_hz=None):
+ """One reference-free recording: two words over a floor of RMS ``floor``,
+ white, or a tone at ``tone_hz`` (a white floor loses two thirds of its
+ power in the scorer's 16 kHz reading; a tone keeps it)."""
+ root, out_root = tmp_path / "realset", tmp_path / "out"
+ (root / "mix").mkdir(parents=True)
+ n = SECS * SR
+ if tone_hz is None:
+ mix = torch.randn(n,
+ generator=torch.Generator().manual_seed(11)) * floor
+ else:
+ t = torch.arange(n, dtype=torch.float64) / SR
+ mix = (math.sqrt(2.0) * floor *
+ torch.sin(2 * math.pi * tone_hz * t)).float()
+ for a, b in SPEECH_S:
+ a, b = int(a * SR), int(b * SR)
+ mix[a:b] += speechlike(b - a, 5)
+ _write(root / "mix" / "real_x_000.wav", mix)
+ rows = [{
+ "id": "real_x_000.wav",
+ "condition": "real_x",
+ "mix_path": "mix/real_x_000.wav",
+ "clean_path": None,
+ }]
+ with open(root / "manifest.jsonl", "w", encoding="utf-8") as fh:
+ fh.write("".join(json.dumps(r) + "\n" for r in rows))
+ json.dump({
+ "set_id": "realtiny",
+ "n_items": 1
+ }, open(root / "checksums.json", "w", encoding="utf-8"))
+ monkeypatch.setattr(common, "EVAL", str(root))
+ monkeypatch.setattr(common, "OUT_ROOT", str(out_root))
+ monkeypatch.setattr(scorebench, "NISQA_ON", False)
+ return common.manifest(str(root)), out_root
+
+
+def _real_scores(rows, name):
+ return scorebench.score_system(name, rows, _Spk(), _WordVad(),
+ None)["real_x"]
+
+
+def test_a_short_word_is_speech_and_never_a_floor_to_suppress(
+ tmp_path, monkeypatch):
+ """Every detected segment is speech; only the deletion rule needs half a
+ second of it."""
+ rows, out_root = _real_set(tmp_path, monkeypatch, floor=0.01)
+ render(rows, out_root, "same", lambda r, mix, ref: mix)
+
+ def drop_word(r, mix, ref):
+ y = mix.clone()
+ a, b = (int(t * SR) for t in SPEECH_S[0])
+ y[a:b] = 0.0
+ return y
+
+ render(rows, out_root, "dropword", drop_word)
+
+ same, dropped = _real_scores(rows, "same"), _real_scores(rows, "dropword")
+
+ assert same["nonvoiced_supp_db"] == pytest.approx(0.0, abs=1e-6)
+ # the word is speech: deleting it is not cleaning the floor
+ assert dropped["nonvoiced_supp_db"] == pytest.approx(0.0, abs=0.3)
+ # and the deletion rule reads the phrase alone, as before
+ assert same["n_segments"] == 1
+
+
+def test_the_non_voiced_floor_is_read_by_frame_with_the_delay_undone(
+ tmp_path, monkeypatch):
+ """A late passthrough and a quiet floor are not suppression; a halved floor
+ is 6 dB of it."""
+ rows, out_root = _real_set(tmp_path, monkeypatch, floor=10**(-65 / 20))
+ render(rows, out_root, "late",
+ lambda r, mix, ref: torch.cat([torch.zeros(480), mix[:-480]]))
+
+ def halved(r, mix, ref):
+ y = mix * 0.5
+ for a, b in SPEECH_S:
+ a, b = int(a * SR), int(b * SR)
+ y[a:b] = mix[a:b]
+ return y
+
+ render(rows, out_root, "halved", halved)
+
+ late, half = _real_scores(rows, "late"), _real_scores(rows, "halved")
+
+ assert abs(late["nonvoiced_supp_db"]) < 0.5
+ # the raw row: the published one undoes the system's gain, which for this
+ # system is the halving itself
+ assert half["nonvoiced_supp_raw_db"] == pytest.approx(-6.02, abs=0.4)
+
+
+def test_a_filtered_pass_leaves_the_whole_set_files_of_input_alone(
+ tiny_set, tmp_path, monkeypatch):
+ rows, out_root = tiny_set
+ render(rows, out_root, "sys", lambda r, mix, ref: mix * 0.7)
+ results = tmp_path / "results"
+ results.mkdir()
+ digest = stamprender.outputs_digest([r["id"] for r in rows],
+ str(out_root / "sys"))
+ (results / "sys.meta.json").write_text(
+ json.dumps({
+ "set_id": "tiny",
+ "name": "sys",
+ "outputs_sha256": digest
+ }))
+ # the unprocessed input's identity, as runsystem.py --input writes it
+ (results / "INPUT.meta.json").write_text(
+ json.dumps({
+ "set_id": "tiny",
+ "name": "INPUT",
+ "mechanism": "unprocessed input"
+ }))
+ monkeypatch.setattr(common, "RESULTS", str(results))
+ monkeypatch.setattr(common,
+ "SpeakerEmbedder",
+ lambda cache_dir=None: _Spk())
+ monkeypatch.setattr(common, "Vad", _Vad)
+ monkeypatch.setattr(sys, "argv", ["scorebench.py", "--systems", "sys"])
+ scorebench.main()
+ whole = (results / "INPUT.metrics.json").read_text()
+ records = (results / "INPUT.items.jsonl").read_text()
+
+ monkeypatch.setattr(
+ sys, "argv", ["scorebench.py", "--systems", "sys", "--conds", "clean"])
+ scorebench.main()
+
+ assert (results / "INPUT.metrics.json").read_text() == whole
+ assert (results / "INPUT.items.jsonl").read_text() == records
+ looked = json.loads((results / "sys.metrics.json").read_text())
+ assert looked["_selection"] == {"conds": "clean", "limit": 0}
+
+ # the discovered INPUT no more than a named one: a filtered pass over
+ # every output directory leaves it alone too
+ monkeypatch.setattr(sys, "argv", ["scorebench.py", "--conds", "clean"])
+ scorebench.main()
+
+ assert (results / "INPUT.metrics.json").read_text() == whole
+ assert (results / "INPUT.items.jsonl").read_text() == records
+
+
+def test_strong_suppression_of_a_quiet_floor_is_read_in_full(
+ tmp_path, monkeypatch):
+ """A -78 dBFS floor attenuated by 40 dB reads -40 dB: the log's guard sits
+ far below the floors the row admits (a 1e-9 guard read 12 dB here)."""
+ rows, out_root = _real_set(tmp_path,
+ monkeypatch,
+ floor=10**(-78 / 20),
+ tone_hz=700)
+
+ def cleaned(r, mix, ref):
+ y = mix * 0.01
+ for a, b in SPEECH_S:
+ a, b = int(a * SR), int(b * SR)
+ y[a:b] = mix[a:b]
+ return y
+
+ render(rows, out_root, "cleaned", cleaned)
+
+ scores = _real_scores(rows, "cleaned")
+
+ assert scores["nonvoiced_supp_raw_db"] == pytest.approx(-40.0, abs=0.5)
diff --git a/tests/bench/scripts/test_scorecontent.py b/tests/bench/scripts/test_scorecontent.py
new file mode 100644
index 0000000..cdab32e
--- /dev/null
+++ b/tests/bench/scripts/test_scorecontent.py
@@ -0,0 +1,540 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Word alignment, word classes and the verified panel.
+
+Rates are pooled, and changes are paired.
+"""
+
+# pylint: disable=unused-argument
+
+import json
+import math
+import os
+import zlib
+
+import numpy as np
+import pytest
+import soundfile as sf
+
+import common
+import observations
+import scoreasr
+import scorecontent
+
+
+class _Norm:
+
+ def tokens(self, text, language):
+ clean = "".join(
+ ch.lower() if ch.isalnum() or ch.isspace() else " " for ch in text)
+ return clean.split()
+
+
+class _Asr:
+ """Transcribes by reading ``<audio>.txt``."""
+
+ tag = "fake"
+ identity = {"engine": "fake", "model": "fake"}
+
+ def transcribe(self, path, language=None):
+ return open(path + ".txt", encoding="utf-8").read()
+
+
+def test_alignment_counts_kept_substituted_deleted_and_inserted():
+ ref = "the cat sat on the mat".split()
+ assert scorecontent.align(ref, ref) == (["kept"] * 6, 0)
+ ops, ins = scorecontent.align("the cat on the mat".split(), ref)
+ assert ops == ["kept", "kept", "del", "kept", "kept", "kept"] and ins == 0
+ ops, ins = scorecontent.align("the cat sat on a big mat".split(), ref)
+ assert ops == ["kept", "kept", "kept", "kept", "sub", "kept"] and ins == 1
+ assert scorecontent.align([], ref) == (["del"] * 6, 0)
+ assert scorecontent.align("x y".split(), []) == ([], 2)
+
+
+def test_word_classes():
+ assert [
+ scorecontent.word_class(t)
+ for t in ("1984", "3rd", "at", "the", "cat", "walk", "idea", "yes")
+ ] == [
+ "number",
+ "number",
+ "short",
+ "short",
+ "short",
+ "consonant-final",
+ "other",
+ "short",
+ ]
+ assert (scorecontent.word_class("morning") == "consonant-final" and
+ scorecontent.word_class("sofa") == "other")
+
+
+def test_the_panel_is_verified_english_paired_items_of_the_named_conditions():
+ rows = [
+ {
+ "id": "a.wav",
+ "condition": "clean",
+ "language": "en",
+ "clean_path": "r",
+ },
+ {
+ "id": "b.wav",
+ "condition": "clean",
+ "language": "en",
+ "clean_path": "r",
+ },
+ {
+ "id": "c.wav",
+ "condition": "clean",
+ "language": "de",
+ "clean_path": "r",
+ },
+ {
+ "id": "d.wav",
+ "condition": "wild@-5",
+ "language": "en",
+ "clean_path": "r",
+ },
+ {
+ "id": "e.wav",
+ "condition": "clean",
+ "language": "en"
+ },
+ ]
+ golden = {
+ "a.wav": {
+ "tier": "corpus-verified"
+ },
+ "b.wav": {
+ "tier": "recognisers-agree"
+ }, # machine agreement only: not verified
+ "c.wav": {
+ "tier": "corpus-verified"
+ },
+ "d.wav": {
+ "tier": "corpus-verified"
+ },
+ "e.wav": {
+ "tier": "gemini-accepted"
+ },
+ }
+
+ def panel_ids(conditions):
+ return [r["id"] for r in scorecontent.panel(rows, golden, conditions)]
+
+ assert panel_ids(("clean",)) == ["a.wav"]
+ golden["b.wav"]["tier"] = "human-verified"
+ assert panel_ids(("clean", "wild@-5")) == [
+ "a.wav",
+ "b.wav",
+ "d.wav",
+ ]
+
+
+def _set(tmp_path, monkeypatch):
+ root, out = tmp_path / "set", tmp_path / "out"
+ (root / "mix").mkdir(parents=True)
+ (root / "ref").mkdir()
+ texts = [
+ "the cat sat on the mat at 10",
+ "we walked home past the shop",
+ "call me at 7 tonight",
+ ]
+ rows, golden = [], {}
+ for i, text in enumerate(texts):
+ rid = f"clean_{i:03d}.wav"
+ x = (0.1 * np.sin(np.arange(12000) * (i + 1) / 50)).astype(np.float32)
+ for d in ("mix", "ref"):
+ sf.write(str(root / d / rid), x, 48000, subtype="FLOAT")
+ path = str(root / d / rid) + ".txt"
+ with open(path, "w", encoding="utf-8") as fh:
+ fh.write(text)
+ rows.append({
+ "id": rid,
+ "condition": "clean",
+ "language": "en",
+ "clean_path": str(root / "ref" / rid),
+ "mix_path": str(root / "mix" / rid),
+ })
+ golden[rid] = {
+ "id": rid,
+ "language": "en",
+ "text": text,
+ "tier": "corpus-verified",
+ }
+ json.dump(
+ {
+ "set_id": "tiny",
+ "n_items": len(rows)
+ },
+ open(root / "checksums.json", "w", encoding="utf-8"),
+ )
+ monkeypatch.setattr(common, "EVAL", str(root))
+ monkeypatch.setattr(common, "OUT_ROOT", str(out))
+ return rows, golden, out
+
+
+def _render(rows, out, name, fn):
+ (out / name).mkdir(parents=True, exist_ok=True)
+ for r in rows:
+ x, sr = sf.read(r["clean_path"], dtype="float32")
+ # perturbed by a stable hash of the transcript: outputs that transcribe
+ # differently never share bytes (the cache keys on bytes), and the same
+ # text always gives the same bytes
+ sf.write(
+ str(out / name / r["id"]),
+ x * (1 + 1e-6 * (zlib.crc32(fn(r).encode()) % 997 + 1)),
+ sr,
+ subtype="FLOAT",
+ )
+ path = str(out / name / r["id"]) + ".txt"
+ with open(path, "w", encoding="utf-8") as fh:
+ fh.write(fn(r))
+
+
+def test_rates_are_pooled_per_class_and_paired_against_the_input(
+ tmp_path, monkeypatch):
+ rows, golden, out = _set(tmp_path, monkeypatch)
+ asr = _Asr()
+ cache = scoreasr.Cache(str(tmp_path / "cache"), "fake", _Asr.identity)
+ norm = _Norm()
+ _render(rows, out, "perfect", lambda r: golden[r["id"]]["text"])
+ _render(
+ rows,
+ out,
+ "dropsshort",
+ lambda r: " ".join(t for t in golden[r["id"]]["text"].split()
+ if len(t) > 3 or t.isdigit()),
+ )
+
+ # numbers gone; a spurious word inserted early, away from them, so it
+ # reads as an insertion, not a substitution
+ def without_numbers(r):
+ kept = [t for t in golden[r["id"]]["text"].split() if not t.isdigit()]
+ return " ".join(kept[:1] + ["extra"] + kept[1:])
+
+ _render(rows, out, "dropsnumbers", without_numbers)
+ inp = scorecontent.score_system("INPUT", rows, asr, cache, norm, golden)
+ perfect = scorecontent.score_system("perfect", rows, asr, cache, norm,
+ golden)
+ short = scorecontent.score_system("dropsshort", rows, asr, cache, norm,
+ golden)
+ numbers = scorecontent.score_system("dropsnumbers", rows, asr, cache, norm,
+ golden)
+ assert (inp["rates"]["all"]["del_pct"] == 0.0 and
+ perfect["rates"]["all"]["del_pct"] == 0.0)
+ assert (short["rates"]["short"]["del_pct"] == 100.0 and
+ short["rates"]["number"]["del_pct"] == 0.0)
+ assert (short["rates"]["consonant-final"]["del_pct"] == 0.0 and
+ short["rates"]["all"]["sub_pct"] == 0.0)
+ assert (numbers["rates"]["number"]["del_pct"] == 100.0 and
+ numbers["rates"]["short"]["del_pct"] == 0.0)
+ # 19 reference words
+ assert numbers["rates"]["all"]["ins_pct"] == pytest.approx(100.0 * 3 / 19)
+ lo, hi = short["rates"]["all"]["del_ci95"]
+ assert lo <= short["rates"]["all"]["del_pct"] <= hi
+ d = scorecontent.paired_delta(short, inp)
+ assert d["n_items"] == 3 and d["delta"] > 0 and d["ci95"][0] > 0
+ assert scorecontent.paired_delta(perfect, inp)["delta"] == 0.0
+ md = scorecontent.markdown({
+ "INPUT": inp,
+ "dropsshort": short,
+ "perfect": perfect
+ })
+ assert "| INPUT | 3 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | - |" in md
+ assert "| dropsshort | 3 |" in md and "| perfect | 3 | 0.0 |" in md
+ # controls go in their own table, read against the untouched reference they
+ # were made from
+ md = scorecontent.markdown({
+ "INPUT": inp,
+ "ctl_reference": perfect,
+ "ctl_delete80ms": short
+ })
+ tables = md.split("deletions vs reference")
+ assert len(tables) == 2 and "| ctl_reference | 3 | 0.0 |" in tables[1]
+ assert "| ctl_delete80ms | 3 |" in tables[1] and "ctl_" not in tables[0]
+
+
+def test_controls_are_rendered_from_the_panel_references_and_stamped(
+ tmp_path, monkeypatch):
+ rows, _, out = _set(tmp_path, monkeypatch)
+ monkeypatch.setattr(common, "RESULTS", str(tmp_path / "results"))
+ (tmp_path / "results").mkdir()
+ systems = scorecontent.render_controls(rows, ("reference", "delete80ms"))
+ assert systems == ["ctl_reference", "ctl_delete80ms"]
+ for name in systems:
+ assert sorted(p.name for p in (out / name).iterdir()) == sorted(
+ r["id"] for r in rows)
+ meta = json.load(
+ open(tmp_path / "results" / f"{name}.meta.json", encoding="utf-8"))
+ assert meta["set_id"] == "tiny" and meta["n_files"] == len(rows)
+ assert len(meta["controls_sha256"]) == 64
+ ref, _ = sf.read(rows[0]["clean_path"], dtype="float32")
+ kept, _ = sf.read(out / "ctl_reference" / rows[0]["id"], dtype="float32")
+ cut, _ = sf.read(out / "ctl_delete80ms" / rows[0]["id"], dtype="float32")
+ assert np.array_equal(kept, ref) and (cut == 0).sum() >= int(0.076 * 48000)
+
+
+def test_control_renders_are_reused_only_while_sources_and_code_are_unchanged(
+ tmp_path, monkeypatch):
+ rows, _, out = _set(tmp_path, monkeypatch)
+ monkeypatch.setattr(common, "RESULTS", str(tmp_path / "results"))
+ (tmp_path / "results").mkdir()
+ scorecontent.render_controls(rows, ("reference",))
+ first = {
+ r["id"]: os.stat(out / "ctl_reference" / r["id"]).st_mtime_ns
+ for r in rows
+ }
+ # nothing changed: every file is kept as it is
+ scorecontent.render_controls(rows, ("reference",))
+ assert {
+ r["id"]: os.stat(out / "ctl_reference" / r["id"]).st_mtime_ns
+ for r in rows
+ } == first
+ # the reference of one item changes: that item alone is rendered again
+ x, sr = sf.read(rows[1]["clean_path"], dtype="float32")
+ sf.write(rows[1]["clean_path"], x * 0.5, sr, subtype="FLOAT")
+ scorecontent.render_controls(rows, ("reference",))
+ again = {
+ r["id"]: os.stat(out / "ctl_reference" / r["id"]).st_mtime_ns
+ for r in rows
+ }
+ assert again[rows[1]["id"]] != first[rows[1]["id"]]
+ assert all(again[r["id"]] == first[r["id"]] for r in (rows[0], rows[2]))
+ y, _ = sf.read(out / "ctl_reference" / rows[1]["id"], dtype="float32")
+ assert np.array_equal(y, x * 0.5)
+ # the controls' implementation changes: everything is rendered again
+ monkeypatch.setattr(
+ observations,
+ "implementation",
+ lambda *paths: "another implementation",
+ )
+ scorecontent.render_controls(rows, ("reference",))
+ third = {
+ r["id"]: os.stat(out / "ctl_reference" / r["id"]).st_mtime_ns
+ for r in rows
+ }
+ assert all(third[r["id"]] != again[r["id"]] for r in rows)
+ path = tmp_path / "results" / "ctl_reference.meta.json"
+ with open(path, encoding="utf-8") as fh:
+ meta = json.load(fh)
+ assert meta["controls_sha256"] == "another implementation"
+
+
+def _counts(n, dels, subs=0, cls="other"):
+ cells = {
+ c: {
+ "n": 0,
+ "kept": 0,
+ "sub": 0,
+ "del": 0
+ } for c in scorecontent.CLASSES
+ }
+ cells[cls] = {"n": n, "kept": n - dels - subs, "sub": subs, "del": dels}
+ return cells
+
+
+def _panel_rows():
+ """Six items from two recordings, each at three levels of one bed.
+
+ The set repeats its recordings the same way.
+ """
+ rows = []
+ for k, speech in enumerate(("recording-a", "recording-b")):
+ for level in ("+4", "0", "-5"):
+ rows.append({
+ "id": f"babble{level}_{k}.wav",
+ "condition": f"babble@{level}",
+ "language": "en",
+ "clean_path": "r",
+ "mix_path": "m",
+ "provenance": {
+ "speech": speech,
+ "corruptor": "[email protected]",
+ },
+ })
+ return rows
+
+
+def test_groups_are_opaque_labels_of_the_recording_and_the_bed():
+ rows = _panel_rows()
+ records = {
+ r["id"]: {
+ "condition": r["condition"],
+ "classes": _counts(10, 1),
+ "ins": 0,
+ } for r in rows
+ }
+ scorecontent.label_groups(records, rows)
+ speech = {records[r["id"]]["speech_group"] for r in rows}
+ # two recordings, however many levels; nothing names a corpus
+ assert speech == {"s0", "s1"}
+ # one bed behind every item
+ assert {records[r["id"]]["bed_group"] for r in rows} == {"b0"}
+ first = records[rows[0]["id"]]["speech_group"]
+ assert all(records[r["id"]]["speech_group"] == first for r in rows[:3])
+ groups = scorecontent.groups_of(records)
+ assert len(groups) == 2 and len(groups[0]) == 6
+
+
+def test_intervals_resample_recordings_and_change_is_pooled_rate_difference():
+ rows = _panel_rows()
+ # recording a loses a word per item, recording b loses none: the deletion
+ # rate depends on which recordings are drawn, so its interval spans from 0
+ # to about a fifth
+ left = {"items": {}, "missing": []}
+ right = {"items": {}, "missing": []}
+ for r in rows:
+ dels = 2 if r["provenance"]["speech"] == "recording-a" else 0
+ left["items"][r["id"]] = {
+ "condition": r["condition"],
+ "classes": _counts(10, dels),
+ "ins": 0,
+ }
+ right["items"][r["id"]] = {
+ "condition": r["condition"],
+ "classes": _counts(10, 0),
+ "ins": 0,
+ }
+ scorecontent.label_groups(left["items"], rows)
+ scorecontent.label_groups(right["items"], rows)
+ left["rates"] = scorecontent.pooled(left["items"])
+ right["rates"] = scorecontent.pooled(right["items"])
+ assert (left["rates"]["all"]["del_pct"] == 10.0 and
+ right["rates"]["all"]["del_pct"] == 0.0)
+ assert (
+ left["rates"]["all"]["n_items"],
+ left["rates"]["all"]["n_recordings"],
+ left["rates"]["all"]["n_beds"],
+ ) == (6, 2, 1)
+ assert ("rest on the 2 recordings and 1 beds behind the 6 items"
+ in scorecontent.markdown({
+ "INPUT": right,
+ "sys": left
+ }))
+ lo, hi = left["rates"]["all"]["del_ci95"]
+ # only recording b drawn ... only recording a drawn
+ assert lo == 0.0 and hi == 20.0
+ d = scorecontent.paired_delta(left, right)
+ assert (d["delta"] == 10.0 and d["ci95"] == [0.0, 20.0] and
+ not d["incomplete"])
+ assert d["n_items"] == 6
+ # an item-level bootstrap would have read the six items as independent and
+ # given a tighter interval; the clustered one cannot exclude zero from two
+ # recordings
+ items = np.array([20.0, 20.0, 20.0, 0.0, 0.0, 0.0])
+ rng = np.random.default_rng(0)
+ boots = [items[rng.integers(0, 6, 6)].mean() for _ in range(1000)]
+ assert np.percentile(boots, 2.5) > 0.0
+
+
+def test_incomplete_cohorts_are_marked_never_intersected():
+ rows = _panel_rows()
+ full = {"items": {}, "missing": []}
+ part = {"items": {}, "missing": [rows[-1]["id"]]}
+ for r in rows:
+ full["items"][r["id"]] = {
+ "condition": r["condition"],
+ "classes": _counts(10, 0),
+ "ins": 0,
+ }
+ if r["id"] != rows[-1]["id"]:
+ part["items"][r["id"]] = {
+ "condition": r["condition"],
+ "classes": _counts(10, 1),
+ "ins": 0,
+ }
+ scorecontent.label_groups(full["items"], rows)
+ scorecontent.label_groups(part["items"], rows[:-1])
+ full["rates"] = scorecontent.pooled(full["items"])
+ part["rates"] = scorecontent.pooled(part["items"])
+ d = scorecontent.paired_delta(part, full)
+ assert (d["incomplete"] and math.isnan(d["delta"]) and
+ d["missing"] == [rows[-1]["id"]])
+ md = scorecontent.markdown({"INPUT": full, "partial": part})
+ assert ("| partial | 5 of 6 (incomplete) |" in md and
+ "incomplete (1 items differ)" in md)
+ assert "| INPUT | 6 |" in md
+
+
+def test_missing_outputs_are_listed_not_skipped(tmp_path, monkeypatch):
+ rows, golden, out = _set(tmp_path, monkeypatch)
+ asr = _Asr()
+ cache = scoreasr.Cache(str(tmp_path / "cache"), "fake", _Asr.identity)
+ norm = _Norm()
+ _render(rows[:2], out, "partial", lambda r: golden[r["id"]]["text"])
+ res = scorecontent.score_system("partial", rows, asr, cache, norm, golden)
+ assert res["missing"] == [rows[2]["id"]] and len(res["items"]) == 2
+ assert math.isfinite(res["rates"]["all"]["del_pct"])
+
+
+def test_incompatible_recognisers_or_reference_tokens_are_refused():
+ rows = _panel_rows()
+ left = {
+ "items": {},
+ "missing": [],
+ "asr_identity": {
+ "engine": "whisper",
+ "model": "large-v3"
+ },
+ }
+ right = {
+ "items": {},
+ "missing": [],
+ "asr_identity": {
+ "engine": "whisper",
+ "model": "small"
+ },
+ }
+ for r in rows:
+ left["items"][r["id"]] = {
+ "condition": r["condition"],
+ "classes": _counts(10, 1),
+ "ins": 0,
+ }
+ right["items"][r["id"]] = {
+ "condition": r["condition"],
+ "classes": _counts(10, 1),
+ "ins": 0,
+ }
+ scorecontent.label_groups(left["items"], rows)
+ scorecontent.label_groups(right["items"], rows)
+ left["rates"] = scorecontent.pooled(left["items"])
+ right["rates"] = scorecontent.pooled(right["items"])
+ d = scorecontent.paired_delta(left, right)
+ assert d["incompatible"] == "recognisers differ" and math.isnan(d["delta"])
+ right["asr_identity"] = dict(left["asr_identity"])
+ assert scorecontent.paired_delta(left, right)["delta"] == 0.0
+ # equal pooled rates over different reference token counts: no difference
+ # may be reported
+ # 10 % as well, on four times the words
+ right["items"][rows[0]["id"]]["classes"] = _counts(40, 4)
+ right["rates"] = scorecontent.pooled(right["items"])
+ d = scorecontent.paired_delta(left, right)
+ assert d["incompatible"] == "reference tokens differ" and math.isnan(
+ d["delta"])
+ md = scorecontent.markdown({"INPUT": right, "sys": left})
+ assert "incompatible (reference tokens differ)" in md
+ # a loaded sidecar carries the identity under its underscore key
+ sidecar = {"_asr_identity": {"engine": "x"}}
+ assert scorecontent.asr_identity(sidecar) == {"engine": "x"}
+
+
+def test_a_system_without_a_render_is_skipped_before_scoring(
+ tmp_path, monkeypatch):
+ monkeypatch.setattr(common, "OUT_ROOT", str(tmp_path / "out"))
+ assert "no outputs" in scorecontent.missing_render("ghost")
+ assert scorecontent.missing_render("INPUT") == ""
+ os.makedirs(tmp_path / "out" / "ghost")
+ assert scorecontent.missing_render("ghost") == ""
diff --git a/tests/bench/scripts/test_scoreevents.py b/tests/bench/scripts/test_scoreevents.py
new file mode 100644
index 0000000..4a23f0b
--- /dev/null
+++ b/tests/bench/scripts/test_scoreevents.py
@@ -0,0 +1,692 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The events sidecar: labelled events and floors in, what its rows say out."""
+
+import json
+import math
+import sys
+
+import numpy as np
+import pytest
+import soundfile as sf
+import torch
+
+import common
+import observations
+import scorebench
+import scoreevents
+
+SR = common.SR
+
+
+class _Vad:
+ """Speech from 1.0 to 2.0 s and from 2.6 to 3.4 s of a 4 s item."""
+
+ def segments(self, x):
+ del x
+ return None, [{
+ "start": 16000,
+ "end": 32000
+ }, {
+ "start": 41600,
+ "end": 54400
+ }]
+
+
+def _burst(n, seed, db):
+ g = torch.Generator().manual_seed(seed)
+ return torch.randn(n, generator=g) * 10**(db / 20)
+
+
+def _same_room_item(seed=0, floor_db=-50.0):
+ """A voice over a pause, an event in the pause and one under the voice."""
+ n = 4 * SR
+ ref = torch.zeros(n)
+ for a, b in ((1.0, 2.0), (2.6, 3.4)):
+ a, b = round(a * SR), round(b * SR)
+ ref[a:b] = _burst(b - a, seed, -12.0)
+ noise = _burst(n, seed + 1, floor_db)
+ events = []
+ for start, kind in ((2.2, "pause"), (1.4, "speech")):
+ length = int(0.1 * SR)
+ a = int(start * SR)
+ noise[a:a + length] += _burst(length, seed + 2, -15.0)
+ events.append([start, start + 0.1, kind, "household", "x", -15.0])
+ row = {
+ "id": "coroomATboth_000.wav",
+ "condition": "coroom@both",
+ "mix_path": "unused",
+ "clean_path": "unused",
+ "provenance": {
+ "events": sorted(events),
+ "pauses": [[2.0, 2.6]],
+ "room_share_rule": scoreevents.ROOM_SHARE_RULE,
+ },
+ }
+ return row, ref + noise, ref, noise
+
+
+def _rows(it,
+ out,
+ mix,
+ ref,
+ out_ref=None,
+ gain_db=0.0,
+ lag=0,
+ room_share_db=0.0):
+ """The item's rows; the system renders the reference unchanged unless
+ ``out_ref`` says otherwise."""
+ out_ref = ref if out_ref is None else out_ref
+ return scoreevents.same_room_metrics(
+ scoreevents.score_same_room(it, out, mix, ref, out_ref, gain_db, lag,
+ room_share_db), it["condition"])
+
+
+def test_the_unchanged_mixture_reads_zero_and_the_reference_reads_the_bound():
+ it, mix, ref, _ = _same_room_item()
+ same = _rows(it, mix, mix, ref)
+ assert same["event_resid_db"] == pytest.approx(0.0, abs=1e-6)
+ assert same["floor_resid_db"] == pytest.approx(0.0, abs=1e-6)
+ # the floor under the voice is -38 dB down: its cross term is below 0.01 dB
+ assert same["voice_level_db"] == pytest.approx(0.0, abs=0.01)
+ clean = _rows(it, ref, mix, ref)
+ assert clean["event_resid_db"] == -scoreevents.ITEM_CLIP_DB
+ assert clean["floor_resid_db"] == -scoreevents.ITEM_CLIP_DB
+ assert clean["voice_level_db"] == pytest.approx(0.0, abs=1e-6)
+ # the unbounded rows stand beside, floored where nothing is left
+ assert same["event_resid_raw_db"] == pytest.approx(0.0, abs=1e-6)
+ assert clean["event_resid_raw_db"] == scoreevents.RAW_FLOOR_DB
+ assert clean["floor_resid_raw_db"] == scoreevents.RAW_FLOOR_DB
+
+
+def test_a_known_reduction_of_the_added_noise_reads_true():
+ it, mix, ref, noise = _same_room_item()
+ for db in (6.0, 12.0):
+ rows = _rows(it, ref + noise * 10**(-db / 20), mix, ref)
+ assert rows["event_resid_db"] == pytest.approx(-db, abs=0.05)
+ assert rows["floor_resid_db"] == pytest.approx(-db, abs=0.05)
+ assert rows["voice_level_db"] == pytest.approx(0.0, abs=0.05)
+
+
+def test_the_voice_turned_down_reads_as_lost_unless_it_is_the_systems_gain():
+ it, mix, ref, _ = _same_room_item()
+ # the voice ducked while the noise is there: the reference's render keeps
+ # its level, the mixture's loses 6 dB
+ quieter = _rows(it, mix * 10**(-6 / 20), mix, ref)
+ assert quieter["voice_level_db"] == pytest.approx(-6.0, abs=0.1)
+ # a system's gain applies to both renders and the base scores undo it
+ gain = 10**(-6 / 20)
+ undone = _rows(it, mix * gain, mix, ref, out_ref=ref * gain, gain_db=-6.0)
+ assert undone["voice_level_db"] == pytest.approx(0.0, abs=0.01)
+ assert undone["event_resid_db"] == pytest.approx(0.0, abs=1e-5)
+ # the same gain unaccounted for reads as the noise reduced by it and,
+ # against the reference, as the voice turned down: a render quieter on
+ # the block than its base scores say is attenuation, not a gain
+ kept = _rows(it, mix * gain, mix, ref, out_ref=ref * gain)
+ # (the noise under the loudest frames adds a few hundredths of a dB)
+ assert kept["voice_pair_db"] == pytest.approx(0.0, abs=0.1)
+ assert kept["voice_level_db"] == pytest.approx(-6.0, abs=0.1)
+ # and with the voice under the gate, nothing counts as removed
+ assert kept["event_resid_db"] == 0.0 and kept["floor_resid_db"] == 0.0
+
+
+def test_the_systems_delay_is_undone_and_its_polarity_cannot_matter():
+ it, mix, ref, _ = _same_room_item()
+ late = (-torch.roll(mix, 37), -torch.roll(ref, 37))
+ exact = _rows(it, late[0], mix, ref, out_ref=late[1], lag=37)
+ assert exact["event_resid_db"] == pytest.approx(0.0, abs=1e-6)
+ assert exact["floor_resid_db"] == pytest.approx(0.0, abs=1e-6)
+ # the floor's cross term on the loudest frames, as for the unchanged mixture
+ assert exact["voice_level_db"] == pytest.approx(0.0, abs=0.01)
+ # a delay not undone only moves the spans a little against the output
+ rows = _rows(it, late[0], mix, ref, out_ref=late[1])
+ assert rows["event_resid_db"] == pytest.approx(0.0, abs=0.2)
+ assert rows["floor_resid_db"] == pytest.approx(0.0, abs=0.2)
+ assert rows["voice_level_db"] == pytest.approx(0.0, abs=0.2)
+
+
+def test_what_a_system_makes_of_the_room_is_charged_on_neither_row():
+ """A system that removes the voice's room and leaves the noise reads the
+ noise untouched: the room it removed is in both renders."""
+ it, dry, _, noise = _same_room_item()
+ tail = 0.5 * torch.roll(dry, 2400) # 50 ms of room after the voice
+ wet = dry + tail
+ mix = wet + noise
+ # the room's share of the reference's level on the frames the voice row
+ # reads, as the set's provenance records it
+ energies = scoreevents.score_same_room(it, dry, mix, wet, dry, 0.0, 0, 0.0)
+ share = 10 * math.log10(energies["voice_ref"] / energies["voice"][1])
+ paired = _rows(it, dry + noise, mix, wet, out_ref=dry, room_share_db=share)
+ assert paired["event_resid_db"] == pytest.approx(0.0, abs=1e-6)
+ assert paired["floor_resid_db"] == pytest.approx(0.0, abs=1e-6)
+ assert paired["voice_level_db"] == pytest.approx(0.0, abs=0.05)
+ # read against the reference alone, the room it removed would have
+ # counted as noise left under the speech and in the pause
+ against_ref = _rows(it, dry + noise, mix, wet, out_ref=wet)
+ assert against_ref["event_resid_db"] > 1.0
+ assert against_ref["floor_resid_db"] > 1.0
+
+
+def test_each_event_is_bounded_before_the_item_reads():
+ it, mix, ref, noise = _same_room_item()
+ # one event removed outright, the other left as it was: half the credit
+ gone = noise.clone()
+ a = int(2.2 * SR)
+ gone[a - 2 * scoreevents.FRAME:a + int((0.1 + scoreevents.DECAY_S) * SR) +
+ 2 * scoreevents.FRAME] = 0.0
+ rows = _rows(it, ref + gone, mix, ref)
+ assert rows["event_resid_db"] == pytest.approx(-scoreevents.ITEM_CLIP_DB /
+ 2,
+ abs=0.05)
+ assert rows["event_resid_raw_db"] == pytest.approx(
+ scoreevents.RAW_FLOOR_DB / 2, abs=0.05)
+
+
+def test_the_voice_row_is_the_lower_of_the_paired_and_the_anchored_read():
+ it, mix, ref, _ = _same_room_item()
+ # both renders 10 dB down: the noise reads as reduced by the scaling,
+ # the voice against the reference as 10 dB down
+ down = 10**(-10 / 20)
+ both = _rows(it, mix * down, mix, ref, out_ref=ref * down)
+ assert both["voice_pair_db"] == pytest.approx(0.0, abs=0.1)
+ assert both["voice_kept_db"] == pytest.approx(-10.0, abs=0.1)
+ assert both["voice_level_db"] == pytest.approx(-10.0, abs=0.1)
+ # the room's share is allowed: a render quieter by just that much reads
+ # as the voice kept
+ allowed = _rows(it,
+ mix * down,
+ mix,
+ ref,
+ out_ref=ref * down,
+ room_share_db=10.0)
+ assert allowed["voice_level_db"] == pytest.approx(0.0, abs=0.1)
+ # a voice ducked with the noise there is read by the paired side,
+ # whatever the allowance
+ ducked = _rows(it, mix * down, mix, ref, room_share_db=10.0)
+ assert ducked["voice_level_db"] == pytest.approx(-10.0, abs=0.1)
+ # a render with no voice on its loudest frames reads the bound, not nothing
+ silent = _rows(it,
+ torch.zeros_like(mix),
+ mix,
+ ref,
+ out_ref=torch.zeros_like(ref))
+ assert silent["voice_level_db"] == -scoreevents.ITEM_CLIP_DB
+ # and silence removes nothing: the noise rows read as left
+ assert silent["event_resid_db"] == 0.0 and silent["floor_resid_db"] == 0.0
+
+
+def test_speech_muted_in_both_renders_shows_against_the_reference():
+ it, mix, ref, _ = _same_room_item()
+ a = int(1.4 * SR)
+ b = int(1.5 * SR) + int(scoreevents.DECAY_S * SR)
+ out_mix, out_ref = ref.clone(), ref.clone() # the noise removed...
+ out_mix[a:b] = 0.0 # ...and the voice muted under the event, in both
+ out_ref[a:b] = 0.0
+ rows = _rows(it, out_mix, mix, ref, out_ref=out_ref)
+ assert rows["voice_pair_db"] == pytest.approx(0.0, abs=0.01)
+ assert rows["voice_level_db"] < -0.3
+
+
+def test_removal_is_credited_only_while_the_voice_is_kept():
+ it, mix, ref, noise = _same_room_item()
+ # a mild loss keeps the credit, the declared floor takes it away
+ mild = _rows(it, (ref + noise * 0.5) * 10**(-2 / 20),
+ mix,
+ ref,
+ out_ref=ref * 10**(-2 / 20))
+ assert mild["voice_level_db"] == pytest.approx(-2.0, abs=0.1)
+ assert mild["event_resid_db"] == pytest.approx(-6.0 - 2.0, abs=0.1)
+ gone = _rows(it, (ref + noise * 0.5) * 10**(-4 / 20),
+ mix,
+ ref,
+ out_ref=ref * 10**(-4 / 20))
+ assert gone["voice_level_db"] == pytest.approx(-4.0, abs=0.1)
+ assert gone["event_resid_db"] == 0.0 and gone["floor_resid_db"] == 0.0
+ # deleting the speech an event sits on, in both renders, is not removal:
+ # that event reads as left while the event in the pause keeps its credit
+ a, b = int(1.4 * SR), int(1.5 * SR) + int(scoreevents.DECAY_S * SR)
+ out_mix, out_ref = ref.clone(), ref.clone()
+ out_mix[a:b] = 0.0
+ out_ref[a:b] = 0.0
+ rows = _rows(it, out_mix, mix, ref, out_ref=out_ref)
+ assert rows["event_resid_db"] == pytest.approx(-scoreevents.ITEM_CLIP_DB /
+ 2,
+ abs=0.05)
+ assert rows["event_resid_raw_db"] == pytest.approx(
+ scoreevents.RAW_FLOOR_DB / 2, abs=0.05)
+
+
+def _wav(path, x):
+ path.parent.mkdir(parents=True, exist_ok=True)
+ sf.write(path, x.numpy(), SR, subtype="FLOAT")
+ return str(path)
+
+
+def test_assemble_reads_the_pair_render_and_marks_one_that_is_missing(
+ tmp_path, monkeypatch):
+ it, mix, ref, noise = _same_room_item()
+ it = dict(it,
+ mix_path=_wav(tmp_path / "set" / "mix" / it["id"], mix),
+ clean_path=_wav(tmp_path / "set" / "ref" / it["id"], ref))
+ monkeypatch.setattr(common, "OUT_ROOT", str(tmp_path / "out"))
+ _wav(tmp_path / "out" / "sys" / it["id"], ref + noise * 10**(-6 / 20))
+ pair_out = tmp_path / "pair" / "out" / "sys"
+ _wav(pair_out / it["id"], ref)
+ records = scoreevents.assemble("sys", [it],
+ None,
+ 0.0,
+ pair_out=str(pair_out))
+ assert records[0]["output_status"] == "ok"
+ assert records[0]["identity"]["pair_output"]
+ rows = scoreevents.same_room_metrics(
+ observations.revive(records[0]["measurements"]), it["condition"])
+ assert rows["event_resid_db"] == pytest.approx(-6.0, abs=0.05)
+ assert scoreevents.pair_outputs_digest(records) == scoreevents.identity_of(
+ [records[0]["identity"]["pair_output"]])
+ # the record is reused only for the same pair of renders
+ reuse = {
+ scorebench.reuse_key(records[0]["identity"]):
+ dict(records[0], gain_db=0.0)
+ }
+ again = scoreevents.assemble("sys", [it],
+ None,
+ 0.0,
+ reuse=reuse,
+ pair_out=str(pair_out))
+ assert again[0]["measurements"] == records[0]["measurements"]
+ other_lag = scoreevents.assemble("sys", [it],
+ None,
+ 0.0,
+ reuse=reuse,
+ pair_out=str(pair_out),
+ lag=5)
+ assert other_lag[0]["lag"] == 5
+ assert other_lag[0]["measurements"] != records[0]["measurements"]
+ _wav(pair_out / it["id"], ref * 0.5)
+ fresh = scoreevents.assemble("sys", [it],
+ None,
+ 0.0,
+ reuse=reuse,
+ pair_out=str(pair_out))
+ assert fresh[0]["identity"]["pair_output"] != records[0]["identity"][
+ "pair_output"]
+ assert fresh[0]["measurements"] != records[0]["measurements"]
+ missing = scoreevents.assemble("sys", [it],
+ None,
+ 0.0,
+ pair_out=str(tmp_path / "nowhere"))
+ assert missing[0]["output_status"] == "missing_pair"
+ assert scoreevents.pair_outputs_digest(missing) is None
+ _wav(pair_out / it["id"], ref[:-480])
+ short = scoreevents.assemble("sys", [it], None, 0.0, pair_out=str(pair_out))
+ assert short[0]["output_status"] == "wrong_length_pair"
+ # INPUT's pair render is the reference itself
+ unchanged = scoreevents.assemble("INPUT", [it], None, 0.0)
+ rows = scoreevents.same_room_metrics(
+ observations.revive(unchanged[0]["measurements"]), it["condition"])
+ assert rows["event_resid_db"] == pytest.approx(0.0, abs=1e-6)
+
+
+def test_the_pair_links_the_references_and_its_renders_carry_the_board(
+ tmp_path, monkeypatch):
+ set_dir = tmp_path / "set"
+ set_dir.mkdir()
+ with open(set_dir / "checksums.json", "w", encoding="utf-8") as fh:
+ json.dump({"set_id": "tiny"}, fh)
+ monkeypatch.setattr(common, "EVAL", str(set_dir))
+ it, mix, ref, _ = _same_room_item()
+ rows = [
+ dict(it,
+ mix_path=_wav(set_dir / "mix" / it["id"], mix),
+ clean_path=_wav(set_dir / "ref" / it["id"], ref)),
+ _real_item()[0],
+ ]
+ root = tmp_path / "pair"
+ assert scoreevents.pair_problem(str(root), rows) == "no probe.json"
+ pair = scoreevents.write_pair(rows, str(root))
+ assert pair["kind"] == scoreevents.PAIR_KIND and pair["set_id"] == "tiny"
+ assert [e["id"] for e in pair["items"]] == [it["id"]]
+ assert pair["identity"] == scoreevents.identity_of(
+ [scorebench.sample_hash(ref)])
+ assert scoreevents.pair_problem(str(root), rows) is None
+ assert scoreevents.write_pair(rows, str(root)) == pair
+ stray = root / "in" / "extra.wav"
+ stray.write_bytes(b"")
+ assert "not pair inputs" in scoreevents.pair_problem(str(root), rows)
+ stray.unlink()
+ with pytest.raises(SystemExit, match="link the pair again"):
+ scoreevents.read_pair(str(tmp_path / "elsewhere"), rows)
+ results = tmp_path / "results"
+ results.mkdir()
+
+ def problem():
+ return scoreevents.pair_render_problem("sys", str(results), str(root),
+ pair)
+
+ assert "no stamp" in problem()
+ with open(results / "sys.meta.json", "w", encoding="utf-8") as fh:
+ json.dump({"render_environment_sha256": "env-board"}, fh)
+ assert "no pair render" in problem()
+ out = root / "out" / "sys"
+ out.mkdir(parents=True)
+ assert "no receipt" in problem()
+
+ def receipt_of(environment, inputs):
+ with open(out / ".receipt-1.json", "w", encoding="utf-8") as fh:
+ json.dump(
+ {
+ "environment_digest": environment,
+ "identity": {
+ "inputs": {
+ "probe": inputs
+ }
+ }
+ }, fh)
+
+ receipt_of("env-other", pair["identity"])
+ assert "another environment" in problem()
+ receipt_of("env-board", "other-inputs")
+ assert "other inputs" in problem()
+ receipt_of("env-board", pair["identity"])
+ assert problem() is None
+
+
+def test_only_the_conditions_with_a_layer_read_its_row():
+ it, mix, ref, _ = _same_room_item()
+ it_floor = dict(it, condition="coroom@floor")
+ rows = _rows(it_floor, mix, mix, ref)
+ assert "event_resid_db" not in rows and "floor_resid_db" in rows
+ it_pause = dict(it, condition="coroom@pause")
+ rows = _rows(it_pause, mix, mix, ref)
+ assert "event_resid_db" in rows and "floor_resid_db" not in rows
+
+
+def _real_item(seed=0, with_event=True):
+ """A voice over a quiet floor with, by default, one impact in its pause."""
+ n = 4 * SR
+ x = _burst(n, seed, -55.0)
+ for a, b in ((1.0, 2.0), (2.6, 3.4)):
+ a, b = round(a * SR), round(b * SR)
+ x[a:b] += _burst(b - a, seed + 1, -12.0)
+ if with_event:
+ a = int(2.25 * SR)
+ x[a:a + int(0.05 * SR)] += _burst(int(0.05 * SR), seed + 2, -18.0)
+ return {
+ "id": f"real_x_{seed:03d}.wav",
+ "condition": "real_everyday",
+ "mix_path": "unused"
+ }, x
+
+
+def test_real_recordings_read_the_events_the_input_holds_outside_speech():
+ it, x = _real_item()
+ m = scoreevents.score_real(it, x, x, _Vad(), 0.0)
+ assert len(m["events"]) == 1 and m["event_spans_s"][0][0] == pytest.approx(
+ 2.25, abs=0.02)
+ same = scoreevents.real_metrics(m)
+ assert same["n_events"] == 1
+ assert same["event_att_db"] == pytest.approx(0.0, abs=1e-6)
+ assert same["voice_level_db"] == pytest.approx(0.0, abs=1e-6)
+ y = x.clone()
+ a = int(2.2 * SR)
+ y[a:a + int(0.3 * SR)] *= 10**(-10 / 20)
+ reduced = scoreevents.real_metrics(
+ scoreevents.score_real(it, y, x, _Vad(), 0.0))
+ assert reduced["event_att_db"] == pytest.approx(-10.0, abs=0.3)
+ quiet_it, quiet = _real_item(with_event=False)
+ none = scoreevents.real_metrics(
+ scoreevents.score_real(quiet_it, quiet, quiet, _Vad(), 0.0))
+ assert none["n_events"] == 0 and "event_att_db" not in none
+
+
+def test_the_detector_ignores_speech_onsets_and_the_spans_follow_the_definition(
+):
+ db = np.full(300, -60.0)
+ db[100:110] = -30.0
+ assert scoreevents.detect_events(db) == [(100, 110)]
+ db[150] = -50.0
+ assert scoreevents.detect_events(db) == [(100, 110)]
+
+
+def _records(rows, out_by_id):
+ records = []
+ for it in rows:
+ rec = observations.item(it)
+ if it["id"] not in out_by_id:
+ rec["output_status"] = "missing"
+ records.append(rec)
+ continue
+ out, mix, ref = out_by_id[it["id"]]
+ if ref is not None:
+ rec["measurements"] = observations.finite(
+ scoreevents.score_same_room(it, out, mix, ref, ref, 0.0))
+ else:
+ rec["measurements"] = observations.finite(
+ scoreevents.score_real(it, out, mix, _Vad(), 0.0))
+ records.append(rec)
+ return records
+
+
+def test_aggregate_pools_the_block_and_the_real_items_with_events():
+ it, mix, ref, noise = _same_room_item()
+ it_floor = dict(it, id="coroomATfloor_000.wav", condition="coroom@floor")
+ real_with, x_with = _real_item(1)
+ real_without, x_without = _real_item(2, with_event=False)
+ missing = dict(it, id="coroomATboth_001.wav")
+ rows = [it, it_floor, real_with, real_without, missing]
+ outputs = {
+ it["id"]: (ref + noise * 10**(-6 / 20), mix, ref),
+ it_floor["id"]: (ref, mix, ref),
+ real_with["id"]: (x_with, x_with, None),
+ real_without["id"]: (x_without, x_without, None),
+ }
+ out = scoreevents.aggregate(_records(rows, outputs), rows, 0.0)
+ assert out["coroom@both"]["n"] == 1 and out["coroom@both"]["n_missing"] == 1
+ assert out["coroom@both"]["event_resid_db"] == pytest.approx(-6.0, abs=0.05)
+ assert out["coroom@floor"]["floor_resid_db"] == -scoreevents.ITEM_CLIP_DB
+ block = out["_coroom"]
+ assert block["n"] == 2 and block["n_expected"] == 3 and block[
+ "n_missing"] == 1
+ assert block["event_resid_db"] == pytest.approx(-6.0, abs=0.05)
+ assert block["floor_resid_db"] == pytest.approx(
+ (-6.0 - scoreevents.ITEM_CLIP_DB) / 2, abs=0.05)
+ assert block["metric_counts"] == {
+ "event_resid_db": 1,
+ "event_resid_raw_db": 1,
+ "floor_resid_db": 2,
+ "floor_resid_raw_db": 2,
+ "voice_level_db": 2,
+ "voice_pair_db": 2,
+ "voice_kept_db": 2,
+ }
+ assert out["coroom@floor"]["metric_counts"]["floor_resid_db"] == 1
+ real = out["_real_events"]
+ assert real["n"] == 1 and real["n_without_events"] == 1 and real[
+ "n_events"] == 1
+ assert real["event_att_db"] == pytest.approx(0.0, abs=1e-6)
+ assert out["_level_cal_db"] == 0.0
+
+
+def test_a_view_re_reads_the_records_at_its_own_calibration():
+ it, mix, ref, noise = _same_room_item()
+ real_with, x_with = _real_item(1)
+ rows = [it, real_with]
+ outputs = {
+ it["id"]: (ref + noise * 10**(-6 / 20), mix, ref),
+ real_with["id"]: (x_with, x_with, None),
+ }
+ records = _records(rows, outputs)
+ for rec in records:
+ rec["gain_db"] = 0.0
+ whole = scoreevents.aggregate(records, rows, 0.0)
+ # 6 dB more gain undone: 6 dB less of the noise left, 6 dB less voice
+ # against the reference, the paired voice read unchanged
+ view = scoreevents.aggregate(records, rows, 6.0)
+ # 6 dB of voice lost is under the gate: the view credits no removal
+ assert view["coroom@both"]["event_resid_db"] == 0.0
+ assert view["coroom@both"]["floor_resid_db"] == 0.0
+ # at 2 dB the voice is kept and the rows move with the gain
+ mild = scoreevents.aggregate(records, rows, 2.0)
+ assert mild["coroom@both"]["event_resid_db"] == pytest.approx(
+ whole["coroom@both"]["event_resid_db"] - 2.0, abs=0.05)
+ assert mild["coroom@both"]["voice_level_db"] == pytest.approx(-2.0, abs=0.1)
+ assert view["coroom@both"]["voice_level_db"] == pytest.approx(-6.0, abs=0.1)
+ assert view["coroom@both"]["voice_pair_db"] == pytest.approx(
+ whole["coroom@both"]["voice_pair_db"], abs=1e-6)
+ assert view["_real_events"]["event_att_db"] == pytest.approx(-6.0, abs=1e-6)
+ assert view["_real_events"]["voice_level_db"] == pytest.approx(-6.0,
+ abs=1e-6)
+ assert view["_level_cal_db"] == 6.0
+
+
+def test_a_label_edit_makes_the_cached_measurement_stale():
+ """Event spans, pauses, the floor and the room allowance are what a
+ same-room measurement reads: changing any of them changes its identity."""
+ row = {
+ "id": "coroomATboth_000.wav",
+ "condition": "coroom@both",
+ "provenance": {
+ "events": [[1.0, 1.1, "speech", "household", "src:a", -23.0]],
+ "pauses": [[2.0, 3.0]],
+ "floor": {
+ "corruptor": "src:b",
+ "floor_dbfs": -60.0
+ },
+ "split": "main",
+ "room_share_db": 0.8,
+ "room_share_rule": scoreevents.ROOM_SHARE_RULE,
+ "scene": 0,
+ },
+ }
+ base = scoreevents.labels_digest(row)
+ assert base is not None
+ for key, value in (("events",
+ [[1.05, 1.1, "speech", "household", "src:a",
+ -23.0]]), ("pauses", [[2.0, 3.1]]),
+ ("room_share_db", 0.9), ("floor", {
+ "corruptor": "src:b",
+ "floor_dbfs": -55.0
+ })):
+ edited = dict(row, provenance=dict(row["provenance"], **{key: value}))
+ assert scoreevents.labels_digest(edited) != base, key
+ # a field no measurement reads leaves the identity alone
+ other = dict(row, provenance=dict(row["provenance"], scene=7))
+ assert scoreevents.labels_digest(other) == base
+ assert scoreevents.labels_digest({"condition": "babble@+4"}) is None
+
+
+def test_a_view_refuses_records_measured_under_other_labels(
+ tmp_path, monkeypatch, capsys):
+ """The aggregate-only entry path compares every same-room record's labels
+ with the current manifest: a relabelled item stops the view instead of
+ deriving it from the old observations."""
+ row = {
+ "id": "coroomATboth_000.wav",
+ "condition": "coroom@both",
+ "provenance": {
+ "events": [[1.0, 1.1, "speech", "household", "src:a", -23.0]],
+ "pauses": [[2.0, 3.0]],
+ "floor": {
+ "corruptor": "src:b",
+ "floor_dbfs": -60.0
+ },
+ "split": "main",
+ "room_share_db": 0.8,
+ "room_share_rule": scoreevents.ROOM_SHARE_RULE,
+ },
+ }
+ record = {
+ "id": row["id"],
+ "output_status": "ok",
+ "identity": {
+ "labels": scoreevents.labels_digest(row)
+ },
+ "measurements": {},
+ }
+ relabelled = json.loads(json.dumps(row))
+ relabelled["provenance"]["events"] = []
+ relabelled["provenance"]["room_share_db"] = 99.0
+ written = []
+ monkeypatch.setattr(common, "guard_private_results", lambda rows: None)
+ monkeypatch.setattr(common, "RESULTS", str(tmp_path))
+ monkeypatch.setattr(
+ scorebench, "view_records", lambda path, name, ids, sha: ("", {
+ "outputs_sha256": None,
+ "lag": 0
+ }, [record]))
+ monkeypatch.setattr(scoreevents, "base_calibration", lambda *a: (0.0, 0))
+ monkeypatch.setattr(scoreevents, "aggregate", lambda *a: {})
+ monkeypatch.setattr(scoreevents, "write", lambda *a: written.append(a))
+ monkeypatch.setattr(sys, "argv", [
+ "scoreevents.py", "--systems", "half", "--aggregate-only",
+ str(tmp_path)
+ ])
+ monkeypatch.setattr(common, "manifest", lambda: [relabelled])
+ scoreevents.main()
+ assert not written
+ assert "measured under other labels" in capsys.readouterr().out
+ monkeypatch.setattr(common, "manifest", lambda: [row])
+ scoreevents.main()
+ assert len(written) == 1
+
+
+def test_turning_both_renders_down_earns_no_removal_credit():
+ """Attenuating the output on both renders shrinks the measured residue,
+ so without the voice gate it would read as noise removed; at and beyond
+ the voice row's floor every such item reads its removal rows as left,
+ whatever the attenuation, and the board cannot be gamed by ducking."""
+ it, mix, ref, _ = _same_room_item()
+ for gain_db in (-3.1, -6.0, -9.9):
+ gain = 10**(gain_db / 20)
+ rows = _rows(it, mix * gain, mix, ref, out_ref=ref * gain)
+ assert rows["voice_level_db"] == pytest.approx(gain_db, abs=0.1)
+ assert rows["event_resid_db"] == 0.0 and rows["floor_resid_db"] == 0.0
+ # just above the floor the voice row charges the loss and the residue
+ # rows read the attenuation as removal: the two move together
+ mild = _rows(it, mix * 10**(-2 / 20), mix, ref, out_ref=ref * 10**(-2 / 20))
+ assert mild["voice_level_db"] == pytest.approx(-2.0, abs=0.1)
+ assert mild["event_resid_db"] == pytest.approx(-2.0, abs=0.1)
+
+
+def test_shares_measured_under_another_allowance_rule_are_refused():
+ """The set's provenance names the rule its shares were measured under; the
+ scorer reads only shares measured under its own (v2, the room-free voice
+ at the direct arrival), and the recorded rule is part of every label
+ digest."""
+ migrated = {
+ "id": "coroomATpause_000.wav",
+ "condition": "coroom@pause",
+ "provenance": {
+ "room_share_db": 1.2,
+ "room_share_rule": scoreevents.ROOM_SHARE_RULE,
+ },
+ }
+ unmigrated = dict(migrated, provenance={"room_share_db": 1.2})
+ v1 = dict(migrated,
+ provenance={
+ "room_share_db": 1.2,
+ "room_share_rule": "level-matched dry share on the "
+ "reference's loudest fifth of speech "
+ "frames, v1"
+ })
+
+ shares = scoreevents.room_shares([migrated])
+
+ assert shares == {"coroomATpause_000.wav": 1.2}
+ assert "direct arrival" in scoreevents.ROOM_SHARE_RULE
+ for stale in (unmigrated, v1):
+ with pytest.raises(SystemExit, match="measured under"):
+ scoreevents.room_shares([stale])
+ assert scoreevents.labels_digest(stale) != scoreevents.labels_digest(
+ migrated)
diff --git a/tests/bench/scripts/test_scorefiles.py b/tests/bench/scripts/test_scorefiles.py
new file mode 100644
index 0000000..5535505
--- /dev/null
+++ b/tests/bench/scripts/test_scorefiles.py
@@ -0,0 +1,430 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Loading score files.
+
+Sidecars are merged only when they belong to the base scores.
+"""
+
+# pylint: disable=protected-access
+
+import json
+import math
+
+import pytest
+import torch
+
+import anchors
+import common
+import ranking
+import scorefiles
+import tiny_board
+
+
+def test_level_calibration_is_subtracted_from_kept_energy(tmp_path):
+ m = tiny_board.metrics(10.0)
+ m["_level_cal_db"] = 6.0
+ tiny_board.write(tmp_path, "loud", m, deletion_pct=1.0)
+ scores = scorefiles.load(str(tmp_path))
+ assert scores["loud"]["babble@+4"]["kept_p10"] == pytest.approx(1.0 - 6.0)
+ # coherent keys too
+ assert scores["loud"]["babble@+4"]["kept_coh_p10"] == pytest.approx(1.0 -
+ 6.0)
+ assert scores["loud"]["babble@+4"]["kept_coh_nb_p10"] == pytest.approx(1.0 -
+ 6.0)
+ assert (scores["loud"]["babble@+4"]["babble_supp_db"] == -10.0
+ ) # suppression is not a gain-shift metric
+ assert scores["loud"]["_level_cal_applied_db"] == 6.0
+
+
+def test_load_merges_sidecars_applies_level_calibration_and_hf_error(tmp_path):
+ base = {
+ "_set_id": "abc",
+ "_level_cal_db": -2.0,
+ "babble@+4": {
+ "voice_kept_db": -5.0,
+ "kept_mean": -5.0,
+ "hf_err_db": 1.25,
+ "level_err_db": 0.5,
+ "n": 48,
+ },
+ }
+ (tmp_path / "x.metrics.json").write_text(json.dumps(base))
+ (tmp_path / "x.nisqa.json").write_text(
+ json.dumps({
+ "_set_id": "abc",
+ "babble@+4": {
+ "nisqa_mos": 4.0,
+ "n": 12
+ }
+ }))
+ (tmp_path / "x.realx.json").write_text(
+ json.dumps({
+ "_set_id": "abc",
+ "_level_cal_db": -2.0,
+ "_items_primary": {
+ "r1": [0, 3]
+ },
+ }))
+ d = scorefiles.load(str(tmp_path))["x"]
+ assert d["babble@+4"]["nisqa_mos"] == 4.0
+ assert (d["babble@+4"]["_hf_err"] == 1.25 and
+ d["babble@+4"]["_level_err"] == 0.5)
+ assert d["_level_cal_applied_db"] == -2.0
+ # raw minus the level offset
+ assert d["babble@+4"]["kept_mean"] == pytest.approx(-3.0)
+ assert d["_deletion"]["primary_anchored"] is True
+ assert d["_deletion"]["items"] == {"r1": [0, 3]}
+ # a sidecar read at another level calibration than the base scores is
+ # refused, not mixed in
+ (tmp_path / "x.realx.json").write_text(
+ json.dumps({
+ "_set_id": "abc",
+ "_level_cal_db": 0.0,
+ "_items_primary": {
+ "r1": [0, 3]
+ },
+ }))
+ with pytest.raises(ValueError, match="another level calibration"):
+ scorefiles.load(str(tmp_path))
+ # a millionth of a decibel is the same read (float32 medians jitter)
+ assert scorefiles.same_calibration(-0.4207916, -0.4207925)
+ assert not scorefiles.same_calibration(-0.42, -0.4205)
+ assert scorefiles.same_calibration(None, None)
+ assert not scorefiles.same_calibration(None, 0.0)
+
+
+def test_stale_sidecar_from_another_build_is_ignored(tmp_path):
+ (tmp_path / "x.metrics.json").write_text(
+ json.dumps({
+ "_set_id": "new",
+ "babble@+4": {
+ "n": 48,
+ "babble_supp_db": -12.0
+ }
+ }))
+ (tmp_path / "x.realx.json").write_text(
+ json.dumps({
+ "_set_id": "old",
+ "_items_primary": {
+ "r": [1, 1]
+ }
+ }))
+ (tmp_path / "x.nisqa.json").write_text(
+ json.dumps({
+ "_set_id": "new",
+ "babble@+4": {
+ "nisqa_mos": 4.0
+ }
+ }))
+ d = scorefiles.load(str(tmp_path))["x"]
+ assert ("babble_supp_db_nb" not in d["babble@+4"] and
+ d["_deletion"]["items"] == {})
+ assert (d["babble@+4"]["nisqa_mos"] == 4.0 and
+ d["babble@+4"]["babble_supp_db"] == -12.0)
+
+
+def test_a_sidecar_of_another_render_than_its_base_scores_is_ignored(
+ tmp_path, capsys):
+ (tmp_path / "x.metrics.json").write_text(
+ json.dumps({
+ "_set_id": "tiny",
+ "_outputs_sha256": "new",
+ "babble@+4": {
+ "n": 48,
+ "babble_supp_db": -12.0
+ }
+ }))
+ for ext, digest, mos in ((".nisqa.json", "old", 4.0),):
+ (tmp_path / f"x{ext}").write_text(
+ json.dumps({
+ "_set_id": "tiny",
+ "_outputs_sha256": digest,
+ "babble@+4": {
+ "nisqa_mos": mos
+ }
+ }))
+ d = scorefiles.load(str(tmp_path))["x"]
+ assert "nisqa_mos" not in d["babble@+4"]
+ assert "x.nisqa.json read another render" in capsys.readouterr().err
+
+
+def test_sidecar_from_another_subset_is_ignored_and_a_matching_one_merges(
+ tmp_path,):
+ (tmp_path / "x.metrics.json").write_text(
+ json.dumps({
+ "_set_id": "s",
+ "_subset": "core",
+ "babble@+4": {
+ "n": 40,
+ "nisqa_mos": 4.0,
+ "babble_supp_db": -12.0,
+ },
+ }))
+ # no stamp: legacy all-set data, never core coverage
+ (tmp_path / "x.nisqa.json").write_text(
+ json.dumps({
+ "_set_id": "s",
+ "babble@+4": {
+ "nisqa_mos": 1.0,
+ "n": 72
+ }
+ }))
+ (tmp_path / "x.realx.json").write_text(
+ json.dumps({
+ "_set_id": "s",
+ "_subset": "all",
+ "_items_primary": {
+ "r": [1, 1]
+ }
+ }))
+ d = scorefiles.load(str(tmp_path))["x"]
+ # the core value stands
+ assert d["babble@+4"]["nisqa_mos"] == 4.0 and d["babble@+4"]["n"] == 40
+ assert (d["_deletion"]["items"] == {} and
+ d["_deletion"]["primary_anchored"] is False)
+
+
+def test_sidecar_anchor_version_must_match_base_scores(tmp_path):
+ data = {
+ "_set_id": "tiny",
+ "_subset": "all",
+ **anchors.stamp(),
+ "clean": {
+ "n": 20
+ },
+ }
+ (tmp_path / "model.metrics.json").write_text(json.dumps(data))
+ side = dict(data, _anchors_version="different")
+ (tmp_path / "model.nisqa.json").write_text(json.dumps(side))
+ with pytest.raises(ValueError, match="anchor version"):
+ scorefiles.load(tmp_path)
+
+
+def test_level_error_is_the_scorers_mean_absolute_level_change(tmp_path):
+ quiet, loud = tiny_board.metrics(10.0), tiny_board.metrics(10.0)
+ quiet["clean"]["level_err_db"], loud["clean"]["level_err_db"] = 2.5, 1.5
+ del loud["music@-6"]["level_err_db"]
+ tiny_board.write(tmp_path, "quiet", quiet, deletion_pct=1.0)
+ tiny_board.write(tmp_path, "loud", loud, deletion_pct=1.0)
+ scores = scorefiles.load(str(tmp_path))
+ assert (scores["quiet"]["clean"]["_level_err"] == 2.5 and
+ scores["loud"]["clean"]["_level_err"] == 1.5)
+ # nothing measured, nothing derived
+ assert "_level_err" not in scores["loud"]["music@-6"]
+ assert ["clean", "_level_err",
+ -1] in [list(r) for r in ranking.AXES_FULL["fidelity"]]
+ assert not any(
+ row[1].startswith("si_sdr") for row in ranking.AXES_FULL["fidelity"])
+
+
+def test_load_merges_the_kept_sidecar_with_its_own_item_counts(tmp_path):
+ (tmp_path / "x.metrics.json").write_text(
+ json.dumps({
+ "_set_id": "abc",
+ "_level_cal_db": 0.0,
+ "clean": {
+ "n": 72,
+ "si_sdr": 30.0
+ },
+ }))
+ (tmp_path / "x.kept.json").write_text(
+ json.dumps({
+ "_set_id": "abc",
+ "_level_cal_db": 0.0,
+ "clean": {
+ "n": 72,
+ "n_missing": 0,
+ "mag_snr": 27.5,
+ "mag_snr_nb": 28.0,
+ },
+ "nonverbal@+0": {
+ "n": 48,
+ "n_missing": 0,
+ "nv_lost_pct": 12.5,
+ "nv_events_lost_pct": 10.0,
+ "nv_blocks": 108,
+ "nv_events": 50,
+ "nv_items": 30,
+ },
+ }))
+ d = scorefiles.load(str(tmp_path))["x"]
+ assert d["clean"]["mag_snr"] == 27.5 and d["clean"]["si_sdr"] == 30.0
+ assert (d["nonverbal@+0"]["nv_lost_pct"] == 12.5 and
+ d["nonverbal@+0"]["nv_blocks"] == 108)
+ # only the sidecar's own measurements are merged
+ assert "n_missing" not in d["nonverbal@+0"]
+ # the items it was scored on
+ assert d["nonverbal@+0"]["metric_counts"]["nv_lost_pct"] == 48
+ scores = {"x": d}
+ assert ranking._covered(scores, "x", "nonverbal@+0", "nv_lost_pct")
+ d["nonverbal@+0"]["metric_counts"]["nv_lost_pct"] = 12
+ assert not ranking._covered(scores, "x", "nonverbal@+0", "nv_lost_pct")
+
+
+def test_sidecar_coverage_reads_the_items_that_observe_and_refuses_missing_ones(
+ tmp_path,):
+ (tmp_path / "x.metrics.json").write_text(
+ json.dumps({
+ "_set_id": "abc",
+ "_level_cal_db": 0.0,
+ "nonverbal@+0": {
+ "n": 48,
+ "n_missing": 0
+ },
+ }))
+ cell = {
+ "n": 48,
+ "n_missing": 0,
+ "nv_lost_pct": 12.5,
+ "nv_events_lost_pct": 10.0,
+ "nv_items": 22,
+ "metric_counts": {
+ "nv_lost_pct": 22,
+ "nv_events_lost_pct": 22
+ },
+ }
+ (tmp_path / "x.kept.json").write_text(
+ json.dumps({
+ "_set_id": "abc",
+ "_level_cal_db": 0.0,
+ "nonverbal@+0": cell
+ }))
+ scores = scorefiles.load(str(tmp_path))
+ # observing, not scored
+ assert scores["x"]["nonverbal@+0"]["metric_counts"]["nv_lost_pct"] == 22
+ assert ranking._covered(scores, "x", "nonverbal@+0", "nv_lost_pct")
+ # a panel where fewer than MIN_ITEMS recordings carry a laugh cannot feed
+ # the axis
+ cell["metric_counts"] = {"nv_lost_pct": 12, "nv_events_lost_pct": 12}
+ (tmp_path / "x.kept.json").write_text(
+ json.dumps({
+ "_set_id": "abc",
+ "_level_cal_db": 0.0,
+ "nonverbal@+0": cell
+ }))
+ assert not ranking._covered(scorefiles.load(str(tmp_path)), "x",
+ "nonverbal@+0", "nv_lost_pct")
+ # an item the sidecar did not get back makes the row incomplete, never a
+ # smaller mean
+ cell["metric_counts"] = {"nv_lost_pct": 22, "nv_events_lost_pct": 22}
+ cell.update(n=47, n_missing=1)
+ (tmp_path / "x.kept.json").write_text(
+ json.dumps({
+ "_set_id": "abc",
+ "_level_cal_db": 0.0,
+ "nonverbal@+0": cell
+ }))
+ scores = scorefiles.load(str(tmp_path))
+ assert scores["x"]["nonverbal@+0"]["metric_missing"]["nv_lost_pct"] == 1
+ assert not ranking._covered(scores, "x", "nonverbal@+0", "nv_lost_pct")
+
+
+def test_a_sidecar_measured_on_other_outputs_than_the_base_scores_is_ignored(
+ tmp_path,):
+ (tmp_path / "x.metrics.json").write_text(
+ json.dumps({
+ "_set_id": "abc",
+ "_level_cal_db": 0.0,
+ "clean": {
+ "n": 48
+ }
+ }))
+ (tmp_path / "x.kept.json").write_text(
+ json.dumps({
+ "_set_id": "abc",
+ "_level_cal_db": 0.0,
+ "clean": {
+ "n": 48,
+ "mag_snr": 40.0
+ },
+ }))
+
+ def records(path, outputs):
+ lines = [json.dumps({"type": "records", "system": "x"})]
+ lines += [
+ json.dumps({
+ "id": uid,
+ "identity": {
+ "output": h
+ }
+ }) for uid, h in outputs.items()
+ ]
+ (tmp_path / path).write_text("\n".join(lines) + "\n")
+
+ records("x.items.jsonl", {"a.wav": "h1", "b.wav": "h2"})
+ records("x.kept.items.jsonl", {"a.wav": "h1"})
+ # the same outputs: merged
+ assert scorefiles.load(str(tmp_path))["x"]["clean"]["mag_snr"] == 40.0
+ # a re-render since: stale
+ records("x.kept.items.jsonl", {"a.wav": "h1", "b.wav": "old"})
+ assert "mag_snr" not in scorefiles.load(str(tmp_path))["x"]["clean"]
+ # no records to check against: accepted as before
+ (tmp_path / "x.items.jsonl").unlink()
+ assert scorefiles.load(str(tmp_path))["x"]["clean"]["mag_snr"] == 40.0
+
+
+def test_energy_above_a_band_limited_input_marks_the_system_as_restoring():
+ keeps = {
+ "srsweep_8k": {
+ "band_kept_db": [0, 0, 0, -24.0, -47.0, -47.0, -47.0]
+ },
+ "srsweep_16k": {
+ "band_kept_db": [0, 0, 0, 0, -40.0, -47.0, -47.0]
+ }
+ }
+ restores = {
+ "srsweep_8k": {
+ "band_kept_db": [0.6, 0.4, 0.1, 55.6, 48.3, 41.4, 31.2]
+ },
+ "srsweep_16k": {
+ "band_kept_db": [0, 0, 0, 0, 54.5, 45.5, 33.7]
+ }
+ }
+ leaks = {"srsweep_8k": {"band_kept_db": [0, 0, 0, 3.9, 0.4, -1.0, -1.9]}}
+ above = ranking.ASSIGN["above_db"]
+ assert scorefiles.band_above_input_db(keeps) <= above
+ assert scorefiles.band_above_input_db(restores) > above
+ # the bands inside the input's band are subtracted: a gain cancels
+ assert scorefiles.band_above_input_db(restores) == pytest.approx(55.6 -
+ 1.1 / 3)
+ # a few decibels of resampler leakage are not restoration
+ assert scorefiles.band_above_input_db(leaks) <= above
+ # a system without a band-limited row is unknown, not a keeper
+ assert math.isnan(
+ scorefiles.band_above_input_db({"clean": {
+ "si_sdr": 50.0
+ }}))
+ assert scorefiles.band_above_input_db({}) != scorefiles.band_above_input_db(
+ {})
+
+
+def test_the_band_test_ignores_a_gain_and_reads_every_band_above_the_input():
+ sr = common.SR
+ time = torch.arange(sr, dtype=torch.float64) / sr
+ window = 0.5 - 0.5 * torch.cos(2 * math.pi * time)
+ # a gain everywhere, no new frequency: not restoration
+ ref = (0.1 * window * torch.sin(2 * math.pi * 3800 * time)).float()
+ bands = common.band_kept_db(ref * 10**(11 / 20), ref)
+ assert scorefiles.band_above_input_db(
+ {"srsweep_8k": {
+ "band_kept_db": bands
+ }}) <= ranking.ASSIGN["above_db"]
+ # a tone far above the input's band, beyond the first band above it
+ ref = (0.1 * window * torch.sin(2 * math.pi * 1000 * time)).float()
+ out = ref + (0.02 * window * torch.sin(2 * math.pi * 15000 * time)).float()
+ bands = common.band_kept_db(out, ref)
+ assert scorefiles.band_above_input_db(
+ {"srsweep_8k": {
+ "band_kept_db": bands
+ }}) > ranking.ASSIGN["above_db"]
diff --git a/tests/bench/scripts/test_scorekept.py b/tests/bench/scripts/test_scorekept.py
new file mode 100644
index 0000000..303bc90
--- /dev/null
+++ b/tests/bench/scripts/test_scorekept.py
@@ -0,0 +1,285 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The kept sidecar reads the voice outside speech.
+
+It also reads the spectrum of clean speech.
+"""
+
+# pylint: disable=redefined-outer-name
+
+import json
+import os
+import pathlib
+
+import numpy as np
+import pytest
+import soundfile as sf
+import torch
+
+import common
+import scorebench
+import scorekept
+
+SR = common.SR
+# one second of speech, a 400 ms laugh
+SPEECH, LAUGH = (0, SR), (int(1.3 * SR), int(1.7 * SR))
+
+
+class _Vad:
+ """Calls the first second speech, whatever it is handed."""
+
+ def segments(self, x):
+ # pylint: disable-next=import-outside-toplevel
+ import torchaudio
+
+ return torchaudio.functional.resample(x, SR, 16000), [{
+ "start": 0,
+ "end": 16000
+ }]
+
+
+def _voice(seed):
+ ref = torch.zeros(2 * SR)
+ g = torch.Generator().manual_seed(seed)
+ ref[SPEECH[0]:SPEECH[1]] = 0.1 * torch.randn(SR, generator=g)
+ ref[LAUGH[0]:LAUGH[1]] = 0.05 * torch.randn(LAUGH[1] - LAUGH[0],
+ generator=g)
+ return ref
+
+
+def _write(path, x):
+ sf.write(str(path), x.numpy(), SR, subtype="FLOAT")
+
+
+def vocal_set(tmp_path, monkeypatch):
+ """Returns recordings of laughs, under a bed and clean, and clean speech.
+
+ Laughs under a quiet bed (one of them buried under a loud one), laughs on
+ clean recordings and clean speech; a system that keeps everything and one
+ that gates the laugh.
+ """
+ root, out_root = tmp_path / "set", tmp_path / "out"
+ for d in (
+ root / "mix",
+ root / "ref",
+ out_root / "keeps",
+ out_root / "gates",
+ ):
+ d.mkdir(parents=True)
+ rows = []
+ for i, (cond, bed) in enumerate((
+ ("nonverbal@+0", 0.02),
+ ("nonverbal@+0", 0.02),
+ ("nonverbal@+0", 0.5),
+ ("nonverbal_clean", 0.0),
+ ("nonverbal_clean", 0.0),
+ ("clean", 0.0),
+ ("clean", 0.0),
+ )):
+ rid = f"{cond.replace('@+', 'ATp')}_{i:03d}.wav"
+ ref = _voice(i)
+ mix = ref + bed * torch.randn(
+ len(ref), generator=torch.Generator().manual_seed(50 + i))
+ gated = mix.clone()
+ gated[LAUGH[0]:LAUGH[1]] = 0.0
+ _write(root / "ref" / rid, ref)
+ _write(root / "mix" / rid, mix)
+ _write(out_root / "keeps" / rid, mix)
+ _write(out_root / "gates" / rid, gated)
+ rows.append({
+ "id": rid,
+ "condition": cond,
+ "mix_path": f"mix/{rid}",
+ "clean_path": f"ref/{rid}",
+ })
+ with open(root / "manifest.jsonl", "w", encoding="utf-8") as fh:
+ fh.write("".join(json.dumps(r) + "\n" for r in rows))
+ json.dump(
+ {
+ "set_id": "tiny",
+ "n_items": len(rows)
+ },
+ open(root / "checksums.json", "w", encoding="utf-8"),
+ )
+ monkeypatch.setattr(common, "EVAL", str(root))
+ monkeypatch.setattr(common, "OUT_ROOT", str(out_root))
+ monkeypatch.setattr(common, "RESULTS", str(tmp_path / "results"))
+ return common.manifest(str(root))
+
+
+def test_module_applies_the_identity_rule_of_scorebench():
+ # one rule decides which renders a sidecar may read: scorebench's
+ assert not hasattr(scorekept, "render_problem")
+ assert "render_problem" in scorekept.main.__code__.co_names
+
+
+def test_events_are_runs_of_consecutive_blocks():
+ mask = torch.tensor([0, 1, 1, 0, 1, 0, 0, 1], dtype=torch.bool)
+ assert scorekept.events(mask) == [(1, 3), (4, 5), (7, 8)]
+ assert not scorekept.events(torch.zeros(4, dtype=torch.bool))
+
+
+def test_vocal_blocks_are_loud_outside_speech_and_not_buried():
+ ref = _voice(0)
+ speech = torch.zeros(20, dtype=torch.bool)
+ speech[:10] = True
+ alone = scorekept.vocal_blocks(ref, speech, ref)
+ # the laugh, not the speech
+ assert torch.nonzero(alone).flatten().tolist() == [13, 14, 15, 16]
+ quiet_bed = ref + 0.02 * torch.randn(
+ len(ref), generator=torch.Generator().manual_seed(1))
+ with_bed = scorekept.vocal_blocks(ref, speech, quiet_bed)
+ assert with_bed.tolist() == alone.tolist()
+ loud_bed = ref + 0.5 * torch.randn(
+ len(ref), generator=torch.Generator().manual_seed(2))
+ # 20 dB under the bed: nothing to keep
+ assert not scorekept.vocal_blocks(ref, speech, loud_bed).any()
+ whisper = ref.clone()
+ # 46 dB under the loudest block: not a vocal sound
+ whisper[scorekept.FRAME * 13:] *= 0.01
+ assert not scorekept.vocal_blocks(whisper, speech, whisper).any()
+
+
+def test_magnitude_ratio_ignores_gain_and_phase_and_reads_a_changed_spectrum():
+ ref = _voice(3)
+ assert scorekept.mag_snr(ref, ref) == 120.0
+ assert scorekept.mag_snr(0.5 * ref, ref) > 100.0
+ assert scorekept.mag_snr(-ref, ref) > 100.0
+ g = torch.Generator().manual_seed(4)
+ slight = ref + 0.001 * torch.randn(len(ref), generator=g)
+ heavy = ref + 0.02 * torch.randn(len(ref), generator=g)
+ heavy_snr = scorekept.mag_snr(heavy, ref)
+ slight_snr = scorekept.mag_snr(slight, ref)
+ assert 5.0 < heavy_snr < slight_snr < 120.0
+ assert np.isnan(scorekept.mag_snr(ref[:100], ref[:100]))
+
+
+def test_a_gated_laugh_is_lost_and_a_kept_one_is_not(vocal_set):
+ rows = [r for r in vocal_set if scorekept.wanted(r)]
+ assert len(rows) == 7
+ kept_records = scorekept.assemble("keeps", rows, vad=_Vad())
+ kept = scorekept.aggregate(kept_records, rows, 0.0)
+ gated_records = scorekept.assemble("gates", rows, vad=_Vad())
+ gated = scorekept.aggregate(gated_records, rows, 0.0)
+ noisy, clean = kept["nonverbal@+0"], kept["nonverbal_clean"]
+ # the buried laugh is nobody's to keep
+ assert noisy["n"] == 3 and noisy["nv_items"] == 2
+ assert noisy["nv_blocks"] == 8 and noisy["nv_events"] == 2
+ assert noisy["nv_lost_pct"] == 0.0 and clean["nv_lost_pct"] == 0.0
+ assert gated["nonverbal@+0"]["nv_lost_pct"] == 100.0
+ assert gated["nonverbal@+0"]["nv_events_lost_pct"] == 100.0
+ assert gated["nonverbal_clean"]["nv_lost_pct"] == 100.0
+ by_id = {r["id"]: r for r in gated_records}
+ assert by_id[rows[0]["id"]]["metrics"]["nv_lost"] == 4
+ assert by_id[rows[0]["id"]]["metrics"]["nv_lost_pct"] == 100.0
+ assert by_id[rows[2]["id"]]["metrics"]["nv_blocks"] == 0
+ assert "nv_lost_pct" not in by_id[rows[2]["id"]]["metrics"]
+ # gating a laugh changes the spectrum of nothing in the clean condition's
+ # speech
+ assert (kept["clean"]["mag_snr"] == 120.0 and
+ "nv_lost_pct" not in kept["clean"])
+ # the clean items hold the same laugh, now gone
+ assert gated["clean"]["mag_snr"] < 30.0
+
+
+def test_level_calibration_is_removed_before_a_block_is_called_lost(vocal_set):
+ rows = [r for r in vocal_set if r["condition"] == "nonverbal_clean"]
+ quiet = os.path.join(common.OUT_ROOT, "quiet")
+ os.makedirs(quiet)
+ for r in rows:
+ _write(
+ pathlib.Path(quiet) / r["id"], 0.25 * common.load48(r["mix_path"]))
+ records = scorekept.assemble("quiet", rows, vad=_Vad())
+ uncalibrated = scorekept.aggregate(records, rows, 0.0)["nonverbal_clean"]
+ assert uncalibrated["nv_lost_pct"] == 100.0
+ calibrated = scorekept.aggregate(records, rows, -12.0)["nonverbal_clean"]
+ assert calibrated["nv_lost_pct"] == 0.0
+
+
+def test_records_reuse_and_views_derive(vocal_set):
+ rows = [r for r in vocal_set if scorekept.wanted(r)]
+ first = scorekept.assemble("gates", rows, vad=_Vad())
+ whole = scorekept.aggregate(first, rows, 0.0)
+ index = {scorebench.reuse_key(r["identity"]): r for r in first}
+ # no detector needed: nothing is scored
+ again = scorekept.assemble("gates", rows, reuse=index)
+ assert scorekept.aggregate(again, rows, 0.0) == whole
+ reused = [r["measurements"] for r in again]
+ assert reused == [r["measurements"] for r in first]
+ view = rows[:2] + rows[5:6]
+ derived = scorekept.aggregate(
+ [r for r in first if r["id"] in {v["id"] for v in view}], view, 0.0)
+ direct_records = scorekept.assemble("gates", view, vad=_Vad())
+ direct = scorekept.aggregate(direct_records, view, 0.0)
+ assert derived == direct and derived["nonverbal@+0"]["n"] == 2
+ assert "nonverbal_clean" not in derived
+
+
+def test_the_files_name_the_render_they_read_and_a_view_keeps_it(
+ vocal_set, tmp_path, monkeypatch):
+ # pylint: disable-next=import-outside-toplevel
+ import sys
+
+ results, view = pathlib.Path(common.RESULTS), tmp_path / "view"
+ results.mkdir()
+ view.mkdir()
+ rendered = "e" * 64
+ (results / "gates.meta.json").write_text(
+ json.dumps({
+ "set_id": "tiny",
+ "name": "gates",
+ "outputs_sha256": rendered
+ }))
+ for where, subset in ((results, "all"), (view, "gate")):
+ (where / "gates.metrics.json").write_text(
+ json.dumps({
+ "_set_id": "tiny",
+ "_subset": subset,
+ "_level_cal_db": 0.0
+ }))
+ monkeypatch.setattr(common, "Vad", _Vad)
+ monkeypatch.setattr(sys, "argv", ["scorekept.py", "--systems", "gates"])
+ scorekept.main()
+ whole = json.loads((results / "gates.kept.json").read_text())
+ with open(results / "gates.kept.items.jsonl", encoding="utf-8") as fh:
+ header = json.loads(fh.readline())
+ assert whole["_outputs_sha256"] == rendered == header["outputs_sha256"]
+ members = {r["id"] for r in vocal_set[:2]}
+ monkeypatch.setattr(common, "SUBSET", "gate")
+ monkeypatch.setattr(common,
+ "panel_members",
+ lambda name, root=None: members)
+ monkeypatch.setattr(common, "RESULTS", str(view))
+ monkeypatch.setattr(
+ sys,
+ "argv",
+ [
+ "scorekept.py", "--systems", "gates", "--aggregate-only",
+ str(results)
+ ],
+ )
+ scorekept.main()
+ derived = json.loads((view / "gates.kept.json").read_text())
+ assert derived["_outputs_sha256"] == rendered
+
+
+def test_missing_outputs_are_counted_not_averaged_away(vocal_set):
+ rows = [r for r in vocal_set if scorekept.wanted(r)]
+ os.remove(os.path.join(common.OUT_ROOT, "keeps", rows[0]["id"]))
+ records = scorekept.assemble("keeps", rows, vad=_Vad())
+ out = scorekept.aggregate(records, rows, 0.0)
+ assert records[0]["output_status"] == "missing"
+ assert (out["nonverbal@+0"]["n"] == 2 and
+ out["nonverbal@+0"]["n_missing"] == 1)
diff --git a/tests/bench/scripts/test_scorenisqa.py b/tests/bench/scripts/test_scorenisqa.py
new file mode 100644
index 0000000..b81d8b7
--- /dev/null
+++ b/tests/bench/scripts/test_scorenisqa.py
@@ -0,0 +1,60 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The scorenisqa sidecar imports cleanly.
+
+It applies the render-identity rule.
+"""
+
+import pytest
+
+import scorenisqa
+
+
+def test_module_applies_the_identity_rule_of_scorebench():
+ # one rule decides which renders a sidecar may read: scorebench's
+ assert not hasattr(scorenisqa, "render_problem")
+ assert "render_problem" in scorenisqa.main.__code__.co_names
+
+
+def test_a_familys_eligible_seconds_sum_the_items_that_carry_them():
+ """An item without primary segments revives to NaN; the family's eligible
+ duration is the sum over the others."""
+ rows = [{"id": str(i), "condition": "real_x"} for i in range(3)]
+ records = [{
+ "id": "0",
+ "metrics": {
+ "nisqa_mos": 3.0,
+ "nisqa_mos_primary": 3.1,
+ "nisqa_primary_eligible_s": 4.0,
+ "nisqa_primary_coverage": 0.9
+ }
+ }, {
+ "id": "1",
+ "metrics": {
+ "nisqa_mos": 3.5,
+ "nisqa_mos_primary": 3.6,
+ "nisqa_primary_eligible_s": 6.0,
+ "nisqa_primary_coverage": 0.8
+ }
+ }, {
+ "id": "2",
+ "metrics": {
+ "nisqa_mos": 2.5
+ }
+ }]
+
+ cell = scorenisqa.aggregate(records, rows, ["real_x"], 0)["real_x"]
+
+ assert cell["nisqa_primary_items"] == 2
+ assert cell["nisqa_primary_eligible_s"] == pytest.approx(10.0)
diff --git a/tests/bench/scripts/test_scorerealx.py b/tests/bench/scripts/test_scorerealx.py
new file mode 100644
index 0000000..116eb81
--- /dev/null
+++ b/tests/bench/scripts/test_scorerealx.py
@@ -0,0 +1,305 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Real-recording deletion sidecar: item selection and interval arithmetic."""
+
+import pytest
+import torch
+import torchaudio
+
+pytest.importorskip("scipy")
+# pylint: disable=wrong-import-position
+import common
+import levels
+import observations
+import scorebench
+import scorerealx
+
+# pylint: enable=wrong-import-position
+
+ROWS = [{
+ "condition": c
+} for c in ("real_noisy", "real_calls", "real_zh", "babble@+4", "clean")]
+
+
+def _conds(rows):
+ return [r["condition"] for r in rows]
+
+
+def test_select_items_default_prefix_pools_every_real_condition():
+ assert _conds(scorerealx.select_items(ROWS, "real")) == [
+ "real_noisy",
+ "real_calls",
+ "real_zh",
+ ]
+
+
+def test_select_items_explicit_names_are_exact_matches():
+ assert _conds(scorerealx.select_items(ROWS, "real_noisy,babble@+4")) == [
+ "real_noisy",
+ "babble@+4",
+ ]
+ # a name, not a prefix
+ assert _conds(scorerealx.select_items(ROWS, "real_noisy")) == ["real_noisy"]
+ # trailing comma
+ trailing = scorerealx.select_items(ROWS, "real_noisy,")
+ assert _conds(trailing) == ["real_noisy"]
+ assert scorerealx.select_items(ROWS, "nothing") == []
+
+
+def test_ci95_is_clopper_pearson_in_percent():
+ lo, hi = scorerealx.ci95(0, 100)
+ assert lo == 0.0 and hi == pytest.approx(100 * (1 - 0.025**(1 / 100)),
+ abs=1e-6)
+ lo, hi = scorerealx.ci95(100, 100)
+ assert hi == 100.0 and lo == pytest.approx(100 * 0.025**(1 / 100), abs=1e-6)
+ lo, hi = scorerealx.ci95(5, 100)
+ assert lo == pytest.approx(1.643, abs=0.01) and hi == pytest.approx(
+ 11.283, abs=0.01)
+ # every segment the detector reports counts; Silero reports none shorter
+ assert scorerealx.MIN_SEG == 4000 and levels.DEL_DB == -10.0
+ assert scorerealx.EDGE == 800
+
+
+def _record(uid, cond, drops, prim, edge):
+ return {
+ "id": uid,
+ "condition": cond,
+ "output_status": "ok",
+ "measurements": {
+ "seg_drop": drops,
+ "seg_primary": prim,
+ "seg_edge": edge,
+ "seg_start": [16000 * i for i in range(len(drops))],
+ "seg_end": [16000 * i + 8000 for i in range(len(drops))],
+ "anchor_sims": [[1.0] * len(drops)] if drops else [],
+ },
+ }
+
+
+def test_aggregate_leaves_edge_fragments_out_of_every_pool():
+ items = [{
+ "id": "a",
+ "condition": "real_x"
+ }, {
+ "id": "b",
+ "condition": "real_x"
+ }]
+ records = [
+ # the first segment is a word the recording cut off, and it is gone
+ _record("a", "real_x", [-30.0, -1.0, -2.0], [1.0, 1.0, 1.0],
+ [1.0, 0.0, 0.0]),
+ # one inner deletion, one fragment kept
+ _record("b", "real_x", [-1.0, -15.0, -1.0], [1.0, 1.0, 0.0],
+ [0.0, 0.0, 1.0]),
+ ]
+ out = scorerealx.aggregate(records, items, 0.85, 0.0)
+ assert out["real_x"]["n_segments"] == 4 and out["real_x"]["n_deleted"] == 1
+ assert out["_items_real"] == {"a": [0, 2], "b": [1, 2]}
+ assert out["_items_primary"] == {"a": [0, 2], "b": [1, 2]}
+ assert out["_pooled_primary"]["n_segments"] == 4
+ assert out["_edge_segments"] == {
+ "real_x": {
+ "n_segments": 2,
+ "n_deleted": 1
+ }
+ }
+ assert out["_trimmed_segments"] == 0 and out["_widened_segments"] == 0
+ # records of an older scorer carry no edge flags: every segment is inner
+ legacy = _record("a", "real_x", [-30.0, -1.0], [1.0, 1.0], [])
+ legacy["measurements"].pop("seg_edge")
+ out = scorerealx.aggregate([legacy], items[:1], 0.85, 0.0)
+ assert out["_items_real"] == {"a": [1, 2]} and out["_edge_segments"] == {}
+ # the diagnostics count what the records say
+ counted = _record("a", "real_x", [-1.0, -2.0], [1.0, 1.0], [0.0, 0.0])
+ counted["measurements"].update(seg_trimmed=[1.0, 0.0],
+ seg_widened=[0.0, 1.0])
+ out = scorerealx.aggregate([counted], items[:1], 0.85, 0.0)
+ assert out["_trimmed_segments"] == 1 and out["_widened_segments"] == 1
+
+
+def test_item_metrics_keep_primary_drops_of_inner_segments_only():
+ metrics = scorerealx.item_metrics({
+ "seg_drop": [-30.0, -1.0, -20.0],
+ "seg_primary": [1.0, 1.0, 1.0],
+ "seg_edge": [1.0, 0.0, 0.0],
+ "seg_trimmed": [0.0, 1.0, 0.0],
+ "seg_widened": [1.0, 0.0, 0.0],
+ })
+ assert metrics == {
+ "n_segments": 3,
+ "n_edge_segments": 1,
+ "n_trimmed_segments": 1,
+ "n_widened_segments": 1,
+ "primary_segments": 2,
+ "primary_drops": [-1.0, -20.0],
+ }
+
+
+class _EdgeVad:
+ """A 14 s item: speech from its start to 12.5 s, and its last 0.4 s."""
+
+ def segments(self, x):
+ x16 = torchaudio.functional.resample(x, 48000, 16000)
+ return x16, [{
+ "start": 0,
+ "end": 200000
+ }, {
+ "start": len(x16) - 6400,
+ "end": len(x16)
+ }]
+
+
+def test_a_segment_touching_an_edge_loses_the_edge_and_keeps_its_interior(
+ tmp_path, monkeypatch):
+ monkeypatch.setattr(common, "EVAL", str(tmp_path))
+ g = torch.Generator().manual_seed(3)
+ mix = torch.randn(14 * 48000, generator=g) * 0.1
+ it = {"id": "a.wav", "condition": "real_x", "mix_path": "a.wav"}
+ same = scorerealx.score_item(it, mix, mix, _EdgeVad(), [1.0, 1.0], 0.85)
+ # the long utterance keeps its interior, read from 300 ms in; the 0.4 s
+ # fragment at the end is reported, not read
+ assert same["seg_start"] == [scorerealx.TRIM, 224000 - 6400]
+ assert same["seg_end"] == [200000, 224000]
+ assert same["seg_edge"] == [0.0, 1.0]
+ assert same["seg_trimmed"] == [1.0, 0.0]
+ assert same["seg_widened"] == [0.0, 1.0]
+ assert same["seg_drop"] == pytest.approx([0.0, 0.0], abs=1e-6)
+ # the review's case: the whole utterance deleted used to go uncharged
+ out = mix.clone()
+ out[:int(12.5 * 48000)] = 0.0
+ out[-int(0.5 * 48000):] = 0.0
+ gone = scorerealx.score_item(it, out, mix, _EdgeVad(), [1.0, 1.0], 0.85)
+ assert gone["seg_drop"][0] < -60 and gone["seg_drop"][1] < levels.DEL_DB
+ metrics = scorerealx.item_metrics(gone)
+ assert metrics["primary_segments"] == 1 and metrics["n_edge_segments"] == 1
+ assert levels.deleted(metrics["primary_drops"], 0.0) == [1.0]
+ # the first 300 ms alone silenced is the cut-off word, nobody's
+ head = mix.clone()
+ head[:int(0.3 * 48000)] = 0.0
+ assert scorerealx.score_item(it, head, mix, _EdgeVad(), [1.0, 1.0],
+ 0.85)["seg_drop"][0] == pytest.approx(0.0,
+ abs=0.05)
+
+
+def test_frozen_decisions_bind_reuse_and_require_inputs_boundaries(
+ tmp_path, monkeypatch):
+ out_root = tmp_path / "out"
+ (out_root / "half").mkdir(parents=True)
+ (out_root / "half" / "a.wav").write_bytes(b"")
+ mix = tmp_path / "a.wav"
+ mix.write_bytes(b"")
+ items = [{"id": "a.wav", "condition": "real_x", "mix_path": str(mix)}]
+ monkeypatch.setattr(common, "OUT_ROOT", str(out_root))
+ monkeypatch.setattr(common, "load48", lambda path: torch.ones(48000))
+ monkeypatch.setattr(common, "file_hashes", lambda: (lambda path: "h"))
+ calls = []
+
+ def fake_score_item(it, out, mix, vad, sims, threshold):
+ del it, out, mix, vad
+ calls.append(sims)
+ flags = [1.0 if s >= threshold else 0.0 for s in (sims or [0.0, 0.0])]
+ return {
+ "seg_drop": [-1.0, -2.0],
+ "seg_primary": flags,
+ "seg_edge": [0.0, 0.0],
+ "seg_trimmed": [0.0, 0.0],
+ "seg_widened": [0.0, 0.0],
+ "seg_start": [1000, 9000],
+ "seg_end": [5000, 13000],
+ "anchor_sims": [list(sims)] if sims else [],
+ }
+
+ monkeypatch.setattr(scorerealx, "score_item", fake_score_item)
+ decision = {
+ "a.wav": {
+ "sims": [0.1, 0.99],
+ "start": [1000, 9000],
+ "end": [5000, 13000]
+ }
+ }
+ spk = object() # anchoring on, the embedder never called
+ first = scorerealx.assemble("half", items, None, spk, 0.85, frozen=decision)
+ key = scorerealx.frozen_key(decision["a.wav"])
+ assert first[0]["identity"]["semantics"]["frozen"] == key
+ assert first[0]["measurements"]["seg_primary"] == [0.0, 1.0]
+ # the same decision of INPUT: the record is reused
+ index = {scorebench.reuse_key(r["identity"]): r for r in first}
+ again = scorerealx.assemble("half",
+ items,
+ None,
+ spk,
+ 0.85,
+ reuse=index,
+ frozen=decision)
+ assert len(calls) == 1
+ assert again[0]["measurements"] == first[0]["measurements"]
+ # INPUT decided again and the flags swapped: the cached record is of
+ # another decision and is not reused (the review's cache test)
+ swapped = {"a.wav": dict(decision["a.wav"], sims=[0.99, 0.1])}
+ fresh = scorerealx.assemble("half",
+ items,
+ None,
+ spk,
+ 0.85,
+ reuse=index,
+ frozen=swapped)
+ assert len(calls) == 2
+ assert fresh[0]["measurements"]["seg_primary"] == [1.0, 0.0]
+ assert fresh[0]["identity"]["semantics"]["frozen"] != key
+ # the boundaries must be INPUT's to the sample, not merely as many
+ moved = {"a.wav": dict(decision["a.wav"], start=[1000, 9100])}
+ with pytest.raises(SystemExit, match="differ from INPUT's"):
+ scorerealx.assemble("half", items, None, spk, 0.85, frozen=moved)
+ # a pass without anchoring carries no decision
+ own = scorerealx.assemble("half", items, None, None, 0.85)
+ assert own[0]["identity"]["semantics"]["frozen"] is None
+
+
+def test_frozen_sims_reads_inputs_flags_and_refuses_other_records(
+ tmp_path, monkeypatch):
+ monkeypatch.setattr(common, "set_id", lambda root=None: "tiny")
+ items = [{"id": "a"}, {"id": "b"}]
+ records = [
+ _record("a", "real_x", [-1.0, -2.0], [1.0, 0.0], [0.0, 0.0]),
+ _record("b", "real_x", [], [], []),
+ ]
+ records[0]["measurements"]["anchor_sims"] = [[0.9, 0.2]]
+ path = tmp_path / "INPUT.realx.items.jsonl"
+ observations.sidecar(path, records, "INPUT", "tiny", "all", False,
+ scorerealx.SCORER_SHA256)
+ assert scorerealx.frozen_sims(path, items) == {
+ "a": {
+ "sims": [0.9, 0.2],
+ "start": [0, 16000],
+ "end": [8000, 24000]
+ },
+ "b": {
+ "sims": None,
+ "start": [],
+ "end": []
+ },
+ }
+ assert scorerealx.frozen_key({"sims": [0.9, 0.2]}) != scorerealx.frozen_key(
+ {"sims": [0.2, 0.9]})
+ with pytest.raises(SystemExit, match="lacks 1 items"):
+ scorerealx.frozen_sims(path, items + [{"id": "c"}])
+ observations.sidecar(path, records, "half", "tiny", "all", False,
+ scorerealx.SCORER_SHA256)
+ with pytest.raises(SystemExit, match="not INPUT"):
+ scorerealx.frozen_sims(path, items)
+ observations.sidecar(path, records, "INPUT", "tiny", "all", False, "other")
+ with pytest.raises(SystemExit, match="another deletion scorer"):
+ scorerealx.frozen_sims(path, items)
+ with pytest.raises(SystemExit, match="missing"):
+ scorerealx.frozen_sims(tmp_path / "none.jsonl", items)
diff --git a/tests/bench/scripts/test_scoreresidual.py b/tests/bench/scripts/test_scoreresidual.py
new file mode 100644
index 0000000..dced629
--- /dev/null
+++ b/tests/bench/scripts/test_scoreresidual.py
@@ -0,0 +1,519 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The residual sidecar: known damage in, what its two rows say out."""
+
+import json
+import math
+
+import numpy as np
+import pytest
+import torch
+
+import anchors
+import common
+import observations
+import scorebench
+import scoreresidual
+
+SR = common.SR
+BANDS = len(scoreresidual.CENTRES_HZ)
+
+
+class _Vad:
+ """Speech from 1.0 to 2.0 s and from 2.6 to 3.0 s of a 4 s item."""
+
+ def segments(self, x):
+ del x
+ return None, [{
+ "start": 16000,
+ "end": 32000
+ }, {
+ "start": 41600,
+ "end": 48000
+ }]
+
+
+def _item(seed=0, floor_db=-40.0, voice_db=-10.0, seconds=4.0):
+ """A voice burst over a steady floor, both white."""
+ g = torch.Generator().manual_seed(seed)
+ n = int(seconds * SR)
+ floor = torch.randn(n, generator=g) * 10**(floor_db / 20)
+ voice = torch.zeros(n)
+ for start, end in ((1.0, 2.0), (2.6, 3.0)):
+ a, b = int(start * SR), min(int(end * SR), n)
+ if b > a:
+ voice[a:b] = torch.randn(b - a, generator=g) * 10**(voice_db / 20)
+ return floor + voice
+
+
+def _pause_scaled(x, db, vad=_Vad()):
+ """``x`` with everything outside the widened speech lowered by ``db``."""
+ y = x.clone()
+ _, segs = vad.segments(x)
+ keep = torch.zeros(len(x), dtype=torch.bool)
+ for s in segs:
+ a = int((s["start"] / 16000 - scoreresidual.PRE_S) * SR)
+ b = int((s["end"] / 16000 + scoreresidual.POST_S) * SR)
+ keep[max(a, 0):b] = True
+ y[~keep] *= 10**(-db / 20)
+ return y
+
+
+ROW = {"id": "real_x_000.wav", "condition": "real_x", "mix_path": "unused"}
+
+
+def _rows(out, mix):
+ return scoreresidual.pause_metrics(
+ scoreresidual.score_real(ROW, out, mix, _Vad()))
+
+
+def test_weighting_follows_the_468_table_normalised_at_1_khz():
+ assert scoreresidual.weighting(1000.0) == pytest.approx(1.0)
+ for hz, db in ((100.0, -19.8), (6300.0, 12.2), (10000.0, 8.1), (20000.0,
+ -22.2)):
+ assert 20 * math.log10(scoreresidual.weighting(hz)) == pytest.approx(
+ db, abs=0.2)
+ assert BANDS == 27
+ assert scoreresidual.NB_BANDS == 22
+ # every bin between the lowest and highest band edge belongs to a band
+ freqs = np.arange(scoreresidual.N_FFT // 2 + 1) * SR / scoreresidual.N_FFT
+ inside = (freqs >= 50 * 2**(-1 / 6)) & (freqs < 20000 * 2**(1 / 6))
+ assert (scoreresidual.BAND_OF_BIN[inside] >= 0).all()
+ # the 62.5 Hz band holds no bin at this resolution: it is not read
+ assert not scoreresidual.SUPPORTED[1] and scoreresidual.SUPPORTED[2:].all()
+
+
+def test_the_unchanged_input_reads_zero_and_known_reductions_read_true():
+ x = _item()
+ identity = _rows(x, x)
+ assert identity["pause_resid_db"] == pytest.approx(0.0, abs=1e-6)
+ assert identity["pause_resid_db_nb"] == pytest.approx(0.0, abs=1e-6)
+ assert identity["pause_gain_db"] == pytest.approx(0.0, abs=1e-6)
+ for db in (3.0, 10.0):
+ rows = _rows(_pause_scaled(x, db), x)
+ assert rows["pause_resid_db"] == pytest.approx(-db, abs=0.3)
+ assert rows["pause_resid_db_nb"] == pytest.approx(-db, abs=0.3)
+ # the residual against the voice: the floor sits about 30 dB under the
+ # voice's loudest frames before anything is removed
+ assert -36 < identity["pause_level_db"] < -24
+ # and saturates at the clip once inaudible, as the reduction saturates at
+ # the item's bound: a pause silenced outright earns no more than 20 dB
+ silent = _rows(_pause_scaled(x, 60.0), x)
+ assert silent["pause_level_db"] == scoreresidual.LEVEL_CLIP_DB
+ assert silent["pause_resid_db"] == -scoreresidual.ITEM_CLIP_DB
+ assert _rows(_pause_scaled(x, 20.0),
+ x)["pause_resid_db"] == pytest.approx(-20.0, abs=0.3)
+
+
+def test_the_items_own_gain_is_undone_and_turning_it_down_earns_nothing():
+ x = _item()
+ # a louder or quieter copy reads the same pauses
+ assert _rows(x * 2.0, x)["pause_resid_db"] == pytest.approx(0.0, abs=1e-6)
+ assert _rows(x * 0.5, x)["pause_resid_db"] == pytest.approx(0.0, abs=1e-6)
+ assert _rows(x * 0.5, x)["pause_gain_db"] == pytest.approx(-6.02, abs=0.01)
+ # the loophole the review measured: this recording turned down 6 dB while
+ # the clean items stay as they are (so the system's gain reads 0 dB) buys
+ # nothing here, whatever that gain says
+ assert _rows(x * 10**(-6 / 20),
+ x)["pause_resid_db"] == pytest.approx(0.0, abs=1e-6)
+ # the voice turned down 6 dB and the pauses 12 dB: 6 dB of cleanup
+ both = _pause_scaled(x * 10**(-6 / 20), 6.0)
+ assert _rows(both, x)["pause_resid_db"] == pytest.approx(-6.0, abs=0.3)
+ # delay and polarity are undone too
+ delayed = torch.cat([torch.zeros(960), x[:-960]])
+ assert _rows(delayed, x)["pause_resid_db"] == pytest.approx(0.0, abs=0.2)
+ assert _rows(-x, x)["pause_resid_db"] == pytest.approx(0.0, abs=1e-6)
+
+
+def test_deleting_speech_or_its_edges_earns_no_pause_credit():
+ x = _item()
+ # the words gone, the pauses untouched: the voice is gone with them, so
+ # the pauses are as loud as ever against it, the bound
+ gated = x.clone()
+ gated[SR:2 * SR] = 0.0
+ gated[int(2.6 * SR):3 * SR] = 0.0
+ assert _rows(gated, x)["pause_resid_db"] == scoreresidual.ITEM_CLIP_DB
+ # the 200 ms after each word gone: inside the widened mask, not a pause
+ tails = x.clone()
+ tails[2 * SR:int(2.2 * SR)] = 0.0
+ tails[3 * SR:int(3.2 * SR)] = 0.0
+ assert _rows(tails, x)["pause_resid_db"] == pytest.approx(0.0, abs=1e-6)
+ # the item's first and last 300 ms are nobody's: silencing them reads
+ # nothing either
+ edges = x.clone()
+ edges[:int(0.3 * SR)] = 0.0
+ edges[-int(0.3 * SR):] = 0.0
+ assert _rows(edges, x)["pause_resid_db"] == pytest.approx(0.0, abs=1e-6)
+
+
+def test_hiss_counts_more_than_hum_of_the_same_energy():
+ x = _item()
+ t = torch.arange(len(x)) / SR
+ hum = torch.sin(2 * math.pi * 100 * t) * 10**(-30 / 20)
+ g = torch.Generator().manual_seed(7)
+ hiss = torch.randn(len(x), generator=g) * 10**(-30 / 20)
+ hiss = torch.from_numpy(
+ np.fft.irfft(
+ np.fft.rfft(hiss.numpy()) *
+ (np.fft.rfftfreq(len(x), 1 / SR) > 4000), len(x))).float()
+ hiss *= hum.norm() / hiss.norm()
+ with_hum = _rows(x + hum, x)["pause_resid_db"]
+ with_hiss = _rows(x + hiss, x)["pause_resid_db"]
+ assert with_hiss > with_hum + 6.0
+
+
+def test_an_item_without_enough_pause_or_an_old_record_is_not_read():
+ x = _item(seconds=0.9) # the edges off, under 0.4 s of pause is left
+ measured = scoreresidual.score_real(ROW, x, x, _Vad())
+ assert measured["pause_seconds"] < scoreresidual.MIN_PAUSE_S
+ assert not scoreresidual.pause_metrics(measured)
+ # a record without the output's voice energy (an earlier scorer's)
+ older = dict(scoreresidual.score_real(ROW, _item(), _item(), _Vad()))
+ older.pop("speech_out")
+ assert not scoreresidual.pause_metrics(older)
+
+
+def _measurement(out_db, gain_db=0.0, voice_db=30.0, bands=None):
+ """A real item's measurement: flat pauses ``out_db`` under the input's.
+
+ The whole output, voice included, sits ``gain_db`` from the input; the
+ input's voice is ``voice_db`` over its pauses.
+ """
+ out = np.ones(BANDS) if bands is None else np.array(bands, dtype=float)
+ return {
+ "pause_seconds": 1.0,
+ "speech_seconds": 1.0,
+ "pause_frames": 100,
+ "loud_frames": 100,
+ "pause_out": (out * 10**((out_db + gain_db) / 10)).tolist(),
+ "pause_in": out.tolist(),
+ "speech_in": (out * 10**(voice_db / 10)).tolist(),
+ "speech_out": (out * 10**((voice_db + gain_db) / 10)).tolist(),
+ }
+
+
+def test_the_worst_band_skips_the_empty_band_and_the_bands_the_voice_lacks():
+ # the review's construction: every populated band 20 dB under the voice,
+ # the 62.5 Hz band structurally empty, which read 0 dB before
+ rows = scoreresidual.pause_metrics(_measurement(-20.0, voice_db=0.0))
+ assert rows["floor_db"] == pytest.approx(-20.0, abs=1e-6)
+ assert rows["floor_worst_db"] == pytest.approx(-20.0, abs=1e-6)
+ # a band the voice does not occupy does not set the worst band either
+ bands = np.ones(BANDS)
+ bands[-1] = 1e-6 # no voice at 20 kHz
+ m = _measurement(-20.0, voice_db=0.0, bands=bands)
+ m["pause_out"][-1] = 1.0 # the pause holds a full tone there
+ assert scoreresidual.pause_metrics(m)["floor_worst_db"] == pytest.approx(
+ -20.0, abs=1e-6)
+
+
+def _energies(o, r, m):
+ return [
+ float((o * o).mean()),
+ float((o * r).mean()),
+ float((r * r).mean()),
+ float(((m - r)**2).mean()),
+ ]
+
+
+def test_babble_residual_reads_interference_and_not_the_voices_level():
+ g = torch.Generator().manual_seed(1)
+ r = torch.randn(48000, generator=g)
+ n = torch.randn(48000, generator=g) * 10**(-4 / 20)
+ m = r + n
+ # the unchanged mixture: every bit of the chatter, 0 dB
+ assert scoreresidual.babble_metrics(_energies(m, r,
+ m)) == pytest.approx(0.0,
+ abs=0.1)
+ # the voice 3 dB down and the chatter gone: nothing left to charge, the
+ # item's bound
+ assert scoreresidual.babble_metrics(_energies(
+ 0.7 * r, r, m)) == -scoreresidual.ITEM_CLIP_DB
+ # half the chatter left: -6 dB, whatever the voice's level
+ half = r + 0.5 * n
+ assert scoreresidual.babble_metrics(_energies(half, r,
+ m)) == pytest.approx(-6.0,
+ abs=0.2)
+ assert scoreresidual.babble_metrics(_energies(0.5 * half, r,
+ m)) == pytest.approx(-6.0,
+ abs=0.2)
+ # a deleted voice is charged, as SI-SDR charges it; silence reads the
+ # bound, the worst value, never the floor
+ gone = r.clone()
+ gone[:24000] = 0.0
+ assert scoreresidual.babble_metrics(_energies(gone, r, m)) > -3.0
+ assert scoreresidual.babble_metrics(_energies(
+ torch.zeros(48000), r, m)) == scoreresidual.ITEM_CLIP_DB
+ assert scoreresidual.babble_metrics(_energies(
+ -r, r, m)) == scoreresidual.ITEM_CLIP_DB
+
+
+def test_attenuation_never_improves_the_chatter_row():
+ # the review's counterexample: an output barely holding a tenth of the
+ # voice read +23.9 dB, and 1 % quieter read the floor
+ energies = [1.0, 0.1001, 1.0, 0.4]
+ quieter = [0.99**2, 0.1001 * 0.99, 1.0, 0.4]
+ assert scoreresidual.babble_metrics(energies) == scoreresidual.ITEM_CLIP_DB
+ assert scoreresidual.babble_metrics(quieter) == scoreresidual.ITEM_CLIP_DB
+ # and in general the row is the same at every output gain
+ g = torch.Generator().manual_seed(2)
+ r = torch.randn(48000, generator=g)
+ n = torch.randn(48000, generator=g) * 10**(-4 / 20)
+ out = r + 0.3 * n
+ readings = [
+ scoreresidual.babble_metrics(_energies(a * out, r, r + n))
+ for a in (1.0, 0.5, 0.1, 0.01, 0.001)
+ ]
+ assert max(readings) - min(readings) < 1e-3
+
+
+def test_item_contributions_are_bounded_before_pooling():
+ # the review's construction: 13 of 121 items with their pauses silenced
+ # and 108 untouched bought the whole axis; an item now gives at most the
+ # bound, and the pool reads what it should
+ rows = [{
+ "id": str(i),
+ "condition": "real_wild",
+ "mix_path": "x"
+ } for i in range(121)]
+ records = [{
+ "id": str(i),
+ "output_status": "ok",
+ "measurements": _measurement(-200.0 if i < 13 else 0.0),
+ } for i in range(121)]
+ pooled = scoreresidual.aggregate(records, rows,
+ 0.0)["_real_cleanup"]["pause_resid_db"]
+ assert pooled == pytest.approx(-20.0 * 13 / 121, abs=1e-6)
+ assert anchors.normalize(pooled, {
+ "floor": 0.0,
+ "ceiling": -20.0
+ }) == pytest.approx(13 / 121, abs=1e-6)
+
+
+def test_aggregate_pools_real_items_and_keeps_every_count():
+ rows = [
+ {
+ "id": "a",
+ "condition": "real_wild",
+ "mix_path": "x"
+ },
+ {
+ "id": "b",
+ "condition": "real_wild",
+ "mix_path": "x"
+ },
+ {
+ "id": "c",
+ "condition": "real_dirty",
+ "mix_path": "x"
+ },
+ {
+ "id": "e",
+ "condition": "real_noisy",
+ "mix_path": "x"
+ },
+ {
+ "id": "d",
+ "condition": "babble@+4",
+ "mix_path": "x",
+ "clean_path": "y"
+ },
+ ]
+
+ def real(uid, out_db, gain_db=0.0, seconds=1.0):
+ m = _measurement(out_db, gain_db)
+ m["pause_seconds"] = seconds
+ return {"id": uid, "output_status": "ok", "measurements": m}
+
+ records = [
+ real("a", -10.0),
+ # a 6 dB louder output reads the same pauses
+ real("b", -20.0, gain_db=6.0),
+ real("c", -3.0, seconds=0.1),
+ {
+ "id": "e",
+ "output_status": "missing"
+ },
+ {
+ "id": "d",
+ "output_status": "ok",
+ "measurements": {
+ "babble_energy": [[1.0, 1.0, 1.0, 0.5]],
+ "babble_energy_nb": [[1.0, 1.0, 1.0, 0.5]],
+ },
+ },
+ ]
+ out = scoreresidual.aggregate(records, rows, 0.0)
+ assert out["real_wild"]["pause_resid_db"] == pytest.approx(-15.0)
+ assert out["real_wild"]["n"] == 2 and out["real_wild"]["n_missing"] == 0
+ # too little pause on its only item: short, not missing, still counted
+ assert out["real_dirty"] == {
+ "n_expected": 1,
+ "n_missing": 0,
+ "n": 0,
+ "n_short": 1
+ }
+ # an output the system did not return: missing, never a smaller mean
+ assert out["real_noisy"] == {"n_expected": 1, "n_missing": 1, "n": 0}
+ pooled = out["_real_cleanup"]
+ assert pooled["pause_resid_db"] == pytest.approx(-15.0)
+ assert (pooled["n"], pooled["n_expected"], pooled["n_missing"],
+ pooled["n_short"]) == (2, 4, 1, 1)
+ assert pooled["by_family"] == {"real_wild": pytest.approx(-15.0)}
+ assert out["babble@+4"]["babble_resid_db"] == -scoreresidual.ITEM_CLIP_DB
+ assert out["babble@+4"]["n"] == 1
+ # the records carry the item's rows for a pairing
+ assert records[1]["metrics"]["pause_resid_db"] == pytest.approx(-20.0)
+ # the system's calibration is recorded, not applied
+ assert scoreresidual.aggregate(records, rows, 6.0)["_level_cal_db"] == 6.0
+ assert scoreresidual.aggregate(
+ records, rows,
+ 6.0)["_real_cleanup"]["pause_resid_db"] == pytest.approx(-15.0)
+
+
+def test_base_records_and_scores_must_be_this_render_and_this_scorer(
+ tmp_path, monkeypatch):
+ monkeypatch.setattr(common, "set_id", lambda root=None: "tiny")
+ records = [{
+ "id": "d",
+ "condition": "babble@+4",
+ "output_status": "ok",
+ "identity": {
+ "output": "o"
+ },
+ "measurements": {
+ "babble_energy": [[1.0, 1.0, 1.0, 0.5]],
+ "babble_energy_nb": [[1.0, 1.0, 1.0, 0.5]],
+ },
+ }]
+ path = tmp_path / "half.items.jsonl"
+ observations.sidecar(path,
+ records,
+ "half",
+ "tiny",
+ "all",
+ False,
+ scorebench.SCORER_SHA256,
+ render_identity={"outputs_sha256": "render-1"})
+ held = scoreresidual.base_energies(path, {"d"}, "half", "render-1")
+ assert held["d"][1] == [1.0, 1.0, 1.0, 0.5]
+ with pytest.raises(SystemExit, match="another render"):
+ scoreresidual.base_energies(path, {"d"}, "half", "render-2")
+ with pytest.raises(SystemExit, match="another system"):
+ scoreresidual.base_energies(path, {"d"}, "other", "render-1")
+ observations.sidecar(path,
+ records,
+ "half",
+ "tiny",
+ "all",
+ False,
+ "an earlier scorer",
+ render_identity={"outputs_sha256": "render-1"})
+ with pytest.raises(SystemExit, match="another scorer"):
+ scoreresidual.base_energies(path, {"d"}, "half", "render-1")
+ with pytest.raises(SystemExit, match="missing"):
+ scoreresidual.base_energies(tmp_path / "none.jsonl", {"d"}, "half",
+ "render-1")
+ # the base scores the calibration is read from, likewise
+ metrics = tmp_path / "half.metrics.json"
+ metrics.write_text(
+ json.dumps({
+ "_level_cal_db": -0.5,
+ "_scorer_sha256": scorebench.SCORER_SHA256,
+ "_outputs_sha256": "render-1",
+ }))
+ assert scoreresidual.level_calibration(tmp_path, "half", "render-1") == -0.5
+ with pytest.raises(SystemExit, match="another render"):
+ scoreresidual.level_calibration(tmp_path, "half", "render-2")
+ metrics.write_text(
+ json.dumps({
+ "_level_cal_db": -0.5,
+ "_scorer_sha256": "older",
+ "_outputs_sha256": "render-1",
+ }))
+ with pytest.raises(SystemExit, match="another base scorer"):
+ scoreresidual.level_calibration(tmp_path, "half", "render-1")
+
+
+def test_the_level_row_is_bounded_per_item_against_the_items_own_input():
+ """The board's cleanup row gives an item at most ITEM_CLIP_DB of credit or
+ penalty against its own input, then the audibility cap."""
+ # the input's pauses 10 dB under its voice, silenced by the output
+ silenced = scoreresidual.pause_metrics(_measurement(-200.0, voice_db=10.0))
+ # a quiet recording whose pauses are already 30 dB down still saturates
+ quiet = scoreresidual.pause_metrics(_measurement(-200.0, voice_db=30.0))
+ # pauses made 60 dB louder lose at most the bound
+ louder = scoreresidual.pause_metrics(_measurement(60.0, voice_db=10.0))
+
+ assert silenced["pause_level_db"] == pytest.approx(
+ -10.0 - scoreresidual.ITEM_CLIP_DB, abs=1e-6)
+ assert quiet["pause_level_db"] == scoreresidual.LEVEL_CLIP_DB
+ assert louder["pause_level_db"] == pytest.approx(-10.0 +
+ scoreresidual.ITEM_CLIP_DB,
+ abs=1e-6)
+
+
+def test_the_pause_rows_pool_every_real_family_the_everyday_recordings_too():
+ rows = [{
+ "id": "e",
+ "condition": "real_everyday",
+ "mix_path": "x"
+ }, {
+ "id": "w",
+ "condition": "real_wild",
+ "mix_path": "x"
+ }]
+ records = [{
+ "id": "e",
+ "output_status": "ok",
+ "measurements": _measurement(-10.0)
+ }, {
+ "id": "w",
+ "output_status": "ok",
+ "measurements": _measurement(0.0)
+ }]
+
+ pooled = scoreresidual.aggregate(records, rows, 0.0)["_real_cleanup"]
+
+ assert "real_everyday" in scoreresidual.REAL
+ assert pooled["n"] == 2
+ assert pooled["pause_resid_db"] == pytest.approx(-5.0, abs=1e-6)
+
+
+def test_items_without_speech_are_counted_apart_from_those_without_pause():
+ rows = [{
+ "id": i,
+ "condition": "real_noisy",
+ "mix_path": "x"
+ } for i in ("short", "mute")]
+ short = _measurement(0.0)
+ short["pause_seconds"] = 0.1
+ mute = _measurement(0.0)
+ mute["loud_frames"] = 0
+ records = [{
+ "id": "short",
+ "output_status": "ok",
+ "measurements": short
+ }, {
+ "id": "mute",
+ "output_status": "ok",
+ "measurements": mute
+ }]
+
+ out = scoreresidual.aggregate(records, rows, 0.0)
+
+ assert out["real_noisy"]["n_short"] == 1
+ assert out["real_noisy"]["n_no_speech"] == 1
+ assert out["_real_cleanup"]["n_short"] == 1
+ assert out["_real_cleanup"]["n_no_speech"] == 1
diff --git a/tests/bench/scripts/test_scorestream.py b/tests/bench/scripts/test_scorestream.py
new file mode 100644
index 0000000..2bfc1ab
--- /dev/null
+++ b/tests/bench/scripts/test_scorestream.py
@@ -0,0 +1,634 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The streaming probe: look-ahead at several splices and long-input drift.
+
+Read on renders of known behaviour, bound to the probe they were cut from and to
+the audio the board scored.
+"""
+
+# pylint: disable=redefined-outer-name,unused-argument
+
+import json
+import os
+
+import numpy as np
+import pytest
+import soundfile as sf
+import torch
+
+import common
+import observations
+import receipt
+import scorebench
+import scorestream
+
+SR = common.SR
+SECONDS = 2.5 # every long item of the tiny set
+N_ITEMS = 3
+
+
+def _speech(seed, seconds=SECONDS, level=0.2):
+ g = torch.Generator().manual_seed(seed)
+ n = int(seconds * SR)
+ t = torch.arange(n) / SR
+ env = 0.3 + 0.7 * (0.5 + 0.5 * torch.sin(2 * np.pi * 3.0 * t)).pow(2)
+ return (torch.randn(n, generator=g) * env * level).numpy().astype("float32")
+
+
+def _write(path, x):
+ sf.write(str(path), np.asarray(x, dtype="float32"), SR, subtype="FLOAT")
+
+
+# fake systems: a function of the whole input it is handed, as a wrapper would
+# be
+def echo(x):
+ return x.copy()
+
+
+def lookahead(x, ms=30):
+ """Each sample is the mean of the next ``ms`` of input.
+
+ It is causal, with a known look-ahead.
+ """
+ k = SR * ms // 1000
+ c = np.concatenate([[0.0], np.cumsum(np.pad(x, (0, k)))])
+ return ((c[k:k + len(x)] - c[:len(x)]) / k).astype("float32")
+
+
+def offline(x):
+ """Scales the whole file by the level of its last 300 ms.
+
+ Every sample depends on the end.
+ """
+ tail = x[-int(0.3 * SR):]
+ return (x / (np.sqrt((tail**2).mean()) + 1e-9) * 0.1).astype("float32")
+
+
+def blocks(x, seconds=0.5):
+ """Normalises independent half-second blocks.
+
+ Non-causal inside a block, and invisible to a splice that falls on a block
+ boundary.
+ """
+ n = int(seconds * SR)
+ y = x.copy()
+ for i in range(0, len(x), n):
+ seg = x[i:i + n]
+ y[i:i + n] = seg / (np.sqrt((seg**2).mean()) + 1e-9) * 0.1
+ return y.astype("float32")
+
+
+def drifting(x):
+ """Adds noise that grows with the time since its own start.
+
+ From half a second on: state that goes bad, and a fresh start that is the
+ better one.
+ """
+ g = np.random.default_rng(len(x))
+ t = np.arange(len(x)) / SR
+ ramp = np.maximum(0.0, t - 0.5)
+ return (x + 0.3 * ramp * g.standard_normal(len(x))).astype("float32")
+
+
+def gating(x, after=1.25):
+ """Goes silent ``after`` seconds from its own start.
+
+ Speech is dropped once the state is old.
+ """
+ y = x.copy()
+ y[int(after * SR):] = 0.0
+ return y
+
+
+def muting(x):
+ """Silences the last 0.6 s of every item whatever came before.
+
+ It is a loss with no context in it.
+ """
+ y = x.copy()
+ y[-int(0.6 * SR):] = 0.0
+ return y
+
+
+SYSTEMS = {
+ "echo": echo,
+ "ahead": lookahead,
+ "offline": offline,
+ "blocks": blocks,
+ "drifty": drifting,
+ "gater": gating,
+ "muter": muting,
+}
+
+
+def small_rule(monkeypatch):
+ """Returns the probe geometry scaled to short items.
+
+ A one-second stretch from 1.2 s after a 0.4 s lead-in (the cut starts at 0.8
+ s), with splices into the stretch that avoid the half-second grid of the
+ cut, and one on it (0.3 into the stretch is 0.7 into the cut; 0.1 is 0.5).
+ """
+ monkeypatch.setattr(scorestream, "GRID_SECONDS", 0.4)
+ monkeypatch.setattr(scorestream, "TAIL_START", 1.2)
+ monkeypatch.setattr(scorestream, "LEAD_IN", 0.4)
+ monkeypatch.setattr(scorestream, "TAIL_SECONDS", 1.0)
+ monkeypatch.setattr(scorestream, "SPLICES", (0.3, 0.1, 0.7))
+ monkeypatch.setattr(scorestream, "COLD_START_SECONDS", 0.2)
+ monkeypatch.setattr(scorestream, "DROP_DB", 10.0)
+ monkeypatch.setattr(scorestream, "MIN_ITEMS", 2)
+
+
+def _set(tmp_path, monkeypatch, n_items=N_ITEMS):
+ root = tmp_path / "set"
+ out_root = tmp_path / "out"
+ results = tmp_path / "results"
+ for d in (root / "mix", root / "ref", results):
+ d.mkdir(parents=True, exist_ok=True)
+ rows = []
+ for i in range(n_items):
+ rid = f"longATp4_{i:03d}.wav"
+ ref = _speech(i)
+ noise = np.random.default_rng(100 + i).standard_normal(len(ref))
+ mix = ref + 0.05 * noise.astype("float32")
+ _write(root / "ref" / rid, ref)
+ _write(root / "mix" / rid, mix)
+ rows.append({
+ "id": rid,
+ "condition": "long@+4",
+ "mix_path": f"mix/{rid}",
+ "clean_path": f"ref/{rid}",
+ })
+ rows.append({
+ "id": "clean_000.wav",
+ "condition": "clean",
+ "mix_path": "mix/longATp4_000.wav",
+ })
+ with open(root / "manifest.jsonl", "w", encoding="utf-8") as fh:
+ fh.write("".join(json.dumps(r) + "\n" for r in rows))
+ json.dump(
+ {
+ "set_id": "tiny",
+ "n_items": len(rows)
+ },
+ open(root / "checksums.json", "w", encoding="utf-8"),
+ )
+ monkeypatch.setattr(common, "EVAL", str(root))
+ monkeypatch.setattr(common, "OUT_ROOT", str(out_root))
+ monkeypatch.setattr(common, "RESULTS", str(results))
+ return root, out_root, results
+
+
+def _render(name, fn, manifest, probe, probe_root, out_root, results):
+ """Leaves what a wrapper run or runsystem.py leaves behind.
+
+ The whole renders scored into records, the board's stamp, and the probe
+ outputs with the receipt of the same environment.
+ """
+ (out_root / name).mkdir(parents=True, exist_ok=True)
+ records = []
+ for r in scorestream.source_rows(manifest):
+ _write(out_root / name / r["id"],
+ fn(common.load48(r["mix_path"]).numpy()))
+ rec = observations.item(r)
+ output = common.load48(str(out_root / name / r["id"]))
+ rec["identity"] = {"output": scorebench.sample_hash(output)}
+ records.append(rec)
+ observations.write(
+ results / f"{name}.items.jsonl",
+ records,
+ {
+ "system": name,
+ "set_id": "tiny",
+ "subset": "all",
+ "n_expected": len(records),
+ },
+ )
+ pout = probe_root / "out" / name
+ pout.mkdir(parents=True, exist_ok=True)
+ environment = {"system": name, "wrapper_sha256": name * 4}
+ board_ident = dict(environment, inputs={"set_id": "tiny"})
+ board = {
+ "name": name,
+ "set_id": "tiny",
+ "render_receipt_sha256": receipt.digest(board_ident),
+ "render_environment_sha256": receipt.environment_digest(board_ident),
+ }
+ receipt.write(str(pout),
+ dict(environment, inputs={"probe": probe["identity"]}))
+ json.dump(board, open(results / f"{name}.meta.json", "w", encoding="utf-8"))
+ for entry in probe["items"]:
+ for pname in [entry["tail"]] + [f["name"] for f in entry["futures"]]:
+ _write(
+ pout / pname,
+ fn(common.load48(str(probe_root / "in" / pname)).numpy()),
+ )
+
+
+def _receipt_only(out_dir, ident):
+ """Replaces the receipts in ``out_dir`` with one of ``ident``."""
+ for name in os.listdir(out_dir):
+ if name.startswith(".receipt-"):
+ os.remove(os.path.join(out_dir, name))
+ receipt.write(out_dir, ident)
+
+
+def probe_set(tmp_path, monkeypatch, small_rule):
+ """Returns a tiny set whose long items every fake system rendered whole.
+
+ Each was scored on it, and the probe cut from it was rendered by the same
+ fakes.
+ """
+ root, out_root, results = _set(tmp_path, monkeypatch)
+ manifest = common.manifest(str(root))
+ probe_root = tmp_path / "probe"
+ probe = scorestream.write_probe(manifest, str(probe_root))
+ for name, fn in SYSTEMS.items():
+ _render(name, fn, manifest, probe, probe_root, out_root, results)
+ _render("ours", echo, manifest, probe, probe_root, out_root, results)
+ return {
+ "rows": manifest,
+ "probe": probe,
+ "root": str(probe_root),
+ "results": str(results),
+ }
+
+
+def test_probe_cuts_a_lead_in_a_stretch_and_three_futures_per_item(probe_set):
+ probe, root, rows = probe_set["probe"], probe_set["root"], probe_set["rows"]
+ assert (probe["set_id"] == "tiny" and
+ probe["probe_version"] == scorestream.PROBE_VERSION)
+ ids = [e["id"] for e in probe["items"]]
+ assert ids == [r["id"] for r in scorestream.source_rows(rows)]
+ assert probe["identity"] == scorestream.identity_of(
+ scorestream.probe_hashes(probe))
+ assert probe["cut_seconds"] == 0.8 and probe["lead_in_seconds"] == 0.4
+ first = probe["items"][0]
+ # on the 0.4 s grid
+ assert first["cut_seconds"] == 0.8 and first["stretch_seconds"] == 1.2
+ tail = common.load48(os.path.join(root, "in", first["tail"])).numpy()
+ mix = common.load48(rows[0]["mix_path"]).numpy()
+ a, k, b = scorestream.cut_bounds()
+ assert (a, k, b) == (int(0.8 * SR), int(1.2 * SR), int(2.2 * SR))
+ assert len(tail) == b - a and np.array_equal(tail, mix[a:b])
+ other = common.load48(rows[1]["mix_path"]).numpy()
+ splices = [f["splice_seconds"] for f in first["futures"]]
+ assert splices == pytest.approx([0.7, 0.5, 1.1])
+ for f in first["futures"]:
+ future = common.load48(os.path.join(root, "in", f["name"])).numpy()
+ j = int(round(f["splice_seconds"] * SR))
+ assert np.array_equal(future[:j], tail[:j]) and np.array_equal(
+ future[j:], other[a:b - j])
+ assert scorestream.read_probe(root, rows)["items"] == probe["items"]
+
+
+def test_probe_is_rewritten_only_if_stale_and_refuses_what_it_cannot_vouch_for(
+ probe_set, monkeypatch):
+ root, rows, probe = probe_set["root"], probe_set["rows"], probe_set["probe"]
+ assert scorestream.probe_problem(root, rows) is None
+ before = os.path.getmtime(os.path.join(root, "probe.json"))
+ # current: left alone, renders stay valid
+ assert scorestream.write_probe(rows, root) == probe
+ assert os.path.getmtime(os.path.join(root, "probe.json")) == before
+ path = os.path.join(root, "in", probe["items"][0]["tail"])
+ x = common.load48(path).numpy()
+ _write(path, x * 0.5)
+ assert "not the recorded probe input" in scorestream.probe_problem(
+ root, rows)
+ with pytest.raises(SystemExit, match="write the probe again"):
+ scorestream.read_probe(root, rows)
+ # the same samples again: current, whatever the file's bytes say
+ _write(path, x)
+ assert scorestream.probe_problem(root, rows) is None
+ stray = os.path.join(root, "in", "leftover.wav")
+ _write(stray, x)
+ assert "not probe inputs" in scorestream.probe_problem(root, rows)
+ # rewritten without it
+ assert scorestream.write_probe(rows, root)["identity"] == probe["identity"]
+ assert (not os.path.exists(stray) and
+ scorestream.probe_problem(root, rows) is None)
+ # a new verdict rule re-reads, never re-cuts
+ monkeypatch.setattr(scorestream, "RULE_VERSION", "99")
+ assert scorestream.probe_problem(root, rows) is None
+ monkeypatch.setattr(scorestream, "PROBE_VERSION", "99")
+ assert "probe version" in scorestream.probe_problem(root, rows)
+ monkeypatch.setattr(scorestream, "PROBE_VERSION", probe["probe_version"])
+ fewer = [r for r in rows if r["id"] != probe["items"][-1]["id"]]
+ assert "complete inventory" in scorestream.probe_problem(root, fewer)
+ monkeypatch.setattr(common, "set_id", lambda root=None: "other")
+ assert "cut from set" in scorestream.probe_problem(root, rows)
+
+
+def test_probe_needs_enough_long_items_of_full_length(tmp_path, monkeypatch,
+ small_rule):
+ rows = [{
+ "id": "a.wav",
+ "condition": "long@+4",
+ "clean_path": "x",
+ "mix_path": "x",
+ }]
+ with pytest.raises(SystemExit, match="needs 2"):
+ scorestream.write_probe(rows, str(tmp_path))
+ short = tmp_path / "short.wav"
+ _write(short, _speech(0, seconds=2.0))
+ rows = [{
+ "id": f"{i}.wav",
+ "condition": "long@+4",
+ "clean_path": str(short),
+ "mix_path": str(short),
+ } for i in range(2)]
+ with pytest.raises(SystemExit, match="shorter than"):
+ scorestream.write_probe(rows, str(tmp_path))
+
+
+def test_look_ahead_is_how_far_before_the_splice_the_output_differs(small_rule):
+ x = _speech(7)
+ y = x.copy()
+ k = int(round(0.7 * SR))
+ y[k:] = _speech(8)[k:]
+ assert scorestream.look_ahead_ms(echo(x), echo(y), 0.7) == (0, False)
+ ahead_x, ahead_y = lookahead(x, 30), lookahead(y, 30)
+ ms, capped = scorestream.look_ahead_ms(ahead_x, ahead_y, 0.7)
+ assert 20 <= ms <= 40 and not capped
+ assert scorestream.look_ahead_ms(offline(x), offline(y), 0.7) == (700, True)
+ # a block normaliser passes a splice on its grid and is caught by one off it
+ z = x.copy()
+ z[int(0.5 * SR):] = _speech(8)[int(0.5 * SR):]
+ assert scorestream.look_ahead_ms(blocks(x), blocks(z), 0.5) == (0, False)
+ ms, capped = scorestream.look_ahead_ms(blocks(x), blocks(y), 0.7)
+ assert 190 <= ms <= 210 and not capped
+ z = np.zeros_like(x) # silence that stays silent is not a difference
+ assert scorestream.look_ahead_ms(z, z, 0.7) == (0, False)
+
+
+def test_verdict_needs_a_bounded_look_ahead_no_drift_and_no_dropped_speech():
+ good = [{
+ "look_ahead_ms": 20,
+ "look_ahead_capped": False,
+ "drift_db": 0.1,
+ "cold_start_db": -0.4,
+ "dropped_seconds": 0,
+ "speech_seconds": 12,
+ "context_diff_db": -40,
+ }] * 3
+ v = scorestream.verdict(good)
+ assert (v["verdict"] == "yes" and v["causal"] and v["holds"] and
+ not v["reasons"])
+ assert (v["cold_start_db"] == pytest.approx(-0.4) and
+ v["speech_seconds"] == 36)
+ assert not v["path_switch"]
+ far = good + [
+ dict(
+ good[0],
+ look_ahead_ms=scorestream.LOOK_AHEAD_MAX_MS + 10,
+ look_ahead_capped=True,
+ )
+ ]
+ v = scorestream.verdict(far)
+ assert v["verdict"] == "no" and not v["causal"] and v["look_ahead_capped"]
+ assert "at least 110 ms of future input" in v["reasons"][0]
+ drifts = good + [dict(good[0], drift_db=scorestream.DRIFT_MIN_DB - 1)]
+ v = scorestream.verdict(drifts)
+ assert v["verdict"] == "no" and v["causal"] and not v["holds"]
+ assert "drifts over a long input" in v["reasons"][0]
+ slow = [dict(good[0], drift_db=scorestream.DRIFT_MEAN_DB - 0.5)] * 3
+ assert not scorestream.verdict(slow)["holds"]
+ gated = good + [dict(good[0], dropped_seconds=3, path_switch=True)]
+ v = scorestream.verdict(gated)
+ assert (v["verdict"] == "no" and v["causal"] and not v["holds"] and
+ v["path_switch"])
+ assert v["dropped_seconds"] == 3 and v["dropout_items"] == 1
+ assert (
+ "drops speech after a long context: 3 of 48 speech seconds on 1 of 4"
+ " items" in v["reasons"][0])
+ assert scorestream.look_ahead_text(v) == "20 (max 20)"
+ assert (scorestream.look_ahead_text(
+ scorestream.verdict(far)) == "20 (max ≥110)"
+ ) # only the maximum reached the start
+ most = [dict(good[0], look_ahead_ms=700, look_ahead_capped=True)] * 3 + [
+ good[0]
+ ]
+ assert scorestream.look_ahead_text(
+ scorestream.verdict(most)) == "≥700 (max ≥700)"
+ one_short = good + [
+ dict(good[0], look_ahead_ms=300, look_ahead_capped=False),
+ dict(good[0], look_ahead_ms=200, look_ahead_capped=True),
+ ]
+ # the 300 ms one was measured
+ assert scorestream.look_ahead_text(
+ scorestream.verdict(one_short)) == "20 (max 300)"
+
+
+def test_measure_reads_the_fakes_as_built(probe_set):
+ rows = probe_set["rows"]
+ probe = probe_set["probe"]
+ root = probe_set["root"]
+ results = probe_set["results"]
+ out = {
+ n: scorestream.measure(n, rows, probe, root, results) for n in SYSTEMS
+ }
+ assert (out["echo"]["verdict"] == "yes" and
+ out["echo"]["look_ahead_max_ms"] == 0)
+ assert out["echo"]["drift_mean_db"] == pytest.approx(0.0, abs=1e-6)
+ assert out["echo"]["cold_start_db"] == pytest.approx(0.0, abs=1e-6)
+ assert (out["echo"]["dropped_seconds"] == 0 and
+ out["echo"]["speech_seconds"] == N_ITEMS)
+ assert (out["ahead"]["verdict"] == "yes" and
+ 20 <= out["ahead"]["look_ahead_max_ms"] <= 40)
+ assert out["offline"]["verdict"] == "no" and not out["offline"]["causal"]
+ assert (out["offline"]["look_ahead_capped"] and
+ out["offline"]["look_ahead_max_ms"] >= 490)
+ # caught off the grid
+ assert out["blocks"]["verdict"] == "no" and not out["blocks"]["causal"]
+ assert out["blocks"]["look_ahead_max_ms"] >= 190
+ assert out["drifty"]["verdict"] == "no" and out["drifty"]["causal"]
+ assert (not out["drifty"]["holds"] and
+ out["drifty"]["drift_mean_db"] < scorestream.DRIFT_MEAN_DB)
+ # a fresh start is the better one for it
+ assert out["drifty"]["cold_start_db"] > 0
+ # the muter loses the end of every stretch in both renders: lost speech, but
+ # not to the context
+ assert out["muter"]["dropped_seconds"] == 0
+ # the gater keeps the stretch when it starts fresh and silences it after a
+ # long context
+ assert (out["gater"]["verdict"] == "no" and out["gater"]["causal"] and
+ not out["gater"]["holds"])
+ assert (out["gater"]["dropped_seconds"] == N_ITEMS and
+ "drops speech" in out["gater"]["reasons"][0])
+ for o in out.values():
+ assert o["n_items"] == N_ITEMS and len(o["items"]) == N_ITEMS
+ assert all(
+ len(it["look_ahead_by_splice_ms"]) == 3 and it["output_sha256"]
+ for it in o["items"])
+ assert not o["path_switch"]
+ assert out["echo"]["rule"]["version"] == scorestream.RULE_VERSION
+
+
+def test_a_release_that_switches_inference_paths_is_disclosed(probe_set):
+ rows = probe_set["rows"]
+ probe = probe_set["probe"]
+ root = probe_set["root"]
+ results = probe_set["results"]
+ meta_path = os.path.join(results, "echo.meta.json")
+ board = json.load(open(meta_path, encoding="utf-8"))
+ # items 2.5 s, cut 1.4 s
+ json.dump(dict(board, path_switch_seconds=2.0),
+ open(meta_path, "w", encoding="utf-8"))
+ out = scorestream.measure("echo", rows, probe, root, results)
+ assert out["path_switch"] and all(it["path_switch"] for it in out["items"])
+ assert "different inference paths" in scorestream.describe(out)
+ # both beyond: same path
+ json.dump(dict(board, path_switch_seconds=1.0),
+ open(meta_path, "w", encoding="utf-8"))
+ out = scorestream.measure("echo", rows, probe, root, results)
+ assert not out["path_switch"]
+
+
+def test_measure_refuses_unscored_audio_and_incomplete_or_damaged_probe_outputs(
+ probe_set,):
+ rows = probe_set["rows"]
+ probe = probe_set["probe"]
+ root = probe_set["root"]
+ results = probe_set["results"]
+ whole = os.path.join(common.OUT_ROOT, "echo", rows[0]["id"])
+ x = common.load48(whole).numpy()
+ _write(whole, x * 0.9)
+ with pytest.raises(SystemExit, match="not the audio that was scored"):
+ scorestream.measure("echo", rows, probe, root, results)
+ _write(whole, x)
+ future = os.path.join(root, "out", "echo",
+ probe["items"][1]["futures"][2]["name"])
+ y = common.load48(future).numpy()
+ _write(future, y[:-SR // 10]) # a future output 100 ms short
+ with pytest.raises(SystemExit, match="samples for an input"):
+ scorestream.measure("echo", rows, probe, root, results)
+ bad = y.copy()
+ bad[10] = np.nan
+ _write(future, bad)
+ with pytest.raises(SystemExit, match="not finite"):
+ scorestream.measure("echo", rows, probe, root, results)
+ os.remove(future)
+ with pytest.raises(SystemExit, match="must be complete"):
+ scorestream.measure("echo", rows, probe, root, results)
+ with pytest.raises(SystemExit, match="score nobody before"):
+ scorestream.measure("nobody", rows, probe, root, results)
+
+
+def test_probe_renders_must_come_from_the_boards_environment_and_this_probe(
+ probe_set,):
+ root = probe_set["root"]
+ results = probe_set["results"]
+ probe = probe_set["probe"]
+ out = os.path.join(root, "out", "echo")
+ environment = {"system": "echo", "wrapper_sha256": "echo" * 4}
+ assert scorestream.environment_problem("echo", results, root, probe) is None
+ _receipt_only(out, dict(environment, inputs={"probe": "another probe"}))
+ assert "other probe inputs" in scorestream.environment_problem(
+ "echo", results, root, probe)
+ _receipt_only(
+ out,
+ dict(
+ environment,
+ wrapper_sha256="edited",
+ inputs={"probe": probe["identity"]},
+ ),
+ )
+ assert "another environment" in scorestream.environment_problem(
+ "echo", results, root, probe)
+ edited = [n for n in os.listdir(out) if n.startswith(".receipt-")][0]
+ os.rename(
+ os.path.join(out, edited),
+ os.path.join(out, ".receipt-otherhost-1.json"),
+ )
+ # a second shard
+ receipt.write(out, dict(environment, inputs={"probe": probe["identity"]}))
+ assert "another environment" in scorestream.environment_problem(
+ "echo", results, root, probe)
+ _receipt_only(out, dict(environment, inputs={"probe": probe["identity"]}))
+ assert scorestream.environment_problem("echo", results, root, probe) is None
+ for name in os.listdir(out):
+ if name.startswith(".receipt-"):
+ os.remove(os.path.join(out, name))
+ assert "no receipt" in scorestream.environment_problem(
+ "echo", results, root, probe)
+ assert "no stamp" in scorestream.environment_problem(
+ "nobody", results, root, probe)
+ stamp_path = os.path.join(results, "ours.meta.json")
+ stamp = json.load(open(stamp_path, encoding="utf-8"))
+ json.dump(
+ {
+ k: v for k, v in stamp.items() if k != "render_environment_sha256"
+ },
+ open(stamp_path, "w", encoding="utf-8"),
+ )
+ assert "no render environment" in scorestream.environment_problem(
+ "ours", results, root, probe)
+
+
+def test_main_writes_a_bound_sidecar_per_rendered_system(
+ probe_set, monkeypatch, capsys):
+ root = probe_set["root"]
+ results = probe_set["results"]
+ probe = probe_set["probe"]
+ monkeypatch.setattr("sys.argv", ["scorestream.py", "--probe-dir", root])
+ scorestream.main()
+ side = json.load(
+ open(os.path.join(results, "echo.stream.json"), encoding="utf-8"))
+ assert (side["verdict"] == "yes" and side["_set_id"] == "tiny" and
+ side["_subset"] == "all")
+ assert (side["_rule_version"] == scorestream.RULE_VERSION and
+ side["_scorer_sha256"] == scorestream.SCORER_SHA256)
+ assert side["_probe_identity"] == probe["identity"]
+ with open(os.path.join(results, "echo.meta.json"), encoding="utf-8") as fh:
+ stamp = json.load(fh)
+ assert side["_render_receipt_sha256"] == stamp["render_receipt_sha256"]
+ ours = json.load(
+ open(os.path.join(results, "ours.stream.json"), encoding="utf-8"))
+ assert ours["verdict"] == "yes" and ours["_render_receipt_sha256"]
+ path = os.path.join(results, "offline.stream.json")
+ with open(path, encoding="utf-8") as fh:
+ offline_side = json.load(fh)
+ assert offline_side["verdict"] == "no"
+ text = capsys.readouterr().out
+ assert "offline" in text and "at least 1100 ms of future input" in text
+ assert ("drifts over a long input" in text and "≥1100" in text and
+ "drops speech" in text)
+ assert (side["_probe_version"] == scorestream.PROBE_VERSION and
+ side["rule"]["keep_db"] == scorestream.KEEP_DB)
+ # the probe itself is confirmed, not rewritten, when current
+ monkeypatch.setattr("sys.argv",
+ ["scorestream.py", "--probe", "--probe-dir", root])
+ scorestream.main()
+ assert "probe is current" in capsys.readouterr().out
+ # a system rendered from another probe stops the run
+ _receipt_only(
+ os.path.join(root, "out", "echo"),
+ {
+ "system": "echo",
+ "wrapper_sha256": "echo" * 4,
+ "inputs": {
+ "probe": "stale"
+ },
+ },
+ )
+ monkeypatch.setattr("sys.argv", ["scorestream.py", "--probe-dir", root])
+ with pytest.raises(SystemExit, match="other probe inputs"):
+ scorestream.main()
+
+
+def test_rule_sentence_quotes_the_constants():
+ s = scorestream.rule_sentence()
+ assert (f"{scorestream.LOOK_AHEAD_MAX_MS:.0f} ms" in s and "SI-SDR" in s and
+ s.startswith("the streaming probe"))
diff --git a/tests/bench/scripts/test_seamtest.py b/tests/bench/scripts/test_seamtest.py
new file mode 100644
index 0000000..bdc557f
--- /dev/null
+++ b/tests/bench/scripts/test_seamtest.py
@@ -0,0 +1,278 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Chunk-seam check: zone geometry, the shift trick, and fakes.
+
+The seam behaviour of each fake is known.
+"""
+
+# pylint: disable=redefined-outer-name,unused-argument
+
+import json
+import math
+
+import pytest
+import soundfile as sf
+import torch
+
+import common
+import seamtest
+
+SR = common.SR
+
+
+def speech(seconds, seed=0, level=0.2):
+ n = int(seconds * SR)
+ g = torch.Generator().manual_seed(seed)
+ t = torch.arange(n) / SR
+ env = 0.3 + 0.7 * (0.5 + 0.5 * torch.sin(2 * math.pi * 2.5 * t)).pow(2)
+ return torch.randn(n, generator=g) * env * level
+
+
+def crossfaded(x, chunk_s, overlap_s, seg_fn):
+ """Returns a fake chunked system whose seams sit where the isolator's do.
+
+ The separator's own windowing (model.py, enhance) around ``seg_fn(seg,
+ first, last)``.
+ """
+ chunk, overlap, hop = seamtest.window_samples(chunk_s, overlap_s)
+ n = len(x)
+ if n <= chunk:
+ return seg_fn(x, True, True)
+ out, weight = torch.zeros(n), torch.zeros(n)
+ for start in range(0, n, hop):
+ end = min(start + chunk, n)
+ seg = seg_fn(x[start:end], start == 0, end == n)
+ w = torch.ones(end - start)
+ if overlap > 0 and start > 0:
+ w[:overlap] = torch.linspace(0.0, 1.0, overlap)
+ if overlap > 0 and end < n:
+ w[-overlap:] = torch.linspace(1.0, 0.0, overlap)
+ out[start:end] += seg * w
+ weight[start:end] += w
+ if end == n:
+ break
+ return out / weight.clamp(min=1e-6)
+
+
+def edge_damage(overlap_s, gain=0.25):
+ """Returns a window whose overlapping edges are ``gain`` quieter.
+
+ The first and last ``overlap`` of the window, except at the clip's own ends:
+ after the crossfade every seam zone sits at ``gain``, everything else is
+ intact.
+ """
+ edge = int(overlap_s * SR)
+
+ def fn(seg, first, last):
+ y = seg.clone()
+ if not first:
+ y[:edge] *= gain
+ if not last:
+ y[-edge:] *= gain
+ return y
+
+ return fn
+
+
+def test_seam_zones_follow_the_separators_windows():
+ n = 45 * SR
+ # hop 6 s: windows at 0, 6, ..., 36 s reach the end
+ zones = seamtest.seam_zones(n, 8.0, 2.0)
+ assert len(zones) == 7
+ assert zones[0] == (58, 82) # [6.0 - 0.2, 8.0 + 0.2) s in 100 ms blocks
+ assert zones[-1] == (418, 442)
+ # the same seams one second earlier
+ shifted = seamtest.seam_zones(n, 8.0, 2.0, shift_seconds=1.0)
+ assert len(shifted) == 7 and shifted[0] == (48, 72)
+ # shorter than one window: no seams
+ assert not seamtest.seam_zones(5 * SR, 8.0, 2.0)
+ m = seamtest.seam_mask(450, zones)
+ assert int(m.sum()) == 7 * 24 and bool(m[58]) and not bool(m[57])
+ # overlap capped at half
+ assert seamtest.window_samples(8.0, 6.0) == (8 * SR, 4 * SR, 4 * SR)
+ # zone-sized stretches away from every seam
+ ctrl = seamtest.control_windows(450, zones, 24)
+ assert ctrl and all(b1 - b0 == 24 for b0, b1 in ctrl)
+ assert all(not m[b0:b1].any() for b0, b1 in ctrl)
+ # tiled from the start, short of a seam
+ assert ctrl[0] == (0, 24) and ctrl[1] == (24, 48)
+ # no stretch that long between seams
+ assert not seamtest.control_windows(450, zones, 60)
+
+
+def test_block_diff_reads_the_floor_for_identical_signals_and_level_otherwise():
+ x = speech(2.0)
+ d, loud = seamtest.block_diff_db(x, x, x)
+ assert float(d.max()) == seamtest.DIFF_FLOOR_DB and bool(loud.all())
+ d, _ = seamtest.block_diff_db(x, 0.5 * x, x)
+ assert float(d.mean()) == pytest.approx(20 * math.log10(0.5), abs=0.01)
+
+
+def test_identity_system_reads_the_floor_and_no_seam_penalty():
+ x = speech(20.0)
+ d = seamtest.measure_item(lambda a, c, o: a, x, x, 4.0, 1.0)
+ assert d["n_seam_blocks"] > 0 and d["n_else_blocks"] > 0
+ assert d["shift_diff_db"] == seamtest.DIFF_FLOOR_DB
+ assert d["shift_diff_seam_mean_db"] == seamtest.DIFF_FLOOR_DB
+ assert abs(d["seam_penalty_db"]) < 0.01 and abs(d["seam_dip_db"]) < 0.01
+ assert (abs(d["kept_seam_db"]) < 0.01 and
+ abs(d["seam_resid_excess_db"]) < 0.5)
+
+
+def test_edge_damage_is_caught_at_the_seams_and_nowhere_else():
+ x = speech(20.0, seed=1)
+
+ def run(a, c, o):
+ return crossfaded(a, c, o, edge_damage(o))
+
+ d = seamtest.measure_item(run, x, x, 4.0, 1.0, shift_seconds=1.0)
+ # -12 dB at every seam
+ assert d["seam_dip_db"] == pytest.approx(20 * math.log10(0.25), abs=0.5)
+ # the mean over the widened zone still shows it
+ assert d["seam_penalty_db"] < -6
+ # nothing lost between the seams
+ assert d["kept_else_db"] == pytest.approx(0.0, abs=0.05)
+ # position-independent there
+ assert d["shift_diff_else_mean_db"] == seamtest.DIFF_FLOOR_DB
+ assert d["shift_diff_seam_mean_db"] > d["shift_diff_else_mean_db"] + 40
+ # the worst block of every zone: the full -12 dB dip
+ assert d["shift_diff_seam_max_db"] > -8
+ # and of every control window: nothing
+ assert d["shift_diff_else_max_db"] == seamtest.DIFF_FLOOR_DB
+ assert d["n_control_windows"] > 0
+ assert d["worst_in_seam"]
+
+
+def test_noise_everywhere_is_position_dependence_but_not_a_seam_penalty():
+
+ # fresh -30 dB noise on every call: the two passes differ everywhere
+ def run(a, c, o):
+ g = torch.Generator().manual_seed(len(a))
+ return a + torch.randn(len(a), generator=g) * float(
+ a.pow(2).mean().sqrt()) * 10**(-30 / 20)
+
+ x = speech(20.0, seed=2)
+ d = seamtest.measure_item(run, x, x, 4.0, 1.0)
+ # two independent draws: +3 dB
+ assert d["shift_diff_db"] == pytest.approx(-30 + 3, abs=2)
+ assert abs(d["shift_diff_seam_mean_db"] - d["shift_diff_else_mean_db"]) < 2
+ # same statistic
+ assert abs(d["shift_diff_seam_max_db"] - d["shift_diff_else_max_db"]) < 2
+ # both sides fluctuate
+ assert abs(d["seam_penalty_db"]) < 0.5 and abs(d["seam_dip_db"]) < 1
+
+
+def test_reference_free_clip_reports_position_dependence_only():
+ x = speech(12.0)
+ d = seamtest.measure_item(lambda a, c, o: a, x, None, 4.0, 1.0)
+ assert "shift_diff_seam_mean_db" in d and "seam_penalty_db" not in d
+
+
+def test_short_clip_has_no_seams_but_a_shift_difference():
+ x = speech(3.0)
+ d = seamtest.measure_item(lambda a, c, o: a, x, x, 8.0, 2.0)
+ assert (d["n_seam_blocks"] == 0 and
+ d["shift_diff_seam_mean_db"] != d["shift_diff_seam_mean_db"])
+ assert d["shift_diff_db"] == seamtest.DIFF_FLOOR_DB
+ s = seamtest.aggregate([d])
+ assert (s["n_with_seams"] == 0 and
+ s["seam_penalty_db"] != s["seam_penalty_db"])
+
+
+def test_aggregate_averages_items_and_counts_seams():
+ a = {
+ "n_seam_blocks": 4,
+ "shift_diff_db": -50.0,
+ "seam_penalty_db": -2.0,
+ "worst_in_seam": True,
+ }
+ b = {"n_seam_blocks": 0, "shift_diff_db": -70.0, "worst_in_seam": False}
+ s = seamtest.aggregate([a, b])
+ assert s["n_items"] == 2 and s["n_with_seams"] == 1
+ assert s["shift_diff_db"] == -60.0 and s["seam_penalty_db"] == -2.0
+ assert s["worst_in_seam_frac"] == 1.0 # only items with seams vote
+
+
+def test_parse_windows_and_label():
+ windows = seamtest.parse_windows("8/2,5/1", (8.0, 2.0))
+ assert windows == [(8.0, 2.0), (5.0, 1.0)]
+ assert seamtest.parse_windows("", (8.0, 2.0)) == [(8.0, 2.0)]
+ assert (seamtest.label(8.0, 2.0) == "8/2" and
+ seamtest.label(0.5, 0.1) == "0.5/0.1")
+
+
+def long_set(tmp_path, monkeypatch):
+ root = tmp_path / "set"
+ (root / "mix").mkdir(parents=True)
+ (root / "ref").mkdir()
+ rows = []
+ for i in range(2):
+ x = speech(3.0, seed=10 + i)
+ rid = f"longATp4_{i:03d}.wav"
+ sf.write(str(root / "mix" / rid), x.numpy(), SR, subtype="FLOAT")
+ sf.write(str(root / "ref" / rid), x.numpy(), SR, subtype="FLOAT")
+ rows.append({
+ "id": rid,
+ "condition": "long@+4",
+ "mix_path": f"mix/{rid}",
+ "clean_path": f"ref/{rid}",
+ })
+ with open(root / "manifest.jsonl", "w", encoding="utf-8") as fh:
+ fh.write("".join(json.dumps(r) + "\n" for r in rows))
+ json.dump({
+ "set_id": "tiny",
+ "n_items": 2
+ }, open(root / "checksums.json", "w", encoding="utf-8"))
+ monkeypatch.setattr(common, "EVAL", str(root))
+ return root
+
+
+def test_main_runs_the_tiny_model_through_the_public_path(
+ identity_model, long_set, tmp_path, monkeypatch):
+ # pylint: disable-next=import-outside-toplevel
+ from inworld.voice_isolation import isolator
+
+ vi = isolator.VoiceIsolator(identity_model, device="cpu")
+ calls = []
+
+ def runner(a):
+ calls.append(a.model)
+ return vi, (lambda x, c=None, o=None: vi.isolate(
+ x, SR, chunk_seconds=c, overlap_seconds=o))
+
+ monkeypatch.setattr(common, "isolator_runner", runner)
+ out = tmp_path / "seams.json"
+ monkeypatch.setattr(
+ "sys.argv",
+ [
+ "seamtest.py",
+ "--model",
+ "tiny",
+ "--windows",
+ "0.5/0.1",
+ "--shift-seconds",
+ "0.3",
+ "--out",
+ str(out),
+ ],
+ )
+ seamtest.main()
+ r = json.load(open(out, encoding="utf-8"))
+ assert calls == ["tiny"] and r["set_id"] == "tiny" and r["model"] == "tiny"
+ w = r["windows"]["0.5/0.1"]
+ assert w["summary"]["n_items"] == 2 and w["summary"]["n_with_seams"] == 2
+ # the tiny model is the identity
+ assert abs(w["summary"]["seam_penalty_db"]) < 0.5
+ assert w["items"][0]["id"] == "longATp4_000.wav"
diff --git a/tests/bench/scripts/test_sidecarviews.py b/tests/bench/scripts/test_sidecarviews.py
new file mode 100644
index 0000000..c92da6c
--- /dev/null
+++ b/tests/bench/scripts/test_sidecarviews.py
@@ -0,0 +1,369 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The three sidecars keep per-item records.
+
+The records are reused across passes and derive any view.
+"""
+
+# pylint: disable=redefined-outer-name,unused-argument
+
+import json
+import pathlib
+
+import pytest
+import soundfile as sf
+import torch
+
+import common
+import levels
+import observations
+import scorebench
+import scorenisqa
+import scorerealx
+
+SR = common.SR
+
+
+def _write(path, x):
+ sf.write(str(path), x.numpy(), SR, subtype="FLOAT")
+
+
+def tiny_real_set(tmp_path, monkeypatch):
+ """Two babble items with references and three real recordings.
+
+ The set comes with the outputs of a system 'half'.
+ """
+ root, out_root = tmp_path / "set", tmp_path / "out"
+ (root / "mix").mkdir(parents=True)
+ (root / "ref").mkdir()
+ (out_root / "half").mkdir(parents=True)
+ n = 2 * SR
+ rows = []
+ for i in range(5):
+ g = torch.Generator().manual_seed(i)
+ speech = torch.randn(n, generator=g) * 0.1
+ noise = (
+ torch.randn(n, generator=torch.Generator().manual_seed(100 + i)) *
+ 0.05)
+ real = i >= 2
+ rid = f"{'real_x' if real else 'babbleATp4'}_{i:03d}.wav"
+ mix = speech + noise
+ _write(root / "mix" / rid, mix)
+ row = {
+ "id": rid,
+ "condition": "real_x" if real else "babble@+4",
+ "mix_path": f"mix/{rid}",
+ }
+ if not real:
+ _write(root / "ref" / rid, speech)
+ row["clean_path"] = f"ref/{rid}"
+ rows.append(row)
+ # the last one deleted
+ _write(out_root / "half" / rid, mix * (0.5 if i != 4 else 0.02))
+ with open(root / "manifest.jsonl", "w", encoding="utf-8") as fh:
+ fh.write("".join(json.dumps(r) + "\n" for r in rows))
+ json.dump(
+ {
+ "set_id": "tiny",
+ "n_items": len(rows)
+ },
+ open(root / "checksums.json", "w", encoding="utf-8"),
+ )
+ monkeypatch.setattr(common, "EVAL", str(root))
+ monkeypatch.setattr(common, "OUT_ROOT", str(out_root))
+ monkeypatch.setattr(common, "RESULTS", str(tmp_path / "results"))
+
+ def fake_nisqa(x):
+ return float(3 + x.abs().mean()), 1.0, 2.0, 3.0, 4.0
+
+ monkeypatch.setattr(common, "nisqa", fake_nisqa)
+ return common.manifest(str(root))
+
+
+class _Vad:
+
+ def segments(self, x):
+ # pylint: disable-next=import-outside-toplevel
+ import torchaudio
+
+ x16 = torchaudio.functional.resample(x, SR, 16000)
+ # two inner segments: one touching an edge would be a cut-off word
+ return x16, [
+ {
+ "start": len(x16) // 8,
+ "end": len(x16) // 2
+ },
+ {
+ "start": len(x16) // 2,
+ "end": 7 * len(x16) // 8
+ },
+ ]
+
+
+class _Spk:
+
+ def emb(self, w):
+ return torch.tensor([1.0, 0.0])
+
+
+def _index(records, system, scorer):
+ return {
+ scorebench.reuse_key(r["identity"]): r
+ for r in records
+ if r.get("identity")
+ }
+
+
+def test_nisqa_records_reuse_and_the_mean_reads_the_first_items_of_a_view(
+ tiny_real_set,):
+ rows = tiny_real_set
+ want = ["babble@+4", "real_x"]
+ first = scorenisqa.assemble("half", rows)
+ assert all(r["identity"]["output"] for r in first)
+ whole = scorenisqa.aggregate(first, rows, want, 48)
+ assert whole["real_x"]["n"] == 3 and whole["babble@+4"]["n"] == 2
+ reuse = _index(first, "half", scorenisqa.SCORER_SHA256)
+ again = scorenisqa.assemble("half", rows, reuse=reuse)
+ assert [r["metrics"] for r in again] == [r["metrics"] for r in first]
+ # the published sample: the first item(s)
+ limited = scorenisqa.aggregate(first, rows, want, 1)
+ assert limited["real_x"]["n"] == 1 and limited["real_x"]["n_expected"] == 1
+ # a view of two real items
+ view = [r for r in rows if r["condition"] == "real_x"][1:]
+ derived = scorenisqa.aggregate(
+ [r for r in first if r["id"] in {v["id"] for v in view}], view, want,
+ 48)
+ direct_records = scorenisqa.assemble("half", view)
+ direct = scorenisqa.aggregate(direct_records, view, want, 48)
+ assert derived == direct and "babble@+4" not in derived
+
+
+def test_realx_records_carry_segments_and_anchors_and_views_derive(
+ tiny_real_set,):
+ pytest.importorskip("scipy", reason="needs the eval extra")
+ rows = tiny_real_set
+ items = scorerealx.select_items(rows, "real")
+ first = scorerealx.assemble("half", items, _Vad(), _Spk(), 0.85)
+ out = scorerealx.aggregate(first, items, 0.85, 0.0)
+ assert (out["_pooled_real"]["n_segments"] == 6 and
+ out["_pooled_real"]["n_deleted"] == 2)
+ assert out["_pooled_primary"]["n_segments"] == 6
+ assert out["_items_primary"][items[-1]["id"]] == [2, 2]
+ assert set(out["_anchor_sims"]) == {it["id"] for it in items}
+ last = first[-1]["metrics"]
+ assert last["n_segments"] == 2 and last["primary_segments"] == 2
+ assert levels.deleted(last["primary_drops"], 0.0) == [1.0, 1.0]
+ again = scorerealx.assemble(
+ "half",
+ items,
+ _Vad(),
+ _Spk(),
+ 0.85,
+ reuse=_index(first, "half", scorerealx.SCORER_SHA256),
+ )
+ reused = [r["measurements"] for r in again]
+ assert reused == [r["measurements"] for r in first]
+ # the anchoring rule is part of the identity: another threshold scores
+ # afresh
+ other = scorerealx.assemble(
+ "half",
+ items,
+ _Vad(),
+ _Spk(),
+ 0.5,
+ reuse=_index(first, "half", scorerealx.SCORER_SHA256),
+ )
+ assert all(
+ r["identity"]["semantics"]["sim_threshold"] == 0.5 for r in other)
+ view = items[1:]
+ derived = scorerealx.aggregate(
+ [r for r in first if r["id"] in {v["id"] for v in view}],
+ view,
+ 0.85,
+ 0.0,
+ )
+ direct_records = scorerealx.assemble("half", view, _Vad(), _Spk(), 0.85)
+ direct = scorerealx.aggregate(direct_records, view, 0.85, 0.0)
+ assert derived == direct and derived["_pooled_real"]["n_segments"] == 4
+ # without anchoring there is no primary pool and no anchor record
+ plain_records = scorerealx.assemble("half", items, _Vad(), None, 0.85)
+ plain = scorerealx.aggregate(plain_records, items, 0.85, 0.0)
+ assert "_pooled_primary" not in plain and "_anchor_sims" not in plain
+
+
+def test_nisqa_records_carry_the_published_cohort(tiny_real_set):
+ """Only the first ``limit`` items of a condition feed the published mean.
+
+ The others keep their values under measurements, so a paired comparison
+ reads the board's cohort.
+ """
+ rows = tiny_real_set
+ want = ["real_x"]
+ records = scorenisqa.assemble("half", rows)
+ members = scorenisqa.cohort(rows, want, 2)
+ assert len(members) == 2
+ scorenisqa.mark(records, members)
+ inside = [r for r in records if r["id"] in members]
+ outside = [
+ r for r in records
+ if r["condition"] == "real_x" and r["id"] not in members
+ ]
+ assert all(
+ r["cohort"] and r["metrics"] and not r["measurements"] for r in inside)
+ assert all(
+ not r["cohort"] and not r["metrics"] and r["measurements"]["nisqa"]
+ for r in outside)
+ assert scorenisqa.aggregate(records, rows, want, 2)["real_x"]["n"] == 2
+ # a view whose cohort includes an item outside the whole set's finds its
+ # values again
+ view = [r for r in rows if r["condition"] == "real_x"][1:]
+ scorenisqa.mark(records, scorenisqa.cohort(view, want, 48))
+ assert all(
+ r["metrics"] for r in records if r["id"] in {v["id"] for v in view})
+ assert scorenisqa.aggregate(records, view, want, 48)["real_x"]["n"] == 2
+
+
+def test_primary_speaker_quality_reads_frozen_input_segments_one_at_a_time(
+ tiny_real_set, monkeypatch):
+ rows = tiny_real_set
+ items = scorerealx.select_items(rows, "real")
+ records = scorerealx.assemble("half", items, _Vad(), _Spk(), 0.85)
+ m = records[0]["measurements"]
+ # the input's segments
+ assert m["seg_start"] == [4000, 16000] and m["seg_end"] == [16000, 28000]
+ # the fake NISQA reads level: a segment of the loud half scores higher than
+ # a quiet one
+ out = torch.cat([torch.full((48000,), 0.5), torch.full((48000,), 0.05)])
+ q = scorenisqa.primary_quality(out, [(0, 16000), (16000, 32000)],
+ min_seconds=0.5)
+ assert (q["nisqa_primary_eligible_s"] == 2.0 and
+ q["nisqa_primary_coverage"] == 1.0)
+ # duration-weighted mean
+ assert abs(q["nisqa_mos_primary"] - (3.5 + 3.05) / 2) < 1e-6
+ q = scorenisqa.primary_quality(out, [(0, 16000), (16000, 24000)],
+ min_seconds=1.0)
+ assert (q["nisqa_primary_eligible_s"] == 1.0 and
+ abs(q["nisqa_primary_coverage"] - 2 / 3) < 1e-9)
+ # the half-second segment is not scored on its own
+ assert q["nisqa_mos_primary"] == 3.5
+ assert "nisqa_mos_primary" not in scorenisqa.primary_quality(
+ out, [(0, 8000)], min_seconds=1.0)
+ # the frozen segments come from INPUT's deletion records, never from an
+ # output
+ path = str(pathlib.Path(common.RESULTS) / "INPUT.realx.items.jsonl")
+ observations.sidecar(path, records, "INPUT", "tiny", "all", False,
+ scorerealx.SCORER_SHA256)
+ segs = scorenisqa.primary_segments(common.RESULTS)
+ assert segs[items[0]["id"]] == [(4000, 16000), (16000, 28000)]
+ # and only INPUT's, of this set, of the whole set, by the current deletion
+ # scorer, complete
+ observations.sidecar(path, records, "half", "tiny", "all", False,
+ scorerealx.SCORER_SHA256)
+ with pytest.raises(SystemExit, match="not INPUT"):
+ scorenisqa.primary_segments(common.RESULTS)
+ observations.sidecar(path, records, "INPUT", "previous", "all", False,
+ scorerealx.SCORER_SHA256)
+ with pytest.raises(SystemExit, match="not the whole current set"):
+ scorenisqa.primary_segments(common.RESULTS)
+ observations.sidecar(path, records, "INPUT", "tiny", "gate", False,
+ scorerealx.SCORER_SHA256)
+ with pytest.raises(SystemExit, match="not the whole current set"):
+ scorenisqa.primary_segments(common.RESULTS)
+ observations.sidecar(path, records, "INPUT", "tiny", "all", False,
+ "an earlier scorer")
+ with pytest.raises(SystemExit, match="another deletion scorer"):
+ scorenisqa.primary_segments(common.RESULTS)
+ observations.sidecar(path, records[:-1], "INPUT", "tiny", "all", False,
+ scorerealx.SCORER_SHA256)
+ with pytest.raises(SystemExit, match="covers 2 of 3 real items"):
+ scorenisqa.primary_segments(common.RESULTS)
+ # a pass without --primary-anchor: segments present, no speaker anchoring,
+ # nothing primary
+ unanchored = scorerealx.assemble("half", items, _Vad(), None, 0.85)
+ assert all(not r["measurements"]["anchor_sims"] for r in unanchored)
+ assert all(
+ p == 0.0 for r in unanchored for p in r["measurements"]["seg_primary"])
+ observations.sidecar(path, unanchored, "INPUT", "tiny", "all", False,
+ scorerealx.SCORER_SHA256)
+ with pytest.raises(SystemExit, match="no speaker anchoring"):
+ scorenisqa.primary_segments(common.RESULTS)
+ # a recording without usable speech is not an unanchored pass
+ silent = [dict(r, measurements=dict(r["measurements"])) for r in records]
+ silent[0]["measurements"].update(seg_start=[],
+ seg_end=[],
+ seg_drop=[],
+ seg_primary=[],
+ anchor_sims=[])
+ observations.sidecar(path, silent, "INPUT", "tiny", "all", False,
+ scorerealx.SCORER_SHA256)
+ segs = scorenisqa.primary_segments(common.RESULTS)
+ assert items[0]["id"] not in segs and items[1]["id"] in segs
+
+
+def test_nisqa_and_deletion_files_name_the_render_they_read_and_views_keep_it(
+ tiny_real_set, tmp_path, monkeypatch):
+ # pylint: disable-next=import-outside-toplevel
+ import sys
+
+ results, view = tmp_path / "results", tmp_path / "view"
+ results.mkdir()
+ view.mkdir()
+ rendered = "f" * 64
+ (results / "half.meta.json").write_text(
+ json.dumps({
+ "set_id": "tiny",
+ "name": "half",
+ "outputs_sha256": rendered
+ }))
+ for where, subset in ((results, "all"), (view, "gate")):
+ (where / "half.metrics.json").write_text(
+ json.dumps({
+ "_set_id": "tiny",
+ "_subset": subset,
+ "_level_cal_db": 0.0
+ }))
+ monkeypatch.setattr(common, "Vad", _Vad)
+ runs = (
+ (scorenisqa, "nisqa", ["--conds", "babble@+4,real_x"]),
+ (scorerealx, "realx", []),
+ )
+ for module, ext, extra in runs:
+ monkeypatch.setattr(sys, "argv",
+ [f"score{ext}.py", "--systems", "half"] + extra)
+ module.main()
+ whole = json.loads((results / f"half.{ext}.json").read_text())
+ with open(results / f"half.{ext}.items.jsonl", encoding="utf-8") as fh:
+ header = json.loads(fh.readline())
+ assert whole["_outputs_sha256"] == rendered
+ assert header["outputs_sha256"] == rendered
+ # a view: the digest comes from the whole-set records, with no stamp beside
+ members = {r["id"] for r in tiny_real_set[1:]}
+ monkeypatch.setattr(common, "SUBSET", "gate")
+ monkeypatch.setattr(common,
+ "panel_members",
+ lambda name, root=None: members)
+ monkeypatch.setattr(common, "RESULTS", str(view))
+ for module, ext, extra in runs:
+ monkeypatch.setattr(
+ sys,
+ "argv",
+ [
+ f"score{ext}.py", "--systems", "half", "--aggregate-only",
+ str(results)
+ ] + extra,
+ )
+ module.main()
+ derived = json.loads((view / f"half.{ext}.json").read_text())
+ assert derived["_outputs_sha256"] == rendered
diff --git a/tests/bench/scripts/test_speedtest.py b/tests/bench/scripts/test_speedtest.py
new file mode 100644
index 0000000..b93e708
--- /dev/null
+++ b/tests/bench/scripts/test_speedtest.py
@@ -0,0 +1,221 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Runtime check: a fake clock, clip picking and the README line.
+
+Failures are counted, not averaged.
+"""
+
+import json
+import math
+
+import pytest
+import soundfile as sf
+import torch
+
+import common
+import speedtest
+
+SR = common.SR
+
+
+class _Clock:
+ """A clock the fake systems advance by hand.
+
+ Timings are exact, and the tests take no time.
+ """
+
+ def __init__(self):
+ self.t = 0.0
+
+ def __call__(self):
+ return self.t
+
+
+def test_summarize_percentiles_and_empty():
+ s = speedtest.summarize([1.0, 2.0, 3.0, 4.0, 5.0])
+ assert (s["n"] == 5 and s["p50"] == 3.0 and
+ s["p95"] == pytest.approx(4.8) and s["max"] == 5.0)
+ assert s["mean"] == 3.0
+ e = speedtest.summarize([])
+ assert e["n"] == 0 and e["p50"] != e["p50"]
+
+
+def test_check_output_names_every_failure():
+ assert speedtest.check_output(torch.zeros(100), 100) is None
+ assert speedtest.check_output(torch.zeros(99), 100).startswith("length")
+ assert speedtest.check_output(torch.zeros(2, 50), 100).startswith("length")
+ y = torch.zeros(100)
+ y[3] = float("nan")
+ assert speedtest.check_output(y, 100) == "nan"
+ assert speedtest.check_output(object(), 100).startswith("not a signal")
+
+
+def test_cold_start_is_the_first_call_and_warm_passes_are_summarised_per_group(
+):
+ clock = _Clock()
+
+ # 10 ms of work per second of audio, plus 0.5 s the first time (kernel
+ # selection)
+ def run(x):
+ clock.t += 0.01 * len(x) / SR + (0.5 if not run.warm else 0.0)
+ run.warm = True
+ return x
+
+ run.warm = False
+ clips = [
+ ("1s", "a", torch.zeros(SR)),
+ ("1s", "b", torch.zeros(SR)),
+ ("2s", "c", torch.zeros(2 * SR)),
+ ]
+ r = speedtest.measure(run, clips, repeat=3, clock=clock)
+ assert r["cold"]["clip"] == "a" and r["cold"]["seconds"] == pytest.approx(
+ 0.51)
+ assert r["cold"]["failure"] is None
+ g1, g2 = r["groups"]["1s"], r["groups"]["2s"]
+ assert (g1["clips"] == ["a", "b"] and len(g1["times"]) == 6 and
+ g1["n_failed"] == 0)
+ assert g1["summary"]["p50"] == pytest.approx(
+ 0.01) and g1["realtime_p50"] == pytest.approx(100)
+ assert (g2["summary"]["p50"] == pytest.approx(0.02) and
+ g2["mean_clip_seconds"] == 2.0)
+
+
+def test_failures_are_counted_with_their_reason_and_never_averaged():
+ clock = _Clock()
+ calls = []
+
+ def run(x):
+ calls.append(len(x))
+ clock.t += 0.1
+ if len(x) == 2 * SR:
+ return torch.full((len(x),), float("nan"))
+ if len(calls) == 3:
+ raise RuntimeError("out of memory")
+ return x
+
+ clips = [("1s", "a", torch.zeros(SR)), ("2s", "b", torch.zeros(2 * SR))]
+ r = speedtest.measure(run, clips, repeat=2, clock=clock)
+ g1, g2 = r["groups"]["1s"], r["groups"]["2s"]
+ assert g1["n_failed"] == 1 and g1["failures"][0]["reason"].startswith(
+ "raised: out of memory")
+ assert len(g1["times"]) == 1 and g1["summary"]["p50"] == pytest.approx(0.1)
+ assert g2["n_failed"] == 2 and {f["reason"] for f in g2["failures"]
+ } == {"nan"}
+ assert g2["times"] == [] and math.isnan(g2["realtime_p50"])
+ with pytest.raises(ValueError):
+ speedtest.measure(run, [], repeat=1, clock=clock)
+
+
+def test_pick_clips_takes_the_nearest_lengths_per_duration():
+ rows = [
+ ({
+ "id": "a"
+ }, 1.0),
+ ({
+ "id": "b"
+ }, 2.2),
+ ({
+ "id": "c"
+ }, 5.1),
+ ({
+ "id": "d"
+ }, 9.0),
+ ]
+ one = speedtest.pick_clips(rows, [1.0, 5.0], 1)
+ assert [(g, r["id"]) for g, r, _ in one] == [("1s", "a"), ("5s", "c")]
+ two = speedtest.pick_clips(rows, [1.0, 5.0], 2)
+ assert [r["id"] for _, r, _ in two] == ["a", "b", "c", "d"]
+ assert two[0][0] == "1s" and two[-1][0] == "5s"
+
+
+def test_clip_seconds_reads_the_headers(tmp_path):
+ (tmp_path / "mix").mkdir()
+ sf.write(str(tmp_path / "mix" / "x.wav"), torch.zeros(SR // 2).numpy(), SR)
+ rows = [{"id": "x.wav", "mix_path": str(tmp_path / "mix" / "x.wav")}]
+ assert speedtest.clip_seconds(rows)[0][1] == pytest.approx(0.5)
+
+
+def test_readme_line_quotes_p50_realtime_and_memory():
+ report = {
+ "groups": {
+ "30s": {
+ "mean_clip_seconds": 30.0,
+ "summary": {
+ "p50": 7.2
+ },
+ "realtime_p50": 30 / 7.2,
+ },
+ "8s": {
+ "mean_clip_seconds": 8.0,
+ "summary": {
+ "p50": 1.5
+ },
+ "realtime_p50": 8 / 1.5,
+ },
+ "45s": {
+ "mean_clip_seconds": 45.0,
+ "summary": {
+ "p50": float("nan")
+ },
+ "realtime_p50": float("nan"),
+ },
+ }
+ }
+ line = speedtest.readme_line(report, "2.8 GB peak GPU memory")
+ assert (
+ line == "30 s clip in 7.2 s (4.2× realtime); 8 s clip in 1.5 s (5.3×"
+ " realtime); 45s clip: every pass failed; 2.8 GB peak GPU memory")
+
+
+def test_main_synthetic_with_the_tiny_model_writes_the_report(
+ identity_model, tmp_path, monkeypatch):
+ # pylint: disable-next=import-outside-toplevel
+ from inworld.voice_isolation import isolator
+
+ vi = isolator.VoiceIsolator(identity_model, device="cpu")
+ monkeypatch.setattr(
+ common,
+ "isolator_runner",
+ lambda a: (
+ vi,
+ lambda x, c=None, o=None: vi.isolate(
+ x, SR, chunk_seconds=c, overlap_seconds=o),
+ ),
+ )
+ out = tmp_path / "speed.json"
+ monkeypatch.setattr(
+ "sys.argv",
+ [
+ "speedtest.py",
+ "--model",
+ "tiny",
+ "--synthetic",
+ "0.5",
+ "--repeat",
+ "2",
+ "--out",
+ str(out),
+ ],
+ )
+ speedtest.main()
+ r = json.load(open(out, encoding="utf-8"))
+ assert r["synthetic"] and r["set_id"] is None and r["device_type"] == "cpu"
+ g = r["groups"]["0.5s"]
+ assert (g["summary"]["n"] == 2 and g["n_failed"] == 0 and
+ g["realtime_p50"] > 0)
+ assert r["cold"]["failure"] is None and "0 s clip in" in r["readme_line"]
+ # the model's own window
+ assert (r["chunk_seconds"],
+ r["overlap_seconds"]) == (identity_model.config.chunk_seconds,
+ identity_model.config.overlap_seconds)
diff --git a/tests/bench/scripts/test_stamprender.py b/tests/bench/scripts/test_stamprender.py
new file mode 100644
index 0000000..0d5fe73
--- /dev/null
+++ b/tests/bench/scripts/test_stamprender.py
@@ -0,0 +1,224 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""A render is stamped only when every check holds.
+
+The renderer succeeded, every receipt carries the identity being stamped for
+this system, renderer and set, and the inventory is exact and finite.
+"""
+
+# pylint: disable=redefined-outer-name
+
+import glob
+import json
+import sys
+
+import numpy as np
+import pytest
+import soundfile as sf
+
+import receipt
+import stamprender
+
+
+def render(tmp_path, monkeypatch):
+ """A complete three-item render with one receipt.
+
+ Returns its paths and digest.
+ """
+ root = tmp_path / "set"
+ inp, out, res = root / "mix", tmp_path / "out", tmp_path / "res"
+ inp.mkdir(parents=True)
+ out.mkdir()
+ (root / "checksums.json").write_text(json.dumps({"set_id": "tiny"}))
+ meta = tmp_path / "meta"
+ meta.mkdir()
+ json.dump({
+ "display": "Sys",
+ "mechanism": "masking"
+ }, open(meta / "sys.json", "w", encoding="utf-8"))
+ monkeypatch.setattr(receipt, "META_DIR", str(meta))
+ wrapper = tmp_path / "runsys.py"
+ wrapper.write_text("import argparse\n")
+ for i in range(3):
+ x = np.full(48000 + 100 * i, 0.1, dtype="float32")
+ sf.write(inp / f"item_{i}.wav", x, 48000, subtype="FLOAT")
+ sf.write(out / f"item_{i}.wav", x * 0.5, 48000, subtype="FLOAT")
+ digest = receipt.begin("sys", str(wrapper), str(out), ["runsys.py"],
+ str(inp), "cpu")
+ files = sorted(glob.glob(str(inp / "*.wav")))
+ return {
+ "inp": inp,
+ "out": out,
+ "res": res,
+ "wrapper": wrapper,
+ "digest": digest,
+ "files": files,
+ }
+
+
+def _stamp(r, **kw):
+ args = dict(
+ system="sys",
+ renderer=str(r["wrapper"]),
+ files=r["files"],
+ out_dir=str(r["out"]),
+ results=str(r["res"]),
+ set_id="tiny",
+ probe_digest=r["digest"],
+ desc={
+ "display": "Sys",
+ "mechanism": "masking"
+ },
+ )
+ args.update(kw)
+ return stamprender.stamp(**args)
+
+
+def test_a_complete_receipted_render_is_stamped_with_its_identity(render):
+ # a stray file is neither counted nor fatal
+ (render["out"] / "render.log").write_text("noise")
+ sf.write(
+ render["out"] / "item_0.wav",
+ np.zeros(48000, "float32"),
+ 48000,
+ subtype="FLOAT",
+ )
+ meta = _stamp(render, subset="core")
+ # silence is counted, not refused
+ assert meta["n_files"] == 3 and meta["n_silent"] == 1
+ assert meta["render_receipt_sha256"] == render["digest"]
+ receipts = receipt.read_all(str(render["out"]))
+ assert (
+ meta["render_environment_sha256"] == receipts[0]["environment_digest"])
+ assert (meta["display"] == "Sys" and meta["set_id"] == "tiny" and
+ meta["subset"] == "core")
+ assert meta["render_receipt"]["n_receipts"] == 1
+ assert json.load(open(render["res"] / "sys.meta.json",
+ encoding="utf-8")) == meta
+
+
+def test_the_stamp_names_the_exact_bytes_of_its_outputs(render):
+ first = _stamp(render)["outputs_sha256"]
+ assert len(first) == 64 and _stamp(render)["outputs_sha256"] == first
+ # one definition, for a stamp and for a render linked in
+ assert stamprender.outputs_digest(render["files"],
+ str(render["out"])) == first
+ # a stray file is not an output: the digest ignores it
+ (render["out"] / "render.log").write_text("noise")
+ assert _stamp(render)["outputs_sha256"] == first
+ x, _ = sf.read(render["out"] / "item_1.wav", dtype="float32")
+ x[100] += 1e-6 # one sample, one ulp-scale step
+ sf.write(render["out"] / "item_1.wav", x, 48000, subtype="FLOAT")
+ assert _stamp(render)["outputs_sha256"] != first
+
+
+ "change, message",
+ [
+ (dict(probe_digest="0" * 64), "another environment"),
+ (dict(system="other"), "rendered as"),
+ (dict(set_id="another-build"), "not set another-build"),
+ ],
+)
+def test_receipts_of_another_environment_system_or_set_refuse(
+ render, change, message):
+ with pytest.raises(SystemExit, match=message):
+ _stamp(render, **change)
+ path = render["res"] / f"{change.get('system', 'sys')}.meta.json"
+ assert not path.exists()
+
+
+def test_mixed_missing_or_foreign_receipts_refuse(render, tmp_path):
+ out = render["out"]
+ for p in out.glob(".receipt-*.json"):
+ p.rename(out / ".receipt-otherhost-1.json")
+ other = tmp_path / "runother.py"
+ other.write_text("import argparse\nX = 1\n")
+ receipt.begin("sys", str(other), str(out), ["runother.py"],
+ str(render["inp"]), "cpu")
+ with pytest.raises(SystemExit, match="identities"):
+ _stamp(render)
+ for p in out.glob(".receipt-*.json"):
+ p.unlink()
+ with pytest.raises(SystemExit, match="no render receipt"):
+ _stamp(render)
+ receipt.begin("sys", str(other), str(out), ["runother.py"],
+ str(render["inp"]), "cpu")
+ digest = receipt.read_all(str(out))[0]["digest"]
+ with pytest.raises(SystemExit, match="rendered by"):
+ _stamp(render, probe_digest=digest)
+
+
+def test_a_wrong_missing_or_non_finite_output_refuses(render):
+ out = render["out"]
+ x, _ = sf.read(out / "item_1.wav", dtype="float32")
+ sf.write(out / "item_1.wav", x[:-10], 48000, subtype="FLOAT")
+ with pytest.raises(SystemExit, match="frames"):
+ _stamp(render)
+ sf.write(out / "item_1.wav", x, 48000, subtype="PCM_16")
+ with pytest.raises(SystemExit, match="PCM_16"):
+ _stamp(render)
+ y = x.copy()
+ y[5] = np.inf
+ sf.write(out / "item_1.wav", y, 48000, subtype="FLOAT")
+ with pytest.raises(SystemExit, match="NaN or inf"):
+ _stamp(render)
+ sf.write(out / "item_1.wav", x, 48000, subtype="FLOAT")
+ (out / "item_2.wav").unlink()
+ with pytest.raises(SystemExit, match="1 outputs missing"):
+ _stamp(render)
+ # nothing was stamped along the way
+ assert not (render["res"] / "sys.meta.json").exists()
+
+
+def test_the_command_line_refuses_a_failed_renderer_and_stamps_a_good_one(
+ render, monkeypatch, capsys):
+ argv = [
+ "stamprender.py",
+ "sys",
+ "--wrapper",
+ str(render["wrapper"]),
+ "--inputs",
+ str(render["inp"]),
+ "--outputs",
+ str(render["out"]),
+ "--results",
+ str(render["res"]),
+ "--set-id",
+ "tiny",
+ "--probe-digest",
+ render["digest"],
+ ]
+ monkeypatch.setattr(sys, "argv", argv + ["--wrapper-exit", "1"])
+ with pytest.raises(SystemExit, match="exited 1"):
+ stamprender.main()
+ monkeypatch.setattr(sys, "argv", argv + ["--wrapper-exit", "0"])
+ stamprender.main()
+ assert "stamped sys: 3 files" in capsys.readouterr().out
+ with open(render["res"] / "sys.meta.json", encoding="utf-8") as fh:
+ meta = json.load(fh)
+ assert meta["mechanism"] == "masking"
+
+
+def test_a_linked_output_refuses_a_computed_renders_stamp(render):
+ """A render writes files; a folder linked in is stamped by runsystem.py
+ --outputs with its source named, never as a computed render."""
+ r = render
+ target = r["out"] / "item_1.wav"
+ target.unlink()
+ target.symlink_to(r["inp"] / "item_1.wav")
+
+ with pytest.raises(SystemExit, match="link"):
+ _stamp(r)
diff --git a/tests/bench/scripts/test_streamview.py b/tests/bench/scripts/test_streamview.py
new file mode 100644
index 0000000..5df9fde
--- /dev/null
+++ b/tests/bench/scripts/test_streamview.py
@@ -0,0 +1,240 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The streaming probe on the board: which sidecars are shown, and how."""
+
+import json
+
+import pytest
+
+import streamview
+
+
+def _stream_side(verdict, set_id="abc", **extra):
+ # pylint: disable-next=import-outside-toplevel
+ import scorestream
+
+ side = {
+ "_set_id": set_id,
+ "_subset": "all",
+ "_rule_version": scorestream.RULE_VERSION,
+ "_scorer_sha256": scorestream.SCORER_SHA256,
+ "verdict": verdict,
+ "causal": verdict == "yes",
+ "holds": verdict == "yes",
+ "look_ahead_ms": 20.0,
+ "look_ahead_max_ms": 30.0,
+ "drift_mean_db": -0.1,
+ "drift_min_db": -0.8,
+ "cold_start_db": -0.3,
+ "dropped_seconds": 0,
+ "speech_seconds": 600,
+ "dropout_items": 0,
+ "path_switch": False,
+ "context_diff_db": -25.0,
+ "n_items": 16,
+ "reasons": [] if verdict == "yes" else ["drifts over a long input"],
+ "rule": {
+ "version": "1"
+ },
+ "items": [{
+ "id": "longATp4_001.wav",
+ "output_sha256": "out-001"
+ }],
+ }
+ side.update(extra)
+ return side
+
+
+def test_stream_sidecars_load_per_system_else_whole_set_and_ignore_other_builds(
+ tmp_path, capsys):
+ whole, core = tmp_path, tmp_path / "core"
+ core.mkdir()
+ (whole / "a.stream.json").write_text(json.dumps(_stream_side("yes")))
+ (whole / "b.stream.json").write_text(
+ json.dumps(_stream_side("no", set_id="old")))
+ (core / "c.stream.json").write_text(json.dumps(_stream_side("no")))
+ scores = {
+ "a": {
+ "_set_id": "abc",
+ "_subset": "core"
+ },
+ "b": {
+ "_set_id": "abc",
+ "_subset": "core"
+ },
+ "c": {
+ "_set_id": "abc",
+ "_subset": "core"
+ },
+ "d": {
+ "_set_id": "abc",
+ "_subset": "core"
+ },
+ }
+ stream = streamview.load_streaming(str(core), scores)
+ # a: from the whole-set directory beside the view
+ assert set(stream) == {"a", "c"}
+ assert "b.stream.json probed on set old" in capsys.readouterr().err
+ assert (streamview.streaming_cell(stream, "a") == "yes" and
+ streamview.streaming_cell(stream, "c") == "no")
+ assert (streamview.streaming_cell(stream, "d") == "–" and
+ streamview.streaming_cell(None, "a") == "–")
+ # a whole-set view never looks beside itself
+ scores_all = {k: {"_set_id": "abc", "_subset": "all"} for k in ("a", "c")}
+ assert set(streamview.load_streaming(str(core), scores_all)) == {"c"}
+ summary = streamview.streaming_summary(stream["a"])
+ assert summary["verdict"] == "yes" and summary["look_ahead_max_ms"] == 30.0
+ assert summary["dropped_seconds"] == 0 and summary["cold_start_db"] == -0.3
+ assert "items" not in summary and "_set_id" not in summary
+ (whole / "e.stream.json").write_text(
+ json.dumps(_stream_side("yes", _sealed=True)))
+ with pytest.raises(ValueError, match="scope"):
+ streamview.load_streaming(str(whole),
+ {"e": {
+ "_set_id": "abc",
+ "_subset": "all"
+ }})
+
+
+def test_obsolete_streaming_verdicts_are_not_shown(tmp_path, capsys):
+ # pylint: disable-next=import-outside-toplevel
+ import observations
+
+ scores = {
+ k: {
+ "_set_id": "abc",
+ "_subset": "all"
+ } for k in ("rule", "impl", "render", "fresh")
+ }
+ (tmp_path / "rule.stream.json").write_text(
+ json.dumps(_stream_side("yes", _rule_version="0")))
+ (tmp_path / "impl.stream.json").write_text(
+ json.dumps(_stream_side("yes", _scorer_sha256="x")))
+ for name, output in (("render", "out-002"), ("fresh", "out-001")):
+ (tmp_path / f"{name}.stream.json").write_text(
+ json.dumps(_stream_side("yes")))
+ observations.write(
+ tmp_path / f"{name}.items.jsonl",
+ [{
+ "id": "longATp4_001.wav",
+ "identity": {
+ "output": output
+ }
+ }],
+ {
+ "system": name,
+ "set_id": "abc",
+ "n_expected": 1
+ },
+ )
+ stream = streamview.load_streaming(str(tmp_path), scores)
+ assert set(stream) == {"fresh"}
+ err = capsys.readouterr().err
+ assert "rule.stream.json follows probe rule '0'" in err
+ assert "impl.stream.json scored by another implementation" in err
+ assert (
+ "render.stream.json read other outputs than the base scores for 1 items"
+ in err)
+
+
+def test_a_streaming_verdict_compared_with_another_render_is_not_shown(
+ tmp_path, capsys):
+ scores = {
+ k: {
+ "_set_id": "abc",
+ "_subset": "all",
+ "_outputs_sha256": "now"
+ } for k in ("moved", "same")
+ }
+ for name, digest in (("moved", "before"), ("same", "now")):
+ (tmp_path / f"{name}.stream.json").write_text(
+ json.dumps(_stream_side("yes", _outputs_sha256=digest)))
+ assert set(streamview.load_streaming(str(tmp_path), scores)) == {"same"}
+ assert "compared with another render" in capsys.readouterr().err
+
+
+def test_streaming_table_lists_probed_systems_in_board_order_and_names_the_rest(
+):
+ stream = {
+ "x": _stream_side("yes"),
+ "z": _stream_side("no", look_ahead_max_ms=10000.0),
+ }
+ tiers = {"x": ("full", "X"), "y": ("full", "Y"), "z": ("nb", "Z")}
+ md = streamview.markdown_streaming(stream, {
+ "full": ["y", "x"],
+ "nb": ["z"]
+ }, tiers)
+ lines = md.splitlines()
+ assert (lines[0] ==
+ "| system | future input (ms) | drift over a long input (dB) | cold"
+ " start (dB) | speech dropped (s) | streaming probe |")
+ assert (lines[2] ==
+ "| X | 20 (max 30) | -0.1 (min -0.8) | -0.3 | 0 of 600 | yes |")
+ assert (lines[3] ==
+ "| Z | 20 (max 10000) | -0.1 (min -0.8) | -0.3 | 0 of 600 | no |")
+ assert lines[-1] == "Not probed: Y."
+ assert "Not probed" not in streamview.markdown_streaming(
+ stream, {"full": ["x"]}, tiers)
+ stream["z"].update(
+ look_ahead_capped=True,
+ path_switch=True,
+ dropped_seconds=7,
+ cold_start_db=float("nan"),
+ )
+ md = streamview.markdown_streaming(stream, {"nb": ["z"]}, tiers)
+ assert ("| Z | ≥20 (max ≥10000) | -0.1 (min -0.8) † | – | 7 of 600 | no |"
+ in md)
+ assert md.splitlines()[-1].startswith(
+ "† the release takes different inference paths")
+
+
+def _measured(drifts, look_ahead=40, dropped=0):
+ return [{
+ "id": f"longATp4_{i:03d}.wav",
+ "output_sha256": f"out-{i:03d}",
+ "look_ahead_ms": look_ahead,
+ "drift_db": d,
+ "dropped_seconds": dropped if i == 0 else 0,
+ "speech_seconds": 12,
+ } for i, d in enumerate(drifts)]
+
+
+def test_the_board_judges_the_recorded_items_with_its_own_floor():
+ # the scorer said no at its -3 dB floor; one item sits at -4.2 dB
+ side = _stream_side("no",
+ items=_measured([-0.2, -4.2, -0.1, -0.1, 0.0, 0.3]))
+ judged = streamview.judged(side)
+ assert judged["verdict"] == "yes" and judged["holds"] and judged["causal"]
+ assert not judged["reasons"]
+ assert judged["rule"]["board_drift_min_db"] == -5.0
+ assert side["verdict"] == "no" # the sidecar itself is not rewritten
+ # below the board's floor, no
+ low = streamview.judged(_stream_side("no", items=_measured([-0.2, -5.5])))
+ assert low["verdict"] == "no" and "limits -1 / -5" in low["reasons"][0]
+ # a mean under -1 dB, no
+ mean = streamview.judged(
+ _stream_side("no", items=_measured([-1.5, -1.6, -0.9])))
+ assert mean["verdict"] == "no" and not mean["holds"]
+ # too much look-ahead, no
+ late = streamview.judged(
+ _stream_side("yes", items=_measured([-0.1, -0.2], look_ahead=120)))
+ assert late["verdict"] == "no" and not late["causal"]
+ assert "120 ms of future input" in late["reasons"][0]
+ # dropped speech, no
+ drop = streamview.judged(
+ _stream_side("yes", items=_measured([-0.1, -0.2], dropped=3)))
+ assert drop["verdict"] == "no" and "drops speech" in drop["reasons"][0]
+ # no per-item measurements: the scorer's verdict stands
+ assert streamview.judged(_stream_side("yes"))["verdict"] == "yes"
+ assert "under 5 dB" in streamview.rule_sentence()
diff --git a/tests/bench/scripts/test_tables.py b/tests/bench/scripts/test_tables.py
new file mode 100644
index 0000000..7d83ab1
--- /dev/null
+++ b/tests/bench/scripts/test_tables.py
@@ -0,0 +1,226 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The board as markdown tables."""
+
+import ranking
+import tables
+
+
+def test_markdown_table_lists_full_tier_in_order_with_axes_and_headline_metrics(
+):
+ scores = {
+ "x": {
+ "babble@+4": {
+ "babble_supp_db": -12.04,
+ "babble_resid_db": -12.04,
+ "spk_sim": 0.9876,
+ "nisqa_mos": 4.0,
+ },
+ "nonverbal@+0": {
+ "nv_lost_pct": 4.63
+ },
+ "_real_cleanup": {
+ "pause_level_db": -15.24
+ },
+ "srsweep_8k": {
+ "band_kept_db": [0, 0, 0, -24.0, -47.0, -47.0, -47.0]
+ },
+ "_deletion": {
+ "pct": 0.2
+ },
+ },
+ "y": {
+ "babble@+4": {
+ "babble_supp_db": -10.1,
+ "babble_resid_db": -10.1,
+ "spk_sim": 0.98,
+ "nisqa_mos": 4.5,
+ },
+ "_real_cleanup": {
+ "pause_level_db": -8.0
+ },
+ "srsweep_8k": {
+ "band_kept_db": [0, 0, 0, -24.0, -47.0, -47.0, -47.0]
+ },
+ "_deletion": {
+ "pct": 0.44
+ },
+ },
+ }
+ axis_scores = {
+ "x": {
+ a: 1.0 for a in ranking.AXES_FULL
+ },
+ "y": {
+ a: 0.5 for a in ranking.AXES_FULL
+ }
+ }
+ md = tables.markdown_table(
+ scores,
+ axis_scores,
+ {
+ "x": 0.7777,
+ "y": 0.5
+ },
+ {"full": ["x", "y"]},
+ {
+ "x": ("full", "X label"),
+ "y": ("full", "Y label")
+ },
+ )
+ lines = md.splitlines()
+ assert (lines[0].startswith(
+ "| # | system | precision | denoising | removes | keeps | sounds |"
+ " supp | music | cleanup | events | voices | pres | fidel | timbre |"
+ " qual | band |") and len(lines) == 4)
+ assert lines[0].endswith(
+ "| supp dB | pauses dB | del % | laughs lost % | NISQA |")
+ assert lines[2].startswith(
+ "| 1 | X label | – | **1.000** | 1.00 | 1.00 | 1.00 | 1.00 | 1.00 |")
+ assert lines[2].endswith("| -12.0 | -15.2 | 0.2 | 4.6 | 4.00 |")
+ assert lines[3].startswith("| 2 | Y label | – | **0.500** | 0.50 |")
+ assert len({len(line.split("|")) for line in lines}) == 1
+ stream = {"x": {"verdict": "yes"}, "y": {"verdict": "nonsense"}}
+ md = tables.markdown_table(
+ scores,
+ axis_scores,
+ {
+ "x": 0.7777,
+ "y": 0.5
+ },
+ {"full": ["x", "y"]},
+ {
+ "x": ("full", "X label"),
+ "y": ("full", "Y label")
+ },
+ stream,
+ )
+ # the mark after a name: the streaming probe says yes, with the note
+ assert "| 1 | X label\\* | – | **1.000** |" in md
+ assert "| 2 | Y label | – | **0.500** |" in md
+ assert md.endswith(tables.STREAMING_NOTE)
+
+
+def test_the_16k_tier_gets_its_own_table_only_when_it_has_an_entrant():
+ scores = {
+ "z": {
+ "babble@+4": {
+ "babble_supp_db_nb": -9.04,
+ "babble_resid_db_nb": -9.04,
+ "spk_sim_nb": 0.9512,
+ "nisqa_mos": 3.9,
+ },
+ "_real_cleanup": {
+ "pause_level_db": -7.5
+ },
+ "srsweep_8k": {
+ "band_kept_db": [0, 0, 0, -24.0, -47.0, -47.0, -47.0]
+ },
+ "_deletion": {
+ "pct": 1.2
+ },
+ }
+ }
+ axis_scores = {"z": {a: 0.4 for a in ranking.AXES_NB}}
+ tiers = {"z": ("nb", "Z label (16k)")}
+ assert (tables.markdown_table_nb(scores, axis_scores, {"z": 0.4}, {
+ "full": [],
+ "nb": []
+ }, tiers) == "")
+ md = tables.markdown_table_nb(scores, axis_scores, {"z": 0.4}, {
+ "full": [],
+ "nb": ["z"]
+ }, tiers)
+ lines = md.splitlines()
+ assert lines[0].startswith(
+ "| # | system | precision | denoising | removes | keeps | sounds |")
+ assert "supp dB (0–8 kHz)" in lines[0]
+ assert lines[2].startswith("| 1 | Z label (16k) | – | **0.400** | 0.40 |")
+ assert lines[2].endswith("| -9.0 | -7.5 | 1.2 | – | 3.90 |")
+ assert len(lines[0].split("|")) == len(lines[2].split("|"))
+
+
+def test_outside_tables_can_add_an_axis_in_its_own_order(monkeypatch):
+ monkeypatch.setattr(ranking, "OUTSIDE", [])
+ axis_scores = {
+ "x": {
+ "room": 0.2,
+ "music": 0.9
+ },
+ "y": {
+ "room": 0.8,
+ "music": 0.1
+ }
+ }
+ tiers = {"x": ("full", "X"), "y": ("full", "Y")}
+ assert tables.markdown_outside(axis_scores, {"full": ["x", "y"]},
+ tiers) == ""
+ md = tables.markdown_outside(axis_scores, {"full": ["x", "y"]}, tiers,
+ ["room"])
+ assert md.splitlines()[0] == "| # | system | room |"
+ assert (md.splitlines()[2] == "| 1 | Y | 0.80 |" and
+ md.splitlines()[3] == "| 2 | X | 0.20 |")
+
+
+def test_each_board_lists_its_own_systems_and_the_mark_means_streaming():
+ scores = {
+ "z": {
+ "babble@+4": {
+ "babble_resid_db": -9.0,
+ "nisqa_mos": 3.9
+ },
+ "_real_cleanup": {
+ "pause_level_db": -7.5
+ },
+ "_deletion": {
+ "pct": 1.2
+ },
+ }
+ }
+ # a system that restores above the input's band
+ scores["r"] = dict(scores["z"],
+ srsweep_8k={"band_kept_db": [0, 0, 0, 40, 30, 20, 10]})
+ axis_scores = {
+ "z": {
+ a: 0.4 for a in ranking.AXES_FULL
+ },
+ "r": {
+ a: 0.6 for a in ranking.AXES_FULL
+ },
+ }
+ tiers = {"z": ("full", "Z"), "r": ("full", "R")}
+ order = {"full": ["z"], "nb": [], "restoration": ["r"]}
+ md = tables.markdown_table(scores, axis_scores, {
+ "z": 0.4,
+ "r": 0.6
+ }, order, tiers)
+ # no mark without the probe, no note
+ assert "| 1 | Z |" in md and "| R |" not in md
+ assert not md.endswith(tables.STREAMING_NOTE)
+ md = tables.markdown_table(scores, axis_scores, {
+ "z": 0.4,
+ "r": 0.6
+ }, order, tiers, {"z": {
+ "verdict": "yes"
+ }})
+ assert "| 1 | Z\\* |" in md and md.endswith(tables.STREAMING_NOTE)
+ both = tables.markdown_boards(scores, axis_scores, {
+ "z": 0.4,
+ "r": 0.6
+ }, order, tiers)
+ denoising, restoration = both.split("**Restoration**")
+ assert denoising.startswith("**Denoising**") and "| 1 | Z |" in denoising
+ assert "| R |" not in denoising and "| 1 | R |" in restoration
+ assert "more than 10 dB on the band-limited rows" in restoration
+ assert "| precision | restoration | restores | room | band |" in restoration
diff --git a/tests/bench/scripts/test_transitiontest.py b/tests/bench/scripts/test_transitiontest.py
new file mode 100644
index 0000000..4d6fea1
--- /dev/null
+++ b/tests/bench/scripts/test_transitiontest.py
@@ -0,0 +1,286 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Transition check: stimulus geometry, recovery counting, and fakes.
+
+Each fake has a known dip and recovery.
+"""
+
+# pylint: disable=redefined-outer-name,unused-argument
+
+import json
+import math
+
+import pytest
+import soundfile as sf
+import torch
+
+import common
+import transitiontest
+
+SR = common.SR
+FRAME = transitiontest.FRAME
+
+
+def speech(seconds, seed=0, level=0.2, quiet_ends=0.5):
+ """Speech-like noise with silent ends.
+
+ The silent ends keep the speech centre well inside the clip.
+ """
+ n = int(seconds * SR)
+ g = torch.Generator().manual_seed(seed)
+ t = torch.arange(n) / SR
+ env = 0.3 + 0.7 * (0.5 + 0.5 * torch.sin(2 * math.pi * 2.0 * t)).pow(2)
+ x = torch.randn(n, generator=g) * env * level
+ q = int(quiet_ends * SR)
+ x[:q] = 0
+ x[-q:] = 0
+ return x
+
+
+def bed_for(ref, snr_db, seed=99):
+ g = torch.Generator().manual_seed(seed)
+ b = torch.randn(len(ref), generator=g)
+ active = ref[ref != 0]
+ return (b * float(active.pow(2).mean().sqrt()) /
+ float(b.pow(2).mean().sqrt()) * 10**(-snr_db / 20))
+
+
+def test_speech_centre_is_the_middle_of_the_loud_span():
+ ref = speech(6.0) # speech in blocks 5..54: the centre is block 29
+ assert transitiontest.speech_center_block(ref) == 29
+ # nothing loud: the clip's middle
+ assert transitiontest.speech_center_block(torch.zeros(3 * SR)) == 15
+
+
+def test_build_stimulus_gates_the_bed_at_the_block_boundary():
+ ref = speech(6.0)
+ bed = bed_for(ref, 0.0)
+ t, ramp = 30, 960
+ on = transitiontest.build_stimulus(ref, bed, t, "onset", ramp=ramp)
+ off = transitiontest.build_stimulus(ref, bed, t, "offset", ramp=ramp)
+ edge = t * FRAME
+ # nothing before the ramp
+ assert torch.equal(on[:edge - ramp], ref[:edge - ramp])
+ # the new state from the boundary on
+ assert torch.allclose(on[edge:], (ref + bed)[edge:])
+ assert torch.allclose(off[:edge - ramp], (ref + bed)[:edge - ramp])
+ assert torch.equal(off[edge:], ref[edge:])
+ # the two gates are complementary
+ assert torch.allclose(on + off, 2 * ref + bed)
+ with pytest.raises(ValueError):
+ transitiontest.build_stimulus(ref, bed, t, "sideways")
+
+
+def test_recovery_counts_blocks_until_the_level_holds():
+ kept = torch.tensor([0.0] * 10 + [-10.0] * 5 + [0.0] * 20)
+ loud = torch.ones(len(kept), dtype=torch.bool)
+ assert transitiontest.recovery_blocks(kept, loud, 10, 0.0, 3.0) == 5
+ # inside the tolerance from the start
+ assert transitiontest.recovery_blocks(kept, loud, 10, 0.0, 12.0) == 0
+ never = torch.tensor([0.0] * 10 + [-10.0] * 25)
+ assert math.isnan(transitiontest.recovery_blocks(never, loud, 10, 0.0, 3.0))
+ flicker = torch.tensor([0.0] * 10 + [-10.0, 0.0, -10.0, 0.0, 0.0, 0.0] +
+ [0.0] * 10)
+ loud_cut = loud[:len(flicker)]
+ # one good block does not count
+ assert transitiontest.recovery_blocks(flicker, loud_cut, 10, 0.0, 3.0) == 3
+ quiet = loud.clone()
+ quiet[12:15] = False # quiet blocks neither help nor hurt
+ assert transitiontest.recovery_blocks(kept, quiet, 10, 0.0, 3.0) == 5
+
+
+def test_oracle_and_identity_read_zero_everywhere():
+ ref = speech(8.0, seed=1)
+ bed = bed_for(ref, 0.0)
+ mix = ref + bed
+ # the oracle, and the unprocessed input
+ for run in (lambda s: ref, lambda s: s):
+ r = transitiontest.measure_item(run, mix, ref)
+ for kind in ("onset", "offset"):
+ k = r[kind]
+ # the ramp block only
+ assert abs(k["dip_db"]) < 0.3 and abs(k["pre_db"]) < 0.3
+ assert k["recovery_ms"] == 0.0 and abs(k["leak_db"]) < 0.5
+ assert abs(k["steady_delta_db"]) < 0.01
+ ident = transitiontest.measure_item(lambda s: s, mix, ref)
+ # the bed itself
+ assert ident["onset"]["resid_new_state_db"] == pytest.approx(0.0, abs=2.5)
+ assert ident["offset"]["resid_new_state_db"] < -70 # nothing but the voice
+ assert abs(ident["onset"]["kept_new_state_db"]) < 0.5
+
+
+def _bed_changes_at(stim, ref, t, frame=FRAME):
+ """A fake's ear.
+
+ Does the bed under the reference differ before and after block ``t``?
+ """
+ d = stim - ref
+ e0 = float(d[max(0, (t - 10) * frame):t * frame].pow(2).mean())
+ e1 = float(d[t * frame:(t + 10) * frame].pow(2).mean())
+ return abs(10 * math.log10((e1 + 1e-12) / (e0 + 1e-12))) > 20
+
+
+def test_a_slow_adapter_shows_its_dip_and_recovery_time():
+ ref = speech(8.0, seed=2)
+ bed = bed_for(ref, 0.0)
+ mix = ref + bed
+ t = transitiontest.speech_center_block(ref)
+ # -10.5 dB for the 500 ms after a change, then the voice again
+ gain, hold_blocks = 0.3, 5
+
+ def adapter(stim):
+ y = ref.clone()
+ if _bed_changes_at(stim, ref, t):
+ y[t * FRAME:(t + hold_blocks) * FRAME] *= gain
+ return y
+
+ r = transitiontest.measure_item(adapter, mix, ref, t_block=t)
+ for kind in ("onset", "offset"):
+ assert r[kind]["dip_db"] == pytest.approx(20 * math.log10(gain),
+ abs=0.1)
+ assert r[kind]["recovery_ms"] == pytest.approx(hold_blocks * 100)
+ assert (abs(r[kind]["pre_db"]) < 0.01 and
+ abs(r[kind]["steady_delta_db"]) < 0.01)
+
+
+def test_a_reaction_that_never_settles_is_a_steady_delta_without_recovery():
+ ref = speech(8.0, seed=3)
+ mix = ref + bed_for(ref, 0.0)
+ t = transitiontest.speech_center_block(ref)
+
+ def halves_after_a_change(stim):
+ y = ref.clone()
+ if _bed_changes_at(stim, ref, t):
+ y[t * FRAME:] *= 0.5
+ return y
+
+ def onset(run):
+ return transitiontest.measure_item(run, mix, ref, t_block=t)["onset"]
+
+ r = onset(halves_after_a_change)
+ assert r["dip_db"] == pytest.approx(-6.02, abs=0.05)
+ assert r["steady_delta_db"] == pytest.approx(-6.02, abs=0.05)
+ assert math.isnan(r["recovery_ms"])
+ # the same halving
+ steady = onset(lambda s: ref * 0.5)
+ # on every input
+ assert (abs(steady["dip_db"]) < 0.01 and
+ abs(steady["steady_delta_db"]) < 0.01)
+
+
+def test_a_model_that_reacts_before_the_change_shows_a_pre_echo():
+ ref = speech(8.0, seed=4)
+ mix = ref + bed_for(ref, 0.0)
+ t = transitiontest.speech_center_block(ref)
+
+ def anticipates(stim):
+ y = ref.clone()
+ if _bed_changes_at(stim, ref, t):
+ y[(t - 3) * FRAME:t * FRAME] *= 0.1 # 300 ms of look-ahead damage
+ return y
+
+ r = transitiontest.measure_item(anticipates, mix, ref, t_block=t)["offset"]
+ assert r["pre_db"] == pytest.approx(-20.0, abs=0.1)
+ assert abs(r["dip_db"]) < 0.01 and r["recovery_ms"] == 0.0
+
+
+def test_aggregate_reports_means_worst_and_never_recovered():
+ a = {
+ "onset": {
+ k: 0.0 for k in transitiontest.RESPONSE_KEYS
+ },
+ "offset": {
+ k: 0.0 for k in transitiontest.RESPONSE_KEYS
+ },
+ }
+ assert "dip_control_db" not in transitiontest.RESPONSE_KEYS
+ b = {
+ "onset":
+ dict({k: -2.0 for k in transitiontest.RESPONSE_KEYS},
+ recovery_ms=float("nan")),
+ "offset":
+ dict({k: -4.0 for k in transitiontest.RESPONSE_KEYS},
+ recovery_ms=800.0),
+ }
+ s = transitiontest.aggregate([a, b])
+ assert s["n_items"] == 2
+ assert s["onset"]["dip_db"] == -1.0 and s["onset"]["dip_worst_db"] == -2.0
+ assert (s["onset"]["n_never_recovered"] == 1 and
+ s["onset"]["recovery_ms"] == 0.0)
+ assert (s["offset"]["recovery_max_ms"] == 800.0 and
+ s["offset"]["n_never_recovered"] == 0)
+
+
+def paired_set(tmp_path, monkeypatch):
+ root = tmp_path / "set"
+ (root / "mix").mkdir(parents=True)
+ (root / "ref").mkdir()
+ rows = []
+ for i in range(2):
+ ref = speech(5.0, seed=30 + i)
+ mix = ref + bed_for(ref, 5.0, seed=40 + i)
+ rid = f"ambienceATp0_{i:03d}.wav"
+ sf.write(str(root / "mix" / rid), mix.numpy(), SR, subtype="FLOAT")
+ sf.write(str(root / "ref" / rid), ref.numpy(), SR, subtype="FLOAT")
+ rows.append({
+ "id": rid,
+ "condition": "ambience@+0",
+ "mix_path": f"mix/{rid}",
+ "clean_path": f"ref/{rid}",
+ })
+ with open(root / "manifest.jsonl", "w", encoding="utf-8") as fh:
+ fh.write("".join(json.dumps(r) + "\n" for r in rows))
+ json.dump({
+ "set_id": "tiny",
+ "n_items": 2
+ }, open(root / "checksums.json", "w", encoding="utf-8"))
+ monkeypatch.setattr(common, "EVAL", str(root))
+ return root
+
+
+def test_main_runs_both_stimuli_through_the_tiny_model(identity_model,
+ paired_set, tmp_path,
+ monkeypatch):
+ # pylint: disable-next=import-outside-toplevel
+ from inworld.voice_isolation import isolator
+
+ vi = isolator.VoiceIsolator(identity_model, device="cpu")
+ monkeypatch.setattr(
+ common,
+ "isolator_runner",
+ lambda a: (vi, lambda x, c=None, o=None: vi.isolate(x, SR)),
+ )
+ out = tmp_path / "transitions.json"
+ monkeypatch.setattr(
+ "sys.argv",
+ [
+ "transitiontest.py",
+ "--model",
+ "tiny",
+ "--conds",
+ "ambience@+0",
+ "--out",
+ str(out),
+ ],
+ )
+ transitiontest.main()
+ r = json.load(open(out, encoding="utf-8"))
+ assert r["set_id"] == "tiny" and r["ramp_ms"] == 20.0
+ s = r["conditions"]["ambience@+0"]["summary"]
+ assert s["n_items"] == 2
+ # identity
+ assert (abs(s["onset"]["dip_db"]) < 0.5 and
+ s["onset"]["n_never_recovered"] == 0)
+ assert r["conditions"]["ambience@+0"]["items"][0]["onset"]["t_s"] > 0
diff --git a/tests/bench/scripts/test_twicetest.py b/tests/bench/scripts/test_twicetest.py
new file mode 100644
index 0000000..32d7893
--- /dev/null
+++ b/tests/bench/scripts/test_twicetest.py
@@ -0,0 +1,210 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Double-processing check: second-pass cost, idempotence and determinism.
+
+The fakes have a known second-pass cost.
+"""
+
+# pylint: disable=redefined-outer-name,unused-argument
+
+import json
+import math
+
+import pytest
+import soundfile as sf
+import torch
+
+import common
+import twicetest
+
+SR = common.SR
+HALF_DB = 20 * math.log10(0.5)
+
+
+def speech(seconds, seed=0, level=0.2):
+ n = int(seconds * SR)
+ g = torch.Generator().manual_seed(seed)
+ t = torch.arange(n) / SR
+ env = 0.2 + 0.8 * (0.5 + 0.5 * torch.sin(2 * math.pi * 2.0 * t)).pow(2)
+ return torch.randn(n, generator=g) * env * level
+
+
+class _Spk:
+
+ def sim(self, a, b, key_b=None):
+ n = min(len(a), len(b))
+ return float(torch.nn.functional.cosine_similarity(a[:n], b[:n], dim=0))
+
+
+def test_diff_db_floor_and_level():
+ x = speech(1.0)
+ assert twicetest.diff_db(x, x) == twicetest.DIFF_FLOOR_DB
+ assert twicetest.diff_db(0.5 * x, x) == pytest.approx(HALF_DB, abs=0.01)
+
+
+def test_identity_costs_nothing_and_is_idempotent_and_deterministic():
+ x = speech(3.0)
+ d = twicetest.measure_item(lambda a: a, x, x, spk=_Spk())
+ assert (abs(d["pass1_kept_coh_mean_db"]) < 0.01 and
+ abs(d["second_pass_kept_delta_db"]) < 0.01)
+ assert (d["idempotence_db"] == twicetest.DIFF_FLOOR_DB and
+ d["determinism_db"] == twicetest.DIFF_FLOOR_DB)
+ assert (d["pass1_spk_sim"] == pytest.approx(1.0, abs=1e-4) and
+ d["second_pass_spk_delta"] == 0.0)
+
+
+def test_an_attenuator_loses_the_same_again_on_the_second_pass():
+ x = speech(3.0, seed=1)
+ d = twicetest.measure_item(lambda a: 0.5 * a, x, x)
+ assert d["pass1_kept_coh_mean_db"] == pytest.approx(HALF_DB, abs=0.02)
+ assert d["pass2_kept_coh_mean_db"] == pytest.approx(2 * HALF_DB, abs=0.02)
+ assert d["second_pass_kept_delta_db"] == pytest.approx(HALF_DB, abs=0.02)
+ # |0.25x - 0.5x| / |0.5x|
+ assert d["idempotence_db"] == pytest.approx(HALF_DB, abs=0.02)
+ assert d["determinism_db"] == twicetest.DIFF_FLOOR_DB
+
+
+def test_a_soft_gate_that_erodes_quiet_blocks_costs_more_the_second_time():
+ x = speech(4.0, seed=2)
+ frame = 4800
+ blocks = x[:len(x) // frame * frame].reshape(-1, frame)
+ thr = 0.5 * float(blocks.pow(2).mean(1).median())
+
+ # blocks under a fixed threshold are turned down in proportion: each pass
+ # finds them quieter than the last and turns them down further
+ def gate(a):
+ y = a.clone()
+ e = a[:len(a) // frame * frame].reshape(-1, frame).pow(2).mean(1)
+ for b, g in enumerate((e / thr).clamp(max=1.0).tolist()):
+ y[b * frame:(b + 1) * frame] *= g
+ return y
+
+ d = twicetest.measure_item(gate, x, x)
+ # the quiet blocks lost something after one pass
+ assert d["pass1_kept_coh_p10_db"] < -3
+ assert d["second_pass_p10_delta_db"] < -3 # and more after two
+ assert d["second_pass_kept_delta_db"] < -0.5
+ assert d["idempotence_db"] > -30 # the second pass rewrote something
+
+
+def test_a_nondeterministic_system_reads_its_own_noise_level():
+
+ # the global generator advances: every call draws different noise
+ def noisy(a):
+ return a + torch.randn(len(a)) * float(
+ a.pow(2).mean().sqrt()) * 10**(-20 / 20)
+
+ x = speech(3.0, seed=3)
+ d = twicetest.measure_item(noisy, x, x)
+ # two draws: +3 dB
+ assert d["determinism_db"] == pytest.approx(-20 + 3, abs=1.5)
+ assert d["determinism_db"] > -40
+
+
+def test_failures_are_named_by_pass_and_counted():
+ x = speech(1.0)
+ calls = []
+
+ def flaky(a):
+ calls.append(1)
+ if len(calls) == 2:
+ raise RuntimeError("boom")
+ return a
+
+ d = twicetest.measure_item(flaky, x, x)
+ assert d == {"failure": "pass 2 raised: boom"}
+ short = twicetest.measure_item(lambda a: a[:-1], x, x)
+ assert short["failure"].startswith("pass 1 length")
+ nan = torch.full((len(x),), float("nan"))
+ nonfinite = twicetest.measure_item(lambda a: nan, x, x)
+ assert nonfinite["failure"] == "pass 1 nan"
+ passed = {"idempotence_db": -50.0, "determinism_db": -90.0}
+ s = twicetest.aggregate([d, passed])
+ assert (s["n_items"] == 2 and s["n_failed"] == 1 and
+ s["failures"] == ["pass 2 raised: boom"])
+ assert s["idempotence_db"] == -50.0 and s["determinism_max_db"] == -90.0
+
+
+def paired_set(tmp_path, monkeypatch):
+ root = tmp_path / "set"
+ (root / "mix").mkdir(parents=True)
+ (root / "ref").mkdir()
+ rows = []
+ for cond, count in (("babble@+4", 2), ("real_x", 1)):
+ for i in range(count):
+ x = speech(2.0, seed=20 + i)
+ rid = f"{cond.replace('@', 'AT')}_{i:03d}.wav"
+ sf.write(str(root / "mix" / rid), x.numpy(), SR, subtype="FLOAT")
+ row = {
+ "id": rid,
+ "condition": cond,
+ "mix_path": f"mix/{rid}",
+ "clean_path": None,
+ }
+ if cond != "real_x":
+ sf.write(str(root / "ref" / rid),
+ x.numpy(),
+ SR,
+ subtype="FLOAT")
+ row["clean_path"] = f"ref/{rid}"
+ rows.append(row)
+ with open(root / "manifest.jsonl", "w", encoding="utf-8") as fh:
+ fh.write("".join(json.dumps(r) + "\n" for r in rows))
+ json.dump(
+ {
+ "set_id": "tiny",
+ "n_items": len(rows)
+ },
+ open(root / "checksums.json", "w", encoding="utf-8"),
+ )
+ monkeypatch.setattr(common, "EVAL", str(root))
+ return root
+
+
+def test_main_scores_paired_items_only_with_the_tiny_model(
+ identity_model, paired_set, tmp_path, monkeypatch):
+ # pylint: disable-next=import-outside-toplevel
+ from inworld.voice_isolation import isolator
+
+ vi = isolator.VoiceIsolator(identity_model, device="cpu")
+ monkeypatch.setattr(
+ common,
+ "isolator_runner",
+ lambda a: (vi, lambda x, c=None, o=None: vi.isolate(x, SR)),
+ )
+ out = tmp_path / "twice.json"
+ monkeypatch.setattr(
+ "sys.argv",
+ [
+ "twicetest.py",
+ "--model",
+ "tiny",
+ "--conds",
+ "babble@+4,real_x",
+ "--no-speaker",
+ "--out",
+ str(out),
+ ],
+ )
+ twicetest.main()
+ r = json.load(open(out, encoding="utf-8"))
+ assert r["set_id"] == "tiny" and r["model"] == "tiny"
+ assert r["conditions"]["babble@+4"]["summary"]["n_items"] == 2
+ # no reference: nothing to read
+ assert r["conditions"]["real_x"]["summary"]["n_items"] == 0
+ s = r["conditions"]["babble@+4"]["summary"]
+ # identity model
+ assert s["n_failed"] == 0 and abs(s["second_pass_kept_delta_db"]) < 0.5
+ assert "pass1_spk_sim" not in s
diff --git a/tests/bench/scripts/test_validateset.py b/tests/bench/scripts/test_validateset.py
new file mode 100644
index 0000000..c1efdd0
--- /dev/null
+++ b/tests/bench/scripts/test_validateset.py
@@ -0,0 +1,469 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The set validator on a tiny hand-made set.
+
+A sound set passes; tampering is caught.
+"""
+
+import hashlib
+import json
+import os
+import shutil
+
+import numpy as np
+import pytest
+import soundfile as sf
+
+import scoreevents
+import validateset
+
+# pylint: disable=protected-access
+
+SR = 48000
+
+
+def _sha256(path):
+ return hashlib.sha256(open(path, "rb").read()).hexdigest()
+
+
+def _make_set(root, n_per_cond=3, wild=0, wild_policy="retention"):
+ """Builds a small set of two additive conditions over two languages.
+
+ White-noise 'speech' at -26 dBFS, plus one reference-free real item; a
+ public-style manifest without provenance fields. ``wild`` adds that many
+ in-the-wild items: a band-limited reference with a floor of its own under a
+ bed.
+ """
+ os.makedirs(os.path.join(root, "mix"))
+ os.makedirs(os.path.join(root, "ref"))
+ rng = np.random.default_rng(0)
+ rows, files = [], {}
+ for i in range(wild):
+ speech = rng.standard_normal(6 * SR).astype(np.float32)
+ spec = np.fft.rfft(speech)
+ # a phone microphone: nothing above 6 kHz
+ spec[int(6000 * len(speech) / SR):] = 0
+ speech = np.fft.irfft(spec, n=len(speech)).astype(np.float32)
+ # its own noise floor, about 14 dB under the speech
+ floor = np.sqrt((speech**2).mean())
+ noise = rng.standard_normal(6 * SR).astype(np.float32)
+ speech = speech + 0.2 * noise * floor
+ speech *= 10**(-26 / 20) / np.sqrt((speech**2).mean())
+ bed = rng.standard_normal(6 * SR).astype(np.float32)
+ bed *= (np.sqrt((speech**2).mean()) / np.sqrt(
+ (bed**2).mean()) / 10**(-5 / 20))
+ base = f"wildAT-5_{i:03d}.wav"
+ sf.write(os.path.join(root, "mix", base),
+ speech + bed,
+ SR,
+ subtype="FLOAT")
+ sf.write(os.path.join(root, "ref", base), speech, SR, subtype="FLOAT")
+ row = dict(
+ id=base,
+ condition="wild@-5",
+ family="wild",
+ language=("en", "de")[i % 2],
+ speaker=f"wild{i}",
+ mix_path=f"mix/{base}",
+ clean_path=f"ref/{base}",
+ snr=-5.0,
+ score_from=0,
+ effective_bandwidth_hz=6000,
+ )
+ if wild_policy:
+ row["score_policy"] = wild_policy
+ rows.append(row)
+ for cond, snr in (("babble@+4", 4.0), ("ambience@-5", -5.0)):
+ for i in range(n_per_cond):
+ speech = rng.standard_normal(6 * SR).astype(np.float32)
+ speech *= 10**(-26 / 20) / np.sqrt((speech**2).mean())
+ noise = rng.standard_normal(6 * SR).astype(np.float32)
+ noise *= (np.sqrt((speech**2).mean()) / np.sqrt(
+ (noise**2).mean()) / 10**(snr / 20))
+ base = f"{cond}_{i:03d}.wav".replace("@", "AT").replace("+", "p")
+ sf.write(
+ os.path.join(root, "mix", base),
+ speech + noise,
+ SR,
+ subtype="FLOAT",
+ )
+ sf.write(os.path.join(root, "ref", base),
+ speech,
+ SR,
+ subtype="FLOAT")
+ rows.append(
+ dict(
+ id=base,
+ condition=cond,
+ family=cond.split("@", maxsplit=1)[0],
+ language=("en", "de")[i % 2],
+ speaker=f"spk{i}",
+ mix_path=f"mix/{base}",
+ clean_path=f"ref/{base}",
+ snr=snr,
+ score_from=0,
+ effective_bandwidth_hz=22000,
+ ))
+ real = "real_field_000.wav"
+ sf.write(
+ os.path.join(root, "mix", real),
+ (rng.standard_normal(6 * SR) * 0.05).astype(np.float32),
+ SR,
+ subtype="FLOAT",
+ )
+ rows.append(
+ dict(
+ id=real,
+ condition="real_field",
+ family="real",
+ language="und",
+ speaker=None,
+ mix_path=f"mix/{real}",
+ clean_path=None,
+ snr=None,
+ score_from=0,
+ effective_bandwidth_hz=None,
+ ))
+ with open(os.path.join(root, "manifest.jsonl"), "w",
+ encoding="utf-8") as fh:
+ for r in rows:
+ fh.write(json.dumps(r) + "\n")
+ for r in rows:
+ for k in ("mix_path", "clean_path"):
+ if r.get(k):
+ files[r[k]] = _sha256(os.path.join(root, r[k]))
+ listing = "".join(f"{k}:{v}\n" for k, v in sorted(files.items()))
+ manifest_sha = hashlib.sha256()
+ for r in sorted(rows, key=lambda r: r["id"]):
+ public = {k: r.get(k) for k in validateset.PUBLIC_FIELDS}
+ manifest_sha.update(json.dumps(public, sort_keys=True).encode())
+ manifest_sha.update(b"\n")
+ manifest_sha = manifest_sha.hexdigest()
+ id_text = listing + f"manifest:{manifest_sha}\n"
+ set_id = hashlib.sha256(id_text.encode()).hexdigest()
+ json.dump(
+ {
+ "set_id": set_id,
+ "n_items": len(rows),
+ "manifest_sha256": manifest_sha,
+ "files": files,
+ },
+ open(os.path.join(root, "checksums.json"), "w", encoding="utf-8"),
+ )
+ return rows
+
+
+def _statuses(rep):
+ return {name: status for name, status, _ in rep.rows}
+
+
+def test_a_sound_set_validates_with_only_the_expected_warnings(tmp_path):
+ root = str(tmp_path / "set")
+ _make_set(root)
+ rep = validateset.validate(root, full=True)
+ st = _statuses(rep)
+ assert rep.ok, [r for r in rep.rows if r[1] == "FAIL"]
+ assert st["realised SNR within tolerance"] == "PASS"
+ assert st["references at speech level"] == "PASS"
+ assert st["set id reproduces from the hashes"] == "PASS"
+ # three items per condition
+ assert st["conditions at the leaderboard minimum"] == "WARN"
+ # the set carries no license contract to check
+ assert not any("licen" in name.lower() for name in st)
+ assert st["language balance (paired items)"] == "PASS"
+ # never a FAIL
+ assert st["references clean (speech over their own floor)"] in (
+ "PASS",
+ "WARN",
+ )
+
+
+def test_language_balance_allows_one_first_language_but_not_unbalanced_others(
+ tmp_path,):
+ root = str(tmp_path / "set")
+ _make_set(root, n_per_cond=6)
+ rows = [
+ json.loads(l)
+ for l in open(os.path.join(root, "manifest.jsonl"), encoding="utf-8")
+ ]
+ paired = [r for r in rows if r.get("clean_path")]
+ # 8 en, 2 de, 2 fr: a first language, balanced others
+ for i, r in enumerate(paired):
+ r["language"] = "en" if i < 8 else ("de", "fr")[i % 2]
+ with open(os.path.join(root, "manifest.jsonl"), "w",
+ encoding="utf-8") as fh:
+ fh.writelines(json.dumps(r) + "\n" for r in rows)
+ rep = validateset.validate(root, full=False)
+ st = dict((r[0], r) for r in rep.rows)["language balance (paired items)"]
+ assert st[1] == "PASS" and st[2].startswith("en 67%")
+ # 8 en, 3 de, 1 fr: the others are not balanced
+ for i, r in enumerate(paired):
+ r["language"] = "en" if i < 8 else ("de" if i < 11 else "fr")
+ with open(os.path.join(root, "manifest.jsonl"), "w",
+ encoding="utf-8") as fh:
+ fh.writelines(json.dumps(r) + "\n" for r in rows)
+ rep = validateset.validate(root, full=False)
+ assert _statuses(rep)["language balance (paired items)"] == "WARN"
+
+
+def test_tampering_with_files_or_the_set_id_fails(tmp_path):
+ root = str(tmp_path / "set")
+ rows = _make_set(root)
+ victim = rows[0]
+ x, sr = sf.read(os.path.join(root, victim["mix_path"]), dtype="float32")
+ sf.write(os.path.join(root, victim["mix_path"]),
+ x * 0.2,
+ sr,
+ subtype="FLOAT") # silently re-levelled
+ os.remove(os.path.join(root, rows[-1]["mix_path"])) # and one file lost
+ rep = validateset.validate(root, full=True)
+ st = _statuses(rep)
+ assert not rep.ok
+ assert st["file hashes match"] == "FAIL" and st["files exist"] == "FAIL"
+ # the re-levelled mix no longer matches its label
+ assert st["realised SNR within tolerance"] == "FAIL"
+ ck = json.load(open(os.path.join(root, "checksums.json"), encoding="utf-8"))
+ ck["set_id"] = "0" * 64
+ json.dump(ck,
+ open(os.path.join(root, "checksums.json"), "w", encoding="utf-8"))
+ st = _statuses(validateset.validate(root, full=True))
+ assert st["set id reproduces from the hashes"] == "FAIL"
+
+
+def test_changing_public_item_semantics_breaks_the_set_id(tmp_path):
+ root = str(tmp_path / "set")
+ _make_set(root)
+ st = _statuses(validateset.validate(root, full=False))
+ assert st["manifest semantics match checksums"] == "PASS"
+ rows = [
+ json.loads(l)
+ for l in open(os.path.join(root, "manifest.jsonl"), encoding="utf-8")
+ ]
+ rows[0]["score_from"] = 4800 # same audio, different scored region
+ with open(os.path.join(root, "manifest.jsonl"), "w",
+ encoding="utf-8") as fh:
+ fh.writelines(json.dumps(r) + "\n" for r in rows)
+ st = _statuses(validateset.validate(root, full=False))
+ assert st["manifest semantics match checksums"] == "FAIL"
+
+
+def test_inventory_check_is_opt_in_and_names_missing_conditions(tmp_path):
+ root = str(tmp_path / "set")
+ _make_set(root)
+ assert "condition inventory complete" not in _statuses(
+ validateset.validate(root, full=False))
+ st = _statuses(validateset.validate(root, full=False,
+ expect_inventory=True))
+ # the hand-made set has three conditions only
+ assert st["condition inventory complete"] == "FAIL"
+
+
+def test_retention_items_are_exempt_from_the_clean_reference_gates(tmp_path):
+ root = str(tmp_path / "wild")
+ _make_set(root, wild=2)
+ rep = validateset.validate(root, full=True)
+ st = _statuses(rep)
+ assert rep.ok, [r for r in rep.rows if r[1] == "FAIL"]
+ # the wild reference is not gated
+ assert st["speech bandwidth field >= 20 kHz"] == "PASS"
+ # the bed's SNR is still checked
+ assert st["realised SNR within tolerance"] == "PASS"
+ assert not [
+ f for f in rep.failing["references clean (speech over their own floor)"]
+ if f.startswith("wild")
+ ]
+ # the same audio without the policy is an ordinary paired item, and then it
+ # fails the gate
+ root2 = str(tmp_path / "plain")
+ _make_set(root2, wild=2, wild_policy=None)
+ rep2 = validateset.validate(root2, full=True)
+ assert _statuses(rep2)["speech bandwidth field >= 20 kHz"] == "FAIL"
+
+
+def test_golden_transcripts_are_checked_against_the_manifest_when_present(
+ tmp_path,):
+ root = str(tmp_path / "set")
+ _make_set(root)
+ rows = [
+ json.loads(l)
+ for l in open(os.path.join(root, "manifest.jsonl"), encoding="utf-8")
+ ]
+ paired = [r for r in rows if r.get("clean_path")]
+ real = [r for r in rows if not r.get("clean_path")]
+ tpath = os.path.join(root, "transcripts.jsonl")
+ with open(tpath, "w", encoding="utf-8") as fh:
+ for r in paired:
+ fh.write(
+ json.dumps({
+ "id": r["id"],
+ "language": r["language"],
+ "text": "some words",
+ "tier": "corpus-verified",
+ }) + "\n")
+ rep = validateset.validate(root, full=False)
+ assert _statuses(rep)["golden transcripts consistent"] == "PASS"
+ lines = open(tpath, encoding="utf-8").read().splitlines()
+ for spoken, status in (
+ ("en" if paired[0]["language"] != "en" else "de", "PASS"),
+ (paired[0]["language"], "FAIL"),
+ ("english", "FAIL"),
+ (7, "FAIL"),
+ ):
+ first = dict(
+ json.loads(lines[0]),
+ # the language heard, where the label is wrong
+ spoken=spoken,
+ )
+ with open(tpath, "w", encoding="utf-8") as fh:
+ fh.write("\n".join([json.dumps(first)] + lines[1:]) + "\n")
+ rep = validateset.validate(root, full=False)
+ assert _statuses(rep)["golden transcripts consistent"] == status
+ with open(tpath, "w", encoding="utf-8") as fh:
+ fh.write("\n".join(lines) + "\n")
+ with open(tpath, "a",
+ encoding="utf-8") as fh: # every kind of bad row, one each
+ fh.write(
+ json.dumps({
+ "id": paired[0]["id"],
+ "language": paired[0]["language"],
+ "text": "again",
+ "tier": "t",
+ }) + "\n") # duplicate
+ fh.write(
+ json.dumps({
+ "id": "ghost.wav",
+ "language": "en",
+ "text": "x",
+ "tier": "t"
+ }) + "\n")
+ fh.write(
+ json.dumps({
+ "id": real[0]["id"],
+ "language": real[0].get("language"),
+ "text": "x",
+ "tier": "t",
+ }) + "\n") # a reference-free item has no golden text
+ fh.write(
+ json.dumps({
+ "id": paired[1]["id"],
+ "language": "xx",
+ "text": " ",
+ "tier": "",
+ }) + "\n") # wrong language, empty text, no tier (and a duplicate)
+ rep = validateset.validate(root, full=False)
+ assert (_statuses(rep)["golden transcripts consistent"] == "FAIL" and
+ not rep.ok)
+ flagged = " ".join(rep.failing["golden transcripts consistent"])
+ for needle in (
+ "duplicate",
+ "not in the manifest",
+ "reference-free",
+ "empty text",
+ "language xx",
+ "no tier",
+ ):
+ assert needle in flagged, needle
+
+
[email protected]("across_conditions", [False, True])
+def test_quick_validation_rejects_duplicate_inputs(tmp_path, across_conditions):
+ """A renamed copy fails even outside the sampled audio or condition."""
+ root = str(tmp_path / "set")
+ rows = _make_set(root)
+ first, second = rows[0], rows[3 if across_conditions else 1]
+ shutil.copyfile(os.path.join(root, first["mix_path"]),
+ os.path.join(root, second["mix_path"]))
+ report = validateset.validate(root, full=False, sample=0.01)
+ assert _statuses(report)["unique input waveforms"] == "FAIL"
+ flagged = " ".join(report.failing["unique input waveforms"])
+ assert first["id"] in flagged and second["id"] in flagged
+
+
+def test_audio_identity_ignores_container_and_signed_zero(tmp_path):
+ """Equivalent decoded samples collide across PCM and floating WAVs."""
+ pcm = tmp_path / "pcm.wav"
+ floating = tmp_path / "floating.wav"
+ samples = np.array([0.0, 0.125, -0.25, 0.0])
+ sf.write(pcm, samples, SR, subtype="PCM_16")
+ samples[-1] = -0.0
+ sf.write(floating, samples, SR, subtype="DOUBLE")
+ assert _sha256(pcm) != _sha256(floating)
+ assert validateset.audio_sha256(pcm) == validateset.audio_sha256(floating)
+
+
+def test_audio_identity_preserves_precision_and_layout(tmp_path):
+ """Distinct PCM32 samples and different timing must not collide."""
+ first = tmp_path / "first.wav"
+ second = tmp_path / "second.wav"
+ sf.write(first, np.array([2**28, 0], dtype=np.int32), SR, subtype="PCM_32")
+ sf.write(second,
+ np.array([2**28 + 1, 0], dtype=np.int32),
+ SR,
+ subtype="PCM_32")
+ assert validateset.audio_sha256(first) != validateset.audio_sha256(second)
+ samples, _ = sf.read(first)
+ sf.write(second, samples, SR // 2, subtype="DOUBLE")
+ assert validateset.audio_sha256(first) != validateset.audio_sha256(second)
+
+
+def test_reference_reuse_does_not_make_inputs_duplicates(tmp_path):
+ """The same target under different noise remains a valid pair of inputs."""
+ root = str(tmp_path / "set")
+ rows = _make_set(root)
+ first = rows[0]
+ second = rows[1]
+ shutil.copyfile(os.path.join(root, first["clean_path"]),
+ os.path.join(root, second["clean_path"]))
+ report = validateset.validate(root, full=True)
+ assert _statuses(report)["unique input waveforms"] == "PASS"
+
+
+def test_the_same_room_block_must_carry_its_labels(tmp_path):
+ root = str(tmp_path / "set")
+ _make_set(root)
+ path = os.path.join(root, "manifest.jsonl")
+ with open(path, encoding="utf-8") as fh:
+ rows = [json.loads(line) for line in fh if line.strip()]
+ rows[0]["condition"], rows[0]["family"] = "coroom@pause", "coroom"
+
+ def write():
+ with open(path, "w", encoding="utf-8") as fh:
+ fh.write("".join(json.dumps(r) + "\n" for r in rows))
+
+ def status():
+ return _statuses(validateset.validate(root, full=False))
+
+ write()
+ assert status()["same-room labels"] == "FAIL"
+ rows[0]["provenance"] = {
+ "events": [[1.0, 1.1, "pause", "household", "x", -15.0]],
+ "pauses": [[0.5, 1.5]],
+ "chain": {
+ "tilt_db_per_octave": 0.0,
+ "peak_hz": 3000,
+ "peak_db": 0.0
+ },
+ "split": "main",
+ "room_share_db": 1.2,
+ "room_share_rule": scoreevents.ROOM_SHARE_RULE,
+ }
+ write()
+ assert status()["same-room labels"] == "PASS"
+ rows[0]["provenance"]["room_share_db"] = "1.2" # a number, not a string
+ write()
+ assert status()["same-room labels"] == "FAIL"
+ # shares measured under another rule than the scorer's are refused
+ rows[0]["provenance"]["room_share_rule"] = "another rule, v1"
+ write()
+ assert status()["same-room allowance rule"] == "FAIL"
diff --git a/tests/bench/scripts/tiny_board.py b/tests/bench/scripts/tiny_board.py
new file mode 100644
index 0000000..8c46bba
--- /dev/null
+++ b/tests/bench/scripts/tiny_board.py
@@ -0,0 +1,156 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Small synthetic boards for the board's tests.
+
+Each board is a set of score files and a frozen calibration.
+"""
+
+import json
+import os
+
+import anchors
+import ranking
+
+FULL = tuple(
+ sorted({
+ c for rows in ranking.AXES_FULL.values() for c, _, _ in rows
+ if not c.startswith("_")
+ })) # every condition the composite axes read
+
+
+def metrics(v: float, n: int = 24) -> dict:
+ """Returns complete synthetic metrics at scale ``v`` with ``n`` items."""
+ d = {
+ c: {
+ "n": n,
+ "babble_supp_db": -v,
+ "babble_resid_db": -v,
+ "babble_resid_db_nb": -v,
+ "si_sdr": v,
+ "kept_p10": v / 10,
+ "kept_mean": v / 10,
+ "kept_coh_p10": v / 10,
+ "kept_coh_nb_p10": v / 10,
+ "spk_sim": 0.9 + v / 1000,
+ "nisqa_mos": 3 + v / 100,
+ "nv_lost_pct": 20 - v,
+ "mag_snr": 10 + v,
+ "band_kept_db": [0, 0, 0, 0, v / 10, v / 10, v / 10],
+ # what scorefiles.load derives from the bands above the input's
+ "band_added_db": v / 10,
+ "hf_err_db": abs(v) / 10,
+ "out_in_rms_db": -v / 10,
+ "level_err_db": abs(v) / 10,
+ # the same-room block's rows (scoreevents): noise left, in dB
+ "event_resid_db": -v,
+ "floor_resid_db": -v,
+ } for c in FULL
+ }
+ # the block pooled: the voice's level while the noise goes, at most zero
+ d["_coroom"] = {"n": n, "voice_level_db": -abs(v) / 100}
+ # the pooled rows of the real recordings (scoreresidual, scorefiles)
+ d["_real_cleanup"] = {
+ "n": n,
+ "pause_resid_db": -v,
+ "pause_resid_db_nb": -v,
+ # the pauses against the output's own voice: the unprocessed recordings
+ # sit at -20.7 dB, the cap at -45
+ "pause_level_db": -20.7 - v,
+ }
+ d["_real_quality"] = {"n": n, "nisqa_mos": 3 + v / 100}
+ d["_level_cal_db"] = 0.0
+ d["_set_id"] = "tiny"
+ d.update(anchors.stamp())
+ return d
+
+
+def write(results: str | os.PathLike[str],
+ name: str,
+ scores: dict,
+ deletion_pct: float | None = None,
+ items: dict[str, list[int]] | None = None) -> None:
+ """Writes the score files of ``name``, with an optional deletion cohort.
+
+ ``items`` is {id: [n_deleted, n_segments]}; ``deletion_pct`` builds a
+ 100-item cohort at that rate.
+ """
+ scores.setdefault("_set_id", "tiny")
+ scores.update(anchors.stamp())
+ json.dump(
+ scores,
+ open(os.path.join(results, f"{name}.metrics.json"),
+ "w",
+ encoding="utf-8"))
+ if items is None and deletion_pct is not None:
+ items = {
+ f"r{i:03d}": [1 if i < deletion_pct else 0, 1] for i in range(100)
+ }
+ if items is not None:
+ json.dump(
+ {
+ "_items_primary": items,
+ "_set_id": scores["_set_id"],
+ "_level_cal_db": scores.get("_level_cal_db"),
+ **anchors.stamp(),
+ },
+ open(os.path.join(results, f"{name}.realx.json"),
+ "w",
+ encoding="utf-8"),
+ )
+
+
+def calibration(scores: dict, cohort: dict[str, int] | None = None) -> dict:
+ """Resolves synthetic anchor endpoints and the supplied deletion cohort."""
+ if cohort is None:
+ items = next(
+ (v["_deletion"]["items"]
+ for v in scores.values()
+ if v.get("_deletion", {}).get("items")),
+ {},
+ )
+ cohort = {uid: values[1] for uid, values in items.items()}
+ policy, refs = anchors.definitions(), {}
+ for name, side in (("INPUT", "floor"), ("REF", "ceiling")):
+ d = metrics(0)
+ # the two anchor rows sit on the declared endpoints, so the policy's
+ # verification against the set passes
+ for rule in policy["rules"]:
+ for cond in rule["conditions"]:
+ at = next(
+ (
+ # a row sits on the endpoint it verifies
+ e
+ for e in ("floor", "ceiling")
+ if (rule[e].get("verify") or {}).get("source") == name),
+ side,
+ )
+ if cond in d and "value" in rule[at]:
+ d[cond].update({
+ metric: rule[at]["value"] for metric in rule["metrics"]
+ })
+ d["_deletion"] = {
+ "items": {
+ uid: [0, count] for uid, count in cohort.items()
+ }
+ }
+ refs[name] = d
+ return anchors.resolve(policy, refs, ranking.AXES_BY_TIER)
+
+
+def rank(scores: dict, tiers: dict) -> tuple[dict, dict, dict]:
+ """Ranks synthetic scores with their resolved calibration."""
+ for data in scores.values():
+ data.setdefault("_set_id", "tiny")
+ data.update(anchors.stamp())
+ return ranking.rank(scores, tiers, calibration(scores))
diff --git a/tests/bench/wrappers/conftest.py b/tests/bench/wrappers/conftest.py
new file mode 100644
index 0000000..e259075
--- /dev/null
+++ b/tests/bench/wrappers/conftest.py
@@ -0,0 +1,90 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Wrapper tests import the wrappers as plain modules.
+
+Release code is never imported here.
+
+``tiny_set`` is a set build of three 48 kHz inputs (``mix/`` beside
+``checksums.json``); ``run_wrapper`` runs a wrapper's ``main`` with its release
+replaced by a fake.
+"""
+
+import json
+import os
+import sys
+
+import numpy as np
+import pytest
+import soundfile as sf
+
+REPO = os.path.dirname(
+ os.path.dirname(os.path.dirname(os.path.dirname(
+ os.path.abspath(__file__)))))
+sys.path.insert(0, os.path.join(REPO, "bench", "wrappers"))
+
+SECONDS = (0.5, 0.75, 1.0)
+
+
+def tiny_set(tmp_path):
+ """Returns (input folder, output folder) of a three-item set build."""
+ root = tmp_path / "set"
+ (root / "mix").mkdir(parents=True)
+ (root / "checksums.json").write_text(json.dumps({"set_id": "tiny-set"}))
+ rng = np.random.default_rng(0)
+ for i, seconds in enumerate(SECONDS):
+ x = (rng.standard_normal(int(seconds * 48000)) * 0.1).astype("float32")
+ sf.write(root / "mix" / f"item_{i}.wav", x, 48000, subtype="FLOAT")
+ return root / "mix", tmp_path / "out"
+
+
+def run_wrapper(monkeypatch):
+ """Runs ``module.main()`` over a folder with ``load`` and the receipt faked.
+
+ Returns:
+ {"load": the arguments load was given, "begin": the receipt call's
+ arguments, "exit": main's return value}.
+ """
+
+ def run(module, in_dir, out_dir, *extra, enhance=None):
+ calls = {}
+
+ def load(*args):
+ calls["load"] = args
+ return enhance or (lambda path, samples, rate:
+ (samples * 0.5, rate))
+
+ monkeypatch.setattr(module, "load", load)
+ monkeypatch.setattr(
+ module.receipt,
+ "begin",
+ lambda *a, **k: calls.setdefault("begin", a),
+ )
+ monkeypatch.setattr(
+ sys,
+ "argv",
+ [
+ module.__file__,
+ "--in-dir",
+ str(in_dir),
+ "--out-dir",
+ str(out_dir),
+ *extra,
+ ],
+ )
+ calls["exit"] = module.main()
+ return calls
+
+ return run
diff --git a/tests/bench/wrappers/test_pase.py b/tests/bench/wrappers/test_pase.py
new file mode 100644
index 0000000..21197f2
--- /dev/null
+++ b/tests/bench/wrappers/test_pase.py
@@ -0,0 +1,135 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The PASE family's runner, with the release's two modules faked.
+
+Items routed by length to the two modules, existing outputs kept, checkpoints
+passed by path, writes made float32, outputs fitted to the input.
+"""
+
+# pylint: disable=redefined-outer-name,unused-argument
+
+import os
+import subprocess
+import sys
+
+import numpy as np
+import pytest
+import soundfile as sf
+
+import pase
+
+
+def lengths(tmp_path):
+ inp, out = tmp_path / "in", tmp_path / "out"
+ inp.mkdir()
+ out.mkdir()
+ for name, seconds in (("short.wav", 5), ("long.wav", 25), ("done.wav", 1)):
+ sf.write(
+ inp / name,
+ np.zeros(48000 * seconds, dtype="float32"),
+ 48000,
+ subtype="FLOAT",
+ )
+ sf.write(
+ out / "done.wav",
+ np.ones(48000, dtype="float32"),
+ 48000,
+ subtype="FLOAT",
+ )
+ return inp, out
+
+
+def test_items_are_routed_by_length_resumed_and_fitted(lengths, monkeypatch):
+ inp, out = lengths
+ calls = []
+
+ def run_module(repo, module, in_dir, out_dir, device, checkpoints):
+ calls.append((module, sorted(os.listdir(in_dir)), device, checkpoints))
+ os.makedirs(out_dir)
+ # the release: the input's rate, a length of its own
+ for name in os.listdir(in_dir):
+ sf.write(
+ os.path.join(out_dir, name),
+ np.full(48000 * 25 - 100, 0.25, "float32"),
+ 48000,
+ )
+
+ monkeypatch.setattr(pase, "run_module", run_module)
+ files = sorted(str(p) for p in inp.iterdir())
+ assert (pase.render("repo", files[:2], str(out), "cuda:0",
+ {"--ckpt": "c.pt"}) == 0)
+ assert [(m, n) for m, n, _, _ in calls] == [("inference.inference_long",
+ ["long.wav"])]
+ assert calls[0][2:] == ("cuda:0", {"--ckpt": "c.pt"})
+ y, rate = sf.read(out / "long.wav", dtype="float32")
+ assert rate == 48000 and len(y) == 48000 * 25 and y[-100:].max() == 0
+ # already there: not re-run
+ assert sf.read(out / "done.wav")[0].min() == 1.0
+
+
+def test_a_failed_module_fails_its_group_only(lengths, monkeypatch, capsys):
+ inp, out = lengths
+
+ def run_module(repo, module, in_dir, out_dir, device, checkpoints):
+ if module == "inference.inference_long":
+ raise subprocess.CalledProcessError(1, module)
+ os.makedirs(out_dir)
+ for name in os.listdir(in_dir):
+ sf.write(
+ os.path.join(out_dir, name),
+ np.zeros(48000 * 5, "float32"),
+ 48000,
+ )
+
+ monkeypatch.setattr(pase, "run_module", run_module)
+ files = sorted(str(p) for p in inp.iterdir())
+ assert pase.render("repo", files, str(out), "cpu", {}) == 1
+ printed = capsys.readouterr().out
+ assert "FAIL long.wav" in printed and "DONE 2/3" in printed
+ assert (out / "short.wav").exists() and not (out / "long.wav").exists()
+
+
+def test_a_missing_checkpoint_stops_before_the_release_runs(tmp_path):
+ with pytest.raises(FileNotFoundError, match="setupfield"):
+ pase.run_module(
+ str(tmp_path),
+ "inference.inference",
+ str(tmp_path),
+ str(tmp_path),
+ "cpu",
+ {"--ckpt": str(tmp_path / "missing.pt")},
+ )
+
+
+def test_the_runner_makes_the_releases_default_writes_float32(tmp_path):
+ (tmp_path / "fakerelease.py").write_text(
+ "import sys, numpy as np, soundfile as sf\n"
+ "out = sys.argv[sys.argv.index('-O') + 1]\n"
+ "x = np.full(100, 0.123456789, dtype='float32')\n"
+ "sf.write(out + '/default.wav', x, 16000)\n"
+ "sf.write(out + '/explicit.wav', x, 16000, subtype='PCM_24')\n"
+ "sf.write(out + '/positional.wav', x, 16000, 'PCM_16')\n")
+ env = dict(os.environ, PYTHONPATH=str(tmp_path))
+ subprocess.run(
+ [sys.executable, "-c", pase.RUNNER, "fakerelease", "-O",
+ str(tmp_path)],
+ env=env,
+ check=True,
+ )
+ assert sf.info(tmp_path / "default.wav").subtype == "FLOAT"
+ x, _ = sf.read(tmp_path / "default.wav", dtype="float32")
+ assert x[0] == np.float32(0.123456789)
+ assert sf.info(tmp_path / "explicit.wav").subtype == "PCM_24"
+ assert sf.info(tmp_path / "positional.wav").subtype == "PCM_16"
diff --git a/tests/bench/wrappers/test_receipt.py b/tests/bench/wrappers/test_receipt.py
new file mode 100644
index 0000000..4f1a9cb
--- /dev/null
+++ b/tests/bench/wrappers/test_receipt.py
@@ -0,0 +1,305 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""A receipt names everything a render depends on.
+
+The code, the release, the weights, the packages, the device, the arguments and
+the inputs of a render, and it changes when any of them does.
+"""
+
+# pylint: disable=redefined-outer-name
+
+import hashlib
+import json
+import os
+import subprocess
+import sys
+
+import pytest
+
+import receipt
+
+
+def _git(path, *args):
+ subprocess.run(
+ [
+ "git",
+ "-C",
+ str(path),
+ "-c",
+ "user.email=t@t",
+ "-c",
+ "user.name=t",
+ *args,
+ ],
+ check=True,
+ capture_output=True,
+ )
+
+
+def release(tmp_path, monkeypatch, tiny_set):
+ """A release checkout with code and weights.
+
+ It comes with its description and a renderer.
+ """
+ meta = tmp_path / "meta"
+ meta.mkdir()
+ src = tmp_path / "src" / "upstream"
+ (src / "ckpts").mkdir(parents=True)
+ (src / "ckpts" / "weights.pt").write_bytes(b"w" * 100)
+ (src / "model.py").write_text("LAYERS = 4\n")
+ (src / "notes.txt").write_text("not code")
+ _git(src, "init", "-q")
+ _git(src, "add", ".")
+ _git(src, "commit", "-q", "-m", "release")
+ json.dump(
+ {
+ "source_dir": "upstream",
+ "weight_globs": ["ckpts/*.pt"]
+ },
+ open(meta / "sys.json", "w", encoding="utf-8"),
+ )
+ wrappers = tmp_path / "wrappers"
+ wrappers.mkdir()
+ (wrappers / "helper.py").write_text("import other\n")
+ (wrappers / "other.py").write_text("X = 1\n")
+ renderer = wrappers / "runsys.py"
+ renderer.write_text("import argparse\nimport helper\nimport receipt\n")
+ monkeypatch.setattr(receipt, "META_DIR", str(meta))
+ monkeypatch.setattr(receipt, "SRC", str(tmp_path / "src"))
+ in_dir, _ = tiny_set
+ return src, renderer, str(in_dir)
+
+
+ARGV = [
+ "runsys.py",
+ "--in-dir",
+ "/a/b",
+ "--out-dir",
+ "/c",
+ "--shard",
+ "1/4",
+ "--device",
+ "cpu",
+ "--limit",
+ "3",
+ "--overwrite",
+ "--steps",
+ "8",
+ "--config",
+ "/x/y/cfg.yaml",
+]
+
+
+def test_identity_names_code_release_weights_packages_device_args_and_inputs(
+ release,):
+ src, renderer, in_dir = release
+ ident = receipt.identity("sys", str(renderer), ARGV, in_dir, "cpu")
+ assert ident["wrapper"] == "runsys.py"
+ code = renderer.read_bytes()
+ assert ident["wrapper_sha256"] == hashlib.sha256(code).hexdigest()
+ # transitively, not receipt
+ assert sorted(ident["helpers_sha256"]) == ["helper.py", "other.py"]
+ head = subprocess.run(
+ ["git", "-C", str(src), "rev-parse", "HEAD"],
+ capture_output=True,
+ text=True,
+ check=True,
+ )
+ assert ident["source"]["git_commit"] == head.stdout.strip()
+ assert ident["weights_sha256"] == {
+ "ckpts/weights.pt": hashlib.sha256(b"w" * 100).hexdigest()
+ }
+ assert ident["n_packages"] > 0 and len(ident["packages_sha256"]) == 64
+ assert ident["device"] == "cpu"
+ # the work selection, the device and --overwrite are not the computation;
+ # paths lose folders
+ assert ident["inference_args"] == ["--steps", "8", "--config", "cfg.yaml"]
+ assert ident["inputs"] == {"set_id": "tiny-set"}
+
+
+def test_every_ingredient_changes_the_digest_and_the_work_selection_does_not(
+ release,):
+ src, renderer, in_dir = release
+ base = receipt.digest(
+ receipt.identity("sys", str(renderer), ARGV, in_dir, "cpu"))
+ same = [
+ "runsys.py",
+ "--steps",
+ "8",
+ "--config",
+ "/elsewhere/cfg.yaml",
+ "--shard",
+ "0/2",
+ ]
+ assert (receipt.digest(
+ receipt.identity("sys", str(renderer), same, in_dir, "cpu")) == base)
+ assert (receipt.digest(
+ receipt.identity("sys", str(renderer), ["r", "--steps", "16"], in_dir,
+ "cpu")) != base)
+
+ def changed(path, text):
+ before = path.read_bytes()
+ path.write_bytes(text)
+ try:
+ return receipt.digest(
+ receipt.identity("sys", str(renderer), ARGV, in_dir, "cpu"))
+ finally:
+ path.write_bytes(before)
+
+ assert changed(src / "ckpts" / "weights.pt", b"v" * 100) != base
+ # an edit, uncommitted
+ assert changed(src / "model.py", b"LAYERS = 5\n") != base
+ # not code or configuration
+ assert changed(src / "notes.txt", b"other notes") == base
+ # a helper's helper
+ assert changed(renderer.parent / "other.py", b"X = 2\n") != base
+ assert changed(renderer, b"import argparse\nimport helper\n") != base
+
+
+def test_the_environment_digest_leaves_the_inputs_out(release, tmp_path):
+ _, renderer, in_dir = release
+ probe = tmp_path / "probe"
+ (probe / "in").mkdir(parents=True)
+ (probe / "probe.json").write_text(json.dumps({"identity": "probe-1"}))
+ board = receipt.identity("sys", str(renderer), ARGV, in_dir, "cpu")
+ cut = receipt.identity("sys", str(renderer), ARGV, str(probe / "in"), "cpu")
+ assert cut["inputs"] == {"probe": "probe-1"}
+ assert receipt.digest(cut) != receipt.digest(board)
+ assert receipt.environment_digest(cut) == receipt.environment_digest(board)
+
+
+def test_inputs_without_a_manifest_are_identified_by_their_bytes(tmp_path):
+ folder = tmp_path / "loose" / "in"
+ folder.mkdir(parents=True)
+ (folder / "a.wav").write_bytes(b"one")
+ first = receipt.inputs(str(folder))
+ (folder / "a.wav").write_bytes(b"two")
+ assert (first != receipt.inputs(str(folder)) and
+ list(first) == ["files_sha256"])
+
+
+def test_missing_weights_release_or_device_are_errors_never_empty_records(
+ release, monkeypatch):
+ src, renderer, in_dir = release
+ (src / "ckpts" / "weights.pt").unlink()
+ with pytest.raises(FileNotFoundError, match="no weights match"):
+ receipt.identity("sys", str(renderer), ARGV, in_dir, "cpu")
+ monkeypatch.setattr(receipt, "SRC", str(src.parent / "nowhere"))
+ with pytest.raises(FileNotFoundError):
+ receipt.identity(
+ "sys",
+ str(renderer),
+ ARGV,
+ in_dir,
+ "cpu",
+ desc={"source_dir": "upstream"},
+ )
+ torch = pytest.importorskip("torch")
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: False)
+ with pytest.raises(RuntimeError, match="CUDA is not available"):
+ receipt.resolve_device("cuda:0")
+
+
+def test_a_given_description_code_list_and_weights_replace_the_defaults(
+ release, tmp_path):
+ _, renderer, in_dir = release
+ package = tmp_path / "pkgroot" / "fakepackage"
+ package.mkdir(parents=True)
+ (package / "__init__.py").write_text("X = 1\n")
+ checkpoint = tmp_path / "ckpt.safetensors"
+ checkpoint.write_bytes(b"c")
+ sys.path.insert(0, str(package.parent))
+ try:
+ ident = receipt.identity(
+ "anything",
+ str(renderer),
+ ARGV,
+ in_dir,
+ "cpu",
+ weights=(str(checkpoint),),
+ desc={"package_dirs": ["fakepackage"]},
+ code=(str(renderer.parent / "other.py"),),
+ )
+ assert ident["source"] is None and list(
+ ident["helpers_sha256"]) == ["other.py"]
+ assert ident["weights_sha256"] == {
+ "ckpt.safetensors": hashlib.sha256(b"c").hexdigest()
+ }
+ before = ident["package_code_sha256"]["fakepackage"]
+ (package / "__init__.py").write_text("X = 2\n")
+ again = receipt.identity(
+ "anything",
+ str(renderer),
+ ARGV,
+ in_dir,
+ "cpu",
+ desc={"package_dirs": ["fakepackage"]},
+ )
+ assert again["package_code_sha256"]["fakepackage"] != before
+ with pytest.raises(ModuleNotFoundError):
+ receipt.identity(
+ "anything",
+ str(renderer),
+ ARGV,
+ in_dir,
+ "cpu",
+ desc={"package_dirs": ["no_such_package_here"]},
+ )
+ finally:
+ sys.path.remove(str(package.parent))
+
+
+def test_begin_writes_one_receipt_per_process(release, tmp_path):
+ _, renderer, in_dir = release
+ out = tmp_path / "out"
+ digest = receipt.begin("sys", str(renderer), str(out), ARGV, in_dir, "cpu")
+ docs = receipt.read_all(str(out))
+ assert len(docs) == 1 and docs[0]["digest"] == digest == receipt.digest(
+ docs[0]["identity"])
+ assert docs[0]["environment_digest"] == receipt.environment_digest(
+ docs[0]["identity"])
+ assert docs[0]["pid"] == os.getpid() and docs[0]["argv"] == [
+ "--steps",
+ "8",
+ "--config",
+ "cfg.yaml",
+ ]
+ assert any(p.startswith("numpy==") for p in docs[0]["packages"])
+ receipt.begin("sys", str(renderer), str(out), ARGV, in_dir, "cpu")
+ assert len(receipt.read_all(str(out))) == 1 # one process, one file
+
+
+def test_the_probe_prints_what_the_renderer_would_record(release, capsys):
+ _, renderer, in_dir = release
+ assert (receipt.main([
+ "receipt.py",
+ "probe",
+ "sys",
+ str(renderer),
+ "--in-dir",
+ in_dir,
+ "--device",
+ "cpu",
+ "--",
+ "--steps",
+ "8",
+ "--config",
+ "/x/y/cfg.yaml",
+ ]) == 0)
+ doc = json.loads(capsys.readouterr().out)
+ assert doc["digest"] == receipt.digest(
+ receipt.identity("sys", str(renderer), ARGV, in_dir, "cpu"))
+ assert doc["environment_digest"] == receipt.environment_digest(
+ doc["identity"])
diff --git a/tests/bench/wrappers/test_runclearvoice.py b/tests/bench/wrappers/test_runclearvoice.py
new file mode 100644
index 0000000..1be728a
--- /dev/null
+++ b/tests/bench/wrappers/test_runclearvoice.py
@@ -0,0 +1,44 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The ClearVoice wrapper renders with absolute paths.
+
+It renders only on the first visible GPU.
+"""
+
+import os
+
+import pytest
+
+import runclearvoice
+
+
+def test_paths_are_absolute_and_every_input_is_rendered(tiny_set, run_wrapper,
+ monkeypatch):
+ in_dir, out_dir = tiny_set
+ monkeypatch.chdir(in_dir.parent)
+ calls = run_wrapper(runclearvoice, "mix",
+ os.path.relpath(out_dir, in_dir.parent))
+ assert calls["exit"] == 0 and calls["load"] == ("cuda:0",)
+ assert calls["begin"][0] == "clearvoice_mf2_48k"
+ assert os.path.isabs(calls["begin"][2]) and os.path.isabs(calls["begin"][4])
+ assert len(list(out_dir.glob("*.wav"))) == 3
+
+
+def test_another_device_or_a_missing_checkpoint_stops_before_the_package_loads(
+ tmp_path, monkeypatch):
+ with pytest.raises(ValueError, match="CUDA_VISIBLE_DEVICES"):
+ runclearvoice.load("cuda:1")
+ monkeypatch.setattr(runclearvoice, "SRC", str(tmp_path))
+ with pytest.raises(FileNotFoundError, match="setupfield"):
+ runclearvoice.load("cuda:0")
diff --git a/tests/bench/wrappers/test_rundfn3.py b/tests/bench/wrappers/test_rundfn3.py
new file mode 100644
index 0000000..07807d6
--- /dev/null
+++ b/tests/bench/wrappers/test_rundfn3.py
@@ -0,0 +1,35 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The DeepFilterNet3 wrapper renders every input.
+
+It needs the pinned model folder.
+"""
+
+import pytest
+
+import rundfn3
+
+
+def test_every_input_is_rendered_under_a_receipt(tiny_set, run_wrapper):
+ in_dir, out_dir = tiny_set
+ calls = run_wrapper(rundfn3, in_dir, out_dir)
+ assert calls["exit"] == 0 and calls["begin"][0] == "dfn3"
+ assert len(list(out_dir.glob("*.wav"))) == 3
+
+
+def test_a_missing_model_folder_stops_before_the_package_loads(
+ tmp_path, monkeypatch):
+ monkeypatch.setattr(rundfn3, "MODEL_DIR", str(tmp_path / "DeepFilterNet3"))
+ with pytest.raises(FileNotFoundError, match="setupfield"):
+ rundfn3.load("cpu")
diff --git a/tests/bench/wrappers/test_runfastenhancer.py b/tests/bench/wrappers/test_runfastenhancer.py
new file mode 100644
index 0000000..35e6315
--- /dev/null
+++ b/tests/bench/wrappers/test_runfastenhancer.py
@@ -0,0 +1,84 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The FastEnhancer wrapper runs the export frame by frame, on the CPU only.
+
+It flushes the export's state and removes the algorithmic delay.
+"""
+
+# pylint: disable=unused-argument
+
+import sys
+
+import numpy as np
+import pytest
+
+import runfastenhancer
+
+
+class _Port:
+
+ def __init__(self, name, shape):
+ self.name, self.shape = name, shape
+
+
+class _DelayLine:
+ """A streaming export that returns its input N_FFT - HOP samples late.
+
+ Through its cache, as the export's recurrent state does.
+ """
+
+ def get_inputs(self):
+ return [
+ _Port("wav_in", [1, runfastenhancer.HOP]),
+ _Port("cache", [1, runfastenhancer.N_FFT - runfastenhancer.HOP]),
+ ]
+
+ def get_outputs(self):
+ return [
+ _Port("wav_out", [1, runfastenhancer.HOP]),
+ _Port("cache_out",
+ [1, runfastenhancer.N_FFT - runfastenhancer.HOP]),
+ ]
+
+ def run(self, names, feeds):
+ line = np.concatenate(
+ [feeds["cache"].reshape(-1), feeds["wav_in"].reshape(-1)])
+ return [
+ line[:runfastenhancer.HOP].reshape(1, -1),
+ line[runfastenhancer.HOP:].reshape(1, -1)
+ ]
+
+
+def test_the_output_is_aligned_with_the_input_and_covers_its_whole_length():
+ n = 48000 * 2 + 37
+ x = np.random.default_rng(0).standard_normal(n).astype("float32")
+ y = runfastenhancer.stream(_DelayLine(), x)
+ assert y.shape == x.shape and y.dtype == np.float32
+ # delay removed, tail flushed: nothing lost, nothing shifted
+ assert np.array_equal(y, x)
+
+
+def test_every_input_is_rendered_and_only_the_cpu_is_accepted(
+ tiny_set, run_wrapper, monkeypatch):
+ in_dir, out_dir = tiny_set
+ calls = run_wrapper(runfastenhancer, in_dir, out_dir, "--threads", "3")
+ assert (calls["exit"] == 0 and calls["load"] == (3,) and
+ calls["begin"][5] == "cpu")
+ monkeypatch.setattr(
+ sys,
+ "argv",
+ ["w", "--in-dir", "a", "--out-dir", "b", "--device", "cuda"],
+ )
+ with pytest.raises(SystemExit):
+ runfastenhancer.main()
diff --git a/tests/bench/wrappers/test_rungapurgenet.py b/tests/bench/wrappers/test_rungapurgenet.py
new file mode 100644
index 0000000..ca91fd5
--- /dev/null
+++ b/tests/bench/wrappers/test_rungapurgenet.py
@@ -0,0 +1,59 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The GAP-URGENet wrapper hands every pinned checkpoint to the release runner.
+
+It hands the device to the runner as well.
+"""
+
+# pylint: disable=unused-argument
+
+import os
+import sys
+
+import pase
+import receipt
+import rungapurgenet
+
+
+def test_the_release_gets_all_five_checkpoints_by_path(tiny_set, monkeypatch):
+ in_dir, out_dir = tiny_set
+ seen = {}
+
+ def render(repo, files, out, device, checkpoints):
+ seen.update(repo=repo,
+ n=len(files),
+ device=device,
+ checkpoints=checkpoints)
+ return 0
+
+ monkeypatch.setattr(pase, "render", render)
+ monkeypatch.setattr(receipt, "begin",
+ lambda *a, **k: seen.setdefault("begin", a))
+ monkeypatch.setattr(
+ sys, "argv", ["w", "--in-dir",
+ str(in_dir), "--out-dir",
+ str(out_dir)])
+ assert rungapurgenet.main() == 0
+ assert (seen["begin"][0] == "gap_urgenet" and seen["device"] == "cuda:0" and
+ seen["n"] == 3)
+ assert {os.path.basename(p) for p in seen["checkpoints"].values()} == {
+ "DeWavLM-Omni.pt",
+ "Adapter.pt",
+ "Vocoder.pt",
+ "Predictor.pt",
+ "PostNet.pt",
+ }
+ assert all(
+ p.startswith(os.path.join(rungapurgenet.REPO, "ckpts"))
+ for p in seen["checkpoints"].values())
diff --git a/tests/bench/wrappers/test_runresembledn.py b/tests/bench/wrappers/test_runresembledn.py
new file mode 100644
index 0000000..aa7ce6a
--- /dev/null
+++ b/tests/bench/wrappers/test_runresembledn.py
@@ -0,0 +1,35 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The resemble-enhance wrapper renders every input.
+
+It needs the pinned weights folder.
+"""
+
+import pytest
+
+import runresembledn
+
+
+def test_every_input_is_rendered_under_a_receipt(tiny_set, run_wrapper):
+ in_dir, out_dir = tiny_set
+ calls = run_wrapper(runresembledn, in_dir, out_dir)
+ assert calls["exit"] == 0 and calls["begin"][0] == "resemble_dn"
+ assert len(list(out_dir.glob("*.wav"))) == 3
+
+
+def test_a_missing_weights_folder_stops_before_the_package_loads(
+ tmp_path, monkeypatch):
+ monkeypatch.setattr(runresembledn, "RUN_DIR", str(tmp_path))
+ with pytest.raises(FileNotFoundError, match="setupfield"):
+ runresembledn.load("cpu")
diff --git a/tests/bench/wrappers/test_runreusenemotron.py b/tests/bench/wrappers/test_runreusenemotron.py
new file mode 100644
index 0000000..4f1bfe2
--- /dev/null
+++ b/tests/bench/wrappers/test_runreusenemotron.py
@@ -0,0 +1,33 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The NemotronLabs RE-USE wrapper receipts its render.
+
+It runs the release over every input.
+"""
+
+import soundfile as sf
+
+import runreusenemotron
+
+
+def test_every_input_is_rendered_under_a_receipt(tiny_set, run_wrapper):
+ in_dir, out_dir = tiny_set
+ calls = run_wrapper(runreusenemotron, in_dir, out_dir, "--device", "cuda:1")
+ assert calls["exit"] == 0 and calls["load"] == ("cuda:1",)
+ assert calls["begin"][0] == "reuse_nemotron" and calls["begin"][
+ 5] == "cuda:1"
+ assert sorted(p.name for p in out_dir.glob("*.wav")) == [
+ f"item_{i}.wav" for i in range(3)
+ ]
+ assert sf.info(str(out_dir / "item_0.wav")).frames == 24000
diff --git a/tests/bench/wrappers/test_runreusenemotronlaughter.py b/tests/bench/wrappers/test_runreusenemotronlaughter.py
new file mode 100644
index 0000000..11ff7b8
--- /dev/null
+++ b/tests/bench/wrappers/test_runreusenemotronlaughter.py
@@ -0,0 +1,34 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The NemotronLabs RE-USE-laughter wrapper receipts its render.
+
+It runs the release over every input.
+"""
+
+import soundfile as sf
+
+import runreusenemotronlaughter
+
+
+def test_every_input_is_rendered_under_a_receipt(tiny_set, run_wrapper):
+ in_dir, out_dir = tiny_set
+ calls = run_wrapper(runreusenemotronlaughter, in_dir, out_dir, "--device",
+ "cuda:1")
+ assert calls["exit"] == 0 and calls["load"] == ("cuda:1",)
+ assert calls["begin"][0] == "reuse_nemotron_laughter" and calls["begin"][
+ 5] == "cuda:1"
+ assert sorted(p.name for p in out_dir.glob("*.wav")) == [
+ f"item_{i}.wav" for i in range(3)
+ ]
+ assert sf.info(str(out_dir / "item_0.wav")).frames == 24000
diff --git a/tests/bench/wrappers/test_runsmule.py b/tests/bench/wrappers/test_runsmule.py
new file mode 100644
index 0000000..db889f0
--- /dev/null
+++ b/tests/bench/wrappers/test_runsmule.py
@@ -0,0 +1,45 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The Smule Renaissance wrapper renders 48 kHz inputs only.
+
+It fills the release's short tail.
+"""
+
+# pylint: disable=unused-argument
+
+import numpy as np
+import soundfile as sf
+
+import runsmule
+
+
+def test_a_short_output_is_filled_and_another_rate_fails(
+ tiny_set, run_wrapper, capsys):
+ in_dir, out_dir = tiny_set
+ sf.write(
+ in_dir / "item_3.wav",
+ np.zeros(16000, dtype="float32"),
+ 16000,
+ subtype="FLOAT",
+ )
+
+ # the release's inverse STFT ends up to 2047 samples short
+ def enhance(path, samples, rate):
+ return samples[:len(samples) - 2047] * 0.5, rate
+
+ calls = run_wrapper(runsmule, in_dir, out_dir, enhance=enhance)
+ assert calls["exit"] == 1 and calls["begin"][0] == "smule"
+ y, _ = sf.read(out_dir / "item_0.wav", dtype="float32")
+ assert len(y) == 24000 and not y[-2047:].any() and y[:100].any()
+ assert "FAIL item_3.wav" in capsys.readouterr().out
diff --git a/tests/bench/wrappers/test_rununipase.py b/tests/bench/wrappers/test_rununipase.py
new file mode 100644
index 0000000..33f9915
--- /dev/null
+++ b/tests/bench/wrappers/test_rununipase.py
@@ -0,0 +1,51 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The UniPASE wrapper hands every pinned checkpoint to the release runner.
+
+It hands the device to the runner as well.
+"""
+
+# pylint: disable=unused-argument
+
+import os
+import sys
+
+import pase
+import receipt
+import rununipase
+
+
+def test_the_release_gets_its_four_checkpoints_by_path(tiny_set, monkeypatch):
+ in_dir, out_dir = tiny_set
+ seen = {}
+
+ def render(repo, files, out, device, checkpoints):
+ seen.update(device=device, checkpoints=checkpoints)
+ return 0
+
+ monkeypatch.setattr(pase, "render", render)
+ monkeypatch.setattr(receipt, "begin",
+ lambda *a, **k: seen.setdefault("begin", a))
+ monkeypatch.setattr(
+ sys, "argv", ["w", "--in-dir",
+ str(in_dir), "--out-dir",
+ str(out_dir)])
+ assert rununipase.main() == 0
+ assert seen["begin"][0] == "unipase"
+ assert {os.path.basename(p) for p in seen["checkpoints"].values()} == {
+ "DeWavLM-Omni.pt",
+ "Adapter.pt",
+ "Vocoder_DWO-L1.pt",
+ "PostNet.pt",
+ }
diff --git a/tests/bench/wrappers/test_runurgent26bsrnn.py b/tests/bench/wrappers/test_runurgent26bsrnn.py
new file mode 100644
index 0000000..1c2ed1f
--- /dev/null
+++ b/tests/bench/wrappers/test_runurgent26bsrnn.py
@@ -0,0 +1,29 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The URGENT BSRNN wrapper writes 48 kHz.
+
+It writes another rate only when the native-rate view asks for one.
+"""
+
+import runurgent26bsrnn
+
+
+def test_the_native_rate_view_reaches_the_loader(tiny_set, run_wrapper):
+ in_dir, out_dir = tiny_set
+ calls = run_wrapper(runurgent26bsrnn, in_dir, out_dir)
+ assert calls["exit"] == 0 and calls["load"] == ("cuda:0", False)
+ assert calls["begin"][0] == "urgent26_bsrnn"
+ calls = run_wrapper(runurgent26bsrnn, in_dir, out_dir.parent / "native",
+ "--native-rate")
+ assert calls["load"] == ("cuda:0", True)
diff --git a/tests/bench/wrappers/test_runurgent26bsrnnflow.py b/tests/bench/wrappers/test_runurgent26bsrnnflow.py
new file mode 100644
index 0000000..addb717
--- /dev/null
+++ b/tests/bench/wrappers/test_runurgent26bsrnnflow.py
@@ -0,0 +1,29 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The URGENT FlowSE wrapper writes 48 kHz.
+
+It writes another rate only when the native-rate view asks for one.
+"""
+
+import runurgent26bsrnnflow
+
+
+def test_the_native_rate_view_reaches_the_loader(tiny_set, run_wrapper):
+ in_dir, out_dir = tiny_set
+ calls = run_wrapper(runurgent26bsrnnflow, in_dir, out_dir)
+ assert calls["exit"] == 0 and calls["load"] == ("cuda:0", False)
+ assert calls["begin"][0] == "urgent26_bsrnn_flow"
+ calls = run_wrapper(runurgent26bsrnnflow, in_dir, out_dir.parent / "native",
+ "--native-rate")
+ assert calls["load"] == ("cuda:0", True)
diff --git a/tests/bench/wrappers/test_semamba.py b/tests/bench/wrappers/test_semamba.py
new file mode 100644
index 0000000..fe2e790
--- /dev/null
+++ b/tests/bench/wrappers/test_semamba.py
@@ -0,0 +1,110 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The SEMamba family's runner, with the release's packages faked.
+
+The packages bound by path, the STFT scaled to the input rate, mostly-silent
+frames blanked, the length matched to the input.
+"""
+
+# pylint: disable=redefined-outer-name
+
+import sys
+
+import numpy as np
+import pytest
+
+import semamba
+
+STFTS = """
+import torch
+CALLS = []
+def mag_phase_stft(x, n_fft, hop_size, win_size, compress_factor, center,
+ addeps):
+ CALLS.append((n_fft, hop_size, win_size))
+ frames = x.shape[-1] // hop_size + 1
+ mag = torch.ones(1, n_fft // 2 + 1, frames)
+ return mag, torch.zeros_like(mag), None
+def mag_phase_istft(amp, pha, n_fft, hop, win, compress):
+ return amp.sum(1).repeat_interleave(hop, dim=-1)
+"""
+UTIL = """
+import torch
+def pad_or_trim_to_match(x, y, pad_value):
+ return torch.nn.functional.pad(
+ y, (0, max(0, x.shape[-1] - y.shape[-1])),
+ value=pad_value)[..., :x.shape[-1]]
+"""
+CFG = {
+ "stft_cfg": {
+ "sampling_rate": 8000,
+ "n_fft": 320,
+ "hop_size": 40,
+ "win_size": 320,
+ },
+ "model_cfg": {
+ "compress_factor": 0.3
+ },
+}
+
+
+def release(tmp_path):
+ for package, module, text in (
+ ("models", "stfts", STFTS),
+ ("utils", "util", UTIL),
+ ):
+ (tmp_path / package).mkdir()
+ (tmp_path / package / f"{module}.py").write_text(text)
+ saved = {
+ k: sys.modules.pop(k)
+ for k in list(sys.modules)
+ if k.split(".")[0] in ("models", "utils")
+ }
+ yield semamba.bind(str(tmp_path))
+ for k in [k for k in sys.modules if k.split(".")[0] in ("models", "utils")]:
+ del sys.modules[k]
+ sys.modules.update(saved)
+
+
+def test_sizes_scale_with_the_input_rate_and_stay_even():
+ for base, rate, expected in (
+ (320, 48000, 1920),
+ (40, 48000, 240),
+ (320, 44100, 1764),
+ (160, 22050, 442),
+ (320, 8000, 320),
+ ):
+ assert semamba.make_even(base * rate / 8000) == expected
+ assert semamba.make_even(3) == 4 and semamba.make_even(4) == 4
+
+
+def test_release_runs_at_the_input_rate_blanks_silent_frames_and_keeps_length(
+ release,):
+ util, stfts = release
+
+ def model(mag, pha):
+ amp = mag.clone()
+ # frame 1: more than half of its bins silent
+ amp[:, :amp.shape[1] // 2 + 2, 1] = 0
+ return amp, pha, None
+
+ enhance = semamba.enhancer(model, util, stfts, CFG, "cpu")
+ x = np.random.default_rng(0).standard_normal(48000).astype("float32")
+ y, rate = enhance("a.wav", x, 48000)
+ assert stfts.CALLS[-1] == (1920, 240, 1920) and rate == 48000
+ assert y.dtype == np.float32 and y.shape == x.shape
+ # frame 1 blanked whole, frame 2 kept
+ assert not y[240:480].any() and y[480:720].all()
+ enhance("b.wav", x[:16000], 16000)
+ assert stfts.CALLS[-1] == (640, 80, 640)
diff --git a/tests/bench/wrappers/test_writer.py b/tests/bench/wrappers/test_writer.py
new file mode 100644
index 0000000..abbd528
--- /dev/null
+++ b/tests/bench/wrappers/test_writer.py
@@ -0,0 +1,115 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The shared render loop of the wrappers.
+
+One process's inputs, outputs fitted to the input's length and written whole or
+not at all, failures reported and counted in the exit status.
+"""
+
+import os
+
+import numpy as np
+import pytest
+import soundfile as sf
+
+import writer
+
+
+def test_inputs_are_sorted_sharded_and_limited(tiny_set):
+ in_dir, _ = tiny_set
+ names = [os.path.basename(p) for p in writer.inputs(str(in_dir))]
+ assert names == ["item_0.wav", "item_1.wav", "item_2.wav"]
+ assert [os.path.basename(p) for p in writer.inputs(str(in_dir), "1/2")
+ ] == ["item_1.wav"]
+ assert len(writer.inputs(str(in_dir), limit=2)) == 2
+ with pytest.raises(ValueError):
+ writer.inputs(str(in_dir), "2/2")
+
+
+def test_fit_pads_or_trims_frame_rounding_and_refuses_a_cut_off_output():
+ x = np.ones(1000, dtype=np.float64)
+ assert writer.fit(x, 1010, 48000).dtype == np.float32
+ assert np.array_equal(
+ writer.fit(x, 1010, 48000)[1000:], np.zeros(10, dtype=np.float32))
+ assert len(writer.fit(x, 990, 48000)) == 990
+ with pytest.raises(ValueError, match="cut-off"):
+ writer.fit(x, 1000 + int(0.06 * 48000), 48000)
+
+
+def test_save_writes_float32_whole_or_not_at_all(tmp_path):
+ path = tmp_path / "a.wav"
+ writer.save(str(path), np.full(480, 0.123456789), 48000)
+ info = sf.info(str(path))
+ assert info.subtype == "FLOAT" and info.frames == 480
+ assert sf.read(str(path), dtype="float32")[0][0] == np.float32(0.123456789)
+ with pytest.raises(ValueError, match="NaN"):
+ writer.save(str(tmp_path / "b.wav"), np.array([0.0, np.nan]), 48000)
+ # no output, no partial file
+ assert sorted(os.listdir(tmp_path)) == ["a.wav"]
+
+
+def test_read_averages_channels(tmp_path):
+ sf.write(
+ tmp_path / "s.wav",
+ np.stack([np.ones(10), np.zeros(10)], 1),
+ 48000,
+ subtype="FLOAT",
+ )
+ samples, rate = writer.read(str(tmp_path / "s.wav"))
+ assert (rate == 48000 and samples.shape == (10,) and
+ samples[0] == np.float32(0.5))
+
+
+def test_render_resumes_reports_failures_and_exits_nonzero_unless_all_present(
+ tiny_set, capsys):
+ in_dir, out_dir = tiny_set
+ files = writer.inputs(str(in_dir))
+ os.makedirs(out_dir)
+ sf.write(
+ out_dir / "item_0.wav",
+ np.ones(24000, dtype="float32"),
+ 48000,
+ subtype="FLOAT",
+ )
+ seen = []
+
+ def enhance(path, samples, rate):
+ seen.append(os.path.basename(path))
+ if path.endswith("item_2.wav"):
+ # a cut-off output fails, never padded
+ return samples[:len(samples) // 2], rate
+ return np.concatenate([samples, np.zeros(37, dtype="float32")]), rate
+
+ assert writer.render(files, str(out_dir), enhance) == 1
+ # the existing output is kept, not re-run
+ assert seen == ["item_1.wav", "item_2.wav"]
+ assert sf.read(out_dir / "item_0.wav")[0].min() == 1.0
+ assert sf.info(str(out_dir / "item_1.wav")).frames == 36000
+ assert not (out_dir / "item_2.wav").exists()
+ out = capsys.readouterr().out
+ assert "FAIL item_2.wav" in out and "DONE 2/3" in out
+ assert writer.render(files, str(out_dir), lambda p, s, r: (s, r)) == 0
+ assert "DONE 3/3" in capsys.readouterr().out
+
+
+def test_render_refuses_another_input_rate(tiny_set, capsys):
+ in_dir, out_dir = tiny_set
+ assert (writer.render(
+ writer.inputs(str(in_dir)),
+ str(out_dir),
+ lambda p, s, r: (s, r),
+ expect_rate=16000,
+ ) == 1)
+ assert "expected 16000" in capsys.readouterr().out and not list(
+ out_dir.glob("*.wav"))
diff --git a/tests/conftest.py b/tests/conftest.py
new file mode 100644
index 0000000..e591927
--- /dev/null
+++ b/tests/conftest.py
@@ -0,0 +1,173 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Shared fixtures: tiny CPU-sized models.
+
+The models exercise every architecture branch: attention and Mamba blocks,
+the dual-mode knob with its film, and the plain two-sided model. ``tiny``
+hands a test the builders; the model fixtures build a fresh model per test,
+so a test that moves the mode knob cannot affect another. ``tiny_ckpt`` saves
+the identity model as a release safetensors file, for code that loads a path.
+"""
+
+import json
+import os
+import sys
+import types
+
+import pytest
+import torch
+
+sys.path.insert(
+ 0,
+ os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
+ "src"),
+)
+
+# pylint: disable=wrong-import-position
+from inworld.voice_isolation import model
+
+# pylint: enable=wrong-import-position
+
+FIXTURES = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures")
+
+TINY = dict(
+ width=16,
+ block_types=("transformer", "mamba"),
+ num_heads=2,
+ n_fft=64,
+ hop_length=16,
+ band_plan=((6000, 24000),),
+ chunk_seconds=1.0, # one render window for every test clip
+ overlap_seconds=0.25,
+)
+DUAL = dict(dual_mode=True,
+ lookahead_frames=0,
+ lookahead_frames_choices=(0, 2),
+ mode_film=True)
+WINDOWED = dict(causal=True,
+ lookahead_frames=0,
+ lookahead_frames_choices=(0, 2, 4),
+ attention_window_frames=8)
+
+
+def tiny_config(**overrides) -> model.VoiceIsolatorConfig:
+ kw = dict(TINY)
+ kw.update(overrides)
+ return model.VoiceIsolatorConfig(**kw)
+
+
+def randomize(m: model.VoiceIsolatorNetwork,
+ seed: int) -> model.VoiceIsolatorNetwork:
+ """Gives the zero-initialised heads and knobs random weights.
+
+ The model then changes its input, so tests can tell its modes apart.
+ """
+ g = torch.Generator().manual_seed(seed)
+ with torch.no_grad():
+ for head in m.denoise_decoder.heads:
+ head[-1].weight.copy_(
+ torch.randn(head[-1].weight.shape, generator=g) * 0.05)
+ if hasattr(m, "lookahead_embedding"):
+ m.lookahead_embedding.weight.copy_(
+ torch.randn(m.lookahead_embedding.weight.shape, generator=g) *
+ 0.1)
+ if hasattr(m, "mode_film"):
+ m.mode_film.weight.copy_(
+ torch.randn(m.mode_film.weight.shape, generator=g) * 0.05)
+ # The released decoders' condition is far from its zero init; a
+ # random one makes the decoder's controls matter in every test.
+ condition = m.denoise_decoder.condition
+ condition.weight.copy_(
+ torch.randn(condition.weight.shape, generator=g) * 0.2)
+ condition.bias.copy_(
+ torch.randn(condition.bias.shape, generator=g) * 0.1)
+ return m
+
+
+def build_identity(**overrides) -> model.VoiceIsolatorNetwork:
+ """A dual-mode model at initialisation: an exact identity in every mode."""
+ torch.manual_seed(0)
+ kw = dict(DUAL)
+ kw.update(overrides)
+ return model.VoiceIsolatorNetwork(tiny_config(**kw)).eval()
+
+
+def build_dual(seed: int = 1, **overrides) -> model.VoiceIsolatorNetwork:
+ """A dual-mode model (streaming positions 0 and 2) that changes audio."""
+ return randomize(build_identity(**overrides), seed)
+
+
+def build_offline(seed: int = 1) -> model.VoiceIsolatorNetwork:
+ """A plain two-sided model that changes audio."""
+ torch.manual_seed(0)
+ return randomize(model.VoiceIsolatorNetwork(tiny_config()).eval(), seed)
+
+
+def build_windowed(seed: int = 1, **overrides) -> model.VoiceIsolatorNetwork:
+ """A causal model with an eight-frame attention window and three
+ streaming positions (0, 2 and 4) that changes audio."""
+ torch.manual_seed(0)
+ kw = dict(WINDOWED)
+ kw.update(overrides)
+ return randomize(model.VoiceIsolatorNetwork(tiny_config(**kw)).eval(), seed)
+
+
[email protected](scope="session")
+def tiny():
+ """The builders: ``config``, ``identity``, ``dual``, ``offline`` and
+ ``windowed``."""
+ return types.SimpleNamespace(config=tiny_config,
+ identity=build_identity,
+ dual=build_dual,
+ offline=build_offline,
+ windowed=build_windowed)
+
+
+def dual_model():
+ return build_dual()
+
+
+def offline_model():
+ return build_offline()
+
+
+def windowed_model():
+ return build_windowed()
+
+
+def identity_model():
+ return build_identity()
+
+
[email protected](scope="module")
+def tiny_ckpt(tmp_path_factory, tiny): # pylint: disable=redefined-outer-name
+ """An identity-at-init dual-mode model as a release safetensors file."""
+ # pylint: disable-next=import-outside-toplevel
+ import safetensors.torch
+
+ m = tiny.identity()
+ folder = tmp_path_factory.mktemp("ckpt")
+ path = folder / "tiny.safetensors"
+ safetensors.torch.save_file(
+ {
+ k: v.contiguous() for k, v in m.state_dict().items()
+ },
+ str(path),
+ metadata={"config": json.dumps(m.config.to_dict())},
+ )
+ return str(path)
diff --git a/tests/demo/conftest.py b/tests/demo/conftest.py
new file mode 100644
index 0000000..701de61
--- /dev/null
+++ b/tests/demo/conftest.py
@@ -0,0 +1,38 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Demo tests import demo/*.py as plain modules."""
+
+import os
+import sys
+import wave
+
+import pytest
+
+REPO = os.path.dirname(
+ os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+sys.path.insert(0, os.path.join(REPO, "demo"))
+
+
+def example_directory(tmp_path):
+ """A folder holding one synthetic WAV."""
+ directory = tmp_path / "examples"
+ directory.mkdir()
+ path = directory / "synthetic_silence.wav"
+ with wave.open(str(path), "wb") as audio:
+ audio.setnchannels(1)
+ audio.setsampwidth(2)
+ audio.setframerate(48000)
+ audio.writeframes(b"\0\0" * 2400)
+ return directory
diff --git a/tests/demo/test_app.py b/tests/demo/test_app.py
new file mode 100644
index 0000000..986880c
--- /dev/null
+++ b/tests/demo/test_app.py
@@ -0,0 +1,714 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Two fixed-mode demo models, playback levels and browser file boundaries."""
+
+import asyncio
+import io
+import json
+import pathlib
+import sys
+from unittest import mock
+
+import numpy as np
+import pytest
+import soundfile as sf
+import torch
+
+from inworld import voice_isolation
+
+pytest.importorskip("gradio")
+
+# pylint: disable=wrong-import-position
+import fastapi
+from fastapi import testclient
+from gradio import route_utils
+import gradio as gr
+
+import app
+import example_audio
+import online
+
+# pylint: enable=wrong-import-position
+
+
[email protected](name="models")
+def loaded_models(tiny):
+ """Two independent tiny networks behind the actual public facade."""
+ offline = voice_isolation.VoiceIsolator(tiny.identity(),
+ device="cpu",
+ precision="fp32",
+ mode="offline")
+ realtime = voice_isolation.VoiceIsolator(tiny.identity(),
+ device="cpu",
+ precision="fp32",
+ mode="streaming",
+ lookahead_frames=2,
+ block_frames=4)
+ return app.DemoModels(offline, realtime)
+
+
+def test_models_load_once_in_fixed_modes_with_no_shared_network(models):
+ with mock.patch.object(voice_isolation.VoiceIsolator,
+ "load",
+ autospec=True,
+ side_effect=[models.offline,
+ models.realtime]) as load:
+ loaded = app.load_models("offline.safetensors", "online.safetensors",
+ "cpu", "fp32")
+ app.build_demo(loaded)
+ app.build_demo(loaded)
+
+ assert load.call_args_list == [
+ mock.call("offline.safetensors",
+ device="cpu",
+ mode="offline",
+ precision="fp32"),
+ mock.call("online.safetensors",
+ device="cpu",
+ mode="streaming",
+ precision="fp32",
+ lookahead_frames=2,
+ block_frames=4),
+ ]
+ assert loaded.offline is models.offline
+ assert loaded.realtime is models.realtime
+ assert (loaded.offline_name,
+ loaded.realtime_name) == ("offline.safetensors",
+ "online.safetensors")
+ assert loaded.offline.model is not loaded.realtime.model
+ assert loaded.offline_lock is not loaded.realtime_lock
+
+
[email protected]("message", ["checkpoint only streams", "bad checksum"])
+def test_checkpoint_errors_fail_startup_without_mode_fallback(message):
+ with mock.patch.object(voice_isolation.VoiceIsolator,
+ "load",
+ autospec=True,
+ side_effect=ValueError(message)) as load:
+ with pytest.raises(ValueError, match=message):
+ app.load_models("wrong.safetensors", "online.safetensors")
+
+ load.assert_called_once_with("wrong.safetensors",
+ device=None,
+ mode="offline",
+ precision="auto")
+
+
[email protected]("failure", ["mode", "shared network"])
+def test_startup_refuses_wrong_modes_and_shared_networks(models, failure):
+ if failure == "mode":
+ realtime = models.offline
+ message = "offline and a realtime"
+ else:
+ realtime = voice_isolation.VoiceIsolator(models.offline.model,
+ device="cpu",
+ mode="streaming",
+ lookahead_frames=2)
+ message = "separate model instance"
+
+ with mock.patch.object(voice_isolation.VoiceIsolator,
+ "load",
+ autospec=True,
+ side_effect=[models.offline, realtime]):
+ with pytest.raises(ValueError, match=message):
+ app.load_models()
+
+
+def test_pcm16_preserves_quiet_levels_and_clips_without_peak_normalizing():
+ samples = np.array([0.05, 0.5, -1.5, 1.5], dtype=np.float32)
+
+ played = app.pcm16(samples)
+
+ assert played.dtype == np.int16
+ assert played.tolist() == [
+ round(0.05 * 32767),
+ round(0.5 * 32767), -32767, 32767
+ ]
+ assert app.pcm16(np.zeros(0, dtype=np.float32)).shape == (0,)
+
+
[email protected]("input_level,voice_level", [(0.1, 0.025), (0.5, 1.25),
+ (-0.5, 1.25)])
+def test_offline_residual_uses_original_levels_before_playback_clipping(
+ models, input_level, voice_level):
+ audio = np.full(2400, input_level, dtype=np.float32)
+ voice = np.full(audio.shape, voice_level, dtype=np.float32)
+ background = audio - voice
+
+ with (mock.patch.object(models.offline,
+ "isolate",
+ autospec=True,
+ return_value=voice) as
+ isolate, mock.patch.object(models.realtime, "isolate",
+ autospec=True) as realtime,
+ mock.patch.object(app,
+ "spectrogram_png",
+ autospec=True,
+ side_effect=["voice-image",
+ "background-image"]) as image):
+ output = app.run_offline((48000, audio), models)
+
+ preview, voice_image, residual, background_image, timing = output
+ assert isolate.call_count == 1
+ np.testing.assert_array_equal(isolate.call_args.args[0], audio)
+ assert isolate.call_args.args[1] == 48000
+ assert isolate.call_args.kwargs == {"output_sample_rate": 48000}
+ realtime.assert_not_called()
+ assert preview[0] == residual[0] == 48000
+ np.testing.assert_array_equal(preview[1], app.pcm16(voice))
+ np.testing.assert_array_equal(residual[1], app.pcm16(background))
+ np.testing.assert_array_equal(image.call_args_list[0].args[0], voice)
+ np.testing.assert_array_equal(image.call_args_list[1].args[0], background)
+ assert (voice_image, background_image) == ("voice-image",
+ "background-image")
+ assert "processed in" in timing
+ if max(abs(voice_level), abs(float(background[0]))) <= 1:
+ rebuilt = (preview[1].astype(np.float32) + residual[1]) / 32767
+ np.testing.assert_allclose(rebuilt, audio, rtol=0, atol=1 / 32767)
+
+
+def test_offline_aligns_integer_stereo_before_background_subtraction(models):
+ rate = 22050
+ left = np.arange(-10000, 10000, 20, dtype=np.int16)
+ stereo = np.column_stack((left, np.flip(left) // 3))
+ mono = (stereo.astype(np.float32) / np.iinfo(stereo.dtype).max).mean(axis=1)
+ aligned = voice_isolation.resample(torch.from_numpy(mono), rate,
+ 48000).numpy()
+ voice = aligned * 0.3
+
+ with mock.patch.object(models.offline,
+ "isolate",
+ autospec=True,
+ return_value=voice) as isolate:
+ output = app.run_offline((rate, stereo), models)
+
+ np.testing.assert_array_equal(isolate.call_args.args[0], mono)
+ assert isolate.call_args.args[1] == rate
+ assert isolate.call_args.kwargs == {"output_sample_rate": 48000}
+ assert output[0][0] == output[2][0] == 48000
+ np.testing.assert_array_equal(output[0][1], app.pcm16(voice))
+ np.testing.assert_array_equal(output[2][1], app.pcm16(aligned - voice))
+
+
+ None, (48000, np.zeros(0)), (48000, np.array([np.nan])),
+ (48000, np.zeros((2, 2, 2)))
+])
+def test_invalid_recordings_fail_before_inference(models, audio):
+ with mock.patch.object(models.offline, "isolate", autospec=True) as isolate:
+ with pytest.raises(gr.Error):
+ app.run_offline(audio, models)
+
+ isolate.assert_not_called()
+
+
+def test_offline_rejects_misaligned_output_and_real_model_runs(models):
+ audio = np.full(2400, 0.05, dtype=np.float32)
+ with mock.patch.object(models.offline,
+ "isolate",
+ autospec=True,
+ return_value=audio[:-1]):
+ with pytest.raises(gr.Error, match="same length"):
+ app.run_offline((48000, audio), models)
+
+ result = app.run_offline((48000, audio), models)
+
+ assert result[0][1].shape == result[2][1].shape == audio.shape
+ np.testing.assert_allclose(result[0][1].astype(float) / 32767,
+ audio,
+ atol=2 / 32767,
+ rtol=0)
+
+
+def test_two_tabs_wire_online_events_to_per_browser_state(models):
+ demo = app.build_demo(models)
+ components = {item["id"]: item for item in demo.config["components"]}
+ events = demo.config["dependencies"]
+ tabs = [
+ item["props"]["label"]
+ for item in components.values()
+ if item["type"] == "tabitem"
+ ]
+ state = next(
+ item for item in components.values() if item["type"] == "state")
+ studio = next(item for item in components.values()
+ if item["props"].get("elem_id") == "live-studio")
+ player = next(item for item in components.values()
+ if item["props"].get("elem_id") == "online-result")
+ original = next(item for item in components.values()
+ if item["props"].get("elem_id") == "online-input")
+
+ assert tabs == ["Offline", "Online"]
+ assert demo.blocks[state["id"]].value is None
+ assert demo.blocks[state["id"]].delete_callback is online.close_recording
+ assert demo.blocks[state["id"]].time_to_live == 120
+ for name, method, outputs in [
+ ("record_start", "start",
+ [state["id"], studio["id"], player["id"], original["id"]]),
+ ("audio_chunk", "push", [state["id"], studio["id"]]),
+ ("record_finish", "finish",
+ [state["id"], studio["id"], player["id"], original["id"]]),
+ ]:
+ event = next(
+ item for item in events
+ if [studio["id"], name] in [list(t) for t in item["targets"]])
+ assert event["inputs"] == [state["id"]]
+ assert event["outputs"] == outputs
+ function = demo.fns[event["id"]]
+ assert function.fn.__name__ == method
+ assert function.fn.__self__.model is models.realtime
+ assert function.fn.__self__.model_lock is models.realtime_lock
+ assert event["api_visibility"] == "private"
+ assert event["queue"] is False
+ if name == "audio_chunk":
+ # A response watcher can send the next chunk before Gradio marks
+ # the previous event complete; "once" silently drops that chunk.
+ assert event["trigger_mode"] == "multiple"
+ assert not any(item["type"] == "dataset" for item in components.values())
+ unload = next(item for item in events
+ if any(target[1] == "unload" for target in item["targets"]))
+ assert demo.fns[unload["id"]].fn.__name__ == "release"
+
+
+def test_a_new_input_cancels_its_isolation_without_waiting_for_the_model(
+ models):
+ demo = app.build_demo(models)
+ events = demo.config["dependencies"]
+ click = next(
+ event for event in events if event["api_name"] == "isolate_offline")
+ changes = [
+ event for event in events
+ if any(target[1] == "change" for target in event["targets"])
+ ]
+
+ preview = demo.fns[changes[0]["id"]]
+
+ assert preview.fn is app.input_changed
+ assert preview.concurrency_id != demo.fns[click["id"]].concurrency_id
+ assert any(click["id"] in event["cancels"] for event in changes)
+
+
+def test_custom_examples_show_only_listed_audio(models, example_directory):
+ (example_directory / "private-note.txt").write_text("PRIVATE_NOTE",
+ encoding="utf-8")
+ examples = example_audio.load_examples(example_directory)
+
+ demo = app.build_demo(models, examples)
+
+ config = json.dumps(demo.config, default=str)
+ assert "synthetic_silence" in config
+ assert "PRIVATE_NOTE" not in config
+ assert any(item["type"] == "dataset" for item in demo.config["components"])
+
+
+def test_offline_downloads_keep_levels_and_input_changes_clear_results(
+ models, tmp_path, monkeypatch):
+ monkeypatch.setenv("GRADIO_TEMP_DIR", str(tmp_path / "cache"))
+ source = tmp_path / "input.wav"
+ sf.write(source,
+ np.full(2400, 3277, dtype=np.int16),
+ 48000,
+ subtype="PCM_16")
+ voice = np.full(2400, 0.025, dtype=np.float32)
+ demo = app.build_demo(models)
+ click = next(event for event in demo.config["dependencies"]
+ if event["api_name"] == "isolate_offline")
+ change = next(event for event in demo.config["dependencies"]
+ if any(target[1] == "change" for target in event["targets"]))
+ web_app = gr.mount_gradio_app(fastapi.FastAPI(), demo, path="/")
+
+ with (testclient.TestClient(web_app) as client,
+ mock.patch.object(models.offline,
+ "isolate",
+ autospec=True,
+ return_value=voice)):
+ with source.open("rb") as recording:
+ upload = client.post(
+ demo.config.get("api_prefix", "") + "/upload",
+ files={"files": (source.name, recording, "audio/wav")})
+ assert upload.status_code == 200
+ audio = {"path": upload.json()[0], "meta": {"_type": "gradio.FileData"}}
+ result = asyncio.run(demo.process_api(click["id"], [audio]))["data"]
+ for metadata, level in ((result[0], 0.025), (result[2],
+ 3277 / 32767 - 0.025)):
+ assert pathlib.Path(metadata["path"]).is_relative_to(
+ pathlib.Path(demo.GRADIO_CACHE))
+ response = client.get(metadata["url"])
+ assert response.status_code == 200
+ samples, rate = sf.read(io.BytesIO(response.content), dtype="int16")
+ assert rate == 48000
+ assert samples.tolist() == [round(level * 32767)] * len(voice)
+ changed = asyncio.run(demo.process_api(change["id"], [audio]))["data"]
+ cleared = asyncio.run(demo.process_api(change["id"], [None]))["data"]
+
+ assert changed[0] is not None
+ assert changed[1:] == [None, None, None, None, ""]
+ assert cleared == [None, None, None, None, None, ""]
+
+
[email protected]("bundled", [True, False])
+def test_main_loads_once_and_allows_only_named_example_files(
+ models, tmp_path, monkeypatch, bundled):
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.delenv("VOICE_ISOLATION_EXAMPLES", raising=False)
+ monkeypatch.setattr(sys, "argv",
+ ["app.py"] if bundled else ["app.py", "--examples", ""])
+ demo = mock.create_autospec(gr.Blocks, instance=True, spec_set=True)
+ demo.launch.return_value = (None, "http://localhost", None)
+ examples = example_audio.load_examples(
+ example_audio.DEFAULT_DIRECTORY) if bundled else None
+
+ calls = mock.Mock()
+ with (mock.patch.object(app,
+ "load_models",
+ autospec=True,
+ return_value=models) as
+ load, mock.patch.object(app, "warm_up", autospec=True) as warm,
+ mock.patch.object(app, "build_demo", autospec=True,
+ return_value=demo) as build):
+ calls.attach_mock(load, "load")
+ calls.attach_mock(warm, "warm_up")
+ calls.attach_mock(build, "build_demo")
+ app.main()
+
+ load.assert_called_once_with(app.registry.REPO_ID, app.registry.REPO_ID,
+ None, "auto")
+ warm.assert_called_once_with(models)
+ build.assert_called_once_with(models, examples)
+ assert [call[0] for call in calls.mock_calls
+ ] == ["load", "warm_up", "build_demo"]
+ launch = demo.launch.call_args.kwargs
+ assert launch["allowed_paths"] == ([row[0] for row in examples.rows]
+ if examples else [])
+ assert "api" not in launch["footer_links"]
+ assert ".show-api-divider" in launch["css"]
+ demo.block_thread.assert_called_once_with()
+
+
[email protected]("failure", ["no audio", "non-audio", "bad auth"])
+def test_main_rejects_invalid_startup_before_loading_models(
+ example_directory, monkeypatch, failure):
+ path = example_directory / "synthetic_silence.wav"
+ arguments = ["app.py", "--share", "--examples", str(example_directory)]
+ if failure == "no audio":
+ path.unlink()
+ elif failure == "non-audio":
+ path.write_bytes(b'{"private": "a disguised sidecar"}')
+ else:
+ arguments.extend(["--auth", "invalid"])
+ monkeypatch.setattr(sys, "argv", arguments)
+
+ with mock.patch.object(app, "load_models", autospec=True) as load:
+ with pytest.raises(SystemExit):
+ app.main()
+
+ load.assert_not_called()
+
+
[email protected]("variable",
+ ["GRADIO_TEMP_DIR", "GRADIO_EXAMPLES_CACHE"])
[email protected]("inside_cache", [False, True])
+def test_main_rejects_examples_in_gradio_cache(example_directory, monkeypatch,
+ capsys, variable, inside_cache):
+ cache = example_directory.parent if inside_cache else example_directory
+ monkeypatch.setenv(variable, str(cache))
+ monkeypatch.setattr(
+ sys, "argv",
+ ["app.py", "--examples", str(example_directory)])
+
+ with mock.patch.object(app, "load_models", autospec=True) as load:
+ with pytest.raises(SystemExit) as error:
+ app.main()
+
+ assert error.value.code == 2
+ assert "outside Gradio" in capsys.readouterr().err
+ load.assert_not_called()
+
+
+def test_routes_allow_examples_but_deny_private_sidecars(
+ models, example_directory, tmp_path, monkeypatch):
+ monkeypatch.setenv("GRADIO_TEMP_DIR", str(tmp_path / "cache"))
+ monkeypatch.chdir(tmp_path)
+ private_note = example_directory / "private-note.txt"
+ private_note.write_text("Private test note.", encoding="utf-8")
+ nested = example_directory / "private"
+ nested.mkdir()
+ nested_note = nested / "note.txt"
+ nested_note.write_text("Nested test note.", encoding="utf-8")
+ nested_audio = nested / "unlisted.wav"
+ nested_audio.write_bytes(
+ (example_directory / "synthetic_silence.wav").read_bytes())
+ linked_note = example_directory / "linked-note.txt"
+ linked_note.symlink_to(private_note)
+ examples = example_audio.load_examples(example_directory)
+ demo = app.build_demo(models, examples)
+ web_app = gr.mount_gradio_app(
+ fastapi.FastAPI(),
+ demo,
+ path="/",
+ allowed_paths=[row[0] for row in examples.rows])
+ prefix = demo.config.get("api_prefix", "") + "/file="
+
+ with testclient.TestClient(web_app) as client:
+ audio = client.get(prefix + examples.rows[0][0])
+ denied = [
+ client.get(prefix + str(path))
+ for path in (private_note, nested_note, nested_audio, linked_note)
+ ]
+
+ assert audio.status_code == 200
+ assert audio.content == pathlib.Path(examples.rows[0][0]).read_bytes()
+ assert all(response.status_code == 403 for response in denied)
+
+
[email protected]("device,kind,name,detail", [
+ ("cpu", "cpu", "CPU", "Apple M4 Max · 3 threads"),
+ ("mps", "metal", "Metal GPU", "Apple M4 Max"),
+ ("cuda", "gpu", "CUDA GPU", "NVIDIA L4"),
+])
+def test_devices_are_named_for_people(monkeypatch, device, kind, name, detail):
+ monkeypatch.setattr(app, "processor_name", lambda: "Apple M4 Max")
+ monkeypatch.setattr(torch, "get_num_threads", lambda: 3)
+ monkeypatch.setattr(torch.cuda, "get_device_name",
+ lambda device: "NVIDIA L4")
+
+ info = app.describe_device(device)
+
+ assert info == app.DeviceInfo(kind, name, detail)
+
+
+def test_processor_name_falls_back_to_the_machine_type(monkeypatch):
+
+ def unavailable(*args, **kwargs):
+ raise OSError("no sysctl")
+
+ monkeypatch.setattr(app.subprocess, "run", unavailable)
+ monkeypatch.setattr(app.platform, "processor", lambda: "")
+ monkeypatch.setattr(app.platform, "machine", lambda: "arm64")
+ monkeypatch.setattr(app.sys, "platform", "darwin")
+ app.processor_name.cache_clear()
+
+ try:
+ name = app.processor_name()
+ finally:
+ app.processor_name.cache_clear()
+
+ assert name == "arm64"
+
+
+def test_the_header_names_the_inference_device(models, monkeypatch):
+ monkeypatch.setattr(app, "processor_name", lambda: "Chip <b>&</b>")
+
+ header = app.header_html(models)
+ demo = app.build_demo(models)
+
+ assert header.count('class="device-badge device-cpu"') == 1
+ assert "Running on <strong>CPU</strong>" in header
+ assert "Chip &lt;b&gt;&amp;&lt;/b&gt;" in header and "<b>" not in header
+ assert "device-badge" in json.dumps(demo.config, default=str)
+
+
+def test_models_on_two_devices_get_one_badge_each(models, monkeypatch):
+ infos = {
+ "offline": app.DeviceInfo("cpu", "CPU", "Apple M4 Max · 4 threads"),
+ "realtime": app.DeviceInfo("metal", "Metal GPU", "Apple M4 Max"),
+ }
+ monkeypatch.setattr(
+ app, "describe_device", lambda device: infos[
+ "offline" if device is models.offline.device else "realtime"])
+ monkeypatch.setattr(models.realtime, "device", torch.device("meta"))
+
+ header = app.header_html(models)
+
+ assert "Offline: Running on <strong>CPU</strong>" in header
+ assert "Online: Running on <strong>Metal GPU</strong>" in header
+
+
+def test_offline_timing_names_the_device(models):
+ audio = np.full(2400, 0.05, dtype=np.float32)
+
+ timing = app.run_offline((48000, audio), models)[-1]
+
+ assert timing.endswith("× real time on CPU")
+
+
+def test_input_spectrograms_share_the_outputs_frequency_axis():
+ rate = 16000
+ audio = (0.3 * np.sin(2 * np.pi * 3000 * np.arange(rate) / rate)).astype(
+ np.float32)
+ at_48k = voice_isolation.resample(torch.from_numpy(audio), rate,
+ 48000).numpy()
+
+ image = app.spectrogram_png(audio, rate)
+
+ assert image.shape == app.spectrogram_png(at_48k).shape
+ rows = image.shape[0]
+ loudest = int(np.argmax(image.astype(int).sum(axis=(1, 2))))
+ # 3 kHz sits an eighth of the way up a 0-24 kHz axis (row 0 is the top).
+ assert abs((rows - 1 - loudest) / (rows - 1) - 3000 / 24000) < 0.01
+
+
+def test_warm_up_runs_both_models_through_a_crossfade(models):
+ with (mock.patch.object(models.offline,
+ "isolate",
+ wraps=models.offline.isolate) as isolate,
+ mock.patch.object(models.realtime,
+ "stream",
+ wraps=models.realtime.stream) as stream):
+ app.warm_up(models)
+
+ isolate.assert_called_once()
+ assert isolate.call_args.args[1] == 48000
+ stream.assert_called_once_with(window_frames=8, crossfade_frames=4)
+
+
+def test_two_models_on_the_apple_gpu_share_one_lock(models, monkeypatch):
+ monkeypatch.setattr(models.offline, "device", torch.device("mps"))
+ monkeypatch.setattr(models.realtime, "device", torch.device("mps"))
+
+ shared = app.DemoModels(models.offline, models.realtime)
+
+ assert shared.realtime_lock is shared.offline_lock
+ assert models.realtime_lock is not models.offline_lock
+
+
+def test_the_cache_sweep_keeps_the_samples(models, example_directory):
+ examples = example_audio.load_examples(example_directory)
+ demo = app.build_demo(models, examples)
+ copies = set().union(*demo.temp_file_sets)
+
+ # Gradio's hourly sweep, with every file old enough to go.
+ route_utils.delete_files_created_by_app(demo, 0)
+
+ assert copies
+ assert all(pathlib.Path(path).exists() for path in copies)
+
+
[email protected]("name,subtype,file_format", [
+ ("extensible.wav", "FLOAT", "WAVEX"),
+ ("double.wav", "DOUBLE", "WAV"),
+ ("lossless.flac", "PCM_24", "FLAC"),
+])
+def test_uploads_decode_at_their_own_level(tmp_path, name, subtype,
+ file_format):
+ path = tmp_path / name
+ tone = (0.5 * np.sin(np.arange(9600) / 7)).astype(np.float32)
+ sf.write(path,
+ np.column_stack((tone, tone)),
+ 96000,
+ subtype=subtype,
+ format=file_format)
+
+ rate, audio = app.load_input(str(path))
+
+ assert rate == 96000
+ np.testing.assert_allclose(audio, tone, atol=1e-6)
+
+
+def test_offline_refuses_inputs_longer_than_its_limit(tmp_path, monkeypatch,
+ models):
+ monkeypatch.setattr(app, "MAX_OFFLINE_SECONDS", 1)
+ path = tmp_path / "long.wav"
+ sf.write(path, np.zeros(96000, dtype=np.float32), 48000)
+
+ with mock.patch.object(models.offline, "isolate", autospec=True) as isolate:
+ with pytest.raises(gr.Error, match="takes up to"):
+ app.run_offline(str(path), models)
+
+ isolate.assert_not_called()
+
+
+def test_rates_sharing_few_factors_with_48k_are_resampled_first(models):
+ rate = 7993
+ audio = np.random.RandomState(3).normal(0, 0.1, rate).astype(np.float32)
+
+ with mock.patch.object(models.offline,
+ "isolate",
+ wraps=models.offline.isolate) as isolate:
+ voice, _, background, _, _ = app.run_offline((rate, audio), models)
+
+ assert isolate.call_args.args[1] == 48000
+ assert voice[1].shape == background[1].shape
+ assert abs(voice[1].size - 48000) <= 1
+
+
+def test_an_unusable_input_still_clears_the_previous_results(tmp_path):
+ path = tmp_path / "empty.wav"
+ sf.write(path, np.zeros(0, dtype=np.float32), 48000)
+
+ with mock.patch.object(app.gr, "Warning", autospec=True) as warning:
+ cleared = app.input_changed(str(path))
+
+ assert cleared == (None, None, None, None, None, "")
+ warning.assert_called_once()
+
+
[email protected]("spec,mode,name", [
+ ("inworld/voice-isolator", "offline", "voice-isolator-v1"),
+ ("inworld/voice-isolator", "streaming", "voice-isolator-v1-realtime"),
+ ("voice-isolator-v1-realtime", "streaming", "voice-isolator-v1-realtime"),
+ ("hf://org/repo/sub/realtime.safetensors@main", "streaming",
+ "sub/realtime.safetensors"),
+ ("/checkpoints/run7/ema.safetensors", "offline", "ema.safetensors"),
+])
+def test_checkpoints_are_named_as_released_or_by_file(spec, mode, name):
+ assert app.model_name(spec, mode) == name
+
+
+def test_each_tab_names_its_own_model(models):
+ named = app.DemoModels(models.offline,
+ models.realtime,
+ offline_name="offline-ckpt.safetensors",
+ realtime_name="live-ckpt.safetensors")
+ lookahead_ms = round(models.realtime.lookahead_frames *
+ models.realtime.frame_seconds * 1000)
+
+ demo = app.build_demo(named)
+
+ texts = [
+ item["props"].get("value") or ""
+ for item in demo.config["components"]
+ if item["type"] == "markdown"
+ ]
+ offline_intro = next(text for text in texts if "offline-ckpt" in text)
+ online_intro = next(text for text in texts if "live-ckpt" in text)
+ assert "different model" in offline_intro
+ assert "live-ckpt" not in offline_intro
+ assert "separate model" in online_intro
+ assert "offline-ckpt" not in online_intro
+ assert f"{lookahead_ms} ms ahead" in online_intro
+
+
+def test_a_superseded_isolation_gives_way_without_running(models):
+ audio = np.full(2400, 0.05, dtype=np.float32)
+
+ with mock.patch.object(models.offline, "isolate", autospec=True) as isolate:
+ result = app.run_offline((48000, audio),
+ models,
+ superseded=lambda: True)
+
+ isolate.assert_not_called()
+ assert list(result) == [gr.skip()] * 5
+
+
+def test_a_newer_request_supersedes_only_its_own_browsers():
+ latest = app.LatestRequests()
+ first = latest.begin(gr.Request(session_hash="tab"))
+ other = latest.begin(gr.Request(session_hash="other tab"))
+
+ second = latest.begin(gr.Request(session_hash="tab"))
+ latest.forget(gr.Request(session_hash="other tab"))
+
+ assert first() and not second()
+ assert other()
diff --git a/tests/demo/test_build_examples.py b/tests/demo/test_build_examples.py
new file mode 100644
index 0000000..fe6f36e
--- /dev/null
+++ b/tests/demo/test_build_examples.py
@@ -0,0 +1,71 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Checks offline example generation and source-integrity enforcement."""
+
+import hashlib
+import pathlib
+
+import numpy as np
+import pytest
+import soundfile as sf
+
+import build_examples
+import example_audio
+
+
+def test_builds_the_two_generated_examples_without_external_audio(tmp_path):
+ build_examples.build_examples(tmp_path)
+
+ written = sorted(path.name for path in tmp_path.iterdir())
+ assert written == ["sample_14.wav", "sample_15.wav"]
+ listed = {
+ pathlib.Path(row[0]).name for row in example_audio.load_examples(
+ example_audio.DEFAULT_DIRECTORY).rows
+ }
+ assert set(written) <= listed
+ for name in written:
+ audio, rate = sf.read(tmp_path / name)
+ assert rate == 48000
+ assert audio.ndim == 1
+ assert 8 <= len(audio) / rate <= 12
+ assert np.isfinite(audio).all()
+ assert 0 < np.max(np.abs(audio)) <= 0.951
+ first = [
+ hashlib.sha256((tmp_path / name).read_bytes()).hexdigest()
+ for name in written
+ ]
+
+ build_examples.build_examples(tmp_path)
+
+ assert first == [
+ hashlib.sha256((tmp_path / name).read_bytes()).hexdigest()
+ for name in written
+ ]
+
+
+def test_changed_source_is_refused_before_writing(tmp_path, monkeypatch):
+ source = tmp_path / "sources"
+ source.mkdir()
+ (source / "input.flac").write_bytes(b"changed recording")
+ recipe = dict(build_examples.RECIPES[0],
+ source="sources/input.flac",
+ source_sha256="0" * 64)
+ monkeypatch.setattr(build_examples, "EXAMPLES", tmp_path)
+ monkeypatch.setattr(build_examples, "RECIPES", (recipe,))
+ destination = tmp_path / "output"
+
+ with pytest.raises(ValueError, match="Source SHA-256 mismatch"):
+ build_examples.build_examples(destination)
+
+ assert not destination.exists()
diff --git a/tests/demo/test_example_audio.py b/tests/demo/test_example_audio.py
new file mode 100644
index 0000000..2612886
--- /dev/null
+++ b/tests/demo/test_example_audio.py
@@ -0,0 +1,125 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Only the decodable audio files of the examples folder are offered."""
+
+import numpy as np
+import pytest
+import soundfile as sf
+
+import example_audio
+
+
+def test_load_lists_audio_files_in_name_order_labelled_by_name(
+ example_directory):
+ (example_directory / "private-note.txt").write_text("Not for the browser.",
+ encoding="utf-8")
+ (example_directory / "nested").mkdir()
+ (example_directory / "nested" / "inner.wav").write_bytes(
+ (example_directory / "synthetic_silence.wav").read_bytes())
+ for name in ("sample_10.flac", "sample_2.wav"):
+ sf.write(example_directory / name, np.zeros(4800), 48000)
+
+ examples = example_audio.load_examples(example_directory)
+
+ assert examples.rows == [[str(example_directory / "sample_2.wav")],
+ [str(example_directory / "sample_10.flac")],
+ [str(example_directory / "synthetic_silence.wav")]]
+ assert examples.labels == ["sample_2", "sample_10", "synthetic_silence"]
+
+
[email protected]("kind", ["missing", "empty"])
+def test_load_requires_a_folder_with_audio(tmp_path, kind):
+ directory = tmp_path / "examples"
+ if kind == "empty":
+ directory.mkdir()
+ (directory / "note.txt").write_text("no audio", encoding="utf-8")
+
+ with pytest.raises(ValueError, match="No example"):
+ example_audio.load_examples(directory)
+
+
+def test_load_rejects_linked_audio(example_directory):
+ target = example_directory.parent / "private.wav"
+ target.write_bytes(
+ (example_directory / "synthetic_silence.wav").read_bytes())
+ (example_directory / "linked.wav").symlink_to(target)
+
+ with pytest.raises(ValueError, match="regular"):
+ example_audio.load_examples(example_directory)
+
+
+def test_bundled_examples_load_with_distinct_labels():
+ examples = example_audio.load_examples(example_audio.DEFAULT_DIRECTORY)
+
+ assert examples.rows and len(examples.rows) == len(examples.labels)
+ assert len(set(examples.labels)) == len(examples.labels)
+ for row in examples.rows:
+ info = sf.info(row[0])
+ assert (info.samplerate, info.channels) == (48000, 1)
+
+
+def _replace_audio(directory, name, content):
+ (directory / "synthetic_silence.wav").unlink()
+ (directory / name).write_bytes(content)
+
+
[email protected]("suffix", ["wav", "flac", "mp3", "ogg"])
+ "content",
+ [b'{"private": "sidecar content"}', b"<html>Private note</html>"])
+def test_load_rejects_disguised_sidecars(example_directory, suffix, content):
+ _replace_audio(example_directory, "disguised." + suffix, content)
+
+ with pytest.raises(ValueError, match="Cannot decode example audio"):
+ example_audio.load_examples(example_directory)
+
+
[email protected]("suffix,format_name,subtype",
+ [("wav", "WAV", "PCM_16"), ("flac", "FLAC", "PCM_16"),
+ ("mp3", "MP3", "MPEG_LAYER_III"),
+ ("ogg", "OGG", "VORBIS")])
+def test_load_accepts_decodable_advertised_formats(example_directory, tmp_path,
+ suffix, format_name,
+ subtype):
+ if not sf.check_format(format_name, subtype):
+ pytest.skip(f"libsndfile cannot encode the {format_name} test fixture")
+ source = tmp_path / ("generated." + suffix)
+ sf.write(source, np.zeros(4800), 48000, format=format_name, subtype=subtype)
+ _replace_audio(example_directory, source.name, source.read_bytes())
+
+ examples = example_audio.load_examples(example_directory)
+
+ assert examples.rows == [[str(example_directory / source.name)]]
+
+
+def test_load_rejects_valid_audio_with_a_mismatched_suffix(example_directory):
+ content = (example_directory / "synthetic_silence.wav").read_bytes()
+ _replace_audio(example_directory, "wrong.flac", content)
+
+ with pytest.raises(ValueError, match="format does not match"):
+ example_audio.load_examples(example_directory)
+
+
[email protected]("kind", ["truncated", "empty", "nonfinite"])
+def test_load_rejects_invalid_audio_payloads(example_directory, tmp_path, kind):
+ source = tmp_path / "invalid.wav"
+ samples = np.array([float("nan")]) if kind == "nonfinite" else np.zeros(0)
+ sf.write(source, samples, 48000, subtype="FLOAT")
+ content = source.read_bytes()
+ if kind == "truncated":
+ content = content[:14]
+ _replace_audio(example_directory, source.name, content)
+
+ with pytest.raises(ValueError, match="decode|empty|non-finite"):
+ example_audio.load_examples(example_directory)
diff --git a/tests/demo/test_live.py b/tests/demo/test_live.py
new file mode 100644
index 0000000..d866ea1
--- /dev/null
+++ b/tests/demo/test_live.py
@@ -0,0 +1,215 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The microphone uses one stream, preserving chunk boundaries and levels."""
+
+import json
+import threading
+
+import numpy as np
+import pytest
+
+from inworld import voice_isolation
+import live
+
+
+def _isolator(network):
+ return voice_isolation.VoiceIsolator(network,
+ device="cpu",
+ precision="fp32",
+ mode="streaming",
+ lookahead_frames=2,
+ block_frames=4)
+
+
+def test_incremental_microphone_matches_a_whole_stream(windowed_model):
+ isolator = _isolator(windowed_model)
+ samples = np.random.RandomState(7).normal(0, 0.02, 4003).astype(np.float32)
+ expected = isolator.isolate(samples, 48000)
+ session = live.LiveSession(isolator)
+
+ for chunk in np.array_split(samples, 7):
+ update = session.push((48000, chunk))
+ rate, actual = session.finish()
+
+ assert not update.finished
+ assert update.output_seconds > 0
+ assert rate == 48000
+ assert actual.shape == samples.shape
+ np.testing.assert_allclose(actual, expected, atol=2e-6)
+ np.testing.assert_array_equal(session.finish()[1], actual)
+ assert session.push((48000, samples)).finished
+ np.testing.assert_array_equal(session.finish()[1], actual)
+
+
[email protected]("rate", [16000, 44100])
+def test_resampling_preserves_fractional_positions_and_flushes_tail(
+ identity_model, rate):
+ soxr = pytest.importorskip("soxr")
+ samples = (0.05 * np.sin(np.arange(1103) * 0.07)).astype(np.float32)
+ expected = soxr.resample(samples, rate, 48000)
+ session = live.LiveSession(_isolator(identity_model))
+
+ for chunk in np.array_split(samples, 13):
+ session.push((rate, chunk))
+ out_rate, actual = session.finish()
+
+ assert out_rate == 48000
+ assert actual.shape == expected.shape
+ np.testing.assert_allclose(actual, expected, atol=1e-7)
+ assert session.snapshot().input_seconds == pytest.approx(
+ len(samples) / rate)
+
+
+def test_integer_stereo_audio_keeps_its_absolute_level(identity_model):
+ pcm = np.tile(
+ np.array([[-32768, 0], [0, 32767], [1000, 3000]], dtype=np.int16),
+ (101, 1))
+ expected = (pcm.astype(np.float32) / 32768).mean(axis=1)
+ session = live.LiveSession(_isolator(identity_model))
+
+ session.push((48000, pcm))
+ _, actual = session.finish()
+
+ np.testing.assert_allclose(actual, expected, atol=1e-7)
+ assert actual.max() < 0.51
+
+
+def test_two_browsers_have_independent_streams_and_recordings(windowed_model):
+ isolator = _isolator(windowed_model)
+ first = np.random.RandomState(2).normal(0, 0.02, 2033).astype(np.float32)
+ second = np.random.RandomState(3).normal(0, 0.04, 2033).astype(np.float32)
+ expected = [isolator.isolate(x, 48000) for x in (first, second)]
+ model_lock = threading.Lock()
+ sessions = [
+ live.LiveSession(isolator, model_lock=model_lock) for _ in range(2)
+ ]
+
+ for offset in range(0, first.size, 137):
+ for session, samples in zip(sessions, (first, second)):
+ session.push((48000, samples[offset:offset + 137]))
+ actual = [session.finish()[1] for session in sessions]
+
+ for result, reference in zip(actual, expected):
+ np.testing.assert_allclose(result, reference, atol=2e-6)
+ assert not np.allclose(actual[0], actual[1])
+
+
[email protected]("rate", [44100, 48000])
+def test_recording_limit_caps_audio_and_automatically_finishes(
+ identity_model, rate):
+ if rate != 48000:
+ pytest.importorskip("soxr")
+ session = live.LiveSession(_isolator(identity_model), max_seconds=0.02)
+ samples = np.zeros(rate // 10, dtype=np.float32)
+
+ update = session.push((rate, samples))
+ _, actual = session.finish()
+
+ assert update.limit_reached and update.finished
+ assert update.input_seconds == pytest.approx(0.02)
+ assert actual.shape == (960,)
+ session.push((rate, samples))
+ np.testing.assert_array_equal(session.finish()[1], actual)
+
+
+def test_visualizations_are_bounded_aligned_and_json_serializable(
+ identity_model):
+ session = live.LiveSession(_isolator(identity_model), window_seconds=0.01)
+ samples = np.full(1600, 0.03, dtype=np.float32)
+
+ session.push((48000, samples))
+ session.finish()
+ update = session.snapshot()
+ data = update.visualization
+
+ assert data["end_seconds"] - data["start_seconds"] == pytest.approx(0.01)
+ assert data["end_seconds"] == pytest.approx(samples.size / 48000)
+ assert len(data["input"]["waveform"]) == live.WAVEFORM_BINS
+ spec = np.asarray(data["output"]["spectrogram"])
+ assert spec.shape == (live.FREQUENCY_BINS, live.TIME_BINS)
+ assert 0 <= spec.min() <= spec.max() <= 255
+ np.testing.assert_allclose(data["input"]["waveform"],
+ data["output"]["waveform"],
+ atol=1e-7)
+ assert json.loads(json.dumps(data, allow_nan=False))["sample_rate"] == 48000
+
+
+def test_changed_sample_rate_requires_a_new_recording(identity_model):
+ session = live.LiveSession(_isolator(identity_model))
+ samples = np.zeros(100, dtype=np.float32)
+ session.push((48000, samples))
+
+ with pytest.raises(ValueError, match="sample rate changed"):
+ session.push((44100, samples))
+
+ assert session.finish()[1].size == samples.size
+
+
+ (0, np.zeros(10)),
+ (48000.5, np.zeros(10)),
+ (48000, np.zeros((2, 3, 4))),
+ (48000, np.array([np.nan])),
+ (48000, np.array([np.inf])),
+ (48000, np.array(["not audio"])),
+])
+def test_invalid_microphone_input_does_not_enter_the_stream(
+ identity_model, audio):
+ session = live.LiveSession(_isolator(identity_model))
+
+ with pytest.raises(ValueError):
+ session.push(audio)
+
+ assert session.finish()[1].size == 0
+
+
+def test_empty_recording_and_reset_release_the_session(identity_model):
+ session = live.LiveSession(_isolator(identity_model))
+
+ assert session.push(None).input_seconds == 0
+ assert session.finish()[1].size == 0
+ session.reset()
+
+ update = session.snapshot()
+ assert update.finished and update.output_seconds == 0
+ assert update.visualization["input"]["waveform"] == []
+ assert session.finish()[1].size == 0
+
+
+def test_live_session_rejects_an_offline_model(identity_model):
+ isolator = voice_isolation.VoiceIsolator(identity_model, device="cpu")
+
+ with pytest.raises(ValueError, match="realtime model"):
+ live.LiveSession(isolator)
+
+
[email protected]("rate", [48000, 16000])
+def test_the_recorded_input_is_the_streamed_audio_aligned_with_the_voice(
+ windowed_model, rate):
+ soxr = pytest.importorskip("soxr")
+ samples = (0.05 * np.sin(np.arange(2207) * 0.05)).astype(np.float32)
+ expected = (samples if rate == 48000 else soxr.resample(
+ samples, rate, 48000))
+ session = live.LiveSession(_isolator(windowed_model))
+
+ for chunk in np.array_split(samples, 5):
+ session.push((rate, chunk))
+ _, voice = session.finish()
+ recorded_rate, recorded = session.recorded()
+ session.reset()
+
+ assert recorded_rate == 48000
+ assert recorded.shape == voice.shape == expected.shape
+ np.testing.assert_allclose(recorded, expected, atol=1e-7)
+ assert session.recorded()[1].size == 0
diff --git a/tests/demo/test_online.py b/tests/demo/test_online.py
new file mode 100644
index 0000000..5f037c1
--- /dev/null
+++ b/tests/demo/test_online.py
@@ -0,0 +1,459 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Browser event ordering and isolated microphone recordings."""
+
+import base64
+import threading
+import time
+from unittest import mock
+
+import numpy as np
+import pytest
+import soundfile as sf
+
+from inworld import voice_isolation
+import live
+
+pytest.importorskip("gradio")
+
+# pylint: disable=wrong-import-position
+import gradio as gr
+
+import online
+
+# pylint: enable=wrong-import-position
+
+
[email protected](name="server")
+def online_server(identity_model, monkeypatch, tmp_path):
+ """A real tiny model with player files confined to the test directory."""
+ monkeypatch.setenv("GRADIO_TEMP_DIR", str(tmp_path))
+ model = voice_isolation.VoiceIsolator(identity_model,
+ device="cpu",
+ precision="fp32",
+ mode="streaming",
+ lookahead_frames=2)
+ return online.Online(model, threading.RLock())
+
+
+def _event(take="first", **data):
+ return gr.EventData(None, {"take": take, **data})
+
+
+def _pcm(samples):
+ """Base64 little-endian 16-bit PCM, as the browser sends it."""
+ scaled = np.round(np.asarray(samples, dtype=np.float64) * 32768)
+ pcm = np.clip(scaled, -32768, 32767).astype("<i2")
+ return base64.b64encode(pcm.tobytes()).decode()
+
+
+def _request(browser):
+ return gr.Request(session_hash=browser)
+
+
+def _push(server, recording, sequence, samples, rate=48000, take="first"):
+ return server.push(
+ recording, _event(take, sequence=sequence, pcm=_pcm(samples),
+ rate=rate))
+
+
+def _preview(audio):
+ samples, rate = sf.read(audio.value["path"], dtype="int16")
+ assert rate == 48000
+ return samples
+
+
+def test_ordered_chunks_finish_once_and_keep_playback_at_its_own_level(server):
+ recording, ready, audio, original = server.start(None, _event())
+ first = np.full(503, 0.03, dtype=np.float32)
+ last = np.full(211, -0.02, dtype=np.float32)
+
+ recording, active = _push(server, recording, 1, first)
+ recording, _ = _push(server, recording, 2, last)
+ same, final, player, original_after = server.finish(
+ recording, _event(sequence=2, listen=True))
+ _, repeated, repeated_player, _ = server.finish(
+ recording, _event(sequence=2, listen=False))
+
+ assert ready["phase"] == "ready" and ready["sequence"] == 0
+ assert audio is None and original is None
+ assert active["phase"] == "active" and active["sequence"] == 1
+ assert same is recording
+ assert final["phase"] == repeated["phase"] == "finished"
+ # The browser starts playback itself once the player has loaded.
+ assert not player.autoplay and not repeated_player.autoplay
+ expected = np.round(np.concatenate((first, last)) * 32767).astype(np.int16)
+ np.testing.assert_allclose(_preview(player), expected, atol=1)
+ np.testing.assert_array_equal(_preview(repeated_player), _preview(player))
+ np.testing.assert_allclose(_preview(original_after), expected, atol=1)
+ assert not original_after.autoplay
+ assert final["input_seconds"] == pytest.approx(expected.size / 48000)
+
+
+def test_a_new_take_releases_the_previous_recording(server):
+ previous, *_ = server.start(None, _event("previous"))
+ _push(server, previous, 1, np.ones(200, dtype=np.float32), take="previous")
+
+ current, response, audio, original = server.start(previous,
+ _event("current"))
+
+ assert current is not previous
+ assert current.sequence == 0
+ assert response["take"] == "current" and response["input_seconds"] == 0
+ assert audio is None and original is None
+ assert previous.session.snapshot().finished
+ assert previous.session.finish()[1].size == 0
+
+
+def test_late_events_from_a_previous_take_do_not_touch_the_current_one(server):
+ current, *_ = server.start(None, _event("current"))
+
+ state, response = _push(server, current, 1, np.ones(100), take="previous")
+ ended, final, player, original = server.finish(
+ current, _event("previous", sequence=0))
+
+ assert state is ended is current
+ for answer in (response, final):
+ assert answer["phase"] == "error" and answer["take"] == "previous"
+ assert player == original == gr.skip()
+ assert current.sequence == 0
+ assert current.session.snapshot().input_seconds == 0
+
+
[email protected]("sequence", [1, 3])
+def test_duplicate_or_missing_chunks_abort_instead_of_replaying_audio(
+ server, sequence):
+ recording, *_ = server.start(None, _event())
+ _push(server, recording, 1, np.zeros(100, dtype=np.float32))
+
+ _, response = _push(server, recording, sequence,
+ np.zeros(100, dtype=np.float32))
+
+ assert response["phase"] == "error"
+ assert "order" in response["message"]
+ assert recording.session.snapshot().finished
+ assert recording.session.finish()[1].size == 0
+
+
+def test_finish_before_the_last_chunk_is_acknowledged_reports_it(server):
+ recording, *_ = server.start(None, _event())
+ _push(server, recording, 1, np.zeros(100, dtype=np.float32))
+
+ _, early, voice, original = server.finish(recording, _event(sequence=2))
+
+ assert early["phase"] == "error" and "did not reach" in early["message"]
+ assert voice == original == gr.skip()
+ assert not recording.session.snapshot().finished
+ _push(server, recording, 2, np.zeros(37, dtype=np.float32))
+ _, response, audio, _ = server.finish(recording, _event(sequence=2))
+ assert response["phase"] == "finished"
+ assert _preview(audio).size == 137
+
+
+def test_two_browser_states_remain_independent_on_one_server(server):
+ first, *_ = server.start(None, _event("first"))
+ second, *_ = server.start(None, _event("second"))
+
+ _push(server, first, 1, np.full(200, 0.01, dtype=np.float32), take="first")
+ _push(server,
+ second,
+ 1,
+ np.full(307, -0.02, dtype=np.float32),
+ take="second")
+ _, _, first_audio, _ = server.finish(first, _event("first", sequence=1))
+ _, _, second_audio, _ = server.finish(second, _event("second", sequence=1))
+
+ assert _preview(first_audio).shape == (200,)
+ assert _preview(second_audio).shape == (307,)
+ np.testing.assert_allclose(_preview(first_audio),
+ round(0.01 * 32767),
+ atol=1)
+ np.testing.assert_allclose(_preview(second_audio),
+ round(-0.02 * 32767),
+ atol=1)
+
+
+def test_the_duration_cap_reports_to_the_browser_and_ignores_late_audio(server):
+ session = live.LiveSession(server.model,
+ max_seconds=0.02,
+ model_lock=server.model_lock)
+ recording = online.Recording("first", session)
+
+ _, capped = _push(server, recording, 1, np.zeros(1200, dtype=np.float32))
+ _push(server, recording, 2, np.ones(100, dtype=np.float32))
+ _, final, audio, _ = server.finish(recording, _event(sequence=2))
+
+ assert capped["limit_reached"] and final["limit_reached"]
+ assert final["input_seconds"] == pytest.approx(0.02)
+ np.testing.assert_array_equal(_preview(audio), np.zeros(960,
+ dtype=np.int16))
+
+
+ {
+ "rate": 0,
+ "pcm": _pcm([0.0])
+ },
+ {
+ "rate": 48000.5,
+ "pcm": _pcm([0.0])
+ },
+ {
+ "rate": 48000,
+ "pcm": [0.0]
+ },
+ {
+ "rate": 48000,
+ "pcm": "not audio!"
+ },
+ {
+ "rate": 48000,
+ "pcm": base64.b64encode(b"odd").decode()
+ },
+ {
+ "rate": 48000,
+ "pcm": _pcm(np.zeros(48001))
+ },
+])
+def test_invalid_browser_audio_is_rejected_before_sequence_advances(
+ server, data):
+ recording, *_ = server.start(None, _event())
+
+ _, response = server.push(recording, _event(sequence=1, **data))
+
+ assert response["phase"] == "error"
+ assert recording.sequence == 0
+ assert recording.session.snapshot().input_seconds == 0
+ assert recording.session.snapshot().finished
+
+
[email protected]("sequence", [True, 1.0])
+def test_chunk_sequence_is_an_integer_counter(server, sequence):
+ recording, *_ = server.start(None, _event())
+
+ _, response = _push(server, recording, sequence, np.zeros(10))
+
+ assert response["phase"] == "error"
+ assert recording.sequence == 0
+
+
+def test_expiring_browser_state_releases_its_recording(server):
+ recording, *_ = server.start(None, _event())
+ _push(server, recording, 1, np.full(500, 0.01, dtype=np.float32))
+
+ online.close_recording(recording)
+ online.close_recording(None)
+
+ assert recording.session.snapshot().finished
+ assert recording.session.finish()[1].size == 0
+
+
+def test_finish_returns_the_unprocessed_input_beside_the_voice(server):
+ labelled = online.Online(server.model, server.model_lock, "Metal GPU")
+ recording, ready, *_ = labelled.start(None, _event())
+ noisy = np.linspace(-0.5, 0.5, 701, dtype=np.float32)
+ recording, active = _push(labelled, recording, 1, noisy)
+ silent = (48000, np.zeros(noisy.size, dtype=np.float32))
+
+ with mock.patch.object(recording.session,
+ "finish",
+ autospec=True,
+ return_value=silent):
+ _, final, voice, original = labelled.finish(
+ recording, _event(sequence=1, listen=True))
+
+ np.testing.assert_array_equal(_preview(voice), np.zeros(701, np.int16))
+ np.testing.assert_allclose(_preview(original),
+ np.round(noisy * 32767),
+ atol=1)
+ assert not voice.autoplay and not original.autoplay
+ assert ready["device"] == active["device"] == final["device"] == "Metal GPU"
+
+
+def test_a_busy_server_refuses_a_take_until_one_finishes(server):
+ first, *_ = server.start(None, _event("first"), _request("a"))
+ server.start(None, _event("second"), _request("b"))
+
+ refused, response, *_ = server.start(None, _event("third"), _request("c"))
+ _push(server, first, 1, np.zeros(100, dtype=np.float32))
+ server.finish(first, _event("first", sequence=1))
+ third, ready, *_ = server.start(None, _event("third"), _request("c"))
+
+ assert server.max_takes == 2
+ assert refused is None
+ assert response["phase"] == "error" and response["take"] == "third"
+ assert "busy" in response["message"]
+ assert ready["phase"] == "ready" and third.take == "third"
+
+
+def test_closing_the_tab_releases_its_take_at_once(server):
+ recording, *_ = server.start(None, _event(), _request("tab"))
+ _push(server, recording, 1, np.full(500, 0.01, dtype=np.float32))
+ other, *_ = server.start(None, _event("other"), _request("other tab"))
+
+ server.release(_request("tab"))
+ server.release(_request("never recorded"))
+
+ assert recording.session.snapshot().finished
+ assert recording.session.finish()[1].size == 0
+ assert not other.session.snapshot().finished
+
+
+def test_a_tab_whose_state_expired_still_releases_its_last_take(server):
+ previous, *_ = server.start(None, _event("previous"), _request("tab"))
+
+ current, *_ = server.start(None, _event("current"), _request("tab"))
+
+ assert previous.session.snapshot().finished
+ assert not current.session.snapshot().finished
+
+
+def test_a_failed_flush_ends_the_take_with_an_error(server):
+ recording, *_ = server.start(None, _event())
+ _push(server, recording, 1, np.zeros(100, dtype=np.float32))
+
+ with mock.patch.object(recording.session,
+ "finish",
+ autospec=True,
+ side_effect=RuntimeError("no full recording")):
+ _, response, voice, original = server.finish(recording,
+ _event(sequence=1))
+
+ assert response["phase"] == "error" and response["take"] == "first"
+ assert "no full recording" in response["message"]
+ assert voice == original == gr.skip()
+ assert recording.session.snapshot().finished
+
+
+def test_a_second_of_audio_fits_one_event_at_any_rate(server):
+ recording, *_ = server.start(None, _event())
+
+ _, response = _push(server, recording, 1, np.zeros(44100), rate=44100)
+
+ assert response["phase"] == "active"
+ assert response["input_seconds"] == pytest.approx(1.0)
+
+
+def test_a_take_that_cannot_start_reports_why(server):
+ with mock.patch.object(live,
+ "LiveSession",
+ autospec=True,
+ side_effect=RuntimeError("MPS out of memory")):
+ recording, response, voice, original = server.start(None, _event())
+
+ assert recording is None and voice is None and original is None
+ assert response["phase"] == "error" and response["take"] == "first"
+ assert "out of memory" in response["message"]
+
+
+def test_a_take_does_not_wait_long_for_a_busy_model(server):
+ impatient = online.Online(server.model, server.model_lock, start_wait=0.05)
+ held, release = threading.Event(), threading.Event()
+
+ def hold():
+ with server.model_lock:
+ held.set()
+ release.wait(5)
+
+ holder = threading.Thread(target=hold)
+ holder.start()
+ held.wait(5)
+ try:
+ recording, response, *_ = impatient.start(None, _event())
+ finally:
+ release.set()
+ holder.join()
+
+ assert recording is None
+ assert response["phase"] == "error" and "busy" in response["message"]
+ assert impatient.start(None, _event("later"))[1]["phase"] == "ready"
+
+
+def test_a_silent_take_gives_up_its_place(server, monkeypatch):
+ now = [1000.0]
+ monkeypatch.setattr(online.time, "monotonic", lambda: now[0])
+ first, *_ = server.start(None, _event("first"), _request("a"))
+ server.start(None, _event("second"), _request("b"))
+ _push(server, first, 1, np.zeros(100, dtype=np.float32))
+
+ now[0] += online.IDLE_SECONDS + 1
+ third, response, *_ = server.start(None, _event("third"), _request("c"))
+
+ assert response["phase"] == "ready" and third.take == "third"
+
+
+def test_an_idle_take_is_released_and_refused_when_another_starts(
+ server, monkeypatch):
+ now = [1000.0]
+ monkeypatch.setattr(online.time, "monotonic", lambda: now[0])
+ idle, *_ = server.start(None, _event("idle"), _request("a"))
+ _push(server, idle, 1, np.zeros(100, dtype=np.float32), take="idle")
+ other, *_ = server.start(None, _event("other"), _request("b"))
+
+ now[0] += online.IDLE_SECONDS + 1
+ third, ready, *_ = server.start(None, _event("third"), _request("c"))
+ _, late = _push(server,
+ idle,
+ 2,
+ np.zeros(100, dtype=np.float32),
+ take="idle")
+ _, finished, voice, original = server.finish(idle, _event("idle",
+ sequence=1))
+
+ assert ready["phase"] == "ready" and third.take == "third"
+ assert idle.session.finished and other.session.finished
+ assert late["phase"] == "error" and "without audio" in late["message"]
+ assert finished["phase"] == "error"
+ assert voice == original == gr.skip()
+
+
+def test_a_take_still_sending_audio_is_never_idle(server, monkeypatch):
+ now = [1000.0]
+ monkeypatch.setattr(online.time, "monotonic", lambda: now[0])
+ waiting, *_ = server.start(None, _event("waiting"), _request("a"))
+ waiting.pushing = 1
+
+ now[0] += online.IDLE_SECONDS + 1
+ server.start(None, _event("other"), _request("b"))
+
+ assert not waiting.expired and not waiting.session.finished
+
+
+def test_a_tab_closed_while_its_take_starts_leaves_nothing_behind(server):
+ slow = online.Online(server.model, server.model_lock, start_wait=5)
+ held, free = threading.Event(), threading.Event()
+ answer = {}
+
+ def hold():
+ with server.model_lock:
+ held.set()
+ free.wait(5)
+
+ holder = threading.Thread(target=hold)
+ holder.start()
+ held.wait(5)
+ starter = threading.Thread(target=lambda: answer.update(result=slow.start(
+ None, _event(), _request("tab"))))
+ starter.start()
+ time.sleep(0.2)
+ slow.release(_request("tab"))
+ free.set()
+ holder.join()
+ starter.join()
+
+ recording, response, *_ = answer["result"]
+ assert recording is None and response["phase"] == "error"
+ for browser in ("x", "y"):
+ assert slow.start(None, _event(browser),
+ _request(browser))[1]["phase"] == "ready"
diff --git a/tests/docs/conftest.py b/tests/docs/conftest.py
new file mode 100644
index 0000000..a5e4013
--- /dev/null
+++ b/tests/docs/conftest.py
@@ -0,0 +1,21 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Docs tests import the scripts under docs/ as plain modules."""
+
+import os
+import sys
+
+REPO = os.path.dirname(
+ os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+sys.path.insert(0, os.path.join(REPO, "docs"))
diff --git a/tests/docs/test_build_figures.py b/tests/docs/test_build_figures.py
new file mode 100644
index 0000000..c8c0102
--- /dev/null
+++ b/tests/docs/test_build_figures.py
@@ -0,0 +1,144 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The README's figures: the board chart reads the board, both themes render."""
+
+import json
+import os
+import sys
+import xml.etree.ElementTree as ET
+
+import build_figures
+
+SVG = "{http://www.w3.org/2000/svg}"
+
+BOARD = {
+ "set_id": "f5a6420d67b7ef45" + "0" * 48,
+ "anchors_version": 7,
+ "axes_version": 7,
+ "tie_bands": {
+ "composite": 0.03,
+ "timbre": 0.05
+ },
+ "order": {
+ "full": [
+ "voice_isolator_v0", "other", "voice_isolator_v0_realtime", "broken"
+ ],
+ "nb": []
+ },
+ "systems": {
+ "voice_isolator_v0": {
+ "label": "Inworld Voice Isolator (64M, offline)",
+ "composite": 0.7489
+ },
+ "other": {
+ "label": "Someone's <denoiser> & co",
+ "composite": 0.7261
+ },
+ "voice_isolator_v0_realtime": {
+ "label": "Inworld Voice Isolator realtime",
+ "composite": 0.6
+ },
+ "broken": {
+ "label": "no composite",
+ "composite": None
+ },
+ },
+}
+
+
+def test_board_rows_follow_the_board_order_and_mark_our_systems():
+ rows = build_figures.board_rows(BOARD)
+ assert [r[0].split(" (")[0] for r in rows] == [
+ "Inworld Voice Isolator", "Someone's <denoiser> & co",
+ "Inworld Voice Isolator realtime"
+ ]
+ assert [r[2] for r in rows] == [True, False, True]
+
+
+def test_board_chart_is_generated_from_the_board_in_both_themes():
+ for mode in ("light", "dark"):
+ svg = build_figures.board_svg(BOARD, mode)
+ ET.fromstring(svg) # well-formed
+ palette = build_figures.PALETTES[mode]
+ # one bar per system, no legend: the row labels carry the identity
+ assert svg.count(f'fill="{palette["ours"]}"') == 2
+ assert svg.count(f'fill="{palette["others"]}"') == 1
+ for value in ("0.749", "0.726", "0.600"):
+ assert value in svg
+ assert "Someone&#x27;s &lt;denoiser&gt; &amp; co" in svg
+ assert "no composite" not in svg
+ assert "0.03 are ties" in svg and "f5a6420d67b7ef45" in svg
+ changed = json.loads(json.dumps(BOARD))
+ changed["systems"]["other"]["composite"] = 0.5
+ assert "0.500" in build_figures.board_svg(changed, "light")
+
+
+def test_architecture_diagram_names_the_stages_and_both_checkpoints():
+ for mode in ("light", "dark"):
+
+ root = ET.fromstring(build_figures.architecture_svg(mode))
+
+ # the words are live text, and the description repeats them in full
+ words = "".join("".join(t.itertext()) for t in root.iter(f"{SVG}text"))
+ for needle in ("STFT", "Band split", "7 dual-path blocks",
+ "Per-band heads", "iSTFT", "Inside each dual-path block",
+ "Realtime checkpoint", "Offline checkpoint"):
+ assert needle in words, needle
+ desc = root.find(f"{SVG}desc").text
+ for needle in ("STFT", "B = 46 bands", "Seven dual-path blocks",
+ "Per-band linear heads", "X_hat = X + M (.) X + R",
+ "realtime checkpoint", "offline checkpoint"):
+ assert needle in desc, needle
+
+
+def test_architecture_diagram_is_drawn_per_theme_within_its_canvas():
+ svgs = {
+ mode: build_figures.architecture_svg(mode) for mode in ("light", "dark")
+ }
+
+ for mode, svg in svgs.items():
+ root = ET.fromstring(svg)
+ width = float(root.get("width"))
+ assert build_figures.ARCH_PALETTES[mode]["bg"] in svg
+ assert all(
+ 0 <= float(t.get("x")) <= width for t in root.iter(f"{SVG}text"))
+ assert svgs["light"] != svgs["dark"]
+
+
+def test_main_without_a_board_draws_the_architecture_only(
+ tmp_path, monkeypatch, capsys):
+ out = tmp_path / "assets"
+ monkeypatch.setattr(sys, "argv", ["build_figures.py", "--out", str(out)])
+ build_figures.main()
+ assert sorted(
+ os.listdir(out)) == ["architecture-dark.svg", "architecture-light.svg"]
+ assert capsys.readouterr().out.count("wrote ") == 2
+
+
+def test_main_writes_four_figures(tmp_path, monkeypatch, capsys):
+ board = tmp_path / "leaderboard.json"
+ board.write_text(json.dumps(BOARD))
+ out = tmp_path / "assets"
+ monkeypatch.setattr(
+ sys, "argv",
+ ["build_figures.py", "--leaderboard",
+ str(board), "--out",
+ str(out)])
+ build_figures.main()
+ names = sorted(os.listdir(out))
+ assert names == [
+ "architecture-dark.svg", "architecture-light.svg", "board-dark.svg",
+ "board-light.svg"
+ ]
+ assert capsys.readouterr().out.count("wrote ") == 4
diff --git a/tests/examples/test_notebooks.py b/tests/examples/test_notebooks.py
new file mode 100644
index 0000000..72ffe1f
--- /dev/null
+++ b/tests/examples/test_notebooks.py
@@ -0,0 +1,59 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Example notebooks contain portable source without saved execution state."""
+
+import json
+import pathlib
+import subprocess
+
+import pytest
+
+REPO = pathlib.Path(__file__).resolve().parents[2]
+NOTEBOOKS = sorted(path for path in (REPO / "examples").rglob("*.ipynb")
+ if ".ipynb_checkpoints" not in path.parts)
+
+
[email protected]("path", NOTEBOOKS, ids=lambda path: path.name)
+def test_notebook_contains_source_without_execution_state(path):
+ notebook = json.loads(path.read_text(encoding="utf-8"))
+
+ saved = []
+ if notebook.get("metadata", {}).get("widgets"):
+ saved.append("widget state")
+ for index, cell in enumerate(notebook["cells"]):
+ if cell.get("outputs") or cell.get("execution_count") is not None:
+ saved.append(f"cell {index}: outputs or execution count")
+ if cell.get("attachments"):
+ saved.append(f"cell {index}: embedded attachments")
+ if any(
+ cell.get("metadata", {}).get(key)
+ for key in ("execution", "ExecuteTime")):
+ saved.append(f"cell {index}: execution metadata")
+
+ assert not saved, {str(path.relative_to(REPO)): saved}
+
+
+def test_editor_notebook_checkpoints_are_not_tracked():
+ if not (REPO / ".git").exists():
+ pytest.skip("needs a Git checkout")
+ tracked = subprocess.check_output(["git", "ls-files", "-z"],
+ cwd=REPO,
+ text=True).split("\0")
+
+ checkpoints = [
+ path for path in tracked
+ if ".ipynb_checkpoints" in pathlib.PurePosixPath(path).parts
+ ]
+
+ assert not checkpoints
diff --git a/tests/fixtures/README.md b/tests/fixtures/README.md
new file mode 100644
index 0000000..105300e
--- /dev/null
+++ b/tests/fixtures/README.md
@@ -0,0 +1,40 @@
+# Golden parity fixtures
+
+The fixture inputs are derived from
+[`sample_14.wav`](../../demo/examples/sample_14.wav): LibriSpeech dev-clean
+utterance 2277-149896-0032 (Sister Carrie, read by zinniz; LibriSpeech (c) 2014
+Vassil Panayotov, CC BY 4.0) with generated hiss. The recording and its
+derivatives, including these input WAVs and expected arrays, use CC BY 4.0. The
+generator and test code use this repository's
+[Apache-2.0 license](../../LICENSE).
+
+The same 3-second input is used by `offline_3s` and `realtime_stream_3s`; the same
+11-second input is used by `offline_11s` and `realtime_stream_11s`.
+[`generate_inputs.py`](generate_inputs.py) copies the first 3 seconds for the
+short input and pads the complete recording with silence to 11 seconds for the
+long input. It copies PCM16 samples without resampling or changing their level.
+Recreate the inputs in a separate directory with:
+
+```sh
+python tests/fixtures/generate_inputs.py staging/fixture_inputs
+```
+
+Each `expected.npy` is a float32 render from the independent training reference,
+using the training checkpoint behind the released model. It is not generated by
+the package being tested. Each `meta.json` records the released model's SHA256,
+render settings, tolerance and the hashes of both files. The streaming fixtures
+also record the input piece sizes and stateful reference runner settings. Its
+recorded buffering latency describes the reference runner; use
+`VoiceIsolator.latency_samples()` for the package's streaming latency.
+
+To refresh expected arrays, run the independent reference over the generated
+inputs at the settings in `meta.json`, preserving the released model identity
+and the `1e-4` tolerance. Then run:
+
+```sh
+python -m pytest tests/inworld/voice_isolation/test_golden.py -q -rs
+```
+
+Input reproducibility and file hashes are checked without model weights. Output
+parity requires the corresponding released checkpoint under `models/` (or
+`VOICE_ISOLATION_GOLDEN_MODEL` for one checkpoint at a time).
diff --git a/tests/fixtures/generate_inputs.py b/tests/fixtures/generate_inputs.py
new file mode 100644
index 0000000..dd38fdd
--- /dev/null
+++ b/tests/fixtures/generate_inputs.py
@@ -0,0 +1,48 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Derives parity inputs from the attributed, checked-in speech example."""
+
+import argparse
+import pathlib
+import wave
+
+SAMPLE_RATE = 48000
+DURATIONS = (3, 11)
+SOURCE = (pathlib.Path(__file__).resolve().parents[2] / "demo" / "examples" /
+ "sample_14.wav")
+
+
+def main() -> None:
+ """Writes the two input WAVs into the requested output directory."""
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("output", type=pathlib.Path)
+ args = parser.parse_args()
+ args.output.mkdir(parents=True, exist_ok=True)
+ with wave.open(str(SOURCE), "rb") as handle:
+ if (handle.getnchannels(), handle.getsampwidth(),
+ handle.getframerate()) != (1, 2, SAMPLE_RATE):
+ raise ValueError("The source must be mono PCM16 audio at 48 kHz.")
+ source = handle.readframes(handle.getnframes())
+ for seconds in DURATIONS:
+ size = seconds * SAMPLE_RATE * 2
+ frames = source[:size].ljust(size, b"\0")
+ with wave.open(str(args.output / f"{seconds}s.wav"), "wb") as handle:
+ handle.setnchannels(1)
+ handle.setsampwidth(2)
+ handle.setframerate(SAMPLE_RATE)
+ handle.writeframes(frames)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/fixtures/offline_11s/expected.npy b/tests/fixtures/offline_11s/expected.npy
new file mode 100644
index 0000000..9a499d9
Binary files /dev/null and b/tests/fixtures/offline_11s/expected.npy differ
diff --git a/tests/fixtures/offline_11s/input.wav b/tests/fixtures/offline_11s/input.wav
new file mode 100644
index 0000000..d00d700
Binary files /dev/null and b/tests/fixtures/offline_11s/input.wav differ
diff --git a/tests/fixtures/offline_11s/meta.json b/tests/fixtures/offline_11s/meta.json
new file mode 100644
index 0000000..8b7d637
--- /dev/null
+++ b/tests/fixtures/offline_11s/meta.json
@@ -0,0 +1,14 @@
+{
+ "model": "models/denoiser.safetensors",
+ "model_sha256": "647335a6aeb4dc706b895532c209d51e0e84a4849d17b339f00d4392a050ae53",
+ "precision": "fp32",
+ "mode": "offline",
+ "lookahead_frames": 0,
+ "chunk_seconds": 8.0,
+ "overlap_seconds": 2.0,
+ "tolerance": 0.0001,
+ "render_device": "cpu",
+ "reference": "training-side reference implementation (the training checkpoint's network, never the release file or the package, over the clip in make_goldens.py's own copy of the package's offline window placement: every window a full one, the last ending at the clip's end and fading in where the window before it fades out)",
+ "input_sha256": "f54d1971b0e6d5daa35660b274a712e26c75fb37cc4870ceb8082a7f331c4bf1",
+ "expected_sha256": "361ff4dacfc7090b6b810ccb24e289a5d089302435b98ea7d4def1a6bccff188"
+}
diff --git a/tests/fixtures/offline_3s/expected.npy b/tests/fixtures/offline_3s/expected.npy
new file mode 100644
index 0000000..9479daa
Binary files /dev/null and b/tests/fixtures/offline_3s/expected.npy differ
diff --git a/tests/fixtures/offline_3s/input.wav b/tests/fixtures/offline_3s/input.wav
new file mode 100644
index 0000000..3adc1ba
Binary files /dev/null and b/tests/fixtures/offline_3s/input.wav differ
diff --git a/tests/fixtures/offline_3s/meta.json b/tests/fixtures/offline_3s/meta.json
new file mode 100644
index 0000000..2c78ca4
--- /dev/null
+++ b/tests/fixtures/offline_3s/meta.json
@@ -0,0 +1,14 @@
+{
+ "model": "models/denoiser.safetensors",
+ "model_sha256": "647335a6aeb4dc706b895532c209d51e0e84a4849d17b339f00d4392a050ae53",
+ "precision": "fp32",
+ "mode": "offline",
+ "lookahead_frames": 0,
+ "chunk_seconds": 8.0,
+ "overlap_seconds": 2.0,
+ "tolerance": 0.0001,
+ "render_device": "cpu",
+ "reference": "training-side reference implementation (the training checkpoint's network, never the release file or the package, over the clip in make_goldens.py's own copy of the package's offline window placement: every window a full one, the last ending at the clip's end and fading in where the window before it fades out)",
+ "input_sha256": "ba34cb451867fd3bb5b2c4e18f314d22e8379556d7a9dabb73bbf8ac2c45443b",
+ "expected_sha256": "f2d1c8f94e522df34600d85767b08ac921a20bdc8449296e90485c909c020633"
+}
diff --git a/tests/fixtures/realtime_stream_11s/expected.npy b/tests/fixtures/realtime_stream_11s/expected.npy
new file mode 100644
index 0000000..8b45a91
Binary files /dev/null and b/tests/fixtures/realtime_stream_11s/expected.npy differ
diff --git a/tests/fixtures/realtime_stream_11s/input.wav b/tests/fixtures/realtime_stream_11s/input.wav
new file mode 100644
index 0000000..d00d700
Binary files /dev/null and b/tests/fixtures/realtime_stream_11s/input.wav differ
diff --git a/tests/fixtures/realtime_stream_11s/meta.json b/tests/fixtures/realtime_stream_11s/meta.json
new file mode 100644
index 0000000..6cacc5b
--- /dev/null
+++ b/tests/fixtures/realtime_stream_11s/meta.json
@@ -0,0 +1,24 @@
+{
+ "model": "models/denoiser_realtime.safetensors",
+ "model_sha256": "76598f05523c0669e76562a8b2f31c9d395fca316e80c907ee11775e7497ae0f",
+ "precision": "fp32",
+ "mode": "streaming",
+ "lookahead_frames": 2,
+ "chunk_seconds": 8.0,
+ "overlap_seconds": 2.0,
+ "tolerance": 0.0001,
+ "render_device": "cpu",
+ "reference": "training-side reference implementation (windowed streaming runner, make_goldens.py)",
+ "input_sha256": "f54d1971b0e6d5daa35660b274a712e26c75fb37cc4870ceb8082a7f331c4bf1",
+ "expected_sha256": "8ac994037761c49fb7c82962c66919ea71d6023d2b33b5eac7cee8ff5fd03ad1",
+ "runner": {
+ "block_frames": 4,
+ "cache_frames": 1200,
+ "window_frames": 600,
+ "crossfade_frames": 200,
+ "push": [
+ 24000
+ ],
+ "latency_samples": 4448
+ }
+}
diff --git a/tests/fixtures/realtime_stream_3s/expected.npy b/tests/fixtures/realtime_stream_3s/expected.npy
new file mode 100644
index 0000000..764dca1
Binary files /dev/null and b/tests/fixtures/realtime_stream_3s/expected.npy differ
diff --git a/tests/fixtures/realtime_stream_3s/input.wav b/tests/fixtures/realtime_stream_3s/input.wav
new file mode 100644
index 0000000..3adc1ba
Binary files /dev/null and b/tests/fixtures/realtime_stream_3s/input.wav differ
diff --git a/tests/fixtures/realtime_stream_3s/meta.json b/tests/fixtures/realtime_stream_3s/meta.json
new file mode 100644
index 0000000..bd47d34
--- /dev/null
+++ b/tests/fixtures/realtime_stream_3s/meta.json
@@ -0,0 +1,24 @@
+{
+ "model": "models/denoiser_realtime.safetensors",
+ "model_sha256": "76598f05523c0669e76562a8b2f31c9d395fca316e80c907ee11775e7497ae0f",
+ "precision": "fp32",
+ "mode": "streaming",
+ "lookahead_frames": 2,
+ "chunk_seconds": 8.0,
+ "overlap_seconds": 2.0,
+ "tolerance": 0.0001,
+ "render_device": "cpu",
+ "reference": "training-side reference implementation (windowed streaming runner, make_goldens.py)",
+ "input_sha256": "ba34cb451867fd3bb5b2c4e18f314d22e8379556d7a9dabb73bbf8ac2c45443b",
+ "expected_sha256": "6ea83cd3b91b7ac462f9c9b103bdb5266f43fff949e03983279742e161de114e",
+ "runner": {
+ "block_frames": 4,
+ "cache_frames": 1200,
+ "window_frames": 600,
+ "crossfade_frames": 200,
+ "push": [
+ 24000
+ ],
+ "latency_samples": 4448
+ }
+}
diff --git a/tests/inworld/voice_isolation/test_audio.py b/tests/inworld/voice_isolation/test_audio.py
new file mode 100644
index 0000000..391942a
--- /dev/null
+++ b/tests/inworld/voice_isolation/test_audio.py
@@ -0,0 +1,111 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Input conversion and resampling contracts of the public API."""
+
+# pylint: disable=redefined-outer-name
+
+import os
+import stat
+
+import numpy as np
+import pytest
+import soundfile as sf
+import torch
+
+from inworld.voice_isolation import audio as audio_lib
+
+
+def umask():
+ """Runs the test under umask 027, then restores the process's own."""
+ previous = os.umask(0o027)
+ yield 0o027
+ os.umask(previous)
+
+
+def test_int16_pcm_is_scaled_to_unit_range():
+ x = np.array([-32768, 0, 16384, 32767], dtype=np.int16)
+ y = audio_lib.to_mono(x)
+ assert y.dtype == torch.float32
+ assert torch.allclose(y, torch.tensor([-1.0, 0.0, 0.5, 32767 / 32768]))
+
+
+def test_uint8_pcm_is_centred():
+ y = audio_lib.to_mono(np.array([0, 128, 255], dtype=np.uint8))
+ assert torch.allclose(y, torch.tensor([-1.0, 0.0, 127 / 128]))
+
+
+def test_float_input_passes_through_and_stereo_is_downmixed():
+ # [C, T]
+ stereo = np.stack([np.ones(100, np.float32), -np.ones(100, np.float32)])
+ assert torch.allclose(audio_lib.to_mono(stereo), torch.zeros(100))
+ # [T, C]
+ assert torch.allclose(audio_lib.to_mono(stereo.T), torch.zeros(100))
+ t = torch.linspace(-0.5, 0.5, 50)
+ assert torch.equal(audio_lib.to_mono(t), t)
+
+
+def test_to_mono_rejects_3d():
+ with pytest.raises(ValueError):
+ audio_lib.to_mono(np.zeros((2, 3, 4), np.float32))
+
+
+def test_resample_identity_and_length():
+ x = torch.randn(48000)
+ assert audio_lib.resample(x, 48000, 48000) is x
+ y = audio_lib.resample(x, 48000, 16000)
+ assert abs(len(y) - 16000) <= 1
+
+
+def test_save_audio_scales_pcm_instead_of_clipping(tmp_path):
+ y = torch.zeros(1000)
+ y[100], y[200] = 1.5, -0.75
+ audio_lib.save_audio(str(tmp_path / "pcm.wav"), y, 48000)
+ z, _ = audio_lib.load_audio(str(tmp_path / "pcm.wav"))
+ assert (abs(float(z.abs().max()) - 1.0) < 1e-3 and
+ abs(float(z[200]) + 0.5) < 1e-3)
+ audio_lib.save_audio(str(tmp_path / "f32.wav"), y, 48000, subtype="FLOAT")
+ z32, _ = audio_lib.load_audio(str(tmp_path / "f32.wav"))
+ assert float(z32[100]) == pytest.approx(1.5)
+
+
+def test_int64_and_more_than_eight_channels_are_refused():
+ with pytest.raises(ValueError, match="int64"):
+ audio_lib.to_mono(np.zeros(100, np.int64))
+ with pytest.raises(ValueError, match="at most eight channels"):
+ audio_lib.to_mono(np.zeros((16, 48000), np.float32))
+ assert audio_lib.to_mono(np.zeros((8, 48000), np.float32)).shape == (48000,)
+
+
+def test_save_audio_leaves_nothing_behind_when_a_write_fails(
+ tmp_path, monkeypatch):
+ write = sf.write
+
+ def full_disk(path, data, *args, **kwargs):
+ write(path, data[:10], *args, **kwargs)
+ raise OSError("No space left on device")
+
+ monkeypatch.setattr(sf, "write", full_disk)
+ with pytest.raises(OSError):
+ audio_lib.save_audio(str(tmp_path / "out.wav"), torch.zeros(1000),
+ 48000)
+ assert not list(tmp_path.iterdir())
+
+
+def test_saved_audio_gets_the_permissions_of_any_new_file(tmp_path, umask):
+ path = tmp_path / "out.wav"
+
+ audio_lib.save_audio(str(path), torch.zeros(100), 48000)
+
+ assert oct(stat.S_IMODE(path.stat().st_mode)) == oct(0o666 & ~umask)
diff --git a/tests/inworld/voice_isolation/test_cli.py b/tests/inworld/voice_isolation/test_cli.py
new file mode 100644
index 0000000..cb0fe9f
--- /dev/null
+++ b/tests/inworld/voice_isolation/test_cli.py
@@ -0,0 +1,699 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The `voice-isolate` command line.
+
+Argument contract, file mapping, end-to-end on a tiny model.
+"""
+
+# pylint: disable=protected-access,redefined-outer-name,unused-argument
+
+import math
+import os
+import stat
+import sys
+from unittest import mock
+
+import pytest
+import soundfile as sf
+import torch
+
+from inworld.voice_isolation import audio as audio_lib
+from inworld.voice_isolation import cli
+
+SR = 48000
+
+
+def _sine(seconds, sr=SR, amp=0.3, hz=440.0):
+ t = torch.arange(int(seconds * sr)) / sr
+ return amp * torch.sin(2 * math.pi * hz * t)
+
+
+def ignores_case(tmp_path):
+ """Whether tmp_path's file system finds a name in another case, as macOS
+ and Windows do by default and Linux does not."""
+ probe = tmp_path / "case-probe"
+ probe.touch()
+ found = (tmp_path / "CASE-PROBE").exists()
+ probe.unlink()
+ return found
+
+
+def umask():
+ """Runs the test under umask 027, then restores the process's own."""
+ previous = os.umask(0o027)
+ yield 0o027
+ os.umask(previous)
+
+
+def _run(*argv):
+ return cli.main(list(argv) + ["--device", "cpu"])
+
+
+def _files(folder):
+ return sorted(
+ str(path.relative_to(folder))
+ for path in folder.rglob("*")
+ if path.is_file())
+
+
+def test_parse_defaults():
+ a = cli.parse_args(["in.wav", "out.wav"])
+ assert (a.model, a.output_sr) == (
+ "inworld/voice-isolator",
+ 48000,
+ )
+ assert (a.mode, a.lookahead, a.block_frames) == ("offline", 0, 4)
+ assert (a.device, a.precision, a.float32) == (None, "auto", False)
+ assert (a.chunk_seconds, a.overlap_seconds, a.shard, a.num_shards) == (
+ None,
+ None,
+ 0,
+ 1,
+ )
+ assert a.offline_passes is None
+ assert a.background is None and not a.no_background
+ assert cli.parse_args(["in.wav", "out.wav", "--offline-passes",
+ "2"]).offline_passes == 2
+
+
+def test_parse_flags():
+ a = cli.parse_args([
+ "d",
+ "o",
+ "--model",
+ "m.safetensors",
+ "--mode",
+ "streaming",
+ "--lookahead",
+ "2",
+ "--block-frames",
+ "2",
+ "--window-frames",
+ "40",
+ "--crossfade-frames",
+ "10",
+ "--output-sr",
+ "0",
+ "--device",
+ "cpu",
+ "--precision",
+ "bf16",
+ "--chunk-seconds",
+ "4",
+ "--overlap-seconds",
+ "1",
+ "--shard",
+ "2",
+ "--num-shards",
+ "3",
+ "--float32",
+ ])
+ assert (a.model, a.output_sr, a.device) == (
+ "m.safetensors",
+ 0,
+ "cpu",
+ )
+ assert (a.mode, a.lookahead, a.block_frames, a.precision) == ("streaming",
+ 2, 2, "bf16")
+ assert (a.window_frames, a.crossfade_frames) == (40, 10)
+ assert a.float32
+ assert (a.chunk_seconds, a.overlap_seconds, a.shard, a.num_shards) == (
+ 4.0,
+ 1.0,
+ 2,
+ 3,
+ )
+ with pytest.raises(SystemExit):
+ cli.parse_args(["d", "o", "--mode", "live"])
+
+
+def test_outputs_file_mode_is_one_pair_never_resumed(tmp_path):
+ a, b = str(tmp_path / "a.wav"), str(tmp_path / "b.wav")
+ assert cli._outputs(a, b, 0, 1) == ([(a, b, None)], False)
+ folder = tmp_path / "outs"
+ folder.mkdir()
+ assert cli._outputs(a, str(folder), 0,
+ 1) == ([(a, str(folder / "a.wav"), None)], False)
+
+
+def test_outputs_directory_mode_recurses_filters_and_shards(tmp_path):
+ src, out = tmp_path / "in", tmp_path / "out"
+ (src / "sub").mkdir(parents=True)
+ for name in ("a.wav", "b.flac", "c.txt", "sub/d.mp3", "sub/e.WAV"):
+ (src / name).write_bytes(b"x")
+ pairs, resume = cli._outputs(str(src), str(out), 0, 1)
+ assert resume and out.is_dir()
+ assert [os.path.relpath(dst, out) for _, dst, _ in pairs
+ ] == ["a.wav", "b.wav", "sub/d.wav", "sub/e.wav"]
+ first, _ = cli._outputs(str(src), str(out), 0, 2)
+ second, _ = cli._outputs(str(src), str(out), 1, 2)
+ assert len(first) + len(second) == 4 and not set(first) & set(second)
+
+
+ "extra",
+ [
+ ["--alpha", "0.5"],
+ ["--stage2", "s2.safetensors"],
+ ],
+)
+def test_unsupported_restoration_flags_are_refused(extra, capsys):
+ with pytest.raises(SystemExit) as error:
+ cli.parse_args(["in.wav", "out.wav"] + extra)
+
+ assert error.value.code == 2
+ assert "unrecognized arguments" in capsys.readouterr().err
+
+
+def test_directory_mode_resumes_without_loading_a_model(tmp_path, capsys):
+ src, out = tmp_path / "in", tmp_path / "out"
+ src.mkdir()
+ out.mkdir()
+ audio_lib.save_audio(str(src / "a.wav"), _sine(0.1), SR, subtype="FLOAT")
+ (out / "a.wav").write_bytes(b"done")
+ (out / "a_background.wav").write_bytes(b"done background")
+ assert cli.main([str(src), str(out), "--model", "no-such-checkpoint"]) == 0
+ assert "0 to do" in capsys.readouterr().out
+ assert (out / "a.wav").read_bytes() == b"done"
+ assert (out / "a_background.wav").read_bytes() == b"done background"
+
+
+def test_file_mode_replaces_an_existing_output(tmp_path, tiny_ckpt):
+ inp, out = tmp_path / "in.wav", tmp_path / "out.wav"
+ audio_lib.save_audio(str(inp), _sine(0.1), SR, subtype="FLOAT")
+ out.write_bytes(b"an earlier run with other settings")
+ assert _run(str(inp), str(out), "--model", tiny_ckpt, "--float32") == 0
+ assert sf.info(str(out)).subtype == "FLOAT"
+
+
+def test_an_interrupted_write_leaves_no_output(tmp_path, tiny_ckpt, monkeypatch,
+ capsys):
+ src, out = tmp_path / "in", tmp_path / "out"
+ src.mkdir()
+ audio_lib.save_audio(str(src / "a.wav"), _sine(0.2), SR, subtype="FLOAT")
+ write = sf.write
+
+ def full_disk(path, data, *args, **kwargs):
+ # a partial file, then the error
+ write(path, data[:len(data) // 2], *args, **kwargs)
+ raise OSError("No space left on device")
+
+ monkeypatch.setattr(sf, "write", full_disk)
+ assert _run(str(src), str(out), "--model", tiny_ckpt) == 1
+ assert not list(out.iterdir()) # nothing a resumed run would take as done
+ monkeypatch.setattr(sf, "write", write)
+ assert _run(str(src), str(out), "--model", tiny_ckpt) == 0
+ assert sf.info(str(out / "a.wav")).frames == int(0.2 * SR)
+
+
+def test_voice_only_pcm16_default_and_float32(tmp_path, tiny_ckpt):
+ x = _sine(1.0)
+ inp = tmp_path / "in.wav"
+ audio_lib.save_audio(str(inp), x, SR, subtype="FLOAT")
+ out = tmp_path / "out.wav"
+ assert _run(str(inp), str(out), "--model", tiny_ckpt,
+ "--no-background") == 0
+ info = sf.info(str(out))
+ assert (info.subtype, info.samplerate, info.frames) == (
+ "PCM_16",
+ SR,
+ len(x),
+ )
+ y, _ = audio_lib.load_audio(str(out))
+ # identity-at-init model, 16-bit quantisation
+ assert torch.allclose(y, x, atol=2e-4)
+ out32 = tmp_path / "out32.wav"
+ assert _run(str(inp), str(out32), "--model", tiny_ckpt, "--float32",
+ "--no-background") == 0
+ assert sf.info(str(out32)).subtype == "FLOAT"
+ y32, _ = audio_lib.load_audio(str(out32))
+ assert torch.allclose(y32, x, atol=1e-4)
+ assert not (tmp_path / "out_background.wav").exists()
+ assert not (tmp_path / "out32_background.wav").exists()
+
+
+def test_streaming_mode_runs_end_to_end(tmp_path, tiny_ckpt):
+ x = _sine(0.3)
+ inp = tmp_path / "in.wav"
+ audio_lib.save_audio(str(inp), x, SR, subtype="FLOAT")
+ out = tmp_path / "out.wav"
+ assert _run(str(inp), str(out), "--model", tiny_ckpt, "--mode", "streaming",
+ "--lookahead", "2", "--float32") == 0
+ assert _run(str(inp), str(out), "--model", tiny_ckpt, "--mode", "streaming",
+ "--lookahead", "2", "--window-frames", "40",
+ "--crossfade-frames", "10", "--float32") == 0
+ y, _ = audio_lib.load_audio(str(out))
+ assert y.shape == x.shape and torch.isfinite(y).all()
+ assert not (tmp_path / "out_background.wav").exists()
+ with pytest.raises(ValueError, match="lookahead_frames must be one of"):
+ _run(str(inp), str(out), "--model", tiny_ckpt, "--mode", "streaming",
+ "--lookahead", "3")
+
+
+def test_pcm16_output_above_full_scale_is_scaled_not_clipped(
+ tmp_path, tiny_ckpt):
+ x = _sine(0.5, amp=1.5)
+ inp, out = tmp_path / "hot.wav", tmp_path / "out.wav"
+ audio_lib.save_audio(str(inp), x, SR, subtype="FLOAT")
+ assert _run(str(inp), str(out), "--model", tiny_ckpt,
+ "--no-background") == 0
+ y, _ = audio_lib.load_audio(str(out))
+ assert 0.999 <= float(y.abs().max()) <= 1.0
+ assert torch.allclose(y / y.abs().max(), x / x.abs().max(),
+ atol=2e-3) # same shape, no flat tops
+ out32 = tmp_path / "out32.wav"
+ assert _run(str(inp), str(out32), "--model", tiny_ckpt, "--float32",
+ "--no-background") == 0
+ y32, _ = audio_lib.load_audio(str(out32))
+ # float output is untouched
+ assert float(y32.abs().max()) == pytest.approx(1.5, abs=1e-3)
+
+
+def test_output_rate_default_resamples_and_zero_keeps_input_rate(
+ tmp_path, tiny_ckpt):
+ x = _sine(0.5, sr=24000)
+ inp = tmp_path / "in24.wav"
+ audio_lib.save_audio(str(inp), x, 24000, subtype="FLOAT")
+ out48, out24 = tmp_path / "o48.wav", tmp_path / "o24.wav"
+ assert _run(str(inp), str(out48), "--model", tiny_ckpt) == 0
+ assert (sf.info(str(out48)).samplerate, sf.info(str(out48)).frames) == (
+ SR,
+ 24000,
+ )
+ assert (_run(str(inp), str(out24), "--model", tiny_ckpt, "--output-sr",
+ "0") == 0)
+ assert (sf.info(str(out24)).samplerate, sf.info(str(out24)).frames) == (
+ 24000,
+ 12000,
+ )
+
+
+def test_directory_mode_keeps_basenames_and_reports_bad_files(
+ tmp_path, tiny_ckpt, capsys):
+ src, out = tmp_path / "in", tmp_path / "out"
+ (src / "sub").mkdir(parents=True)
+ audio_lib.save_audio(str(src / "a.wav"), _sine(0.2), SR, subtype="FLOAT")
+ sf.write(str(src / "sub" / "b.flac"), _sine(0.2).numpy(), SR)
+ (src / "broken.wav").write_bytes(b"not audio at all")
+ rc = _run(str(src), str(out), "--model", tiny_ckpt)
+ # one bad file must not stop the batch, but the exit code says so
+ assert rc == 1
+ assert (out / "a.wav").exists() and (out / "sub" / "b.wav").exists()
+ assert not (out / "broken.wav").exists()
+ log = capsys.readouterr().out
+ assert f"FAIL {src / 'broken.wav'}" in log and "DONE 2/3" in log
+
+
+# each name also matches the decoy beside it as a glob pattern
[email protected]("name, decoy", [("Takes [2024]", "Takes 2"),
+ ("take*", "take two"),
+ ("take?", "take2")])
+def test_directory_input_names_are_literal(tmp_path, tiny_ckpt, capsys, name,
+ decoy):
+ src, out = tmp_path / name, tmp_path / "out"
+ for folder, clip in ((src, "a.wav"), (tmp_path / decoy, "b.wav")):
+ folder.mkdir()
+ audio_lib.save_audio(str(folder / clip),
+ _sine(0.1),
+ SR,
+ subtype="FLOAT")
+
+ result = _run(str(src), str(out), "--model", tiny_ckpt)
+
+ assert result == 0
+ assert "1 file(s), 1 to do" in capsys.readouterr().out
+ assert _files(out) == ["a.wav", "a_background.wav"]
+
+
+def test_directory_input_needs_an_output_directory(tmp_path):
+ src, out = tmp_path / "in", tmp_path / "out.wav"
+ src.mkdir()
+ (src / "a.wav").write_bytes(b"x")
+ out.write_bytes(b"an unrelated file")
+
+ with pytest.raises(SystemExit, match="needs an output directory"):
+ _run(str(src), str(out), "--model", "not-a-model")
+
+ assert out.read_bytes() == b"an unrelated file"
+
+
+def test_colliding_or_self_overwriting_outputs_are_refused_before_any_work(
+ tmp_path,):
+ src, out = tmp_path / "in", tmp_path / "out"
+ src.mkdir()
+ for name in ("same.wav", "same.flac", "other.wav"):
+ (src / name).write_bytes(b"x")
+ with pytest.raises(SystemExit, match="would both be written to"):
+ cli._outputs(str(src), str(out), 0, 1)
+ # even across shards
+ with pytest.raises(SystemExit, match="would both be written to"):
+ cli._outputs(str(src), str(out), 1, 2)
+ (src / "same.flac").unlink()
+ with pytest.raises(SystemExit, match="outside the input directory"):
+ cli._outputs(str(src), str(src), 0, 1)
+ with pytest.raises(SystemExit, match="overwritten by an output"):
+ cli._outputs(str(src / "other.wav"), str(src / "other.wav"), 0, 1)
+ (src / "same.flac").write_bytes(b"x")
+ # before any model loads
+ with pytest.raises(SystemExit, match="would both be written to"):
+ cli.main([str(src), str(out), "--model", "no-such-checkpoint"])
+
+
[email protected]("output_rate", [0, 32000, 48000])
+def test_offline_pair_preserves_mono_input_sum_and_levels(
+ tmp_path, output_rate):
+ sample_rate = 24000
+ source = _sine(0.1, sr=sample_rate, amp=1.5)
+ stereo = torch.stack([source, source * 0.8], dim=1).numpy()
+ inp, out = tmp_path / "input.wav", tmp_path / "voice.wav"
+ sf.write(inp, stereo, sample_rate, subtype="FLOAT")
+ network = mock.create_autospec(cli.isolator.VoiceIsolator,
+ instance=True,
+ spec_set=True)
+
+ def isolate(audio, sr, output_sample_rate, **_):
+ return audio_lib.resample(audio, sr, output_sample_rate) * 1.25
+
+ network.isolate.side_effect = isolate
+
+ with mock.patch.object(cli.isolator.VoiceIsolator,
+ "load",
+ autospec=True,
+ return_value=network):
+ result = _run(str(inp), str(out), "--output-sr", str(output_rate))
+
+ assert result == 0
+ background = tmp_path / "voice_background.wav"
+ voice, sr = audio_lib.load_audio(str(out))
+ noise, noise_sr = audio_lib.load_audio(str(background))
+ mono, _ = audio_lib.load_audio(str(inp))
+ expected = audio_lib.resample(mono, sample_rate, sr)
+ assert sr == noise_sr == (output_rate or sample_rate)
+ assert sf.info(out).subtype == sf.info(background).subtype == "FLOAT"
+ assert float(voice.abs().max()) > 1.0
+ assert torch.allclose(voice + noise, expected, atol=2e-7, rtol=1e-6)
+ assert torch.allclose(noise, -expected * 0.25, atol=2e-7, rtol=1e-6)
+
+
+def test_explicit_background_path_is_created(tmp_path, tiny_ckpt):
+ inp, out = tmp_path / "input.wav", tmp_path / "voice.wav"
+ background = tmp_path / "residuals" / "noise.wav"
+ audio_lib.save_audio(str(inp), _sine(0.1), SR, subtype="FLOAT")
+
+ result = _run(str(inp), str(out), "--model", tiny_ckpt, "--background",
+ str(background))
+
+ assert result == 0
+ assert sf.info(background).subtype == "FLOAT"
+ assert not (tmp_path / "voice_background.wav").exists()
+
+
[email protected]("extra, outputs", [
+ pytest.param([], ["out.wav", "out_background.wav"], id="pair"),
+ pytest.param(["--no-background"], ["out.wav"], id="voice-only"),
+])
+def test_outputs_get_the_permissions_of_any_new_file(tmp_path, tiny_ckpt, umask,
+ extra, outputs):
+ inp = tmp_path / "in.wav"
+ audio_lib.save_audio(str(inp), _sine(0.1), SR, subtype="FLOAT")
+
+ result = _run(str(inp), str(tmp_path / "out.wav"), "--model", tiny_ckpt,
+ *extra)
+
+ assert result == 0
+ assert [
+ oct(stat.S_IMODE((tmp_path / name).stat().st_mode)) for name in outputs
+ ] == [oct(0o666 & ~umask)] * len(outputs)
+
+
[email protected]("missing", ["voice", "background"])
+def test_directory_resume_rebuilds_an_incomplete_pair(tmp_path, tiny_ckpt,
+ missing):
+ src, out = tmp_path / "input", tmp_path / "output"
+ src.mkdir()
+ out.mkdir()
+ x = _sine(0.1)
+ audio_lib.save_audio(str(src / "a.wav"), x, SR, subtype="FLOAT")
+ voice, background = out / "a.wav", out / "a_background.wav"
+ (background if missing == "voice" else voice).write_bytes(b"old output")
+
+ result = _run(str(src), str(out), "--model", tiny_ckpt)
+
+ assert result == 0
+ y, _ = audio_lib.load_audio(str(voice))
+ residual, _ = audio_lib.load_audio(str(background))
+ assert torch.allclose(y + residual, x, atol=1e-7)
+
+
+def test_failed_background_commit_leaves_pair_resumable(tmp_path, tiny_ckpt):
+ src, out = tmp_path / "input", tmp_path / "output"
+ src.mkdir()
+ out.mkdir()
+ audio_lib.save_audio(str(src / "a.wav"), _sine(0.1), SR, subtype="FLOAT")
+ background = out / "a_background.wav"
+ background.write_bytes(b"old background without a voice")
+ replace = os.replace
+
+ def interrupted(source, destination):
+ if os.fspath(destination) == str(background):
+ raise OSError("Interrupted before background commit")
+ return replace(source, destination)
+
+ with mock.patch.object(os,
+ "replace",
+ autospec=True,
+ side_effect=interrupted):
+ result = _run(str(src), str(out), "--model", tiny_ckpt)
+
+ assert result == 1
+ assert (out / "a.wav").is_file()
+ assert not background.exists()
+ assert not list(out.glob(".pair-*"))
+ assert _run(str(src), str(out), "--model", tiny_ckpt) == 0
+ assert sf.info(background).subtype == "FLOAT"
+
+
[email protected]("alias", ["symlink", "hardlink", "directory"])
+def test_source_path_alias_is_refused_before_loading(tmp_path, alias):
+ inp = tmp_path / "input.wav"
+ inp.write_bytes(b"original recording")
+ out = tmp_path / "output.wav"
+ if alias == "symlink":
+ out.symlink_to(inp)
+ elif alias == "hardlink":
+ os.link(inp, out)
+ else:
+ directory = tmp_path / "alias"
+ directory.symlink_to(tmp_path, target_is_directory=True)
+ out = directory / inp.name
+
+ with pytest.raises(SystemExit, match="overwritten by an output"):
+ _run(str(inp), str(out), "--model", "not-a-model")
+
+ assert inp.read_bytes() == b"original recording"
+
+
+def test_background_collision_is_checked_across_shards(tmp_path):
+ src, out = tmp_path / "input", tmp_path / "output"
+ src.mkdir()
+ (src / "a.wav").write_bytes(b"first input")
+ (src / "a_background.wav").write_bytes(b"second input")
+
+ with pytest.raises(SystemExit, match="would both be written to"):
+ _run(str(src), str(out), "--shard", "1", "--num-shards", "2", "--model",
+ "not-a-model")
+
+ assert not out.exists()
+
+
+def test_explicit_background_cannot_alias_source_or_voice(tmp_path):
+ inp, out = tmp_path / "input.wav", tmp_path / "voice.wav"
+ inp.write_bytes(b"original")
+
+ with pytest.raises(SystemExit, match="overwritten by an output"):
+ _run(str(inp), str(out), "--background", str(inp))
+ with pytest.raises(SystemExit, match="would both be written to"):
+ _run(str(inp), str(out), "--background", str(out))
+
+ assert inp.read_bytes() == b"original"
+
+
[email protected]("inputs, argv, outputs, refusal", [
+ pytest.param(["song.wav"],
+ ["song.wav", "clean.wav", "--background", "CLEAN.wav"],
+ ["CLEAN.wav", "clean.wav"],
+ "would both be written",
+ id="background-is-the-voice"),
+ pytest.param(["in/a.wav", "in/A.flac"], ["in", "out"], [
+ "out/A.wav", "out/A_background.wav", "out/a.wav", "out/a_background.wav"
+ ],
+ "would both be written",
+ id="two-voices"),
+ pytest.param(["in/x.wav", "in/x_Background.wav"], ["in", "out"], [
+ "out/x.wav", "out/x_Background.wav", "out/x_Background_background.wav",
+ "out/x_background.wav"
+ ],
+ "would both be written",
+ id="a-voice-is-a-background"),
+ pytest.param(["data/a.wav"], ["data", "DATA/out"],
+ ["DATA/out/a.wav", "DATA/out/a_background.wav"],
+ "outside the input",
+ id="output-inside-the-input"),
+])
+def test_names_differing_in_case_are_one_file_only_where_case_is_ignored(
+ tmp_path, monkeypatch, tiny_ckpt, ignores_case, inputs, argv, outputs,
+ refusal):
+ monkeypatch.chdir(tmp_path)
+ for name in inputs:
+ os.makedirs(os.path.dirname(name) or ".", exist_ok=True)
+ sf.write(name, _sine(0.1).numpy(), SR)
+
+ try:
+ outcome = _run(*argv, "--model", tiny_ckpt)
+ except SystemExit as refused:
+ outcome = refused.code
+
+ if ignores_case: # refused before anything is written
+ assert refusal in str(outcome)
+ assert _files(tmp_path) == sorted(inputs)
+ else:
+ assert outcome == 0
+ assert _files(tmp_path) == sorted(inputs + outputs)
+
+
+ "extra, message",
+ [(["--mode", "streaming", "--background", "noise.wav"], "only in offline"),
+ (["--output-sr", "-1"], "must be positive")])
+def test_invalid_output_options_fail_before_loading(tmp_path, extra, message):
+ with pytest.raises(SystemExit, match=message):
+ _run(str(tmp_path / "input.wav"), str(tmp_path / "out.wav"), *extra)
+
+
+def test_paired_outputs_require_wav_files(tmp_path):
+ with pytest.raises(SystemExit, match="must be WAV files"):
+ _run(str(tmp_path / "input.wav"), str(tmp_path / "out.flac"))
+
+
[email protected]("shard,num_shards", [(0, 0), (2, 2), (-1, 2)])
+def test_shard_arguments_outside_their_range_are_refused(
+ tmp_path, shard, num_shards):
+ with pytest.raises(SystemExit, match="--shard must be in"):
+ cli.main([
+ str(tmp_path),
+ str(tmp_path / "out"),
+ "--shard",
+ str(shard),
+ "--num-shards",
+ str(num_shards),
+ ])
+
+
+ "platform,device,env,cores,expected",
+ [
+ ("darwin", "cpu", {}, 12, 2),
+ ("darwin", "cpu", {}, 1, None), # never more threads than cores
+ ("darwin", "cpu", {
+ "OMP_NUM_THREADS": "8"
+ }, 12, None),
+ ("darwin", "mps", {}, 12, None),
+ ("linux", "cpu", {}, 12, None),
+ ])
+def test_cpu_threads_are_capped_on_macos_only(monkeypatch, platform, device,
+ env, cores, expected):
+ calls = []
+ monkeypatch.setattr(sys, "platform", platform)
+ monkeypatch.delenv("OMP_NUM_THREADS", raising=False)
+ for k, v in env.items():
+ monkeypatch.setenv(k, v)
+ monkeypatch.setattr(torch, "get_num_threads", lambda: cores)
+ monkeypatch.setattr(torch, "set_num_threads", calls.append)
+ cli._limit_macos_cpu_threads(torch.device(device))
+ assert calls == ([] if expected is None else [expected])
+
+
[email protected]("suffix", ["/", "/sub"])
+def test_an_output_directory_that_cannot_be_made_is_one_line_of_error(
+ tmp_path, suffix):
+ src, out = tmp_path / "in", tmp_path / "out.wav"
+ src.mkdir()
+ (src / "a.wav").write_bytes(b"x")
+ out.write_bytes(b"an unrelated file")
+
+ with pytest.raises(SystemExit, match="Cannot create the output directory"):
+ _run(str(src), str(out) + suffix, "--model", "not-a-model")
+
+ assert out.read_bytes() == b"an unrelated file"
+
+
[email protected]("inputs, argv", [
+ (["song.wav"], ["song.wav", "clean.wav", "--background", "CLEAN.wav"]),
+ (["in/a.wav", "in/A.flac"], ["in", "out"]),
+ (["in/x.wav", "in/x_Background.wav"], ["in", "out"]),
+])
+def test_names_differing_in_case_are_refused_where_a_folder_ignores_case(
+ tmp_path, monkeypatch, inputs, argv):
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.setattr(cli, "_ignores_case", lambda folder: True)
+ for name in inputs:
+ os.makedirs(os.path.dirname(name) or ".", exist_ok=True)
+ sf.write(name, _sine(0.1).numpy(), SR)
+
+ with pytest.raises(SystemExit, match="would both be written"):
+ _run(*argv, "--model", "not-a-model")
+
+ assert _files(tmp_path) == sorted(inputs)
+
+
+def test_the_case_probe_agrees_with_the_file_system(tmp_path, ignores_case):
+ assert cli._ignores_case(str(tmp_path)) == ignores_case
+
+
+def test_an_empty_folder_is_probed_with_a_file_of_its_own(
+ tmp_path, monkeypatch, ignores_case):
+ folder = tmp_path / "empty"
+ folder.mkdir()
+ monkeypatch.setattr(cli, "_probe_paths", lambda path: iter(()))
+
+ found = cli._ignores_case(str(folder))
+
+ assert found == ignores_case
+ assert not any(folder.iterdir())
+
+
+def test_a_folder_that_cannot_be_probed_counts_as_ignoring_case(
+ tmp_path, monkeypatch):
+
+ def read_only(*args, **kwargs):
+ raise PermissionError("read-only")
+
+ monkeypatch.setattr(cli, "_probe_paths", lambda path: iter(()))
+ monkeypatch.setattr(cli.tempfile, "mkstemp", read_only)
+
+ assert cli._ignores_case(str(tmp_path))
+
+
+def test_a_hard_link_in_another_case_is_not_taken_for_ignored_case(
+ tmp_path, ignores_case):
+ if ignores_case:
+ pytest.skip("needs a file system that tells case apart")
+ folder = tmp_path / "links"
+ folder.mkdir()
+ (folder / "readme").write_bytes(b"x")
+ os.link(folder / "readme", folder / "README")
+
+ assert not cli._ignores_case(str(folder))
diff --git a/tests/inworld/voice_isolation/test_doctor.py b/tests/inworld/voice_isolation/test_doctor.py
new file mode 100644
index 0000000..ae2c175
--- /dev/null
+++ b/tests/inworld/voice_isolation/test_doctor.py
@@ -0,0 +1,268 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The `voice-isolate-doctor` readiness check.
+
+No network and no released weights: the Hub cache and the registry's fetch
+are replaced, and ``--full`` runs a tiny checkpoint.
+"""
+
+# pylint: disable=redefined-outer-name,unused-argument
+
+import hashlib
+import json
+import sys
+
+import huggingface_hub
+from huggingface_hub import errors as hub_errors
+import pytest
+import torch
+
+from inworld.voice_isolation import doctor
+from inworld.voice_isolation import isolator
+from inworld.voice_isolation import registry
+
+
+def empty_cache(monkeypatch):
+ """No released weights in the Hugging Face cache."""
+ monkeypatch.setattr(huggingface_hub, "try_to_load_from_cache",
+ lambda *args, **kwargs: None)
+
+
+def on_cpu(monkeypatch):
+ """Inference picks the CPU, as on a machine with no GPU."""
+ monkeypatch.setattr(isolator, "default_device", lambda: torch.device("cpu"))
+
+
+def _lines(capsys):
+ return capsys.readouterr().out.strip().splitlines()
+
+
+def _hub_error(cls):
+ """A Hub HTTP error, built bare: its constructor needs a live response."""
+ return cls.__new__(cls, "401 Client Error")
+
+
+def test_default_level_without_weights_is_ready_and_succeeds(
+ empty_cache, on_cpu, capsys):
+
+ status = doctor.main([])
+
+ lines = _lines(capsys)
+ assert status == 0
+ assert lines[-1] == ("Ready to install weights: run voice-isolate-doctor"
+ " --full")
+ assert ("INFO voice-isolator-v1: not downloaded yet; run with --full"
+ in lines)
+ assert not any(line.startswith("FAIL") for line in lines)
+ assert any(line.startswith("INFO torch: torch ") for line in lines)
+
+
+ "platform_name, machine, torch_version, chosen, level",
+ [
+ ("darwin", "arm64", "2.5.1", False, "WARN"),
+ ("darwin", "arm64", "2.6.0", False, "INFO"),
+ ("darwin", "arm64", "2.5.1", True, "INFO"),
+ ("linux", "x86_64", "2.5.1", False, "INFO"),
+ ],
+)
+def test_an_apple_silicon_mac_left_on_the_cpu_by_an_old_torch_warns(
+ empty_cache, on_cpu, monkeypatch, capsys, platform_name, machine,
+ torch_version, chosen, level):
+ monkeypatch.setattr(sys, "platform", platform_name)
+ monkeypatch.setattr(doctor.platform, "machine", lambda: machine)
+ monkeypatch.setattr(torch, "__version__", torch_version)
+ argv = ["--device", "cpu"] if chosen else []
+
+ status = doctor.main(argv)
+
+ (device,) = [line for line in _lines(capsys) if " device: " in line]
+ assert status == 0
+ assert device.startswith(level)
+ if level == "WARN":
+ assert "upgrade torch to 2.6 or later" in device
+
+
+def test_the_device_line_names_the_device_inference_picks(
+ empty_cache, monkeypatch, capsys):
+ monkeypatch.setattr(isolator, "default_device", lambda: torch.device("mps"))
+
+ doctor.main([])
+
+ assert "INFO device: inference runs on mps" in _lines(capsys)
+
+
[email protected]("matches", [True, False])
+def test_cached_weights_are_checked_against_the_registry(
+ tmp_path, on_cpu, monkeypatch, capsys, matches):
+ cached = tmp_path / "denoiser.safetensors"
+ cached.write_bytes(b"weights")
+ digest = hashlib.sha256(b"weights" if matches else b"other").hexdigest()
+ entry = dict(registry.MODELS["voice-isolator-v1"], sha256=digest)
+ monkeypatch.setattr(registry, "MODELS", {"voice-isolator-v1": entry})
+ monkeypatch.setattr(huggingface_hub, "try_to_load_from_cache",
+ lambda *args, **kwargs: str(cached))
+
+ status = doctor.main([])
+
+ lines = _lines(capsys)
+ if matches:
+ assert status == 0
+ assert f"OK voice-isolator-v1: cached at {cached}" in lines
+ assert lines[-1].startswith("Ready: run voice-isolate-doctor --full")
+ else:
+ assert status == 1
+ assert (f"FAIL voice-isolator-v1: checksum mismatch: delete {cached}"
+ " and run again") in lines
+ assert lines[-1] == "1 problem: see the FAIL lines above"
+
+
+def test_full_runs_both_given_checkpoints_and_is_all_set(
+ tiny_ckpt, empty_cache, capsys):
+
+ status = doctor.main([
+ "--full", "--offline-model", tiny_ckpt, "--online-model", tiny_ckpt,
+ "--device", "cpu"
+ ])
+
+ lines = _lines(capsys)
+ assert status == 0
+ assert lines.count(f"OK {tiny_ckpt}: loads and runs on cpu") == 2
+ assert lines[-1] == (f"All set: {tiny_ckpt} and {tiny_ckpt} on cpu"
+ f" (torch {torch.__version__})")
+
+
+ "cause, message",
+ [
+ (_hub_error(hub_errors.RepositoryNotFoundError),
+ "inworld/voice-isolator is not reachable: pass --offline-model and"
+ " --online-model with local .safetensors files"),
+ (_hub_error(hub_errors.GatedRepoError),
+ "inworld/voice-isolator is not reachable"),
+ (hub_errors.LocalEntryNotFoundError("connection error"),
+ "cannot reach huggingface.co: check the network, or pass a local"
+ " file"),
+ (None, "checksum mismatch: delete the cached file and run again"),
+ ],
+)
+def test_full_names_why_the_released_weights_could_not_be_fetched(
+ empty_cache, on_cpu, monkeypatch, capsys, cause, message):
+
+ def resolve(name_or_path, mode="offline"):
+ if cause is None:
+ raise RuntimeError(f"Checksum mismatch for {name_or_path}:"
+ " expected a, got b.")
+ raise RuntimeError("could not be fetched from the Hub") from cause
+
+ monkeypatch.setattr(registry, "resolve", resolve)
+
+ status = doctor.main(["--full"])
+
+ lines = _lines(capsys)
+ failed = [line for line in lines if line.startswith("FAIL")]
+ assert status == 1
+ assert [line.split(": ", 1)[0] for line in failed
+ ] == ["FAIL voice-isolator-v1", "FAIL voice-isolator-v1-realtime"]
+ assert all(message in line for line in failed)
+ assert lines[-1] == "2 problems: see the FAIL lines above"
+
+
+ "error, message",
+ [
+ (_hub_error(hub_errors.RepositoryNotFoundError),
+ "not reachable: check the location and your access to it, or pass a"
+ " local .safetensors file"),
+ (hub_errors.LocalEntryNotFoundError("connection error"),
+ "cannot reach huggingface.co: check the network, or pass a local"
+ " file"),
+ (OSError("disk full"),
+ "could not fetch hf://org/repo/w.safetensors: disk full"),
+ ],
+)
+def test_full_reports_an_hf_location_that_cannot_be_fetched(
+ tiny_ckpt, empty_cache, monkeypatch, capsys, error, message):
+ spec = "hf://org/repo/w.safetensors"
+
+ def hf_hub_download(repo_id, filename, revision=None):
+ raise error
+
+ monkeypatch.setattr(huggingface_hub, "hf_hub_download", hf_hub_download)
+
+ status = doctor.main([
+ "--full", "--offline-model", spec, "--online-model", tiny_ckpt,
+ "--device", "cpu"
+ ])
+
+ lines = _lines(capsys)
+ assert status == 1
+ assert f"FAIL {spec}: {message}" in lines
+ assert f"OK {tiny_ckpt}: loads and runs on cpu" in lines
+ assert lines[-1] == "1 problem: see the FAIL lines above"
+
+
+def test_json_still_reports_when_an_hf_location_cannot_be_fetched(
+ tiny_ckpt, empty_cache, monkeypatch, capsys):
+
+ def hf_hub_download(repo_id, filename, revision=None):
+ raise _hub_error(hub_errors.RepositoryNotFoundError)
+
+ monkeypatch.setattr(huggingface_hub, "hf_hub_download", hf_hub_download)
+
+ status = doctor.main([
+ "--json", "--full", "--offline-model", "hf://org/repo/w.safetensors",
+ "--online-model", tiny_ckpt, "--device", "cpu"
+ ])
+
+ report = json.loads(capsys.readouterr().out)
+ failed = [c for c in report["checks"] if c["level"] == "FAIL"]
+ assert status == 1
+ assert report["ok"] is False
+ assert [c["name"] for c in failed] == ["hf://org/repo/w.safetensors"]
+
+
+def test_full_reports_a_checkpoint_that_does_not_load(tmp_path, tiny_ckpt,
+ empty_cache, capsys):
+ broken = tmp_path / "broken.safetensors"
+ broken.write_bytes(b"not a checkpoint")
+
+ status = doctor.main([
+ "--full", "--offline-model",
+ str(broken), "--online-model", tiny_ckpt, "--device", "cpu"
+ ])
+
+ lines = _lines(capsys)
+ (failed,) = [line for line in lines if line.startswith("FAIL")]
+ assert status == 1
+ assert failed.startswith(f"FAIL {broken}: failed on cpu: ")
+ assert "try --device cpu" not in failed
+ assert f"OK {tiny_ckpt}: loads and runs on cpu" in lines
+
+
+def test_json_carries_the_same_checks_and_summary(empty_cache, on_cpu, capsys):
+ doctor.main([])
+ text = _lines(capsys)
+
+ status = doctor.main(["--json"])
+
+ report = json.loads(capsys.readouterr().out)
+ assert status == 0
+ assert report["ok"] is True
+ assert report["summary"] == text[-1]
+ rows = [(c["level"], c["name"], c["message"]) for c in report["checks"]]
+ assert [f"{level:<4} {name}: {message}" for level, name, message in rows
+ ] == text[:-1]
diff --git a/tests/inworld/voice_isolation/test_golden.py b/tests/inworld/voice_isolation/test_golden.py
new file mode 100644
index 0000000..2e0591b
--- /dev/null
+++ b/tests/inworld/voice_isolation/test_golden.py
@@ -0,0 +1,170 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Golden parity against the reference implementation.
+
+Fixtures live in tests/fixtures/<name>/{meta.json, input.wav, expected.npy}
+and are rendered by the training-side reference implementation. ``meta.json``
+names the model (registry name or path, overridable with
+VOICE_ISOLATION_GOLDEN_MODEL), the mode (``offline`` or ``streaming`` with
+``lookahead_frames``), the window, the tolerance and, for a fixture rendered
+through the reference's stateful runner, ``runner`` with its ``block_frames``
+and the piece sizes pushed. Output parity is skipped when the model is absent;
+input reproducibility and fixture hashes are checked without model weights.
+"""
+
+import glob
+import hashlib
+import json
+import os
+import pathlib
+import subprocess
+import sys
+
+import numpy as np
+import pytest
+import torch
+
+from inworld.voice_isolation import audio as audio_lib
+from inworld.voice_isolation import isolator
+
+FIXTURES = os.path.join(
+ os.path.dirname(os.path.dirname(os.path.dirname(
+ os.path.abspath(__file__)))),
+ "fixtures",
+)
+CASES = sorted(glob.glob(os.path.join(FIXTURES, "*", "meta.json")))
+
+REPO = os.path.dirname(
+ os.path.dirname(os.path.dirname(os.path.dirname(
+ os.path.abspath(__file__)))))
+
+
+def _model_path(meta):
+ """Registry name, absolute path, or path relative to the repository root."""
+ p = os.environ.get("VOICE_ISOLATION_GOLDEN_MODEL") or meta.get("model")
+ if p and "/" in p and not os.path.isabs(p) and not os.path.exists(p):
+ p = os.path.join(REPO, p)
+ if not p or (not os.path.exists(p) and "/" in p):
+ pytest.skip("golden model checkpoint not available")
+ want = meta.get("model_sha256")
+ if want and os.path.exists(p) and not os.path.isdir(p):
+ have = hashlib.sha256(open(p, "rb").read()).hexdigest()
+ if have != want:
+ pytest.skip(
+ f"checkpoint on disk ({have[:12]}) is not the fixtures' model"
+ f" ({want[:12]}); regenerate the goldens with the independent"
+ " reference before checking parity")
+ return p
+
+
+def _stream(vi, x, runner):
+ # a fixture rendered by the plain stream names no window: 0 turns the
+ # session's default windows off
+ stream = vi.stream(block_frames=int(runner.get("block_frames", 4)),
+ cache_frames=runner.get("cache_frames"),
+ window_frames=runner.get("window_frames", 0),
+ crossfade_frames=runner.get("crossfade_frames"))
+ sizes = [int(s) for s in runner.get("push", [1920])]
+ pieces, pos, index = [], 0, 0
+ while pos < len(x):
+ step = sizes[index % len(sizes)]
+ pieces.append(stream.push(x[pos:pos + step]))
+ pos += step
+ index += 1
+ pieces.append(stream.flush())
+ return torch.cat(pieces)
+
+
+def test_fixture_inputs_are_reproducible(tmp_path):
+ generator = os.path.join(FIXTURES, "generate_inputs.py")
+
+ subprocess.run([sys.executable, generator, str(tmp_path)], check=True)
+
+ for case in CASES:
+ directory = pathlib.Path(case).parent
+ seconds = directory.name.rsplit("_", 1)[1]
+ recorded = (directory / "input.wav").read_bytes()
+ regenerated = (tmp_path / f"{seconds}.wav").read_bytes()
+ assert recorded == regenerated
+
+
+ "meta_path",
+ CASES,
+ ids=[os.path.basename(os.path.dirname(c)) for c in CASES])
+def test_fixture_files_match_their_recorded_hashes(meta_path):
+ directory = pathlib.Path(meta_path).parent
+ meta = json.loads(pathlib.Path(meta_path).read_text(encoding="utf-8"))
+
+ actual = {
+ "input_sha256":
+ hashlib.sha256((directory / "input.wav").read_bytes()).hexdigest(),
+ "expected_sha256":
+ hashlib.sha256(
+ (directory / "expected.npy").read_bytes()).hexdigest(),
+ }
+
+ assert actual == {key: meta[key] for key in actual}
+
+
+ "meta_path",
+ CASES,
+ ids=[os.path.basename(os.path.dirname(c)) for c in CASES],
+)
+def test_reference_signal_rejects_silence_and_half_level(meta_path):
+ directory = pathlib.Path(meta_path).parent
+ meta = json.loads(pathlib.Path(meta_path).read_text(encoding="utf-8"))
+ expected = np.load(directory / "expected.npy")
+
+ silence_error = np.abs(expected).max()
+ half_level_error = np.abs(expected - 0.5 * expected).max()
+
+ assert silence_error > meta["tolerance"]
+ assert half_level_error > meta["tolerance"]
+
+
+ "meta_path",
+ CASES,
+ ids=[os.path.basename(os.path.dirname(c)) for c in CASES],
+)
+def test_golden_parity(meta_path):
+ d = os.path.dirname(meta_path)
+ meta = json.load(open(meta_path, encoding="utf-8"))
+ vi = isolator.VoiceIsolator.load(
+ _model_path(meta),
+ device="cpu",
+ precision=meta.get("precision", "fp32"),
+ mode=meta.get("mode", "offline"),
+ lookahead_frames=int(meta.get("lookahead_frames", 0)),
+ )
+ x, sr = audio_lib.load_audio(os.path.join(d, "input.wav"))
+ if meta.get("runner"):
+ assert sr == vi.sample_rate
+ y = _stream(vi, x, meta["runner"])
+ else:
+ y = vi.isolate(
+ x,
+ sr,
+ output_sample_rate=48000,
+ chunk_seconds=meta.get("chunk_seconds"),
+ overlap_seconds=meta.get("overlap_seconds"),
+ )
+ expected = torch.from_numpy(np.load(os.path.join(d, "expected.npy")))
+ # the whole render, sample for sample: a truncated output is a failure
+ assert len(y) == len(
+ expected), f"{len(y)} samples, expected {len(expected)}"
+ err = (y - expected).abs().max().item()
+ assert err <= meta.get("tolerance", 1e-4), f"max abs error {err}"
diff --git a/tests/inworld/voice_isolation/test_init.py b/tests/inworld/voice_isolation/test_init.py
new file mode 100644
index 0000000..ef28be9
--- /dev/null
+++ b/tests/inworld/voice_isolation/test_init.py
@@ -0,0 +1,78 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Package boundaries: the public surface and what importing it must not do."""
+
+import importlib
+import subprocess
+import sys
+
+import pytest
+
+
+def test_namespace_import_reads_nicely():
+ # pylint: disable-next=import-outside-toplevel
+ from inworld import voice_isolation
+
+ assert hasattr(voice_isolation, "VoiceIsolator")
+ assert hasattr(voice_isolation, "VoiceIsolatorNetwork")
+ assert hasattr(voice_isolation, "VoiceIsolatorConfig")
+ for name in ("Denoiser", "DenoiserNetwork", "DenoiserConfig", "Isolator",
+ "IsolatorConfig"):
+ assert not hasattr(voice_isolation, name)
+ for name in ("denoise", "denoise_many"):
+ assert not hasattr(voice_isolation.VoiceIsolator, name)
+ assert not hasattr(voice_isolation, "TwoStageModel")
+ assert not hasattr(voice_isolation.VoiceIsolator, "enhance")
+ for name in voice_isolation.__all__:
+ assert hasattr(voice_isolation, name), name
+
+
+ "mod",
+ [
+ "model",
+ "scan",
+ "streaming",
+ "audio",
+ "isolator",
+ "registry",
+ "cli",
+ "doctor",
+ ],
+)
+def test_modules_import_without_optional_extras(mod):
+ importlib.import_module(f"inworld.voice_isolation.{mod}")
+
+
+def test_import_does_not_touch_network():
+ """Importing the package must not import heavy optional packages.
+
+ Nor may it hit the hub.
+ """
+ code = (
+ "import sys; import inworld.voice_isolation.isolator; bad = [m for m in"
+ " ('demucs', 'transformers', 'gradio', 'mamba_ssm', 'huggingface_hub',"
+ " 'safetensors') if m in sys.modules];"
+ " print(bad); sys.exit(1 if bad else 0)")
+ r = subprocess.run( # the exit status is read below
+ [sys.executable, "-c", code],
+ check=False,
+ capture_output=True,
+ text=True,
+ env={
+ "PYTHONPATH": ":".join(sys.path),
+ "PATH": "/usr/bin:/bin"
+ },
+ )
+ assert r.returncode == 0, r.stdout + r.stderr
diff --git a/tests/inworld/voice_isolation/test_isolator.py b/tests/inworld/voice_isolation/test_isolator.py
new file mode 100644
index 0000000..06ee8b2
--- /dev/null
+++ b/tests/inworld/voice_isolation/test_isolator.py
@@ -0,0 +1,571 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""VoiceIsolator on CPU: rates, channels, modes, checkpoints and precision."""
+
+# pylint: disable=redefined-outer-name
+import dataclasses
+import json
+import os
+
+import numpy as np
+import pytest
+import torch
+
+from inworld.voice_isolation import audio as audio_lib
+from inworld.voice_isolation import isolator as isolator_lib
+from inworld.voice_isolation import registry
+
+
+def isolator(dual_model):
+ return isolator_lib.VoiceIsolator(dual_model, device="cpu")
+
+
+def _training_checkpoint(m, path, prefix="isolator.", extra=None):
+ """Writes a checkpoint the way training does: config, prefixed state."""
+ state = {prefix + k: v for k, v in m.state_dict().items()}
+ state.update(extra or {})
+ torch.save(
+ {
+ "config": {
+ "modeling": {
+ "compact_family": m.config.to_dict()
+ }
+ },
+ "model": state,
+ }, path)
+ return str(path)
+
+
[email protected]("sr", [16000, 24000, 44100, 48000])
+def test_sample_rate_round_trip(isolator, sr):
+ torch.manual_seed(0)
+ x = torch.randn(int(0.13 * sr)) * 0.3
+ y = isolator.isolate(x, sr)
+ assert isinstance(y, torch.Tensor)
+ assert y.shape == x.shape
+ assert torch.isfinite(y).all()
+
+
+def test_numpy_in_numpy_out_and_output_rate(isolator):
+ x = (np.random.RandomState(0).randn(2400) * 0.3).astype(np.float32)
+ y = isolator.isolate(x, 24000, output_sample_rate=48000)
+ assert isinstance(y, np.ndarray)
+ assert y.shape == (4800,)
+
+
+def test_identity_model_passes_48k_audio_through(identity_model):
+ vi = isolator_lib.VoiceIsolator(identity_model, device="cpu")
+ torch.manual_seed(0)
+ x = torch.randn(4800) * 0.3
+ assert torch.equal(vi.isolate(x, 48000), x)
+ vi.mode = "streaming"
+ assert torch.equal(vi.isolate(x, 48000), x)
+
+
+def test_the_level_is_left_alone(identity_model):
+ vi = isolator_lib.VoiceIsolator(identity_model, device="cpu")
+ x = torch.randn(4800) * 0.001
+ assert torch.equal(vi.isolate(x, 48000), x)
+
+
+def test_stereo_and_transposed_inputs_are_downmixed(isolator):
+ torch.manual_seed(0)
+ mono = torch.randn(4800) * 0.3
+ ref = isolator.isolate(mono, 48000)
+ assert torch.allclose(isolator.isolate(torch.stack([mono, mono]), 48000),
+ ref,
+ atol=1e-5)
+ assert torch.allclose(isolator.isolate(torch.stack([mono, mono], 1), 48000),
+ ref,
+ atol=1e-5)
+
+
+def test_modes_and_lookahead(isolator):
+ assert isolator.mode == "offline" and isolator.lookahead_choices == (0, 2)
+ assert isolator.frame_seconds == pytest.approx(16 / 48000)
+ torch.manual_seed(0)
+ x = torch.randn(4800) * 0.3
+ offline = isolator.isolate(x, 48000)
+ isolator.mode = "streaming"
+ assert isolator.model.lookahead_frames == 0
+ k0 = isolator.isolate(x, 48000)
+ isolator.lookahead_frames = 2
+ assert isolator.model.lookahead_frames == 2
+ k2 = isolator.isolate(x, 48000)
+ assert not torch.allclose(offline, k0, atol=1e-4)
+ assert not torch.allclose(k0, k2, atol=1e-4)
+ # the block sets throughput, not latency
+ assert isolator.latency_samples() == 64 + 16 * 2
+ assert isolator.latency_samples(block_frames=1) == 64 + 16 * 2
+ with pytest.raises(ValueError, match="lookahead_frames must be one of"):
+ isolator.lookahead_frames = 1
+ with pytest.raises(ValueError, match="mode must be one of"):
+ isolator.mode = "live"
+ isolator.mode = "offline"
+ assert torch.equal(isolator.isolate(x, 48000), offline)
+
+
+def test_an_offline_only_checkpoint_has_no_streaming_mode(offline_model):
+ vi = isolator_lib.VoiceIsolator(offline_model, device="cpu")
+ assert vi.lookahead_choices == ()
+ with pytest.raises(ValueError, match="no streaming mode"):
+ vi.mode = "streaming"
+ with pytest.raises(ValueError, match="no streaming mode"):
+ isolator_lib.VoiceIsolator(offline_model,
+ device="cpu",
+ mode="streaming")
+
+
+def test_the_stream_needs_streaming_mode(isolator):
+ with pytest.raises(RuntimeError, match="mode='streaming'"):
+ isolator.stream()
+ isolator.mode = "streaming"
+ stream = isolator.stream(block_frames=2)
+ x = torch.randn(2000) * 0.3
+ out = torch.cat([stream.push(x), stream.flush()])
+ assert out.shape == x.shape
+
+
+ "factory", [isolator_lib.VoiceIsolator, isolator_lib.VoiceIsolator.load])
+def test_unsupported_restoration_is_rejected_before_loading(factory):
+ with pytest.raises(ValueError,
+ match="Stage-2 restoration is not supported"):
+ factory("no-such-checkpoint", stage2="no-such-restorer", device="cpu")
+
+
+def test_load_accepts_default_stage2_for_frozen_helpers(dual_model, tmp_path):
+ path = _training_checkpoint(dual_model, tmp_path / "weights.pt")
+ x = torch.randn(4800, generator=torch.Generator().manual_seed(4)) * 0.3
+ expected = isolator_lib.VoiceIsolator(dual_model,
+ device="cpu").isolate(x, 48000)
+
+ loaded = isolator_lib.VoiceIsolator.load(path, stage2=None, device="cpu")
+ actual = loaded.isolate(x, 48000)
+
+ assert torch.equal(actual, expected)
+
+
+def test_the_default_model_is_the_repository_id_resolved_by_mode(
+ dual_model, tmp_path, monkeypatch):
+ path = _training_checkpoint(dual_model, tmp_path / "weights.pt")
+ calls = []
+
+ def resolve(model, mode="offline"):
+ calls.append((model, mode))
+ return path
+
+ monkeypatch.setattr(registry, "resolve", resolve)
+
+ offline = isolator_lib.VoiceIsolator(device="cpu")
+ live = isolator_lib.VoiceIsolator.load(device="cpu", mode="streaming")
+
+ assert calls == [(registry.REPO_ID, "offline"),
+ (registry.REPO_ID, "streaming")]
+ assert (offline.mode, live.mode) == ("offline", "streaming")
+
+
+def test_load_model_reads_safetensors_and_training_checkpoints(
+ dual_model, tmp_path):
+ # pylint: disable-next=import-outside-toplevel
+ import safetensors.torch
+
+ st = {k: v.contiguous() for k, v in dual_model.state_dict().items()}
+ safetensors.torch.save_file(
+ st,
+ str(tmp_path / "m.safetensors"),
+ metadata={"config": json.dumps(dual_model.config.to_dict())},
+ )
+ m1 = isolator_lib.load_model(str(tmp_path / "m.safetensors"))
+ m2 = isolator_lib.load_model(
+ _training_checkpoint(
+ dual_model,
+ tmp_path / "ema.pt",
+ extra={"isolator.enhance_decoder.heads.0.0.weight": torch.ones(3)}))
+ x = torch.randn(3, 2400)
+ with torch.inference_mode():
+ assert torch.equal(m1(x), dual_model(x))
+ assert torch.equal(m2(x), dual_model(x))
+ assert m1.config == dual_model.config
+
+
+def test_a_checkpoint_without_its_architecture_is_refused(dual_model, tmp_path):
+ torch.save({"model": dual_model.state_dict()}, tmp_path / "bare.pt")
+ with pytest.raises(ValueError, match="no embedded architecture"):
+ isolator_lib.load_model(str(tmp_path / "bare.pt"))
+ torch.save(dual_model.state_dict(), tmp_path / "state.pt")
+ with pytest.raises(ValueError, match="no embedded architecture"):
+ isolator_lib.load_model(str(tmp_path / "state.pt"))
+ # pylint: disable-next=import-outside-toplevel
+ import safetensors.torch
+
+ safetensors.torch.save_file(
+ {
+ k: v.contiguous() for k, v in dual_model.state_dict().items()
+ }, str(tmp_path / "nometa.safetensors"))
+ with pytest.raises(ValueError, match="lacks the 'config'"):
+ isolator_lib.load_model(str(tmp_path / "nometa.safetensors"))
+
+
+def test_unknown_config_field_is_rejected(dual_model, tmp_path):
+ path = _training_checkpoint(dual_model, tmp_path / "ema.pt")
+ raw = torch.load(path, weights_only=True)
+ raw["config"]["modeling"]["compact_family"]["future_knob"] = 7
+ torch.save(raw, path)
+ with pytest.raises(ValueError, match="does not implement"):
+ isolator_lib.load_model(path)
+
+
+def test_save_and_load_audio(tmp_path):
+ x = torch.sin(torch.linspace(0, 100, 24000)) * 0.5
+ audio_lib.save_audio(str(tmp_path / "a.wav"), x, 24000, subtype="FLOAT")
+ y, sr = audio_lib.load_audio(str(tmp_path / "a.wav"))
+ assert sr == 24000
+ assert torch.allclose(x, y, atol=1e-6)
+ assert not os.path.exists(tmp_path / "b.wav")
+
+
+def test_missing_learned_weights_are_rejected(dual_model, tmp_path):
+ """A checkpoint lacking a learned tensor must not run on random init."""
+ path = _training_checkpoint(dual_model, tmp_path / "ema.pt")
+ raw = torch.load(path, weights_only=True)
+ raw["model"].pop("isolator.band_embedding")
+ torch.save(raw, path)
+ with pytest.raises(RuntimeError, match="missing"):
+ isolator_lib.load_model(path)
+
+
+def test_unexpected_model_weights_are_rejected(dual_model, tmp_path):
+ path = _training_checkpoint(
+ dual_model,
+ tmp_path / "ema.pt",
+ extra={"isolator.not_in_this_architecture.weight": torch.zeros(3)})
+ with pytest.raises(RuntimeError, match="unexpected"):
+ isolator_lib.load_model(path)
+
+
+class _Payload:
+ """Stand-in for an arbitrary pickled object (module scope for pickling)."""
+
+
+def test_pickled_objects_in_checkpoints_are_refused(tmp_path):
+ p = tmp_path / "evil.pt"
+ torch.save({"config": {"modeling": {}}, "model": {}, "obj": _Payload()}, p)
+ with pytest.raises(ValueError, match="plain tensors"):
+ isolator_lib.load_model(str(p))
+
+
+def _clips(sr, seed=0):
+ g = torch.Generator().manual_seed(seed)
+ loud = [torch.randn(int(0.05 * sr), generator=g) * 0.2 for _ in range(3)]
+ quiet = torch.randn(int(0.03 * sr), generator=g) * 0.05
+ return loud + [quiet]
+
+
+def test_isolate_many_matches_isolate_across_lengths(isolator):
+ clips = _clips(isolator.sample_rate)
+ single = [isolator.isolate(c, isolator.sample_rate) for c in clips]
+ many = isolator.isolate_many(clips, isolator.sample_rate)
+ assert len(many) == len(clips)
+ for s, m in zip(single, many):
+ assert s.shape == m.shape
+ assert torch.allclose(s, m, atol=1e-5, rtol=1e-4)
+
+
+def test_isolate_many_keeps_order_types_and_rates(isolator):
+ in_sr = 16000
+ clips = [c.numpy() for c in _clips(in_sr, seed=1)]
+ out = isolator.isolate_many(clips, in_sr, output_sample_rate=48000)
+ assert all(isinstance(o, np.ndarray) for o in out)
+ for c, o in zip(clips, out):
+ ref = isolator.isolate(c, in_sr, output_sample_rate=48000)
+ assert len(o) == len(ref) and np.allclose(o, ref, atol=1e-5, rtol=1e-4)
+ same_rate = isolator.isolate_many(clips, in_sr)
+ assert [len(o) for o in same_rate] == [len(c) for c in clips]
+
+
+def test_precision_defaults_to_the_training_precision_on_a_gpu_only(dual_model):
+ # auto: bf16 autocast on a CUDA device, float32 anywhere else
+ assert isolator_lib.DEFAULT_PRECISION == "auto"
+ vi = isolator_lib.VoiceIsolator(dual_model, device="cpu")
+ assert vi.precision == "fp32"
+ assert isolator_lib.VoiceIsolator(dual_model,
+ device="cpu",
+ precision="auto").precision == "fp32"
+ assert isolator_lib.VoiceIsolator(dual_model,
+ device="cpu",
+ precision="bf16").precision == "bf16"
+ if torch.cuda.is_available():
+ on_gpu = isolator_lib.VoiceIsolator(dual_model, device="cuda")
+ assert on_gpu.precision == "bf16"
+ with pytest.raises(ValueError, match="precision"):
+ isolator_lib.VoiceIsolator(dual_model, device="cpu", precision="fp8")
+
+
+def test_reduced_precision_stays_close_to_fp32(tiny):
+ if not torch.cuda.is_available():
+ pytest.skip("autocast parity is checked on a GPU")
+ clip = torch.randn(4800, generator=torch.Generator().manual_seed(2)) * 0.2
+ ref = isolator_lib.VoiceIsolator(tiny.dual(),
+ device="cuda").isolate(clip, 48000)
+ for precision in ("fp16", "bf16"):
+ out = isolator_lib.VoiceIsolator(tiny.dual(),
+ device="cuda",
+ precision=precision).isolate(
+ clip, 48000)
+ err = float(
+ (out - ref).pow(2).mean()) / max(float(ref.pow(2).mean()), 1e-12)
+ assert err < 1e-4
+
+
+ "kw",
+ [
+ {
+ "chunk_seconds": -1.0
+ },
+ {
+ "overlap_seconds": -0.5
+ },
+ {
+ "chunk_seconds": float("nan")
+ },
+ {
+ "chunk_seconds": 0.0001
+ },
+ ],
+)
+def test_invalid_windows_fail_before_any_audio_is_processed(
+ isolator, monkeypatch, kw):
+
+ def untouched(*args, **kwargs):
+ raise AssertionError("audio was processed")
+
+ monkeypatch.setattr(isolator, "_prepare", untouched)
+ with pytest.raises(ValueError):
+ isolator.isolate(np.zeros(4800, dtype=np.float32), 48000, **kw)
+ with pytest.raises(ValueError):
+ isolator.isolate_many([np.zeros(4800, dtype=np.float32)], 48000, **kw)
+
+
+ "audio,message",
+ [
+ (np.zeros(0, dtype=np.float32), "empty"),
+ (np.array([0.1, np.inf, 0.0], dtype=np.float32), "NaN or infinite"),
+ (np.array([0.1, np.nan, 0.0], dtype=np.float32), "NaN or infinite"),
+ ],
+)
+def test_empty_or_non_finite_audio_is_refused(isolator, audio, message):
+ with pytest.raises(ValueError, match=message):
+ isolator.isolate(audio, 48000)
+
+
+def test_streaming_mode_renders_through_the_stream(isolator):
+ torch.manual_seed(0)
+ x = torch.randn(2000) * 0.3
+ isolator.mode = "streaming"
+ isolator.lookahead_frames = 2
+ rendered = isolator.isolate(x, 48000)
+ session = isolator.stream()
+ manual = torch.cat(
+ [session.push(x[:900]),
+ session.push(x[900:]),
+ session.flush()])
+ assert torch.allclose(rendered, manual, atol=1e-6)
+ assert isolator.block_frames == 4 and isolator.latency_samples(
+ ) == 64 + 16 * 2
+
+
+def test_isolate_many_in_streaming_mode_matches_isolate(isolator):
+ isolator.mode = "streaming"
+ clips = _clips(isolator.sample_rate)
+ single = [isolator.isolate(c, isolator.sample_rate) for c in clips]
+ many = isolator.isolate_many(clips, isolator.sample_rate)
+ for s, m in zip(single, many):
+ assert s.shape == m.shape and torch.allclose(s, m, atol=1e-5)
+
+
+def test_block_frames_are_validated(dual_model):
+ with pytest.raises(ValueError, match="block_frames"):
+ isolator_lib.VoiceIsolator(dual_model, device="cpu", block_frames=0)
+ vi = isolator_lib.VoiceIsolator(dual_model,
+ device="cpu",
+ block_frames=2,
+ mode="streaming")
+ assert vi.latency_samples() == 64 and vi.stream().block_frames == 2
+
+
+def test_the_streams_memory_is_the_training_window_unless_set(dual_model):
+ vi = isolator_lib.VoiceIsolator(dual_model,
+ device="cpu",
+ mode="streaming",
+ lookahead_frames=0)
+ assert vi.cache_frames is None
+ default = vi.stream()
+ longer = isolator_lib.VoiceIsolator(dual_model,
+ device="cpu",
+ mode="streaming",
+ lookahead_frames=0,
+ cache_frames=2 * default.cache_frames)
+ assert longer.stream().cache_frames == 2 * default.cache_frames
+ assert longer.stream(cache_frames=7).cache_frames == 7
+ with pytest.raises(ValueError, match="cache_frames"):
+ isolator_lib.VoiceIsolator(dual_model, device="cpu", cache_frames=0)
+
+
+def test_the_streams_windows_default_on_and_zero_turns_them_off(dual_model):
+ vi = isolator_lib.VoiceIsolator(dual_model,
+ device="cpu",
+ mode="streaming",
+ lookahead_frames=0)
+ assert (vi.window_frames,
+ vi.crossfade_frames) == (isolator_lib.STREAM_WINDOW_FRAMES,
+ isolator_lib.STREAM_CROSSFADE_FRAMES)
+ session = vi.stream()
+ assert (session.window_frames, session.crossfade_frames) == (600, 200)
+ assert vi.stream(window_frames=0).window_frames is None
+ off = isolator_lib.VoiceIsolator(dual_model,
+ device="cpu",
+ mode="streaming",
+ lookahead_frames=0,
+ window_frames=0)
+ assert off.window_frames is None and off.stream().window_frames is None
+ assert off.stream(window_frames=400).crossfade_frames == 200
+ custom = isolator_lib.VoiceIsolator(dual_model,
+ device="cpu",
+ mode="streaming",
+ lookahead_frames=0,
+ window_frames=40,
+ crossfade_frames=10)
+ session = custom.stream()
+ assert (session.window_frames, session.crossfade_frames) == (40, 10)
+ assert custom.stream(window_frames=80).crossfade_frames == 10
+ x = torch.randn(48000, generator=torch.Generator().manual_seed(3)) * 0.3
+ y = custom.isolate(x, 48000)
+ assert y.shape == x.shape and torch.isfinite(y).all()
+ with pytest.raises(ValueError, match="crossfade_frames"):
+ isolator_lib.VoiceIsolator(dual_model,
+ device="cpu",
+ window_frames=40,
+ crossfade_frames=40)
+
+
+def test_offline_passes_run_the_model_over_its_own_output(tiny):
+ net = tiny.offline()
+ x = torch.randn(4800, generator=torch.Generator().manual_seed(3)) * 0.3
+ once = isolator_lib.VoiceIsolator(net, device="cpu", precision="fp32")
+ twice = isolator_lib.VoiceIsolator(net,
+ device="cpu",
+ precision="fp32",
+ offline_passes=2)
+ assert once.offline_passes == 1 and twice.offline_passes == 2
+ with torch.inference_mode():
+ expected = net.enhance(net.enhance(x))
+ assert torch.allclose(twice.isolate(x, 48000), expected, atol=1e-6)
+ assert not torch.allclose(twice.isolate(x, 48000), once.isolate(x, 48000))
+ # batched clips take the same passes
+ many = twice.isolate_many([x, x[:2400]], 48000)
+ assert torch.allclose(many[0], twice.isolate(x, 48000), atol=1e-5)
+
+
+def test_the_checkpoint_carries_its_passes_and_a_request_overrides_them(tiny):
+ net = tiny.dual()
+ net.config = dataclasses.replace(net.config, offline_passes=2)
+ assert isolator_lib.VoiceIsolator(net, device="cpu").offline_passes == 2
+ assert isolator_lib.VoiceIsolator(net, device="cpu",
+ offline_passes=1).offline_passes == 1
+ x = torch.randn(4800, generator=torch.Generator().manual_seed(4)) * 0.3
+ # streaming ignores the file's count: the stream is one pass
+ live = isolator_lib.VoiceIsolator(net, device="cpu", mode="streaming")
+ plain = tiny.dual()
+ single = isolator_lib.VoiceIsolator(plain, device="cpu", mode="streaming")
+ assert torch.allclose(live.isolate(x, 48000),
+ single.isolate(x, 48000),
+ atol=1e-6)
+ # a request above one is refused where it cannot apply
+ with pytest.raises(ValueError, match="offline mode"):
+ isolator_lib.VoiceIsolator(plain,
+ device="cpu",
+ mode="streaming",
+ offline_passes=2)
+ with pytest.raises(ValueError, match="offline mode"):
+ isolator_lib.VoiceIsolator(tiny.windowed(),
+ device="cpu",
+ mode="streaming",
+ offline_passes=2)
+ with pytest.raises(ValueError, match="whole number"):
+ isolator_lib.VoiceIsolator(plain, device="cpu", offline_passes=0)
+
+
+ "cuda,mps,version,fft_ok,expected",
+ [
+ (True, True, "2.6.0", True, "cuda"),
+ (False, True, "2.6.0", True, "mps"),
+ (False, True, "2.15.0", True, "mps"),
+ (False, False, "2.6.0", True, "cpu"),
+ # the supported torch>=2.1 whose MPS backend cannot run the models
+ (False, True, "2.1.0", True, "cpu"),
+ (False, True, "2.5.1", True, "cpu"),
+ # a macOS whose Metal backend lacks a working FFT
+ (False, True, "2.6.0", False, "cpu"),
+ ])
+def test_default_device_prefers_cuda_then_a_working_mps_then_cpu(
+ monkeypatch, cuda, mps, version, fft_ok, expected):
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: cuda)
+ monkeypatch.setattr(torch.backends.mps, "is_available", lambda: mps)
+ monkeypatch.setattr(torch, "__version__",
+ torch.torch_version.TorchVersion(version))
+ monkeypatch.setattr(isolator_lib, "_mps_fft_matches_cpu", lambda: fft_ok)
+ assert isolator_lib.default_device() == torch.device(expected)
+
+
+def test_the_mps_fft_check_reports_a_missing_op_as_unusable(monkeypatch):
+ # pylint: disable=protected-access
+
+ def missing(*_):
+ raise NotImplementedError("aten::_fft_r2c is not implemented for MPS")
+
+ monkeypatch.setattr(torch.Tensor, "to", lambda self, *_: self)
+ monkeypatch.setattr(torch.fft, "rfft", missing)
+ isolator_lib._mps_fft_matches_cpu.cache_clear()
+ try:
+ assert not isolator_lib._mps_fft_matches_cpu()
+ finally:
+ isolator_lib._mps_fft_matches_cpu.cache_clear()
+
+
+def test_an_explicit_device_overrides_the_default(dual_model, monkeypatch):
+ monkeypatch.setattr(isolator_lib, "default_device",
+ lambda: pytest.fail("default_device was consulted"))
+ assert isolator_lib.VoiceIsolator(
+ dual_model, device="cpu").device == torch.device("cpu")
+
+
[email protected]("mode", isolator_lib.MODES)
+def test_mps_matches_cpu(tiny, mode):
+ if isolator_lib.default_device().type != "mps":
+ pytest.skip("needs a Metal backend the default would choose")
+ clip = torch.randn(9600, generator=torch.Generator().manual_seed(3)) * 0.2
+ model = tiny.dual()
+ outs = [
+ np.asarray(
+ isolator_lib.VoiceIsolator(model, device=device,
+ mode=mode).isolate(clip, 48000))
+ for device in ("cpu", "mps")
+ ]
+ assert outs[1].dtype == outs[0].dtype and outs[1].shape == outs[0].shape
+ assert np.allclose(outs[1], outs[0], atol=1e-4)
diff --git a/tests/inworld/voice_isolation/test_model.py b/tests/inworld/voice_isolation/test_model.py
new file mode 100644
index 0000000..bf7dc48
--- /dev/null
+++ b/tests/inworld/voice_isolation/test_model.py
@@ -0,0 +1,391 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The isolator network: config, bands, modes, causality, windows."""
+
+import dataclasses
+
+import pytest
+import torch
+
+from inworld.voice_isolation import model
+
+SR = 48000
+
+
[email protected]("position", ["offline", 0, 2])
+def test_identity_at_init(identity_model, position):
+ """The untrained model is an exact identity: its heads start at zero."""
+ if position == "offline":
+ identity_model.set_offline()
+ else:
+ identity_model.set_lookahead(position)
+ torch.manual_seed(0)
+ x = torch.randn(2, SR // 10) * 0.3
+ with torch.inference_mode():
+ y = identity_model(x)
+ assert torch.equal(y, x)
+ assert torch.equal(identity_model.enhance(x[0]), x[0])
+
+
+def test_band_edges_cover_the_spectrum_once(tiny):
+ edges = model.band_edges(model.VoiceIsolatorConfig())
+ assert len(edges) == 46
+ assert edges[0][0] == 0 and edges[-1][1] == 1025
+ assert all(a[1] == b[0] for a, b in zip(edges, edges[1:]))
+ tiny = model.band_edges(tiny.config())
+ assert tiny == [(0, 8), (8, 16), (16, 24), (24, 32), (32, 33)]
+
+
+def test_the_released_architectures_have_their_parameter_counts():
+ offline = model.VoiceIsolatorNetwork(model.VoiceIsolatorConfig(width=512))
+ assert offline.num_params == 64_047_112
+ assert offline.default_window() == (12.0, 2.0)
+ assert len(offline.blocks) == 7 and len(offline.edges) == 46
+ realtime = model.VoiceIsolatorNetwork(
+ model.VoiceIsolatorConfig(width=512,
+ causal=True,
+ chunk_seconds=30.0,
+ lookahead_frames=2,
+ lookahead_frames_choices=(0, 2, 4),
+ attention_window_frames=1200))
+ assert realtime.num_params == 58_178_056
+ assert not realtime.offline and realtime.lookahead_frames == 2
+
+
+ "overrides,match",
+ [
+ (dict(width=15), "multiple of twice"),
+ (dict(block_types=("grid",)), "block_types"),
+ (dict(n_fft=65), "n_fft must be even"),
+ (dict(hop_length=40), "n_fft must be even"),
+ (dict(correction_bound=1.0), "correction_bound"),
+ (dict(overlap_seconds=0.6), "overlap_seconds"),
+ (dict(exclusive_axes="none"), "exclusive_axes"),
+ (dict(lookahead_frames_choices=(2, 0)), "ascending"),
+ (dict(lookahead_frames=1), "causal or dual-mode"),
+ (dict(dual_mode=True), "list the streaming positions"),
+ (dict(dual_mode=True, lookahead_frames_choices=(0,),
+ causal=True), "leave causal off"),
+ (dict(mode_film=True), "mode_film"),
+ (dict(causal=True, lookahead_frames=3, lookahead_frames_choices=(0, 2)),
+ "one of lookahead_frames_choices"),
+ (dict(attention_window_frames=8), "needs a causal model"),
+ (dict(causal=True, attention_window_frames=-1), "negative"),
+ ],
+)
+def test_configs_that_cannot_be_built_are_refused(tiny, overrides, match):
+ with pytest.raises(ValueError, match=match):
+ tiny.config(**overrides)
+
+
+def test_config_from_a_checkpoint_dictionary():
+ raw = dict(
+ width=16,
+ block_types=["transformer", "mamba"],
+ num_heads=2,
+ n_fft=64,
+ hop_length=16,
+ chunk_seconds=0.05,
+ overlap_seconds=0.01,
+ band_plan=[[6000, 24000]],
+ attention_backend="fa2",
+ checkpoint_every=1,
+ offline_mode_prob=0.5,
+ dual_distill=True,
+ grid_width=48,
+ representation="bands",
+ hint_checkpoint=None,
+ dual_mode=True,
+ lookahead_frames=0,
+ lookahead_frames_choices=[0, 2],
+ )
+ cfg = model.VoiceIsolatorConfig.from_dict(raw)
+ assert cfg.block_types == ("transformer", "mamba")
+ assert cfg.lookahead_frames_choices == (0, 2)
+ assert cfg.band_plan == ((6000, 24000),)
+ assert model.VoiceIsolatorConfig.from_dict(cfg.to_dict()) == cfg
+ with pytest.raises(ValueError, match="does not implement"):
+ model.VoiceIsolatorConfig.from_dict(dict(raw, future_knob=7))
+ with pytest.raises(ValueError, match="representation"):
+ model.VoiceIsolatorConfig.from_dict(
+ dict(raw, representation="full_grid"))
+ with pytest.raises(ValueError, match="decoder_type"):
+ model.VoiceIsolatorConfig.from_dict(
+ dict(raw, decoder_type="positive_real"))
+ with pytest.raises(ValueError, match="hint_checkpoint"):
+ model.VoiceIsolatorConfig.from_dict(dict(raw, hint_checkpoint="h.pt"))
+ assert dataclasses.asdict(cfg) == cfg.to_dict()
+ windowed = model.VoiceIsolatorConfig.from_dict(
+ dict(raw,
+ dual_mode=False,
+ causal=True,
+ lookahead_frames_choices=[0, 2, 4],
+ attention_window_frames=1200))
+ assert windowed.attention_window_frames == 1200
+ assert model.VoiceIsolatorConfig.from_dict(windowed.to_dict()) == windowed
+
+
+def test_an_attention_window_bounds_the_causal_forward(tiny):
+ """A frame sees itself and the ``window - 1`` frames before it: the
+ windowed model equals the same weights without a window on a clip that
+ fits the window and differs once the clip is longer."""
+ mask = model.window_mask(6, 3, torch.device("cpu"))
+ assert mask.tolist() == [
+ [j <= i and i - j < 3 for j in range(6)] for i in range(6)
+ ]
+ windowed, plain = tiny.windowed(), tiny.windowed(attention_window_frames=0)
+ assert all(
+ torch.equal(a, b)
+ for a, b in zip(windowed.parameters(), plain.parameters()))
+ hop = windowed.config.hop_length
+ window = windowed.config.attention_window_frames
+ g = torch.Generator().manual_seed(3)
+ short = torch.randn(1, hop * (window - 2), generator=g) * 0.3
+ long = torch.randn(1, hop * 6 * window, generator=g) * 0.3
+ with torch.inference_mode():
+ assert torch.allclose(windowed(short), plain(short), atol=1e-6)
+ assert not torch.allclose(windowed(long), plain(long), atol=1e-4)
+
+
+def test_the_mode_knob(dual_model, offline_model):
+ assert dual_model.offline and dual_model.lookahead_frames == 0
+ assert dual_model.set_lookahead(2) == 2
+ assert not dual_model.offline and dual_model.lookahead_frames == 2
+ dual_model.set_offline()
+ assert dual_model.offline
+ with pytest.raises(ValueError, match="not among the trained positions"):
+ dual_model.set_lookahead(1)
+ assert offline_model.offline
+ with pytest.raises(ValueError, match="no streaming positions"):
+ offline_model.set_lookahead(0)
+ with pytest.raises(ValueError, match="Only a dual-mode"):
+ offline_model.set_offline()
+
+
+def test_the_modes_give_different_outputs(dual_model):
+ torch.manual_seed(0)
+ x = torch.randn(1, SR // 10) * 0.3
+ outputs = []
+ for position in ("offline", 0, 2):
+ if position == "offline":
+ dual_model.set_offline()
+ else:
+ dual_model.set_lookahead(position)
+ with torch.inference_mode():
+ outputs.append(dual_model(x))
+ assert not torch.allclose(outputs[0], outputs[1], atol=1e-4)
+ assert not torch.allclose(outputs[1], outputs[2], atol=1e-4)
+
+
[email protected]("lookahead", [0, 2])
+def test_a_streaming_position_reads_exactly_its_lookahead_ahead(
+ dual_model, lookahead):
+ """Changing the input from sample j on leaves earlier output alone.
+
+ Up to one STFT window plus the look-ahead frames before j; offline, the
+ change reaches the start of the clip.
+ """
+ cfg = dual_model.config
+ torch.manual_seed(0)
+ x = torch.randn(1, SR // 10) * 0.3
+ j = SR // 20
+ x2 = x.clone()
+ x2[:, j:] = torch.randn(x2.shape[-1] - j) * 0.3
+ dual_model.set_lookahead(lookahead)
+ with torch.inference_mode():
+ y1, y2 = dual_model(x), dual_model(x2)
+ safe = j - cfg.n_fft - cfg.hop_length * (lookahead + 1)
+ assert torch.allclose(y1[:, :safe], y2[:, :safe], atol=1e-6)
+ assert not torch.allclose(y1, y2, atol=1e-4)
+ dual_model.set_offline()
+ with torch.inference_mode():
+ y1, y2 = dual_model(x), dual_model(x2)
+ assert (y1[:, :cfg.n_fft] - y2[:, :cfg.n_fft]).abs().max() > 1e-6
+
+
+def test_batched_forward_matches_single_clips(dual_model):
+ torch.manual_seed(0)
+ x = torch.randn(3, SR // 10) * 0.3
+ with torch.inference_mode():
+ batched = dual_model(x)
+ single = torch.cat([dual_model(x[i:i + 1]) for i in range(3)])
+ assert torch.allclose(batched, single, atol=1e-5)
+
+
+def test_windowed_render_matches_a_single_pass_within_one_window(dual_model):
+ torch.manual_seed(0)
+ x = torch.randn(SR // 20) * 0.3
+ with torch.inference_mode():
+ single = dual_model(x[None])[0]
+ assert torch.equal(dual_model.enhance(x), single)
+ assert dual_model.default_window() == (dual_model.config.chunk_seconds,
+ dual_model.config.overlap_seconds)
+
+
+def test_chunked_render_keeps_the_length_and_is_deterministic(dual_model):
+ torch.manual_seed(0)
+ x = torch.randn(2, int(0.137 * SR)) * 0.3
+ y = dual_model.enhance(x, chunk_seconds=0.03, overlap_seconds=0.01)
+ assert y.shape == x.shape
+ assert torch.equal(
+ y, dual_model.enhance(x, chunk_seconds=0.03, overlap_seconds=0.01))
+ assert torch.isfinite(y).all()
+
+
+def test_chunking_an_identity_model_stays_the_identity(identity_model):
+ """The crossfade weights sum to one everywhere, with and without overlap."""
+ torch.manual_seed(0)
+ x = torch.randn(int(0.137 * SR)) * 0.3
+ for overlap in (0.01, 0.0, 0.02):
+ y = identity_model.enhance(x,
+ chunk_seconds=0.03,
+ overlap_seconds=overlap)
+ assert torch.allclose(y, x, atol=1e-5)
+
+
[email protected]("extra", [1, 7, 100, 959])
+def test_every_window_of_a_long_clip_is_a_full_window(dual_model, extra):
+ """A clip just past a step boundary no longer ends in a stub window."""
+ torch.manual_seed(0)
+ chunk, overlap = model.window_samples(0.03, 0.01, SR)
+ x = torch.randn(2 * (chunk - overlap) + chunk + extra) * 0.3
+ lengths = []
+ hook = dual_model.register_forward_pre_hook(
+ lambda _, args: lengths.append(args[0].shape[-1]))
+
+ try:
+ y = dual_model.enhance(x, chunk_seconds=0.03, overlap_seconds=0.01)
+ finally:
+ hook.remove()
+
+ assert y.shape == x.shape
+ assert set(lengths) == {chunk}
+
+
+def test_the_tail_of_a_long_clip_comes_from_the_last_full_window(dual_model):
+ torch.manual_seed(0)
+ chunk, overlap = model.window_samples(0.03, 0.01, SR)
+ step = chunk - overlap
+ n = 2 * step + chunk + 100
+ x = torch.randn(n) * 0.3
+ with torch.inference_mode():
+ last = dual_model(x[None, n - chunk:])[0]
+
+ y = dual_model.enhance(x, chunk_seconds=0.03, overlap_seconds=0.01)
+
+ previous_end = 2 * step + chunk
+ assert torch.allclose(y[previous_end:],
+ last[previous_end - (n - chunk):],
+ atol=1e-6)
+
+
[email protected]("samples", [1, 16, 32, 63, 64, 65])
+def test_inputs_shorter_than_one_window(dual_model, samples):
+ torch.manual_seed(0)
+ x = torch.randn(samples) * 0.3
+ y = dual_model.enhance(x)
+ assert y.shape == (samples,)
+ assert torch.isfinite(y).all()
+
+
+def test_bad_inputs_are_refused(dual_model):
+ with pytest.raises(ValueError, match="mono audio"):
+ dual_model(torch.zeros(10))
+ with pytest.raises(ValueError, match="mono audio"):
+ dual_model(torch.zeros(1, 0))
+ with pytest.raises(ValueError, match="mono audio"):
+ dual_model(torch.zeros(1, 10, dtype=torch.int32))
+
+
+ "chunk,overlap,match",
+ [
+ (-8.0, 2.0, "shorter than"),
+ (0.0, 0.0, "shorter than"),
+ (float("nan"), 1.0, "must be finite"),
+ (float("inf"), 1.0, "must be finite"),
+ (8.0, -1.0, "must not be negative"),
+ (8.0, float("nan"), "must be finite"),
+ ("eight", 1.0, "number of seconds"),
+ ],
+)
+def test_windows_that_would_drop_or_blank_audio_are_refused(
+ dual_model, chunk, overlap, match):
+ x = torch.randn(4800)
+ with pytest.raises(ValueError, match=match):
+ dual_model.enhance(x, chunk_seconds=chunk, overlap_seconds=overlap)
+
+
+def test_window_samples_caps_the_crossfade_at_half_the_window():
+ assert model.window_samples(1.0, 0.25, 48000) == (48000, 12000)
+ assert model.window_samples(1.0, 0.9, 48000) == (48000, 24000)
+ assert model.window_samples(1.0, 0.0, 48000) == (48000, 0)
+
+
+def test_read_ahead_takes_later_frames_and_holds_the_last():
+ raw = torch.arange(6.0).view(1, 1, 6, 1)
+ assert model.read_ahead(raw, 2).flatten().tolist() == [2, 3, 4, 5, 5, 5]
+ assert torch.equal(model.read_ahead(raw, 0), raw)
+
+
+def test_rope_rotation_is_relative():
+ """Attention logits depend on the offset between positions only."""
+ torch.manual_seed(0)
+ q = torch.randn(1, 1, 1, 8)
+ k = torch.randn(1, 1, 1, 8)
+ cos, sin = model.rope_tables(20, 8, "cpu", torch.float32)
+ logits = []
+ for base in (0, 7):
+ rq = model.apply_rope(q, cos[base + 3:base + 4], sin[base + 3:base + 4])
+ rk = model.apply_rope(k, cos[base:base + 1], sin[base:base + 1])
+ logits.append((rq * rk).sum())
+ assert torch.allclose(logits[0], logits[1], atol=1e-5)
+
+
+def test_exclusive_attention_removes_the_own_value_component():
+ torch.manual_seed(0)
+ value = torch.randn(2, 3, 5, 4)
+ output = model.exclusive(value * 2.0, value)
+ assert torch.allclose(output, torch.zeros_like(output), atol=1e-6)
+ orthogonal = model.exclusive(torch.randn(2, 3, 5, 4), value)
+ assert torch.allclose((orthogonal * value).sum(-1),
+ torch.zeros(2, 3, 5),
+ atol=1e-5)
+
+
+def test_bounded_correction_never_exceeds_the_bound():
+ torch.manual_seed(0)
+ reference = torch.randn(3, 7, dtype=torch.complex64)
+ correction = model.bounded_correction(
+ torch.randn(3, 7, 2) * 10, reference, 0.5)
+ magnitude = torch.linalg.vector_norm(correction, dim=-1)
+ assert (magnitude <= 0.5 * reference.abs() + 1e-6).all()
+
+
+def test_offline_passes_are_a_count_a_causal_model_cannot_take(tiny):
+ assert tiny.config().offline_passes == 1
+ two = model.VoiceIsolatorConfig.from_dict(
+ dict(tiny.config().to_dict(), offline_passes=2))
+ assert two.offline_passes == 2
+ assert model.VoiceIsolatorConfig.from_dict(two.to_dict()) == two
+ for bad in (0, -1, 1.5, True, "2"):
+ with pytest.raises(ValueError, match="whole number"):
+ tiny.config(offline_passes=bad)
+ # a causal model streams in one pass; a dual-mode one runs passes offline
+ with pytest.raises(ValueError, match="causal model streams in one pass"):
+ tiny.config(causal=True, offline_passes=2)
+ assert tiny.config(dual_mode=True,
+ lookahead_frames_choices=(0, 2),
+ offline_passes=2).offline_passes == 2
diff --git a/tests/inworld/voice_isolation/test_registry.py b/tests/inworld/voice_isolation/test_registry.py
new file mode 100644
index 0000000..8aa8627
--- /dev/null
+++ b/tests/inworld/voice_isolation/test_registry.py
@@ -0,0 +1,226 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""Registry resolution rules.
+
+The tests use no network, only parsing and the local-path shortcut.
+"""
+
+import hashlib
+import sys
+import types
+
+import pytest
+
+from inworld.voice_isolation import registry
+
+
+def test_hf_spec_parses_repo_file_and_revision():
+ assert registry.parse_hf(
+ "hf://inworld/voice-isolator/denoiser.safetensors") == (
+ "inworld/voice-isolator",
+ "denoiser.safetensors",
+ None,
+ )
+ assert registry.parse_hf("hf://org/repo/sub/dir/[email protected]") == (
+ "org/repo",
+ "sub/dir/w.safetensors",
+ "v0.1",
+ )
+
+
+ ["hf://org/repo", "hf:///repo/file", "hf://org//file"])
+def test_hf_spec_rejects_incomplete_specs(bad):
+ with pytest.raises(ValueError):
+ registry.parse_hf(bad)
+
+
+def test_existing_path_is_returned_untouched(tmp_path):
+ p = tmp_path / "weights.safetensors"
+ p.write_bytes(b"x")
+ assert registry.resolve(str(p)) == str(p)
+
+
+ ["not-a-model", "denoiser", "denoiser-realtime"])
+def test_unknown_name_lists_known_models(name):
+ with pytest.raises(ValueError, match="voice-isolator-v1"):
+ registry.resolve(name)
+
+
+def test_registry_entries_are_consistent():
+ assert set(
+ registry.MODELS) == {"voice-isolator-v1", "voice-isolator-v1-realtime"}
+ for name, entry in registry.MODELS.items():
+ assert entry["repo_id"].count("/") == 1
+ assert entry["filename"].endswith(".safetensors")
+ assert entry["stage"] == 1
+ assert len(entry["sha256"]) == 64, name
+
+
+def test_a_registry_name_is_never_shadowed_and_always_verified(
+ tmp_path, monkeypatch):
+ weights = tmp_path / "hub" / "w.safetensors"
+ weights.parent.mkdir()
+ weights.write_bytes(b"released weights")
+ calls = []
+
+ def hf_hub_download(repo_id, filename, revision=None):
+ calls.append((repo_id, filename, revision))
+ return str(weights)
+
+ monkeypatch.setitem(
+ sys.modules,
+ "huggingface_hub",
+ types.SimpleNamespace(hf_hub_download=hf_hub_download),
+ )
+ entry = dict(
+ registry.MODELS["voice-isolator-v1"],
+ sha256=hashlib.sha256(b"released weights").hexdigest(),
+ revision="abc123",
+ )
+ monkeypatch.setitem(registry.MODELS, "voice-isolator-v1", entry)
+ monkeypatch.chdir(tmp_path)
+ local = tmp_path / "voice-isolator-v1"
+ local.write_bytes(b"a local file of the same name")
+ assert registry.resolve("voice-isolator-v1") == str(weights)
+ assert calls == [(entry["repo_id"], entry["filename"], "abc123")]
+ assert registry.resolve("./voice-isolator-v1") == "./voice-isolator-v1"
+ weights.write_bytes(b"other weights")
+ with pytest.raises(RuntimeError, match="Checksum mismatch"):
+ registry.resolve("voice-isolator-v1")
+
+
+def test_the_repository_id_resolves_to_the_checkpoint_of_the_mode(
+ tmp_path, monkeypatch):
+ weights = tmp_path / "w.safetensors"
+ weights.write_bytes(b"released weights")
+ calls = []
+
+ def hf_hub_download(repo_id, filename, revision=None):
+ calls.append((repo_id, filename, revision))
+ return str(weights)
+
+ monkeypatch.setitem(
+ sys.modules,
+ "huggingface_hub",
+ types.SimpleNamespace(hf_hub_download=hf_hub_download),
+ )
+ digest = hashlib.sha256(b"released weights").hexdigest()
+ for name in registry.MODE_MODELS.values():
+ monkeypatch.setitem(registry.MODELS, name,
+ dict(registry.MODELS[name], sha256=digest))
+
+ paths = [
+ registry.resolve(registry.REPO_ID),
+ registry.resolve(registry.REPO_ID, "streaming"),
+ registry.resolve("voice-isolator-v1", "streaming"),
+ ]
+
+ assert registry.REPO_ID == "inworld/voice-isolator"
+ assert paths == [str(weights)] * 3
+ assert [filename for _, filename, _ in calls] == [
+ "denoiser.safetensors", "denoiser_realtime.safetensors",
+ "denoiser.safetensors"
+ ]
+ assert {repo_id for repo_id, _, _ in calls} == {registry.REPO_ID}
+ with pytest.raises(ValueError, match="mode must be one of"):
+ registry.resolve(registry.REPO_ID, "live")
+
+
+def test_an_unreleased_name_is_refused_rather_than_loaded_unverified(
+ monkeypatch):
+ entry = dict(registry.MODELS["voice-isolator-v1"], sha256=None)
+ monkeypatch.setitem(registry.MODELS, "voice-isolator-v1", entry)
+ with pytest.raises(ValueError, match="not released yet"):
+ registry.resolve("voice-isolator-v1")
+
+
+def test_the_file_hash_is_read_in_blocks(tmp_path):
+ p = tmp_path / "w.bin"
+ p.write_bytes(b"x" * (3 << 20))
+ digest = registry.sha256_file(str(p))
+ assert digest == hashlib.sha256(b"x" * (3 << 20)).hexdigest()
+
+
+def test_a_hub_failure_names_the_file_to_load_by_path(monkeypatch):
+
+ def hf_hub_download(repo_id, filename, revision=None):
+ raise OSError(f"404 Client Error: {repo_id}/{filename}@{revision}")
+
+ monkeypatch.setitem(
+ sys.modules,
+ "huggingface_hub",
+ types.SimpleNamespace(hf_hub_download=hf_hub_download),
+ )
+ with pytest.raises(RuntimeError, match="by its path") as info:
+ registry.resolve("voice-isolator-v1")
+ assert "inworld/voice-isolator/denoiser.safetensors" in str(info.value)
+ assert isinstance(info.value.__cause__, OSError)
+
+
+def test_pinned_names_fetch_the_published_files(monkeypatch):
+ fetched = []
+
+ def hf_hub_download(repo_id, filename, revision=None):
+ fetched.append((repo_id, filename, revision))
+ raise OSError("offline")
+
+ monkeypatch.setitem(
+ sys.modules,
+ "huggingface_hub",
+ types.SimpleNamespace(hf_hub_download=hf_hub_download),
+ )
+
+ for former in ("voice-isolator-v0", "voice-isolator-v0-realtime"):
+ with pytest.raises(RuntimeError, match="by its path"):
+ registry.resolve(former)
+
+ offline = ("inworld/voice-isolator", "denoiser.safetensors",
+ registry.PINNED["voice-isolator-v0"]["revision"])
+ live = ("inworld/voice-isolator", "denoiser_realtime.safetensors",
+ registry.PINNED["voice-isolator-v0-realtime"]["revision"])
+ assert fetched == [offline, live]
+ assert not set(registry.PINNED) & set(registry.MODELS)
+
+
+def test_the_v0_names_keep_the_shipped_files_when_v1_changes(
+ tmp_path, monkeypatch):
+ candidate = tmp_path / "denoiser.safetensors"
+ candidate.write_bytes(b"a release candidate")
+ calls = []
+
+ def hf_hub_download(repo_id, filename, revision=None):
+ calls.append((repo_id, filename, revision))
+ return str(candidate)
+
+ monkeypatch.setitem(
+ sys.modules,
+ "huggingface_hub",
+ types.SimpleNamespace(hf_hub_download=hf_hub_download),
+ )
+ monkeypatch.setitem(
+ registry.MODELS, "voice-isolator-v1",
+ dict(registry.MODELS["voice-isolator-v1"],
+ sha256=hashlib.sha256(b"a release candidate").hexdigest()))
+
+ v1 = registry.resolve("voice-isolator-v1")
+
+ assert v1 == str(candidate)
+ # the published v0 rows' name refuses the new file rather than load it
+ with pytest.raises(RuntimeError,
+ match="Checksum mismatch for voice-isolator-v0"):
+ registry.resolve("voice-isolator-v0")
+ assert registry.PINNED["voice-isolator-v0"]["sha256"].startswith("647335a6")
+ assert len(calls) == 2
diff --git a/tests/inworld/voice_isolation/test_scan.py b/tests/inworld/voice_isolation/test_scan.py
new file mode 100644
index 0000000..9e9ae80
--- /dev/null
+++ b/tests/inworld/voice_isolation/test_scan.py
@@ -0,0 +1,177 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The selective scan: chunks against the frame-by-frame recurrence."""
+
+# pylint: disable=protected-access
+import pytest
+import torch
+
+from inworld.voice_isolation import model
+from inworld.voice_isolation import scan
+
+
+def _inputs(batch, frames, channels, state, seed=0):
+ g = torch.Generator().manual_seed(seed)
+
+ def rand(*shape):
+ return torch.randn(*shape, generator=g)
+
+ return dict(
+ u=rand(batch, frames, channels),
+ delta=torch.nn.functional.softplus(rand(batch, frames, channels) * 2),
+ a=-torch.exp(rand(channels, state)),
+ b=rand(batch, frames, state),
+ c=rand(batch, frames, state),
+ d=rand(channels),
+ z=rand(batch, frames, channels),
+ )
+
+
[email protected]("frames", [1, 2, 7, 64, 203])
+def test_the_scan_matches_the_recurrence(frames, monkeypatch):
+ monkeypatch.setattr(scan, "BLOCK", 5)
+ kw = _inputs(3, frames, 5, 4)
+ y, h = scan.selective_scan(**kw)
+ ref, href = scan.selective_scan_reference(**kw)
+ assert torch.allclose(y, ref, atol=1e-5, rtol=1e-5)
+ assert torch.allclose(h, href, atol=1e-5, rtol=1e-5)
+ assert y.dtype == torch.float32 and y.shape == kw["u"].shape
+
+
+def test_a_carried_state_splits_the_scan_anywhere(monkeypatch):
+ monkeypatch.setattr(scan, "BLOCK", 3)
+ kw = _inputs(2, 40, 6, 3, seed=1)
+ whole, final = scan.selective_scan(**kw)
+ parts, state = [], None
+ for start, stop in ((0, 1), (1, 17), (17, 18), (18, 40)):
+ piece = {
+ k: (v[:, start:stop] if v.ndim == 3 else v) for k, v in kw.items()
+ }
+ y, state = scan.selective_scan(**piece, state=state)
+ parts.append(y)
+ assert torch.allclose(torch.cat(parts, 1), whole, atol=1e-5)
+ assert torch.allclose(state, final, atol=1e-5)
+
+
+def _metal_or_skip():
+ if not torch.backends.mps.is_available():
+ pytest.skip("the Metal scan runs on Apple's GPU")
+ if scan.metal_kernel() is None:
+ pytest.skip("this PyTorch cannot compile Metal kernels")
+
+
[email protected]("frames", [1, 2, 46, 203])
[email protected]("carried", [False, True])
[email protected]("gated", [False, True])
+def test_the_metal_scan_matches_the_recurrence(frames, carried, gated):
+ _metal_or_skip()
+ kw = _inputs(3, frames, 37, 16, seed=frames)
+ if not gated:
+ kw["z"] = None
+ state = torch.randn(3, 37, 16) if carried else None
+
+ y, h = scan.selective_scan(**{
+ k: None if v is None else v.to("mps") for k, v in kw.items()
+ },
+ state=None if state is None else state.to("mps"))
+
+ ref, href = scan.selective_scan_reference(**kw, state=state)
+ assert y.device.type == "mps" and y.shape == kw["u"].shape
+ assert torch.allclose(y.cpu(), ref, atol=1e-5, rtol=1e-5)
+ assert torch.allclose(h.cpu(), href, atol=1e-5, rtol=1e-5)
+
+
+def test_more_states_than_the_metal_scan_holds_take_the_torch_scan():
+ _metal_or_skip()
+ kw = _inputs(2, 9, 5, scan.METAL_STATES + 1, seed=5)
+
+ y, _ = scan.selective_scan(**{k: v.to("mps") for k, v in kw.items()})
+
+ ref, _ = scan.selective_scan_reference(**kw)
+ assert torch.allclose(y.cpu(), ref, atol=1e-5, rtol=1e-5)
+
+
+def test_fast_decays_do_not_overflow():
+ kw = _inputs(1, 50, 4, 2)
+ kw["delta"] = kw["delta"] * 100
+ y, _ = scan.selective_scan(**kw)
+ assert torch.isfinite(y).all()
+ ref, _ = scan.selective_scan_reference(**kw)
+ assert torch.allclose(y, ref, atol=1e-4, rtol=1e-4)
+
+
+def test_the_mamba_module_carries_its_convolution_and_state():
+ torch.manual_seed(0)
+ mamba = model.Mamba(8, 4, 3, 2).eval()
+ with torch.no_grad():
+ for p in mamba.parameters():
+ p.add_(torch.randn_like(p) * 0.1)
+ x = torch.randn(2, 25, 8)
+ with torch.inference_mode():
+ whole, (tail, state) = mamba(x)
+ first, carried = mamba(x[:, :1])
+ assert carried[0].shape == (2, 16, 2)
+ second, carried = mamba(x[:, 1:9], carried)
+ third, (tail2, state2) = mamba(x[:, 9:], carried)
+ assert torch.allclose(torch.cat([first, second, third], 1),
+ whole,
+ atol=1e-5)
+ assert torch.allclose(tail2, tail, atol=1e-5) and torch.allclose(
+ state2, state, atol=1e-5)
+ assert tail.shape == (2, 16, 2)
+
+
+def test_the_two_sided_block_is_causal_only_when_streaming():
+ torch.manual_seed(0)
+ block = model.BidirectionalMamba(8, 4, 3, 2, causal=False).eval()
+ with torch.no_grad():
+ for p in block.parameters():
+ p.add_(torch.randn_like(p) * 0.1)
+ x = torch.randn(1, 30, 8)
+ x2 = x.clone()
+ x2[:, 20:] += 1.0
+ with torch.inference_mode():
+ assert torch.allclose(block(x, causal=True)[:, :20],
+ block(x2, causal=True)[:, :20],
+ atol=1e-6)
+ assert not torch.allclose(
+ block(x)[:, :20], block(x2)[:, :20], atol=1e-4)
+
+
+def test_the_kernel_path_matches_the_recurrence_when_installed():
+ pytest.importorskip("mamba_ssm")
+ if not torch.cuda.is_available():
+ pytest.skip("the fused kernels run on CUDA")
+ assert scan.kernel() is not None
+ kw = {k: v.cuda() for k, v in _inputs(3, 150, 8, 4, seed=2).items()}
+ y, h = scan.selective_scan(**kw)
+ ref, href = scan.selective_scan_reference(**kw)
+ assert torch.allclose(y, ref, atol=1e-5, rtol=1e-5)
+ assert torch.allclose(h, href, atol=1e-5, rtol=1e-5)
+
+
+def test_the_fused_kernels_agree_when_installed():
+ mamba_ssm = pytest.importorskip("mamba_ssm")
+ if not torch.cuda.is_available():
+ pytest.skip("the fused kernels run on CUDA")
+ torch.manual_seed(0)
+ ours = model.Mamba(32, 16, 4, 2).cuda().eval()
+ theirs = mamba_ssm.Mamba(d_model=32, d_state=16, d_conv=4,
+ expand=2).cuda().eval()
+ theirs.load_state_dict(ours.state_dict())
+ x = torch.randn(3, 100, 32, device="cuda")
+ with torch.inference_mode():
+ y, _ = ours(x)
+ ref = theirs(x)
+ assert torch.allclose(y, ref, atol=1e-4, rtol=1e-4)
diff --git a/tests/inworld/voice_isolation/test_streaming.py b/tests/inworld/voice_isolation/test_streaming.py
new file mode 100644
index 0000000..52d8c68
--- /dev/null
+++ b/tests/inworld/voice_isolation/test_streaming.py
@@ -0,0 +1,509 @@
+# Copyright 2026 Inworld AI
+#
+# 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.
+"""The stream against the whole-clip forward at the same position."""
+
+import numpy as np
+import pytest
+import torch
+
+from inworld.voice_isolation import streaming
+
+SR = 48000
+
+
+def _clip(seconds=0.05, seed=0):
+ """A clip that starts with one window of silence.
+
+ Zero padding (the stream) and reflect padding (a clip) then agree at the
+ start; the end differs by construction and is left out of comparisons.
+ """
+ g = torch.Generator().manual_seed(seed)
+ return torch.cat(
+ [torch.zeros(64),
+ torch.randn(int(seconds * SR), generator=g) * 0.3])
+
+
+def _run(stream, clip, sizes):
+ pieces, pos, index = [], 0, 0
+ while pos < clip.shape[-1]:
+ step = sizes[index % len(sizes)]
+ pieces.append(stream.push(clip[..., pos:pos + step]))
+ pos += step
+ index += 1
+ pieces.append(stream.flush())
+ return torch.cat(pieces, dim=-1)
+
+
[email protected]("lookahead,block", [(0, 1), (0, 3), (2, 4), (2, 7)])
+def test_the_stream_equals_the_whole_clip_at_its_position(
+ dual_model, lookahead, block):
+ dual_model.set_lookahead(lookahead)
+ clip = _clip()
+ with torch.inference_mode():
+ whole = dual_model(clip[None])[0]
+ out = _run(streaming.Stream(dual_model, block_frames=block), clip,
+ (37, 101, 5))
+ assert out.shape == clip.shape
+ tail = 2 * dual_model.config.n_fft
+ assert torch.allclose(out[:-tail], whole[:-tail], atol=1e-5)
+
+
+def test_piece_sizes_do_not_change_the_output(dual_model):
+ """Within the attention cache, how the audio arrives does not matter."""
+ dual_model.set_lookahead(0)
+ clip = _clip(0.04)
+ a = _run(streaming.Stream(dual_model, block_frames=4), clip, (1000,))
+ b = _run(streaming.Stream(dual_model, block_frames=4), clip, (1, 7, 300))
+ assert torch.allclose(a, b, atol=1e-6)
+
+
+def test_samples_are_released_once_final_and_nothing_is_lost(dual_model):
+ dual_model.set_lookahead(2)
+ stream = streaming.Stream(dual_model, block_frames=4)
+ clip = _clip()
+ released = 0
+ for pos in range(0, len(clip), 500):
+ out = stream.push(clip[pos:pos + 500])
+ released += len(out)
+ fed = min(pos + 500, len(clip))
+ assert released <= fed
+ assert released >= fed - stream.latency_samples - stream.hop
+ released += len(stream.flush())
+ assert released == len(clip)
+ assert stream.latency_samples == 64 + 16 * 2 # the block adds none
+ assert stream.latency_seconds == pytest.approx(stream.latency_samples / SR)
+
+
+def test_the_stream_needs_a_streaming_position(dual_model, offline_model):
+ dual_model.set_offline()
+ with pytest.raises(ValueError, match="streaming position"):
+ streaming.Stream(dual_model)
+ with pytest.raises(ValueError, match="streaming position"):
+ streaming.Stream(offline_model)
+ dual_model.set_lookahead(0)
+ with pytest.raises(ValueError, match="at least one frame"):
+ streaming.Stream(dual_model, block_frames=0)
+
+
+def test_flush_ends_the_stream(dual_model):
+ dual_model.set_lookahead(0)
+ stream = streaming.Stream(dual_model)
+ clip = _clip(0.02)
+ out = torch.cat([stream.push(clip), stream.flush()])
+ assert out.shape == clip.shape
+ assert stream.flush().numel() == 0
+ with pytest.raises(RuntimeError, match="flushed"):
+ stream.push(clip)
+
+
+def test_numpy_in_numpy_out_and_bad_pieces_refused(dual_model):
+ dual_model.set_lookahead(0)
+ stream = streaming.Stream(dual_model)
+ out = stream.push(_clip(0.02).numpy())
+ assert isinstance(out, np.ndarray) and out.dtype == np.float32
+ assert isinstance(stream.flush(as_numpy=True), np.ndarray)
+ stream = streaming.Stream(dual_model)
+ with pytest.raises(ValueError, match="mono float"):
+ stream.push(torch.zeros(1, 2, 10))
+ with pytest.raises(ValueError, match="mono float"):
+ stream.push(torch.zeros(10, dtype=torch.int16))
+
+
+def test_a_short_cache_bounds_the_attention_past(dual_model):
+ dual_model.set_lookahead(0)
+ clip = _clip(0.1)
+ unbounded = _run(streaming.Stream(dual_model, block_frames=4), clip, (640,))
+ bounded = _run(streaming.Stream(dual_model, block_frames=4, cache_frames=8),
+ clip, (640,))
+ assert bounded.shape == unbounded.shape
+ assert not torch.allclose(bounded, unbounded, atol=1e-4)
+
+
+def test_clips_stream_in_lockstep_as_a_batch(dual_model):
+ dual_model.set_lookahead(2)
+ clips = torch.stack([_clip(seed=1), _clip(seed=2)])
+ alone = [_run(streaming.Stream(dual_model), c, (500,)) for c in clips]
+ together = _run(streaming.Stream(dual_model), clips, (500,))
+ assert together.shape == clips.shape
+ for j in range(2):
+ assert torch.allclose(together[j], alone[j], atol=1e-5)
+ assert isinstance(
+ streaming.Stream(dual_model).push(clips[:, :300].numpy()), np.ndarray)
+ with pytest.raises(ValueError, match="same rank and batch"):
+ stream = streaming.Stream(dual_model)
+ stream.push(clips[:, :100])
+ stream.push(clips[0, :100])
+
+
+def test_silence_appended_to_a_clip_changes_nothing_before_its_last_window(
+ dual_model):
+ dual_model.set_lookahead(0)
+ clip = _clip()
+ alone = _run(streaming.Stream(dual_model), clip, (640,))
+ padded = _run(streaming.Stream(dual_model),
+ torch.cat([clip, torch.zeros(3000)]), (640,))
+ n_fft = dual_model.config.n_fft
+ assert torch.allclose(padded[:len(clip) - n_fft], alone[:-n_fft], atol=1e-6)
+
+
[email protected]("lookahead", [0, 2])
+def test_padded_clips_with_their_lengths_end_exactly_as_alone(
+ dual_model, lookahead):
+ dual_model.set_lookahead(lookahead)
+ short, long = _clip(0.03, seed=3), _clip(0.04, seed=4)
+ alone = [
+ _run(streaming.Stream(dual_model), c, (700,)) for c in (short, long)
+ ]
+ batch = torch.stack(
+ [torch.cat([short, torch.zeros(len(long) - len(short))]), long])
+ together = _run(
+ streaming.Stream(dual_model, lengths=[len(short), len(long)]), batch,
+ (700,))
+ assert torch.allclose(together[0, :len(short)], alone[0], atol=1e-5)
+ assert torch.allclose(together[1], alone[1], atol=1e-5)
+ with pytest.raises(ValueError, match="lengths names every clip"):
+ streaming.Stream(dual_model, lengths=[1]).push(batch[:, :100])
+
+
+def _windowed(model, clip, window, crossfade, cache=None):
+ stream = streaming.Stream(model,
+ block_frames=4,
+ cache_frames=cache,
+ window_frames=window,
+ crossfade_frames=crossfade)
+ return _run(stream, clip, (301,)), stream
+
+
+def test_windowed_attention_equals_the_plain_stream_before_the_first_crossfade(
+ dual_model):
+ dual_model.set_lookahead(0)
+ clip = _clip(seconds=0.5, seed=7)
+ plain, _ = _windowed(dual_model, clip, None, None)
+ windowed, stream = _windowed(dual_model, clip, 40, 10)
+ assert windowed.shape == plain.shape == clip.shape
+ assert torch.isfinite(windowed).all()
+ # Frames before the first crossfade (30 frames) are lane A alone: the
+ # samples agree until the synthesis window that first overlaps a blended
+ # frame.
+ same = 30 * stream.hop - stream.n_fft
+ assert torch.equal(windowed[:same], plain[:same])
+ assert not torch.allclose(windowed, plain)
+
+
+def test_windowed_attention_swaps_lanes_at_every_boundary_and_bounds_each_lane(
+ dual_model):
+ dual_model.set_lookahead(0)
+ clip = _clip(seconds=0.5, seed=8)
+ out, stream = _windowed(dual_model, clip, 40, 10, cache=1000)
+ assert out.shape == clip.shape and torch.isfinite(out).all()
+ frames = clip.shape[-1] // stream.hop
+ expected = [40 * k for k in range(1, frames // 40 + 1)]
+ assert stream.boundaries == expected[:len(stream.boundaries)]
+ assert len(stream.boundaries) >= 30
+ for state in stream.states:
+ if isinstance(state, streaming._AttentionState): # pylint: disable=protected-access
+ assert state.end <= 40 + 10
+
+
+def test_windowed_attention_flushes_inside_a_crossfade(dual_model):
+ dual_model.set_lookahead(0)
+ g = torch.Generator().manual_seed(9)
+ # ends five frames into the first crossfade, which starts at frame 30
+ clip = torch.randn(35 * 16 + 8, generator=g) * 0.3
+ out, stream = _windowed(dual_model, clip, 40, 10)
+ assert out.shape == clip.shape and torch.isfinite(out).all()
+ assert stream.states_b is not None and not stream.boundaries
+
+
[email protected]("window,crossfade", [(40, None), (None, 10), (40, 40),
+ (40, 0)])
+def test_windowed_attention_arguments_go_together(dual_model, window,
+ crossfade):
+ dual_model.set_lookahead(0)
+ with pytest.raises(ValueError):
+ streaming.Stream(dual_model,
+ window_frames=window,
+ crossfade_frames=crossfade)
+
+
+def test_windowed_clips_stream_in_lockstep_as_a_batch(dual_model):
+ dual_model.set_lookahead(2)
+ clips = torch.stack(
+ [_clip(seconds=0.3, seed=1),
+ _clip(seconds=0.3, seed=2)])
+ alone = [_windowed(dual_model, c, 40, 10)[0] for c in clips]
+ together, _ = _windowed(dual_model, clips, 40, 10)
+ assert together.shape == clips.shape
+ for j in range(2):
+ assert torch.allclose(together[j], alone[j], atol=1e-5)
+
+
+def _lane_values(model, clip, window, crossfade, block, sizes, monkeypatch):
+ """The blended decoder output per frame when each lane emits its own
+ constant: 0 for the first lane, 1 for the next, and so on."""
+ lanes, alive = {}, [] # every lane is kept alive so no id is reused
+ clone = streaming._clone_states # pylint: disable=protected-access
+
+ def tagged_clone(states):
+ fresh = clone(states)
+ alive.append(fresh)
+ lanes[id(fresh)] = len(alive)
+ return fresh
+
+ monkeypatch.setattr(streaming, "_clone_states", tagged_clone)
+
+ def backbone(self, features, states, film): # pylint: disable=unused-argument
+ return torch.cat([
+ torch.full_like(features, float(lanes.get(id(lane), 0)))
+ for lane in states
+ ])
+
+ monkeypatch.setattr(streaming.Stream, "_backbone", backbone)
+ decode = streaming._PackedBands.decode # pylint: disable=protected-access
+
+ def constant(self, features):
+ """The decoder's output shape, each batch row (lanes run stacked)
+ filled with its lane's constant."""
+ out = decode(self, features)
+ return features.flatten(1)[:, 0].view(-1, 1, 1, 1).to(
+ out.dtype).expand_as(out).clone()
+
+ monkeypatch.setattr(streaming._PackedBands, "decode", constant) # pylint: disable=protected-access
+ blocks, values = [], []
+ run = streaming.Stream._run_block # pylint: disable=protected-access
+
+ def spy(self, spectra):
+ start = self._frames # pylint: disable=protected-access
+ raw = run(self, spectra)
+ blocks.append((start, spectra.shape[0]))
+ values.extend(float(v) for v in raw[:, 0, 0, 0])
+ return raw
+
+ monkeypatch.setattr(streaming.Stream, "_run_block", spy)
+ stream = streaming.Stream(model,
+ block_frames=block,
+ window_frames=window,
+ crossfade_frames=crossfade)
+ _run(stream, clip, sizes)
+ return blocks, values, stream
+
+
[email protected]("window,crossfade,block,sizes", [
+ (40, 10, 4, (301,)),
+ (40, 10, 4, (37, 101, 5)),
+ (37, 9, 4, (480,)),
+ (30, 11, 7, (16 * 13 + 3,)),
+ (25, 5, 3, (97, 211)),
+])
+def test_the_new_lane_owns_every_frame_from_its_boundary(
+ dual_model, window, crossfade, block, sizes, monkeypatch):
+ dual_model.set_lookahead(0)
+ clip = _clip(seconds=0.5, seed=11)
+ blocks, values, stream = _lane_values(dual_model, clip, window, crossfade,
+ block, sizes, monkeypatch)
+ start = window - crossfade
+ for first, count in blocks:
+ last = first + count - 1
+ assert first // window == last // window, (first, count)
+ assert not first % window < start <= last % window, (first, count)
+ for f, value in enumerate(values):
+ k, offset = divmod(f, window)
+ ramp = min(max((offset - start + 1) / crossfade, 0.0), 1.0)
+ assert value == pytest.approx(k + ramp, abs=1e-5), (f, value)
+ assert stream.boundaries == [
+ window * k for k in range(1,
+ len(values) // window + 1)
+ ]
+
+
[email protected]("sizes", [(301,), (37, 101, 5), (16 * 40 - 8,), (1,)])
+def test_windowed_output_does_not_depend_on_the_pushes(dual_model, sizes):
+ dual_model.set_lookahead(2)
+ clip = _clip(seconds=0.3, seed=12)
+ reference, _ = _windowed(dual_model, clip, 40, 10)
+ out = _run(
+ streaming.Stream(dual_model,
+ block_frames=4,
+ window_frames=40,
+ crossfade_frames=10), clip, sizes)
+ assert torch.allclose(out, reference, atol=1e-5)
+
+
[email protected]("sizes", [(37, 101, 5), (16 * 40 - 8,), (1,)])
+def test_the_plain_stream_does_not_depend_on_the_pushes_within_its_cache(
+ dual_model, sizes):
+ dual_model.set_lookahead(2)
+ clip = _clip(seconds=0.3, seed=12)
+ frames = clip.shape[-1] // dual_model.config.hop_length + 1
+ reference = _run(
+ streaming.Stream(dual_model, block_frames=4, cache_frames=frames), clip,
+ (301,))
+ out = _run(
+ streaming.Stream(dual_model, block_frames=4, cache_frames=frames), clip,
+ sizes)
+ assert torch.allclose(out, reference, atol=1e-5)
+
+
[email protected]("lookahead", [0, 2, 4])
[email protected]("block", [1, 4, 7])
+def test_a_windowed_checkpoint_streams_as_its_forward_beyond_the_cache(
+ windowed_model, lookahead, block):
+ """The stream keeps the training bound, a frame seeing itself and the
+ window - 1 frames before it, across every block and cache eviction."""
+ windowed_model.set_lookahead(lookahead)
+ clip = _clip(0.1)
+ config = windowed_model.config
+ assert clip.shape[
+ -1] // config.hop_length > 4 * config.attention_window_frames
+ with torch.inference_mode():
+ whole = windowed_model(clip[None])[0]
+ stream = streaming.Stream(windowed_model, block_frames=block)
+ assert stream.cache_frames == config.attention_window_frames
+ out = _run(stream, clip, (37, 101, 5))
+ tail = 2 * config.n_fft
+ assert torch.allclose(out[:-tail], whole[:-tail], atol=1e-5)
+
+
[email protected]("sizes", [(1,), (37, 101, 5), (640,)])
+def test_a_windowed_checkpoint_does_not_depend_on_the_pushes(
+ windowed_model, sizes):
+ windowed_model.set_lookahead(2)
+ clip = _clip(0.1, seed=5)
+ reference = _run(streaming.Stream(windowed_model, block_frames=4), clip,
+ (301,))
+ out = _run(streaming.Stream(windowed_model, block_frames=4), clip, sizes)
+ assert torch.allclose(out, reference, atol=1e-5)
+
+
+def test_a_cache_of_the_window_less_one_is_exact_and_a_shorter_one_bounds(
+ windowed_model):
+ windowed_model.set_lookahead(0)
+ clip = _clip(0.1)
+ window = windowed_model.config.attention_window_frames
+ with torch.inference_mode():
+ whole = windowed_model(clip[None])[0]
+ exact = _run(
+ streaming.Stream(windowed_model,
+ block_frames=4,
+ cache_frames=window - 1), clip, (640,))
+ short = _run(
+ streaming.Stream(windowed_model,
+ block_frames=4,
+ cache_frames=window // 2), clip, (640,))
+ tail = 2 * windowed_model.config.n_fft
+ assert torch.allclose(exact[:-tail], whole[:-tail], atol=1e-5)
+ assert not torch.allclose(short[:-tail], whole[:-tail], atol=1e-4)
+
+
+def test_windowed_lanes_run_on_a_windowed_checkpoint(windowed_model):
+ windowed_model.set_lookahead(2)
+ clip = _clip(0.1, seed=6)
+ out = _run(
+ streaming.Stream(windowed_model,
+ block_frames=4,
+ window_frames=40,
+ crossfade_frames=10), clip, (37, 101, 5))
+ assert out.shape == clip.shape and torch.isfinite(out).all()
+
+
[email protected]("sizes", [(301,), (37, 101, 5), (1,)])
+def test_compacting_the_attention_buffer_changes_nothing_but_rounding(
+ dual_model, sizes):
+ dual_model.set_lookahead(2)
+ clip = _clip(seconds=0.4, seed=11)
+ compacting = streaming.Stream(dual_model, block_frames=4, cache_frames=8)
+ roomy = streaming.Stream(dual_model, block_frames=4, cache_frames=8)
+ config = dual_model.config
+ roomy._attention = streaming._AttentionCache( # pylint: disable=protected-access
+ 8, 4096, config.width // config.num_heads,
+ config.attention_window_frames, clip.device)
+
+ out = _run(compacting, clip, sizes)
+
+ reference = _run(roomy, clip, sizes)
+ assert compacting._attention.capacity < clip.shape[-1] // config.hop_length # pylint: disable=protected-access
+ assert torch.allclose(out, reference, atol=1e-5)
+
+
[email protected]("batch,frames", [(1, 1), (3, 4)])
+def test_the_packed_bands_equal_the_model_encoders_and_decoder_heads(
+ dual_model, batch, frames):
+ dual_model.set_lookahead(2)
+ packed = streaming._PackedBands(dual_model) # pylint: disable=protected-access
+ g = torch.Generator().manual_seed(12)
+ bins = dual_model.config.n_fft // 2 + 1
+ spectrum = torch.complex(torch.randn(batch, bins, frames, generator=g),
+ torch.randn(batch, bins, frames, generator=g))
+ features = torch.randn(batch,
+ len(dual_model.edges),
+ frames,
+ dual_model.config.width,
+ generator=g)
+
+ with torch.inference_mode():
+ encoded = packed.encode(dual_model, spectrum)
+ decoded = packed.decode(features)
+ expected_encoded = dual_model.encode(spectrum)
+ expected_decoded = dual_model.denoise_decoder(features)
+
+ assert encoded.shape == expected_encoded.shape
+ assert torch.allclose(encoded, expected_encoded, atol=1e-5)
+ assert decoded.dtype == torch.float32
+ assert decoded.shape == expected_decoded.shape
+ assert torch.allclose(decoded, expected_decoded, atol=1e-5)
+
+
+def test_streams_of_one_model_share_its_packed_band_weights(dual_model):
+ dual_model.set_lookahead(2)
+
+ first = streaming.Stream(dual_model)
+ second = streaming.Stream(dual_model, block_frames=7)
+
+ # pylint: disable-next=protected-access
+ assert first._bands is second._bands
+
+
+def test_a_new_stream_follows_band_weights_changed_in_place(dual_model):
+ dual_model.set_lookahead(2)
+ clip = _clip()
+ before = _run(streaming.Stream(dual_model), clip, (480,))
+ changed = {
+ name:
+ tensor * 1.5 if name.startswith(("encoders.0.", "denoise_decoder."
+ "heads.0.")) else tensor
+ for name, tensor in dual_model.state_dict().items()
+ }
+ dual_model.load_state_dict(changed)
+ with torch.inference_mode():
+ whole = dual_model(clip[None])[0]
+
+ after = _run(streaming.Stream(dual_model), clip, (480,))
+
+ tail = 2 * dual_model.config.n_fft
+ assert not torch.allclose(after[:-tail], before[:-tail], atol=1e-4)
+ assert torch.allclose(after[:-tail], whole[:-tail], atol=1e-5)
+
+
+def test_a_model_built_in_inference_mode_streams(tiny):
+ with torch.inference_mode():
+ model = tiny.dual()
+ model.set_lookahead(2)
+ clip = _clip()
+ with torch.inference_mode():
+ whole = model(clip[None])[0]
+
+ out = _run(streaming.Stream(model), clip, (480,))
+
+ tail = 2 * model.config.n_fft
+ assert torch.allclose(out[:-tail], whole[:-tail], atol=1e-5)