- Python 100%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
README tables and flash section updated; AGENTS records the three integration traps (fp32-nominal, .weight property, silent multi-edit no-op that once turned an int8 bench into bf16-vs-bf16). |
||
| resonance | ||
| tests | ||
| .gitignore | ||
| AGENTS.md | ||
| LICENSE | ||
| pyproject.toml | ||
| README.md | ||
resonance
A small, best-effort OpenAI-compatible TTS server for
Chatterbox models — nano,
turbo, and multilingual v3 — running on CPU, with voice presets built
from WAV reference clips (voice cloning) exposed as the fixed voice
parameter of the OpenAI speech API.
Toy / personal-project scope: one model instance, a single generation lock, no streaming, simple FIFO queue.
How it fits together
- Inference is done by the
chatterbox-ttspackage (ChatterboxTurboTTS/ChatterboxMultilingualTTS,generate(),prepare_conditionals(), …). - Checkpoints are downloaded from HF into
models/chatterbox-<nano|turbo|multilingual>/. The multilingual one is v3 (t3_mtl23ls_v3), per the model card — the repo hosts every version of everything, we fetch exactly the v3 files. - A voice preset is a
Conditionalsobject extracted from a >5 s reference clip and saved asvoices/<name>.pt. The OAIvoiceparameter is simply the preset name. POST /v1/audio/speechaccepts the usual OpenAI request shape and returns audio bytes (mp3by default;wav/pcmnatively,opus/aac/flacvia ffmpeg).
Requirements
- Python 3.11 / 3.12
ffmpegon PATH formp3/opus/aac/flacresponses (not needed forwav/pcm)- ~3 GB disk per model, ~2 GB RAM at runtime (nano)
Setup
uv venv --python 3.12 .venv
source .venv/bin/activate
# CPU-only torch keeps the install small (chatterbox-tts pins torch 2.6 on py<3.14):
uv pip install torch==2.6.0 torchaudio==2.6.0 --index-url https://download.pytorch.org/whl/cpu
uv pip install -e .
This installs resonance-engine (a git dependency) — see the next section for what it is and when it is required.
Download a model (nano is the default; turbo is higher quality English; multilingual covers 23 languages with CFG + exaggeration controls; flash is the English block-diffusion model — near/above realtime on CPU):
python -m resonance download --model nano # or: turbo, multilingual, flash, all
The inference engine (resonance-engine)
resonance-engine is this server's own inference layer: first-class ports of every code path the resonance shims used to monkeypatch (the multilingual v3 AR sampling loop, flow-ODE options, torch.compile shims, precision handling) plus the vendored Chatterbox-Flash block-diffusion decoder (torch path, from the upstream MIT repo with the FlashInfer/MLX/CUDA-graph code stripped). Same-seed output is bit-exact against the chatterbox-tts / chatterbox-flash packages.
When it runs:
- flash always uses it (the package stack has no flash);
--use-engineroutes nano / turbo / multilingual through it too (same voices, presets, flags and output — it is the recommended backend);- without the flag, the other families use the chatterbox-tts package path unchanged.
It is installed automatically as a git dependency
(resonance-engine @ git+https://code.allura.moe/rae/resonance-engine.git);
for development, clone it next to this repo and
uv pip install -e --no-deps ../resonance-engine (or keep the dev/
softlink convention) — the venv pick whichever install is present.
Voice presets
# nano/turbo preset (default model kind — works on both nano and turbo):
python -m resonance preset my_voice.wav
# multilingual preset (separate family; note the distinct name):
python -m resonance preset my_voice.wav --model multilingual --name my_voice_mtl
python -m resonance voices # list presets + their model family
A preset is built for the model kind selected by --model (or
RESONANCE_MODEL) — one clip produces one family's preset, so clone the
same clip once per family you serve. Use distinct names: presets share a single
voices/ directory, and overwriting a preset of the other family loses it
(the CLI logs a warning when it detects that).
Or over HTTP (multipart): POST /v1/voices with file=@clip.wav and optional
name=... — this builds a preset for the loaded model's family; GET /v1/voices lists voices; DELETE /v1/voices/<name> removes one.
Every model checkpoint also ships a built-in reference voice, exposed as the
preset name builtin.
Presets are scoped to a model family. nano and turbo share conditioning, so
presets work across both — but multilingual presets are built from different
conditioning (150- vs 375-token speech prompts) and are not interchangeable
with nano/turbo presets. GET /v1/voices marks each preset with its family and
a compatible flag; using an incompatible one by name returns a 400 with a
rebuild hint. GET /v1/audio/voices lists only voices usable with the loaded
model.
Running
python -m resonance serve # 127.0.0.1:8123, nano, ./models, ./voices
python -m resonance serve --model multilingual --port 9000 --api-key sekrit
python -m resonance serve --model flash --flash-block-size 32 # English, engine-backed
| Flag | Env | Default | Meaning |
|---|---|---|---|
--host / --port |
RESONANCE_HOST/PORT |
127.0.0.1:8123 |
bind address |
--model |
RESONANCE_MODEL |
nano |
nano, turbo, multilingual or flash |
--models-dir |
RESONANCE_MODELS_DIR |
models |
checkpoint storage |
--voices-dir |
RESONANCE_VOICES_DIR |
voices |
preset storage |
--api-key |
RESONANCE_API_KEY |
— | require Authorization: Bearer <key> |
--strict |
RESONANCE_STRICT |
false |
error on unknown model/voice instead of fallback |
--queue-size |
RESONANCE_QUEUE_SIZE |
32 |
max queued synthesis requests before 503 |
--logs |
RESONANCE_LOG_BODIES |
false |
log full speech request bodies (debug frontend chunking) |
--download |
RESONANCE_DOWNLOAD_ON_START |
true |
auto-download model if missing |
--device |
RESONANCE_DEVICE |
cpu |
inference device |
--use-engine |
RESONANCE_USE_ENGINE |
false |
run inference via the resonance-engine package (bit-exact ports of the same code paths; flash always uses it) |
--flash-num-steps |
RESONANCE_FLASH_NUM_STEPS |
0 (=10) |
flash default max denoise steps per block; the request num_steps param wins (K6 ~2×, K4 ~2.4× faster than K10, near-lossless) |
--flash-block-size |
RESONANCE_FLASH_BLOCK_SIZE |
16 |
flash block-diffusion block size D — 32 is faster at similar quality (tail trim on) |
--no-flash-tail-trim |
RESONANCE_FLASH_TAIL_TRIM |
false |
disable the flash EOS-miss near-silent tail trim |
flash is the English block-diffusion model (paper-claimed ≥ AR quality at
much lower latency). --t3-int8 works here too: K8-int8 runs at K6-bf16
speed (~0.76–0.78× vs 0.84–1.0× RT) — take the higher num_steps (less
artifacting on long sequences) for free. Its conditioning is multilingual-lineage (150-token
prompts), so multilingual presets work on flash directly — same
voices/*.pt library, no rebuilds. The t3 loads in bf16 by default
(precision auto → flash bf16, matching the vendor's own from_local
default; multilingual stays fp32 unless asked). The speed knob is
num_steps (max denoise steps per block; early decoding rarely needs the
budget): set the default with --flash-num-steps, override per request.
Measured on the 7640HS with --flash-block-size 32: K10 ≈ 0.5× (0.55×
compiled), K6 ≈ 0.83× → 0.98× with --fast, K4 ≈ 1.16× → 1.2–1.3×
with --fast — K4 listening verdict: near-lossless. --fast (bf16 +
compile) also applies to flash; the boot prewarm uses the first compatible
preset (flash ships no builtin voice). cfg_scale: 0 is not a speedup on
flash (halves the batch but slows PMI convergence).
Using it
curl localhost:8123/v1/audio/speech \
-H 'Content-Type: application/json' \
-d '{"model":"tts-1","voice":"my_voice","input":"Hello! [chuckle] Nice to meet you."}' \
-o out.mp3
With the OpenAI client (or any OAI-compatible frontend):
from openai import OpenAI
client = OpenAI(base_url="http://127.0.0.1:8123/v1", api_key="anything")
with client.audio.speech.with_streaming_response.create(
model="tts-1", voice="my_voice",
input="Hello from resonance!",
response_format="wav",
) as resp:
resp.stream_to_file("out.wav")
POST /v1/audio/speech parameter mapping
| OpenAI param | Behaviour |
|---|---|
model |
aliases: tts-1, resonance, nano, chatterbox-nano → nano; tts-1-hd, gpt-4o-mini-tts, turbo, chatterbox-turbo → turbo; v3, mtl, multilingual, chatterbox-multilingual(-v3) → multilingual; flash, chatterbox-flash → flash. Aliases of a non-loaded model, and unknown names, fall back to the loaded model (404 in --strict mode). |
input |
up to 4096 chars; nano/turbo support paralinguistic tags ([laugh], [cough], …) |
voice |
preset name, or {"id": "name"}. Unknown names: if exactly one compatible preset exists it is used; stock OAI voice names (alloy, …) use the built-in voice; otherwise 400 |
response_format |
mp3 (default), wav, pcm (raw 24 kHz s16le mono, like OpenAI), opus, aac, flac (ffmpeg) |
speed |
ignored (always 1.0) — chatterbox has no speed knob |
instructions |
ignored — use paralinguistic tags in input instead |
Extensions (all optional; unset values fall back to server defaults):
| Extension | nano/turbo default | multilingual default | Notes |
|---|---|---|---|
temperature |
0.8 | 0.8 | |
top_p |
0.95 | 1.0 | |
top_k |
1000 | — | nano/turbo only (ignored + noticed on multilingual) |
repetition_penalty |
1.2 | 1.2 | |
exaggeration |
— | 0.5 | multilingual only (emotion intensity; higher = more expressive, tends faster speech) |
cfg_weight |
— | 0.5 | multilingual only (lower ≈ 0.3 = more expressive; higher = calmer pacing) |
min_p |
— | 0.05 | multilingual only |
language_id / language |
— | en (default) |
multilingual only; ISO code: ar da de el en es fi fr he hi it ja ko ms nl no pl pt ru sv sw tr zh |
num_steps |
— | — | flash only (max denoise steps per block; paper default 10) |
time_shift_tau |
— | — | flash only (early-decoding aggressiveness, 0 disables) |
cfg_scale |
— | — | flash only (CFG guidance weight, paper default 1.0) |
position_temperature |
— | — | flash only (PMI position-ranking temperature, default 5) |
n_cfm_timesteps |
— | — | flash only (meanflow CFM steps, default 2) |
Response headers x-resonance-model / x-resonance-voice record what was
actually used.
Other endpoints
GET /v1/models— OAI-style model list (aliases of the loaded model)GET /v1/audio/voices— vLLM-Omni-style listing (frontends that poll this path get{"voices": [...], "uploaded_voices": [{name, created_at, file_size}, ...]};voicesincludes the built-in voice,uploaded_voicesdescribes the presets. We carry no consent/ref_text/speaker_description metadata, so those optional fields are omitted)GET /v1/voices,POST /v1/voices,DELETE /v1/voices/{name}— preset managementGET /healthz— no auth, reports load state
Logging
All server log lines are timestamped (YYYY-MM-DD HH:MM:SS.mmm). Three kinds:
... INFO resonance.access: POST /v1/audio/speech -> 200 (3734 ms) 127.0.0.1 <- every request
... INFO resonance.engine: generated 3.52s audio: 51 chars, voice=vienna, 3.73s wall (0.9x realtime)
... INFO resonance.server: speech request body: {"model":"tts-1","input":"...",...} <- with --logs
resonance.accessreplaces uvicorn's access log (timestamped, with duration and client IP)resonance.enginelogs one line per generation: audio duration, input length, voice, wall time and realtime factor — the queue wait is roughlyrequest duration - generation wall--logs(orRESONANCE_LOG_BODIES=1) dumps the full parsed speech request body at submit time, so you can see what a frontend actually sends — input lengths reveal poor (or absent) chunking. Bodies are logged before generation, so queued work stays visible during long generations.
Notes & caveats
-
Multilingual v3 on PyPI chatterbox-tts 0.1.7: the released package is missing several things master added for v3 — our loader replicates them: v3 checkpoint loading (package hardcodes v2), master's
generate()(final token noise trim), and master's token-sampling loop. The last one matters most: 0.1.7's multilingual inference wraps generation in anAlignmentStreamAnalyzer(deleted on master) whose stale token-repetition heuristic forces EOS after any 2x-repeated token — silence-adjacent tokens repeat like that naturally, so speech constantly truncated to a word or two. Expect ~0.2× realtime on CPU (500M CFG model), much slower than nano — or ~0.4× with--fast(below). -
Optional CPU speed-ups (multilingual flags apply on the engine backend to every family — turbo/nano included — and on the package path to multilingual only; fp32 stays the default and is always lossless). Measured on a Ryzen 5 7640HS (Zen 4,
AVX512_BF16):Flag Effect Speed (t3 decode) Quality --fastbf16 t3 + torch.compile~2.1× mtl (e2e ~2×); turbo fp32 0.42× → 0.61× lossless to the ear --precision bf16t3 weights in bf16 ~1.8× mtl; turbo +33% lossless to the ear --compiletorch.compilethe t3 transformer+~15% on top of bf16 lossless --t3-int8row-wise int8 t3 Linears on torch._int_mm(engine backend)mtl 1.29× over bf16+compile (0.41→0.53× RT); turbo 1.51× (0.60→0.91×); flash +15–20% — K8-int8 ≈ K6-bf16 speed ear-gated; logit dev ≈3× bf16's, top-1 identical; ear-verdict on mtl/turbo: lossless --s3gen-int8int8-quantize s3gen Linears ~20% off the vocoder phase minor loss --s3gen-autocastbf16-autocast the s3gen CFM flow ~45% off the flow phase minor loss --flow-no-cfgskip the flow's built-in CFG ~2× on the flow phase fine; slightly faster delivery --flow-steps Nfewer ODE steps (default 10) ~linear in N on the flow phase needs listening --fast(orRESONANCE_FAST=1) is the recommended combo.--compileadds ~1–2 min to boot (the compile is pre-warmed there, not on the first request).--s3gen-int8and--s3gen-autocasttarget the same Linears at the same quality tier — if both are given, autocast wins (it's faster). The--flow-*flags rework the CFM ODE loop: stock runs 10 Euler steps with a batch-doubled (CFG) UNet per step — the guidance rate 0.7 is baked into the checkpoint with no API to disable it.--flow-no-cfgruns the UNet single-batch (halving work per step); listening verdict: quality holds. Delivery can pace slightly faster in some samples (observed on the builtin voice; didn't reproduce with voice presets — possibly sampling variance) — if a sample feels rushed, ask for a lowerexaggeration(e.g. 0.3), which reliably slows delivery back down.--flow-stepssimply cuts the step count. Everything stacks:--fast --s3gen-autocast --flow-no-cfgmeasures ~0.5× realtime with voice presets on the 7640HS (vs ~0.4× for plain--fast --s3gen-autocast); swapping the bf16 tier for--t3-int8(i.e.--use-engine --t3-int8 --compile --s3gen-autocast --flow-no-cfg) reaches ~0.6× realtime — the current mtl maximum. On turbo the same flag takes bf16+compile from 0.60× to 0.91×. One request-level note:cfg_weight: 0.0in a speech request switches t3 to an exact single-batch (guidance-off) path — mathematically identical output, though on CPU it buys little (t3 decode is weight-streaming-bound, so the doubled batch was nearly free). Not offered, deliberately: fp16 (noAVX512-FP16on Zen 4 → PyTorch falls into a scalar matmul stub, 100×+ slower), int8 t3 (torch.ao dynamic kernels gave zero gain for this skinny batch-2 CFG decode workload), full-bf16 casting of the s3gen flow (garbles the audio — the CFM ODE is precision-hungry; autocast-style mixed precision stays usable), and a heun/midpoint ODE solver (2nd-order in theory — in practice it produced quick vibrato-like artifacts on real voices and was removed). -
Queueing. One model, one generation at a time. Requests go through a bounded FIFO queue (
--queue-size, default 32), so frontends that split a message into several parallel requests get their parts synthesized in send order. Overflow returns an OpenAI-shaped503(code: server_busy) with aRetry-After: 5header.GET /healthzreports currentqueuedepth. Waiting requests occupy no threads (async endpoint awaiting a future). -
Nano on PyPI chatterbox-tts 0.1.7: the released package only contains the turbo codepath.
resonance/loader.pydelegates to the package when it supportsnano=and otherwise replicates itsfrom_localwith the two nano deltas (GPT2-small backbone config +t3_nano_v1.safetensors), as on master. When a newerchatterbox-ttsships nano support, the shim is bypassed automatically. -
Generation is serialized behind a lock (single model, CPU-bound). On a 12-core CPU nano synthesizes roughly at ~1–2× realtime after the first request warms up.
-
Presets embed conditioning from the model's voice encoder / S3Gen front-ends; they are plain
.ptfiles you can copy between machines, but only within their model family (see the note above) -
All generated audio carries Resemble AI's imperceptible PerTh watermark (embedded by the model itself).
-
pyproject.tomlassumes CPU torch is already installed (see Setup); on a GPU box install the CUDA build instead.
Tests
uv pip install -e ".[dev]"
python -m pytest tests/ -q