the ultimate vocal synthesizer - sing, speak, beatbox, and more
Rust
Hill climb: rules, log and a speech judge for one experiment at a time
Jameson Hodge5186d64a3330
diff --git a/docs/hill-climb/README.md b/docs/hill-climb/README.mdnew file mode 100644index 0000000..c114548--- /dev/null+++ b/docs/hill-climb/README.md@@ -0,0 +1,133 @@+# Hill climb: one measured step at a time toward a real voice++An agent improves CHIMERA's voice in small steps. Each run is one experiment: one hypothesis and+one change, measured against a real singer (the Children's Song Dataset, see+[csd-comparison.md](../csd-comparison.md)) and guarded so that speech, the tests and real-time+speed don't get worse. A change is kept only if the judges call it better. Nothing reaches main+until the owner has listened to the result and merged it.++The log of every experiment is [log.md](log.md). Read it before you start.++## Before you start++- **Where.** Work in this worktree, on branch `t3/vocal-quality-hill-climb`. Never commit to+ main.+- **Data.** The dataset is in `~/datasets/csd/CSD` (fetch it with `tools/fetch-csd.sh`). The+ speech judge needs `tools/asr/setup.sh` once.+- **The best run so far** is in `out/hill/best/`: `score.json` and `report.md` (singer),+ `speech/wer.json` (speech) and `bench.txt` (speed). If it is missing, measure the current+ commit into `out/hill/best` the same way as below.++## One experiment++1. **Pick one hypothesis.** Read `out/hill/best/report.md` (the score table, largest costs+ first) and the log. Aim at a large cost the log doesn't show as exhausted, or try a new angle+ on one. Before you touch code, write down in a sentence or two:+ - what is physically wrong+ - what you will change+ - which terms should move+2. **Make the change.** Keep it small, readable and motivated by physiology, acoustics or+ phonetics. These are fair game:+ - the voice source (`crates/chimera/src/sources/`)+ - the voice (`voice/`)+ - the airway (`airway/`)+ - anatomy and articulation (`anatomy/`, `control/`)+ - the planners (`phonetics/`)+3. **Measure** (below). If the change adds a tunable value, you may try a few values. Log what+ you tried.+4. **Keep or revert** (below).+5. **Log it** and stop. One experiment per run. If an idea needs a large rewrite or more than+ about an hour, log it under "Leads" as a proposal and pick something smaller.++## What you may not change++- **The judges.** Don't touch any of these:+ - `crates/chimera-cli/src/compare.rs`, `compare/score.rs`+ - `tools/asr/`+ - the held-out songs, the dataset, the sentences++ The comparison sings with the settings `render song` uses: pressure 9, tension 0.55 and+ 35-cent vibrato (`render_notes` in compare.rs). Change how the engine responds to those+ settings, not the settings.+- **The output.** No EQ, filter or effect that shapes the sound toward the singer's spectrum.+ Fix the cause in the source or the tract.+- **Special cases.** None for the dataset, one song, one measured value, or the female body+ alone. A body parameter is fine when it has an anatomical reason.+- **The singing convention.** `plan_song` puts the vowel on the beat and its consonants before+ it. Don't move consonants onto the beat to fit CSD's note starts. Voiced-consonant onsets are+ not scored for this reason.+- **The calibrated tables** (`crates/chimera/src/phonetics/*.generated.json`) by hand. If a+ change moves the vowels' formants, regenerate the tables with `chimera calibrate` and say so in+ the log.+- **The tests.** Don't weaken or delete one to let a change through. A failing test, other than+ a golden fixture (below), means the change is reverted.+- **The held-out songs as a guide.** Decide on the training verdict only, and don't choose+ changes by the held-out score. It is there to show whether a gain carries over.++## Measuring++```sh+cargo build --release -p chimera-cli+cargo run --release -p chimera-cli -- compare csd ~/datasets/csd/CSD out/hill/try --against out/hill/best/score.json+~/.cache/chimera-asr/.venv/bin/python tools/asr/speech_wer.py out/hill/try/speech --against out/hill/best/speech/wer.json+cargo run --release -q -p chimera --example bench > out/hill/try/bench.txt+```++1. **Singer.** The comparison ends with a verdict: BETTER, WORSE or NO CLEAR CHANGE, and the+ reasons when worse. `out/hill/try/report.md` has the new score table.+2. **Speech.** The speech judge ends with OK or WORSE. WORSE means the word error rate rose by+ more than 3 points. It also lists the sentences Whisper got wrong.+3. **Speed.** The bench prints the real-time load. Compare its `os=2` line with+ `out/hill/best/bench.txt`. It is noisy, so rerun it once before calling a change slower.++## Keep or revert++Keep the change only if all of these hold:++1. The singer verdict is **BETTER**.+2. The speech verdict is **OK**.+3. The bench is no more than **10 % slower**.+4. **The tests pass.**+ 1. Run `CHIMERA_BLESS=1 cargo test --workspace`. This regenerates the golden fixtures in+ `crates/chimera/tests/golden`, which change with any change to the sound.+ 2. Then run `cargo test --workspace` and `bun run wasm && bun test tests`. Both must pass.+ 3. Restore the fixtures with `git checkout -- crates/chimera/tests/golden`. They are blessed+ once per batch, when the batch goes to a PR, so the history doesn't carry a copy of them+ for every experiment. Until then the golden tests fail on this branch, which is expected.+ 4. `git status` must show only your change: no test file edited.++**If kept:**++1. Commit the engine change (without the fixtures). The message gives the hypothesis, the+ change, and the numbers:+ - training score before → after+ - held-out score before → after+ - speech word error rate before → after+ - the terms that moved+2. Replace `out/hill/best` with `out/hill/try`:+ `rm -rf out/hill/best && mv out/hill/try out/hill/best`.+3. Add the log entry, commit it, and push.++**If reverted:**++1. Restore the engine: `git checkout -- crates/`, and remove any new files the change added.+ Delete `out/hill/try`.+2. Add the log entry, commit it, and push anyway, so the next run doesn't retry the idea.++## The log entry++Add one entry at the end of `log.md`:++```markdown+### N. <short title> (kept | reverted)++- Hypothesis: what was wrong and why the change should fix it.+- Change: what changed, in which files; values tried.+- Singer: training score a → b, held-out c → d; the terms that moved.+- Speech: word error rate a → b.+- Verdict: the reasons, if reverted.+- Commit: the hash, if kept.+- Next: what this suggests trying, or not trying, next.+```++Update "Leads" at the top of the log when an experiment closes a lead or opens a new one.diff --git a/docs/hill-climb/log.md b/docs/hill-climb/log.mdnew file mode 100644index 0000000..a07ae10--- /dev/null+++ b/docs/hill-climb/log.md@@ -0,0 +1,43 @@+# Hill-climb log++The rules are in [README.md](README.md). Entries are in order, newest last.++## Baseline (2026-11-07)++- **Singer:** training score 1.433, held-out 1.590. 0 means every term is within her own+ variation; lower is better.+- **Speech:** word error rate 38.7 %. Harvard sentences 32.5 % (male) and 37.5 % (female);+ nonsense sentences 47.9 % and 38.0 %.+- **Speed:** the voice takes 18.3 % of one core in real time (`os=2`).++## Leads++The largest costs at the baseline, and what they point at. When an experiment closes a lead or+opens a new one, update this list and give the experiment's number.++1. **Spectral tilt and the fundamental.** Costs: level 4–8 kHz 5.4, H1−H2 2.1, level 2–4 kHz+ 1.4, level 0–0.5 kHz 1.4.+ - Too much energy above 2 kHz and too little below 500 Hz, on every vowel.+ - H1−H2 is too low on low notes (−5.8 dB, she has +4.0) and too high on high ones (+8.2 dB,+ she has +0.1).+ - Together they sound like a source that is too pressed. Look at the open quotient, skew and+ closure sharpness, and at how they vary with pitch and effort+ (`crates/chimera/src/sources/glottis.rs`, and how `voice/human_voice.rs` drives it).+2. **Aperiodicity.** Cost 2.9: the synth's is about twice hers. Look at jitter, shimmer, drift+ and aspiration noise in the source. She is a clean, trained voice.+3. **Phrase onsets.** Costs: vowel-initial 1.4, voiceless-initial 1.1.+ - Voicing starts about 20 ms early before a vowel.+ - Before /s/, /f/ and /h/ the synth voices 100–130 ms before the note, so the voicing runs+ into the fricative or comes before it.+ - Look at how a phrase starts: the 60 ms lead in `plan_song`, and the glottal abduction of a+ voiceless onset.+4. **Vibrato.** Costs: rate 0.67, share 0.62. The synth puts 35-cent vibrato on every long note+ at 5.5 Hz. She uses it on about two thirds of her long notes, at about 6.1 Hz+ (`vibrato_gesture` in `crates/chimera/src/phonetics/sing.rs`).+5. **Voicing in held notes.** Cost 0.26. Gaps mid-note, worst in en018a, en041a and en043a+ (0.65–0.70 voiced).+6. **Speech consonants.** Not scored, only guarded. Whisper mishears /tʃ/, /dʒ/, /ʃ/ and /s/:+ "sheet" as "feet", "chicken leg" as "quickly like", "juice" as "roost". This is for a later+ loop on speech.++## Experimentsdiff --git a/tools/asr/sentences.tsv b/tools/asr/sentences.tsvnew file mode 100644index 0000000..03f1b6b--- /dev/null+++ b/tools/asr/sentences.tsv@@ -0,0 +1,20 @@+harvard The birch canoe slid on the smooth planks.+harvard Glue the sheet to the dark blue background.+harvard It's easy to tell the depth of a well.+harvard These days a chicken leg is a rare dish.+harvard Rice is often served in round bowls.+harvard The juice of lemons makes fine punch.+harvard The box was thrown beside the parked truck.+harvard The hogs were fed chopped corn and garbage.+harvard Four hours of steady work faced us.+harvard A large size in stockings is hard to sell.+nonsense The green chair drinks the late song.+nonsense A cold paper walks under the sharp tree.+nonsense The thin road hears a loud milk.+nonsense Some bright doors sell the quiet fish.+nonsense The wet bird pushes a heavy number.+nonsense Her round table sings the dark rope.+nonsense A fast window paints the sweet stone.+nonsense The small river eats the black chain.+nonsense The long fork reads a soft hill.+nonsense One tall cloud fixes the warm bell.diff --git a/tools/asr/setup.sh b/tools/asr/setup.shnew file mode 100755index 0000000..3add5df--- /dev/null+++ b/tools/asr/setup.sh@@ -0,0 +1,9 @@+#!/usr/bin/env bash+# One-time setup for tools/asr/speech_wer.py: a Python env with faster-whisper in+# ~/.cache/chimera-asr (the small.en model, ~0.5 GB, downloads there on first use).+set -euo pipefail+dir="$HOME/.cache/chimera-asr"+mkdir -p "$dir/models"+[ -x "$dir/.venv/bin/python" ] || uv venv -q --python 3.12 "$dir/.venv"+uv pip install -q --python "$dir/.venv/bin/python" faster-whisper==1.2.1+echo "run: $dir/.venv/bin/python tools/asr/speech_wer.py <outdir> [--against earlier/wer.json]"diff --git a/tools/asr/speech_wer.py b/tools/asr/speech_wer.pynew file mode 100644index 0000000..2220cae--- /dev/null+++ b/tools/asr/speech_wer.py@@ -0,0 +1,108 @@+"""Speech intelligibility of the engine, scored by Whisper: render each sentence with+`chimera render text` in the male and female voices, transcribe it with faster-whisper+(small.en, greedy, so the same audio gives the same words) and count word errors.++usage: speech_wer.py <outdir> [--against earlier/wer.json]++Writes <outdir>/wer.json and the renders. With --against it says whether the word error rate+rose by more than SLACK points, which a tuning loop treats as a speech regression.++Set up once with tools/asr/setup.sh (a Python env and the model in ~/.cache/chimera-asr).+The sentences are in sentences.tsv: Harvard sentences (IEEE 1969) and semantically+unpredictable ones, which Whisper can't guess from context.+"""++import json+import os+import re+import subprocess+import sys+import wave+from concurrent.futures import ThreadPoolExecutor++import numpy as np+from faster_whisper import WhisperModel++HERE = os.path.dirname(os.path.abspath(__file__))+REPO = os.path.dirname(os.path.dirname(HERE))+CACHE = os.path.expanduser("~/.cache/chimera-asr/models")+BODIES = ("male", "female")+# word error rate (points) a change may add before it counts as a speech regression+SLACK = 3.0+++def words(text):+ text = re.sub(r"[^a-z' ]+", " ", text.lower().replace("’", "'"))+ return [w.strip("'") for w in text.split() if w.strip("'")]+++def edits(ref, hyp):+ d = list(range(len(hyp) + 1))+ for i, r in enumerate(ref, 1):+ prev, d[0] = d[0], i+ for j, h in enumerate(hyp, 1):+ prev, d[j] = d[j], min(d[j] + 1, d[j - 1] + 1, prev + (r != h))+ return d[len(hyp)]+++def load16k(path):+ """Mono float32 at 16 kHz from a 16-bit PCM WAV (band-limited FFT resampling)."""+ with wave.open(path) as w:+ ch, rate = w.getnchannels(), w.getframerate()+ x = np.frombuffer(w.readframes(w.getnframes()), dtype="<i2").astype(np.float64) / 32768.0+ x = x.reshape(-1, ch).mean(axis=1)+ n = int(round(len(x) * 16000 / rate))+ return (np.fft.irfft(np.fft.rfft(x)[: n // 2 + 1], n) * (n / len(x))).astype(np.float32)+++def main():+ args = sys.argv[1:]+ against = None+ if "--against" in args:+ i = args.index("--against")+ against = args[i + 1]+ del args[i : i + 2]+ out = args[0]+ os.makedirs(out, exist_ok=True)+ sentences = [line.rstrip("\n").split("\t") for line in open(os.path.join(HERE, "sentences.tsv"))]+ chimera = os.path.join(REPO, "target/release/chimera")+ jobs = [(kind, text, body, os.path.join(out, f"{kind}-{body}-{i + 1:02d}"))+ for i, (kind, text) in enumerate(sentences) for body in BODIES]++ def render(job):+ _, text, body, stem = job+ subprocess.run([chimera, "render", "text", stem, text, body], check=True, capture_output=True)++ with ThreadPoolExecutor(os.cpu_count()) as pool:+ list(pool.map(render, jobs))++ model = WhisperModel("small.en", device="cpu", compute_type="int8", cpu_threads=os.cpu_count(),+ download_root=CACHE)+ rows, totals = [], {}+ for kind, text, body, stem in jobs:+ segs, _ = model.transcribe(load16k(stem + ".wav"), language="en", beam_size=1, temperature=0.0,+ condition_on_previous_text=False, vad_filter=False)+ heard = " ".join(s.text.strip() for s in segs)+ ref = words(text)+ e = edits(ref, words(heard))+ rows.append({"kind": kind, "body": body, "text": text, "heard": heard, "errors": e, "words": len(ref)})+ for key in (f"{kind}-{body}", "all"):+ t = totals.setdefault(key, [0, 0])+ t[0] += e+ t[1] += len(ref)+ wer = {k: round(100.0 * e / n, 2) for k, (e, n) in totals.items()}+ report = {"wer": wer, "sentences": rows}+ with open(os.path.join(out, "wer.json"), "w") as f:+ json.dump(report, f, indent=1)+ for r in rows:+ if r["errors"]:+ print(f" {r['kind']:8s} {r['body']:6s} {r['errors']}/{r['words']} {r['text']} → {r['heard']}")+ print("word error rate (%): " + ", ".join(f"{k} {v}" for k, v in sorted(wer.items())))+ if against:+ old = json.load(open(against))["wer"]["all"]+ new = wer["all"]+ verdict = "WORSE" if new > old + SLACK else "OK"+ print(f"speech verdict against {against}: {verdict} (word error rate {old} → {new} %, slack {SLACK})")+++main()