Skip to content

A research project focused on developing a lightweight neural voice cloning and speech synthesis system, optimized for deployment on edge devices.

Python

Improve docs & add preset voices

IgorSwat6a2f3783cf1f
diff --git a/README.md b/README.md
index 34f1082..95caf46 100644
--- a/README.md
+++ b/README.md
@@ -1,9 +1,8 @@
# Reverb
-**Reverb** is a **voice-cloning-first text-to-speech model**. Built on top of one of the leading open-weight
-TTS models, it combines exceptional quality in mimicking any reference speaker, including prosody, emotions and voice
-timbre, with cost efficiency and high performance, allowing it to run locally on mobile and desktop systems. It speaks
-seven languages: English, German, French, Spanish, Italian, Polish and Portuguese.
+**Reverb** is a voice-cloning text-to-speech model: give it a few seconds of someone speaking, and it speaks any text
+in that voice. It speaks English, German, French, Spanish, Italian, Polish and Portuguese, and is small and fast enough
+to run locally on desktop and mobile devices.
## Install
@@ -11,8 +10,8 @@ seven languages: English, German, French, Spanish, Italian, Polish and Portugues
pip install .
```
-Python 3.10 or later. The weights are downloaded from Hugging Face on first use. While the weights repository is
-private, log in first (`hf auth login`) or set `HF_TOKEN`.
+Python 3.10 or later. The weights download from Hugging Face on first use; while the weights repository is private, log
+in first (`hf auth login`) or set `HF_TOKEN`.
## Quick start
@@ -22,100 +21,15 @@ from reverb_tts import TTS
tts = TTS.from_pretrained()
voice = tts.voice("reference.wav", "The exact transcript of the reference recording.", language="en")
-audio = tts.generate("I bought 3 tickets for $49, and we leave at 7:30 tomorrow.", voice, language="en", seed=0)
+audio = tts.generate("Hello! This is my cloned voice.", voice, language="en")
sf.write("output.wav", audio, tts.sample_rate)
```
-## Usage
+## Documentation
-**Voices.** `tts.voice(audio, transcript, language)` takes a file path, or samples with their `sample_rate`. Use 3-10 s
-of clean speech from one speaker, with a transcript that matches it exactly; `language` is the recording's. A voice
-can be saved and loaded, so the recording needn't be encoded again:
-
-```python
-from reverb_tts import Voice
-
-voice.save("anna.npz")
-voice = Voice.load("anna.npz")
-```
-
-**Generating.** `tts.generate(text, voice, language)` returns float32 samples at `tts.sample_rate` (24 kHz).
-
-- `language` is the text's, and may differ from the voice's.
-- `seed` makes a take reproducible; without one, each call draws a new take.
-- `speed` scales the estimated length (`speed=1.2` speaks faster); `duration` sets it in seconds.
-- A list of texts is generated in batches and returns a list, with one voice and language for all or one per text.
-- A text estimated over 30 s is cut at sentence ends and spoken in pieces of about 15 s.
-
-**Text.** Text is prepared with [Verbalis](https://github.com/software-mansion-labs/Verbalis) before it reaches the
-model: numbers, dates, money, units, symbols and abbreviations are read out as words. Pass `prepare=False` for text
-that is already prepared.
-
-**Sampler.** Every sampler setting can be overridden per call, or for a loaded model:
-
-```python
-audio = tts.generate(text, voice, language="en", steps=12, remasking=False)
-
-from reverb_tts import SamplerConfig
-tts = TTS.from_pretrained(sampler=SamplerConfig(steps=12, polish_guidance=0.5))
-```
-
-The settings and what they do are in [docs/pipeline.md](docs/pipeline.md#sampler-settings).
-
-**Variants and devices.** `TTS.from_pretrained(variant=...)` picks the weights:
-
-| Variant | Decoder weights | Download |
-|---|---|---|
-| `fp32` | fp32 | 1.19 GB |
-| `int8` (default) | int8, one scale per output channel | 307 MB |
-| `int8a8` | int8, with int8 activations | 307 MB |
-| `int4` | int4, one scale per group of 32 inputs | 191 MB |
-
-Quantized weights are expanded to the compute dtype on load, so they download smaller but run at full speed on any
-device. The device is the first available of CUDA, MPS and the CPU (or `device=`); the dtype is bfloat16 on CUDA,
-float16 on MPS and float32 on the CPU (or `dtype=`). `TTS.from_pretrained("path/to/folder")` loads local weights.
-
-## How it works
-
-[docs/pipeline.md](docs/pipeline.md) walks through the whole pipeline, from text and reference to audio.
-
-The model is a masked-diffusion TTS model working on [Higgs audio codec](https://huggingface.co/eustlb/higgs-audio-v2-tokenizer)
-tokens: it fills in a grid of codec tokens (8 codebooks per frame, 25 frames per second) over several passes,
-conditioned on the text and on the reference speaker's audio. It was made from
-[OmniVoice](https://github.com/k2-fsa/OmniVoice) in three stages:
-
-1. **Pruning with distillation.** 4 of the 28 transformer layers are dropped, the FFN shrinks from 3072 to 2048, and the
- text vocabulary from 151,676 to 62,035 tokens. The pruned student is trained to match OmniVoice's predictions.
-2. **Supervised retraining** on cleaned, selected subsets of open datasets in the seven languages, such as
- [Emilia](https://huggingface.co/datasets/amphion/Emilia-Dataset) and variants of YODAS2, such as
- [yodas2-sidon](https://huggingface.co/datasets/sarulab-speech/yodas2_sidon).
-3. **Preference post-training with DPO.** The model generates several takes per prompt, a critic fitted on human
- preference rankings and a CTC intelligibility check pick winners and losers, and DPO trains on those pairs, in
- rounds.
-
-Three changes make each generation cheap:
-
-- **CFG self-distillation.** Classifier-free guidance normally runs every pass twice, with and without conditioning.
- The model learned the guided output directly, so each pass is one forward.
-- **Prefix blocking.** The text and reference prefix never attends to the generated audio, so its keys and values are
- computed once and reused by every pass.
-- **A two-stage sampler.** 8 passes decide codebooks 0-1, then two polish passes decide codebooks 2-7: 10 forwards in
- all, against OmniVoice's default of 32 guided passes (64 forwards).
-
-| | OmniVoice | Reverb |
-|---|---|---|
-| Parameters | 613M | **297M** |
-| Weights | 2.45 GB (fp32) | 1.19 GB (fp32), 307 MB (int8), 191 MB (int4) |
-| Forwards per generation | 64 (32 passes with CFG) | **10** |
-
-## Tests
-
-```bash
-pip install ".[test]"
-pytest
-```
-
-The tests use a small random model, so they need no download.
+- [Overview](docs/overview.md): what the model is, how it was made, and how it scores.
+- [Usage](docs/usage.md): every use case, from the quick start to sampler settings.
+- [Reference](docs/reference.md): model variants and the repositories' layout.
## License and acknowledgments
@@ -123,7 +37,7 @@ The tests use a small random model, so they need no download.
- **Model weights:** [CC BY-NC 4.0](https://creativecommons.org/licenses/by-nc/4.0/), for non-commercial use with
attribution.
-The model's weights were initialized from [OmniVoice](https://github.com/k2-fsa/OmniVoice) by the k2-fsa team, and its
+Reverb's weights were initialized from [OmniVoice](https://github.com/k2-fsa/OmniVoice) by the k2-fsa team, and its
target-length rule and prompt format come from OmniVoice's code. We thank its authors for releasing the model and code
-openly. The model uses the [Higgs Audio v2 tokenizer](https://huggingface.co/eustlb/higgs-audio-v2-tokenizer) as its
-audio codec, and [Verbalis](https://github.com/software-mansion-labs/Verbalis) prepares its text.
+openly. Reverb uses the [Higgs Audio v2 tokenizer](https://huggingface.co/eustlb/higgs-audio-v2-tokenizer) as its audio
+codec, and [Verbalis](https://github.com/software-mansion-labs/Verbalis) prepares its text.
diff --git a/docs/overview.md b/docs/overview.md
new file mode 100644
index 0000000..a907d09
--- /dev/null
+++ b/docs/overview.md
@@ -0,0 +1,40 @@
+# Overview
+
+Reverb is a masked-diffusion text-to-speech model. It fills in a grid of
+[Higgs audio codec](https://huggingface.co/eustlb/higgs-audio-v2-tokenizer) tokens (8 codebooks per frame, 25 frames per
+second) over a few passes, conditioned on the text and on a reference recording of the voice to clone.
+
+## How it was made
+
+1. **Initialized from [OmniVoice](https://github.com/k2-fsa/OmniVoice)**, a 613M-parameter masked-diffusion TTS model.
+2. **Pruned with distillation:** 4 of the 28 transformer layers removed, the FFN cut from 3072 to 2048, the text
+ vocabulary from 151,676 to 62,035 tokens; the pruned model was trained to match OmniVoice's predictions.
+3. **Retrained** on cleaned, selected subsets of open speech datasets in the seven languages.
+4. **Preference post-training (RLHF-like):** the model generated several takes per prompt, a critic fitted on human
+ preference rankings and a CTC intelligibility check picked the better and worse ones, and DPO trained on those pairs.
+
+## Results
+
+Quality on the [MiniMax Multilingual Test Set](https://huggingface.co/datasets/k2-fsa/TTS_eval_datasets) (the seven
+languages, 700 sentences), scored with OmniVoice's evaluation scripts; WER and SIM-o are averaged over languages. Speed
+is RTFx, seconds of speech generated per second: batch 32 on one RTX 5090, from the text and an already-encoded reference
+to the waveform, each model in its default runtime.
+
+| Model | Parameters | Weights (16-bit) | WER ↓ | SIM-o ↑ | RTFx ↑ |
+|---|---|---|---|---|---|
+| **Reverb** | **297M** | **0.59 GB** | **1.35%** | 0.816 | **164.9×** |
+| [OmniVoice](https://huggingface.co/k2-fsa/OmniVoice) | 613M | 1.23 GB | 1.64% | **0.835** | 13.2× |
+| [Qwen3-TTS 0.6B Base](https://huggingface.co/Qwen/Qwen3-TTS-12Hz-0.6B-Base) | 915M | 1.83 GB | 11.96%¹ | 0.780¹ | 3.3× |
+| [Audio8-TTS-Realistic-Air](https://huggingface.co/Edge0/Audio8-TTS-Realistic-Air) | 601M | 1.20 GB | 1.97% | 0.750 | 4.2× |
+
+¹ Over the six languages Qwen3-TTS supports (Polish excluded); the other models over all seven.
+
+On an Apple M4 Pro (ExecuTorch MLX, median time from text to audio codes; speed relative to real time in brackets),
+against OmniVoice at 16 guided passes:
+
+| Reference + target speech | OmniVoice | Reverb int8 | Speed-up |
+|---|---|---|---|
+| 5 s + 5 s | 2,278 ms (2.2×) | **175 ms (28.5×)** | 13.0× |
+| 5 s + 10 s | 3,388 ms (3.0×) | **300 ms (33.4×)** | 11.3× |
+| 10 s + 5 s | 3,132 ms (1.6×) | **192 ms (26.1×)** | 16.3× |
+| 10 s + 10 s | 4,157 ms (2.4×) | **317 ms (31.5×)** | 13.1× |
diff --git a/docs/pipeline.md b/docs/pipeline.md
deleted file mode 100644
index 9fe289e..0000000
--- a/docs/pipeline.md
+++ /dev/null
@@ -1,147 +0,0 @@
-# How Reverb generates speech
-
-This is the whole inference pipeline, step by step, as `reverb_tts` runs it. The code is short and follows the
-same order: [text.py](../reverb_tts/text.py), [audio.py](../reverb_tts/audio.py),
-[model.py](../reverb_tts/model.py), [sampler.py](../reverb_tts/sampler.py) and
-[tts.py](../reverb_tts/tts.py), which ties them together.
-
-## The model
-
-The model is a masked-diffusion text-to-speech model: OmniVoice pruned to 297M parameters and retrained. It speaks in
-tokens of the [Higgs audio codec](https://huggingface.co/eustlb/higgs-audio-v2-tokenizer): 25 frames per second, each
-frame 8 codebooks from coarse (0) to fine (7), each codebook 1024 codes plus a mask token. One bidirectional
-transformer (a Qwen3 backbone) reads one sequence:
-
-```
-[ prompt + reference transcript + text | reference frames ][ target frames ]
- prefix target
-```
-
-The target starts fully masked and is filled in over several passes. A frame's input is the sum of its 8 codebook
-embeddings; a masked slot has an embedding of its own.
-
-## 1. Text
-
-The text to speak and the reference transcript are both prepared with [Verbalis](https://github.com/software-mansion-labs/Verbalis):
-numbers, dates, times, money, units, symbols, abbreviations and web addresses become words, and quotes, apostrophes,
-dashes and ellipses take the forms the training transcripts use (`"`, `'`, ` - `, `...`). Brackets, which never
-occurred in training text, are dropped. `prepare=False` skips this for text that is already prepared.
-
-The model was trained on seven languages: English, German, French, Spanish, Italian, Polish and Portuguese (Brazilian).
-
-## 2. Reference
-
-The reference recording is mixed down to mono, resampled to 24 kHz with the windowed-sinc filter the training
-references were resampled with, and zero-padded to whole codec frames (960 samples). Without the padding, the codec's
-encoder pads its input by half a frame for about half of all lengths, and the codes come out misaligned. The Higgs
-encoder then turns it into codes `[8, R]`.
-
-A good reference is 3-10 s of clean speech from one speaker, with a transcript that matches the audio exactly: the
-target's length is estimated from it. References over 15 s are known to make worse takes.
-
-## 3. Prompt
-
-```
-<|denoise|><|lang_start|>{language}<|lang_end|><|instruct_start|>None<|instruct_end|><|text_start|>{reference transcript} {text}<|text_end|>
-```
-
-`language` is the text's language code. The reference may be in another language.
-
-## 4. Target length
-
-The length is estimated, not predicted: the text's spoken weight, at the rate the reference speaks its transcript.
-Letters weigh 1, digits 3.5, punctuation and symbols 0.5, spaces 0.2 and combining marks 0. A text shorter than
-50 frames gets relatively more time (the estimate is stretched by a cube root). `speed` divides the estimate, and
-`duration` replaces it.
-
-A text estimated over 30 s is cut at sentence ends into pieces of about 15 s. The pieces are generated with
-consecutive seeds, trimmed, and joined.
-
-## 5. Prefix
-
-Two properties of the model keep a generation cheap:
-
-- **Prefix blocking:** the prefix never attends to the target. It runs once, and its keys and values are cached; each
- pass then runs over the target frames only.
-- **Distilled guidance:** classifier-free guidance was distilled into the weights, so each pass is a single forward,
- with no unconditional branch.
-
-Several takes are generated together as a batch, padded on the right; padded keys are masked out.
-
-## 6. Main passes: codebooks 0-1
-
-`steps` passes decide codebooks 0 and 1, which carry the content and the timing.
-
-- **Schedule.** With u = k / steps, the fraction of slots decided after pass k is t = s·u / (1 - (1 - s)·u), where
- s is `t_shift` (0.1). Pass k commits ⌈2·F·(t_{k+1} - t_k)⌉ of the 2·F slots, so early passes commit few and the last
- pass fills whatever is left.
-- **Which slots.** Each masked slot scores (log p - `codebook_penalty`·c) / `position_temperature` + Gumbel noise,
- where log p is the log-probability of its most likely code and c its codebook (0 or 1). The highest scores are
- committed to their most likely code. The noise comes from a CPU generator seeded with the take's seed, so a seed
- gives the same noise on any device.
-- **Remasking.** On every pass but the last, the model re-reads the codes committed earlier, and the ones it now finds
- least likely are masked again: `remask_ratio` as many as the pass committed.
-
-## 7. Polish passes: codebooks 2-7
-
-Two passes decide codebooks 2-7, which carry the voice's timbre and detail, with codebooks 0-1 complete. In both, every
-attention score from the target to the reference frames gets `polish_bias` added, in every layer and head, so the
-fine codebooks follow the reference more closely.
-
-1. The first pass predicts codebooks 2-7 and commits codebooks 2-3.
-2. The second pass, with codebooks 0-3 known, predicts codebooks 4-7 and commits the most likely code of
- lp₂ + `polish_guidance`·(lp₂ - lp₁), where lp₁ and lp₂ are the two passes' log-probabilities for codebooks 4-7.
-
-## 8. Audio
-
-The Higgs decoder turns the codes into 24 kHz audio. The last 200 ms are cut, since the final frames can hold a short
-burst of noise. Then leading and trailing silence (10 ms windows under -50 dBFS) is trimmed, keeping 100 ms on each
-side; a sound of at most 120 ms alone at either edge is a codec burst rather than speech, and goes too.
-
-## Cost
-
-One generation is 1 prefix pass and `steps` + 2 target passes: 10 target passes with the defaults, against
-OmniVoice's default of 32 guided passes (64 forwards).
-
-## Sampler settings
-
-| Setting | Default | What it does |
-|---|---|---|
-| `steps` | 8 | main passes |
-| `remasking` | True | whether main passes withdraw earlier commits |
-| `remask_ratio` | 0.25 | commits withdrawn per new commit |
-| `t_shift` | 0.1 | warps the schedule towards the last passes |
-| `codebook_penalty` | 5.0 | makes codebook 0 tend to go before codebook 1 |
-| `position_temperature` | 5.0 | scales confidence against the Gumbel noise; higher is more random |
-| `polish_bias` | 1.0 | attention bias towards the reference in the polish passes |
-| `polish_guidance` | 1.0 | weight of the second polish pass's change over the first |
-
-Override any of them per call (`tts.generate(..., steps=12, remasking=False)`), or for a loaded model
-(`TTS.from_pretrained(sampler=SamplerConfig(steps=12))`).
-
-On the MiniMax multilingual test set (the seven languages, 700 texts, one take each, on CUDA in bf16), the defaults
-scored 1.35% WER and 0.816 speaker similarity (SIM-o), against 1.50% and 0.817 with `remasking=False`.
-
-## Weights
-
-| Variant | Decoder projections | Activations | Download |
-|---|---|---|---|
-| `fp32` | fp32 | full precision | 1.19 GB |
-| `int8` (default) | int8, one scale per output channel | full precision | 307 MB |
-| `int8a8` | int8, one scale per output channel | int8, one scale per token | 307 MB |
-| `int4` | int4, one scale per group of 32 inputs | full precision | 191 MB |
-
-In the quantized variants, the text embedding table and the audio embeddings are int8 with one scale per row, and
-the remaining weights are bf16. On load, every weight is expanded to the compute dtype: PyTorch has no int8 or int4
-matrix product that runs the same on the CPU, MPS and CUDA. A quantized variant therefore downloads smaller but runs
-at the same speed, in the same memory, as fp32 weights cast to that dtype. `int8a8` additionally rounds each token's
-projection inputs to int8, as it was made to run.
-
-The compute dtype is bfloat16 on CUDA (float16 without bf16 support), float16 on MPS and float32 on the CPU. Each
-codebook's head rows are centred on load, which leaves the softmax unchanged and keeps the logits small enough for
-16-bit floats.
-
-## Reproducibility
-
-The same inputs, seed, device and dtype give the same take. Takes generated in one batch share padding, which can
-change 16-bit rounding: a text generated in a list may come out slightly different from the same text alone.
diff --git a/docs/reference.md b/docs/reference.md
new file mode 100644
index 0000000..68b396c
--- /dev/null
+++ b/docs/reference.md
@@ -0,0 +1,50 @@
+# Reference
+
+## Model variants
+
+Weights for the Python package (`TTS.from_pretrained(variant=...)`):
+
+| Variant | Weights | Activations | Download |
+|---|---|---|---|
+| `fp32` | fp32 | full precision | 1.19 GB |
+| `int8` (default) | int8, one scale per output channel | full precision | 307 MB |
+| `int8a8` | int8, one scale per output channel | int8, one scale per token | 307 MB |
+| `int4` | int4, one scale per group of 32 inputs | full precision | 191 MB |
+
+In the quantized variants the decoder's linear layers hold the quantized weights, with fp16 scales. In automatic scoring
+of generated speech, `int8` and `int8a8` showed no measurable loss against `fp32`, and `int4` a small one.
+
+[ExecuTorch](https://pytorch.org/executorch) programs for on-device inference (Apple GPUs through MLX), with the codec
+kept out of the program:
+
+| Program | Size |
+|---|---|
+| MLX fp16 | 612 MB |
+| MLX int8 | 352 MB |
+| MLX int4 | 232 MB |
+
+## Repository layout
+
+This repository:
+
+```
+reverb_tts/
+ tts.py TTS and Voice: the public API
+ text.py text preparation, length estimate, long-text splitting
+ audio.py loading audio, trimming silence
+ sampler.py the sampler and its settings
+ model.py the network
+tests/ tests on a small random model, no download needed
+docs/
+```
+
+The weights on Hugging Face, [software-mansion/Reverb-TTS](https://huggingface.co/software-mansion/Reverb-TTS):
+
+```
+model/
+ tokenizer.json, tokenizer_config.json, chat_template.jinja
+ safetensors/<variant>/ config.json, model.safetensors: fp32, int8, int8a8, int4
+ executorch/mlx/<precision>/ echo_mlx_<precision>.pte: fp16, int8, int4
+voices/ preset voices: <name>.json
+```
+
diff --git a/docs/usage.md b/docs/usage.md
new file mode 100644
index 0000000..c1dc056
--- /dev/null
+++ b/docs/usage.md
@@ -0,0 +1,132 @@
+# Usage
+
+## Speak in a cloned voice
+
+```python
+import soundfile as sf
+from reverb_tts import TTS
+
+tts = TTS.from_pretrained()
+voice = tts.voice("anna.wav", "The exact transcript of the recording.", language="en")
+audio = tts.generate("Nice to meet you. I'll be your guide today.", voice, language="en")
+sf.write("output.wav", audio, tts.sample_rate)
+```
+
+- **The reference:** 3-10 s of clean speech from one speaker (over 15 s makes worse takes), with a transcript that matches
+ it word for word. `language` in `voice` is the recording's language.
+- **The audio input:** a file path in any format and sample rate, or samples (`[samples]` or `[channels, samples]`) with
+ `sample_rate=`.
+- **The output:** float32 samples at `tts.sample_rate` (24 kHz), with silent edges trimmed (`trim=False` keeps them).
+
+## Use a preset voice
+
+Preset voices need no recording:
+
+```python
+tts.preset_voices() # ['angry_male', 'sensual_female', 'standard_male']
+voice = tts.preset_voice("standard_male")
+audio = tts.generate("Hello! This is a preset voice speaking.", voice, language="en")
+```
+
+Presets come from the `voices/` folder of
+[software-mansion/Reverb-TTS](https://huggingface.co/software-mansion/Reverb-TTS), or of the local folder the model was
+loaded from. `Voice.load` reads a preset file directly.
+
+## Reuse a voice
+
+A voice holds the reference's codec codes, so it can be saved and loaded without encoding the recording again:
+
+```python
+from reverb_tts import Voice
+
+voice.save("anna.npz")
+voice = Voice.load("anna.npz")
+```
+
+## Speak another language
+
+`language` in `generate` is the text's language. It can differ from the voice's:
+
+```python
+voice = tts.voice("anna.wav", "The exact transcript of the recording.", language="en")
+audio = tts.generate("Dzień dobry, jak się masz?", voice, language="pl")
+```
+
+## Reproduce a take, or draw several
+
+Without a seed, every call draws a new take. A seed makes it reproducible:
+
+```python
+audio = tts.generate(text, voice, language="en", seed=42)
+takes = [tts.generate(text, voice, language="en", seed=s) for s in range(4)] # four takes to choose from
+```
+
+## Control the length
+
+The length is estimated from the text and the reference's speaking rate:
+
+```python
+audio = tts.generate(text, voice, language="en", speed=1.25) # length = estimate / 1.25 = 0.8x: faster speech
+audio = tts.generate(text, voice, language="en", speed=0.9) # length = estimate / 0.9 = 1.11x: slower speech
+audio = tts.generate(text, voice, language="en", duration=4.0) # length = 4 s, whatever the estimate
+```
+
+## Long texts
+
+A text estimated over 30 s is cut at sentence ends into pieces of about 15 s, generated with consecutive seeds, and
+joined. This happens automatically, unless `duration` is set.
+
+## Many texts at once
+
+A list of texts is generated in batches and returns a list. Give one voice and language for all, or one per text:
+
+```python
+audios = tts.generate(["First line.", "Second line."], voice, language="en")
+audios = tts.generate(["Hello.", "Bonjour."], [anna, pierre], language=["en", "fr"])
+```
+
+## Text preparation
+
+Text and transcripts are prepared with [Verbalis](https://github.com/software-mansion-labs/Verbalis) first: numbers,
+dates, money, units, symbols and abbreviations become words ("$49" becomes "forty-nine dollars"). Pass `prepare=False`
+for text that is already written out, in `generate` or in `voice`.
+
+## Weights and hardware
+
+```python
+import torch
+
+tts = TTS.from_pretrained(variant="int4") # fp32, int8 (default), int8a8 or int4
+tts = TTS.from_pretrained(device="cpu", dtype=torch.float32)
+tts = TTS.from_pretrained("path/to/weights") # a local folder
+```
+
+- **variant:** quantized weights download smaller and are expanded to `dtype` on load, so every variant runs at the same
+ speed. See [Reference](reference.md#model-variants).
+- **device:** the first available of CUDA, MPS and CPU by default.
+- **dtype:** bfloat16 on CUDA (float16 without bf16 support), float16 on MPS, float32 on CPU by default.
+
+## Sampler settings
+
+Override any setting for one call, or for a loaded model:
+
+```python
+audio = tts.generate(text, voice, language="en", steps=12, remasking=False)
+
+from reverb_tts import SamplerConfig
+tts = TTS.from_pretrained(sampler=SamplerConfig(steps=12))
+```
+
+| Setting | Default | What it does |
+|---|---|---|
+| `steps` | 8 | main passes, which decide codebooks 0-1 (content and timing) |
+| `remasking` | True | main passes withdraw earlier picks the model has come to doubt |
+| `remask_ratio` | 0.25 | picks withdrawn per new pick |
+| `t_shift` | 0.1 | warps the schedule: few picks early, most in the last passes |
+| `codebook_penalty` | 5.0 | makes codebook 0 tend to be decided before codebook 1 |
+| `position_temperature` | 5.0 | scales confidence against random noise; higher is more random |
+| `polish_bias` | 1.0 | attention bias towards the reference in the polish passes |
+| `polish_guidance` | 1.0 | weight of the second polish pass's change over the first (codebooks 4-7) |
+
+The defaults are the tuned setup. On the MiniMax test set they scored 1.35% WER and 0.816 SIM-o, against 1.50% and
+0.817 with `remasking=False`.
diff --git a/reverb_tts/sampler.py b/reverb_tts/sampler.py
index d3cecf5..29df561 100644
--- a/reverb_tts/sampler.py
+++ b/reverb_tts/sampler.py
@@ -1,5 +1,5 @@
"""
-The sampler: `steps` main passes decide codebooks 0-1, then two polish passes decide codebooks 2-7 (docs/pipeline.md).
+The sampler: `steps` main passes decide codebooks 0-1, then two polish passes decide codebooks 2-7.
Takes are generated in batches: each prompt's prefix runs once, and every pass runs over the target frames only.
"""
diff --git a/reverb_tts/tts.py b/reverb_tts/tts.py
index 6bcecab..29e0589 100644
--- a/reverb_tts/tts.py
+++ b/reverb_tts/tts.py
@@ -6,6 +6,7 @@ The public API: load a model, make a voice from a reference recording, and speak
audio = tts.generate("Text to speak.", voice, language="en", seed=0) # float32 samples at tts.sample_rate
"""
+import json
import logging
import random
from dataclasses import dataclass, replace
@@ -14,17 +15,18 @@ from typing import Any, List, Optional, Sequence, Tuple, TypeVar, Union
import numpy as np
import torch
-from huggingface_hub import snapshot_download
+from huggingface_hub import hf_hub_download, list_repo_files, snapshot_download
from transformers import HiggsAudioV2TokenizerModel, Qwen2Tokenizer
from reverb_tts.audio import AudioInput, load_audio, trim_silence
-from reverb_tts.model import Network
+from reverb_tts.model import CODEBOOKS, MASK, Network
from reverb_tts.sampler import Batch, Prompt, SamplerConfig, sample
from reverb_tts.text import check_language, estimate_frames, prepare_text, split_text
logger = logging.getLogger(__name__)
REPOSITORY, REVISION = "software-mansion/Echo", "v1.0.0" # the released weights
+PRESETS = "software-mansion/Reverb-TTS" # preset voices, as voices/<name>.json
CODEC, CODEC_REVISION = "eustlb/higgs-audio-v2-tokenizer", "0e3a9177c2991016b8e5e17d23aa474ee665bef2"
VARIANTS = ("fp32", "int8", "int8a8", "int4")
FRAME_RATE = 25 # codec frames per second
@@ -58,20 +60,33 @@ class Voice:
@classmethod
def load(cls, path: Union[str, Path]) -> "Voice":
- data = np.load(path)
- return cls(torch.from_numpy(data["codes"].astype(np.int64)), str(data["text"]), str(data["language"]))
+ """
+ Reads a voice from an .npz file written by `save`, or from a preset .json file: {codes, transcript, language},
+ the codes as 8 x frames integers, row-major, and the transcript already prepared.
+ """
+
+ if Path(path).suffix != ".json":
+ data = np.load(path)
+ return cls(torch.from_numpy(data["codes"].astype(np.int64)), str(data["text"]), str(data["language"]))
+ data = json.loads(Path(path).read_text())
+ codes = torch.tensor(data["codes"], dtype=torch.long)
+ if codes.numel() == 0 or codes.numel() % CODEBOOKS or not 0 <= int(codes.min()) <= int(codes.max()) < MASK:
+ raise ValueError(f"{path}: expected codes as {CODEBOOKS} x frames integers below {MASK}")
+ return cls(codes.view(CODEBOOKS, -1), data["transcript"], check_language(data["language"]))
class TTS:
"""
- A loaded model with its tokenizer and audio codec. `sampler` holds the default sampler settings, and
- `batch_frames` caps the target frames generated together, padding included.
+ A loaded model with its tokenizer and audio codec. `sampler` holds the default sampler settings, `batch_frames`
+ caps the target frames generated together, padding included, and `presets` is a local folder of preset voices
+ (by default they come from Hugging Face).
"""
def __init__(self, network: Network, tokenizer: Any, codec: Any, sampler: Optional[SamplerConfig] = None,
- batch_frames: int = 8192) -> None:
+ batch_frames: int = 8192, presets: Optional[Union[str, Path]] = None, token: Optional[str] = None) -> None:
self.network, self.tokenizer, self.codec = network, tokenizer, codec
self.sampler, self.batch_frames = sampler or SamplerConfig(), batch_frames
+ self.presets, self.token = (Path(presets) if presets is not None else None), token
@property
def device(self) -> torch.device:
@@ -110,7 +125,31 @@ class TTS:
network = Network.load(weights).to(device, dtype or _default_dtype(device))
revision = codec_revision or (CODEC_REVISION if codec == CODEC else None)
codec_model = HiggsAudioV2TokenizerModel.from_pretrained(codec, revision=revision).to(device).eval()
- return cls(network, Qwen2Tokenizer.from_pretrained(tokenizer), codec_model, sampler)
+ local = Path(name_or_path).expanduser() / "voices"
+ return cls(network, Qwen2Tokenizer.from_pretrained(tokenizer), codec_model, sampler,
+ presets=local if local.is_dir() else None, token=token)
+
+ def preset_voices(self) -> List[str]:
+ """
+ The names of the preset voices.
+ """
+
+ if self.presets is not None:
+ return sorted(p.stem for p in self.presets.glob("*.json"))
+ files = list_repo_files(PRESETS, token=self.token)
+ return sorted(Path(f).stem for f in files if f.startswith("voices/") and f.endswith(".json"))
+
+ def preset_voice(self, name: str) -> Voice:
+ """
+ A preset voice, by name (see `preset_voices`): ready to use, with no recording to encode.
+ """
+
+ names = self.preset_voices()
+ if name not in names:
+ raise ValueError(f"unknown preset voice {name!r}, expected one of: {', '.join(names)}")
+ if self.presets is not None:
+ return Voice.load(self.presets / f"{name}.json")
+ return Voice.load(hf_hub_download(PRESETS, f"voices/{name}.json", token=self.token))
@torch.inference_mode()
def voice(self, audio: AudioInput, text: str, language: str, *, sample_rate: Optional[int] = None,
diff --git a/tests/test_tts.py b/tests/test_tts.py
index 5c4895e..b2f05b4 100644
--- a/tests/test_tts.py
+++ b/tests/test_tts.py
@@ -30,6 +30,33 @@ def test_a_voice_survives_a_round_trip_to_disk(voice: Voice, tmp_path: Path) ->
assert torch.equal(loaded.codes, voice.codes) and (loaded.text, loaded.language) == (voice.text, voice.language)
+def write_preset(path: Path, codes: List[int], language: str = "en") -> Path:
+ path.write_text(json.dumps({"name": path.stem, "language": language, "transcript": "Hello there.", "codes": codes}))
+ return path
+
+
+def test_a_preset_file_loads_as_a_voice(tmp_path: Path) -> None:
+ loaded = Voice.load(write_preset(tmp_path / "anna.json", list(range(8 * 5))))
+ assert loaded.codes.shape == (8, 5) and loaded.codes[1, 0] == 5 # row-major: one codebook per row
+ assert (loaded.text, loaded.language) == ("Hello there.", "en")
+
+
[email protected]("codes, language", [(list(range(9)), "en"), ([1024] * 8, "en"), ([0] * 8, "xx")])
+def test_a_malformed_preset_file_is_rejected(tmp_path: Path, codes: List[int], language: str) -> None:
+ with pytest.raises(ValueError):
+ Voice.load(write_preset(tmp_path / "bad.json", codes, language))
+
+
+def test_preset_voices_come_from_a_local_folder(tts: TTS, tmp_path: Path) -> None:
+ write_preset(tmp_path / "anna.json", [3] * 16)
+ write_preset(tmp_path / "piotr.json", [4] * 16, "pl")
+ tts.presets = tmp_path
+ assert tts.preset_voices() == ["anna", "piotr"]
+ assert tts.preset_voice("piotr").language == "pl"
+ with pytest.raises(ValueError, match="anna, piotr"):
+ tts.preset_voice("nobody")
+
+
def test_generate_returns_one_take_or_a_list(tts: TTS, voice: Voice) -> None:
single = tts.generate("Hello there.", voice, "en", seed=0)
assert isinstance(single, np.ndarray) and single.dtype == np.float32 and len(single) > 0