Skip to content

Open-source State-of-the-art TTS model which runs on a CPU 😻

Python

Add KittenTTS 2 and rename the package to kittenml

stellon-admin36ef3090ca1e
diff --git a/.gitignore b/.gitignore
index c81f9f1..950e8c1 100644
--- a/.gitignore
+++ b/.gitignore
@@ -245,4 +245,9 @@ marimo/_lsp/
__marimo__/
# Streamlit
-.streamlit/secrets.toml
\ No newline at end of file
+.streamlit/secrets.toml
+
+# Internal tooling: builds the model repository from a private inference bundle,
+# and regenerates the vendored s3gen / student-flow files from private checkouts.
+# Not useful without those inputs, so it is kept out of the published repo.
+scripts/
diff --git a/MANIFEST.in b/MANIFEST.in
index 953bb15..8e79b61 100644
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -1,9 +1,9 @@
include README.md
include LICENSE
include requirements.txt
-recursive-include kittentts *.py
-recursive-include kittentts *.json
-recursive-include kittentts *.txt
-recursive-include kittentts *.onnx
+recursive-include kittenml *.py
+recursive-include kittenml *.json
+recursive-include kittenml *.txt
+recursive-include kittenml *.onnx
global-exclude __pycache__
global-exclude *.py[co]
diff --git a/README.md b/README.md
index f558a21..84aad64 100644
--- a/README.md
+++ b/README.md
@@ -1,7 +1,7 @@
# Kitten TTS
<p align="center">
- <img width="607" alt="Kitten TTS" src="https://github.com/user-attachments/assets/6e24bdc1-9750-4416-ad8b-275bdc30b798" />
+ <img width="607" alt="Kitten TTS" src="https://raw.githubusercontent.com/KittenML/KittenTTS/main/assets/banner.png" />
</p>
<p align="center">
@@ -13,9 +13,13 @@
> ## **New:** Free Kitten TTS API available at [https://platform.kittenml.com](https://platform.kittenml.com/)
-Kitten TTS is an open-source, lightweight text-to-speech library built on ONNX. With models ranging from 15M to 80M parameters (25-80 MB on disk), it delivers high-quality voice synthesis on CPU without requiring a GPU.
+Kitten TTS is an open-source text-to-speech library. Its flagship model, **KittenTTS 2**, is a
+1.7B-parameter speech language model with in-context voice cloning and expression control: give it
+five seconds of anyone's voice and it speaks your text in that voice.
-> **Status:** Developer preview -- APIs may change between releases.
+The library also ships the original [**lightweight legacy models**](docs/onnx-models.md),
+15M-80M parameters, which run on CPU without a GPU. Both families load through the same
+`KittenTTS(...)` constructor.
**Commercial support is available.** For integration assistance, custom voices, or enterprise licensing, [contact us](https://docs.google.com/forms/d/e/1FAIpQLSc49erSr7jmh3H2yeqH4oZyRRuXm0ROuQdOgWguTzx6SMdUnQ/viewform?usp=preview).
@@ -25,24 +29,37 @@ Kitten TTS is an open-source, lightweight text-to-speech library built on ONNX.
- [Available Models](#available-models)
- [Demo](#demo)
- [Quick Start](#quick-start)
-- [API Reference](#api-reference)
+- [Voice cloning](#voice-cloning)
+- [Expression controls](#expression-controls)
+- [Running on CPU](#running-on-cpu)
+- [Long text and streaming](#long-text-and-streaming)
+- [Documentation](#documentation)
- [System Requirements](#system-requirements)
-- [Roadmap](#roadmap)
- [Commercial Support](#commercial-support)
- [Community and Support](#community-and-support)
- [License](#license)
## Features
-- **Ultra-lightweight** -- Model sizes from 25 MB (int8) to 80 MB, suitable for edge deployment
-- **CPU-optimized** -- ONNX-based inference runs efficiently without a GPU
-- **8 built-in voices** -- Bella, Jasper, Luna, Bruno, Rosie, Hugo, Kiki, and Leo
-- **Adjustable speech speed** -- Control playback rate via the `speed` parameter
-- **Text preprocessing** -- Built-in pipeline handles numbers, currencies, units, and more
+- **Voice cloning** -- Clone any speaker from 5-30 seconds of audio, no fine-tuning
+- **47 built-in voices** -- Including the eight from KittenTTS 0.8 and nine non-English
+- **Multilingual** -- Ten languages: English, Arabic, Chinese, French, German, Hindi, Italian, Portuguese, Russian, Spanish
+- **Expression control** -- `[emotion]` tags, inline `<event>` tags, and `(((emphasis)))` spans
+- **Decoding presets** -- Trade stability against expressiveness per request
+- **Long-form text** -- Sentence-aware chunking with seamless joins
+- **Text preprocessing** -- Numbers, currencies, dates, units and abbreviations expanded automatically
- **24 kHz output** -- High-quality audio at a standard sample rate
-
+- **Runs without a GPU**
## Available Models
+**KittenTTS 2** -- speech language model:
+
+| Model | Parameters | Size | Voices | Download |
+|---|---|---|---|---|
+| kitten-tts-2 | 1.7B | 506 MiB | 47 + cloning | [KittenML/kitten-tts-2](https://huggingface.co/KittenML/kitten-tts-2) |
+
+**Lightweight ONNX** -- runs on CPU, no GPU required:
+
| Model | Parameters | Size | Download |
|---|---|---|---|
| kitten-tts-mini | 80M | 80 MB | [KittenML/kitten-tts-mini-0.8](https://huggingface.co/KittenML/kitten-tts-mini-0.8) |
@@ -50,7 +67,6 @@ Kitten TTS is an open-source, lightweight text-to-speech library built on ONNX.
| kitten-tts-nano | 15M | 56 MB | [KittenML/kitten-tts-nano-0.8](https://huggingface.co/KittenML/kitten-tts-nano-0.8-fp32) |
| kitten-tts-nano (int8) | 15M | 25 MB | [KittenML/kitten-tts-nano-0.8-int8](https://huggingface.co/KittenML/kitten-tts-nano-0.8-int8) |
-> **Note:** Some users have reported issues with the `kitten-tts-nano-0.8-int8` model. If you encounter problems, please [open an issue](https://github.com/KittenML/KittenTTS/issues).
## Demo
@@ -64,126 +80,155 @@ Try Kitten TTS directly in your browser on [Hugging Face Spaces](https://hugging
### Prerequisites
-- Python 3.8 or later
-- pip
+- Python 3.9 or later
+- A CUDA GPU with roughly 8 GB free, or a CPU with about 6 GB of RAM
+- About 1 GB of disk space for the model, or 506 MiB with the smaller weights
### Installation
```bash
-pip install https://github.com/KittenML/KittenTTS/releases/download/0.8.1/kittentts-0.8.1-py3-none-any.whl
+pip install kittenml
```
-### Basic Usage
+That is the whole install. KittenTTS 2 is the default model, voice cloning is included, and no
+Hugging Face login is needed -- every weight the model uses ships in its own repository. It also
+pulls the small ONNX runtime, so the [lightweight models](docs/onnx-models.md) work from the
+same install.
+
+### Basic usage
```python
-from kittentts import KittenTTS
+from kittenml import KittenTTS
+import soundfile as sf
-model = KittenTTS("KittenML/kitten-tts-mini-0.8")
-audio = model.generate("This high-quality TTS model runs without a GPU.", voice="Jasper")
+m = KittenTTS("KittenML/kitten-tts-2")
-import soundfile as sf
-sf.write("output.wav", audio, 24000)
+audio = m.generate("One day, a little girl named Lily found a needle in her room.",
+ voice="Bruno")
+sf.write("output.wav", audio, m.sample_rate)
```
-### Advanced Usage
+`m.available_voices` lists all 47 built-in voices, described in
+[voices and expression](docs/voices-and-expression.md). Bella, Jasper, Luna, Bruno, Rosie, Hugo,
+Kiki and Leo are the same speakers as in KittenTTS 0.8, so code written against the ONNX models
+keeps working.
+
+The weights come in two sizes. The default is 947 MiB and lossless; `weights="emb4"` is 506 MiB
+because it quantises the token embedding, which costs a little quality. Only the one you ask for
+is downloaded.
```python
-# Adjust speech speed (default: 1.0)
-audio = model.generate("Hello, world.", voice="Luna", speed=1.2)
+m = KittenTTS("KittenML/kitten-tts-2", weights="emb4") # half the download
+```
-# Save directly to a file
-model.generate_to_file("Hello, world.", "output.wav", voice="Bruno", speed=0.9)
+```python
+# Trade stability against expressiveness
+audio = m.generate("Hello, world.", voice="Luna", preset="expressive")
-# List available voices
-print(model.available_voices)
-# ['Bella', 'Jasper', 'Luna', 'Bruno', 'Rosie', 'Hugo', 'Kiki', 'Leo']
+# Save directly to a file
+m.generate_to_file("Hello, world.", "output.wav", voice="Bruno")
```
-### Using with GPU
+## Voice cloning
-```
-pip install -r requirements_gpu.txt
-```
+Pass `reference=` instead of `voice=` — same method, the recording just replaces the built-in
+speaker. Give it 5-30 seconds of a single speaker. The transcript is part of the prompt, but you
+do not have to type it; Whisper fills it in when omitted.
```python
-m = KittenTTS("KittenML/kitten-tts-mini-0.8", backend="cuda")
-```
+audio = m.generate("This is my own voice, cloned.", reference="my_voice.wav")
-Check out `example_cuda.py`
+# Supplying the transcript skips the Whisper pass
+audio = m.generate("This is my own voice.", reference="my_voice.wav",
+ reference_text="what is actually said in the clip")
+```
-## API Reference
+The reference feeds the model by two independent routes -- a speaker embedding through the
+model's projection head, and the clip itself as codec tokens in the prompt -- so identity
+survives even when one route is weak.
-### `KittenTTS(model_name, cache_dir=None)`
+Measured on the built-in voices: a generated clip scores 0.49-0.72 speaker similarity against its
+own reference and 0.01-0.18 against the other 37, and cloning an unseen recording scores 0.81
+against that recording.
-Load a model from Hugging Face Hub.
+## Expression controls
-| Parameter | Type | Default | Description |
-|---|---|---|---|
-| `model_name` | `str` | `"KittenML/kitten-tts-nano-0.8"` | Hugging Face repository ID |
-| `cache_dir` | `str` | `None` | Local directory for caching downloaded model files |
+> **Beta.** Emotion control steers delivery rather than guaranteeing it, and the effect varies
+> by voice and by sentence.
-### `model.generate(text, voice, speed, clean_text)`
+```python
+audio = m.generate(
+ "[joyful] We actually won the grant <laugh> I can (((hardly))) believe it!",
+ voice="Kiki",
+ preset="expressive",
+)
+```
-Synthesize speech from text, returning a NumPy array of audio samples at 24 kHz.
+A leading `[emotion]` tag, inline `<event>` tags and `(((emphasis)))` spans reach the model as
+markup rather than being spoken, and automatically enable its expression conditioning. Ten
+emotions and ten vocal events are recognised -- see
+[voices and expression](docs/voices-and-expression.md) for the full lists and what is not
+covered.
-| Parameter | Type | Default | Description |
-|---|---|---|---|
-| `text` | `str` | -- | Input text to synthesize |
-| `voice` | `str` | `"expr-voice-5-m"` | Voice name (see available voices) |
-| `speed` | `float` | `1.0` | Speech speed multiplier |
-| `clean_text` | `bool` | `False` | Preprocess text (expand numbers, currencies, etc.) |
+## Running on CPU
-### `model.generate_to_file(text, output_path, voice, speed, sample_rate, clean_text)`
+KittenTTS 2 runs on CPU out of the box — `device` is auto-detected — but the fastest way is
+[kitten-tts-2-cpp](https://github.com/KittenML/kitten-tts-2-cpp), our llama.cpp fork. It reads
+the GGUF weights in the model repository's `cpp/` directory.
-Synthesize speech and write directly to an audio file.
-| Parameter | Type | Default | Description |
-|---|---|---|---|
-| `text` | `str` | -- | Input text to synthesize |
-| `output_path` | `str` | -- | Path to save the audio file |
-| `voice` | `str` | `"expr-voice-5-m"` | Voice name |
-| `speed` | `float` | `1.0` | Speech speed multiplier |
-| `sample_rate` | `int` | `24000` | Audio sample rate in Hz |
-| `clean_text` | `bool` | `True` | Preprocess text (expand numbers, currencies, etc.) |
+## Long text and streaming
-### `normalize_text(text, locale="en-US", return_spans=False)`
+Long input is split on sentence boundaries and synthesized chunk by chunk, then joined with
+silence trimming and short edge fades so the seams are inaudible. This is automatic: the model is
+reliable on short inputs but truncates or drifts into repetition when asked for a whole script in
+one pass.
-Normalize text for TTS without generating audio.
+To start playing before the whole thing is ready, stream it:
```python
-from kittentts import normalize_text
+for chunk in m.generate_stream(long_text, voice="Luna"):
+ play(chunk) # each chunk is a numpy array at m.sample_rate
+```
-normalized = normalize_text("Dr. Rivera paid $12.50 at 3:05 p.m.")
-# "Doctor Rivera paid twelve dollars and fifty cents at three oh five p m."
+It takes the same arguments as `generate`, so `reference=` streams a cloned voice too.
-result = normalize_text("Fig. 2", return_spans=True)
-print(result.text)
-print(result.spans)
-```
+Streaming is **chunk-level, not token-level**: a chunk is generated and vocoded in full before it
+is yielded, so the first chunk still costs its own generation time. On an A100, a 936-character
+passage yielded its first 21 s of audio after 17 s and finished 54 s of audio in 42 s of wall
+clock -- so playback keeps ahead of generation, but there is a real initial delay.
+
+Two consequences worth knowing:
-When `return_spans=True`, the result includes original-to-normalized character spans for changed segments such as abbreviations, dates, times, numbers, currency, URLs, and punctuation.
+- **Short text does not stream.** Input that fits in one chunk (under roughly 380 characters,
+ and short trailing pieces get merged into their neighbour) yields exactly one chunk, so
+ `generate_stream` behaves like `generate`.
+- **Chunks are yielded raw.** `generate` post-processes the seams -- trimming each segment's edge
+ silence, adding short fades and one consistent pause -- which a streaming caller cannot do
+ without waiting for the next chunk. Concatenating streamed chunks directly gives slightly
+ rougher joins than `generate` on the same text.
-### `model.available_voices`
+## Documentation
-Returns a list of available voice names: `['Bella', 'Jasper', 'Luna', 'Bruno', 'Rosie', 'Hugo', 'Kiki', 'Leo']`
+| | |
+|---|---|
+| [API reference](docs/api.md) | Every argument to `generate`, streaming, and the advanced knobs |
+| [Voices and expression](docs/voices-and-expression.md) | The 47 voices, emotion and vocal-event tags, the ten languages |
+| [Decoders](docs/decoders.md) | How audio is decoded, and the smaller quantised decoders |
+| [Text normalization](docs/text-normalization.md) | How written text becomes spoken text |
+| [Architecture](docs/architecture.md) | What the model is, package layout, vendored components |
+| [Lightweight ONNX models](docs/onnx-models.md) | The CPU models, 15M-80M parameters, and their API |
## System Requirements
-- **Operating system:** Linux, macOS, or Windows
-- **Python:** 3.8 or later
-- **Hardware:** Runs on CPU; no GPU required
-- **Disk space:** 25-80 MB depending on model variant
+**KittenTTS 2**
-A virtual environment (conda, venv, or similar) is recommended to avoid dependency conflicts.
+- **Operating system:** Linux, Windows or Mac
+- **Python:** 3.9 or later
-## Roadmap
-- [ ] Release optimized inference engine
-- [ ] Release mobile SDK
-- [ ] Release higher quality TTS models
-- [ ] Release multilingual TTS
-- [ ] Release KittenASR
-- [ ] Need anything else? [Let us know](https://github.com/KittenML/KittenTTS/issues)
+A virtual environment (conda, venv, or similar) is recommended to avoid dependency conflicts.
+
## Commercial Support
@@ -201,4 +246,15 @@ We offer commercial support for teams integrating Kitten TTS into their products
## License
-This project is licensed under the [Apache License 2.0](LICENSE).
+This project is licensed under the [Apache License 2.0](LICENSE). That covers the code in this
+repository.
+
+**The models are licensed separately and their terms may differ.** Each model repository carries
+its own licensing, so check the one you intend to use before relying on it — do not assume the
+code's license extends to the weights.
+
+KittenTTS 2 is released under the
+[Stellon Labs Community License](https://huggingface.co/KittenML/kitten-tts-2/blob/main/LICENSE.md):
+free for research, non-commercial and limited commercial use, with the commercial grant ending
+once you pass USD $1,000,000 in annual revenue or total funding. The older ONNX models carry their
+own terms in their own repositories.
diff --git a/assets/banner.png b/assets/banner.png
new file mode 100644
index 0000000..2b1787d
Binary files /dev/null and b/assets/banner.png differ
diff --git a/docs/README.md b/docs/README.md
new file mode 100644
index 0000000..a575890
--- /dev/null
+++ b/docs/README.md
@@ -0,0 +1,12 @@
+# Documentation
+
+Fuller detail than the [project README](../README.md), which covers getting started.
+
+| | |
+|---|---|
+| [api.md](api.md) | The KittenTTS 2 API: every argument to `generate`, streaming, and the advanced knobs |
+| [voices-and-expression.md](voices-and-expression.md) | The 47 built-in voices, the emotion and vocal-event tags, the ten languages |
+| [decoders.md](decoders.md) | How audio is decoded, and the smaller quantised decoders |
+| [text-normalization.md](text-normalization.md) | How written text becomes spoken text |
+| [architecture.md](architecture.md) | What the model is, package layout, vendored components |
+| [onnx-models.md](onnx-models.md) | The lightweight CPU models and their API |
diff --git a/docs/api.md b/docs/api.md
new file mode 100644
index 0000000..a02dd5c
--- /dev/null
+++ b/docs/api.md
@@ -0,0 +1,75 @@
+# API Reference
+
+The KittenTTS 2 API. For the ONNX models see [onnx-models.md](onnx-models.md).
+
+# `KittenTTS(model_name, cache_dir=None, device=None, hf_token=None)`
+
+Loads whichever model family the repository's `config.json` declares.
+
+| Parameter | Type | Default | Description |
+|---|---|---|---|
+| `model_name` | `str` | -- | Hugging Face repo ID, or a path to a local repository directory |
+| `cache_dir` | `str` | `None` | Local directory for caching downloaded files |
+| `device` | `str` | `None` | `"cuda"` or `"cpu"`; auto-detected when omitted. CPU works, at roughly 2-3x slower than real time -- and on a many-core host `torch.set_num_threads(8)` is markedly faster than letting it use every core |
+| `hf_token` | `str` | `None` | Token, only for downloading a private model repository |
+| `decoder` | `str` | repo default | Which decoder to load; see [decoders.md](decoders.md) |
+| `weights` | `str` | `"packed"` | Which weight packing to load: `"packed"` (lossless), `"emb4"` (smaller, quantised embedding), `"full"` (bf16) |
+
+# `model.generate(text, voice=None, reference=None, ...)`
+
+Returns a float32 NumPy array at `model.sample_rate` (24 kHz). The speaker comes from exactly one
+of `voice` or `reference`; giving both, or `reference_text` without `reference`, raises
+`ValueError`.
+
+| Parameter | Type | Default | Description |
+|---|---|---|---|
+| `text` | `str` | -- | Text to speak; supports the expression controls above |
+| `voice` | `str` | repo default | Built-in voice name |
+| `reference` | `str` | `None` | Path to a recording to clone instead of using a built-in voice |
+| `reference_text` | `str` | `None` | Reference transcript; auto-transcribed when omitted |
+| `preset` | `str` | `"stable"` | Decoding preset: `"stable"` or `"expressive"` |
+| `max_new_tokens` | `int` | `1000` | Per-chunk token budget; 25 tokens is about one second |
+| `normalize` | `bool` | `True` | Expand written forms before synthesis |
+| `use_reference_prompt` | `bool` | repo default | Include the reference clip's audio in the prompt |
+| `temperature`, `top_k`, `top_p`, `min_p` | | preset | Override individual preset values |
+| `advanced` | `dict` | `None` | Rarely-needed knobs; see [Advanced options](#advanced-options) |
+
+# Advanced options
+
+`temperature`, `top_k`, `top_p` and `min_p` are arguments in their own right. Everything else
+tunable lives behind `advanced=`, a dict validated against `ADVANCED_OPTIONS` -- an unknown key
+raises `ValueError` rather than being silently ignored.
+
+```python
+audio = m.generate("Hello.", voice="Bruno", advanced={"seed": 1234}) # reproducible
+```
+
+| Option | Default | What it does |
+|---|---|---|
+| `seed` | `None` | Seed the sampler; the same seed gives the same audio |
+| `repetition_penalty` | `1.1` | Penalty on tokens already seen; higher suppresses loops harder |
+| `repetition_window` | repo default | Limit that penalty to the last N generated tokens |
+| `token_run_penalty` | `1.3` | Escalating penalty once one codec token repeats |
+| `token_run_grace` | `10` | How many repeats to allow before that kicks in |
+| `chunk_chars` | repo default | Target chunk size for long text |
+| `chunk_min_chars` | repo default | Chunks below this are merged into a neighbour |
+| `chunk_gap_s` | `0.16` | Pause inserted at a chunk join |
+| `use_emotion` | `None` | Force expression conditioning on or off; `None` auto-detects from tags |
+
+`model.advanced_options` returns these with the repository's defaults already filled in.
+
+# `model.generate_stream(...)`
+
+Same arguments; yields each chunk's audio as it is produced.
+
+# `model.generate_to_file(text, output_path, **kwargs)`
+
+Synthesize and write a wav. Returns the path written.
+
+# `model.available_voices`
+
+List of the built-in voice names accepted by `voice`.
+
+# `model.sample_rate`
+
+Output sample rate, 24000.
diff --git a/docs/architecture.md b/docs/architecture.md
new file mode 100644
index 0000000..ca39c0d
--- /dev/null
+++ b/docs/architecture.md
@@ -0,0 +1,64 @@
+# Architecture
+
+KittenTTS 2 is not a phoneme-to-waveform model. It is a language model over a vocabulary shared
+between text and audio: it reads your text and writes S3 audio codec tokens, which the s3gen
+vocoder turns into 24 kHz speech. Voice identity enters through a speaker embedding projected into
+the first position's hidden state, plus the reference clip's own codec tokens in the prompt.
+
+# Package layout
+
+```
+kittenml/
+ get_model.py KittenTTS(...) -- reads config.json, builds the right backend
+ repo.py repository resolution shared by both backends
+ preprocess.py text normalization shared by both backends
+ kittentts2/ the KittenTTS 2 speech language model
+ model.py KittenTTS2: generate, clone, streaming
+ prompt.py reference prefix and target segment assembly
+ logits.py decode-time sampling and runaway penalties
+ speaker.py spk_proj head, pyannote embedding, Whisper transcription
+ text.py expression markup, normalization, chunking, joining
+ tokens.py the shared text/audio token layout
+ vocoder.py reference encoding and token -> waveform
+ s3gen.py vendored S3 tokenizer + s3gen vocoder
+ kittentts_legacy/ the ONNX models
+ model.py KittenTTSOnnx: generate, speed control
+ onnx_model.py the ONNX session and phonemizer
+```
+
+Neither backend is imported until it is the one selected, so a KittenTTS 2 install never needs
+espeak and an ONNX install never needs torch.
+
+# The model repository
+
+A KittenTTS 2 repository is assembled by internal tooling from a training bundle, and holds
+everything inference needs:
+
+```
+config.json token layout, decode presets, voice and decoder indexes
+lm/ the speech language model, plus its spk_proj head
+speaker/ the speaker-embedding model and its license
+voices/ reference clips, transcripts, and precomputed embeddings
+decoders/ optional quantised decoders
+```
+
+Precomputing the per-voice embeddings is what lets a built-in voice skip the embedding model
+entirely at run time. Nothing in the repository is gated, so installing KittenTTS 2 needs no
+Hugging Face credentials.
+
+Only the paths `config.json` names are downloaded, so a repository can carry artifacts for other
+runtimes without every install paying for them.
+
+### Packed language-model weights
+
+The LM's linear weights are ternary: within each 128-wide group every value is exactly one of
+`{-scale, 0, +scale}`. Stored as bf16 that spends 16 bits per weight to express one of three
+states, so `ternary.py` packs them five trits to a byte — 1.6 bits each, log2(3) rounded up to a
+byte boundary — keeping every group's scale at full bf16 precision. The token embedding, layer
+norms and speaker head are not ternary and are stored unchanged.
+
+That takes the checkpoint from 3.47 GB to 0.95 GB **losslessly**: unpacking reproduces the
+original tensors bit-for-bit, and generated audio is bit-identical. `config.json` advertises it as
+`lm_packed`, and the loader prefers it when present.
+
+See `example.py` for a runnable script, and `example_cloning.py`, `example_expression.py`, `example_streaming.py` and `example_advanced.py` for the rest of the API.
diff --git a/docs/decoders.md b/docs/decoders.md
new file mode 100644
index 0000000..6543060
--- /dev/null
+++ b/docs/decoders.md
@@ -0,0 +1,26 @@
+# Decoders
+
+How KittenTTS 2 turns the model's codec tokens back into audio, and the
+smaller decoders you can swap in.
+
+Audio is decoded in two stages: a flow turns the model's codec tokens into a mel spectrogram,
+then a vocoder turns that into audio. The flow can be swapped for a distilled, weight-quantised
+student that is much smaller on disk:
+
+```python
+m = KittenTTS("KittenML/kitten-tts-2", decoder="student_w4")
+```
+
+| Decoder | Flow on disk | Notes |
+|---|---|---|
+| `default` | 459 MB | The stock flow, two sampling steps. Best quality |
+| `student_w4` | 39 MB | Distilled single-step student, weights packed to 4 bits |
+
+`model.available_decoders` lists them. Only the flow changes -- the tokenizer, speaker encoder
+and vocoder are shared, so voices and prompts behave the same.
+
+Two things worth knowing before choosing one. Quantisation shrinks storage and memory bandwidth,
+not arithmetic, so these are **not meaningfully faster** without a kernel that multiplies in low
+precision. And quality is below the default: measured mel L1 against the teacher is 0.250 for the
+4-bit student versus 0.168 dense, and voices far from the student's 539-speaker training pool
+degrade more than they do on the default decoder. Pick these for footprint.
diff --git a/docs/onnx-models.md b/docs/onnx-models.md
new file mode 100644
index 0000000..f58f036
--- /dev/null
+++ b/docs/onnx-models.md
@@ -0,0 +1,95 @@
+# Lightweight ONNX models
+
+The original Kitten TTS models. For KittenTTS 2 see [api.md](api.md).
+
+The original Kitten TTS models, 15M to 80M parameters (25-80 MB on disk), built on ONNX. They run
+efficiently on CPU without a GPU, which makes them the right choice for edge deployment and for
+anything that cannot carry a PyTorch stack. They offer eight voices and adjustable speech speed,
+and no voice cloning or expression control.
+
+# Installation
+
+Already covered by `pip install kittenml`, which includes the ONNX runtime. Python 3.8 or later,
+and no GPU required.
+
+Note that the default install also pulls PyTorch for KittenTTS 2, which is large relative to
+these models. Installing `kittenml` with `--no-deps` alongside `onnxruntime`, `espeakng_loader`,
+`phonemizer`, `soundfile`, `numpy` and `huggingface_hub` is enough to run them on their own.
+
+# Basic usage
+
+```python
+from kittenml import KittenTTS
+
+model = KittenTTS("KittenML/kitten-tts-mini-0.8")
+audio = model.generate("This high-quality TTS model runs without a GPU.", voice="Jasper")
+
+import soundfile as sf
+sf.write("output.wav", audio, 24000)
+```
+
+# Advanced usage
+
+```python
+# Adjust speech speed (default: 1.0)
+audio = model.generate("Hello, world.", voice="Luna", speed=1.2)
+
+# Save directly to a file
+model.generate_to_file("Hello, world.", "output.wav", voice="Bruno", speed=0.9)
+
+# List available voices
+print(model.available_voices)
+# ['Bella', 'Jasper', 'Luna', 'Bruno', 'Rosie', 'Hugo', 'Kiki', 'Leo']
+```
+
+# Using with GPU
+
+```
+pip install -r requirements_gpu.txt
+```
+
+```python
+m = KittenTTS("KittenML/kitten-tts-mini-0.8", backend="cuda")
+```
+
+Check out `example_onnx_0.8.py`
+
+# ONNX API Reference
+
+# `KittenTTS(model_name, cache_dir=None, backend=None)`
+
+Load a model from Hugging Face Hub.
+
+| Parameter | Type | Default | Description |
+|---|---|---|---|
+| `model_name` | `str` | `"KittenML/kitten-tts-nano-0.8"` | Hugging Face repository ID |
+| `cache_dir` | `str` | `None` | Local directory for caching downloaded model files |
+| `backend` | `str` | `None` | ONNX execution provider: `"cpu"`, `"cuda"`, `"amd_gpu"` |
+
+# `model.generate(text, voice, speed, clean_text)`
+
+Synthesize speech from text, returning a NumPy array of audio samples at 24 kHz.
+
+| Parameter | Type | Default | Description |
+|---|---|---|---|
+| `text` | `str` | -- | Input text to synthesize |
+| `voice` | `str` | `"expr-voice-5-m"` | Voice name (see available voices) |
+| `speed` | `float` | `1.0` | Speech speed multiplier |
+| `clean_text` | `bool` | `False` | Preprocess text (expand numbers, currencies, etc.) |
+
+# `model.generate_to_file(text, output_path, voice, speed, sample_rate, clean_text)`
+
+Synthesize speech and write directly to an audio file.
+
+| Parameter | Type | Default | Description |
+|---|---|---|---|
+| `text` | `str` | -- | Input text to synthesize |
+| `output_path` | `str` | -- | Path to save the audio file |
+| `voice` | `str` | `"expr-voice-5-m"` | Voice name |
+| `speed` | `float` | `1.0` | Speech speed multiplier |
+| `sample_rate` | `int` | `24000` | Audio sample rate in Hz |
+| `clean_text` | `bool` | `True` | Preprocess text (expand numbers, currencies, etc.) |
+
+# `model.available_voices`
+
+Returns a list of available voice names: `['Bella', 'Jasper', 'Luna', 'Bruno', 'Rosie', 'Hugo', 'Kiki', 'Leo']`
diff --git a/docs/text-normalization.md b/docs/text-normalization.md
new file mode 100644
index 0000000..e7405bf
--- /dev/null
+++ b/docs/text-normalization.md
@@ -0,0 +1,25 @@
+# Text normalization
+
+Numbers, currencies, dates, units and abbreviations are expanded automatically before synthesis,
+so `$12.50` is spoken rather than spelled. You can also call it directly:
+
+```python
+from kittenml import normalize_text
+
+normalized = normalize_text("Dr. Rivera paid $12.50 at 3:05 p.m.")
+# "Doctor Rivera paid twelve dollars and fifty cents at three oh five p m."
+
+result = normalize_text("Fig. 2", return_spans=True)
+print(result.text)
+print(result.spans)
+```
+
+With `return_spans=True` the result also carries original-to-normalized character spans for each
+changed segment.
+
+KittenTTS 2 uses [`kitten-text-processing`](https://github.com/KittenML/kitten-text-processing)
+for this, which reproduces the normalization the checkpoint was served with. It is pure Python
+and pulled in automatically, so there is nothing to compile on any platform.
+
+The `normalize_text` shown above is `kittenml/preprocess.py`, a separate in-repo implementation
+that the ONNX models use and that is the one able to return spans.
diff --git a/docs/voices-and-expression.md b/docs/voices-and-expression.md
new file mode 100644
index 0000000..1bacdee
--- /dev/null
+++ b/docs/voices-and-expression.md
@@ -0,0 +1,151 @@
+# Voices and expression
+
+The built-in voices, the expression markup the model understands, and what it does and
+does not cover. See [api.md](api.md) for the arguments these go with.
+
+## Expression controls
+
+Three kinds of markup reach the model as direction rather than as words to pronounce. Using
+any of them automatically switches on the model's `{emo: 1}` conditioning; pass
+`advanced={"use_emotion": False}` to force it off, or `True` to force it on for untagged text.
+
+Emotion support is **early beta**. It steers delivery rather than guaranteeing it, and the
+effect varies by voice and by sentence.
+
+### Emotion
+
+A leading tag sets the emotion for the whole line.
+
+```python
+m.generate("[joyful] We actually won the grant!", voice="Kiki")
+```
+
+`[angry]` `[contemplative]` `[excited]` `[joyful]` `[mundane]` `[nervous]` `[sad]` `[stern]`
+`[surprised]` `[tender]`
+
+### Vocal events
+
+An inline tag inserts a non-verbal beat anywhere in the line.
+
+```python
+m.generate("We won <laugh> I can hardly believe it.", voice="Kiki")
+```
+
+`<gasp>` `<giggle>` `<growl>` `<gulp>` `<laugh>` `<pause>` `<scoff>` `<sigh>` `<sob>` `<um>`
+
+### Emphasis
+
+Triple parentheses stress a word or short phrase.
+
+```python
+m.generate("I told you (((never))) to open that door.", voice="Victor")
+```
+
+### Why these lists and not others
+
+The training data carries 2,684 distinct emotion values and 1,101 distinct vocal-event values.
+The twenty above are the ten most common of each, covering roughly half of all tagged lines.
+They are a recognition list, not the model's full vocabulary: a rarer tag such as `[reverent]`
+is real in the data but is **not** recognised here, and will be normalized and spoken as
+ordinary text.
+
+That restraint is deliberate. Treating every bracketed span as markup would silently swallow
+things people write for other reasons — a citation like `section [3]`, a comparison like
+`x < 5`. Those are left as text.
+
+Anything bracketed that is *not* one of these tags gets rewritten to plain comma-separated
+text before synthesis, because the model destabilises on bracket punctuation it was not
+trained to read. This was observed directly: a parenthetical list,
+`(salons, dental offices, restaurants)`, generated abnormally fast — ~0.043 s/char against
+0.056–0.093 for every other chunk of the same request, reproducibly — consistent with the
+model rushing through it.
+
+`EXPRESSION_TAGS` and `VOCAL_EVENT_TAGS` in `kittenml.kittentts2.text` are the live lists;
+extend them if you want more tags protected.
+
+## Built-in voices
+
+Forty-seven voices, listed by `model.available_voices`: thirty-eight English, plus nine named
+after the [languages](#languages) below. Bella, Jasper, Luna, Bruno, Rosie, Hugo, Kiki and Leo
+are the same speakers as in KittenTTS 0.8, so code written against the ONNX models keeps
+working.
+
+| Voice | Character | | Voice | Character |
+|---|---|---|---|---|
+| **Bella** | KittenTTS 0.8 voice, female | | **Herbert** | Wise elderly professor, male |
+| **Jasper** | KittenTTS 0.8 voice, male | | **Diana** | Stern military officer, female |
+| **Luna** | KittenTTS 0.8 voice, female | | **Laurence** | Dramatic stage actor, male |
+| **Bruno** | KittenTTS 0.8 voice, male | | **Maeve** | Cozy warm storyteller, female |
+| **Rosie** | KittenTTS 0.8 voice, female | | **Walter** | Warm grandfather, male |
+| **Hugo** | KittenTTS 0.8 voice, male | | **Edith** | Soft elderly grandmother, female |
+| **Kiki** | KittenTTS 0.8 voice, female | | **Miles** | Gentle librarian, male |
+| **Leo** | KittenTTS 0.8 voice, male | | **Grace** | Soothing nurse, female |
+| **Matthew** | Exhausted mechanic, male | | **Reginald** | Distinguished elderly diplomat, male |
+| **Elliot** | Grieving young, male | | **Iris** | Hushed museum guide, female |
+| **Willow** | Hushed young, female | | **Frank** | Gravelly grizzled war veteran, male |
+| **Dolores** | Southern elderly, female | | **Serena** | Gentle yoga instructor, female |
+| **Victor** | Controlled fury older, male | | **Julian** | Dreamy poet soft, male |
+| **Dante** | Playful smooth young, male | | **Eleanor** | Somber historian, female |
+| **Alfred** | Tender older, male | | **Otis** | Rumbling blues musician, male |
+| **Saoirse** | Joyful irish, female | | **Vincent** | Hushed museum guide, male |
+| **Claire** | Playful professional, female | | **Martha** | Weathered radio journalist, female |
+| **Raven** | Controlled fury young, female | | **Sable** | Hushed conspirator, female |
+| **Marcus** | Smooth radio DJ, male | | **Victoria** | Regal narrator, female |
+
+Every reference clip is 8–18 seconds of a single speaker. A voice is the clip *and* its
+transcript: both go into the prompt, which is why cloning a new voice wants a transcript too
+(and transcribes one for you when you omit it).
+
+## Languages
+
+The model is multilingual. Its SFT mix is about 10% non-English across nine languages, and a
+Hindi voice was added on top, giving ten in total. Each ships as one built-in voice, named
+after its language:
+
+| Voice | Language | Voice | Language |
+|---|---|---|---|
+| **Arabic** | العربية | **Italian** | Italiano |
+| **Chinese** | 简体中文 | **Portuguese** | Português |
+| **French** | Français | **Russian** | Русский |
+| **German** | Deutsch | **Spanish** | Español |
+| **Hindi** | हिन्दी | | |
+
+```python
+m.generate("Guten Morgen. Ich wünsche dir einen wunderschönen Tag.",
+ voice="German", normalize=False)
+```
+
+The voice carries the language: these clips are what supply the accent and phonotactics, so
+asking an English voice for German text will not work well. Cloning from your own non-English
+recording works the same way.
+
+**Pass `normalize=False` for non-English text.** The normalizer is English-tuned, and will
+mangle numbers, dates and abbreviations in other languages. That is a real limitation, not an
+oversight — the upstream demo carries the same caveat.
+
+One reference clip per language is a modest base, so expect these to be less robust than the
+English voices, and quality to vary by language. Measured by transcribing generated audio back
+with Whisper, all ten reproduce their prompt: German, Spanish, French, Italian, Portuguese,
+Russian and Chinese came back verbatim; Arabic and Hindi came back with small errors.
+
+## Getting more expressive output
+
+The `expressive` preset loosens sampling a little. To push further, use the
+[advanced options](api.md#advanced-options): disable `top_k` by setting it to `0`, raise
+`temperature` above `1.0`, and raise `top_p` to `0.9` or above. The further you push, the
+livelier — and the less predictable — the delivery.
+
+```python
+m.generate("[excited] This is going to be good!", voice="Dante",
+ preset="expressive", top_k=0, temperature=1.1, top_p=0.95)
+```
+
+## Known limitations
+
+- Emotion conditioning is early beta; it biases delivery rather than guaranteeing it.
+- Only the twenty tags above are recognised, not the full long tail in the data.
+- The non-English voices rest on a single reference clip each; they are more fragile than the
+ English set, and the text normalizer does not cover them.
+- Voices far from the model's training distribution clone less well than the built-in ones.
+ This is more pronounced on the quantised [decoders](decoders.md), whose student was trained
+ on a 539-speaker pool.
diff --git a/example.py b/example.py
index ad1e5b4..7b20e01 100644
--- a/example.py
+++ b/example.py
@@ -1,27 +1,13 @@
-from kittentts import KittenTTS
-
-# it will run blazing fast on any GPU. But this example will run on CPU.
-
-# Step 1: Load the model
-m = KittenTTS("KittenML/kitten-tts-mini-0.8") # 80M version (highest quality)
-# m = KittenTTS("KittenML/kitten-tts-micro-0.8") # 40M version (balances speed and quality )
-# m = KittenTTS("KittenML/kitten-tts-nano-0.8") # 15M version (tiny and faster )
-
-
-# Step 2: Generate the audio
-
-# this is a sample from the TinyStories dataset.
-text ="""One day, a little girl named Lily found a needle in her room. She knew it was difficult to play with it because it was sharp. """
-
+"""KittenTTS 2 — the basics."""
+import soundfile as sf
-# available_voices : ['Bella', 'Jasper', 'Luna', 'Bruno', 'Rosie', 'Hugo', 'Kiki', 'Leo']
-voice = 'Bruno'
+from kittenml import KittenTTS
+m = KittenTTS("KittenML/kitten-tts-2")
+print(m.available_voices)
-audio = m.generate(text=text, voice=voice )
+text = "One day, a little girl named Lily found a needle in her room."
+audio = m.generate(text, voice="Bruno")
-# Save the audio
-import soundfile as sf
-sf.write('output.wav', audio, 24000)
-print(f"Audio saved to output.wav")
\ No newline at end of file
+sf.write("output.wav", audio, m.sample_rate)
diff --git a/example_advanced.py b/example_advanced.py
new file mode 100644
index 0000000..6701fea
--- /dev/null
+++ b/example_advanced.py
@@ -0,0 +1,31 @@
+"""KittenTTS 2 — smaller weights, smaller decoder, and decoding knobs."""
+import soundfile as sf
+
+from kittenml import KittenTTS
+
+text = "The quick brown fox jumps over the lazy dog."
+
+# Weights: "packed" (954 MB, default, lossless), "emb4" (469 MB, lossy
+# embedding), "full" (3469 MB, plain bf16). Only the one you ask for downloads.
+m = KittenTTS("KittenML/kitten-tts-2", weights="emb4")
+
+# Decoder: "default" (459 MB) or "student_w4" (39 MB).
+m = KittenTTS("KittenML/kitten-tts-2", decoder="student_w4")
+
+# Device is auto-detected; force it if you want to.
+m = KittenTTS("KittenML/kitten-tts-2", device="cpu")
+
+# Sampling: a preset, or individual overrides.
+audio = m.generate(text, voice="Bruno", preset="expressive")
+audio = m.generate(text, voice="Bruno", temperature=0.7, top_p=0.9, top_k=50)
+
+# Seed for a reproducible generation.
+audio = m.generate(text, voice="Bruno", advanced={"seed": 1234})
+sf.write("output.wav", audio, m.sample_rate)
+
+# Everything `advanced=` accepts, with this model's values.
+print(m.advanced_options)
+
+# Skip text normalization, or just see what it would do.
+m.generate("Read $12.50 as written.", voice="Bruno", normalize=False)
+print(m.normalize_text("Dr. Chen arrives at 9:30 a.m. on the 3rd."))
diff --git a/example_cloning.py b/example_cloning.py
new file mode 100644
index 0000000..9370dec
--- /dev/null
+++ b/example_cloning.py
@@ -0,0 +1,15 @@
+"""KittenTTS 2 — clone a voice from 5-30 seconds of a single speaker."""
+import soundfile as sf
+
+from kittenml import KittenTTS
+
+m = KittenTTS("KittenML/kitten-tts-2")
+
+audio = m.generate("This is my own voice, cloned.", reference="my_voice.wav")
+sf.write("cloned.wav", audio, m.sample_rate)
+
+# The clip is transcribed automatically. Pass the transcript if you have it.
+audio = m.generate("The transcript is optional, but it helps.",
+ reference="my_voice.wav",
+ reference_text="What the recording actually says.")
+sf.write("cloned2.wav", audio, m.sample_rate)
diff --git a/example_cuda.py b/example_cuda.py
deleted file mode 100644
index 1cca8d6..0000000
--- a/example_cuda.py
+++ /dev/null
@@ -1,27 +0,0 @@
-from kittentts import KittenTTS
-
-# This example will runs on GPU.
-
-# Step 1: Load the model
-m = KittenTTS("KittenML/kitten-tts-mini-0.8", backend="cuda") # 80M version (highest quality)
-# m = KittenTTS("KittenML/kitten-tts-micro-0.8") # 40M version (balances speed and quality )
-# m = KittenTTS("KittenML/kitten-tts-nano-0.8") # 15M version (tiny and faster )
-
-
-# Step 2: Generate the audio
-
-# this is a sample from the TinyStories dataset.
-text ="""One day, a little girl named Lily found a needle in her room. She knew it was difficult to play with it because it was sharp. """
-
-
-# available_voices : ['Bella', 'Jasper', 'Luna', 'Bruno', 'Rosie', 'Hugo', 'Kiki', 'Leo']
-voice = 'Bruno'
-
-
-
-audio = m.generate(text=text, voice=voice )
-
-# Save the audio
-import soundfile as sf
-sf.write('output.wav', audio, 24000)
-print(f"Audio saved to output.wav")
\ No newline at end of file
diff --git a/example_expression.py b/example_expression.py
new file mode 100644
index 0000000..dbfb03c
--- /dev/null
+++ b/example_expression.py
@@ -0,0 +1,30 @@
+"""KittenTTS 2 — expression tags and other languages.
+
+Expression control is in beta: it steers delivery rather than guaranteeing it.
+"""
+import soundfile as sf
+
+from kittenml import KittenTTS
+
+m = KittenTTS("KittenML/kitten-tts-2")
+
+# A leading [emotion], inline <events>, and (((emphasis))) spans.
+audio = m.generate(
+ "[joyful] We won the grant <laugh> I can (((hardly))) believe it!",
+ voice="Kiki",
+ preset="expressive", # "stable" is the default
+)
+sf.write("expressive.wav", audio, m.sample_rate)
+
+# Emotions: angry contemplative excited joyful mundane
+# nervous sad stern surprised tender
+# Events: gasp giggle growl gulp laugh
+# pause scoff sigh sob um
+
+# Other languages: the voice carries the accent. normalize=False because the
+# text normalizer is English-tuned.
+audio = m.generate("Guten Morgen. Ich wünsche dir einen wunderschönen Tag.",
+ voice="German", normalize=False)
+sf.write("german.wav", audio, m.sample_rate)
+
+# Also: Arabic, Spanish, French, Italian, Portuguese, Russian, Chinese, Hindi.
diff --git a/example_onnx_0.8.py b/example_onnx_0.8.py
new file mode 100644
index 0000000..ef9f7af
--- /dev/null
+++ b/example_onnx_0.8.py
@@ -0,0 +1,23 @@
+"""KittenTTS 0.8 — the older ONNX models.
+
+15M to 80M parameters, no cloning and no expression control, but tiny.
+"""
+import soundfile as sf
+
+from kittenml import KittenTTS
+
+m = KittenTTS("KittenML/kitten-tts-mini-0.8") # 80M, highest quality
+# m = KittenTTS("KittenML/kitten-tts-micro-0.8") # 40M
+# m = KittenTTS("KittenML/kitten-tts-nano-0.8") # 15M, smallest
+
+print(m.available_voices)
+
+text = "One day, a little girl named Lily found a needle in her room."
+audio = m.generate(text, voice="Bruno")
+sf.write("output.wav", audio, 24000)
+
+# Speed control, which KittenTTS 2 does not have.
+sf.write("slow.wav", m.generate(text, voice="Luna", speed=0.8), 24000)
+
+# ONNX Runtime can use an accelerator, with the matching onnxruntime build.
+# m = KittenTTS("KittenML/kitten-tts-mini-0.8", backend="cuda")
diff --git a/example_streaming.py b/example_streaming.py
index bc41518..7ac2ce4 100644
--- a/example_streaming.py
+++ b/example_streaming.py
@@ -1,39 +1,22 @@
+"""KittenTTS 2 — get each chunk as soon as it is generated."""
import numpy as np
import soundfile as sf
-from kittentts import KittenTTS
-SAMPLE_RATE = 24000
+from kittenml import KittenTTS
-# Step 1: Load the model
-m = KittenTTS("KittenML/kitten-tts-mini-0.8") # 80M version (highest quality)
-# m = KittenTTS("KittenML/kitten-tts-mini-0.8", backend="cuda") # GPU version
-# m = KittenTTS("KittenML/kitten-tts-micro-0.8") # 40M version
-# m = KittenTTS("KittenML/kitten-tts-nano-0.8") # 15M version (tiny and faster)
+m = KittenTTS("KittenML/kitten-tts-2")
-# Step 2: Define text and voice
-text = """One day, a little girl named Lily found a needle in her room. She knew it was difficult to play with it because it was sharp. Lily wanted to use the needle to sew a button on her shirt. She asked her mom for help."""
+text = ("One day, a little girl named Lily found a needle in her room. "
+ "She knew it was difficult to play with it because it was sharp. "
+ "Lily wanted to use the needle to sew a button on her shirt. "
+ "She asked her mom for help, and her mom smiled and said yes. "
+ "They sat together by the window, where the afternoon light was best, "
+ "and her mom showed her how to hold the fabric steady with one hand.")
-voice = "Bruno"
-
-# Optional: try to import sounddevice for real-time playback
-try:
- import sounddevice as sd
- has_audio = True
-except (ImportError, OSError):
- has_audio = False
-
-# Step 3: Stream audio chunk by chunk
-print("Streaming audio...")
+# Each chunk is a 1-D float32 array. Text under ~380 characters yields once.
chunks = []
-for i, chunk in enumerate(m.generate_stream(text=text, voice=voice)):
- audio = chunk.squeeze()
- chunks.append(audio)
- print(f" Chunk {i + 1}: {len(audio)} samples ({len(audio) / SAMPLE_RATE:.2f}s)")
- if has_audio:
- sd.play(audio, samplerate=SAMPLE_RATE)
- sd.wait()
+for chunk in m.generate_stream(text, voice="Luna"):
+ print(f"{len(chunk) / m.sample_rate:.1f}s")
+ chunks.append(chunk)
-# Save the full audio
-full_audio = np.concatenate(chunks)
-sf.write("output_streaming.wav", full_audio, SAMPLE_RATE)
-print(f"Audio saved to output_streaming.wav ({len(full_audio) / SAMPLE_RATE:.2f}s total)")
+sf.write("output_streaming.wav", np.concatenate(chunks), m.sample_rate)
diff --git a/kittenml/__init__.py b/kittenml/__init__.py
new file mode 100644
index 0000000..d438b64
--- /dev/null
+++ b/kittenml/__init__.py
@@ -0,0 +1,40 @@
+from kittenml.preprocess import NormalizedSpan, NormalizedTextResult, normalize_text, normalize_text_result
+
+try: # the installed distribution is the source of truth
+ from importlib.metadata import version as _version
+
+ __version__ = _version("kittenml")
+except Exception: # running from a source tree without an install
+ __version__ = "0.0.0.dev0"
+__author__ = "KittenML"
+__description__ = "Text-to-speech with voice cloning and expression control, plus ultra-lightweight models that run on CPU"
+
+__all__ = [
+ "get_model",
+ "KittenTTS",
+ "KittenTTS2",
+ "KittenTTSOnnx",
+ "normalize_text",
+ "normalize_text_result",
+ "NormalizedSpan",
+ "NormalizedTextResult",
+]
+
+
+def __getattr__(name):
+ if name in {"get_model", "KittenTTS"}:
+ from kittenml.get_model import KittenTTS, get_model
+
+ return {"get_model": get_model, "KittenTTS": KittenTTS}[name]
+ # Imported lazily: KittenTTS 2 pulls in torch and transformers, which an
+ # ONNX-only install does not have.
+ if name == "KittenTTS2":
+ from kittenml.kittentts2 import KittenTTS2
+
+ return KittenTTS2
+ # Likewise the ONNX backend, which needs espeak and phonemizer.
+ if name == "KittenTTSOnnx":
+ from kittenml.kittentts_legacy import KittenTTSOnnx
+
+ return KittenTTSOnnx
+ raise AttributeError(f"module 'kittenml' has no attribute {name!r}")
diff --git a/kittenml/get_model.py b/kittenml/get_model.py
new file mode 100644
index 0000000..54c6188
--- /dev/null
+++ b/kittenml/get_model.py
@@ -0,0 +1,94 @@
+"""The shared entry point: one constructor, two model families.
+
+`KittenTTS(...)` reads the repository's config.json and builds whichever backend
+it declares — `kittentts2` for the KittenTTS 2 speech language model, `kittentts_legacy`
+for the ONNX models. Neither backend is imported until it is the one selected, so
+a KittenTTS 2 install never needs espeak and an ONNX install never needs torch.
+"""
+
+from huggingface_hub import snapshot_download
+
+from .kittentts_legacy import KittenTTSOnnx, download_from_huggingface # noqa: F401
+from .repo import KITTEN2_TYPE, ONNX_TYPES, resolve_repo
+
+
+def _kitten2_files(config, decoder=None, weights=None):
+ """The paths a KittenTTS 2 repository's config actually points at.
+
+ A model repository may carry artifacts for other runtimes alongside these — a
+ llama.cpp bundle, say — and `snapshot_download` takes everything by default.
+ Narrowing it to what the config declares keeps an install from pulling gigabytes
+ it cannot use, and needs no knowledge of what else happens to be in there.
+ """
+ import posixpath
+
+ wanted = {"config.json"}
+ lm_dir = config.get("lm_dir", "lm")
+ # Only the selected weight variant. The packings are equivalent models at very
+ # different sizes, so fetching all of them would defeat the point of having them.
+ variant = weights or config.get("default_weights", "packed")
+ declared = {"packed": config.get("lm_packed"), "emb4": config.get("lm_emb4")}
+ if variant in declared and declared[variant]:
+ wanted.add(declared[variant])
+ wanted.add(posixpath.join(lm_dir, "*.json"))
+ wanted.add(posixpath.join(lm_dir, "*.txt"))
+ else:
+ wanted.add(posixpath.join(lm_dir, "*"))
+ for key, default in (("voices", "voices/voices.json"),
+ ("speaker_embedding", "speaker/model.safetensors")):
+ path = config.get(key, default)
+ wanted.add(posixpath.join(posixpath.dirname(path), "*"))
+ # Only the decoder being used. The default decoder needs none of these files, and
+ # fetching every alternative would add ~100 MB nobody asked for. Picking a
+ # different one later constructs a new model, which downloads it then.
+ decoders = config.get("decoders", {})
+ name = decoder or config.get("default_decoder", "default")
+ if name in decoders:
+ wanted.add(decoders[name])
+ return sorted(wanted)
+
+
+class KittenTTS(KittenTTSOnnx):
+ """Entry point for every KittenTTS model.
+
+ The repository's config.json decides what you get back. An ONNX repository
+ yields this class, which is the ONNX backend. A KittenTTS 2 repository yields
+ a `kittentts2.KittenTTS2` instead — a language model with a larger API: voice
+ cloning, expression tags, decoding presets.
+
+ m = KittenTTS("KittenML/kitten-tts-mini-0.8") # ONNX, runs on CPU
+ m = KittenTTS("KittenML/kitten-tts-2") # KittenTTS 2, GPU optional
+
+ Both also accept a path to a local repository directory.
+ """
+
+ def __new__(cls, model_name="KittenML/kitten-tts-nano-0.8", cache_dir=None,
+ backend=None, device=None, hf_token=None, decoder=None, weights=None):
+ local_dir, repo_id, config = resolve_repo(model_name, cache_dir)
+ model_type = config.get("type")
+
+ if model_type == KITTEN2_TYPE:
+ from .kittentts2 import KittenTTS2
+ if local_dir is None:
+ local_dir = snapshot_download(
+ repo_id=repo_id, cache_dir=cache_dir, token=hf_token,
+ allow_patterns=_kitten2_files(config, decoder, weights))
+ # Returning a different class means __init__ below is never called.
+ return KittenTTS2(local_dir, config, device=device, cache_dir=cache_dir,
+ hf_token=hf_token, decoder=decoder, weights=weights)
+
+ if model_type not in ONNX_TYPES:
+ raise ValueError(
+ f"Unsupported model type {model_type!r}; expected one of "
+ f"{[*ONNX_TYPES, KITTEN2_TYPE]}")
+
+ instance = super().__new__(cls)
+ # Hand the already-resolved repository to KittenTTSOnnx.__init__ rather
+ # than making it hit the Hub a second time.
+ instance._resolved = (local_dir, repo_id, config)
+ return instance
+
+
+def get_model(repo_id="KittenML/kitten-tts-nano-0.1", cache_dir=None, backend=None):
+ """Get a KittenTTS model (legacy function for backward compatibility)."""
+ return KittenTTS(repo_id, cache_dir, backend=backend)
diff --git a/kittenml/kittentts2/__init__.py b/kittenml/kittentts2/__init__.py
new file mode 100644
index 0000000..8104b2f
--- /dev/null
+++ b/kittenml/kittentts2/__init__.py
@@ -0,0 +1,19 @@
+"""KittenTTS 2 — a speech language model with in-context voice cloning.
+
+Loaded through `kittenml.KittenTTS` when a repository's config.json declares
+`"type": "KITTEN2"`. See `model.KittenTTS2` for the API.
+"""
+
+from .model import KittenTTS2
+from .text import (EXPRESSION_TAGS, VOCAL_EVENT_TAGS, has_expression_tag,
+ warm_normalizer)
+from .tokens import TokenMap
+
+__all__ = [
+ "KittenTTS2",
+ "TokenMap",
+ "has_expression_tag",
+ "warm_normalizer",
+ "EXPRESSION_TAGS",
+ "VOCAL_EVENT_TAGS",
+]
diff --git a/kittenml/kittentts2/logits.py b/kittenml/kittentts2/logits.py
new file mode 100644
index 0000000..025de1d
--- /dev/null
+++ b/kittenml/kittentts2/logits.py
@@ -0,0 +1,120 @@
+"""Sampling pipeline for KittenTTS 2 decoding.
+
+The whole pipeline is assembled explicitly as a `LogitsProcessorList` and handed
+to `generate()` with neutral sampling kwargs, so transformers adds nothing of its
+own and the ordering here is the ordering that runs.
+
+Both custom processors are vectorised. The stock equivalents call
+`input_ids[b].tolist()` on every decode step for every row — a GPU-to-Python copy
+of the whole sequence followed by a Python loop — which costs O(batch x seq) of
+interpreter time per token and stalls the GPU as the sequence grows. These
+compute the same thing on-device.
+"""
+
+import torch
+from transformers import (
+ LogitsProcessor,
+ LogitsProcessorList,
+ MinPLogitsWarper,
+ TemperatureLogitsWarper,
+ TopKLogitsWarper,
+ TopPLogitsWarper,
+)
+
+# The S3 codec's silence token, as an offset within the audio range. Runs of it are
+# the model's most common stuck state, and it is the one token the repetition
+# penalty must leave alone (see RepetitionPenaltyExempt).
+SILENCE_TOKEN = 4299
+
+
+class RepetitionPenaltyExempt(LogitsProcessor):
+ """Repetition penalty that never penalises the sequence-terminating tokens.
+
+ `<speech_end>`, `[STOP]` and the silence codec token are exempt: penalising
+ them suppresses the trailing silence the model needs before it can close a
+ segment, which turns a clean ending into an over-generation.
+
+ window=None scans the whole sequence. window=N restricts the scan to the last
+ N *generated* positions, so codec tokens from a long in-context reference
+ cannot suppress valid target-audio tokens merely for having occurred in the
+ prompt. Vectorising across the batch is safe because every caller left-pads
+ to a common width first, making `prompt_length` uniform across rows.
+ """
+
+ def __init__(self, penalty, exempt_ids, window=None, prompt_length=0):
+ self.penalty = float(penalty)
+ self._exempt = sorted({int(i) for i in exempt_ids})
+ self._exempt_t = None
+ self.window = int(window) if window else None
+ self.prompt_length = int(prompt_length)
+
+ def __call__(self, input_ids, scores):
+ hist = input_ids
+ if self.window is not None:
+ start = max(self.prompt_length, input_ids.shape[1] - self.window)
+ hist = input_ids[:, start:]
+ if hist.shape[1] == 0:
+ return scores
+ got = torch.gather(scores, 1, hist)
+ got = torch.where(got < 0, got * self.penalty, got / self.penalty)
+ out = scores.scatter(1, hist, got)
+ if self._exempt:
+ if self._exempt_t is None or self._exempt_t.device != scores.device:
+ self._exempt_t = torch.tensor(self._exempt, device=scores.device, dtype=torch.long)
+ out[:, self._exempt_t] = scores[:, self._exempt_t]
+ return out
+
+
+class TokenRunPenalty(LogitsProcessor):
+ """Escalating penalty on a codec token repeated past `grace` times in a row.
+
+ Catches the model getting stuck on one token — silence, room tone, or a held
+ phoneme — which is the dominant long-generation failure. The trailing run
+ length is a reversed cumulative product over the equality mask, so no Python
+ rescan of the sequence is needed.
+ """
+
+ def __init__(self, lo, hi, grace=10, strength=1.3):
+ self.lo, self.hi = int(lo), int(hi)
+ self.grace, self.strength = int(grace), float(strength)
+
+ def __call__(self, input_ids, scores):
+ last = input_ids[:, -1]
+ eq = (input_ids == last.unsqueeze(1)).to(torch.int8)
+ run = eq.flip(1).cumprod(dim=1).sum(dim=1)
+ hit = ((last >= self.lo) & (last < self.hi) & (run >= self.grace)).nonzero().flatten()
+ if hit.numel():
+ penalty = (run[hit] - self.grace + 1).to(scores.dtype) * self.strength
+ scores[hit, last[hit]] -= penalty
+ return scores
+
+
+def build_logits_processors(token_map, temperature, top_k, top_p, min_p,
+ repetition_penalty=1.1, repetition_window=None,
+ token_run_penalty=1.3, token_run_grace=10,
+ prompt_length=0):
+ """Assemble the decode-time processor list.
+
+ Penalties come before the warpers so that truncation sees already-penalised
+ scores; that ordering is part of what the decode presets were tuned against.
+ """
+ lo, hi = token_map.audio_id_base, token_map.audio_id_end
+ silence_id = lo + SILENCE_TOKEN
+ processors = LogitsProcessorList()
+
+ if token_run_penalty:
+ processors.append(TokenRunPenalty(lo, hi, token_run_grace, token_run_penalty))
+ if repetition_penalty != 1.0:
+ exempt = {token_map.speech_end_id, token_map.stop_id, silence_id}
+ processors.append(RepetitionPenaltyExempt(
+ repetition_penalty, exempt, window=repetition_window, prompt_length=prompt_length))
+ if temperature != 1.0:
+ processors.append(TemperatureLogitsWarper(float(temperature)))
+ if top_k:
+ processors.append(TopKLogitsWarper(int(top_k)))
+ if top_p < 1.0:
+ processors.append(TopPLogitsWarper(float(top_p)))
+ if min_p > 0.0:
+ processors.append(MinPLogitsWarper(float(min_p)))
+ return processors
+
diff --git a/kittenml/kittentts2/model.py b/kittenml/kittentts2/model.py
new file mode 100644
index 0000000..60db654
--- /dev/null
+++ b/kittenml/kittentts2/model.py
@@ -0,0 +1,549 @@
+"""KittenTTS 2: a speech language model with in-context voice cloning.
+
+Unlike the ONNX KittenTTS models, which map phonemes to a waveform directly,
+KittenTTS 2 is an autoregressive language model over a shared text/audio
+vocabulary. It reads the text to speak and writes S3 codec tokens, which a
+separate vocoder turns into audio. A voice is supplied two ways at once: a
+speaker embedding through the model's own projection head, and the reference clip
+itself as codec tokens in the prompt.
+
+ from kittenml import KittenTTS
+
+ m = KittenTTS("/path/to/kitten-tts-2")
+ audio = m.generate("Hello there.", voice="Bruno")
+ audio = m.generate("Hello there.", reference="my_voice.wav")
+"""
+
+import contextlib
+import json
+import pathlib
+
+import numpy as np
+import torch
+
+from . import text as text_utils
+from .logits import build_logits_processors
+from .prompt import build_generation_prompt, build_reference_prefix
+from .speaker import (SPEAKER_EMBEDDING_DIM, WHISPER_MODEL, ReferenceTranscriber,
+ SpeakerEncoder, attach_speaker_head)
+from .tokens import TokenMap
+from .vocoder import S3Codec, resolve_reference_path
+
+# The codec runs at 25 Hz, so this is the conversion between a token budget and
+# seconds of audio.
+TOKENS_PER_SECOND = 25
+# Measured delivery rate for this checkpoint. Used to size a per-chunk token budget
+# from the chunk's length, which caps a runaway without truncating honest speech.
+CHARS_PER_SECOND = 20.0
+CHUNK_BUDGET_SLACK = 1.8
+MIN_CHUNK_BUDGET = 200
+
+# Knobs behind the `advanced=` argument. Everything here has a working default and
+# most callers never touch it; they are exposed because the values that steer
+# runaway generations and chunking are worth being able to tune per request.
+# `None` means "use whatever the model repository configured".
+ADVANCED_OPTIONS = {
+ # Penalty applied to tokens already seen. Raising it suppresses loops harder,
+ # at the cost of clipping legitimately repeated sounds.
+ "repetition_penalty": 1.1,
+ # Limit that penalty to the last N generated tokens. None scans everything,
+ # which lets a long reference clip suppress valid target audio.
+ "repetition_window": None,
+ # Escalating penalty once one codec token repeats `grace` times in a row —
+ # the main guard against the model sticking on silence or a held phoneme.
+ "token_run_penalty": 1.3,
+ "token_run_grace": 10,
+ # Chunking. Shorter chunks are steadier but more seams; see text.py.
+ "chunk_chars": None,
+ "chunk_min_chars": None,
+ "chunk_gap_s": text_utils.CHUNK_GAP_S,
+ # Emotion conditioning. None auto-enables it whenever the text carries an
+ # expression tag; True or False force it, to A/B the effect.
+ "use_emotion": None,
+ # Seed the sampler for a reproducible generation.
+ "seed": None,
+}
+
+
+def _quiet_unexpected_keys():
+ """Quieten transformers' loading chatter for one from_pretrained call."""
+ import logging
+
+ # ERROR rather than silence, and only for this one call: a genuine failure
+ # still raises, and anything the caller loads later logs normally again. Covers
+ # the unexpected-key report and the tensor-parallel notes, neither of which
+ # says anything useful here.
+ transformers_logger = logging.getLogger("transformers")
+ previous = transformers_logger.level
+ transformers_logger.setLevel(logging.ERROR)
+ try:
+ yield
+ finally:
+ transformers_logger.setLevel(previous)
+
+
+class KittenTTS2:
+ """A loaded KittenTTS 2 model.
+
+ Instantiated by `kittenml.KittenTTS` when a repository's config declares
+ `"type": "KITTEN2"`; construct it directly only if you want to bypass that
+ dispatch.
+ """
+
+ def __init__(self, repo_dir, config, device=None, cache_dir=None, hf_token=None,
+ decoder=None, weights=None):
+ self.repo_dir = pathlib.Path(repo_dir)
+ self.config = config
+ self.cache_dir = cache_dir
+
+ if device is None:
+ device = "cuda" if torch.cuda.is_available() else "cpu"
+ self.device = device
+
+ self.token_map = TokenMap.from_config(config)
+ generation = config.get("generation", {})
+ self.decode_presets = config.get("decode_presets", {})
+ self.default_preset = config.get("default_preset", "stable")
+ self.emotion_control = generation.get("emotion_control")
+ self.repetition_window = generation.get("repetition_window")
+ self.use_reference_prompt = generation.get("use_reference_prompt", True)
+ self.chunk_chars = generation.get("chunk_chars", text_utils.CHUNK_CHARS)
+ self.chunk_min_chars = generation.get("chunk_min_chars", text_utils.CHUNK_MIN_CHARS)
+
+ self.weights = weights or config.get("default_weights", "packed")
+ self._load_language_model()
+ self.decoders = config.get("decoders", {})
+ self.decoder = decoder or config.get("default_decoder", "default")
+ self.codec = S3Codec(device=self.device, cache_dir=cache_dir,
+ student_weights=self._decoder_weights(self.decoder))
+ self.speaker_encoder = SpeakerEncoder(
+ self.repo_dir / config.get("speaker_embedding", "speaker/model.safetensors"),
+ device=self.device)
+ self.transcriber = ReferenceTranscriber(
+ device=self.device, cache_dir=cache_dir,
+ model_name=config.get("transcriber", WHISPER_MODEL))
+
+ self.voices = self._load_voices()
+ self._reference_cache = {}
+
+ @property
+ def sample_rate(self):
+ return self.codec.sample_rate
+
+ def _decoder_weights(self, name):
+ """Path to a named decoder's weights, or None for the built-in flow."""
+ if name == "default":
+ return None
+ if name not in self.decoders:
+ raise ValueError(f"Unknown decoder {name!r}. "
+ f"Choose from: {self.available_decoders}")
+ return self.repo_dir / self.decoders[name]
+
+ @property
+ def available_decoders(self):
+ """Decoder names accepted by the `decoder` argument."""
+ return ["default", *self.decoders]
+
+ @property
+ def advanced_options(self):
+ """The `advanced=` knobs and the values this model would use for them."""
+ return self._resolve_advanced(None)
+
+ @property
+ def available_voices(self):
+ """Names accepted by the `voice` argument."""
+ return list(self.voices)
+
+ # ── loading ───────────────────────────────────────────────────────────────
+ def _load_language_model(self):
+ from transformers import AutoTokenizer
+
+ lm_dir = self.repo_dir / self.config.get("lm_dir", "lm")
+ if not lm_dir.is_dir():
+ raise FileNotFoundError(f"language model directory not found: {lm_dir}")
+
+ self.dtype = torch.bfloat16 if self.config.get("dtype", "bf16") == "bf16" else torch.float32
+ self.tokenizer = AutoTokenizer.from_pretrained(str(lm_dir))
+ # The weights on disk are already the folded ternary codeword — every weight
+ # group is exactly {-gamma, 0, +gamma}, not a latent full-precision tensor.
+ # Re-quantizing them would shrink each nonzero weight by its group's sparsity
+ # fraction, so this loads as an ordinary model on purpose.
+ # The checkpoint carries spk_proj.* alongside the LM weights, which the
+ # architecture knows nothing about; attach_speaker_head installs them below.
+ state = self._load_lm_weights(lm_dir)
+ with _quiet_unexpected_keys():
+ model = self._build_lm(lm_dir, state)
+ model = model.to(self.device)
+ # `state` already holds spk_proj, so pass it rather than re-reading the file.
+ attach_speaker_head(model, str(lm_dir), self.device, self.dtype,
+ spk_dim=self.config.get("speaker_embedding_dim",
+ SPEAKER_EMBEDDING_DIM),
+ state=state)
+ del state
+ model.eval()
+ self.model = model
+
+ def _build_lm(self, lm_dir, state):
+ """Instantiate the architecture and install `state` into it.
+
+ Built from the config rather than via from_pretrained, because
+ from_pretrained insists on finding a weights file on disk even when handed a
+ state dict — and with the packed weights there is no such file.
+
+ Not built on the meta device, tempting as that is to skip initialising 1.7B
+ values that are about to be overwritten: the rotary embedding's inv_freq is a
+ non-persistent buffer computed in __init__, so it is absent from the state
+ dict and would stay meta, which only surfaces later as "cannot copy out of
+ meta tensor" when the model moves to the GPU.
+ """
+ from transformers import AutoConfig, AutoModelForCausalLM
+
+ # transformers moved this between 4.x and 5.x, and it is only an
+ # optimisation, so a version that has neither just pays the init cost.
+ try:
+ from transformers.initialization import no_init_weights
+ except ImportError:
+ try:
+ from transformers.modeling_utils import no_init_weights
+ except ImportError:
+ no_init_weights = contextlib.nullcontext
+
+ lm_config = AutoConfig.from_pretrained(str(lm_dir))
+ for attention in ("flash_attention_2", "sdpa"):
+ try:
+ # Every parameter is replaced from the checkpoint a few lines down, so
+ # randomly initialising 1.7B of them first is pure cost — about a
+ # minute of it.
+ with no_init_weights():
+ model = AutoModelForCausalLM.from_config(
+ lm_config, dtype=self.dtype, attn_implementation=attention)
+ break
+ except Exception:
+ if attention == "sdpa":
+ raise
+ missing, _ = model.load_state_dict(state, strict=False, assign=True)
+ # lm_head is tied to the token embedding here, so it is legitimately absent
+ # from the file. Anything else missing means the checkpoint is incomplete and
+ # would otherwise run on random weights.
+ model.tie_weights()
+ unfilled = [n for n in missing if n != "lm_head.weight"]
+ if unfilled:
+ raise ValueError(f"weights missing from the checkpoint: {unfilled[:5]}")
+ return model
+
+ def _weights_path(self, name):
+ """Where a named weight variant lives, or None to read the plain files."""
+ if name == "full":
+ return None
+ key = {"packed": "lm_packed", "emb4": "lm_emb4"}.get(name)
+ if key is None:
+ raise ValueError(f"Unknown weights {name!r}. "
+ f"Choose from: {self.available_weights}")
+ declared = self.config.get(key)
+ if not declared:
+ raise ValueError(f"this repository declares no {name!r} weights")
+ return self.repo_dir / declared
+
+ @property
+ def available_weights(self):
+ """Weight variants this repository offers."""
+ names = ["full"]
+ for name, key in (("packed", "lm_packed"), ("emb4", "lm_emb4")):
+ if self.config.get(key):
+ names.append(name)
+ return names
+
+ def _load_lm_weights(self, lm_dir):
+ """The language model's weights, in whichever packing was selected.
+
+ "packed" is a 1.58-bit packing that is exactly equivalent to
+ model.safetensors at about a third of the size, and is the default.
+ "emb4" is smaller again but quantises the embedding, which is lossy —
+ see tl2_emb4.py. "full" reads the plain bf16 files.
+ """
+ from safetensors import safe_open
+ from safetensors.torch import load_file
+
+ path = self._weights_path(self.weights)
+ if path is not None:
+ if not path.is_file():
+ raise FileNotFoundError(f"{self.weights!r} weights not found: {path}")
+ if self.weights == "emb4":
+ from .tl2_emb4 import load_state_dict
+ return load_state_dict(path)
+ with safe_open(str(path), framework="pt") as handle:
+ metadata = handle.metadata() or {}
+ tensors = {k: handle.get_tensor(k) for k in handle.keys()}
+ from .ternary import unpack_state_dict
+ return unpack_state_dict(tensors, metadata)
+
+ state = {}
+ for shard in sorted(pathlib.Path(lm_dir).glob("model*.safetensors")):
+ if "-" in shard.stem: # a packed variant, not a plain shard
+ continue
+ state.update(load_file(str(shard)))
+ if not state:
+ raise FileNotFoundError(f"no plain model weights in {lm_dir}")
+ return state
+
+ def _load_voices(self):
+ voices_path = self.repo_dir / self.config.get("voices", "voices/voices.json")
+ if not voices_path.is_file():
+ return {}
+ with open(voices_path) as f:
+ entries = json.load(f)
+ root = voices_path.parent
+ return {name: {**spec,
+ "reference": str(root / spec["reference"]),
+ "artifacts": str(root / spec["artifacts"])}
+ for name, spec in entries.items()}
+
+ # ── reference artifacts ───────────────────────────────────────────────────
+ def _voice_reference(self, voice):
+ """Prompt prefix, speaker embedding and vocoder conditioning for a built-in voice.
+
+ The embedding and the reference's codec tokens are precomputed in the
+ repository, so a built-in voice never loads the embedding model at all.
+ """
+ if voice not in self.voices:
+ raise ValueError(
+ f"Voice {voice!r} not available. Choose from: {self.available_voices}")
+ if ("voice", voice) not in self._reference_cache:
+ spec = self.voices[voice]
+ artifacts = np.load(spec["artifacts"])
+ self._reference_cache[("voice", voice)] = self._build_reference(
+ embedding=artifacts["embedding"],
+ reference_tokens=artifacts["reference_tokens"].tolist(),
+ transcript=spec["transcript"],
+ reference_wav=spec["reference"])
+ return self._reference_cache[("voice", voice)]
+
+ def _clone_reference(self, reference_wav, reference_text=None):
+ """The same artifacts, derived on the fly from an arbitrary clip."""
+ reference_wav = resolve_reference_path(reference_wav)
+ key = ("clone", reference_wav, reference_text)
+ if key not in self._reference_cache:
+ transcript = reference_text
+ if not (transcript and transcript.strip()):
+ # The transcript is part of the prompt, and a caller should not have
+ # to type it out; transcribe rather than refuse.
+ transcript = self.transcriber(reference_wav)
+ if not (transcript and transcript.strip()):
+ raise ValueError(
+ f"no speech found in the reference clip: {reference_wav}")
+ self._reference_cache[key] = self._build_reference(
+ embedding=self.speaker_encoder(reference_wav),
+ reference_tokens=self.codec.encode_reference(reference_wav),
+ transcript=transcript,
+ reference_wav=reference_wav)
+ return self._reference_cache[key]
+
+ def _build_reference(self, embedding, reference_tokens, transcript, reference_wav):
+ transcript_ids = self.tokenizer.encode(transcript.strip(), add_special_tokens=False)
+ return {
+ "prefix": build_reference_prefix(self.token_map, transcript_ids, reference_tokens),
+ "embedding": torch.tensor(np.asarray(embedding, np.float32),
+ device=self.device, dtype=self.dtype).unsqueeze(0),
+ "conditioning": self.codec.reference_conditioning(reference_wav),
+ "transcript": transcript,
+ }
+
+ # ── generation ────────────────────────────────────────────────────────────
+ def _resolve_advanced(self, advanced):
+ """Merge caller overrides over the defaults, rejecting unknown keys."""
+ resolved = dict(ADVANCED_OPTIONS)
+ for key, value in (advanced or {}).items():
+ if key not in ADVANCED_OPTIONS:
+ raise ValueError(f"unknown advanced option {key!r}. "
+ f"Valid options: {sorted(ADVANCED_OPTIONS)}")
+ if value is not None:
+ resolved[key] = value
+ # Fall back to the repository's configuration where nothing was given.
+ if resolved["repetition_window"] is None:
+ resolved["repetition_window"] = self.repetition_window
+ if resolved["chunk_chars"] is None:
+ resolved["chunk_chars"] = self.chunk_chars
+ if resolved["chunk_min_chars"] is None:
+ resolved["chunk_min_chars"] = self.chunk_min_chars
+ return resolved
+
+ def _resolve_preset(self, preset, overrides):
+ if preset not in self.decode_presets:
+ raise ValueError(f"Unknown preset {preset!r}. "
+ f"Choose from: {list(self.decode_presets)}")
+ settings = dict(self.decode_presets[preset])
+ settings.update({k: v for k, v in overrides.items() if v is not None})
+ return settings
+
+ def _generate_tokens(self, reference, chunk, settings, max_new_tokens,
+ use_reference_prompt, emotion_ids, advanced):
+ """Run the LM for one chunk and return its audio codec ids (0-based)."""
+ prompt = build_generation_prompt(
+ self.token_map,
+ self.tokenizer.encode(chunk, add_special_tokens=False),
+ reference_prefix=reference["prefix"] if use_reference_prompt else None,
+ emotion_ids=emotion_ids)
+
+ processors = build_logits_processors(
+ self.token_map,
+ temperature=settings["temperature"], top_k=settings["top_k"],
+ top_p=settings["top_p"], min_p=settings.get("min_p", 0.0),
+ repetition_penalty=advanced["repetition_penalty"],
+ repetition_window=advanced["repetition_window"],
+ token_run_penalty=advanced["token_run_penalty"],
+ token_run_grace=advanced["token_run_grace"],
+ prompt_length=len(prompt))
+
+ input_ids = torch.tensor([prompt], dtype=torch.long, device=self.device)
+ # Sampling is done entirely by `processors`; generate() gets neutral kwargs so
+ # it does not add a second, unordered copy of the same warpers.
+ self.model._pending_speaker_embedding = reference["embedding"]
+ try:
+ with torch.no_grad():
+ output = self.model.generate(
+ input_ids, max_new_tokens=int(max_new_tokens), do_sample=True,
+ temperature=1.0, top_p=1.0, top_k=0, repetition_penalty=1.0,
+ logits_processor=processors,
+ eos_token_id=[self.token_map.speech_end_id, self.token_map.stop_id],
+ pad_token_id=getattr(self.tokenizer, "pad_token_id", None) or 0)
+ finally:
+ self.model._pending_speaker_embedding = None
+
+ low, high = self.token_map.audio_id_base, self.token_map.audio_id_end
+ generated = output[0].tolist()[len(prompt):]
+ return [t - low for t in generated if low <= t < high]
+
+ def _chunk_budget(self, chunk, max_new_tokens, single_chunk):
+ """Cap a chunk's generation at what its text plausibly needs.
+
+ A single chunk gets the full budget; within a longer piece, sizing the
+ budget from the chunk's own length stops one runaway chunk from consuming
+ the whole allowance.
+ """
+ if single_chunk:
+ return int(max_new_tokens)
+ expected = len(chunk) / CHARS_PER_SECOND * TOKENS_PER_SECOND * CHUNK_BUDGET_SLACK
+ return max(MIN_CHUNK_BUDGET, min(int(max_new_tokens), int(expected)))
+
+ def _synthesize(self, reference, target_text, preset, max_new_tokens, normalize,
+ use_reference_prompt, overrides, advanced):
+ spoken = text_utils.normalize_text(target_text, normalize=normalize)
+ if not spoken.strip():
+ raise ValueError("no text to speak")
+ chunks = text_utils.split_for_synthesis(spoken, max_chars=advanced["chunk_chars"],
+ min_chars=advanced["chunk_min_chars"])
+ settings = self._resolve_preset(preset, overrides)
+ if advanced["seed"] is not None:
+ torch.manual_seed(int(advanced["seed"]))
+
+ use_emotion = advanced["use_emotion"]
+ if use_emotion is None:
+ use_emotion = text_utils.has_expression_tag(target_text)
+ emotion_ids = None
+ if self.emotion_control and use_emotion:
+ emotion_ids = self.tokenizer.encode(self.emotion_control, add_special_tokens=False)
+
+ # In-context cloning improves speaker fidelity on long text but destabilises
+ # short prompts, where a long reference is extra context the model can loop
+ # back into. The checkpoint's config decides which side of that trade it wants.
+ if use_reference_prompt is None:
+ use_reference_prompt = self.use_reference_prompt
+
+ for chunk in chunks:
+ budget = self._chunk_budget(chunk, max_new_tokens, single_chunk=len(chunks) == 1)
+ audio_ids = self._generate_tokens(reference, chunk, settings, budget,
+ use_reference_prompt, emotion_ids, advanced)
+ wav = self.codec.decode(reference["conditioning"], audio_ids)
+ if wav is not None:
+ yield wav
+
+ # ── public API ────────────────────────────────────────────────────────────
+ def _speaker(self, voice, reference, reference_text):
+ """Resolve the speaker: a built-in voice, or a reference recording."""
+ if reference is not None and voice is not None:
+ raise ValueError("give either voice= or reference=, not both")
+ if reference is not None:
+ return self._clone_reference(reference, reference_text)
+ if reference_text is not None:
+ raise ValueError("reference_text= only applies together with reference=")
+ voice = voice or self.config.get("default_voice")
+ if voice is None:
+ raise ValueError("no voice given and the model declares no default voice")
+ return self._voice_reference(voice)
+
+ def generate(self, text, voice=None, reference=None, reference_text=None,
+ preset=None, max_new_tokens=1000, normalize=True,
+ use_reference_prompt=None, temperature=None, top_k=None,
+ top_p=None, min_p=None, advanced=None):
+ """Synthesize `text` as a built-in voice, or as a cloned one.
+
+ The speaker comes from exactly one of `voice` or `reference`:
+
+ m.generate("Hello.", voice="Bruno") # a built-in voice
+ m.generate("Hello.", reference="my_voice.wav") # cloned from a recording
+
+ Args:
+ text: what to speak. Supports a leading `[emotion]` tag, inline
+ `<event>` tags and `(((emphasis)))` spans.
+ voice: a name from `available_voices`. Defaults to the repository's
+ own default voice when neither this nor `reference` is given.
+ reference: path to roughly 5-30 seconds of a single speaker, to clone.
+ reference_text: what that clip says. Transcribed with Whisper if omitted.
+ preset: a decoding preset name, e.g. "stable" or "expressive".
+ max_new_tokens: per-chunk token budget; 25 tokens is about one second.
+ normalize: expand written forms ("$12.50" -> "twelve dollars fifty cents").
+ use_reference_prompt: include the reference clip's own audio in the
+ prompt. Defaults to the checkpoint's own setting.
+ temperature, top_k, top_p, min_p: override individual preset values.
+ advanced: dict of rarely-needed knobs — repetition and run penalties,
+ chunking, emotion conditioning, and `seed` for a reproducible
+ generation. See `ADVANCED_OPTIONS` for the full set and defaults;
+ an unknown key raises ValueError.
+
+ Returns:
+ A float32 numpy waveform at `self.sample_rate`.
+ """
+ options = self._resolve_advanced(advanced)
+ wavs = list(self._synthesize(
+ self._speaker(voice, reference, reference_text), text,
+ preset or self.default_preset, max_new_tokens, normalize,
+ use_reference_prompt,
+ dict(temperature=temperature, top_k=top_k, top_p=top_p, min_p=min_p),
+ options))
+ return self._join(wavs, options["chunk_gap_s"])
+
+ def generate_stream(self, text, voice=None, reference=None, reference_text=None,
+ preset=None, max_new_tokens=1000, normalize=True,
+ use_reference_prompt=None, temperature=None, top_k=None,
+ top_p=None, min_p=None, advanced=None):
+ """`generate`, yielding each chunk's audio as it is produced.
+
+ Chunks are yielded untrimmed and unjoined — `generate` post-processes the
+ seams, which a streaming caller cannot do without waiting for the next
+ chunk. Text short enough to fit one chunk yields exactly once.
+ """
+ yield from self._synthesize(
+ self._speaker(voice, reference, reference_text), text,
+ preset or self.default_preset, max_new_tokens, normalize,
+ use_reference_prompt,
+ dict(temperature=temperature, top_k=top_k, top_p=top_p, min_p=min_p),
+ self._resolve_advanced(advanced))
+
+ def generate_to_file(self, text, output_path, **kwargs):
+ """Synthesize and write a wav. Returns the path written."""
+ import soundfile as sf
+ audio = self.generate(text, **kwargs)
+ sf.write(str(output_path), audio, self.sample_rate)
+ return str(output_path)
+
+ def normalize_text(self, text):
+ """The spoken form the model will actually hear for `text`."""
+ return text_utils.normalize_text(text)
+
+ def _join(self, wavs, gap_s=text_utils.CHUNK_GAP_S):
+ joined = text_utils.join_chunks(wavs, self.sample_rate, gap_s=gap_s)
+ if joined is None:
+ raise RuntimeError(
+ "the model produced no audio tokens — try different text or a different preset")
+ return joined
diff --git a/kittenml/kittentts2/prompt.py b/kittenml/kittentts2/prompt.py
new file mode 100644
index 0000000..09bdef9
--- /dev/null
+++ b/kittenml/kittentts2/prompt.py
@@ -0,0 +1,56 @@
+"""Prompt assembly for KittenTTS 2.
+
+A generation prompt has two parts. The reference prefix carries the voice being
+cloned — the reference transcript plus its audio as codec tokens — and the target
+segment carries the text to speak. The model then continues with audio tokens
+until it emits `<speech_end>`.
+"""
+
+
+def build_reference_prefix(token_map, reference_text_ids, reference_audio_tokens):
+ """Assemble the in-context reference portion of the prompt.
+
+ Checkpoints wrap the reference differently depending on how they were trained,
+ and prompting one with the other's layout measurably degrades cloning:
+
+ reference-supervised checkpoints (reference-role tokens present):
+ [START] <reference_text_start> text <reference_text_end>
+ <reference_speech_start> audio <reference_speech_end>
+
+ everything else, reusing the target segment's own wrappers:
+ [START] <text_start> text <speech_start> audio <speech_end>
+
+ The caller appends the target segment itself — see `build_generation_prompt`.
+ """
+ base = token_map.audio_id_base
+ audio_ids = [base + t for t in reference_audio_tokens]
+ if token_map.uses_reference_role_tokens:
+ return [token_map.start_id,
+ token_map.reference_text_start_id, *reference_text_ids,
+ token_map.reference_text_end_id,
+ token_map.reference_speech_start_id, *audio_ids,
+ token_map.reference_speech_end_id]
+ return [token_map.start_id,
+ token_map.text_start_id, *reference_text_ids,
+ token_map.speech_start_id, *audio_ids, token_map.speech_end_id]
+
+
+def build_generation_prompt(token_map, target_text_ids, reference_prefix=None,
+ emotion_ids=None):
+ """Assemble the full prompt for one chunk of target text.
+
+ `reference_prefix=None` drops the in-context reference entirely, leaving the
+ speaker embedding (through `spk_proj`) as the only identity signal. That
+ trades a little speaker similarity for stability on short text, where a long
+ reference is context the model can loop back into.
+
+ `emotion_ids` are the tokenized `{emo: 1}` control, spliced in immediately
+ before the target text as the checkpoint was trained to receive it.
+ """
+ head = list(reference_prefix) if reference_prefix else [token_map.start_id]
+ final_marker = [token_map.final_seg_id] if token_map.final_seg_id else []
+ return [*head,
+ *(emotion_ids or []),
+ token_map.text_start_id, *target_text_ids,
+ *final_marker,
+ token_map.speech_start_id]
diff --git a/kittenml/kittentts2/s3gen.py b/kittenml/kittentts2/s3gen.py
new file mode 100644
index 0000000..fbcb382
--- /dev/null
+++ b/kittenml/kittentts2/s3gen.py
@@ -0,0 +1,4230 @@
+"""s3gen — the audio codec KittenTTS 2 generates into and decodes out of.
+
+This is a trimmed, single-file copy of the S3 speech tokenizer and the s3gen
+flow-matching vocoder from ResembleAI's chatterbox (chatterbox-tts 0.1.7, Apache
+2.0), which in turn builds on Alibaba's CosyVoice and Matcha-TTS.
+
+It is vendored rather than installed because the `chatterbox-tts` package pins
+`torch==2.6`, `transformers==5.2` and `gradio`, which conflict with what the
+KittenTTS 2 language model needs. Only the classes S3Gen actually instantiates
+are kept: chatterbox's T3 text-to-token model, voice encoder and text tokenizer
+are gone, as are the unused entries of the architecture registries and the
+encoder/decoder variants this configuration never selects.
+
+Copyright:
+ 2024 Alibaba Inc (CosyVoice)
+ 2023-11-28 Xingchen Song
+ Matcha-TTS authors
+ Resemble AI
+Licensed under the Apache License, Version 2.0.
+"""
+
+import torch
+import logging
+from librosa.filters import mel as librosa_mel_fn
+import numpy as np
+import torch.nn as nn
+from typing import List, Tuple
+import librosa
+import torch.nn.functional as F
+from s3tokenizer.utils import padding
+from s3tokenizer.model_v2 import (
+ S3TokenizerV2,
+ ModelConfig,
+)
+import math
+from typing import Tuple, Union
+from typing import Tuple
+from torch import nn
+from typing import Optional, Tuple
+from torch.nn import functional as F
+from typing import Any, Dict, Optional
+from diffusers.models.attention import (
+ GEGLU,
+ GELU,
+ AdaLayerNorm,
+ AdaLayerNormZero,
+ ApproximateGELU,
+)
+from diffusers.models.attention_processor import Attention
+from typing import Optional
+from diffusers.models.activations import get_activation
+from einops import pack, rearrange, repeat
+from abc import ABC
+from torch.nn.utils.parametrizations import weight_norm
+from typing import Dict, Optional, List
+from scipy.signal import get_window
+from torch.nn import Conv1d
+from torch.nn import ConvTranspose1d
+from torch.nn.utils import remove_weight_norm
+from torch.distributions.uniform import Uniform
+from torch import nn, sin, pow
+from torch.nn import Parameter
+from collections import OrderedDict
+import torch.utils.checkpoint as cp
+import torchaudio.compliance.kaldi as Kaldi
+import random
+from typing import Dict, Optional
+from omegaconf import DictConfig
+import torchaudio as ta
+
+
+# ── from utils.py ──────────────────────────────────────────────────────
+
+
+class AttrDict(dict):
+ def __init__(self, *args, **kwargs):
+ super(AttrDict, self).__init__(*args, **kwargs)
+ self.__dict__ = self
+
+
+# ── from s3gen/const.py ────────────────────────────────────────────────
+
+
+S3GEN_SR = 24000
+
+S3GEN_SIL = 4299
+
+
+# ── from s3gen/configs.py ──────────────────────────────────────────────
+
+
+CFM_PARAMS = AttrDict({
+ "sigma_min": 1e-06,
+ "solver": "euler",
+ "t_scheduler": "cosine",
+ "training_cfg_rate": 0.2,
+ "inference_cfg_rate": 0.7,
+ "reg_loss_type": "l1"
+})
+
+
+# ── from s3gen/utils/mask.py ───────────────────────────────────────────
+
+
+'''
+def subsequent_mask(
+ size: int,
+ device: torch.device = torch.device("cpu"),
+) -> torch.Tensor:
+ """Create mask for subsequent steps (size, size).
+
+ This mask is used only in decoder which works in an auto-regressive mode.
+ This means the current step could only do attention with its left steps.
+
+ In encoder, fully attention is used when streaming is not necessary and
+ the sequence is not long. In this case, no attention mask is needed.
+
+ When streaming is need, chunk-based attention is used in encoder. See
+ subsequent_chunk_mask for the chunk-based attention mask.
+
+ Args:
+ size (int): size of mask
+ str device (str): "cpu" or "cuda" or torch.Tensor.device
+ dtype (torch.device): result dtype
+
+ Returns:
+ torch.Tensor: mask
+
+ Examples:
+ >>> subsequent_mask(3)
+ [[1, 0, 0],
+ [1, 1, 0],
+ [1, 1, 1]]
+ """
+ ret = torch.ones(size, size, device=device, dtype=torch.bool)
+ return torch.tril(ret)
+'''
+
+def subsequent_chunk_mask(
+ size: int,
+ chunk_size: int,
+ num_left_chunks: int = -1,
+ device: torch.device = torch.device("cpu"),
+) -> torch.Tensor:
+ """Create mask for subsequent steps (size, size) with chunk size,
+ this is for streaming encoder
+
+ Args:
+ size (int): size of mask
+ chunk_size (int): size of chunk
+ num_left_chunks (int): number of left chunks
+ <0: use full chunk
+ >=0: use num_left_chunks
+ device (torch.device): "cpu" or "cuda" or torch.Tensor.device
+
+ Returns:
+ torch.Tensor: mask
+
+ Examples:
+ >>> subsequent_chunk_mask(4, 2)
+ [[1, 1, 0, 0],
+ [1, 1, 0, 0],
+ [1, 1, 1, 1],
+ [1, 1, 1, 1]]
+ """
+ # NOTE this modified implementation meets onnx export requirements, but it doesn't support num_left_chunks
+ # actually this is not needed after we have inference cache implemented, will remove it later
+ pos_idx = torch.arange(size, device=device)
+ block_value = (torch.div(pos_idx, chunk_size, rounding_mode='trunc') + 1) * chunk_size
+ ret = pos_idx.unsqueeze(0) < block_value.unsqueeze(1)
+ return ret
+
+def add_optional_chunk_mask(xs: torch.Tensor,
+ masks: torch.Tensor,
+ use_dynamic_chunk: bool,
+ use_dynamic_left_chunk: bool,
+ decoding_chunk_size: int,
+ static_chunk_size: int,
+ num_decoding_left_chunks: int,
+ enable_full_context: bool = True):
+ """ Apply optional mask for encoder.
+
+ Args:
+ xs (torch.Tensor): padded input, (B, L, D), L for max length
+ mask (torch.Tensor): mask for xs, (B, 1, L)
+ use_dynamic_chunk (bool): whether to use dynamic chunk or not
+ use_dynamic_left_chunk (bool): whether to use dynamic left chunk for
+ training.
+ decoding_chunk_size (int): decoding chunk size for dynamic chunk, it's
+ 0: default for training, use random dynamic chunk.
+ <0: for decoding, use full chunk.
+ >0: for decoding, use fixed chunk size as set.
+ static_chunk_size (int): chunk size for static chunk training/decoding
+ if it's greater than 0, if use_dynamic_chunk is true,
+ this parameter will be ignored
+ num_decoding_left_chunks: number of left chunks, this is for decoding,
+ the chunk size is decoding_chunk_size.
+ >=0: use num_decoding_left_chunks
+ <0: use all left chunks
+ enable_full_context (bool):
+ True: chunk size is either [1, 25] or full context(max_len)
+ False: chunk size ~ U[1, 25]
+
+ Returns:
+ torch.Tensor: chunk mask of the input xs.
+ """
+ # Whether to use chunk mask or not
+ if use_dynamic_chunk:
+ max_len = xs.size(1)
+ if decoding_chunk_size < 0:
+ chunk_size = max_len
+ num_left_chunks = -1
+ elif decoding_chunk_size > 0:
+ chunk_size = decoding_chunk_size
+ num_left_chunks = num_decoding_left_chunks
+ else:
+ # chunk size is either [1, 25] or full context(max_len).
+ # Since we use 4 times subsampling and allow up to 1s(100 frames)
+ # delay, the maximum frame is 100 / 4 = 25.
+ chunk_size = torch.randint(1, max_len, (1, )).item()
+ num_left_chunks = -1
+ if chunk_size > max_len // 2 and enable_full_context:
+ chunk_size = max_len
+ else:
+ chunk_size = chunk_size % 25 + 1
+ if use_dynamic_left_chunk:
+ max_left_chunks = (max_len - 1) // chunk_size
+ num_left_chunks = torch.randint(0, max_left_chunks,
+ (1, )).item()
+ chunk_masks = subsequent_chunk_mask(xs.size(1), chunk_size,
+ num_left_chunks,
+ xs.device) # (L, L)
+ chunk_masks = chunk_masks.unsqueeze(0) # (1, L, L)
+ chunk_masks = masks & chunk_masks # (B, L, L)
+ elif static_chunk_size > 0:
+ num_left_chunks = num_decoding_left_chunks
+ chunk_masks = subsequent_chunk_mask(xs.size(1), static_chunk_size,
+ num_left_chunks,
+ xs.device) # (L, L)
+ chunk_masks = chunk_masks.unsqueeze(0) # (1, L, L)
+ chunk_masks = masks & chunk_masks # (B, L, L)
+ else:
+ chunk_masks = masks
+ assert chunk_masks.dtype == torch.bool
+ if (chunk_masks.sum(dim=-1) == 0).sum().item() != 0:
+ logger.debug('get chunk_masks all false at some timestep, force set to true, make sure they are masked in futuer computation!')
+ chunk_masks[chunk_masks.sum(dim=-1)==0] = True
+ return chunk_masks
+
+def make_pad_mask(lengths: torch.Tensor, max_len: int = 0) -> torch.Tensor:
+ """Make mask tensor containing indices of padded part.
+
+ See description of make_non_pad_mask.
+
+ Args:
+ lengths (torch.Tensor): Batch of lengths (B,).
+ Returns:
+ torch.Tensor: Mask tensor containing indices of padded part.
+
+ Examples:
+ >>> lengths = [5, 3, 2]
+ >>> make_pad_mask(lengths)
+ masks = [[0, 0, 0, 0 ,0],
+ [0, 0, 0, 1, 1],
+ [0, 0, 1, 1, 1]]
+ """
+ lengths = lengths.long()
+ batch_size = lengths.size(0)
+ max_len = max_len if max_len > 0 else lengths.max().item()
+ seq_range = torch.arange(0,
+ max_len,
+ dtype=torch.int64,
+ device=lengths.device)
+ seq_range_expand = seq_range.unsqueeze(0).expand(batch_size, max_len)
+ seq_length_expand = lengths.unsqueeze(-1)
+ mask = seq_range_expand >= seq_length_expand
+ return mask
+
+
+# ── from s3gen/utils/mel.py ────────────────────────────────────────────
+
+
+"""mel-spectrogram extraction in Matcha-TTS"""
+
+logger = logging.getLogger(__name__)
+
+# NOTE: they decalred these global vars
+mel_basis = {}
+
+hann_window = {}
+
+def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
+ return torch.log(torch.clamp(x, min=clip_val) * C)
+
+def spectral_normalize_torch(magnitudes):
+ output = dynamic_range_compression_torch(magnitudes)
+ return output
+
+"""
+feat_extractor: !name:matcha.utils.audio.mel_spectrogram
+ n_fft: 1920
+ num_mels: 80
+ sampling_rate: 24000
+ hop_size: 480
+ win_size: 1920
+ fmin: 0
+ fmax: 8000
+ center: False
+
+"""
+
+def mel_spectrogram(y, n_fft=1920, num_mels=80, sampling_rate=24000, hop_size=480, win_size=1920,
+ fmin=0, fmax=8000, center=False):
+ """Copied from https://github.com/shivammehta25/Matcha-TTS/blob/main/matcha/utils/audio.py
+ Set default values according to Cosyvoice's config.
+ """
+
+ if isinstance(y, np.ndarray):
+ y = torch.tensor(y).float()
+
+ if len(y.shape) == 1:
+ y = y[None, ]
+
+ # Debug: Check for audio clipping (values outside [-1.0, 1.0] range)
+ min_val = torch.min(y)
+ max_val = torch.max(y)
+ if min_val < -1.0 or max_val > 1.0:
+ logger.warning(f"Audio values outside normalized range: min={min_val.item():.4f}, max={max_val.item():.4f}")
+
+ global mel_basis, hann_window # pylint: disable=global-statement,global-variable-not-assigned
+ if f"{str(fmax)}_{str(y.device)}" not in mel_basis:
+ mel = librosa_mel_fn(sr=sampling_rate, n_fft=n_fft, n_mels=num_mels, fmin=fmin, fmax=fmax)
+ mel_basis[str(fmax) + "_" + str(y.device)] = torch.from_numpy(mel).float().to(y.device)
+ hann_window[str(y.device)] = torch.hann_window(win_size).to(y.device)
+
+ y = torch.nn.functional.pad(
+ y.unsqueeze(1), (int((n_fft - hop_size) / 2), int((n_fft - hop_size) / 2)), mode="reflect"
+ )
+ y = y.squeeze(1)
+
+ spec = torch.view_as_real(
+ torch.stft(
+ y,
+ n_fft,
+ hop_length=hop_size,
+ win_length=win_size,
+ window=hann_window[str(y.device)],
+ center=center,
+ pad_mode="reflect",
+ normalized=False,
+ onesided=True,
+ return_complex=True,
+ )
+ )
+
+ spec = torch.sqrt(spec.pow(2).sum(-1) + (1e-9))
+
+ spec = torch.matmul(mel_basis[str(fmax) + "_" + str(y.device)], spec)
+ spec = spectral_normalize_torch(spec)
+
+ return spec
+
+
+# ── from s3gen/utils/intmeanflow.py ────────────────────────────────────
+
+
+def get_intmeanflow_time_mixer(dims):
+ """"
+ Diagonal init as described in 3.3 https://arxiv.org/pdf/2510.07979
+ """
+ layer = nn.Linear(dims * 2, dims, bias=False)
+
+ with torch.no_grad():
+ target_weight = torch.zeros(dims, 2 * dims)
+ target_weight[:, 0:dims] = torch.eye(dims)
+ layer.weight.data = target_weight
+
+ return layer
+
+if __name__ == '__main__':
+
+ D_example = 6
+
+ W_layer = get_intmeanflow_time_mixer(D_example)
+
+ print(f"Layer weight (AFTER init):\n{W_layer.weight.data}\n")
+
+ e_t = torch.tensor([0., 1., 2., 3., 4., 5.])
+ e_r = torch.tensor([6., 7., 8., 9., 10., 11.])
+ e_concat = torch.cat([e_t, e_r]).unsqueeze(0) # Shape (1, 12)
+
+ output = W_layer(e_concat)
+
+ print(f"Test Input e_t: \n{e_t}")
+ print(f"Test Input e_r: \n{e_r}")
+ print(f"Test Input concat: \n{e_concat}")
+
+ print(f"Forward Pass Output: \n{output.squeeze(0)}")
+
+
+# ── from s3tokenizer/s3tokenizer.py ────────────────────────────────────
+
+
+# Sampling rate of the inputs to S3TokenizerV2
+S3_SR = 16_000
+
+S3_HOP = 160
+
+S3_TOKEN_HOP = 640
+
+S3_TOKEN_RATE = 25
+
+SPEECH_VOCAB_SIZE = 6561
+
+class S3Tokenizer(S3TokenizerV2):
+ """
+ s3tokenizer.S3TokenizerV2 with the following changes:
+ - a more integrated `forward`
+ - compute `log_mel_spectrogram` using `_mel_filters` and `window` in `register_buffers`
+ """
+
+ ignore_state_dict_missing = ("_mel_filters", "window")
+
+ def __init__(
+ self,
+ name: str="speech_tokenizer_v2_25hz",
+ config: ModelConfig = ModelConfig()
+ ):
+ super().__init__(name)
+
+ self.n_fft = 400
+ _mel_filters = librosa.filters.mel(
+ sr=S3_SR,
+ n_fft=self.n_fft,
+ n_mels=config.n_mels
+ )
+ self.register_buffer(
+ "_mel_filters",
+ torch.FloatTensor(_mel_filters),
+ )
+
+ self.register_buffer(
+ "window",
+ torch.hann_window(self.n_fft),
+ )
+
+ def pad(self, wavs, sr) -> List[torch.Tensor]:
+ """
+ Given a list of wavs with the same `sample_rate`, pad them so that the length is multiple of 40ms (S3 runs at 25 token/sec).
+ """
+ processed_wavs = []
+ for wav in wavs:
+ if isinstance(wav, np.ndarray):
+ wav = torch.from_numpy(wav)
+ if wav.dim() == 1:
+ wav = wav.unsqueeze(0)
+
+ n_tokens = (wav.shape[1] / sr) * S3_TOKEN_RATE
+ n_tokens = np.ceil(n_tokens)
+ intended_wav_len = n_tokens * (sr / S3_TOKEN_RATE)
+ intended_wav_len = int(intended_wav_len)
+ wav = torch.nn.functional.pad(
+ wav,
+ (0, intended_wav_len - wav.shape[-1]),
+ mode="constant",
+ value=0
+ )
+ processed_wavs.append(wav)
+ return processed_wavs
+
+ def _prepare_audio(self, wavs):
+ """Prepare a list of audios for s3tokenizer processing."""
+ processed_wavs = []
+ for wav in wavs:
+ if isinstance(wav, np.ndarray):
+ wav = torch.from_numpy(wav)
+ if wav.dim() == 1:
+ wav = wav.unsqueeze(0)
+
+ processed_wavs.append(wav)
+ return processed_wavs
+
+ @torch.no_grad()
+ def forward(
+ self,
+ wavs: torch.Tensor,
+ accelerator: 'Accelerator'=None,
+ max_len: int=None,
+ ) -> Tuple[torch.Tensor, torch.LongTensor]:
+ """
+ NOTE: mel-spec has a hop size of 160 points (100 frame/sec).
+ FIXME: this class inherits `nn.Module` but doesn't accept `torch.Tensor` and handles a list of wavs one by one, which is unexpected.
+
+ Args
+ ----
+ - `wavs`: 16 kHz speech audio
+ - `max_len` max length to truncate the output sequence to (25 token/sec).
+ NOTE: please pad the waveform if longer sequence is needed.
+ """
+ processed_wavs = self._prepare_audio(wavs)
+ mels, mel_lens = [], []
+ for wav in processed_wavs:
+ wav = wav.to(self.device)
+ mel = self.log_mel_spectrogram(wav) # [B=1, F, T]
+ if max_len is not None:
+ mel = mel[..., :max_len * 4] # num_mel_frames = 4 * num_tokens
+ mels.append(mel.squeeze(0))
+
+ mels, mel_lens = padding(mels)
+ if accelerator is None:
+ tokenizer = self
+ else:
+ tokenizer = accelerator.unwrap_model(self)
+
+ speech_tokens, speech_token_lens = tokenizer.quantize(mels, mel_lens.to(self.device))
+ return (
+ speech_tokens.long().detach(),
+ speech_token_lens.long().detach(),
+ )
+
+ def log_mel_spectrogram(
+ self,
+ audio: torch.Tensor,
+ padding: int = 0,
+ ):
+ """
+ Compute the log-Mel spectrogram of
+
+ Parameters
+ ----------
+ audio: torch.Tensor, shape = (*)
+ The path to audio or either a NumPy array or Tensor containing the
+ audio waveform in 16 kHz
+
+ padding: int
+ Number of zero samples to pad to the right
+
+ Returns
+ -------
+ torch.Tensor, shape = (128, n_frames)
+ A Tensor that contains the Mel spectrogram
+ """
+ if not torch.is_tensor(audio):
+ audio = torch.from_numpy(audio)
+
+ audio = audio.to(self.device)
+ if padding > 0:
+ audio = F.pad(audio, (0, padding))
+ stft = torch.stft(
+ audio, self.n_fft, S3_HOP,
+ window=self.window.to(self.device),
+ return_complex=True
+ )
+ magnitudes = stft[..., :-1].abs()**2
+
+ mel_spec = self._mel_filters.to(self.device) @ magnitudes
+
+ log_spec = torch.clamp(mel_spec, min=1e-10).log10()
+ log_spec = torch.maximum(log_spec, log_spec.max() - 8.0)
+ log_spec = (log_spec + 4.0) / 4.0
+ return log_spec
+
+
+# ── from s3gen/transformer/embedding.py ────────────────────────────────
+
+
+# 2024 Alibaba Inc (Xiang Lyu)
+#
+# 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.
+# Modified from ESPnet(https://github.com/espnet/espnet)
+"""Positonal Encoding Module."""
+
+class EspnetRelPositionalEncoding(torch.nn.Module):
+ """Relative positional encoding module (new implementation).
+
+ Details can be found in https://github.com/espnet/espnet/pull/2816.
+
+ See : Appendix B in https://arxiv.org/abs/1901.02860
+
+ Args:
+ d_model (int): Embedding dimension.
+ dropout_rate (float): Dropout rate.
+ max_len (int): Maximum input length.
+
+ """
+
+ def __init__(self, d_model: int, dropout_rate: float, max_len: int = 5000):
+ """Construct an PositionalEncoding object."""
+ super(EspnetRelPositionalEncoding, self).__init__()
+ self.d_model = d_model
+ self.xscale = math.sqrt(self.d_model)
+ self.dropout = torch.nn.Dropout(p=dropout_rate)
+ self.pe = None
+ self.extend_pe(torch.tensor(0.0).expand(1, max_len))
+
+ def extend_pe(self, x: torch.Tensor):
+ """Reset the positional encodings."""
+ if self.pe is not None:
+ # self.pe contains both positive and negative parts
+ # the length of self.pe is 2 * input_len - 1
+ if self.pe.size(1) >= x.size(1) * 2 - 1:
+ if self.pe.dtype != x.dtype or self.pe.device != x.device:
+ self.pe = self.pe.to(dtype=x.dtype, device=x.device)
+ return
+ # Suppose `i` means to the position of query vecotr and `j` means the
+ # position of key vector. We use position relative positions when keys
+ # are to the left (i>j) and negative relative positions otherwise (i<j).
+ pe_positive = torch.zeros(x.size(1), self.d_model)
+ pe_negative = torch.zeros(x.size(1), self.d_model)
+ position = torch.arange(0, x.size(1), dtype=torch.float32).unsqueeze(1)
+ div_term = torch.exp(
+ torch.arange(0, self.d_model, 2, dtype=torch.float32)
+ * -(math.log(10000.0) / self.d_model)
+ )
+ pe_positive[:, 0::2] = torch.sin(position * div_term)
+ pe_positive[:, 1::2] = torch.cos(position * div_term)
+ pe_negative[:, 0::2] = torch.sin(-1 * position * div_term)
+ pe_negative[:, 1::2] = torch.cos(-1 * position * div_term)
+
+ # Reserve the order of positive indices and concat both positive and
+ # negative indices. This is used to support the shifting trick
+ # as in https://arxiv.org/abs/1901.02860
+ pe_positive = torch.flip(pe_positive, [0]).unsqueeze(0)
+ pe_negative = pe_negative[1:].unsqueeze(0)
+ pe = torch.cat([pe_positive, pe_negative], dim=1)
+ self.pe = pe.to(device=x.device, dtype=x.dtype)
+
+ def forward(self, x: torch.Tensor, offset: Union[int, torch.Tensor] = 0) \
+ -> Tuple[torch.Tensor, torch.Tensor]:
+ """Add positional encoding.
+
+ Args:
+ x (torch.Tensor): Input tensor (batch, time, `*`).
+
+ Returns:
+ torch.Tensor: Encoded tensor (batch, time, `*`).
+
+ """
+ self.extend_pe(x)
+ x = x * self.xscale
+ pos_emb = self.position_encoding(size=x.size(1), offset=offset)
+ return self.dropout(x), self.dropout(pos_emb)
+
+ def position_encoding(self,
+ offset: Union[int, torch.Tensor],
+ size: int) -> torch.Tensor:
+ """ For getting encoding in a streaming fashion
+
+ Attention!!!!!
+ we apply dropout only once at the whole utterance level in a none
+ streaming way, but will call this function several times with
+ increasing input size in a streaming scenario, so the dropout will
+ be applied several times.
+
+ Args:
+ offset (int or torch.tensor): start offset
+ size (int): required size of position encoding
+
+ Returns:
+ torch.Tensor: Corresponding encoding
+ """
+ pos_emb = self.pe[
+ :,
+ self.pe.size(1) // 2 - size + 1: self.pe.size(1) // 2 + size,
+ ]
+ return pos_emb
+
+
+# ── from s3gen/transformer/subsampling.py ──────────────────────────────
+
+
+# 2024 Alibaba Inc (Xiang Lyu)
+#
+# 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.
+# Modified from ESPnet(https://github.com/espnet/espnet)
+"""Subsampling layer definition."""
+
+class BaseSubsampling(torch.nn.Module):
+
+ def __init__(self):
+ super().__init__()
+ self.right_context = 0
+ self.subsampling_rate = 1
+
+ def position_encoding(self, offset: Union[int, torch.Tensor],
+ size: int) -> torch.Tensor:
+ return self.pos_enc.position_encoding(offset, size)
+
+class LinearNoSubsampling(BaseSubsampling):
+ """Linear transform the input without subsampling
+
+ Args:
+ idim (int): Input dimension.
+ odim (int): Output dimension.
+ dropout_rate (float): Dropout rate.
+
+ """
+
+ def __init__(self, idim: int, odim: int, dropout_rate: float,
+ pos_enc_class: torch.nn.Module):
+ """Construct an linear object."""
+ super().__init__()
+ self.out = torch.nn.Sequential(
+ torch.nn.Linear(idim, odim),
+ torch.nn.LayerNorm(odim, eps=1e-5),
+ torch.nn.Dropout(dropout_rate),
+ )
+ self.pos_enc = pos_enc_class
+ self.right_context = 0
+ self.subsampling_rate = 1
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ x_mask: torch.Tensor,
+ offset: Union[int, torch.Tensor] = 0
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ """Input x.
+
+ Args:
+ x (torch.Tensor): Input tensor (#batch, time, idim).
+ x_mask (torch.Tensor): Input mask (#batch, 1, time).
+
+ Returns:
+ torch.Tensor: linear input tensor (#batch, time', odim),
+ where time' = time .
+ torch.Tensor: linear input mask (#batch, 1, time'),
+ where time' = time .
+
+ """
+ x = self.out(x)
+ x, pos_emb = self.pos_enc(x, offset)
+ return x, pos_emb, x_mask
+
+
+# ── from s3gen/transformer/attention.py ────────────────────────────────
+
+
+# 2020 Mobvoi Inc (Binbin Zhang)
+# 2022 Xingchen Song ([email protected])
+# 2024 Alibaba Inc (Xiang Lyu)
+#
+# 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.
+"""Multi-Head Attention layer definition."""
+
+class MultiHeadedAttention(nn.Module):
+ """Multi-Head Attention layer.
+
+ Args:
+ n_head (int): The number of heads.
+ n_feat (int): The number of features.
+ dropout_rate (float): Dropout rate.
+
+ """
+
+ def __init__(self,
+ n_head: int,
+ n_feat: int,
+ dropout_rate: float,
+ key_bias: bool = True):
+ """Construct an MultiHeadedAttention object."""
+ super().__init__()
+ assert n_feat % n_head == 0
+ # We assume d_v always equals d_k
+ self.d_k = n_feat // n_head
+ self.h = n_head
+ self.linear_q = nn.Linear(n_feat, n_feat)
+ self.linear_k = nn.Linear(n_feat, n_feat, bias=key_bias)
+ self.linear_v = nn.Linear(n_feat, n_feat)
+ self.linear_out = nn.Linear(n_feat, n_feat)
+ self.dropout = nn.Dropout(p=dropout_rate)
+
+ def forward_qkv(
+ self, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ """Transform query, key and value.
+
+ Args:
+ query (torch.Tensor): Query tensor (#batch, time1, size).
+ key (torch.Tensor): Key tensor (#batch, time2, size).
+ value (torch.Tensor): Value tensor (#batch, time2, size).
+
+ Returns:
+ torch.Tensor: Transformed query tensor, size
+ (#batch, n_head, time1, d_k).
+ torch.Tensor: Transformed key tensor, size
+ (#batch, n_head, time2, d_k).
+ torch.Tensor: Transformed value tensor, size
+ (#batch, n_head, time2, d_k).
+
+ """
+ n_batch = query.size(0)
+ q = self.linear_q(query).view(n_batch, -1, self.h, self.d_k)
+ k = self.linear_k(key).view(n_batch, -1, self.h, self.d_k)
+ v = self.linear_v(value).view(n_batch, -1, self.h, self.d_k)
+ q = q.transpose(1, 2) # (batch, head, time1, d_k)
+ k = k.transpose(1, 2) # (batch, head, time2, d_k)
+ v = v.transpose(1, 2) # (batch, head, time2, d_k)
+
+ return q, k, v
+
+ def forward_attention(
+ self,
+ value: torch.Tensor,
+ scores: torch.Tensor,
+ mask: torch.Tensor = torch.ones((0, 0, 0), dtype=torch.bool)
+ ) -> torch.Tensor:
+ """Compute attention context vector.
+
+ Args:
+ value (torch.Tensor): Transformed value, size
+ (#batch, n_head, time2, d_k).
+ scores (torch.Tensor): Attention score, size
+ (#batch, n_head, time1, time2).
+ mask (torch.Tensor): Mask, size (#batch, 1, time2) or
+ (#batch, time1, time2), (0, 0, 0) means fake mask.
+
+ Returns:
+ torch.Tensor: Transformed value (#batch, time1, d_model)
+ weighted by the attention score (#batch, time1, time2).
+
+ """
+ n_batch = value.size(0)
+ # NOTE(xcsong): When will `if mask.size(2) > 0` be True?
+ # 1. onnx(16/4) [WHY? Because we feed real cache & real mask for the
+ # 1st chunk to ease the onnx export.]
+ # 2. pytorch training
+ if mask.size(2) > 0: # time2 > 0
+ mask = mask.unsqueeze(1).eq(0) # (batch, 1, *, time2)
+ # For last chunk, time2 might be larger than scores.size(-1)
+ mask = mask[:, :, :, :scores.size(-1)] # (batch, 1, *, time2)
+ scores = scores.masked_fill(mask, -float('inf'))
+ attn = torch.softmax(scores, dim=-1).masked_fill(
+ mask, 0.0) # (batch, head, time1, time2)
+ # NOTE(xcsong): When will `if mask.size(2) > 0` be False?
+ # 1. onnx(16/-1, -1/-1, 16/0)
+ # 2. jit (16/-1, -1/-1, 16/0, 16/4)
+ else:
+ attn = torch.softmax(scores, dim=-1) # (batch, head, time1, time2)
+
+ p_attn = self.dropout(attn)
+ x = torch.matmul(p_attn, value) # (batch, head, time1, d_k)
+ x = (x.transpose(1, 2).contiguous().view(n_batch, -1,
+ self.h * self.d_k)
+ ) # (batch, time1, d_model)
+
+ return self.linear_out(x) # (batch, time1, d_model)
+
+ def forward(
+ self,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ mask: torch.Tensor = torch.ones((0, 0, 0), dtype=torch.bool),
+ pos_emb: torch.Tensor = torch.empty(0),
+ cache: torch.Tensor = torch.zeros((0, 0, 0, 0))
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Compute scaled dot product attention.
+
+ Args:
+ query (torch.Tensor): Query tensor (#batch, time1, size).
+ key (torch.Tensor): Key tensor (#batch, time2, size).
+ value (torch.Tensor): Value tensor (#batch, time2, size).
+ mask (torch.Tensor): Mask tensor (#batch, 1, time2) or
+ (#batch, time1, time2).
+ 1.When applying cross attention between decoder and encoder,
+ the batch padding mask for input is in (#batch, 1, T) shape.
+ 2.When applying self attention of encoder,
+ the mask is in (#batch, T, T) shape.
+ 3.When applying self attention of decoder,
+ the mask is in (#batch, L, L) shape.
+ 4.If the different position in decoder see different block
+ of the encoder, such as Mocha, the passed in mask could be
+ in (#batch, L, T) shape. But there is no such case in current
+ CosyVoice.
+ cache (torch.Tensor): Cache tensor (1, head, cache_t, d_k * 2),
+ where `cache_t == chunk_size * num_decoding_left_chunks`
+ and `head * d_k == size`
+
+
+ Returns:
+ torch.Tensor: Output tensor (#batch, time1, d_model).
+ torch.Tensor: Cache tensor (1, head, cache_t + time1, d_k * 2)
+ where `cache_t == chunk_size * num_decoding_left_chunks`
+ and `head * d_k == size`
+
+ """
+ q, k, v = self.forward_qkv(query, key, value)
+
+ # NOTE(xcsong):
+ # when export onnx model, for 1st chunk, we feed
+ # cache(1, head, 0, d_k * 2) (16/-1, -1/-1, 16/0 mode)
+ # or cache(1, head, real_cache_t, d_k * 2) (16/4 mode).
+ # In all modes, `if cache.size(0) > 0` will alwayse be `True`
+ # and we will always do splitting and
+ # concatnation(this will simplify onnx export). Note that
+ # it's OK to concat & split zero-shaped tensors(see code below).
+ # when export jit model, for 1st chunk, we always feed
+ # cache(0, 0, 0, 0) since jit supports dynamic if-branch.
+ # >>> a = torch.ones((1, 2, 0, 4))
+ # >>> b = torch.ones((1, 2, 3, 4))
+ # >>> c = torch.cat((a, b), dim=2)
+ # >>> torch.equal(b, c) # True
+ # >>> d = torch.split(a, 2, dim=-1)
+ # >>> torch.equal(d[0], d[1]) # True
+ if cache.size(0) > 0:
+ key_cache, value_cache = torch.split(cache,
+ cache.size(-1) // 2,
+ dim=-1)
+ k = torch.cat([key_cache, k], dim=2)
+ v = torch.cat([value_cache, v], dim=2)
+ # NOTE(xcsong): We do cache slicing in encoder.forward_chunk, since it's
+ # non-trivial to calculate `next_cache_start` here.
+ new_cache = torch.cat((k, v), dim=-1)
+
+ scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.d_k)
+ return self.forward_attention(v, scores, mask), new_cache
+
+class RelPositionMultiHeadedAttention(MultiHeadedAttention):
+ """Multi-Head Attention layer with relative position encoding.
+ Paper: https://arxiv.org/abs/1901.02860
+ Args:
+ n_head (int): The number of heads.
+ n_feat (int): The number of features.
+ dropout_rate (float): Dropout rate.
+ """
+
+ def __init__(self,
+ n_head: int,
+ n_feat: int,
+ dropout_rate: float,
+ key_bias: bool = True):
+ """Construct an RelPositionMultiHeadedAttention object."""
+ super().__init__(n_head, n_feat, dropout_rate, key_bias)
+ # linear transformation for positional encoding
+ self.linear_pos = nn.Linear(n_feat, n_feat, bias=False)
+ # these two learnable bias are used in matrix c and matrix d
+ # as described in https://arxiv.org/abs/1901.02860 Section 3.3
+ self.pos_bias_u = nn.Parameter(torch.Tensor(self.h, self.d_k))
+ self.pos_bias_v = nn.Parameter(torch.Tensor(self.h, self.d_k))
+ torch.nn.init.xavier_uniform_(self.pos_bias_u)
+ torch.nn.init.xavier_uniform_(self.pos_bias_v)
+
+ def rel_shift(self, x: torch.Tensor) -> torch.Tensor:
+ """Compute relative positional encoding.
+
+ Args:
+ x (torch.Tensor): Input tensor (batch, head, time1, 2*time1-1).
+ time1 means the length of query vector.
+
+ Returns:
+ torch.Tensor: Output tensor.
+
+ """
+ zero_pad = torch.zeros((x.size()[0], x.size()[1], x.size()[2], 1),
+ device=x.device,
+ dtype=x.dtype)
+ x_padded = torch.cat([zero_pad, x], dim=-1)
+
+ x_padded = x_padded.view(x.size()[0],
+ x.size()[1],
+ x.size(3) + 1, x.size(2))
+ x = x_padded[:, :, 1:].view_as(x)[
+ :, :, :, : x.size(-1) // 2 + 1
+ ] # only keep the positions from 0 to time2
+ return x
+
+ def forward(
+ self,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ mask: torch.Tensor = torch.ones((0, 0, 0), dtype=torch.bool),
+ pos_emb: torch.Tensor = torch.empty(0),
+ cache: torch.Tensor = torch.zeros((0, 0, 0, 0))
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Compute 'Scaled Dot Product Attention' with rel. positional encoding.
+ Args:
+ query (torch.Tensor): Query tensor (#batch, time1, size).
+ key (torch.Tensor): Key tensor (#batch, time2, size).
+ value (torch.Tensor): Value tensor (#batch, time2, size).
+ mask (torch.Tensor): Mask tensor (#batch, 1, time2) or
+ (#batch, time1, time2), (0, 0, 0) means fake mask.
+ pos_emb (torch.Tensor): Positional embedding tensor
+ (#batch, time2, size).
+ cache (torch.Tensor): Cache tensor (1, head, cache_t, d_k * 2),
+ where `cache_t == chunk_size * num_decoding_left_chunks`
+ and `head * d_k == size`
+ Returns:
+ torch.Tensor: Output tensor (#batch, time1, d_model).
+ torch.Tensor: Cache tensor (1, head, cache_t + time1, d_k * 2)
+ where `cache_t == chunk_size * num_decoding_left_chunks`
+ and `head * d_k == size`
+ """
+ q, k, v = self.forward_qkv(query, key, value)
+ q = q.transpose(1, 2) # (batch, time1, head, d_k)
+
+ # NOTE(xcsong):
+ # when export onnx model, for 1st chunk, we feed
+ # cache(1, head, 0, d_k * 2) (16/-1, -1/-1, 16/0 mode)
+ # or cache(1, head, real_cache_t, d_k * 2) (16/4 mode).
+ # In all modes, `if cache.size(0) > 0` will alwayse be `True`
+ # and we will always do splitting and
+ # concatnation(this will simplify onnx export). Note that
+ # it's OK to concat & split zero-shaped tensors(see code below).
+ # when export jit model, for 1st chunk, we always feed
+ # cache(0, 0, 0, 0) since jit supports dynamic if-branch.
+ # >>> a = torch.ones((1, 2, 0, 4))
+ # >>> b = torch.ones((1, 2, 3, 4))
+ # >>> c = torch.cat((a, b), dim=2)
+ # >>> torch.equal(b, c) # True
+ # >>> d = torch.split(a, 2, dim=-1)
+ # >>> torch.equal(d[0], d[1]) # True
+ if cache.size(0) > 0:
+ key_cache, value_cache = torch.split(cache,
+ cache.size(-1) // 2,
+ dim=-1)
+ k = torch.cat([key_cache, k], dim=2)
+ v = torch.cat([value_cache, v], dim=2)
+ # NOTE(xcsong): We do cache slicing in encoder.forward_chunk, since it's
+ # non-trivial to calculate `next_cache_start` here.
+ new_cache = torch.cat((k, v), dim=-1)
+
+ n_batch_pos = pos_emb.size(0)
+ p = self.linear_pos(pos_emb).view(n_batch_pos, -1, self.h, self.d_k)
+ p = p.transpose(1, 2) # (batch, head, time1, d_k)
+
+ # (batch, head, time1, d_k)
+ q_with_bias_u = (q + self.pos_bias_u.to(q.device)).transpose(1, 2)
+ # (batch, head, time1, d_k)
+ q_with_bias_v = (q + self.pos_bias_v.to(q.device)).transpose(1, 2)
+
+ # compute attention score
+ # first compute matrix a and matrix c
+ # as described in https://arxiv.org/abs/1901.02860 Section 3.3
+ # (batch, head, time1, time2)
+ matrix_ac = torch.matmul(q_with_bias_u, k.transpose(-2, -1))
+
+ # compute matrix b and matrix d
+ # (batch, head, time1, time2)
+ matrix_bd = torch.matmul(q_with_bias_v, p.transpose(-2, -1))
+ # NOTE(Xiang Lyu): Keep rel_shift since espnet rel_pos_emb is used
+ if matrix_ac.shape != matrix_bd.shape:
+ matrix_bd = self.rel_shift(matrix_bd)
+
+ scores = (matrix_ac + matrix_bd) / math.sqrt(
+ self.d_k) # (batch, head, time1, time2)
+
+ return self.forward_attention(v, scores, mask), new_cache
+
+
+# ── from s3gen/transformer/convolution.py ──────────────────────────────
+
+
+# 2024 Alibaba Inc (Xiang Lyu)
+#
+# 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.
+# Modified from ESPnet(https://github.com/espnet/espnet)
+"""ConvolutionModule definition."""
+
+class ConvolutionModule(nn.Module):
+ """ConvolutionModule in Conformer model."""
+
+ def __init__(self,
+ channels: int,
+ kernel_size: int = 15,
+ activation: nn.Module = nn.ReLU(),
+ norm: str = "batch_norm",
+ causal: bool = False,
+ bias: bool = True):
+ """Construct an ConvolutionModule object.
+ Args:
+ channels (int): The number of channels of conv layers.
+ kernel_size (int): Kernel size of conv layers.
+ causal (int): Whether use causal convolution or not
+ """
+ super().__init__()
+
+ self.pointwise_conv1 = nn.Conv1d(
+ channels,
+ 2 * channels,
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ bias=bias,
+ )
+ # self.lorder is used to distinguish if it's a causal convolution,
+ # if self.lorder > 0: it's a causal convolution, the input will be
+ # padded with self.lorder frames on the left in forward.
+ # else: it's a symmetrical convolution
+ if causal:
+ padding = 0
+ self.lorder = kernel_size - 1
+ else:
+ # kernel_size should be an odd number for none causal convolution
+ assert (kernel_size - 1) % 2 == 0
+ padding = (kernel_size - 1) // 2
+ self.lorder = 0
+ self.depthwise_conv = nn.Conv1d(
+ channels,
+ channels,
+ kernel_size,
+ stride=1,
+ padding=padding,
+ groups=channels,
+ bias=bias,
+ )
+
+ assert norm in ['batch_norm', 'layer_norm']
+ if norm == "batch_norm":
+ self.use_layer_norm = False
+ self.norm = nn.BatchNorm1d(channels)
+ else:
+ self.use_layer_norm = True
+ self.norm = nn.LayerNorm(channels)
+
+ self.pointwise_conv2 = nn.Conv1d(
+ channels,
+ channels,
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ bias=bias,
+ )
+ self.activation = activation
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ mask_pad: torch.Tensor = torch.ones((0, 0, 0), dtype=torch.bool),
+ cache: torch.Tensor = torch.zeros((0, 0, 0)),
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Compute convolution module.
+ Args:
+ x (torch.Tensor): Input tensor (#batch, time, channels).
+ mask_pad (torch.Tensor): used for batch padding (#batch, 1, time),
+ (0, 0, 0) means fake mask.
+ cache (torch.Tensor): left context cache, it is only
+ used in causal convolution (#batch, channels, cache_t),
+ (0, 0, 0) meas fake cache.
+ Returns:
+ torch.Tensor: Output tensor (#batch, time, channels).
+ """
+ # exchange the temporal dimension and the feature dimension
+ x = x.transpose(1, 2) # (#batch, channels, time)
+
+ # mask batch padding
+ if mask_pad.size(2) > 0: # time > 0
+ x.masked_fill_(~mask_pad, 0.0)
+
+ if self.lorder > 0:
+ if cache.size(2) == 0: # cache_t == 0
+ x = nn.functional.pad(x, (self.lorder, 0), 'constant', 0.0)
+ else:
+ assert cache.size(0) == x.size(0) # equal batch
+ assert cache.size(1) == x.size(1) # equal channel
+ x = torch.cat((cache, x), dim=2)
+ assert (x.size(2) > self.lorder)
+ new_cache = x[:, :, -self.lorder:]
+ else:
+ # It's better we just return None if no cache is required,
+ # However, for JIT export, here we just fake one tensor instead of
+ # None.
+ new_cache = torch.zeros((0, 0, 0), dtype=x.dtype, device=x.device)
+
+ # GLU mechanism
+ x = self.pointwise_conv1(x) # (batch, 2*channel, dim)
+ x = nn.functional.glu(x, dim=1) # (batch, channel, dim)
+
+ # 1D Depthwise Conv
+ x = self.depthwise_conv(x)
+ if self.use_layer_norm:
+ x = x.transpose(1, 2)
+ x = self.activation(self.norm(x))
+ if self.use_layer_norm:
+ x = x.transpose(1, 2)
+ x = self.pointwise_conv2(x)
+ # mask batch padding
+ if mask_pad.size(2) > 0: # time > 0
+ x.masked_fill_(~mask_pad, 0.0)
+
+ return x.transpose(1, 2), new_cache
+
+
+# ── from s3gen/transformer/positionwise_feed_forward.py ────────────────
+
+
+# 2020 Mobvoi Inc (Binbin Zhang)
+#
+# 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.
+"""Positionwise feed forward layer definition."""
+
+class PositionwiseFeedForward(torch.nn.Module):
+ """Positionwise feed forward layer.
+
+ FeedForward are appied on each position of the sequence.
+ The output dim is same with the input dim.
+
+ Args:
+ idim (int): Input dimenstion.
+ hidden_units (int): The number of hidden units.
+ dropout_rate (float): Dropout rate.
+ activation (torch.nn.Module): Activation function
+ """
+
+ def __init__(
+ self,
+ idim: int,
+ hidden_units: int,
+ dropout_rate: float,
+ activation: torch.nn.Module = torch.nn.ReLU(),
+ ):
+ """Construct a PositionwiseFeedForward object."""
+ super(PositionwiseFeedForward, self).__init__()
+ self.w_1 = torch.nn.Linear(idim, hidden_units)
+ self.activation = activation
+ self.dropout = torch.nn.Dropout(dropout_rate)
+ self.w_2 = torch.nn.Linear(hidden_units, idim)
+
+ def forward(self, xs: torch.Tensor) -> torch.Tensor:
+ """Forward function.
+
+ Args:
+ xs: input tensor (B, L, D)
+ Returns:
+ output tensor, (B, L, D)
+ """
+ return self.w_2(self.dropout(self.activation(self.w_1(xs))))
+
+
+# ── from s3gen/transformer/encoder_layer.py ────────────────────────────
+
+
+# 2022 Xingchen Song ([email protected])
+#
+# 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.
+# Modified from ESPnet(https://github.com/espnet/espnet)
+"""Encoder self-attention layer definition."""
+
+class ConformerEncoderLayer(nn.Module):
+ """Encoder layer module.
+ Args:
+ size (int): Input dimension.
+ self_attn (torch.nn.Module): Self-attention module instance.
+ `MultiHeadedAttention` or `RelPositionMultiHeadedAttention`
+ instance can be used as the argument.
+ feed_forward (torch.nn.Module): Feed-forward module instance.
+ `PositionwiseFeedForward` instance can be used as the argument.
+ feed_forward_macaron (torch.nn.Module): Additional feed-forward module
+ instance.
+ `PositionwiseFeedForward` instance can be used as the argument.
+ conv_module (torch.nn.Module): Convolution module instance.
+ `ConvlutionModule` instance can be used as the argument.
+ dropout_rate (float): Dropout rate.
+ normalize_before (bool):
+ True: use layer_norm before each sub-block.
+ False: use layer_norm after each sub-block.
+ """
+
+ def __init__(
+ self,
+ size: int,
+ self_attn: torch.nn.Module,
+ feed_forward: Optional[nn.Module] = None,
+ feed_forward_macaron: Optional[nn.Module] = None,
+ conv_module: Optional[nn.Module] = None,
+ dropout_rate: float = 0.1,
+ normalize_before: bool = True,
+ ):
+ """Construct an EncoderLayer object."""
+ super().__init__()
+ self.self_attn = self_attn
+ self.feed_forward = feed_forward
+ self.feed_forward_macaron = feed_forward_macaron
+ self.conv_module = conv_module
+ self.norm_ff = nn.LayerNorm(size, eps=1e-12) # for the FNN module
+ self.norm_mha = nn.LayerNorm(size, eps=1e-12) # for the MHA module
+ if feed_forward_macaron is not None:
+ self.norm_ff_macaron = nn.LayerNorm(size, eps=1e-12)
+ self.ff_scale = 0.5
+ else:
+ self.ff_scale = 1.0
+ if self.conv_module is not None:
+ self.norm_conv = nn.LayerNorm(size, eps=1e-12) # for the CNN module
+ self.norm_final = nn.LayerNorm(
+ size, eps=1e-12) # for the final output of the block
+ self.dropout = nn.Dropout(dropout_rate)
+ self.size = size
+ self.normalize_before = normalize_before
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ mask: torch.Tensor,
+ pos_emb: torch.Tensor,
+ mask_pad: torch.Tensor = torch.ones((0, 0, 0), dtype=torch.bool),
+ att_cache: torch.Tensor = torch.zeros((0, 0, 0, 0)),
+ cnn_cache: torch.Tensor = torch.zeros((0, 0, 0, 0)),
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
+ """Compute encoded features.
+
+ Args:
+ x (torch.Tensor): (#batch, time, size)
+ mask (torch.Tensor): Mask tensor for the input (#batch, time,time),
+ (0, 0, 0) means fake mask.
+ pos_emb (torch.Tensor): positional encoding, must not be None
+ for ConformerEncoderLayer.
+ mask_pad (torch.Tensor): batch padding mask used for conv module.
+ (#batch, 1,time), (0, 0, 0) means fake mask.
+ att_cache (torch.Tensor): Cache tensor of the KEY & VALUE
+ (#batch=1, head, cache_t1, d_k * 2), head * d_k == size.
+ cnn_cache (torch.Tensor): Convolution cache in conformer layer
+ (#batch=1, size, cache_t2)
+ Returns:
+ torch.Tensor: Output tensor (#batch, time, size).
+ torch.Tensor: Mask tensor (#batch, time, time).
+ torch.Tensor: att_cache tensor,
+ (#batch=1, head, cache_t1 + time, d_k * 2).
+ torch.Tensor: cnn_cahce tensor (#batch, size, cache_t2).
+ """
+
+ # whether to use macaron style
+ if self.feed_forward_macaron is not None:
+ residual = x
+ if self.normalize_before:
+ x = self.norm_ff_macaron(x)
+ x = residual + self.ff_scale * self.dropout(
+ self.feed_forward_macaron(x))
+ if not self.normalize_before:
+ x = self.norm_ff_macaron(x)
+
+ # multi-headed self-attention module
+ residual = x
+ if self.normalize_before:
+ x = self.norm_mha(x)
+ x_att, new_att_cache = self.self_attn(x, x, x, mask, pos_emb,
+ att_cache)
+ x = residual + self.dropout(x_att)
+ if not self.normalize_before:
+ x = self.norm_mha(x)
+
+ # convolution module
+ # Fake new cnn cache here, and then change it in conv_module
+ new_cnn_cache = torch.zeros((0, 0, 0), dtype=x.dtype, device=x.device)
+ if self.conv_module is not None:
+ residual = x
+ if self.normalize_before:
+ x = self.norm_conv(x)
+ x, new_cnn_cache = self.conv_module(x, mask_pad, cnn_cache)
+ x = residual + self.dropout(x)
+
+ if not self.normalize_before:
+ x = self.norm_conv(x)
+
+ # feed forward module
+ residual = x
+ if self.normalize_before:
+ x = self.norm_ff(x)
+
+ x = residual + self.ff_scale * self.dropout(self.feed_forward(x))
+ if not self.normalize_before:
+ x = self.norm_ff(x)
+
+ if self.conv_module is not None:
+ x = self.norm_final(x)
+
+ return x, mask, new_att_cache, new_cnn_cache
+
+
+# The upstream encoder picks its submodules out of registries keyed by config
+# string. S3Gen only ever instantiates one entry of each, so only those are kept —
+# an unexpected configuration raises KeyError here rather than silently running a
+# different architecture than the weights were trained for.
+_SUBSAMPLE_CLASSES = {"linear": LinearNoSubsampling}
+_EMB_CLASSES = {"rel_pos_espnet": EspnetRelPositionalEncoding}
+_ATTENTION_CLASSES = {"rel_selfattn": RelPositionMultiHeadedAttention}
+_ACTIVATION_CLASSES = {"swish": torch.nn.SiLU}
+
+
+# ── from s3gen/transformer/upsample_encoder.py ─────────────────────────
+
+
+# 2022 Xingchen Song ([email protected])
+# 2024 Alibaba Inc (Xiang Lyu)
+#
+# 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.
+# Modified from ESPnet(https://github.com/espnet/espnet)
+"""Encoder definition."""
+
+class Upsample1D(nn.Module):
+ """A 1D upsampling layer with an optional convolution.
+
+ Parameters:
+ channels (`int`):
+ number of channels in the inputs and outputs.
+ use_conv (`bool`, default `False`):
+ option to use a convolution.
+ use_conv_transpose (`bool`, default `False`):
+ option to use a convolution transpose.
+ out_channels (`int`, optional):
+ number of output channels. Defaults to `channels`.
+ """
+
+ def __init__(self, channels: int, out_channels: int, stride: int = 2):
+ super().__init__()
+ self.channels = channels
+ self.out_channels = out_channels
+ self.stride = stride
+ # In this mode, first repeat interpolate, than conv with stride=1
+ self.conv = nn.Conv1d(self.channels, self.out_channels, stride * 2 + 1, stride=1, padding=0)
+
+ def forward(self, inputs: torch.Tensor, input_lengths: torch.Tensor):
+ outputs = F.interpolate(inputs, scale_factor=float(self.stride), mode="nearest")
+ outputs = F.pad(outputs, (self.stride * 2, 0), value=0.0)
+ outputs = self.conv(outputs)
+ return outputs, input_lengths * self.stride
+
+class PreLookaheadLayer(nn.Module):
+ def __init__(self, channels: int, pre_lookahead_len: int = 1):
+ super().__init__()
+ self.channels = channels
+ self.pre_lookahead_len = pre_lookahead_len
+ self.conv1 = nn.Conv1d(
+ channels, channels,
+ kernel_size=pre_lookahead_len + 1,
+ stride=1, padding=0,
+ )
+ self.conv2 = nn.Conv1d(
+ channels, channels,
+ kernel_size=3, stride=1, padding=0,
+ )
+
+ def forward(self, inputs: torch.Tensor) -> torch.Tensor:
+ """
+ inputs: (batch_size, seq_len, channels)
+ """
+ outputs = inputs.transpose(1, 2).contiguous()
+ # look ahead
+ outputs = F.pad(outputs, (0, self.pre_lookahead_len), mode='constant', value=0.0)
+ outputs = F.leaky_relu(self.conv1(outputs))
+ # outputs
+ outputs = F.pad(outputs, (2, 0), mode='constant', value=0.0)
+ outputs = self.conv2(outputs)
+ outputs = outputs.transpose(1, 2).contiguous()
+
+ # residual connection
+ outputs = outputs + inputs
+ return outputs
+
+class UpsampleConformerEncoder(torch.nn.Module):
+
+ def __init__(
+ self,
+ input_size: int = 512,
+ output_size: int = 512,
+ attention_heads: int = 8,
+ linear_units: int = 2048,
+ num_blocks: int = 6,
+ dropout_rate: float = 0.1,
+ positional_dropout_rate: float = 0.1,
+ attention_dropout_rate: float = 0.1,
+ input_layer: str = "linear",
+ pos_enc_layer_type: str = "rel_pos_espnet",
+ normalize_before: bool = True,
+ static_chunk_size: int = 0,
+ use_dynamic_chunk: bool = False,
+ global_cmvn: torch.nn.Module = None,
+ use_dynamic_left_chunk: bool = False,
+ positionwise_conv_kernel_size: int = 1,
+ macaron_style: bool = False,
+ selfattention_layer_type: str = "rel_selfattn",
+ activation_type: str = "swish",
+ use_cnn_module: bool = False,
+ cnn_module_kernel: int = 15,
+ causal: bool = False,
+ cnn_module_norm: str = "batch_norm",
+ key_bias: bool = True,
+ gradient_checkpointing: bool = False,
+ ):
+ """
+ Args:
+ input_size (int): input dim
+ output_size (int): dimension of attention
+ attention_heads (int): the number of heads of multi head attention
+ linear_units (int): the hidden units number of position-wise feed
+ forward
+ num_blocks (int): the number of decoder blocks
+ dropout_rate (float): dropout rate
+ attention_dropout_rate (float): dropout rate in attention
+ positional_dropout_rate (float): dropout rate after adding
+ positional encoding
+ input_layer (str): input layer type.
+ optional [linear, conv2d, conv2d6, conv2d8]
+ pos_enc_layer_type (str): Encoder positional encoding layer type.
+ opitonal [abs_pos, scaled_abs_pos, rel_pos, no_pos]
+ normalize_before (bool):
+ True: use layer_norm before each sub-block of a layer.
+ False: use layer_norm after each sub-block of a layer.
+ static_chunk_size (int): chunk size for static chunk training and
+ decoding
+ use_dynamic_chunk (bool): whether use dynamic chunk size for
+ training or not, You can only use fixed chunk(chunk_size > 0)
+ or dyanmic chunk size(use_dynamic_chunk = True)
+ global_cmvn (Optional[torch.nn.Module]): Optional GlobalCMVN module
+ use_dynamic_left_chunk (bool): whether use dynamic left chunk in
+ dynamic chunk training
+ key_bias: whether use bias in attention.linear_k, False for whisper models.
+ gradient_checkpointing: rerunning a forward-pass segment for each
+ checkpointed segment during backward.
+ """
+ super().__init__()
+ self._output_size = output_size
+
+ self.global_cmvn = global_cmvn
+ self.embed = _SUBSAMPLE_CLASSES[input_layer](
+ input_size,
+ output_size,
+ dropout_rate,
+ _EMB_CLASSES[pos_enc_layer_type](output_size,
+ positional_dropout_rate),
+ )
+
+ self.normalize_before = normalize_before
+ self.after_norm = torch.nn.LayerNorm(output_size, eps=1e-5)
+ self.static_chunk_size = static_chunk_size
+ self.use_dynamic_chunk = use_dynamic_chunk
+ self.use_dynamic_left_chunk = use_dynamic_left_chunk
+ self.gradient_checkpointing = gradient_checkpointing
+ activation = _ACTIVATION_CLASSES[activation_type]()
+ # self-attention module definition
+ encoder_selfattn_layer_args = (
+ attention_heads,
+ output_size,
+ attention_dropout_rate,
+ key_bias,
+ )
+ # feed-forward module definition
+ positionwise_layer_args = (
+ output_size,
+ linear_units,
+ dropout_rate,
+ activation,
+ )
+ # convolution module definition
+ convolution_layer_args = (output_size, cnn_module_kernel, activation,
+ cnn_module_norm, causal)
+ self.pre_lookahead_layer = PreLookaheadLayer(channels=512, pre_lookahead_len=3)
+ self.encoders = torch.nn.ModuleList([
+ ConformerEncoderLayer(
+ output_size,
+ _ATTENTION_CLASSES[selfattention_layer_type](
+ *encoder_selfattn_layer_args),
+ PositionwiseFeedForward(*positionwise_layer_args),
+ PositionwiseFeedForward(
+ *positionwise_layer_args) if macaron_style else None,
+ ConvolutionModule(
+ *convolution_layer_args) if use_cnn_module else None,
+ dropout_rate,
+ normalize_before,
+ ) for _ in range(num_blocks)
+ ])
+ self.up_layer = Upsample1D(channels=512, out_channels=512, stride=2)
+ self.up_embed = _SUBSAMPLE_CLASSES[input_layer](
+ input_size,
+ output_size,
+ dropout_rate,
+ _EMB_CLASSES[pos_enc_layer_type](output_size,
+ positional_dropout_rate),
+ )
+ self.up_encoders = torch.nn.ModuleList([
+ ConformerEncoderLayer(
+ output_size,
+ _ATTENTION_CLASSES[selfattention_layer_type](
+ *encoder_selfattn_layer_args),
+ PositionwiseFeedForward(*positionwise_layer_args),
+ PositionwiseFeedForward(
+ *positionwise_layer_args) if macaron_style else None,
+ ConvolutionModule(
+ *convolution_layer_args) if use_cnn_module else None,
+ dropout_rate,
+ normalize_before,
+ ) for _ in range(4)
+ ])
+
+ def output_size(self) -> int:
+ return self._output_size
+
+ def forward(
+ self,
+ xs: torch.Tensor,
+ xs_lens: torch.Tensor,
+ decoding_chunk_size: int = 0,
+ num_decoding_left_chunks: int = -1,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Embed positions in tensor.
+
+ Args:
+ xs: padded input tensor (B, T, D)
+ xs_lens: input length (B)
+ decoding_chunk_size: decoding chunk size for dynamic chunk
+ 0: default for training, use random dynamic chunk.
+ <0: for decoding, use full chunk.
+ >0: for decoding, use fixed chunk size as set.
+ num_decoding_left_chunks: number of left chunks, this is for decoding,
+ the chunk size is decoding_chunk_size.
+ >=0: use num_decoding_left_chunks
+ <0: use all left chunks
+ Returns:
+ encoder output tensor xs, and subsampled masks
+ xs: padded output tensor (B, T' ~= T/subsample_rate, D)
+ masks: torch.Tensor batch padding mask after subsample
+ (B, 1, T' ~= T/subsample_rate)
+ NOTE(xcsong):
+ We pass the `__call__` method of the modules instead of `forward` to the
+ checkpointing API because `__call__` attaches all the hooks of the module.
+ https://discuss.pytorch.org/t/any-different-between-model-input-and-model-forward-input/3690/2
+ """
+ T = xs.size(1)
+ masks = ~make_pad_mask(xs_lens, T).unsqueeze(1) # (B, 1, T)
+ if self.global_cmvn is not None:
+ xs = self.global_cmvn(xs)
+ xs, pos_emb, masks = self.embed(xs, masks)
+ mask_pad = masks # (B, 1, T/subsample_rate)
+ chunk_masks = add_optional_chunk_mask(xs, masks,
+ self.use_dynamic_chunk,
+ self.use_dynamic_left_chunk,
+ decoding_chunk_size,
+ self.static_chunk_size,
+ num_decoding_left_chunks)
+ # lookahead + conformer encoder
+ xs = self.pre_lookahead_layer(xs)
+ xs = self.forward_layers(xs, chunk_masks, pos_emb, mask_pad)
+
+ # upsample + conformer encoder
+ xs = xs.transpose(1, 2).contiguous()
+ xs, xs_lens = self.up_layer(xs, xs_lens)
+ xs = xs.transpose(1, 2).contiguous()
+ T = xs.size(1)
+ masks = ~make_pad_mask(xs_lens, T).unsqueeze(1) # (B, 1, T)
+ xs, pos_emb, masks = self.up_embed(xs, masks)
+ mask_pad = masks # (B, 1, T/subsample_rate)
+ chunk_masks = add_optional_chunk_mask(xs, masks,
+ self.use_dynamic_chunk,
+ self.use_dynamic_left_chunk,
+ decoding_chunk_size,
+ self.static_chunk_size * self.up_layer.stride,
+ num_decoding_left_chunks)
+ xs = self.forward_up_layers(xs, chunk_masks, pos_emb, mask_pad)
+
+ if self.normalize_before:
+ xs = self.after_norm(xs)
+ # Here we assume the mask is not changed in encoder layers, so just
+ # return the masks before encoder layers, and the masks will be used
+ # for cross attention with decoder later
+ return xs, masks
+
+ def forward_layers(self, xs: torch.Tensor, chunk_masks: torch.Tensor,
+ pos_emb: torch.Tensor,
+ mask_pad: torch.Tensor) -> torch.Tensor:
+ for layer in self.encoders:
+ xs, chunk_masks, _, _ = layer(xs, chunk_masks, pos_emb, mask_pad)
+ return xs
+
+ def forward_up_layers(self, xs: torch.Tensor, chunk_masks: torch.Tensor,
+ pos_emb: torch.Tensor,
+ mask_pad: torch.Tensor) -> torch.Tensor:
+ for layer in self.up_encoders:
+ xs, chunk_masks, _, _ = layer(xs, chunk_masks, pos_emb, mask_pad)
+ return xs
+
+
+# ── from s3gen/matcha/transformer.py ───────────────────────────────────
+
+
+class SnakeBeta(nn.Module):
+ """
+ A modified Snake function which uses separate parameters for the magnitude of the periodic components
+ Shape:
+ - Input: (B, C, T)
+ - Output: (B, C, T), same shape as the input
+ Parameters:
+ - alpha - trainable parameter that controls frequency
+ - beta - trainable parameter that controls magnitude
+ References:
+ - This activation function is a modified version based on this paper by Liu Ziyin, Tilman Hartwig, Masahito Ueda:
+ https://arxiv.org/abs/2006.08195
+ Examples:
+ >>> a1 = snakebeta(256)
+ >>> x = torch.randn(256)
+ >>> x = a1(x)
+ """
+
+ def __init__(self, in_features, out_features, alpha=1.0, alpha_trainable=True, alpha_logscale=True):
+ """
+ Initialization.
+ INPUT:
+ - in_features: shape of the input
+ - alpha - trainable parameter that controls frequency
+ - beta - trainable parameter that controls magnitude
+ alpha is initialized to 1 by default, higher values = higher-frequency.
+ beta is initialized to 1 by default, higher values = higher-magnitude.
+ alpha will be trained along with the rest of your model.
+ """
+ super().__init__()
+ self.in_features = out_features if isinstance(out_features, list) else [out_features]
+ self.proj = torch.nn.Linear(in_features, out_features)
+
+ # initialize alpha
+ self.alpha_logscale = alpha_logscale
+ if self.alpha_logscale: # log scale alphas initialized to zeros
+ self.alpha = nn.Parameter(torch.zeros(self.in_features) * alpha)
+ self.beta = nn.Parameter(torch.zeros(self.in_features) * alpha)
+ else: # linear scale alphas initialized to ones
+ self.alpha = nn.Parameter(torch.ones(self.in_features) * alpha)
+ self.beta = nn.Parameter(torch.ones(self.in_features) * alpha)
+
+ self.alpha.requires_grad = alpha_trainable
+ self.beta.requires_grad = alpha_trainable
+
+ self.no_div_by_zero = 0.000000001
+
+ def forward(self, x):
+ """
+ Forward pass of the function.
+ Applies the function to the input elementwise.
+ SnakeBeta ∶= x + 1/b * sin^2 (xa)
+ """
+ x = self.proj(x)
+ if self.alpha_logscale:
+ alpha = torch.exp(self.alpha)
+ beta = torch.exp(self.beta)
+ else:
+ alpha = self.alpha
+ beta = self.beta
+
+ x = x + (1.0 / (beta + self.no_div_by_zero)) * torch.pow(torch.sin(x * alpha), 2)
+
+ return x
+
+class FeedForward(nn.Module):
+ r"""
+ A feed-forward layer.
+
+ Parameters:
+ dim (`int`): The number of channels in the input.
+ dim_out (`int`, *optional*): The number of channels in the output. If not given, defaults to `dim`.
+ mult (`int`, *optional*, defaults to 4): The multiplier to use for the hidden dimension.
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
+ activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
+ final_dropout (`bool` *optional*, defaults to False): Apply a final dropout.
+ """
+
+ def __init__(
+ self,
+ dim: int,
+ dim_out: Optional[int] = None,
+ mult: int = 4,
+ dropout: float = 0.0,
+ activation_fn: str = "geglu",
+ final_dropout: bool = False,
+ ):
+ super().__init__()
+ inner_dim = int(dim * mult)
+ dim_out = dim_out if dim_out is not None else dim
+
+ if activation_fn == "gelu":
+ act_fn = GELU(dim, inner_dim)
+ if activation_fn == "gelu-approximate":
+ act_fn = GELU(dim, inner_dim, approximate="tanh")
+ elif activation_fn == "geglu":
+ act_fn = GEGLU(dim, inner_dim)
+ elif activation_fn == "geglu-approximate":
+ act_fn = ApproximateGELU(dim, inner_dim)
+ elif activation_fn == "snakebeta":
+ act_fn = SnakeBeta(dim, inner_dim)
+
+ self.net = nn.ModuleList([])
+ # project in
+ self.net.append(act_fn)
+ # project dropout
+ self.net.append(nn.Dropout(dropout))
+ # project out
+ self.net.append(torch.nn.Linear(inner_dim, dim_out))
+ # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout
+ if final_dropout:
+ self.net.append(nn.Dropout(dropout))
+
+ def forward(self, hidden_states):
+ for module in self.net:
+ hidden_states = module(hidden_states)
+ return hidden_states
+
+class BasicTransformerBlock(nn.Module):
+ r"""
+ A basic Transformer block.
+
+ Parameters:
+ dim (`int`): The number of channels in the input and output.
+ num_attention_heads (`int`): The number of heads to use for multi-head attention.
+ attention_head_dim (`int`): The number of channels in each head.
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
+ cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention.
+ only_cross_attention (`bool`, *optional*):
+ Whether to use only cross-attention layers. In this case two cross attention layers are used.
+ double_self_attention (`bool`, *optional*):
+ Whether to use two self-attention layers. In this case no cross attention layers are used.
+ activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
+ num_embeds_ada_norm (:
+ obj: `int`, *optional*): The number of diffusion steps used during training. See `Transformer2DModel`.
+ attention_bias (:
+ obj: `bool`, *optional*, defaults to `False`): Configure if the attentions should contain a bias parameter.
+ """
+
+ def __init__(
+ self,
+ dim: int,
+ num_attention_heads: int,
+ attention_head_dim: int,
+ dropout=0.0,
+ cross_attention_dim: Optional[int] = None,
+ activation_fn: str = "geglu",
+ num_embeds_ada_norm: Optional[int] = None,
+ attention_bias: bool = False,
+ only_cross_attention: bool = False,
+ double_self_attention: bool = False,
+ upcast_attention: bool = False,
+ norm_elementwise_affine: bool = True,
+ norm_type: str = "layer_norm",
+ final_dropout: bool = False,
+ ):
+ super().__init__()
+ self.only_cross_attention = only_cross_attention
+
+ self.use_ada_layer_norm_zero = (num_embeds_ada_norm is not None) and norm_type == "ada_norm_zero"
+ self.use_ada_layer_norm = (num_embeds_ada_norm is not None) and norm_type == "ada_norm"
+
+ if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None:
+ raise ValueError(
+ f"`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to"
+ f" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}."
+ )
+
+ # Define 3 blocks. Each block has its own normalization layer.
+ # 1. Self-Attn
+ if self.use_ada_layer_norm:
+ self.norm1 = AdaLayerNorm(dim, num_embeds_ada_norm)
+ elif self.use_ada_layer_norm_zero:
+ self.norm1 = AdaLayerNormZero(dim, num_embeds_ada_norm)
+ else:
+ self.norm1 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine)
+ self.attn1 = Attention(
+ query_dim=dim,
+ heads=num_attention_heads,
+ dim_head=attention_head_dim,
+ dropout=dropout,
+ bias=attention_bias,
+ cross_attention_dim=cross_attention_dim if only_cross_attention else None,
+ upcast_attention=upcast_attention,
+ )
+
+ # 2. Cross-Attn
+ if cross_attention_dim is not None or double_self_attention:
+ # We currently only use AdaLayerNormZero for self attention where there will only be one attention block.
+ # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during
+ # the second cross attention block.
+ self.norm2 = (
+ AdaLayerNorm(dim, num_embeds_ada_norm)
+ if self.use_ada_layer_norm
+ else nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine)
+ )
+ self.attn2 = Attention(
+ query_dim=dim,
+ cross_attention_dim=cross_attention_dim if not double_self_attention else None,
+ heads=num_attention_heads,
+ dim_head=attention_head_dim,
+ dropout=dropout,
+ bias=attention_bias,
+ upcast_attention=upcast_attention,
+ # scale_qk=False, # uncomment this to not to use flash attention
+ ) # is self-attn if encoder_hidden_states is none
+ else:
+ self.norm2 = None
+ self.attn2 = None
+
+ # 3. Feed-forward
+ self.norm3 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine)
+ self.ff = FeedForward(dim, dropout=dropout, activation_fn=activation_fn, final_dropout=final_dropout)
+
+ # let chunk size default to None
+ self._chunk_size = None
+ self._chunk_dim = 0
+
+ def set_chunk_feed_forward(self, chunk_size: Optional[int], dim: int):
+ # Sets chunk feed-forward
+ self._chunk_size = chunk_size
+ self._chunk_dim = dim
+
+ def forward(
+ self,
+ hidden_states: torch.FloatTensor,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
+ timestep: Optional[torch.LongTensor] = None,
+ cross_attention_kwargs: Dict[str, Any] = None,
+ class_labels: Optional[torch.LongTensor] = None,
+ ):
+ # Notice that normalization is always applied before the real computation in the following blocks.
+ # 1. Self-Attention
+ if self.use_ada_layer_norm:
+ norm_hidden_states = self.norm1(hidden_states, timestep)
+ elif self.use_ada_layer_norm_zero:
+ norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(
+ hidden_states, timestep, class_labels, hidden_dtype=hidden_states.dtype
+ )
+ else:
+ norm_hidden_states = self.norm1(hidden_states)
+
+ cross_attention_kwargs = cross_attention_kwargs if cross_attention_kwargs is not None else {}
+
+ attn_output = self.attn1(
+ norm_hidden_states,
+ encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,
+ attention_mask=encoder_attention_mask if self.only_cross_attention else attention_mask,
+ **cross_attention_kwargs,
+ )
+ if self.use_ada_layer_norm_zero:
+ attn_output = gate_msa.unsqueeze(1) * attn_output
+ hidden_states = attn_output + hidden_states
+
+ # 2. Cross-Attention
+ if self.attn2 is not None:
+ norm_hidden_states = (
+ self.norm2(hidden_states, timestep) if self.use_ada_layer_norm else self.norm2(hidden_states)
+ )
+
+ attn_output = self.attn2(
+ norm_hidden_states,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=encoder_attention_mask,
+ **cross_attention_kwargs,
+ )
+ hidden_states = attn_output + hidden_states
+
+ # 3. Feed-forward
+ norm_hidden_states = self.norm3(hidden_states)
+
+ if self.use_ada_layer_norm_zero:
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
+
+ if self._chunk_size is not None:
+ # "feed_forward_chunk_size" can be used to save memory
+ if norm_hidden_states.shape[self._chunk_dim] % self._chunk_size != 0:
+ raise ValueError(
+ f"`hidden_states` dimension to be chunked: {norm_hidden_states.shape[self._chunk_dim]} has to be divisible by chunk size: {self._chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`."
+ )
+
+ num_chunks = norm_hidden_states.shape[self._chunk_dim] // self._chunk_size
+ ff_output = torch.cat(
+ [self.ff(hid_slice) for hid_slice in norm_hidden_states.chunk(num_chunks, dim=self._chunk_dim)],
+ dim=self._chunk_dim,
+ )
+ else:
+ ff_output = self.ff(norm_hidden_states)
+
+ if self.use_ada_layer_norm_zero:
+ ff_output = gate_mlp.unsqueeze(1) * ff_output
+
+ hidden_states = ff_output + hidden_states
+
+ return hidden_states
+
+
+# ── from s3gen/matcha/decoder.py ───────────────────────────────────────
+
+
+class SinusoidalPosEmb(torch.nn.Module):
+ def __init__(self, dim):
+ super().__init__()
+ self.dim = dim
+ assert self.dim % 2 == 0, "SinusoidalPosEmb requires dim to be even"
+
+ def forward(self, x, scale=1000):
+ if x.ndim < 1:
+ x = x.unsqueeze(0)
+ device = x.device
+ half_dim = self.dim // 2
+ emb = math.log(10000) / (half_dim - 1)
+ emb = torch.exp(torch.arange(half_dim, device=device).float() * -emb)
+ emb = scale * x.unsqueeze(1) * emb.unsqueeze(0)
+ emb = torch.cat((emb.sin(), emb.cos()), dim=-1)
+ return emb
+
+class Block1D(torch.nn.Module):
+ def __init__(self, dim, dim_out, groups=8):
+ super().__init__()
+ self.block = torch.nn.Sequential(
+ torch.nn.Conv1d(dim, dim_out, 3, padding=1),
+ torch.nn.GroupNorm(groups, dim_out),
+ nn.Mish(),
+ )
+
+ def forward(self, x, mask):
+ output = self.block(x * mask)
+ return output * mask
+
+class ResnetBlock1D(torch.nn.Module):
+ def __init__(self, dim, dim_out, time_emb_dim, groups=8):
+ super().__init__()
+ self.mlp = torch.nn.Sequential(nn.Mish(), torch.nn.Linear(time_emb_dim, dim_out))
+
+ self.block1 = Block1D(dim, dim_out, groups=groups)
+ self.block2 = Block1D(dim_out, dim_out, groups=groups)
+
+ self.res_conv = torch.nn.Conv1d(dim, dim_out, 1)
+
+ def forward(self, x, mask, time_emb):
+ h = self.block1(x, mask)
+ h += self.mlp(time_emb).unsqueeze(-1)
+ h = self.block2(h, mask)
+ output = h + self.res_conv(x * mask)
+ return output
+
+class Downsample1D(nn.Module):
+ def __init__(self, dim):
+ super().__init__()
+ self.conv = torch.nn.Conv1d(dim, dim, 3, 2, 1)
+
+ def forward(self, x):
+ return self.conv(x)
+
+class TimestepEmbedding(nn.Module):
+ def __init__(
+ self,
+ in_channels: int,
+ time_embed_dim: int,
+ act_fn: str = "silu",
+ out_dim: int = None,
+ post_act_fn: Optional[str] = None,
+ cond_proj_dim=None,
+ ):
+ super().__init__()
+
+ self.linear_1 = nn.Linear(in_channels, time_embed_dim)
+
+ if cond_proj_dim is not None:
+ self.cond_proj = nn.Linear(cond_proj_dim, in_channels, bias=False)
+ else:
+ self.cond_proj = None
+
+ self.act = get_activation(act_fn)
+
+ if out_dim is not None:
+ time_embed_dim_out = out_dim
+ else:
+ time_embed_dim_out = time_embed_dim
+ self.linear_2 = nn.Linear(time_embed_dim, time_embed_dim_out)
+
+ if post_act_fn is None:
+ self.post_act = None
+ else:
+ self.post_act = get_activation(post_act_fn)
+
+ def forward(self, sample, condition=None):
+ if condition is not None:
+ sample = sample + self.cond_proj(condition)
+ sample = self.linear_1(sample)
+
+ if self.act is not None:
+ sample = self.act(sample)
+
+ sample = self.linear_2(sample)
+
+ if self.post_act is not None:
+ sample = self.post_act(sample)
+ return sample
+
+class MatchaUpsample1D(nn.Module):
+ """A 1D upsampling layer with an optional convolution.
+
+ Parameters:
+ channels (`int`):
+ number of channels in the inputs and outputs.
+ use_conv (`bool`, default `False`):
+ option to use a convolution.
+ use_conv_transpose (`bool`, default `False`):
+ option to use a convolution transpose.
+ out_channels (`int`, optional):
+ number of output channels. Defaults to `channels`.
+ """
+
+ def __init__(self, channels, use_conv=False, use_conv_transpose=True, out_channels=None, name="conv"):
+ super().__init__()
+ self.channels = channels
+ self.out_channels = out_channels or channels
+ self.use_conv = use_conv
+ self.use_conv_transpose = use_conv_transpose
+ self.name = name
+
+ self.conv = None
+ if use_conv_transpose:
+ self.conv = nn.ConvTranspose1d(channels, self.out_channels, 4, 2, 1)
+ elif use_conv:
+ self.conv = nn.Conv1d(self.channels, self.out_channels, 3, padding=1)
+
+ def forward(self, inputs):
+ assert inputs.shape[1] == self.channels
+ if self.use_conv_transpose:
+ return self.conv(inputs)
+
+ outputs = F.interpolate(inputs, scale_factor=2.0, mode="nearest")
+
+ if self.use_conv:
+ outputs = self.conv(outputs)
+
+ return outputs
+
+
+# ── from s3gen/decoder.py ──────────────────────────────────────────────
+
+
+def mask_to_bias(mask: torch.Tensor, dtype: torch.dtype) -> torch.Tensor:
+ assert mask.dtype == torch.bool
+ assert dtype in [torch.float32, torch.bfloat16, torch.float16]
+ mask = mask.to(dtype)
+ # attention mask bias
+ # NOTE(Mddct): torch.finfo jit issues
+ # chunk_masks = (1.0 - chunk_masks) * torch.finfo(dtype).min
+ mask = (1.0 - mask) * -1.0e+10
+ return mask
+
+class Transpose(torch.nn.Module):
+ def __init__(self, dim0: int, dim1: int):
+ super().__init__()
+ self.dim0 = dim0
+ self.dim1 = dim1
+
+ def forward(self, x: torch.Tensor):
+ x = torch.transpose(x, self.dim0, self.dim1)
+ return x
+
+class CausalBlock1D(Block1D):
+ def __init__(self, dim: int, dim_out: int):
+ super(CausalBlock1D, self).__init__(dim, dim_out)
+ self.block = torch.nn.Sequential(
+ CausalConv1d(dim, dim_out, 3),
+ Transpose(1, 2),
+ nn.LayerNorm(dim_out),
+ Transpose(1, 2),
+ nn.Mish(),
+ )
+
+ def forward(self, x: torch.Tensor, mask: torch.Tensor):
+ output = self.block(x * mask)
+ return output * mask
+
+class CausalResnetBlock1D(ResnetBlock1D):
+ def __init__(self, dim: int, dim_out: int, time_emb_dim: int, groups: int = 8):
+ super(CausalResnetBlock1D, self).__init__(dim, dim_out, time_emb_dim, groups)
+ self.block1 = CausalBlock1D(dim, dim_out)
+ self.block2 = CausalBlock1D(dim_out, dim_out)
+
+class CausalConv1d(torch.nn.Conv1d):
+ def __init__(
+ self,
+ in_channels: int,
+ out_channels: int,
+ kernel_size: int,
+ stride: int = 1,
+ dilation: int = 1,
+ groups: int = 1,
+ bias: bool = True,
+ padding_mode: str = 'zeros',
+ device=None,
+ dtype=None
+ ) -> None:
+ super(CausalConv1d, self).__init__(in_channels, out_channels,
+ kernel_size, stride,
+ padding=0, dilation=dilation,
+ groups=groups, bias=bias,
+ padding_mode=padding_mode,
+ device=device, dtype=dtype)
+ assert stride == 1
+ self.causal_padding = (kernel_size - 1, 0)
+
+ def forward(self, x: torch.Tensor):
+ x = F.pad(x, self.causal_padding)
+ x = super(CausalConv1d, self).forward(x)
+ return x
+
+class ConditionalDecoder(nn.Module):
+ def __init__(
+ self,
+ in_channels=320,
+ out_channels=80,
+ causal=True,
+ channels=[256],
+ dropout=0.0,
+ attention_head_dim=64,
+ n_blocks=4,
+ num_mid_blocks=12,
+ num_heads=8,
+ act_fn="gelu",
+ meanflow=False,
+ ):
+ """
+ This decoder requires an input with the same shape of the target. So, if your text content
+ is shorter or longer than the outputs, please re-sampling it before feeding to the decoder.
+ """
+ super().__init__()
+ channels = tuple(channels)
+ self.meanflow = meanflow
+ self.in_channels = in_channels
+ self.out_channels = out_channels
+ self.causal = causal
+ self.time_embeddings = SinusoidalPosEmb(in_channels)
+ time_embed_dim = channels[0] * 4
+ self.time_mlp = TimestepEmbedding(
+ in_channels=in_channels,
+ time_embed_dim=time_embed_dim,
+ act_fn="silu",
+ )
+
+ self.down_blocks = nn.ModuleList([])
+ self.mid_blocks = nn.ModuleList([])
+ self.up_blocks = nn.ModuleList([])
+
+ # NOTE jrm: `static_chunk_size` is missing?
+ self.static_chunk_size = 0
+
+ output_channel = in_channels
+ for i in range(len(channels)): # pylint: disable=consider-using-enumerate
+ input_channel = output_channel
+ output_channel = channels[i]
+ is_last = i == len(channels) - 1
+ resnet = CausalResnetBlock1D(dim=input_channel, dim_out=output_channel, time_emb_dim=time_embed_dim) if self.causal else \
+ ResnetBlock1D(dim=input_channel, dim_out=output_channel, time_emb_dim=time_embed_dim)
+ transformer_blocks = nn.ModuleList(
+ [
+ BasicTransformerBlock(
+ dim=output_channel,
+ num_attention_heads=num_heads,
+ attention_head_dim=attention_head_dim,
+ dropout=dropout,
+ activation_fn=act_fn,
+ )
+ for _ in range(n_blocks)
+ ]
+ )
+ downsample = (
+ Downsample1D(output_channel) if not is_last else
+ CausalConv1d(output_channel, output_channel, 3) if self.causal else nn.Conv1d(output_channel, output_channel, 3, padding=1)
+ )
+ self.down_blocks.append(nn.ModuleList([resnet, transformer_blocks, downsample]))
+
+ for _ in range(num_mid_blocks):
+ input_channel = channels[-1]
+ out_channels = channels[-1]
+ resnet = CausalResnetBlock1D(dim=input_channel, dim_out=output_channel, time_emb_dim=time_embed_dim) if self.causal else \
+ ResnetBlock1D(dim=input_channel, dim_out=output_channel, time_emb_dim=time_embed_dim)
+
+ transformer_blocks = nn.ModuleList(
+ [
+ BasicTransformerBlock(
+ dim=output_channel,
+ num_attention_heads=num_heads,
+ attention_head_dim=attention_head_dim,
+ dropout=dropout,
+ activation_fn=act_fn,
+ )
+ for _ in range(n_blocks)
+ ]
+ )
+
+ self.mid_blocks.append(nn.ModuleList([resnet, transformer_blocks]))
+
+ channels = channels[::-1] + (channels[0],)
+ for i in range(len(channels) - 1):
+ input_channel = channels[i] * 2
+ output_channel = channels[i + 1]
+ is_last = i == len(channels) - 2
+ resnet = CausalResnetBlock1D(
+ dim=input_channel,
+ dim_out=output_channel,
+ time_emb_dim=time_embed_dim,
+ ) if self.causal else ResnetBlock1D(
+ dim=input_channel,
+ dim_out=output_channel,
+ time_emb_dim=time_embed_dim,
+ )
+ transformer_blocks = nn.ModuleList(
+ [
+ BasicTransformerBlock(
+ dim=output_channel,
+ num_attention_heads=num_heads,
+ attention_head_dim=attention_head_dim,
+ dropout=dropout,
+ activation_fn=act_fn,
+ )
+ for _ in range(n_blocks)
+ ]
+ )
+ upsample = (
+ MatchaUpsample1D(output_channel, use_conv_transpose=True)
+ if not is_last
+ else CausalConv1d(output_channel, output_channel, 3) if self.causal else nn.Conv1d(output_channel, output_channel, 3, padding=1)
+ )
+ self.up_blocks.append(nn.ModuleList([resnet, transformer_blocks, upsample]))
+ self.final_block = CausalBlock1D(channels[-1], channels[-1]) if self.causal else Block1D(channels[-1], channels[-1])
+ self.final_proj = nn.Conv1d(channels[-1], self.out_channels, 1)
+ self.initialize_weights()
+ self.time_embed_mixer = None
+ if self.meanflow:
+ self.time_embed_mixer = get_intmeanflow_time_mixer(time_embed_dim)
+
+
+ @property
+ def dtype(self):
+ return self.final_proj.weight.dtype
+
+ def initialize_weights(self):
+ for m in self.modules():
+ if isinstance(m, nn.Conv1d):
+ nn.init.kaiming_normal_(m.weight, nonlinearity="relu")
+ if m.bias is not None:
+ nn.init.constant_(m.bias, 0)
+ elif isinstance(m, nn.GroupNorm):
+ nn.init.constant_(m.weight, 1)
+ nn.init.constant_(m.bias, 0)
+ elif isinstance(m, nn.Linear):
+ nn.init.kaiming_normal_(m.weight, nonlinearity="relu")
+ if m.bias is not None:
+ nn.init.constant_(m.bias, 0)
+
+ def forward(self, x, mask, mu, t, spks=None, cond=None, r=None):
+ """Forward pass of the UNet1DConditional model.
+
+ Args:
+ x: (B, 80, T)
+ mask (_type_)
+ t (_type_): shape (batch_size)
+ spks (_type_, optional) Defaults to None.
+ cond (_type_, optional)
+ r: end time for meanflow mode (shape (1,) tensor)
+
+ Raises:
+ ValueError: _description_
+ ValueError: _description_
+
+ Returns:
+ _type_: _description_
+ """
+ t = self.time_embeddings(t).to(t.dtype)
+ t = self.time_mlp(t)
+
+ if self.meanflow:
+ r = self.time_embeddings(r).to(t.dtype)
+ r = self.time_mlp(r)
+ concat_embed = torch.cat([t, r], dim=1)
+ t = self.time_embed_mixer(concat_embed)
+
+ x = pack([x, mu], "b * t")[0]
+
+ if spks is not None:
+ spks = repeat(spks, "b c -> b c t", t=x.shape[-1])
+ x = pack([x, spks], "b * t")[0]
+ if cond is not None:
+ x = pack([x, cond], "b * t")[0]
+
+ hiddens = []
+ masks = [mask]
+ for resnet, transformer_blocks, downsample in self.down_blocks:
+ mask_down = masks[-1]
+ x = resnet(x, mask_down, t)
+ x = rearrange(x, "b c t -> b t c").contiguous()
+ # attn_mask = torch.matmul(mask_down.transpose(1, 2).contiguous(), mask_down)
+ attn_mask = add_optional_chunk_mask(x, mask_down.bool(), False, False, 0, self.static_chunk_size, -1)
+ attn_mask = mask_to_bias(attn_mask == 1, x.dtype)
+ for transformer_block in transformer_blocks:
+ x = transformer_block(
+ hidden_states=x,
+ attention_mask=attn_mask,
+ timestep=t,
+ )
+ x = rearrange(x, "b t c -> b c t").contiguous()
+ hiddens.append(x) # Save hidden states for skip connections
+ x = downsample(x * mask_down)
+ masks.append(mask_down[:, :, ::2])
+ masks = masks[:-1]
+ mask_mid = masks[-1]
+
+ for resnet, transformer_blocks in self.mid_blocks:
+ x = resnet(x, mask_mid, t)
+ x = rearrange(x, "b c t -> b t c").contiguous()
+ # attn_mask = torch.matmul(mask_mid.transpose(1, 2).contiguous(), mask_mid)
+ attn_mask = add_optional_chunk_mask(x, mask_mid.bool(), False, False, 0, self.static_chunk_size, -1)
+ attn_mask = mask_to_bias(attn_mask == 1, x.dtype)
+ for transformer_block in transformer_blocks:
+ x = transformer_block(
+ hidden_states=x,
+ attention_mask=attn_mask,
+ timestep=t,
+ )
+ x = rearrange(x, "b t c -> b c t").contiguous()
+
+ for resnet, transformer_blocks, upsample in self.up_blocks:
+ mask_up = masks.pop()
+ skip = hiddens.pop()
+ x = pack([x[:, :, :skip.shape[-1]], skip], "b * t")[0]
+ x = resnet(x, mask_up, t)
+ x = rearrange(x, "b c t -> b t c").contiguous()
+ # attn_mask = torch.matmul(mask_up.transpose(1, 2).contiguous(), mask_up)
+ attn_mask = add_optional_chunk_mask(x, mask_up.bool(), False, False, 0, self.static_chunk_size, -1)
+ attn_mask = mask_to_bias(attn_mask == 1, x.dtype)
+ for transformer_block in transformer_blocks:
+ x = transformer_block(
+ hidden_states=x,
+ attention_mask=attn_mask,
+ timestep=t,
+ )
+ x = rearrange(x, "b t c -> b c t").contiguous()
+ x = upsample(x * mask_up)
+ x = self.final_block(x, mask_up)
+ output = self.final_proj(x * mask_up)
+ return output * mask
+
+
+# ── from s3gen/matcha/flow_matching.py ─────────────────────────────────
+
+
+class BASECFM(torch.nn.Module, ABC):
+ def __init__(
+ self,
+ n_feats,
+ cfm_params,
+ n_spks=1,
+ spk_emb_dim=128,
+ ):
+ super().__init__()
+ self.n_feats = n_feats
+ self.n_spks = n_spks
+ self.spk_emb_dim = spk_emb_dim
+ self.solver = cfm_params.solver
+ if hasattr(cfm_params, "sigma_min"):
+ self.sigma_min = cfm_params.sigma_min
+ else:
+ self.sigma_min = 1e-4
+
+ self.estimator = None
+
+ @torch.inference_mode()
+ def forward(self, mu, mask, n_timesteps, temperature=1.0, spks=None, cond=None):
+ """Forward diffusion
+
+ Args:
+ mu (torch.Tensor): output of encoder
+ shape: (batch_size, n_feats, mel_timesteps)
+ mask (torch.Tensor): output_mask
+ shape: (batch_size, 1, mel_timesteps)
+ n_timesteps (int): number of diffusion steps
+ temperature (float, optional): temperature for scaling noise. Defaults to 1.0.
+ spks (torch.Tensor, optional): speaker ids. Defaults to None.
+ shape: (batch_size, spk_emb_dim)
+ cond: Not used but kept for future purposes
+
+ Returns:
+ sample: generated mel-spectrogram
+ shape: (batch_size, n_feats, mel_timesteps)
+ """
+ z = torch.randn_like(mu) * temperature
+ t_span = torch.linspace(0, 1, n_timesteps + 1, device=mu.device)
+ return self.solve_euler(z, t_span=t_span, mu=mu, mask=mask, spks=spks, cond=cond)
+
+ def solve_euler(self, x, t_span, mu, mask, spks, cond):
+ """
+ Fixed euler solver for ODEs.
+ Args:
+ x (torch.Tensor): random noise
+ t_span (torch.Tensor): n_timesteps interpolated
+ shape: (n_timesteps + 1,)
+ mu (torch.Tensor): output of encoder
+ shape: (batch_size, n_feats, mel_timesteps)
+ mask (torch.Tensor): output_mask
+ shape: (batch_size, 1, mel_timesteps)
+ spks (torch.Tensor, optional): speaker ids. Defaults to None.
+ shape: (batch_size, spk_emb_dim)
+ cond: Not used but kept for future purposes
+ """
+ t, _, dt = t_span[0], t_span[-1], t_span[1] - t_span[0]
+
+ # I am storing this because I can later plot it by putting a debugger here and saving it to a file
+ # Or in future might add like a return_all_steps flag
+ sol = []
+
+ for step in range(1, len(t_span)):
+ dphi_dt = self.estimator(x, mask, mu, t, spks, cond)
+
+ x = x + dt * dphi_dt
+ t = t + dt
+ sol.append(x)
+ if step < len(t_span) - 1:
+ dt = t_span[step + 1] - t
+
+ return sol[-1]
+
+ def compute_loss(self, x1, mask, mu, spks=None, cond=None):
+ """Computes diffusion loss
+
+ Args:
+ x1 (torch.Tensor): Target
+ shape: (batch_size, n_feats, mel_timesteps)
+ mask (torch.Tensor): target mask
+ shape: (batch_size, 1, mel_timesteps)
+ mu (torch.Tensor): output of encoder
+ shape: (batch_size, n_feats, mel_timesteps)
+ spks (torch.Tensor, optional): speaker embedding. Defaults to None.
+ shape: (batch_size, spk_emb_dim)
+
+ Returns:
+ loss: conditional flow matching loss
+ y: conditional flow
+ shape: (batch_size, n_feats, mel_timesteps)
+ """
+ b, _, t = mu.shape
+
+ # random timestep
+ t = torch.rand([b, 1, 1], device=mu.device, dtype=mu.dtype)
+ # sample noise p(x_0)
+ z = torch.randn_like(x1)
+
+ y = (1 - (1 - self.sigma_min) * t) * z + t * x1
+ u = x1 - (1 - self.sigma_min) * z
+
+ loss = F.mse_loss(self.estimator(y, mask, mu, t.squeeze(), spks), u, reduction="sum") / (
+ torch.sum(mask) * u.shape[1]
+ )
+ return loss, y
+
+
+# ── from s3gen/flow_matching.py ────────────────────────────────────────
+
+
+def cast_all(*args, dtype):
+ return [a if (not a.dtype.is_floating_point) or a.dtype == dtype else a.to(dtype) for a in args]
+
+class ConditionalCFM(BASECFM):
+ def __init__(self, in_channels, cfm_params, n_spks=1, spk_emb_dim=64, estimator: torch.nn.Module = None):
+ super().__init__(
+ n_feats=in_channels,
+ cfm_params=cfm_params,
+ n_spks=n_spks,
+ spk_emb_dim=spk_emb_dim,
+ )
+ self.t_scheduler = cfm_params.t_scheduler
+ self.training_cfg_rate = cfm_params.training_cfg_rate
+ self.inference_cfg_rate = cfm_params.inference_cfg_rate
+ in_channels = in_channels + (spk_emb_dim if n_spks > 0 else 0)
+ # Just change the architecture of the estimator here
+ self.estimator = estimator
+
+ @torch.inference_mode()
+ def forward(self, mu, mask, n_timesteps, temperature=1.0, spks=None, cond=None, prompt_len=0, flow_cache=torch.zeros(1, 80, 0, 2)):
+ """Forward diffusion
+
+ Args:
+ mu (torch.Tensor): output of encoder
+ shape: (batch_size, n_feats, mel_timesteps)
+ mask (torch.Tensor): output_mask
+ shape: (batch_size, 1, mel_timesteps)
+ n_timesteps (int): number of diffusion steps
+ temperature (float, optional): temperature for scaling noise. Defaults to 1.0.
+ spks (torch.Tensor, optional): speaker ids. Defaults to None.
+ shape: (batch_size, spk_emb_dim)
+ cond: Not used but kept for future purposes
+
+ Returns:
+ sample: generated mel-spectrogram
+ shape: (batch_size, n_feats, mel_timesteps)
+ """
+
+ raise NotImplementedError("unused, needs updating for meanflow model")
+
+ z = torch.randn_like(mu).to(mu.device).to(mu.dtype) * temperature
+ cache_size = flow_cache.shape[2]
+ # fix prompt and overlap part mu and z
+ if cache_size != 0:
+ z[:, :, :cache_size] = flow_cache[:, :, :, 0]
+ mu[:, :, :cache_size] = flow_cache[:, :, :, 1]
+ z_cache = torch.concat([z[:, :, :prompt_len], z[:, :, -34:]], dim=2)
+ mu_cache = torch.concat([mu[:, :, :prompt_len], mu[:, :, -34:]], dim=2)
+ flow_cache = torch.stack([z_cache, mu_cache], dim=-1)
+
+ t_span = torch.linspace(0, 1, n_timesteps + 1, device=mu.device, dtype=mu.dtype)
+ if self.t_scheduler == 'cosine':
+ t_span = 1 - torch.cos(t_span * 0.5 * torch.pi)
+ return self.solve_euler(z, t_span=t_span, mu=mu, mask=mask, spks=spks, cond=cond), flow_cache
+
+ def solve_euler(self, x, t_span, mu, mask, spks, cond, meanflow=False):
+ """
+ Fixed euler solver for ODEs.
+ Args:
+ x (torch.Tensor): random noise
+ t_span (torch.Tensor): n_timesteps interpolated
+ shape: (n_timesteps + 1,)
+ mu (torch.Tensor): output of encoder
+ shape: (batch_size, n_feats, mel_timesteps)
+ mask (torch.Tensor): output_mask
+ shape: (batch_size, 1, mel_timesteps)
+ spks (torch.Tensor, optional): speaker ids. Defaults to None.
+ shape: (batch_size, spk_emb_dim)
+ cond: Not used but kept for future purposes
+ meanflow: meanflow mode
+ """
+ in_dtype = x.dtype
+ x, t_span, mu, mask, spks, cond = cast_all(x, t_span, mu, mask, spks, cond, dtype=self.estimator.dtype)
+
+ # Duplicated batch dims are for CFG
+ # Do not use concat, it may cause memory format changed and trt infer with wrong results!
+ B, T = mu.size(0), x.size(2)
+ x_in = torch.zeros([2 * B, 80, T], device=x.device, dtype=x.dtype)
+ mask_in = torch.zeros([2 * B, 1, T], device=x.device, dtype=x.dtype)
+ mu_in = torch.zeros([2 * B, 80, T], device=x.device, dtype=x.dtype)
+ t_in = torch.zeros([2 * B ], device=x.device, dtype=x.dtype)
+ spks_in = torch.zeros([2 * B, 80 ], device=x.device, dtype=x.dtype)
+ cond_in = torch.zeros([2 * B, 80, T], device=x.device, dtype=x.dtype)
+ r_in = torch.zeros([2 * B ], device=x.device, dtype=x.dtype) # (only used for meanflow)
+
+ for t, r in zip(t_span[:-1], t_span[1:]):
+ t = t.unsqueeze(dim=0)
+ r = r.unsqueeze(dim=0)
+ # Shapes:
+ # x_in ( 2B, 80, T )
+ # mask_in ( 2B, 1, T )
+ # mu_in ( 2B, 80, T )
+ # t_in ( 2B, )
+ # spks_in ( 2B, 80, )
+ # cond_in ( 2B, 80, T )
+ # r_in ( 2B, )
+ # x ( B, 80, T )
+ # mask ( B, 1, T )
+ # mu ( B, 80, T )
+ # t ( B, )
+ # spks ( B, 80, )
+ # cond ( B, 80, T )
+ # r ( B, )
+
+ x_in[:B] = x_in[B:] = x
+ mask_in[:B] = mask_in[B:] = mask
+ mu_in[:B] = mu
+ t_in[:B] = t_in[B:] = t
+ spks_in[:B] = spks
+ cond_in[:B] = cond
+ r_in[:B] = r_in[B:] = r # (only used for meanflow)
+ dxdt = self.estimator.forward(
+ x=x_in, mask=mask_in, mu=mu_in, t=t_in, spks=spks_in, cond=cond_in,
+ r=r_in if meanflow else None,
+ )
+ dxdt, cfg_dxdt = torch.split(dxdt, [B, B], dim=0)
+ dxdt = ((1.0 + self.inference_cfg_rate) * dxdt - self.inference_cfg_rate * cfg_dxdt)
+ dt = r - t
+ x = x + dt * dxdt
+
+
+
+ return x.to(in_dtype)
+
+ def compute_loss(self, x1, mask, mu, spks=None, cond=None):
+ """Computes diffusion loss
+
+ Args:
+ x1 (torch.Tensor): Target
+ shape: (batch_size, n_feats, mel_timesteps)
+ mask (torch.Tensor): target mask
+ shape: (batch_size, 1, mel_timesteps)
+ mu (torch.Tensor): output of encoder
+ shape: (batch_size, n_feats, mel_timesteps)
+ spks (torch.Tensor, optional): speaker embedding. Defaults to None.
+ shape: (batch_size, spk_emb_dim)
+
+ Returns:
+ loss: conditional flow matching loss
+ y: conditional flow
+ shape: (batch_size, n_feats, mel_timesteps)
+ """
+ b, _, t = mu.shape
+
+ # random timestep
+ t = torch.rand([b, 1, 1], device=mu.device, dtype=mu.dtype)
+ if self.t_scheduler == 'cosine':
+ t = 1 - torch.cos(t * 0.5 * torch.pi)
+ # sample noise p(x_0)
+ z = torch.randn_like(x1)
+
+ y = (1 - (1 - self.sigma_min) * t) * z + t * x1
+ u = x1 - (1 - self.sigma_min) * z
+
+ # during training, we randomly drop condition to trade off mode coverage and sample fidelity
+ if self.training_cfg_rate > 0:
+ cfg_mask = torch.rand(b, device=x1.device) > self.training_cfg_rate
+ mu = mu * cfg_mask.view(-1, 1, 1)
+ spks = spks * cfg_mask.view(-1, 1)
+ cond = cond * cfg_mask.view(-1, 1, 1)
+
+ pred = self.estimator(y, mask, mu, t.squeeze(), spks, cond)
+ loss = F.mse_loss(pred * mask, u * mask, reduction="sum") / (torch.sum(mask) * u.shape[1])
+ return loss, y
+
+class CausalConditionalCFM(ConditionalCFM):
+ def __init__(self, in_channels=240, cfm_params=CFM_PARAMS, n_spks=1, spk_emb_dim=80, estimator=None):
+ super().__init__(in_channels, cfm_params, n_spks, spk_emb_dim, estimator)
+ # TODO: BAD BAD IDEA - IT'LL MESS UP DISTILLATION - SETTING TO NONE
+ self.rand_noise = None
+
+ @torch.inference_mode()
+ def forward(self, mu, mask, n_timesteps, temperature=1.0, spks=None, cond=None, noised_mels=None, meanflow=False):
+ """Forward diffusion
+
+ Args:
+ mu (torch.Tensor): output of encoder
+ shape: (batch_size, n_feats, mel_timesteps)
+ mask (torch.Tensor): output_mask
+ shape: (batch_size, 1, mel_timesteps)
+ n_timesteps (int): number of diffusion steps
+ temperature (float, optional): temperature for scaling noise. Defaults to 1.0.
+ spks (torch.Tensor, optional): speaker ids. Defaults to None.
+ shape: (batch_size, spk_emb_dim)
+ cond: Not used but kept for future purposes
+ noised_mels: gt mels noised a time t
+ Returns:
+ sample: generated mel-spectrogram
+ shape: (batch_size, n_feats, mel_timesteps)
+ """
+
+ B = mu.size(0)
+ z = torch.randn_like(mu)
+
+ if noised_mels is not None:
+ prompt_len = mu.size(2) - noised_mels.size(2)
+ z[..., prompt_len:] = noised_mels
+
+ # time steps for reverse diffusion
+ t_span = torch.linspace(0, 1, n_timesteps + 1, device=mu.device, dtype=mu.dtype)
+ if (not meanflow) and (self.t_scheduler == 'cosine'):
+ t_span = 1 - torch.cos(t_span * 0.5 * torch.pi)
+
+ # NOTE: right now, the only meanflow models are also distilled models, which don't need CFG
+ # because they were distilled with CFG outputs. We would need to add another hparam and
+ # change the conditional logic here if we want to use CFG inference with a meanflow model.
+ if meanflow:
+ return self.basic_euler(z, t_span=t_span, mu=mu, mask=mask, spks=spks, cond=cond), None
+
+ return self.solve_euler(z, t_span=t_span, mu=mu, mask=mask, spks=spks, cond=cond, meanflow=meanflow), None
+
+ def basic_euler(self, x, t_span, mu, mask, spks, cond):
+ in_dtype = x.dtype
+ x, t_span, mu, mask, spks, cond = cast_all(x, t_span, mu, mask, spks, cond, dtype=self.estimator.dtype)
+
+ pass
+ for t, r in zip(t_span[..., :-1], t_span[..., 1:]):
+ t, r = t[None], r[None]
+ dxdt = self.estimator.forward(x, mask=mask, mu=mu, t=t, spks=spks, cond=cond, r=r)
+ dt = r - t
+ x = x + dt * dxdt
+
+ return x.to(in_dtype)
+
+
+# ── from s3gen/f0_predictor.py ─────────────────────────────────────────
+
+
+class ConvRNNF0Predictor(nn.Module):
+ def __init__(self,
+ num_class: int = 1,
+ in_channels: int = 80,
+ cond_channels: int = 512
+ ):
+ super().__init__()
+
+ self.num_class = num_class
+ self.condnet = nn.Sequential(
+ weight_norm(
+ nn.Conv1d(in_channels, cond_channels, kernel_size=3, padding=1)
+ ),
+ nn.ELU(),
+ weight_norm(
+ nn.Conv1d(cond_channels, cond_channels, kernel_size=3, padding=1)
+ ),
+ nn.ELU(),
+ weight_norm(
+ nn.Conv1d(cond_channels, cond_channels, kernel_size=3, padding=1)
+ ),
+ nn.ELU(),
+ weight_norm(
+ nn.Conv1d(cond_channels, cond_channels, kernel_size=3, padding=1)
+ ),
+ nn.ELU(),
+ weight_norm(
+ nn.Conv1d(cond_channels, cond_channels, kernel_size=3, padding=1)
+ ),
+ nn.ELU(),
+ )
+ self.classifier = nn.Linear(in_features=cond_channels, out_features=self.num_class)
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ x = self.condnet(x)
+ x = x.transpose(1, 2)
+ return torch.abs(self.classifier(x).squeeze(-1))
+
+
+# ── from s3gen/hifigan.py ──────────────────────────────────────────────
+
+
+"""HIFI-GAN"""
+
+class Snake(nn.Module):
+ '''
+ Implementation of a sine-based periodic activation function
+ Shape:
+ - Input: (B, C, T)
+ - Output: (B, C, T), same shape as the input
+ Parameters:
+ - alpha - trainable parameter
+ References:
+ - This activation function is from this paper by Liu Ziyin, Tilman Hartwig, Masahito Ueda:
+ https://arxiv.org/abs/2006.08195
+ Examples:
+ >>> a1 = snake(256)
+ >>> x = torch.randn(256)
+ >>> x = a1(x)
+ '''
+ def __init__(self, in_features, alpha=1.0, alpha_trainable=True, alpha_logscale=False):
+ '''
+ Initialization.
+ INPUT:
+ - in_features: shape of the input
+ - alpha: trainable parameter
+ alpha is initialized to 1 by default, higher values = higher-frequency.
+ alpha will be trained along with the rest of your model.
+ '''
+ super(Snake, self).__init__()
+ self.in_features = in_features
+
+ # initialize alpha
+ self.alpha_logscale = alpha_logscale
+ if self.alpha_logscale: # log scale alphas initialized to zeros
+ self.alpha = Parameter(torch.zeros(in_features) * alpha)
+ else: # linear scale alphas initialized to ones
+ self.alpha = Parameter(torch.ones(in_features) * alpha)
+
+ self.alpha.requires_grad = alpha_trainable
+
+ self.no_div_by_zero = 0.000000001
+
+ def forward(self, x):
+ '''
+ Forward pass of the function.
+ Applies the function to the input elementwise.
+ Snake ∶= x + 1/a * sin^2 (xa)
+ '''
+ alpha = self.alpha.unsqueeze(0).unsqueeze(-1) # line up with x to [B, C, T]
+ if self.alpha_logscale:
+ alpha = torch.exp(alpha)
+ x = x + (1.0 / (alpha + self.no_div_by_zero)) * pow(sin(x * alpha), 2)
+
+ return x
+
+def get_padding(kernel_size, dilation=1):
+ return int((kernel_size * dilation - dilation) / 2)
+
+def init_weights(m, mean=0.0, std=0.01):
+ classname = m.__class__.__name__
+ if classname.find("Conv") != -1:
+ m.weight.data.normal_(mean, std)
+
+"""hifigan based generator implementation.
+
+This code is modified from https://github.com/jik876/hifi-gan
+ ,https://github.com/kan-bayashi/ParallelWaveGAN and
+ https://github.com/NVIDIA/BigVGAN
+
+"""
+
+class ResBlock(torch.nn.Module):
+ """Residual block module in HiFiGAN/BigVGAN."""
+ def __init__(
+ self,
+ channels: int = 512,
+ kernel_size: int = 3,
+ dilations: List[int] = [1, 3, 5],
+ ):
+ super(ResBlock, self).__init__()
+ self.convs1 = nn.ModuleList()
+ self.convs2 = nn.ModuleList()
+
+ for dilation in dilations:
+ self.convs1.append(
+ weight_norm(
+ Conv1d(
+ channels,
+ channels,
+ kernel_size,
+ 1,
+ dilation=dilation,
+ padding=get_padding(kernel_size, dilation)
+ )
+ )
+ )
+ self.convs2.append(
+ weight_norm(
+ Conv1d(
+ channels,
+ channels,
+ kernel_size,
+ 1,
+ dilation=1,
+ padding=get_padding(kernel_size, 1)
+ )
+ )
+ )
+ self.convs1.apply(init_weights)
+ self.convs2.apply(init_weights)
+ self.activations1 = nn.ModuleList([
+ Snake(channels, alpha_logscale=False)
+ for _ in range(len(self.convs1))
+ ])
+ self.activations2 = nn.ModuleList([
+ Snake(channels, alpha_logscale=False)
+ for _ in range(len(self.convs2))
+ ])
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ for idx in range(len(self.convs1)):
+ xt = self.activations1[idx](x)
+ xt = self.convs1[idx](xt)
+ xt = self.activations2[idx](xt)
+ xt = self.convs2[idx](xt)
+ x = xt + x
+ return x
+
+ def remove_weight_norm(self):
+ for idx in range(len(self.convs1)):
+ remove_weight_norm(self.convs1[idx])
+ remove_weight_norm(self.convs2[idx])
+
+class SineGen(torch.nn.Module):
+ """ Definition of sine generator
+ SineGen(samp_rate, harmonic_num = 0,
+ sine_amp = 0.1, noise_std = 0.003,
+ voiced_threshold = 0,
+ flag_for_pulse=False)
+ samp_rate: sampling rate in Hz
+ harmonic_num: number of harmonic overtones (default 0)
+ sine_amp: amplitude of sine-wavefrom (default 0.1)
+ noise_std: std of Gaussian noise (default 0.003)
+ voiced_thoreshold: F0 threshold for U/V classification (default 0)
+ flag_for_pulse: this SinGen is used inside PulseGen (default False)
+ Note: when flag_for_pulse is True, the first time step of a voiced
+ segment is always sin(np.pi) or cos(0)
+ """
+
+ def __init__(self, samp_rate, harmonic_num=0,
+ sine_amp=0.1, noise_std=0.003,
+ voiced_threshold=0):
+ super(SineGen, self).__init__()
+ self.sine_amp = sine_amp
+ self.noise_std = noise_std
+ self.harmonic_num = harmonic_num
+ self.sampling_rate = samp_rate
+ self.voiced_threshold = voiced_threshold
+
+ def _f02uv(self, f0):
+ # generate uv signal
+ uv = (f0 > self.voiced_threshold).type(torch.float32)
+ return uv
+
+ @torch.no_grad()
+ def forward(self, f0):
+ """
+ :param f0: [B, 1, sample_len], Hz
+ :return: [B, 1, sample_len]
+ """
+
+ F_mat = torch.zeros((f0.size(0), self.harmonic_num + 1, f0.size(-1))).to(f0.device)
+ for i in range(self.harmonic_num + 1):
+ F_mat[:, i: i + 1, :] = f0 * (i + 1) / self.sampling_rate
+
+ theta_mat = 2 * np.pi * (torch.cumsum(F_mat, dim=-1) % 1)
+ u_dist = Uniform(low=-np.pi, high=np.pi)
+ phase_vec = u_dist.sample(sample_shape=(f0.size(0), self.harmonic_num + 1, 1)).to(F_mat.device)
+ phase_vec[:, 0, :] = 0
+
+ # generate sine waveforms
+ sine_waves = self.sine_amp * torch.sin(theta_mat + phase_vec)
+
+ # generate uv signal
+ uv = self._f02uv(f0)
+
+ # noise: for unvoiced should be similar to sine_amp
+ # std = self.sine_amp/3 -> max value ~ self.sine_amp
+ # . for voiced regions is self.noise_std
+ noise_amp = uv * self.noise_std + (1 - uv) * self.sine_amp / 3
+ noise = noise_amp * torch.randn_like(sine_waves)
+
+ # first: set the unvoiced part to 0 by uv
+ # then: additive noise
+ sine_waves = sine_waves * uv + noise
+ return sine_waves, uv, noise
+
+class SourceModuleHnNSF(torch.nn.Module):
+ """ SourceModule for hn-nsf
+ SourceModule(sampling_rate, harmonic_num=0, sine_amp=0.1,
+ add_noise_std=0.003, voiced_threshod=0)
+ sampling_rate: sampling_rate in Hz
+ harmonic_num: number of harmonic above F0 (default: 0)
+ sine_amp: amplitude of sine source signal (default: 0.1)
+ add_noise_std: std of additive Gaussian noise (default: 0.003)
+ note that amplitude of noise in unvoiced is decided
+ by sine_amp
+ voiced_threshold: threhold to set U/V given F0 (default: 0)
+ Sine_source, noise_source = SourceModuleHnNSF(F0_sampled)
+ F0_sampled (batchsize, length, 1)
+ Sine_source (batchsize, length, 1)
+ noise_source (batchsize, length 1)
+ uv (batchsize, length, 1)
+ """
+
+ def __init__(self, sampling_rate, upsample_scale, harmonic_num=0, sine_amp=0.1,
+ add_noise_std=0.003, voiced_threshod=0):
+ super(SourceModuleHnNSF, self).__init__()
+
+ self.sine_amp = sine_amp
+ self.noise_std = add_noise_std
+
+ # to produce sine waveforms
+ self.l_sin_gen = SineGen(sampling_rate, harmonic_num,
+ sine_amp, add_noise_std, voiced_threshod)
+
+ # to merge source harmonics into a single excitation
+ self.l_linear = torch.nn.Linear(harmonic_num + 1, 1)
+ self.l_tanh = torch.nn.Tanh()
+
+ def forward(self, x):
+ """
+ Sine_source, noise_source = SourceModuleHnNSF(F0_sampled)
+ F0_sampled (batchsize, length, 1)
+ Sine_source (batchsize, length, 1)
+ noise_source (batchsize, length 1)
+ """
+ # source for harmonic branch
+ with torch.no_grad():
+ sine_wavs, uv, _ = self.l_sin_gen(x.transpose(1, 2))
+ sine_wavs = sine_wavs.transpose(1, 2)
+ uv = uv.transpose(1, 2)
+ sine_merge = self.l_tanh(self.l_linear(sine_wavs))
+
+ # source for noise branch, in the same shape as uv
+ noise = torch.randn_like(uv) * self.sine_amp / 3
+ return sine_merge, noise, uv
+
+class HiFTGenerator(nn.Module):
+ """
+ HiFTNet Generator: Neural Source Filter + ISTFTNet
+ https://arxiv.org/abs/2309.09493
+ """
+ def __init__(
+ self,
+ in_channels: int = 80,
+ base_channels: int = 512,
+ nb_harmonics: int = 8,
+ sampling_rate: int = 22050,
+ nsf_alpha: float = 0.1,
+ nsf_sigma: float = 0.003,
+ nsf_voiced_threshold: float = 10,
+ upsample_rates: List[int] = [8, 8],
+ upsample_kernel_sizes: List[int] = [16, 16],
+ istft_params: Dict[str, int] = {"n_fft": 16, "hop_len": 4},
+ resblock_kernel_sizes: List[int] = [3, 7, 11],
+ resblock_dilation_sizes: List[List[int]] = [[1, 3, 5], [1, 3, 5], [1, 3, 5]],
+ source_resblock_kernel_sizes: List[int] = [7, 11],
+ source_resblock_dilation_sizes: List[List[int]] = [[1, 3, 5], [1, 3, 5]],
+ lrelu_slope: float = 0.1,
+ audio_limit: float = 0.99,
+ f0_predictor: torch.nn.Module = None,
+ ):
+ super(HiFTGenerator, self).__init__()
+
+ self.out_channels = 1
+ self.nb_harmonics = nb_harmonics
+ self.sampling_rate = sampling_rate
+ self.istft_params = istft_params
+ self.lrelu_slope = lrelu_slope
+ self.audio_limit = audio_limit
+
+ self.num_kernels = len(resblock_kernel_sizes)
+ self.num_upsamples = len(upsample_rates)
+ self.m_source = SourceModuleHnNSF(
+ sampling_rate=sampling_rate,
+ upsample_scale=np.prod(upsample_rates) * istft_params["hop_len"],
+ harmonic_num=nb_harmonics,
+ sine_amp=nsf_alpha,
+ add_noise_std=nsf_sigma,
+ voiced_threshod=nsf_voiced_threshold)
+ self.f0_upsamp = torch.nn.Upsample(scale_factor=np.prod(upsample_rates) * istft_params["hop_len"])
+
+ self.conv_pre = weight_norm(
+ Conv1d(in_channels, base_channels, 7, 1, padding=3)
+ )
+
+ # Up
+ self.ups = nn.ModuleList()
+ for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
+ self.ups.append(
+ weight_norm(
+ ConvTranspose1d(
+ base_channels // (2**i),
+ base_channels // (2**(i + 1)),
+ k,
+ u,
+ padding=(k - u) // 2,
+ )
+ )
+ )
+
+ # Down
+ self.source_downs = nn.ModuleList()
+ self.source_resblocks = nn.ModuleList()
+ downsample_rates = [1] + upsample_rates[::-1][:-1]
+ downsample_cum_rates = np.cumprod(downsample_rates)
+ for i, (u, k, d) in enumerate(zip(downsample_cum_rates[::-1], source_resblock_kernel_sizes, source_resblock_dilation_sizes)):
+ if u == 1:
+ self.source_downs.append(
+ Conv1d(istft_params["n_fft"] + 2, base_channels // (2 ** (i + 1)), 1, 1)
+ )
+ else:
+ self.source_downs.append(
+ Conv1d(istft_params["n_fft"] + 2, base_channels // (2 ** (i + 1)), u * 2, u, padding=(u // 2))
+ )
+
+ self.source_resblocks.append(
+ ResBlock(base_channels // (2 ** (i + 1)), k, d)
+ )
+
+ self.resblocks = nn.ModuleList()
+ for i in range(len(self.ups)):
+ ch = base_channels // (2**(i + 1))
+ for _, (k, d) in enumerate(zip(resblock_kernel_sizes, resblock_dilation_sizes)):
+ self.resblocks.append(ResBlock(ch, k, d))
+
+ self.conv_post = weight_norm(Conv1d(ch, istft_params["n_fft"] + 2, 7, 1, padding=3))
+ self.ups.apply(init_weights)
+ self.conv_post.apply(init_weights)
+ self.reflection_pad = nn.ReflectionPad1d((1, 0))
+ self.stft_window = torch.from_numpy(get_window("hann", istft_params["n_fft"], fftbins=True).astype(np.float32))
+ self.f0_predictor = f0_predictor
+
+ def remove_weight_norm(self):
+ logger.debug('Removing weight norm...')
+ for l in self.ups:
+ remove_weight_norm(l)
+ for l in self.resblocks:
+ l.remove_weight_norm()
+ remove_weight_norm(self.conv_pre)
+ remove_weight_norm(self.conv_post)
+ self.m_source.remove_weight_norm()
+ for l in self.source_downs:
+ remove_weight_norm(l)
+ for l in self.source_resblocks:
+ l.remove_weight_norm()
+
+ def _stft(self, x):
+ spec = torch.stft(
+ x,
+ self.istft_params["n_fft"], self.istft_params["hop_len"], self.istft_params["n_fft"], window=self.stft_window.to(x.device),
+ return_complex=True)
+ spec = torch.view_as_real(spec) # [B, F, TT, 2]
+ return spec[..., 0], spec[..., 1]
+
+ def _istft(self, magnitude, phase):
+ magnitude = torch.clip(magnitude, max=1e2)
+ real = magnitude * torch.cos(phase)
+ img = magnitude * torch.sin(phase)
+ inverse_transform = torch.istft(torch.complex(real, img), self.istft_params["n_fft"], self.istft_params["hop_len"],
+ self.istft_params["n_fft"], window=self.stft_window.to(magnitude.device))
+ return inverse_transform
+
+ def decode(self, x: torch.Tensor, s: torch.Tensor = torch.zeros(1, 1, 0)) -> torch.Tensor:
+ s_stft_real, s_stft_imag = self._stft(s.squeeze(1))
+ s_stft = torch.cat([s_stft_real, s_stft_imag], dim=1)
+
+ x = self.conv_pre(x)
+ for i in range(self.num_upsamples):
+ x = F.leaky_relu(x, self.lrelu_slope)
+ x = self.ups[i](x)
+
+ if i == self.num_upsamples - 1:
+ x = self.reflection_pad(x)
+
+ # fusion
+ si = self.source_downs[i](s_stft)
+ si = self.source_resblocks[i](si)
+ x = x + si
+
+ xs = None
+ for j in range(self.num_kernels):
+ if xs is None:
+ xs = self.resblocks[i * self.num_kernels + j](x)
+ else:
+ xs += self.resblocks[i * self.num_kernels + j](x)
+ x = xs / self.num_kernels
+
+ x = F.leaky_relu(x)
+ x = self.conv_post(x)
+ magnitude = torch.exp(x[:, :self.istft_params["n_fft"] // 2 + 1, :])
+ phase = torch.sin(x[:, self.istft_params["n_fft"] // 2 + 1:, :]) # actually, sin is redundancy
+
+ x = self._istft(magnitude, phase)
+ x = torch.clamp(x, -self.audio_limit, self.audio_limit)
+ return x
+
+ def forward(
+ self,
+ batch: dict,
+ device: torch.device,
+ ) -> Dict[str, Optional[torch.Tensor]]:
+ speech_feat = batch['speech_feat'].transpose(1, 2).to(device)
+ # mel->f0
+ f0 = self.f0_predictor(speech_feat)
+ # f0->source
+ s = self.f0_upsamp(f0[:, None]).transpose(1, 2) # bs,n,t
+ s, _, _ = self.m_source(s)
+ s = s.transpose(1, 2)
+ # mel+source->speech
+ generated_speech = self.decode(x=speech_feat, s=s)
+ return generated_speech, f0
+
+ @torch.inference_mode()
+ def inference(self, speech_feat: torch.Tensor, cache_source: torch.Tensor = torch.zeros(1, 1, 0)) -> torch.Tensor:
+ # mel->f0
+ f0 = self.f0_predictor(speech_feat)
+ # f0->source
+ s = self.f0_upsamp(f0[:, None]).transpose(1, 2) # bs,n,t
+ s, _, _ = self.m_source(s)
+ s = s.transpose(1, 2)
+ # use cache_source to avoid glitch
+ if cache_source.shape[2] != 0:
+ s[:, :, :cache_source.shape[2]] = cache_source
+ generated_speech = self.decode(x=speech_feat, s=s)
+ return generated_speech, s
+
+
+# ── from s3gen/xvector.py ──────────────────────────────────────────────
+
+
+def pad_list(xs, pad_value):
+ """Perform padding for the list of tensors.
+
+ Args:
+ xs (List): List of Tensors [(T_1, `*`), (T_2, `*`), ..., (T_B, `*`)].
+ pad_value (float): Value for padding.
+
+ Returns:
+ Tensor: Padded tensor (B, Tmax, `*`).
+
+ Examples:
+ >>> x = [torch.ones(4), torch.ones(2), torch.ones(1)]
+ >>> x
+ [tensor([1., 1., 1., 1.]), tensor([1., 1.]), tensor([1.])]
+ >>> pad_list(x, 0)
+ tensor([[1., 1., 1., 1.],
+ [1., 1., 0., 0.],
+ [1., 0., 0., 0.]])
+
+ """
+ n_batch = len(xs)
+ max_len = max(x.size(0) for x in xs)
+ pad = xs[0].new(n_batch, max_len, *xs[0].size()[1:]).fill_(pad_value)
+
+ for i in range(n_batch):
+ pad[i, : xs[i].size(0)] = xs[i]
+
+ return pad
+
+def extract_feature(audio):
+ features = []
+ feature_times = []
+ feature_lengths = []
+ for au in audio:
+ feature = Kaldi.fbank(au.unsqueeze(0), num_mel_bins=80)
+ feature = feature - feature.mean(dim=0, keepdim=True)
+ features.append(feature)
+ feature_times.append(au.shape[0])
+ feature_lengths.append(feature.shape[0])
+ # padding for batch inference
+ features_padded = pad_list(features, pad_value=0)
+ # features = torch.cat(features)
+ return features_padded, feature_lengths, feature_times
+
+class BasicResBlock(torch.nn.Module):
+ expansion = 1
+
+ def __init__(self, in_planes, planes, stride=1):
+ super(BasicResBlock, self).__init__()
+ self.conv1 = torch.nn.Conv2d(
+ in_planes, planes, kernel_size=3, stride=(stride, 1), padding=1, bias=False
+ )
+ self.bn1 = torch.nn.BatchNorm2d(planes)
+ self.conv2 = torch.nn.Conv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False)
+ self.bn2 = torch.nn.BatchNorm2d(planes)
+
+ self.shortcut = torch.nn.Sequential()
+ if stride != 1 or in_planes != self.expansion * planes:
+ self.shortcut = torch.nn.Sequential(
+ torch.nn.Conv2d(
+ in_planes,
+ self.expansion * planes,
+ kernel_size=1,
+ stride=(stride, 1),
+ bias=False,
+ ),
+ torch.nn.BatchNorm2d(self.expansion * planes),
+ )
+
+ def forward(self, x):
+ out = F.relu(self.bn1(self.conv1(x)))
+ out = self.bn2(self.conv2(out))
+ out += self.shortcut(x)
+ out = F.relu(out)
+ return out
+
+class FCM(torch.nn.Module):
+ def __init__(self, block=BasicResBlock, num_blocks=[2, 2], m_channels=32, feat_dim=80):
+ super(FCM, self).__init__()
+ self.in_planes = m_channels
+ self.conv1 = torch.nn.Conv2d(1, m_channels, kernel_size=3, stride=1, padding=1, bias=False)
+ self.bn1 = torch.nn.BatchNorm2d(m_channels)
+
+ self.layer1 = self._make_layer(block, m_channels, num_blocks[0], stride=2)
+ self.layer2 = self._make_layer(block, m_channels, num_blocks[0], stride=2)
+
+ self.conv2 = torch.nn.Conv2d(
+ m_channels, m_channels, kernel_size=3, stride=(2, 1), padding=1, bias=False
+ )
+ self.bn2 = torch.nn.BatchNorm2d(m_channels)
+ self.out_channels = m_channels * (feat_dim // 8)
+
+ def _make_layer(self, block, planes, num_blocks, stride):
+ strides = [stride] + [1] * (num_blocks - 1)
+ layers = []
+ for stride in strides:
+ layers.append(block(self.in_planes, planes, stride))
+ self.in_planes = planes * block.expansion
+ return torch.nn.Sequential(*layers)
+
+ def forward(self, x):
+ x = x.unsqueeze(1)
+ out = F.relu(self.bn1(self.conv1(x)))
+ out = self.layer1(out)
+ out = self.layer2(out)
+ out = F.relu(self.bn2(self.conv2(out)))
+
+ shape = out.shape
+ out = out.reshape(shape[0], shape[1] * shape[2], shape[3])
+ return out
+
+def get_nonlinear(config_str, channels):
+ nonlinear = torch.nn.Sequential()
+ for name in config_str.split("-"):
+ if name == "relu":
+ nonlinear.add_module("relu", torch.nn.ReLU(inplace=True))
+ elif name == "prelu":
+ nonlinear.add_module("prelu", torch.nn.PReLU(channels))
+ elif name == "batchnorm":
+ nonlinear.add_module("batchnorm", torch.nn.BatchNorm1d(channels))
+ elif name == "batchnorm_":
+ nonlinear.add_module("batchnorm", torch.nn.BatchNorm1d(channels, affine=False))
+ else:
+ raise ValueError("Unexpected module ({}).".format(name))
+ return nonlinear
+
+def statistics_pooling(x, dim=-1, keepdim=False, unbiased=True, eps=1e-2):
+ mean = x.mean(dim=dim)
+ std = x.std(dim=dim, unbiased=unbiased)
+ stats = torch.cat([mean, std], dim=-1)
+ if keepdim:
+ stats = stats.unsqueeze(dim=dim)
+ return stats
+
+class StatsPool(torch.nn.Module):
+ def forward(self, x):
+ return statistics_pooling(x)
+
+class TDNNLayer(torch.nn.Module):
+ def __init__(
+ self,
+ in_channels,
+ out_channels,
+ kernel_size,
+ stride=1,
+ padding=0,
+ dilation=1,
+ bias=False,
+ config_str="batchnorm-relu",
+ ):
+ super(TDNNLayer, self).__init__()
+ if padding < 0:
+ assert (
+ kernel_size % 2 == 1
+ ), "Expect equal paddings, but got even kernel size ({})".format(kernel_size)
+ padding = (kernel_size - 1) // 2 * dilation
+ self.linear = torch.nn.Conv1d(
+ in_channels,
+ out_channels,
+ kernel_size,
+ stride=stride,
+ padding=padding,
+ dilation=dilation,
+ bias=bias,
+ )
+ self.nonlinear = get_nonlinear(config_str, out_channels)
+
+ def forward(self, x):
+ x = self.linear(x)
+ x = self.nonlinear(x)
+ return x
+
+class CAMLayer(torch.nn.Module):
+ def __init__(
+ self, bn_channels, out_channels, kernel_size, stride, padding, dilation, bias, reduction=2
+ ):
+ super(CAMLayer, self).__init__()
+ self.linear_local = torch.nn.Conv1d(
+ bn_channels,
+ out_channels,
+ kernel_size,
+ stride=stride,
+ padding=padding,
+ dilation=dilation,
+ bias=bias,
+ )
+ self.linear1 = torch.nn.Conv1d(bn_channels, bn_channels // reduction, 1)
+ self.relu = torch.nn.ReLU(inplace=True)
+ self.linear2 = torch.nn.Conv1d(bn_channels // reduction, out_channels, 1)
+ self.sigmoid = torch.nn.Sigmoid()
+
+ def forward(self, x):
+ y = self.linear_local(x)
+ context = x.mean(-1, keepdim=True) + self.seg_pooling(x)
+ context = self.relu(self.linear1(context))
+ m = self.sigmoid(self.linear2(context))
+ return y * m
+
+ def seg_pooling(self, x, seg_len=100, stype="avg"):
+ if stype == "avg":
+ seg = F.avg_pool1d(x, kernel_size=seg_len, stride=seg_len, ceil_mode=True)
+ elif stype == "max":
+ seg = F.max_pool1d(x, kernel_size=seg_len, stride=seg_len, ceil_mode=True)
+ else:
+ raise ValueError("Wrong segment pooling type.")
+ shape = seg.shape
+ seg = seg.unsqueeze(-1).expand(*shape, seg_len).reshape(*shape[:-1], -1)
+ seg = seg[..., : x.shape[-1]]
+ return seg
+
+class CAMDenseTDNNLayer(torch.nn.Module):
+ def __init__(
+ self,
+ in_channels,
+ out_channels,
+ bn_channels,
+ kernel_size,
+ stride=1,
+ dilation=1,
+ bias=False,
+ config_str="batchnorm-relu",
+ memory_efficient=False,
+ ):
+ super(CAMDenseTDNNLayer, self).__init__()
+ assert kernel_size % 2 == 1, "Expect equal paddings, but got even kernel size ({})".format(
+ kernel_size
+ )
+ padding = (kernel_size - 1) // 2 * dilation
+ self.memory_efficient = memory_efficient
+ self.nonlinear1 = get_nonlinear(config_str, in_channels)
+ self.linear1 = torch.nn.Conv1d(in_channels, bn_channels, 1, bias=False)
+ self.nonlinear2 = get_nonlinear(config_str, bn_channels)
+ self.cam_layer = CAMLayer(
+ bn_channels,
+ out_channels,
+ kernel_size,
+ stride=stride,
+ padding=padding,
+ dilation=dilation,
+ bias=bias,
+ )
+
+ def bn_function(self, x):
+ return self.linear1(self.nonlinear1(x))
+
+ def forward(self, x):
+ if self.training and self.memory_efficient:
+ x = cp.checkpoint(self.bn_function, x)
+ else:
+ x = self.bn_function(x)
+ x = self.cam_layer(self.nonlinear2(x))
+ return x
+
+class CAMDenseTDNNBlock(torch.nn.ModuleList):
+ def __init__(
+ self,
+ num_layers,
+ in_channels,
+ out_channels,
+ bn_channels,
+ kernel_size,
+ stride=1,
+ dilation=1,
+ bias=False,
+ config_str="batchnorm-relu",
+ memory_efficient=False,
+ ):
+ super(CAMDenseTDNNBlock, self).__init__()
+ for i in range(num_layers):
+ layer = CAMDenseTDNNLayer(
+ in_channels=in_channels + i * out_channels,
+ out_channels=out_channels,
+ bn_channels=bn_channels,
+ kernel_size=kernel_size,
+ stride=stride,
+ dilation=dilation,
+ bias=bias,
+ config_str=config_str,
+ memory_efficient=memory_efficient,
+ )
+ self.add_module("tdnnd%d" % (i + 1), layer)
+
+ def forward(self, x):
+ for layer in self:
+ x = torch.cat([x, layer(x)], dim=1)
+ return x
+
+class TransitLayer(torch.nn.Module):
+ def __init__(self, in_channels, out_channels, bias=True, config_str="batchnorm-relu"):
+ super(TransitLayer, self).__init__()
+ self.nonlinear = get_nonlinear(config_str, in_channels)
+ self.linear = torch.nn.Conv1d(in_channels, out_channels, 1, bias=bias)
+
+ def forward(self, x):
+ x = self.nonlinear(x)
+ x = self.linear(x)
+ return x
+
+class DenseLayer(torch.nn.Module):
+ def __init__(self, in_channels, out_channels, bias=False, config_str="batchnorm-relu"):
+ super(DenseLayer, self).__init__()
+ self.linear = torch.nn.Conv1d(in_channels, out_channels, 1, bias=bias)
+ self.nonlinear = get_nonlinear(config_str, out_channels)
+
+ def forward(self, x):
+ if len(x.shape) == 2:
+ x = self.linear(x.unsqueeze(dim=-1)).squeeze(dim=-1)
+ else:
+ x = self.linear(x)
+ x = self.nonlinear(x)
+ return x
+
+# @tables.register("model_classes", "CAMPPlus")
+class CAMPPlus(torch.nn.Module):
+ def __init__(
+ self,
+ feat_dim=80,
+ embedding_size=192,
+ growth_rate=32,
+ bn_size=4,
+ init_channels=128,
+ config_str="batchnorm-relu",
+ memory_efficient=True,
+ output_level="segment",
+ **kwargs,
+ ):
+ super().__init__()
+
+ self.head = FCM(feat_dim=feat_dim)
+ channels = self.head.out_channels
+ self.output_level = output_level
+
+ self.xvector = torch.nn.Sequential(
+ OrderedDict(
+ [
+ (
+ "tdnn",
+ TDNNLayer(
+ channels,
+ init_channels,
+ 5,
+ stride=2,
+ dilation=1,
+ padding=-1,
+ config_str=config_str,
+ ),
+ ),
+ ]
+ )
+ )
+ channels = init_channels
+ for i, (num_layers, kernel_size, dilation) in enumerate(
+ zip((12, 24, 16), (3, 3, 3), (1, 2, 2))
+ ):
+ block = CAMDenseTDNNBlock(
+ num_layers=num_layers,
+ in_channels=channels,
+ out_channels=growth_rate,
+ bn_channels=bn_size * growth_rate,
+ kernel_size=kernel_size,
+ dilation=dilation,
+ config_str=config_str,
+ memory_efficient=memory_efficient,
+ )
+ self.xvector.add_module("block%d" % (i + 1), block)
+ channels = channels + num_layers * growth_rate
+ self.xvector.add_module(
+ "transit%d" % (i + 1),
+ TransitLayer(channels, channels // 2, bias=False, config_str=config_str),
+ )
+ channels //= 2
+
+ self.xvector.add_module("out_nonlinear", get_nonlinear(config_str, channels))
+
+ if self.output_level == "segment":
+ self.xvector.add_module("stats", StatsPool())
+ self.xvector.add_module(
+ "dense", DenseLayer(channels * 2, embedding_size, config_str="batchnorm_")
+ )
+ else:
+ assert (
+ self.output_level == "frame"
+ ), "`output_level` should be set to 'segment' or 'frame'. "
+
+ for m in self.modules():
+ if isinstance(m, (torch.nn.Conv1d, torch.nn.Linear)):
+ torch.nn.init.kaiming_normal_(m.weight.data)
+ if m.bias is not None:
+ torch.nn.init.zeros_(m.bias)
+
+ def forward(self, x):
+ x = x.permute(0, 2, 1) # (B,T,F) => (B,F,T)
+ x = self.head(x)
+ x = self.xvector(x)
+ if self.output_level == "frame":
+ x = x.transpose(1, 2)
+ return x
+
+ def inference(self, audio_list):
+ speech, speech_lengths, speech_times = extract_feature(audio_list)
+ results = self.forward(speech.to(torch.float32))
+ return results
+
+
+# ── from s3gen/flow.py ─────────────────────────────────────────────────
+
+
+def _repeat_batch_dim(tnsr, B, ndim):
+ "repeat batch dimension if it's equal to 1"
+ if tnsr is not None:
+ # add missing batch dim if needed
+ while tnsr.ndim < ndim:
+ tnsr = tnsr[None]
+ # repeat batch dim as needed
+ if B > 1 and tnsr.size(0) == 1:
+ tnsr = tnsr.repeat(B, *([1] * (ndim - 1)))
+ assert tnsr.ndim == ndim, f"Expected {ndim=}, got {tnsr.ndim=}"
+ return tnsr
+
+class CausalMaskedDiffWithXvec(torch.nn.Module):
+ def __init__(self,
+ input_size: int = 512,
+ output_size: int = 80,
+ spk_embed_dim: int = 192,
+ output_type: str = "mel",
+ vocab_size: int = 6561,
+ input_frame_rate: int = 25,
+ only_mask_loss: bool = True,
+ token_mel_ratio: int = 2,
+ pre_lookahead_len: int = 3,
+ encoder: torch.nn.Module = None,
+ decoder: torch.nn.Module = None,
+ decoder_conf: Dict = {'in_channels': 240, 'out_channel': 80, 'spk_emb_dim': 80, 'n_spks': 1,
+ 'cfm_params': DictConfig(
+ {'sigma_min': 1e-06, 'solver': 'euler', 't_scheduler': 'cosine',
+ 'training_cfg_rate': 0.2, 'inference_cfg_rate': 0.7,
+ 'reg_loss_type': 'l1'}),
+ 'decoder_params': {'channels': [256, 256], 'dropout': 0.0,
+ 'attention_head_dim': 64,
+ 'n_blocks': 4, 'num_mid_blocks': 12, 'num_heads': 8,
+ 'act_fn': 'gelu'}},
+ mel_feat_conf: Dict = {'n_fft': 1024, 'num_mels': 80, 'sampling_rate': 22050,
+ 'hop_size': 256, 'win_size': 1024, 'fmin': 0, 'fmax': 8000}):
+ super().__init__()
+ self.input_size = input_size
+ self.output_size = output_size
+ self.decoder_conf = decoder_conf
+ self.mel_feat_conf = mel_feat_conf
+ self.vocab_size = vocab_size
+ self.output_type = output_type
+ self.input_frame_rate = input_frame_rate
+ logger.debug(f"input frame rate={self.input_frame_rate}")
+ self.input_embedding = nn.Embedding(vocab_size, input_size)
+ self.spk_embed_affine_layer = torch.nn.Linear(spk_embed_dim, output_size)
+ self.encoder = encoder
+ self.encoder_proj = torch.nn.Linear(self.encoder.output_size(), output_size)
+ self.decoder = decoder
+ self.only_mask_loss = only_mask_loss
+ self.token_mel_ratio = token_mel_ratio
+ self.pre_lookahead_len = pre_lookahead_len
+
+ # NOTE: copied in from cosyvoice repo
+ def compute_loss(
+ self,
+ batch: dict,
+ device: torch.device,
+ ) -> Dict[str, Optional[torch.Tensor]]:
+ token = batch['speech_token'].to(device)
+ token_len = batch['speech_token_len'].to(device)
+ feat = batch['speech_feat'].to(device) # (B, 80, T)
+ feat_len = batch['speech_feat_len'].to(device)
+ embedding = batch['embedding'].to(device)
+
+ # NOTE unified training, static_chunk_size > 0 or = 0
+ # streaming = True if random.random() < 0.5 else False
+
+ # xvec projection
+ embedding = F.normalize(embedding, dim=1)
+ embedding = self.spk_embed_affine_layer(embedding)
+
+ # concat text and prompt_text
+ mask = (~make_pad_mask(token_len)).float().unsqueeze(-1).to(device) # (B, T, 1)
+ token = self.input_embedding(torch.clamp(token, min=0)) * mask # (B, T, emb)
+
+ # text encode
+ h, h_lengths = self.encoder(token, token_len) # (B, T, C) -> (B, 2T, C)
+ h = self.encoder_proj(h)
+
+ # get conditions
+ conds = torch.zeros(feat.shape, device=token.device)
+ for i, j in enumerate(feat_len):
+ if random.random() < 0.5:
+ continue
+ index = random.randint(0, int(0.3 * j))
+ conds[i, :, :index] = feat[i, :, :index]
+
+ mask = (~make_pad_mask(h_lengths.sum(dim=-1).squeeze(dim=1))).to(h)
+ loss, _ = self.decoder.compute_loss(
+ feat.contiguous(),
+ mask.unsqueeze(1),
+ h.transpose(1, 2).contiguous(),
+ embedding,
+ cond=conds,
+ # streaming=streaming,
+ )
+ return {'loss': loss}
+
+ @torch.inference_mode()
+ def inference(self,
+ token,
+ token_len,
+ prompt_token,
+ prompt_token_len,
+ prompt_feat,
+ prompt_feat_len,
+ embedding,
+ finalize,
+ n_timesteps=10,
+ noised_mels=None,
+ meanflow=False):
+ # token: (B, n_toks)
+ # token_len: (B,)
+ B = token.size(0)
+
+ # xvec projection
+ embedding = torch.atleast_2d(embedding)
+ embedding = F.normalize(embedding, dim=1)
+ embedding = self.spk_embed_affine_layer(embedding) # (1 or B, emb_dim)
+
+ # adjust shapes (batching logic)
+ prompt_token = _repeat_batch_dim(prompt_token, B, ndim=2) # (B, n_prompt)
+ prompt_token_len = _repeat_batch_dim(prompt_token_len, B, ndim=1) # (B,)
+ prompt_feat = _repeat_batch_dim(prompt_feat, B, ndim=3) # (B, n_feat, feat_dim=80)
+ prompt_feat_len = _repeat_batch_dim(prompt_feat_len, B, ndim=1) # (B,) or None
+ embedding = _repeat_batch_dim(embedding, B, ndim=2) # (B, emb_dim)
+
+ # concat text and prompt_text
+ token, token_len = torch.concat([prompt_token, token], dim=1), prompt_token_len + token_len
+ mask = (~make_pad_mask(token_len)).unsqueeze(-1).to(embedding)
+
+ if (token >= self.vocab_size).any():
+ logger.error(f"{token.max()}>{self.vocab_size}\n out-of-range special tokens found in flow, fix inputs!")
+ token = self.input_embedding(token.long()) * mask
+
+ # text encode
+ h, h_masks = self.encoder(token, token_len)
+ if finalize is False:
+ h = h[:, :-self.pre_lookahead_len * self.token_mel_ratio]
+
+ h_lengths = h_masks.sum(dim=-1).squeeze(dim=-1)
+ mel_len1, mel_len2 = prompt_feat.shape[1], h.shape[1] - prompt_feat.shape[1]
+ h = self.encoder_proj(h)
+
+ # # get conditions
+ conds = torch.zeros([B, mel_len1 + mel_len2, self.output_size], device=token.device).to(h.dtype)
+ conds[:, :mel_len1] = prompt_feat
+ conds = conds.transpose(1, 2)
+
+ mask = (~make_pad_mask(h_lengths)).unsqueeze(1).to(h)
+
+ if mask.shape[0] != B:
+ mask = mask.repeat(B, 1, 1)
+
+ feat, _ = self.decoder(
+ mu=h.transpose(1, 2).contiguous(),
+ mask=mask,
+ spks=embedding,
+ cond=conds,
+ n_timesteps=n_timesteps,
+ noised_mels=noised_mels,
+ meanflow=meanflow,
+ )
+ feat = feat[:, :, mel_len1:]
+ assert feat.shape[2] == mel_len2
+ return feat, None
+
+
+# ── from s3gen/s3gen.py ────────────────────────────────────────────────
+
+
+def drop_invalid_tokens(x):
+ assert len(x.shape) <= 2 and x.shape[0] == 1, "only batch size of one allowed for now"
+ return x[x < SPEECH_VOCAB_SIZE]
+
+def get_resampler(src_sr, dst_sr, device):
+ return ta.transforms.Resample(src_sr, dst_sr).to(device)
+
+class S3Token2Mel(torch.nn.Module):
+ """
+ S3Gen's CFM decoder maps S3 speech tokens to mel-spectrograms.
+
+ TODO: make these modules configurable?
+ """
+ def __init__(self, meanflow=False):
+ super().__init__()
+ self.tokenizer = S3Tokenizer("speech_tokenizer_v2_25hz")
+ self.mel_extractor = mel_spectrogram # TODO: make it a torch module?
+ self.speaker_encoder = CAMPPlus(
+ # NOTE: This doesn't affect inference. It turns off activation checkpointing
+ # (a training optimization), which causes a crazy DDP error with accelerate
+ memory_efficient=False,
+ )
+ self.meanflow = meanflow
+
+ encoder = UpsampleConformerEncoder(
+ output_size=512,
+ attention_heads=8,
+ linear_units=2048,
+ num_blocks=6,
+ dropout_rate=0.1,
+ positional_dropout_rate=0.1,
+ attention_dropout_rate=0.1,
+ normalize_before=True,
+ input_layer='linear',
+ pos_enc_layer_type='rel_pos_espnet',
+ selfattention_layer_type='rel_selfattn',
+ input_size=512,
+ use_cnn_module=False,
+ macaron_style=False,
+ )
+
+ estimator = ConditionalDecoder(
+ in_channels=320,
+ out_channels=80,
+ causal=True,
+ channels=[256],
+ dropout=0.0,
+ attention_head_dim=64,
+ n_blocks=4,
+ num_mid_blocks=12,
+ num_heads=8,
+ act_fn='gelu',
+ meanflow=self.meanflow,
+ )
+ cfm_params = CFM_PARAMS
+ decoder = CausalConditionalCFM(
+ spk_emb_dim=80,
+ cfm_params=cfm_params,
+ estimator=estimator,
+ )
+
+ self.flow = CausalMaskedDiffWithXvec(
+ encoder=encoder,
+ decoder=decoder
+ )
+
+ self.resamplers = {}
+
+ @property
+ def device(self):
+ params = self.tokenizer.parameters()
+ return next(params).device
+
+ @property
+ def dtype(self):
+ params = self.flow.parameters()
+ return next(params).dtype
+
+ def embed_ref(
+ self,
+ ref_wav: torch.Tensor,
+ ref_sr: int,
+ device="auto",
+ ref_fade_out=True,
+ ):
+ device = self.device if device == "auto" else device
+ if isinstance(ref_wav, np.ndarray):
+ ref_wav = torch.from_numpy(ref_wav).float()
+
+ if ref_wav.device != device:
+ ref_wav = ref_wav.to(device)
+
+ if len(ref_wav.shape) == 1:
+ ref_wav = ref_wav.unsqueeze(0) # (B, L)
+
+ if ref_wav.size(1) > 10 * ref_sr:
+ logger.debug("s3gen received ref longer than 10s")
+
+ ref_wav_24 = ref_wav
+ if ref_sr != S3GEN_SR:
+ ref_wav_24 = get_resampler(ref_sr, S3GEN_SR, device)(ref_wav)
+ ref_wav_24 = ref_wav_24.to(device=device, dtype=self.dtype)
+
+ ref_mels_24 = self.mel_extractor(ref_wav_24).transpose(1, 2).to(dtype=self.dtype)
+ ref_mels_24_len = None
+
+ # Resample to 16kHz
+ ref_wav_16 = ref_wav
+ if ref_sr != S3_SR:
+ ref_wav_16 = get_resampler(ref_sr, S3_SR, device)(ref_wav)
+
+ # Speaker embedding
+ ref_x_vector = self.speaker_encoder.inference(ref_wav_16.to(dtype=self.dtype))
+
+ # Tokenize 16khz reference
+ ref_speech_tokens, ref_speech_token_lens = self.tokenizer(ref_wav_16.float())
+
+ # Make sure mel_len = 2 * stoken_len (happens when the input is not padded to multiple of 40ms)
+ if ref_mels_24.shape[1] != 2 * ref_speech_tokens.shape[1]:
+ logger.debug(
+ "Reference mel length is not equal to 2 * reference token length.\n"
+ )
+ ref_speech_tokens = ref_speech_tokens[:, :ref_mels_24.shape[1] // 2]
+ ref_speech_token_lens[0] = ref_speech_tokens.shape[1]
+
+ return dict(
+ prompt_token=ref_speech_tokens.to(device),
+ prompt_token_len=ref_speech_token_lens,
+ prompt_feat=ref_mels_24,
+ prompt_feat_len=ref_mels_24_len,
+ embedding=ref_x_vector,
+ )
+
+ def forward(
+ self,
+ speech_tokens: torch.LongTensor,
+ # locally-computed ref embedding (mutex with ref_dict)
+ ref_wav: Optional[torch.Tensor],
+ ref_sr: Optional[int],
+ # pre-computed ref embedding (prod API)
+ ref_dict: Optional[dict] = None,
+ n_cfm_timesteps = None,
+ finalize: bool = False,
+ speech_token_lens=None,
+ noised_mels=None,
+ ):
+ """
+ Generate waveforms from S3 speech tokens and a reference waveform, which the speaker timbre is inferred from.
+
+ NOTE:
+ - The speaker encoder accepts 16 kHz waveform.
+ - S3TokenizerV2 accepts 16 kHz waveform.
+ - The mel-spectrogram for the reference assumes 24 kHz input signal.
+ - This function is designed for batch_size=1 only.
+
+ Args
+ ----
+ - `speech_tokens`: S3 speech tokens [B=1, T]
+ - `ref_wav`: reference waveform (`torch.Tensor` with shape=[B=1, T])
+ - `ref_sr`: reference sample rate
+ - `finalize`: whether streaming is finished or not. Note that if False, the last 3 tokens will be ignored.
+ """
+ assert (ref_wav is None) ^ (ref_dict is None), f"Must provide exactly one of ref_wav or ref_dict (got {ref_wav} and {ref_dict})"
+
+ if ref_dict is None:
+ ref_dict = self.embed_ref(ref_wav, ref_sr)
+ else:
+ # type/device casting (all values will be numpy if it's from a prod API call)
+ for rk in list(ref_dict):
+ if isinstance(ref_dict[rk], np.ndarray):
+ ref_dict[rk] = torch.from_numpy(ref_dict[rk])
+ if torch.is_tensor(ref_dict[rk]):
+ ref_dict[rk] = ref_dict[rk].to(device=self.device, dtype=self.dtype)
+
+ speech_tokens = torch.atleast_2d(speech_tokens)
+
+ # backcompat
+ if speech_token_lens is None:
+ speech_token_lens = torch.LongTensor([st.size(-1) for st in speech_tokens]).to(self.device)
+
+ output_mels, _ = self.flow.inference(
+ token=speech_tokens,
+ token_len=speech_token_lens,
+ finalize=finalize,
+ noised_mels=noised_mels,
+ n_timesteps=n_cfm_timesteps,
+ meanflow=self.meanflow,
+ **ref_dict,
+ )
+ return output_mels
+
+class S3Token2Wav(S3Token2Mel):
+ """
+ The decoder of S3Gen is a concat of token-to-mel (CFM) and a mel-to-waveform (HiFiGAN) modules.
+
+ TODO: make these modules configurable?
+ """
+
+ ignore_state_dict_missing = ("tokenizer._mel_filters", "tokenizer.window")
+
+ def __init__(self, meanflow=False):
+ super().__init__(meanflow)
+
+ f0_predictor = ConvRNNF0Predictor()
+ self.mel2wav = HiFTGenerator(
+ sampling_rate=S3GEN_SR,
+ upsample_rates=[8, 5, 3],
+ upsample_kernel_sizes=[16, 11, 7],
+ source_resblock_kernel_sizes=[7, 7, 11],
+ source_resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5], [1, 3, 5]],
+ f0_predictor=f0_predictor,
+ )
+
+ # silence out a few ms and fade audio in to reduce artifacts
+ n_trim = S3GEN_SR // 50 # 20ms = half of a frame
+ trim_fade = torch.zeros(2 * n_trim)
+ trim_fade[n_trim:] = (torch.cos(torch.linspace(torch.pi, 0, n_trim)) + 1) / 2
+ self.register_buffer("trim_fade", trim_fade, persistent=False) # (buffers get automatic device casting)
+ self.estimator_dtype = "fp32"
+
+ def forward(
+ self,
+ speech_tokens,
+ # locally-computed ref embedding (mutex with ref_dict)
+ ref_wav: Optional[torch.Tensor],
+ ref_sr: Optional[int],
+ # pre-computed ref embedding (prod API)
+ ref_dict: Optional[dict] = None,
+ finalize: bool = False,
+ speech_token_lens=None,
+ skip_vocoder=False,
+ n_cfm_timesteps=None,
+ noised_mels=None,
+
+ ):
+ """
+ Generate waveforms from S3 speech tokens and a reference waveform, which the speaker timbre is inferred from.
+ NOTE: used for sync synthesis only. Please use `S3GenStreamer` for streaming synthesis.
+ """
+ output_mels = super().forward(
+ speech_tokens, speech_token_lens=speech_token_lens, ref_wav=ref_wav,
+ ref_sr=ref_sr, ref_dict=ref_dict, finalize=finalize,
+ n_cfm_timesteps=n_cfm_timesteps, noised_mels=noised_mels,
+ )
+
+ if skip_vocoder:
+ return output_mels
+
+ # TODO jrm: ignoring the speed control (mel interpolation) and the HiFTGAN caching mechanisms for now.
+ hift_cache_source = torch.zeros(1, 1, 0).to(self.device)
+
+ output_wavs, *_ = self.mel2wav.inference(speech_feat=output_mels, cache_source=hift_cache_source)
+
+ if not self.training:
+ # NOTE: ad-hoc method to reduce "spillover" from the reference clip.
+ output_wavs[:, :len(self.trim_fade)] *= self.trim_fade
+
+ return output_wavs
+
+ @torch.inference_mode()
+ def flow_inference(
+ self,
+ speech_tokens,
+ # locally-computed ref embedding (mutex with ref_dict)
+ ref_wav: Optional[torch.Tensor] = None,
+ ref_sr: Optional[int] = None,
+ # pre-computed ref embedding (prod API)
+ ref_dict: Optional[dict] = None,
+ n_cfm_timesteps = None,
+ finalize: bool = False,
+ speech_token_lens=None,
+ ):
+ n_cfm_timesteps = n_cfm_timesteps or (2 if self.meanflow else 10)
+ noise = None
+ if self.meanflow:
+ noise = torch.randn(1, 80, speech_tokens.size(-1) * 2, dtype=self.dtype, device=self.device)
+ output_mels = super().forward(
+ speech_tokens, speech_token_lens=speech_token_lens, ref_wav=ref_wav, ref_sr=ref_sr, ref_dict=ref_dict,
+ n_cfm_timesteps=n_cfm_timesteps, finalize=finalize, noised_mels=noise,
+ )
+ return output_mels
+
+ @torch.inference_mode()
+ def hift_inference(self, speech_feat, cache_source: torch.Tensor = None):
+ if cache_source is None:
+ cache_source = torch.zeros(1, 1, 0).to(device=self.device, dtype=self.dtype)
+ return self.mel2wav.inference(speech_feat=speech_feat, cache_source=cache_source)
+
+ @torch.inference_mode()
+ def inference(
+ self,
+ speech_tokens,
+ # locally-computed ref embedding (mutex with ref_dict)
+ ref_wav: Optional[torch.Tensor] = None,
+ ref_sr: Optional[int] = None,
+ # pre-computed ref embedding (prod API)
+ ref_dict: Optional[dict] = None,
+ # left as a kwarg because this can change input/output size ratio
+ drop_invalid_tokens=True,
+ n_cfm_timesteps=None,
+ speech_token_lens=None,
+ ):
+ # hallucination prevention, drop special tokens
+ # if drop_invalid_tokens:
+ # speech_tokens, speech_token_lens = drop_invalid(speech_tokens, pad=S3_QUIET_PAD)
+
+ output_mels = self.flow_inference(
+ speech_tokens,
+ speech_token_lens=speech_token_lens,
+ ref_wav=ref_wav,
+ ref_sr=ref_sr,
+ ref_dict=ref_dict,
+ n_cfm_timesteps=n_cfm_timesteps,
+ finalize=True,
+ )
+ output_mels = output_mels.to(dtype=self.dtype) # FIXME (fp16 mode) is this still needed?
+ output_wavs, output_sources = self.hift_inference(output_mels, None)
+
+ # NOTE: ad-hoc method to reduce "spillover" from the reference clip.
+ output_wavs[:, :len(self.trim_fade)] *= self.trim_fade
+
+ return output_wavs, output_sources
+
+
+# The public surface vocoder.py uses. S3Token2Wav is the full token -> waveform
+# model; S3Token2Mel, its base, stops at the mel spectrogram.
+S3Gen = S3Token2Wav
diff --git a/kittenml/kittentts2/speaker.py b/kittenml/kittentts2/speaker.py
new file mode 100644
index 0000000..9abac2f
--- /dev/null
+++ b/kittenml/kittentts2/speaker.py
@@ -0,0 +1,162 @@
+"""Speaker conditioning for KittenTTS 2.
+
+The model takes a speaker identity through a dedicated `spk_proj` head, not
+through the prompt: a 512-dim pyannote embedding is projected to hidden size and
+written over the first position's input embedding at prefill. That head is trained
+as part of the checkpoint, so it lives alongside the weights and must be restored
+explicitly — transformers knows nothing about it.
+
+Built-in voices ship their embeddings precomputed, so the embedding model is only
+loaded when cloning from a new reference clip. Whisper is likewise only loaded
+when a caller clones without supplying the reference transcript.
+"""
+
+import pathlib
+
+import numpy as np
+import torch
+import torch.nn as nn
+from safetensors.torch import load_file
+
+from .speaker_embedding import EMBEDDING_DIM as SPEAKER_EMBEDDING_DIM
+from .speaker_embedding import SAMPLE_RATE
+
+WHISPER_MODEL = "openai/whisper-large-v3"
+
+
+def attach_speaker_head(model, checkpoint_dir, device, dtype,
+ spk_dim=SPEAKER_EMBEDDING_DIM, state=None):
+ """Restore `model.spk_proj` from the checkpoint and wire up its prefill hook.
+
+ Without this the model runs unconditioned — it still produces speech, but the
+ voice is arbitrary, so a missing head is an error rather than a warning.
+
+ `state` lets a caller pass weights it has already read, which avoids loading
+ several gigabytes twice just to find four tensors.
+ """
+ hidden = int(model.config.hidden_size)
+ model.spk_proj = nn.Sequential(nn.Linear(spk_dim, hidden, bias=True),
+ nn.LayerNorm(hidden)).to(dtype=dtype)
+
+ if state is None:
+ state = {}
+ for shard in sorted(pathlib.Path(checkpoint_dir).glob("model*.safetensors")):
+ state.update(load_file(str(shard)))
+ head_state = {k[len("spk_proj."):]: v.to(dtype)
+ for k, v in state.items() if k.startswith("spk_proj.")}
+ if not head_state:
+ raise ValueError(
+ f"no spk_proj.* weights in {checkpoint_dir} — this checkpoint cannot be "
+ "speaker-conditioned, and generating from it would ignore the voice")
+ model.spk_proj.load_state_dict(head_state, strict=True)
+ model.spk_proj.to(device=device, dtype=dtype).eval()
+
+ def _inject_speaker(module, args, kwargs):
+ embedding = kwargs.pop("speaker_embedding", None)
+ if embedding is None:
+ embedding = getattr(module, "_pending_speaker_embedding", None)
+ input_ids = kwargs.get("input_ids")
+ if embedding is None or input_ids is None:
+ return args, kwargs
+ embeds = module.get_input_embeddings()(input_ids)
+ cache_position = kwargs.get("cache_position")
+ past = kwargs.get("past_key_values")
+ is_prefill = (int(cache_position[0]) == 0) if cache_position is not None else (
+ past is None or (hasattr(past, "get_seq_length") and past.get_seq_length() == 0))
+ # Only at prefill: position 0 carries the speaker, every later step is
+ # ordinary token embedding.
+ if is_prefill and embeds.shape[1] >= 1:
+ projected = module.spk_proj(embedding.to(embeds.dtype)).unsqueeze(1)
+ embeds = torch.cat([projected, embeds[:, 1:, :]], dim=1)
+ kwargs.pop("input_ids", None)
+ kwargs["inputs_embeds"] = embeds
+ return args, kwargs
+
+ model.register_forward_pre_hook(_inject_speaker, with_kwargs=True)
+ return model
+
+
+class SpeakerEncoder:
+ """Turns a reference clip into the 512-dim embedding `spk_proj` expects.
+
+ The weights ship inside the model repository, so this needs no network
+ access and no gated model — see `speaker_embedding.py` for the architecture
+ and for what it is derived from.
+ """
+
+ def __init__(self, weights_path, device="cuda"):
+ self.weights_path = weights_path
+ self.device = device
+ self._model = None
+
+ def _load(self):
+ if self._model is None:
+ from .speaker_embedding import load_speaker_embedding_model
+ self._model = load_speaker_embedding_model(self.weights_path, device=self.device)
+ return self._model
+
+ def __call__(self, wav_path):
+ """Reference clip -> unit-norm 512-dim speaker embedding."""
+ waveform = _load_waveform(wav_path, self.device)
+ with torch.inference_mode():
+ raw = self._load()(waveform).squeeze(0).float().cpu().numpy()
+ norm = float(np.linalg.norm(raw))
+ return (raw / norm).astype(np.float32) if norm > 0 else raw
+
+
+def _load_waveform(wav_path, device, sample_rate=SAMPLE_RATE):
+ """Read a clip as mono at the model's sample rate, shaped (1, 1, samples).
+
+ Channels are averaged and resampling goes through torchaudio, matching how
+ the embeddings this model was trained against were computed — a different
+ resampler shifts the embedding slightly.
+ """
+ import torchaudio
+
+ try:
+ import soundfile as sf
+ audio, file_rate = sf.read(str(wav_path), dtype="float32", always_2d=True)
+ audio = audio.T # (time, channels) -> (channels, time)
+ except Exception: # formats libsndfile cannot open
+ import librosa
+ audio, file_rate = librosa.load(str(wav_path), sr=None, mono=False)
+ audio = np.atleast_2d(audio)
+
+ waveform = torch.from_numpy(np.ascontiguousarray(audio)).float()
+ if waveform.shape[0] > 1:
+ waveform = waveform.mean(dim=0, keepdim=True)
+ if int(file_rate) != sample_rate:
+ waveform = torchaudio.functional.resample(waveform, int(file_rate), sample_rate)
+ return waveform.unsqueeze(0).to(device)
+
+
+class ReferenceTranscriber:
+ """Lazily-loaded Whisper, used only when a clone call omits the transcript.
+
+ The reference transcript is part of the prompt, so cloning needs one either
+ way; a caller should not have to type it out. Nothing is downloaded unless a
+ clone actually arrives without one — the built-in voices ship their
+ transcripts, so they never reach this.
+ """
+
+ def __init__(self, device="cuda", model_name=WHISPER_MODEL, cache_dir=None):
+ self.device = device
+ self.model_name = model_name
+ self.cache_dir = cache_dir
+ self._pipeline = None
+
+ def _load(self):
+ if self._pipeline is None:
+ from transformers import pipeline
+ self._pipeline = pipeline(
+ "automatic-speech-recognition", model=self.model_name,
+ chunk_length_s=30, device=0 if self.device == "cuda" else -1,
+ dtype=torch.float16 if self.device == "cuda" else torch.float32,
+ model_kwargs={"cache_dir": self.cache_dir} if self.cache_dir else {})
+ return self._pipeline
+
+ def __call__(self, wav_path):
+ import librosa
+ wav, sample_rate = librosa.load(str(wav_path), sr=16000, mono=True)
+ del sample_rate
+ return self._load()(wav, generate_kwargs={"language": "en"})["text"].strip()
diff --git a/kittenml/kittentts2/speaker_embedding.py b/kittenml/kittentts2/speaker_embedding.py
new file mode 100644
index 0000000..0aa8a41
--- /dev/null
+++ b/kittenml/kittentts2/speaker_embedding.py
@@ -0,0 +1,189 @@
+"""Speaker embedding: the x-vector model KittenTTS 2's `spk_proj` head was trained on.
+
+A standalone implementation of pyannote's `XVectorSincNet` — a SincNet frontend
+feeding a TDNN stack, statistics pooling and a linear projection to 512
+dimensions. The weights ship inside the KittenTTS 2 repository, so nothing here
+reaches for a gated model at run time.
+
+It is reimplemented rather than imported because `pyannote.audio` pulls in
+lightning, torchmetrics, torch-audiomentations and speechbrain to run one
+96 MB forward pass. Everything below is only that forward pass, and it is
+verified to reproduce pyannote's embeddings exactly.
+
+The model, and this implementation of it, derive from:
+
+ pyannote/embedding (MIT) — Hervé Bredin, pyannote.audio
+ https://huggingface.co/pyannote/embedding
+ SincNet — Mirco Ravanelli, Yoshua Bengio, "Speaker Recognition from raw
+ waveform with SincNet", SLT 2018
+ The parameterised sinc filterbank follows asteroid-filterbanks' ParamSincFB
+ (MIT) — Manuel Pariente et al.
+
+See the LICENSE shipped alongside the weights in the model repository.
+"""
+
+import numpy as np
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+SAMPLE_RATE = 16000
+EMBEDDING_DIM = 512
+
+
+class ParamSincFilterbank(nn.Module):
+ """Band-pass sinc filters parameterised by their cutoff frequencies.
+
+ Each filter is described by two learned numbers — a low cutoff and a
+ bandwidth — rather than by its taps, so the 80 filters carry 80 parameters
+ instead of 80x251. The taps are rebuilt from those numbers on every call.
+
+ Filters come in cosine/sine pairs: `n_filters // 2` of each, concatenated.
+ """
+
+ def __init__(self, n_filters=80, kernel_size=251, stride=10,
+ sample_rate=SAMPLE_RATE, min_low_hz=50, min_band_hz=50):
+ super().__init__()
+ self.n_filters = n_filters
+ self.kernel_size = kernel_size
+ self.stride = stride
+ self.sample_rate = sample_rate
+ self.min_low_hz = min_low_hz
+ self.min_band_hz = min_band_hz
+ self.half_kernel = kernel_size // 2
+
+ self.low_hz_ = nn.Parameter(torch.zeros(n_filters // 2, 1))
+ self.band_hz_ = nn.Parameter(torch.zeros(n_filters // 2, 1))
+ # Both are restored from the checkpoint, which stores them as buffers.
+ self.register_buffer("window_", torch.from_numpy(
+ np.hamming(kernel_size)[:self.half_kernel]).float())
+ self.register_buffer("n_", 2 * np.pi * (
+ torch.arange(-self.half_kernel, 0.0).view(1, -1) / sample_rate))
+
+ def _band_pass(self, low, high, kind):
+ band = (high - low)[:, 0]
+ ft_low = torch.matmul(low, self.n_)
+ ft_high = torch.matmul(high, self.n_)
+ if kind == "cos": # even filters, as in the SincNet paper
+ left = ((torch.sin(ft_high) - torch.sin(ft_low)) / (self.n_ / 2)) * self.window_
+ center = 2 * band.view(-1, 1)
+ right = torch.flip(left, dims=[1])
+ else: # odd filters, the ParamSincFB extension
+ left = ((torch.cos(ft_low) - torch.cos(ft_high)) / (self.n_ / 2)) * self.window_
+ center = torch.zeros_like(band.view(-1, 1))
+ right = -torch.flip(left, dims=[1])
+ band_pass = torch.cat([left, center, right], dim=1) / (2 * band[:, None])
+ return band_pass.view(self.n_filters // 2, 1, self.kernel_size)
+
+ def filters(self):
+ low = self.min_low_hz + torch.abs(self.low_hz_)
+ high = torch.clamp(low + self.min_band_hz + torch.abs(self.band_hz_),
+ self.min_low_hz, self.sample_rate / 2)
+ return torch.cat([self._band_pass(low, high, "cos"),
+ self._band_pass(low, high, "sin")], dim=0)
+
+ def forward(self, waveform):
+ return F.conv1d(waveform, self.filters(), stride=self.stride)
+
+
+class SincNet(nn.Module):
+ """Learned filterbank frontend: three conv/pool/norm stages over raw audio."""
+
+ def __init__(self, sample_rate=SAMPLE_RATE, stride=10):
+ super().__init__()
+ if sample_rate != SAMPLE_RATE:
+ raise ValueError(f"SincNet expects {SAMPLE_RATE} Hz audio, got {sample_rate}")
+ self.wav_norm1d = nn.InstanceNorm1d(1, affine=True)
+ self.conv1d = nn.ModuleList([
+ _SincConvWrapper(ParamSincFilterbank(80, 251, stride=stride,
+ sample_rate=sample_rate)),
+ nn.Conv1d(80, 60, 5, stride=1),
+ nn.Conv1d(60, 60, 5, stride=1),
+ ])
+ self.pool1d = nn.ModuleList([nn.MaxPool1d(3, stride=3) for _ in range(3)])
+ self.norm1d = nn.ModuleList([nn.InstanceNorm1d(c, affine=True) for c in (80, 60, 60)])
+
+ def forward(self, waveforms):
+ outputs = self.wav_norm1d(waveforms)
+ for i, (conv, pool, norm) in enumerate(zip(self.conv1d, self.pool1d, self.norm1d)):
+ outputs = conv(outputs)
+ if i == 0:
+ # The sinc filters are band-pass, so only magnitude carries
+ # information here; the sign is phase.
+ outputs = torch.abs(outputs)
+ outputs = F.leaky_relu(norm(pool(outputs)))
+ return outputs
+
+
+class _SincConvWrapper(nn.Module):
+ """Holds the filterbank under the attribute name the checkpoint expects."""
+
+ def __init__(self, filterbank):
+ super().__init__()
+ self.filterbank = filterbank
+
+ def forward(self, waveform):
+ return self.filterbank(waveform)
+
+
+class XVectorSincNet(nn.Module):
+ """SincNet frontend -> TDNN stack -> statistics pooling -> 512-dim embedding."""
+
+ KERNEL_SIZES = (5, 3, 3, 1, 1)
+ DILATIONS = (1, 2, 3, 1, 1)
+ CHANNELS = (512, 512, 512, 512, 1500)
+
+ def __init__(self, sample_rate=SAMPLE_RATE, sincnet_stride=10, dimension=EMBEDDING_DIM):
+ super().__init__()
+ self.sincnet = SincNet(sample_rate=sample_rate, stride=sincnet_stride)
+ self.tdnns = nn.ModuleList()
+ in_channels = 60
+ for out_channels, kernel_size, dilation in zip(
+ self.CHANNELS, self.KERNEL_SIZES, self.DILATIONS):
+ self.tdnns.extend([
+ nn.Conv1d(in_channels, out_channels, kernel_size, dilation=dilation),
+ nn.LeakyReLU(),
+ nn.BatchNorm1d(out_channels),
+ ])
+ in_channels = out_channels
+ self.embedding = nn.Linear(in_channels * 2, dimension)
+
+ def forward(self, waveforms):
+ """(batch, channel, samples) at 16 kHz -> (batch, 512)."""
+ outputs = self.sincnet(waveforms).squeeze(dim=1)
+ for tdnn in self.tdnns:
+ outputs = tdnn(outputs)
+ # Statistics pooling: mean and unbiased standard deviation over time,
+ # concatenated, so a clip of any length becomes one fixed-size vector.
+ pooled = torch.cat([outputs.mean(dim=-1),
+ outputs.std(dim=-1, correction=1)], dim=-1)
+ return self.embedding(pooled)
+
+
+def load_speaker_embedding_model(weights_path, device="cpu"):
+ """Build the model and load the weights shipped with a KittenTTS 2 repository.
+
+ Accepts either the safetensors file the repository ships or an original
+ pyannote `pytorch_model.bin` checkpoint.
+ """
+ if str(weights_path).endswith(".safetensors"):
+ from safetensors.torch import load_file
+ state = load_file(str(weights_path))
+ else:
+ checkpoint = torch.load(str(weights_path), map_location="cpu", weights_only=False)
+ state = checkpoint.get("state_dict", checkpoint)
+
+ model = XVectorSincNet()
+ # `loss_func.*` is the training-time classification head, and the sinc window
+ # and time vectors are constants rebuilt in __init__. Neither belongs to
+ # inference, so they are ignored whether or not the file happens to carry
+ # them — the repository's own weights are saved without them.
+ state = {k: v for k, v in state.items() if not k.startswith("loss_func.")}
+ buffers = ("window_", "n_")
+ missing, unexpected = model.load_state_dict(state, strict=False)
+ missing = [k for k in missing if not k.endswith(buffers)]
+ unexpected = [k for k in unexpected if not k.endswith(buffers)]
+ if missing or unexpected:
+ raise ValueError(f"speaker embedding weights do not match the model "
+ f"(missing={missing}, unexpected={unexpected})")
+ return model.to(device).eval()
diff --git a/kittenml/kittentts2/student_flow.py b/kittenml/kittentts2/student_flow.py
new file mode 100644
index 0000000..a6ad0f0
--- /dev/null
+++ b/kittenml/kittentts2/student_flow.py
@@ -0,0 +1,2125 @@
+"""The optional quantised decoder: a distilled student flow, tokens -> mel.
+
+KittenTTS 2 decodes in two stages — a flow turns codec tokens into a mel
+spectrogram, then a vocoder turns that into audio. This module is an alternative
+first stage: a distilled student that runs in a single step with its weights
+packed to 4 or 8 bits, cutting the flow from roughly 115 MB to 37 MB. The
+tokenizer, speaker encoder and vocoder are untouched and still come from
+`s3gen.py`.
+
+The trade is deliberate and worth stating plainly: quantisation shrinks storage
+and memory bandwidth, not arithmetic, so this is **not faster** without a kernel
+that multiplies in low precision. Quality is also below the default decoder
+(measured mel L1 against the teacher: 0.250 versus 0.168 for the dense student),
+and voices far from the student's 539-speaker training pool degrade more than the
+default decoder's would. Choose it for footprint, not for speed or fidelity.
+
+Weights are loaded pre-quantised. Dequantising and re-quantising a weight is not a
+no-op in floating point — rounding at a boundary shifts about 10% of weights by
+~1e-7, which accumulated over 474 layers moved the mel output by 0.365. The stored
+codes are therefore used directly.
+
+Generated by scripts/vendor_student_flow.py; edit that, not this. Derived from
+ResembleAI's chatterbox (Apache 2.0), which builds on Alibaba's CosyVoice and
+Matcha-TTS, plus the BitNet-style quantised layers.
+"""
+
+import re
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from torch import Tensor
+import logging
+import math
+from abc import ABC
+from typing import Any, Dict, List, Optional, Tuple, Union
+import numpy as np
+from einops import pack, rearrange, repeat
+from omegaconf import DictConfig
+from torch import sin, pow
+from torch.distributions.uniform import Uniform
+from torch.nn import Conv1d, ConvTranspose1d, Parameter
+from tqdm import tqdm
+try:
+ from diffusers.models.attention import (
+ GEGLU,
+ GELU,
+ AdaLayerNorm,
+ AdaLayerNormZero,
+ ApproximateGELU,
+ )
+except ImportError:
+ from diffusers.models.activations import GEGLU, GELU, ApproximateGELU
+ from diffusers.models.normalization import AdaLayerNorm, AdaLayerNormZero
+from diffusers.models.attention_processor import Attention
+try:
+ from diffusers.models.lora import LoRACompatibleLinear
+except ImportError:
+ # LoRACompatibleLinear was removed in diffusers >= 0.32; fall back to plain Linear
+ LoRACompatibleLinear = nn.Linear
+
+
+# ── quantised layers, from bitnet.py ────────────────────────────────────────────
+
+
+__all__ = [
+ "SimpleRMSNorm", "simple_rms_norm", "activation_quant",
+ "weight_quant_ternary", "weight_quant_sign", "weight_quant_nbit",
+ "BitLinear", "BitConv1d", "convert_to_bitnet", "count_quantised",
+]
+
+
+def simple_rms_norm(x: Tensor, dim: int) -> Tensor:
+ """L2-normalise over the last axis and scale by ``dim ** -0.5``."""
+ return F.normalize(x, dim=-1) * (dim ** -0.5)
+
+
+class SimpleRMSNorm(nn.Module):
+ """Parameter-free. Kept as a module for API compatibility with zeta."""
+
+ def __init__(self, dim: int):
+ super().__init__()
+ self.dim = dim
+ self.scale = dim ** -0.5
+
+ def forward(self, x: Tensor) -> Tensor:
+ return F.normalize(x, dim=-1) * self.scale
+
+
+def activation_quant(x: Tensor, eps: float = 1e-5) -> Tensor:
+ """8-bit per-token quantisation. Scale is divided back out, so this is
+ near-identity in magnitude and only the precision changes."""
+ scale = 127.0 / x.abs().amax(dim=-1, keepdim=True).clamp(min=eps)
+ return (x * scale).round().clamp(-128, 127) / scale
+
+
+def weight_quant_ternary(w: Tensor, eps: float = 1e-5) -> Tensor:
+ """BitNet b1.58: three levels, {-s, 0, +s} with s = mean|w|."""
+ scale = 1.0 / w.abs().mean().clamp(min=eps)
+ return (w * scale).round().clamp(-1, 1) / scale
+
+
+def weight_quant_sign(w: Tensor) -> Tensor:
+ """BitNet 1-bit: two levels. Binary despite often being called ternary."""
+ scale = w.abs().mean()
+ return (w - w.mean()).sign() * scale
+
+
+def weight_quant_nbit(w: Tensor, bits: int, per_channel: bool = True,
+ group_size: int = 0, eps: float = 1e-5) -> Tensor:
+ """Uniform signed n-bit weight quantisation.
+
+ Per-channel by default: one scale per output channel rather than one for the
+ whole tensor. At 8 bits the difference is small, but at 4 bits a single
+ outlier channel otherwise sets the scale for every weight and most of the
+ range goes unused. This is the standard choice for 4-bit PTQ.
+ """
+ qmax = float(2 ** (bits - 1) - 1)
+ if group_size:
+ # One scale per contiguous run of `group_size` weights within an output
+ # channel. Standard for 4-bit LLM quantisation (GPTQ, AWQ use 128) and
+ # much finer than per-channel, which for a conv covers in_ch * kernel
+ # weights under a single scale.
+ shape = w.shape
+ flat = w.reshape(shape[0], -1)
+ n = flat.shape[1]
+ pad = (-n) % group_size
+ if pad:
+ flat = torch.nn.functional.pad(flat, (0, pad))
+ g = flat.reshape(-1, group_size)
+ scale = qmax / g.abs().amax(dim=1, keepdim=True).clamp(min=eps)
+ q = (g * scale).round().clamp(-qmax - 1, qmax) / scale
+ q = q.reshape(shape[0], -1)[:, :n]
+ return q.reshape(shape)
+ if per_channel:
+ flat = w.reshape(w.shape[0], -1)
+ scale = qmax / flat.abs().amax(dim=1).clamp(min=eps)
+ scale = scale.reshape(-1, *([1] * (w.dim() - 1)))
+ else:
+ scale = qmax / w.abs().amax().clamp(min=eps)
+ return (w * scale).round().clamp(-qmax - 1, qmax) / scale
+
+
+_WEIGHT_QUANT = {"ternary": weight_quant_ternary, "sign": weight_quant_sign}
+
+
+_NBIT_RE = re.compile(r"^w(\d+)(_pt)?(?:g(\d+))?(a16)?$")
+
+
+def _check_mode(mode: str) -> str:
+ """Modes: ``ternary``, ``sign``, or ``w<bits>`` (``w4``, ``w8``).
+
+ A ``_pt`` suffix asks for per-tensor scaling instead of per-channel, which is
+ only useful for showing why per-channel is the default.
+ """
+ if mode in _WEIGHT_QUANT or _NBIT_RE.match(mode):
+ return mode
+ raise ValueError(f"unknown quantise mode {mode!r}")
+
+
+def _quantise_weight(w: Tensor, mode: str) -> Tensor:
+ if mode in _WEIGHT_QUANT:
+ return _WEIGHT_QUANT[mode](w)
+ m = _NBIT_RE.match(mode)
+ return weight_quant_nbit(w, int(m.group(1)), per_channel=m.group(2) is None,
+ group_size=int(m.group(3)) if m.group(3) else 0)
+
+
+def _quantise_acts(mode: str) -> bool:
+ """False for an ``a16`` mode, which leaves activations in full precision."""
+ m = _NBIT_RE.match(mode)
+ return not (m and m.group(4))
+
+
+def _ste(x: Tensor, quantised: Tensor) -> Tensor:
+ """Forward the quantised value, backprop as if it were the identity."""
+ return x + (quantised - x).detach()
+
+
+class BitLinear(nn.Linear):
+ """``nn.Linear`` with quantised weights and 8-bit activations."""
+
+ def __init__(self, in_features, out_features, bias=True,
+ mode: str = "ternary", norm_input: bool = True,
+ prequantised: bool = False, device=None, dtype=None):
+ super().__init__(in_features, out_features, bias, device=device, dtype=dtype)
+ self.mode = _check_mode(mode)
+ self.norm_input = norm_input
+ # Set when the stored weight is already on the quantisation grid, as in an
+ # exported model. Re-quantising it is *not* a no-op in floating point:
+ # dequantise-then-requantise flips ~10 % of weights by ~1e-7, which is
+ # enough to move the output noticeably once it accumulates over 474 layers.
+ self.prequantised = prequantised
+
+ def forward(self, x: Tensor, scale: float = 1.0) -> Tensor:
+ # `scale` exists only so this is a drop-in for diffusers'
+ # LoRACompatibleLinear, which some call sites pass it to. There is no LoRA
+ # here, so anything other than 1.0 would be silently dropped — refuse instead.
+ if scale != 1.0:
+ raise ValueError(f"BitLinear got scale={scale}; LoRA is not supported")
+ x = simple_rms_norm(x, self.in_features) if self.norm_input else x
+ x_q = _ste(x, activation_quant(x)) if _quantise_acts(self.mode) else x
+ w_q = (self.weight if self.prequantised else
+ _ste(self.weight, _quantise_weight(self.weight, self.mode)))
+ return F.linear(x_q, w_q, self.bias)
+
+ def extra_repr(self) -> str:
+ return f"{super().extra_repr()}, mode={self.mode}"
+
+
+class BitConv1d(nn.Conv1d):
+ """``nn.Conv1d`` with quantised weights and 8-bit activations.
+
+ Input is ``[B, C, T]``; the norm and the activation quantiser both act over the
+ channel axis, so the tensor is transposed around them.
+ """
+
+ def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0,
+ dilation=1, groups=1, bias=True, padding_mode="zeros",
+ mode: str = "ternary", norm_input: bool = True,
+ causal_padding=None, prequantised: bool = False,
+ device=None, dtype=None):
+ super().__init__(in_channels, out_channels, kernel_size, stride, padding,
+ dilation, groups, bias, padding_mode,
+ device=device, dtype=dtype)
+ self.mode = _check_mode(mode)
+ self.norm_input = norm_input
+ self.prequantised = prequantised # see BitLinear
+ # Carried over from CausalConv1d, which pads in its forward rather than
+ # through nn.Conv1d's padding argument. Dropping it silently shortens the
+ # sequence and the model stops assembling.
+ self.causal_padding = tuple(causal_padding) if causal_padding else None
+
+ def forward(self, x: Tensor) -> Tensor:
+ if self.causal_padding:
+ x = F.pad(x, self.causal_padding)
+ xt = x.transpose(-1, -2)
+ if self.norm_input:
+ xt = simple_rms_norm(xt, self.in_channels)
+ xq = _ste(xt, activation_quant(xt)) if _quantise_acts(self.mode) else xt
+ x_q = xq.transpose(-1, -2)
+ w_q = (self.weight if self.prequantised else
+ _ste(self.weight, _quantise_weight(self.weight, self.mode)))
+ return self._conv_forward(x_q, w_q, self.bias)
+
+ def extra_repr(self) -> str:
+ return f"{super().extra_repr()}, mode={self.mode}"
+
+
+DEFAULT_SKIP = ("final_proj", "input_embedding", "spk_embed_affine_layer")
+
+
+def _is_plain_linear(m: nn.Module) -> bool:
+ """An nn.Linear, or a subclass that behaves exactly like one right now.
+
+ diffusers' LoRACompatibleLinear wraps every transformer feed-forward; with no
+ LoRA attached its forward is plain F.linear, and it holds 6.9 M of the
+ half-size flow's weights — too much to leave dense over a type check.
+ """
+ if type(m) is nn.Linear:
+ return True
+ return (isinstance(m, nn.Linear) and not isinstance(m, BitLinear)
+ and type(m).__name__ == "LoRACompatibleLinear"
+ and getattr(m, "lora_layer", None) is None)
+
+
+def _is_causal_conv1d(m: nn.Module) -> bool:
+ """A Conv1d subclass whose only extra behaviour is a causal pre-pad."""
+ return (isinstance(m, nn.Conv1d) and not isinstance(m, BitConv1d)
+ and type(m).__name__ == "CausalConv1d"
+ and getattr(m, "causal_padding", None) is not None)
+
+
+def convert_to_bitnet(module: nn.Module, mode: str = "ternary",
+ skip: tuple = DEFAULT_SKIP, norm_input: bool = True,
+ prequantised: bool = False, _prefix: str = "") -> nn.Module:
+ """Replace every ``nn.Linear`` / ``nn.Conv1d`` in ``module``, in place.
+
+ Args:
+ module: model to convert.
+ mode: ``ternary`` or ``sign``.
+ skip: names matched against the dotted path of each layer; a layer whose
+ path contains any of these substrings is left dense.
+ norm_input: apply SimpleRMSNorm to layer inputs, as BitNet specifies.
+
+ Returns the same module, converted.
+ """
+ for name, child in list(module.named_children()):
+ path = f"{_prefix}{name}"
+ if any(s in path for s in skip):
+ continue
+ # Exact type only. Subclasses (CausalConv1d, the tokenizer's _S3Linear /
+ # _S3Conv1d) override forward, and replacing them would throw that away.
+ # CausalConv1d is handled explicitly below.
+ if _is_plain_linear(child):
+ new = BitLinear(child.in_features, child.out_features,
+ bias=child.bias is not None, mode=mode,
+ norm_input=norm_input, prequantised=prequantised)
+ new.weight.data.copy_(child.weight.data)
+ if child.bias is not None:
+ new.bias.data.copy_(child.bias.data)
+ setattr(module, name, new)
+ elif type(child) is nn.Conv1d or _is_causal_conv1d(child):
+ new = BitConv1d(child.in_channels, child.out_channels, child.kernel_size,
+ stride=child.stride, padding=child.padding,
+ dilation=child.dilation, groups=child.groups,
+ bias=child.bias is not None,
+ padding_mode=child.padding_mode, mode=mode,
+ norm_input=norm_input, prequantised=prequantised,
+ causal_padding=getattr(child, "causal_padding", None))
+ new.weight.data.copy_(child.weight.data)
+ if child.bias is not None:
+ new.bias.data.copy_(child.bias.data)
+ setattr(module, name, new)
+ else:
+ convert_to_bitnet(child, mode=mode, skip=skip, norm_input=norm_input,
+ prequantised=prequantised, _prefix=f"{path}.")
+ return module
+
+
+def count_quantised(module: nn.Module) -> dict:
+ """Parameters that end up quantised versus left dense, and the memory that buys."""
+ q = sum(m.weight.numel() for m in module.modules()
+ if isinstance(m, (BitLinear, BitConv1d)))
+ total = sum(p.numel() for p in module.parameters())
+ # ternary needs log2(3) bits per weight; everything else stays fp16
+ bits = q * 1.58 + (total - q) * 16
+ return dict(total=total, quantised=q, dense=total - q,
+ quantised_frac=q / total if total else 0.0,
+ mb_fp16=total * 16 / 8 / 2**20, mb_ternary=bits / 8 / 2**20)
+
+
+# ── student flow architecture, from chatterbox_codec.py ─────────────────────────
+
+
+logger = logging.getLogger(__name__)
+
+
+class AttrDict(dict):
+ def __init__(self, *args, **kwargs):
+ super(AttrDict, self).__init__(*args, **kwargs)
+ self.__dict__ = self
+
+
+CFM_PARAMS = AttrDict({
+ "sigma_min": 1e-06,
+ "solver": "euler",
+ "t_scheduler": "cosine",
+ "training_cfg_rate": 0.2,
+ "inference_cfg_rate": 0.7,
+ "reg_loss_type": "l1",
+})
+
+
+class Swish(torch.nn.Module):
+ """Swish activation function."""
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ return x * torch.sigmoid(x)
+
+
+class PositionalEncoding(torch.nn.Module):
+ """Sinusoidal positional encoding."""
+
+ def __init__(self, d_model: int, dropout_rate: float, max_len: int = 5000, reverse: bool = False):
+ super().__init__()
+ self.d_model = d_model
+ self.xscale = math.sqrt(self.d_model)
+ self.dropout = torch.nn.Dropout(p=dropout_rate)
+ self.max_len = max_len
+
+ self.pe = torch.zeros(self.max_len, self.d_model)
+ position = torch.arange(0, self.max_len, dtype=torch.float32).unsqueeze(1)
+ div_term = torch.exp(
+ torch.arange(0, self.d_model, 2, dtype=torch.float32) * -(math.log(10000.0) / self.d_model)
+ )
+ self.pe[:, 0::2] = torch.sin(position * div_term)
+ self.pe[:, 1::2] = torch.cos(position * div_term)
+ self.pe = self.pe.unsqueeze(0)
+
+ def forward(self, x: torch.Tensor, offset: Union[int, torch.Tensor] = 0) -> Tuple[torch.Tensor, torch.Tensor]:
+ self.pe = self.pe.to(x.device)
+ pos_emb = self.position_encoding(offset, x.size(1), False)
+ x = x * self.xscale + pos_emb
+ return self.dropout(x), self.dropout(pos_emb)
+
+ def position_encoding(self, offset: Union[int, torch.Tensor], size: int, apply_dropout: bool = True) -> torch.Tensor:
+ if isinstance(offset, int):
+ assert offset + size <= self.max_len
+ pos_emb = self.pe[:, offset:offset + size]
+ elif isinstance(offset, torch.Tensor) and offset.dim() == 0:
+ assert offset + size <= self.max_len
+ pos_emb = self.pe[:, offset:offset + size]
+ else:
+ assert torch.max(offset) + size <= self.max_len
+ index = offset.unsqueeze(1) + torch.arange(0, size).to(offset.device)
+ flag = index > 0
+ index = index * flag
+ pos_emb = F.embedding(index, self.pe[0])
+ if apply_dropout:
+ pos_emb = self.dropout(pos_emb)
+ return pos_emb
+
+
+class RelPositionalEncoding(PositionalEncoding):
+ def __init__(self, d_model: int, dropout_rate: float, max_len: int = 5000):
+ super().__init__(d_model, dropout_rate, max_len, reverse=True)
+
+ def forward(self, x: torch.Tensor, offset: Union[int, torch.Tensor] = 0) -> Tuple[torch.Tensor, torch.Tensor]:
+ self.pe = self.pe.to(x.device)
+ x = x * self.xscale
+ pos_emb = self.position_encoding(offset, x.size(1), False)
+ return self.dropout(x), self.dropout(pos_emb)
+
+
+class EspnetRelPositionalEncoding(torch.nn.Module):
+ """Relative positional encoding (ESPnet style)."""
+
+ def __init__(self, d_model: int, dropout_rate: float, max_len: int = 5000):
+ super(EspnetRelPositionalEncoding, self).__init__()
+ self.d_model = d_model
+ self.xscale = math.sqrt(self.d_model)
+ self.dropout = torch.nn.Dropout(p=dropout_rate)
+ self.pe = None
+ self.extend_pe(torch.tensor(0.0).expand(1, max_len))
+
+ def extend_pe(self, x: torch.Tensor):
+ if self.pe is not None:
+ if self.pe.size(1) >= x.size(1) * 2 - 1:
+ if self.pe.dtype != x.dtype or self.pe.device != x.device:
+ self.pe = self.pe.to(dtype=x.dtype, device=x.device)
+ return
+ pe_positive = torch.zeros(x.size(1), self.d_model)
+ pe_negative = torch.zeros(x.size(1), self.d_model)
+ position = torch.arange(0, x.size(1), dtype=torch.float32).unsqueeze(1)
+ div_term = torch.exp(
+ torch.arange(0, self.d_model, 2, dtype=torch.float32) * -(math.log(10000.0) / self.d_model)
+ )
+ pe_positive[:, 0::2] = torch.sin(position * div_term)
+ pe_positive[:, 1::2] = torch.cos(position * div_term)
+ pe_negative[:, 0::2] = torch.sin(-1 * position * div_term)
+ pe_negative[:, 1::2] = torch.cos(-1 * position * div_term)
+ pe_positive = torch.flip(pe_positive, [0]).unsqueeze(0)
+ pe_negative = pe_negative[1:].unsqueeze(0)
+ pe = torch.cat([pe_positive, pe_negative], dim=1)
+ self.pe = pe.to(device=x.device, dtype=x.dtype)
+
+ def forward(self, x: torch.Tensor, offset: Union[int, torch.Tensor] = 0) -> Tuple[torch.Tensor, torch.Tensor]:
+ self.extend_pe(x)
+ x = x * self.xscale
+ pos_emb = self.position_encoding(size=x.size(1), offset=offset)
+ return self.dropout(x), self.dropout(pos_emb)
+
+ def position_encoding(self, offset: Union[int, torch.Tensor], size: int) -> torch.Tensor:
+ pos_emb = self.pe[
+ :,
+ self.pe.size(1) // 2 - size + 1: self.pe.size(1) // 2 + size,
+ ]
+ return pos_emb
+
+
+class WhisperPositionalEncoding(PositionalEncoding):
+ def __init__(self, d_model: int, dropout_rate: float, max_len: int = 1500):
+ super().__init__(d_model, dropout_rate, max_len)
+ self.xscale = 1.0
+ log_timescale_increment = np.log(10000) / (d_model // 2 - 1)
+ inv_timescales = torch.exp(-log_timescale_increment * torch.arange(d_model // 2))
+ scaled_time = torch.arange(max_len)[:, np.newaxis] * inv_timescales[np.newaxis, :]
+ pe = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], dim=1)
+ delattr(self, "pe")
+ self.register_buffer("pe", pe.unsqueeze(0))
+
+
+class LearnablePositionalEncoding(PositionalEncoding):
+ def __init__(self, d_model: int, dropout_rate: float, max_len: int = 448):
+ super().__init__(d_model, dropout_rate, max_len)
+ self.pe = torch.nn.Parameter(torch.empty(1, max_len, d_model))
+ self.xscale = 1.0
+
+
+class NoPositionalEncoding(torch.nn.Module):
+ def __init__(self, d_model: int, dropout_rate: float):
+ super().__init__()
+ self.d_model = d_model
+ self.dropout = torch.nn.Dropout(p=dropout_rate)
+
+ def forward(self, x: torch.Tensor, offset: Union[int, torch.Tensor] = 0) -> Tuple[torch.Tensor, torch.Tensor]:
+ pos_emb = torch.zeros(1, x.size(1), self.d_model).to(x.device)
+ return self.dropout(x), pos_emb
+
+ def position_encoding(self, offset: Union[int, torch.Tensor], size: int) -> torch.Tensor:
+ return torch.zeros(1, size, self.d_model)
+
+
+class BaseSubsampling(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.right_context = 0
+ self.subsampling_rate = 1
+
+ def position_encoding(self, offset: Union[int, torch.Tensor], size: int) -> torch.Tensor:
+ return self.pos_enc.position_encoding(offset, size)
+
+
+class EmbedinigNoSubsampling(BaseSubsampling):
+ def __init__(self, idim: int, odim: int, dropout_rate: float, pos_enc_class):
+ super().__init__()
+ self.embed = torch.nn.Embedding(idim, odim)
+ self.pos_enc = pos_enc_class
+
+ def forward(self, x, x_mask, offset=0):
+ x = self.embed(x)
+ x, pos_emb = self.pos_enc(x, offset)
+ return x, pos_emb, x_mask
+
+
+class LinearNoSubsampling(BaseSubsampling):
+ def __init__(self, idim: int, odim: int, dropout_rate: float, pos_enc_class):
+ super().__init__()
+ self.out = torch.nn.Sequential(
+ torch.nn.Linear(idim, odim),
+ torch.nn.LayerNorm(odim, eps=1e-5),
+ torch.nn.Dropout(dropout_rate),
+ )
+ self.pos_enc = pos_enc_class
+ self.right_context = 0
+ self.subsampling_rate = 1
+
+ def forward(self, x, x_mask, offset=0):
+ x = self.out(x)
+ x, pos_emb = self.pos_enc(x, offset)
+ return x, pos_emb, x_mask
+
+
+class LegacyLinearNoSubsampling(BaseSubsampling):
+ def __init__(self, idim: int, odim: int, dropout_rate: float, pos_enc_class):
+ super().__init__()
+ self.out = torch.nn.Sequential(
+ torch.nn.Linear(idim, odim),
+ torch.nn.LayerNorm(odim, eps=1e-5),
+ torch.nn.Dropout(dropout_rate),
+ torch.nn.ReLU(),
+ )
+ self.pos_enc = pos_enc_class
+ self.right_context = 0
+ self.subsampling_rate = 1
+
+ def forward(self, x, x_mask, offset=0):
+ x = self.out(x)
+ x, pos_emb = self.pos_enc(x, offset)
+ return x, pos_emb, x_mask
+
+
+class Conv1dSubsampling2(BaseSubsampling):
+ def __init__(self, idim: int, odim: int, dropout_rate: float, pos_enc_class):
+ super().__init__()
+ self.conv = torch.nn.Sequential(
+ torch.nn.Conv1d(idim, odim, kernel_size=3, padding=1),
+ torch.nn.GELU(),
+ torch.nn.Conv1d(odim, odim, kernel_size=3, stride=2, padding=1),
+ torch.nn.GELU(),
+ )
+ self.pos_enc = pos_enc_class
+ self.subsampling_rate = 2
+ self.right_context = 4
+
+ def forward(self, x, x_mask, offset=0):
+ time = x.size(1)
+ x = x.transpose(1, 2)
+ x = self.conv(x)
+ x = x.transpose(1, 2)
+ x, pos_emb = self.pos_enc(x, offset)
+ return x, pos_emb, x_mask[:, :, (time + 1) % 2::2]
+
+
+class Conv2dSubsampling4(BaseSubsampling):
+ def __init__(self, idim: int, odim: int, dropout_rate: float, pos_enc_class):
+ super().__init__()
+ self.conv = torch.nn.Sequential(
+ torch.nn.Conv2d(1, odim, 3, 2),
+ torch.nn.ReLU(),
+ torch.nn.Conv2d(odim, odim, 3, 2),
+ torch.nn.ReLU(),
+ )
+ self.out = torch.nn.Sequential(
+ torch.nn.Linear(odim * (((idim - 1) // 2 - 1) // 2), odim)
+ )
+ self.pos_enc = pos_enc_class
+ self.subsampling_rate = 4
+ self.right_context = 6
+
+ def forward(self, x, x_mask, offset=0):
+ x = x.unsqueeze(1)
+ x = self.conv(x)
+ b, c, t, f = x.size()
+ x = self.out(x.transpose(1, 2).contiguous().view(b, t, c * f))
+ x, pos_emb = self.pos_enc(x, offset)
+ return x, pos_emb, x_mask[:, :, 2::2][:, :, 2::2]
+
+
+class Conv2dSubsampling6(BaseSubsampling):
+ def __init__(self, idim: int, odim: int, dropout_rate: float, pos_enc_class):
+ super().__init__()
+ self.conv = torch.nn.Sequential(
+ torch.nn.Conv2d(1, odim, 3, 2),
+ torch.nn.ReLU(),
+ torch.nn.Conv2d(odim, odim, 5, 3),
+ torch.nn.ReLU(),
+ )
+ self.linear = torch.nn.Linear(odim * (((idim - 1) // 2 - 2) // 3), odim)
+ self.pos_enc = pos_enc_class
+ self.subsampling_rate = 6
+ self.right_context = 10
+
+ def forward(self, x, x_mask, offset=0):
+ x = x.unsqueeze(1)
+ x = self.conv(x)
+ b, c, t, f = x.size()
+ x = self.linear(x.transpose(1, 2).contiguous().view(b, t, c * f))
+ x, pos_emb = self.pos_enc(x, offset)
+ return x, pos_emb, x_mask[:, :, 2::2][:, :, 4::3]
+
+
+class Conv2dSubsampling8(BaseSubsampling):
+ def __init__(self, idim: int, odim: int, dropout_rate: float, pos_enc_class):
+ super().__init__()
+ self.conv = torch.nn.Sequential(
+ torch.nn.Conv2d(1, odim, 3, 2),
+ torch.nn.ReLU(),
+ torch.nn.Conv2d(odim, odim, 3, 2),
+ torch.nn.ReLU(),
+ torch.nn.Conv2d(odim, odim, 3, 2),
+ torch.nn.ReLU(),
+ )
+ self.linear = torch.nn.Linear(odim * ((((idim - 1) // 2 - 1) // 2 - 1) // 2), odim)
+ self.pos_enc = pos_enc_class
+ self.subsampling_rate = 8
+ self.right_context = 14
+
+ def forward(self, x, x_mask, offset=0):
+ x = x.unsqueeze(1)
+ x = self.conv(x)
+ b, c, t, f = x.size()
+ x = self.linear(x.transpose(1, 2).contiguous().view(b, t, c * f))
+ x, pos_emb = self.pos_enc(x, offset)
+ return x, pos_emb, x_mask[:, :, 2::2][:, :, 2::2][:, :, 2::2]
+
+
+_ACTIVATION_CLASSES = {
+ "hardtanh": torch.nn.Hardtanh,
+ "tanh": torch.nn.Tanh,
+ "relu": torch.nn.ReLU,
+ "selu": torch.nn.SELU,
+ "swish": getattr(torch.nn, "SiLU", Swish),
+ "gelu": torch.nn.GELU,
+}
+
+
+_SUBSAMPLE_CLASSES = {
+ "linear": LinearNoSubsampling,
+ "linear_legacy": LegacyLinearNoSubsampling,
+ "embed": EmbedinigNoSubsampling,
+ "conv1d2": Conv1dSubsampling2,
+ "conv2d": Conv2dSubsampling4,
+ "conv2d6": Conv2dSubsampling6,
+ "conv2d8": Conv2dSubsampling8,
+ "paraformer_dummy": torch.nn.Identity,
+}
+
+
+_EMB_CLASSES = {
+ "embed": PositionalEncoding,
+ "abs_pos": PositionalEncoding,
+ "rel_pos": RelPositionalEncoding,
+ "rel_pos_espnet": EspnetRelPositionalEncoding,
+ "no_pos": NoPositionalEncoding,
+ "abs_pos_whisper": WhisperPositionalEncoding,
+ "embed_learnable_pe": LearnablePositionalEncoding,
+}
+
+
+_ATTENTION_CLASSES = {
+ "selfattn": None, # filled below after class definition
+ "rel_selfattn": None, # filled below
+}
+
+
+def subsequent_chunk_mask(
+ size: int,
+ chunk_size: int,
+ num_left_chunks: int = -1,
+ device: torch.device = torch.device("cpu"),
+) -> torch.Tensor:
+ pos_idx = torch.arange(size, device=device)
+ block_value = (torch.div(pos_idx, chunk_size, rounding_mode='trunc') + 1) * chunk_size
+ ret = pos_idx.unsqueeze(0) < block_value.unsqueeze(1)
+ return ret
+
+
+def add_optional_chunk_mask(
+ xs: torch.Tensor,
+ masks: torch.Tensor,
+ use_dynamic_chunk: bool,
+ use_dynamic_left_chunk: bool,
+ decoding_chunk_size: int,
+ static_chunk_size: int,
+ num_decoding_left_chunks: int,
+ enable_full_context: bool = True,
+):
+ if use_dynamic_chunk:
+ max_len = xs.size(1)
+ if decoding_chunk_size < 0:
+ chunk_size = max_len
+ num_left_chunks = -1
+ elif decoding_chunk_size > 0:
+ chunk_size = decoding_chunk_size
+ num_left_chunks = num_decoding_left_chunks
+ else:
+ chunk_size = torch.randint(1, max_len, (1,)).item()
+ num_left_chunks = -1
+ if chunk_size > max_len // 2 and enable_full_context:
+ chunk_size = max_len
+ else:
+ chunk_size = chunk_size % 25 + 1
+ if use_dynamic_left_chunk:
+ max_left_chunks = (max_len - 1) // chunk_size
+ num_left_chunks = torch.randint(0, max_left_chunks, (1,)).item()
+ chunk_masks = subsequent_chunk_mask(xs.size(1), chunk_size, num_left_chunks, xs.device)
+ chunk_masks = chunk_masks.unsqueeze(0)
+ chunk_masks = masks & chunk_masks
+ elif static_chunk_size > 0:
+ num_left_chunks = num_decoding_left_chunks
+ chunk_masks = subsequent_chunk_mask(xs.size(1), static_chunk_size, num_left_chunks, xs.device)
+ chunk_masks = chunk_masks.unsqueeze(0)
+ chunk_masks = masks & chunk_masks
+ else:
+ chunk_masks = masks
+ assert chunk_masks.dtype == torch.bool
+ if (chunk_masks.sum(dim=-1) == 0).sum().item() != 0:
+ logger.warning(
+ "get chunk_masks all false at some timestep, force set to true, "
+ "make sure they are masked in future computation!"
+ )
+ chunk_masks[chunk_masks.sum(dim=-1) == 0] = True
+ return chunk_masks
+
+
+def make_pad_mask(lengths: torch.Tensor, max_len: int = 0) -> torch.Tensor:
+ lengths = lengths.long()
+ batch_size = lengths.size(0)
+ max_len = max_len if max_len > 0 else lengths.max().item()
+ seq_range = torch.arange(0, max_len, dtype=torch.int64, device=lengths.device)
+ seq_range_expand = seq_range.unsqueeze(0).expand(batch_size, max_len)
+ seq_length_expand = lengths.unsqueeze(-1)
+ mask = seq_range_expand >= seq_length_expand
+ return mask
+
+
+def get_intmeanflow_time_mixer(dims: int) -> nn.Linear:
+ """Diagonal init as described in 3.3 https://arxiv.org/pdf/2510.07979"""
+ layer = nn.Linear(dims * 2, dims, bias=False)
+ with torch.no_grad():
+ target_weight = torch.zeros(dims, 2 * dims)
+ target_weight[:, 0:dims] = torch.eye(dims)
+ layer.weight.data = target_weight
+ return layer
+
+
+class MultiHeadedAttention(nn.Module):
+ def __init__(self, n_head: int, n_feat: int, dropout_rate: float, key_bias: bool = True):
+ super().__init__()
+ assert n_feat % n_head == 0
+ self.d_k = n_feat // n_head
+ self.h = n_head
+ self.linear_q = nn.Linear(n_feat, n_feat)
+ self.linear_k = nn.Linear(n_feat, n_feat, bias=key_bias)
+ self.linear_v = nn.Linear(n_feat, n_feat)
+ self.linear_out = nn.Linear(n_feat, n_feat)
+ self.dropout = nn.Dropout(p=dropout_rate)
+
+ def forward_qkv(self, query, key, value):
+ n_batch = query.size(0)
+ q = self.linear_q(query).view(n_batch, -1, self.h, self.d_k)
+ k = self.linear_k(key).view(n_batch, -1, self.h, self.d_k)
+ v = self.linear_v(value).view(n_batch, -1, self.h, self.d_k)
+ q = q.transpose(1, 2)
+ k = k.transpose(1, 2)
+ v = v.transpose(1, 2)
+ return q, k, v
+
+ def forward_attention(self, value, scores, mask=torch.ones((0, 0, 0), dtype=torch.bool)):
+ n_batch = value.size(0)
+ if mask.size(2) > 0:
+ mask = mask.unsqueeze(1).eq(0)
+ mask = mask[:, :, :, :scores.size(-1)]
+ scores = scores.masked_fill(mask, -float('inf'))
+ attn = torch.softmax(scores, dim=-1).masked_fill(mask, 0.0)
+ else:
+ attn = torch.softmax(scores, dim=-1)
+ p_attn = self.dropout(attn)
+ x = torch.matmul(p_attn, value)
+ x = x.transpose(1, 2).contiguous().view(n_batch, -1, self.h * self.d_k)
+ return self.linear_out(x)
+
+ def forward(
+ self,
+ query,
+ key,
+ value,
+ mask=torch.ones((0, 0, 0), dtype=torch.bool),
+ pos_emb=torch.empty(0),
+ cache=torch.zeros((0, 0, 0, 0)),
+ ):
+ q, k, v = self.forward_qkv(query, key, value)
+ if cache.size(0) > 0:
+ key_cache, value_cache = torch.split(cache, cache.size(-1) // 2, dim=-1)
+ k = torch.cat([key_cache, k], dim=2)
+ v = torch.cat([value_cache, v], dim=2)
+ new_cache = torch.cat((k, v), dim=-1)
+ scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.d_k)
+ return self.forward_attention(v, scores, mask), new_cache
+
+
+class RelPositionMultiHeadedAttention(MultiHeadedAttention):
+ def __init__(self, n_head: int, n_feat: int, dropout_rate: float, key_bias: bool = True):
+ super().__init__(n_head, n_feat, dropout_rate, key_bias)
+ self.linear_pos = nn.Linear(n_feat, n_feat, bias=False)
+ self.pos_bias_u = nn.Parameter(torch.Tensor(self.h, self.d_k))
+ self.pos_bias_v = nn.Parameter(torch.Tensor(self.h, self.d_k))
+ torch.nn.init.xavier_uniform_(self.pos_bias_u)
+ torch.nn.init.xavier_uniform_(self.pos_bias_v)
+
+ def rel_shift(self, x: torch.Tensor) -> torch.Tensor:
+ zero_pad = torch.zeros((x.size()[0], x.size()[1], x.size()[2], 1), device=x.device, dtype=x.dtype)
+ x_padded = torch.cat([zero_pad, x], dim=-1)
+ x_padded = x_padded.view(x.size()[0], x.size()[1], x.size(3) + 1, x.size(2))
+ x = x_padded[:, :, 1:].view_as(x)[:, :, :, :x.size(-1) // 2 + 1]
+ return x
+
+ def forward(
+ self,
+ query,
+ key,
+ value,
+ mask=torch.ones((0, 0, 0), dtype=torch.bool),
+ pos_emb=torch.empty(0),
+ cache=torch.zeros((0, 0, 0, 0)),
+ ):
+ q, k, v = self.forward_qkv(query, key, value)
+ q = q.transpose(1, 2)
+ if cache.size(0) > 0:
+ key_cache, value_cache = torch.split(cache, cache.size(-1) // 2, dim=-1)
+ k = torch.cat([key_cache, k], dim=2)
+ v = torch.cat([value_cache, v], dim=2)
+ new_cache = torch.cat((k, v), dim=-1)
+ n_batch_pos = pos_emb.size(0)
+ p = self.linear_pos(pos_emb).view(n_batch_pos, -1, self.h, self.d_k)
+ p = p.transpose(1, 2)
+ q_with_bias_u = (q + self.pos_bias_u.to(q.device)).transpose(1, 2)
+ q_with_bias_v = (q + self.pos_bias_v.to(q.device)).transpose(1, 2)
+ matrix_ac = torch.matmul(q_with_bias_u, k.transpose(-2, -1))
+ matrix_bd = torch.matmul(q_with_bias_v, p.transpose(-2, -1))
+ if matrix_ac.shape != matrix_bd.shape:
+ matrix_bd = self.rel_shift(matrix_bd)
+ scores = (matrix_ac + matrix_bd) / math.sqrt(self.d_k)
+ return self.forward_attention(v, scores, mask), new_cache
+
+
+class ConvolutionModule(nn.Module):
+ def __init__(self, channels: int, kernel_size: int = 15, activation: nn.Module = nn.ReLU(),
+ norm: str = "batch_norm", causal: bool = False, bias: bool = True):
+ super().__init__()
+ self.pointwise_conv1 = nn.Conv1d(channels, 2 * channels, kernel_size=1, stride=1, padding=0, bias=bias)
+ if causal:
+ padding = 0
+ self.lorder = kernel_size - 1
+ else:
+ assert (kernel_size - 1) % 2 == 0
+ padding = (kernel_size - 1) // 2
+ self.lorder = 0
+ self.depthwise_conv = nn.Conv1d(
+ channels, channels, kernel_size, stride=1, padding=padding, groups=channels, bias=bias
+ )
+ assert norm in ['batch_norm', 'layer_norm']
+ if norm == "batch_norm":
+ self.use_layer_norm = False
+ self.norm = nn.BatchNorm1d(channels)
+ else:
+ self.use_layer_norm = True
+ self.norm = nn.LayerNorm(channels)
+ self.pointwise_conv2 = nn.Conv1d(channels, channels, kernel_size=1, stride=1, padding=0, bias=bias)
+ self.activation = activation
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ mask_pad: torch.Tensor = torch.ones((0, 0, 0), dtype=torch.bool),
+ cache: torch.Tensor = torch.zeros((0, 0, 0)),
+ ):
+ x = x.transpose(1, 2)
+ if mask_pad.size(2) > 0:
+ x.masked_fill_(~mask_pad, 0.0)
+ if self.lorder > 0:
+ if cache.size(2) == 0:
+ x = nn.functional.pad(x, (self.lorder, 0), 'constant', 0.0)
+ else:
+ assert cache.size(0) == x.size(0)
+ assert cache.size(1) == x.size(1)
+ x = torch.cat((cache, x), dim=2)
+ assert (x.size(2) > self.lorder)
+ new_cache = x[:, :, -self.lorder:]
+ else:
+ new_cache = torch.zeros((0, 0, 0), dtype=x.dtype, device=x.device)
+ x = self.pointwise_conv1(x)
+ x = nn.functional.glu(x, dim=1)
+ x = self.depthwise_conv(x)
+ if self.use_layer_norm:
+ x = x.transpose(1, 2)
+ x = self.activation(self.norm(x))
+ if self.use_layer_norm:
+ x = x.transpose(1, 2)
+ x = self.pointwise_conv2(x)
+ if mask_pad.size(2) > 0:
+ x.masked_fill_(~mask_pad, 0.0)
+ return x.transpose(1, 2), new_cache
+
+
+class PositionwiseFeedForward(torch.nn.Module):
+ def __init__(self, idim: int, hidden_units: int, dropout_rate: float,
+ activation: torch.nn.Module = torch.nn.ReLU()):
+ super(PositionwiseFeedForward, self).__init__()
+ self.w_1 = torch.nn.Linear(idim, hidden_units)
+ self.activation = activation
+ self.dropout = torch.nn.Dropout(dropout_rate)
+ self.w_2 = torch.nn.Linear(hidden_units, idim)
+
+ def forward(self, xs: torch.Tensor) -> torch.Tensor:
+ return self.w_2(self.dropout(self.activation(self.w_1(xs))))
+
+
+class ConformerEncoderLayer(nn.Module):
+ def __init__(self, size, self_attn, feed_forward=None, feed_forward_macaron=None,
+ conv_module=None, dropout_rate=0.1, normalize_before=True):
+ super().__init__()
+ self.self_attn = self_attn
+ self.feed_forward = feed_forward
+ self.feed_forward_macaron = feed_forward_macaron
+ self.conv_module = conv_module
+ self.norm_ff = nn.LayerNorm(size, eps=1e-12)
+ self.norm_mha = nn.LayerNorm(size, eps=1e-12)
+ if feed_forward_macaron is not None:
+ self.norm_ff_macaron = nn.LayerNorm(size, eps=1e-12)
+ self.ff_scale = 0.5
+ else:
+ self.ff_scale = 1.0
+ if self.conv_module is not None:
+ self.norm_conv = nn.LayerNorm(size, eps=1e-12)
+ self.norm_final = nn.LayerNorm(size, eps=1e-12)
+ self.dropout = nn.Dropout(dropout_rate)
+ self.size = size
+ self.normalize_before = normalize_before
+
+ def forward(self, x, mask, pos_emb, mask_pad=torch.ones((0, 0, 0), dtype=torch.bool),
+ att_cache=torch.zeros((0, 0, 0, 0)), cnn_cache=torch.zeros((0, 0, 0, 0))):
+ if self.feed_forward_macaron is not None:
+ residual = x
+ if self.normalize_before:
+ x = self.norm_ff_macaron(x)
+ x = residual + self.ff_scale * self.dropout(self.feed_forward_macaron(x))
+ if not self.normalize_before:
+ x = self.norm_ff_macaron(x)
+ residual = x
+ if self.normalize_before:
+ x = self.norm_mha(x)
+ x_att, new_att_cache = self.self_attn(x, x, x, mask, pos_emb, att_cache)
+ x = residual + self.dropout(x_att)
+ if not self.normalize_before:
+ x = self.norm_mha(x)
+ new_cnn_cache = torch.zeros((0, 0, 0), dtype=x.dtype, device=x.device)
+ if self.conv_module is not None:
+ residual = x
+ if self.normalize_before:
+ x = self.norm_conv(x)
+ x, new_cnn_cache = self.conv_module(x, mask_pad, cnn_cache)
+ x = residual + self.dropout(x)
+ if not self.normalize_before:
+ x = self.norm_conv(x)
+ residual = x
+ if self.normalize_before:
+ x = self.norm_ff(x)
+ x = residual + self.ff_scale * self.dropout(self.feed_forward(x))
+ if not self.normalize_before:
+ x = self.norm_ff(x)
+ if self.conv_module is not None:
+ x = self.norm_final(x)
+ return x, mask, new_att_cache, new_cnn_cache
+
+
+class _EncoderUpsample1D(nn.Module):
+ def __init__(self, channels: int, out_channels: int, stride: int = 2):
+ super().__init__()
+ self.channels = channels
+ self.out_channels = out_channels
+ self.stride = stride
+ self.conv = nn.Conv1d(self.channels, self.out_channels, stride * 2 + 1, stride=1, padding=0)
+
+ def forward(self, inputs: torch.Tensor, input_lengths: torch.Tensor):
+ outputs = F.interpolate(inputs, scale_factor=float(self.stride), mode="nearest")
+ outputs = F.pad(outputs, (self.stride * 2, 0), value=0.0)
+ outputs = self.conv(outputs)
+ return outputs, input_lengths * self.stride
+
+
+class PreLookaheadLayer(nn.Module):
+ def __init__(self, channels: int, pre_lookahead_len: int = 1):
+ super().__init__()
+ self.channels = channels
+ self.pre_lookahead_len = pre_lookahead_len
+ self.conv1 = nn.Conv1d(channels, channels, kernel_size=pre_lookahead_len + 1, stride=1, padding=0)
+ self.conv2 = nn.Conv1d(channels, channels, kernel_size=3, stride=1, padding=0)
+
+ def forward(self, inputs: torch.Tensor) -> torch.Tensor:
+ outputs = inputs.transpose(1, 2).contiguous()
+ outputs = F.pad(outputs, (0, self.pre_lookahead_len), mode='constant', value=0.0)
+ outputs = F.leaky_relu(self.conv1(outputs))
+ outputs = F.pad(outputs, (2, 0), mode='constant', value=0.0)
+ outputs = self.conv2(outputs)
+ outputs = outputs.transpose(1, 2).contiguous()
+ outputs = outputs + inputs
+ return outputs
+
+
+class UpsampleConformerEncoder(torch.nn.Module):
+ def __init__(
+ self,
+ input_size: int = 512,
+ output_size: int = 512,
+ attention_heads: int = 8,
+ linear_units: int = 2048,
+ num_blocks: int = 6,
+ dropout_rate: float = 0.1,
+ positional_dropout_rate: float = 0.1,
+ attention_dropout_rate: float = 0.1,
+ input_layer: str = "linear",
+ pos_enc_layer_type: str = "rel_pos_espnet",
+ normalize_before: bool = True,
+ static_chunk_size: int = 0,
+ use_dynamic_chunk: bool = False,
+ global_cmvn: torch.nn.Module = None,
+ use_dynamic_left_chunk: bool = False,
+ positionwise_conv_kernel_size: int = 1,
+ macaron_style: bool = False,
+ selfattention_layer_type: str = "rel_selfattn",
+ activation_type: str = "swish",
+ use_cnn_module: bool = False,
+ cnn_module_kernel: int = 15,
+ causal: bool = False,
+ cnn_module_norm: str = "batch_norm",
+ key_bias: bool = True,
+ gradient_checkpointing: bool = False,
+ num_up_blocks: int = 4,
+ ):
+ super().__init__()
+ self._output_size = output_size
+ self.global_cmvn = global_cmvn
+ self.embed = _SUBSAMPLE_CLASSES[input_layer](
+ input_size,
+ output_size,
+ dropout_rate,
+ _EMB_CLASSES[pos_enc_layer_type](output_size, positional_dropout_rate),
+ )
+ self.normalize_before = normalize_before
+ self.after_norm = torch.nn.LayerNorm(output_size, eps=1e-5)
+ self.static_chunk_size = static_chunk_size
+ self.use_dynamic_chunk = use_dynamic_chunk
+ self.use_dynamic_left_chunk = use_dynamic_left_chunk
+ self.gradient_checkpointing = gradient_checkpointing
+ activation = _ACTIVATION_CLASSES[activation_type]()
+ encoder_selfattn_layer_args = (attention_heads, output_size, attention_dropout_rate, key_bias)
+ positionwise_layer_args = (output_size, linear_units, dropout_rate, activation)
+ convolution_layer_args = (output_size, cnn_module_kernel, activation, cnn_module_norm, causal)
+ self.pre_lookahead_layer = PreLookaheadLayer(channels=output_size, pre_lookahead_len=3)
+ self.encoders = torch.nn.ModuleList([
+ ConformerEncoderLayer(
+ output_size,
+ _ATTENTION_CLASSES[selfattention_layer_type](*encoder_selfattn_layer_args),
+ PositionwiseFeedForward(*positionwise_layer_args),
+ PositionwiseFeedForward(*positionwise_layer_args) if macaron_style else None,
+ ConvolutionModule(*convolution_layer_args) if use_cnn_module else None,
+ dropout_rate,
+ normalize_before,
+ ) for _ in range(num_blocks)
+ ])
+ self.up_layer = _EncoderUpsample1D(channels=output_size, out_channels=output_size, stride=2)
+ self.up_embed = _SUBSAMPLE_CLASSES[input_layer](
+ input_size,
+ output_size,
+ dropout_rate,
+ _EMB_CLASSES[pos_enc_layer_type](output_size, positional_dropout_rate),
+ )
+ self.up_encoders = torch.nn.ModuleList([
+ ConformerEncoderLayer(
+ output_size,
+ _ATTENTION_CLASSES[selfattention_layer_type](*encoder_selfattn_layer_args),
+ PositionwiseFeedForward(*positionwise_layer_args),
+ PositionwiseFeedForward(*positionwise_layer_args) if macaron_style else None,
+ ConvolutionModule(*convolution_layer_args) if use_cnn_module else None,
+ dropout_rate,
+ normalize_before,
+ ) for _ in range(num_up_blocks)
+ ])
+
+ def output_size(self) -> int:
+ return self._output_size
+
+ def forward(self, xs: torch.Tensor, xs_lens: torch.Tensor,
+ decoding_chunk_size: int = 0, num_decoding_left_chunks: int = -1):
+ T = xs.size(1)
+ masks = ~make_pad_mask(xs_lens, T).unsqueeze(1)
+ if self.global_cmvn is not None:
+ xs = self.global_cmvn(xs)
+ xs, pos_emb, masks = self.embed(xs, masks)
+ mask_pad = masks
+ chunk_masks = add_optional_chunk_mask(
+ xs, masks, self.use_dynamic_chunk, self.use_dynamic_left_chunk,
+ decoding_chunk_size, self.static_chunk_size, num_decoding_left_chunks
+ )
+ xs = self.pre_lookahead_layer(xs)
+ xs = self._forward_layers(xs, chunk_masks, pos_emb, mask_pad)
+ xs = xs.transpose(1, 2).contiguous()
+ xs, xs_lens = self.up_layer(xs, xs_lens)
+ xs = xs.transpose(1, 2).contiguous()
+ T = xs.size(1)
+ masks = ~make_pad_mask(xs_lens, T).unsqueeze(1)
+ xs, pos_emb, masks = self.up_embed(xs, masks)
+ mask_pad = masks
+ chunk_masks = add_optional_chunk_mask(
+ xs, masks, self.use_dynamic_chunk, self.use_dynamic_left_chunk,
+ decoding_chunk_size, self.static_chunk_size * self.up_layer.stride, num_decoding_left_chunks
+ )
+ xs = self._forward_up_layers(xs, chunk_masks, pos_emb, mask_pad)
+ if self.normalize_before:
+ xs = self.after_norm(xs)
+ return xs, masks
+
+ def _forward_layers(self, xs, chunk_masks, pos_emb, mask_pad):
+ for layer in self.encoders:
+ xs, chunk_masks, _, _ = layer(xs, chunk_masks, pos_emb, mask_pad)
+ return xs
+
+ def _forward_up_layers(self, xs, chunk_masks, pos_emb, mask_pad):
+ for layer in self.up_encoders:
+ xs, chunk_masks, _, _ = layer(xs, chunk_masks, pos_emb, mask_pad)
+ return xs
+
+
+class SnakeBeta(nn.Module):
+ def __init__(self, in_features, out_features, alpha=1.0, alpha_trainable=True, alpha_logscale=True):
+ super().__init__()
+ self.in_features = out_features if isinstance(out_features, list) else [out_features]
+ self.proj = LoRACompatibleLinear(in_features, out_features)
+ self.alpha_logscale = alpha_logscale
+ if self.alpha_logscale:
+ self.alpha = nn.Parameter(torch.zeros(self.in_features) * alpha)
+ self.beta = nn.Parameter(torch.zeros(self.in_features) * alpha)
+ else:
+ self.alpha = nn.Parameter(torch.ones(self.in_features) * alpha)
+ self.beta = nn.Parameter(torch.ones(self.in_features) * alpha)
+ self.alpha.requires_grad = alpha_trainable
+ self.beta.requires_grad = alpha_trainable
+ self.no_div_by_zero = 0.000000001
+
+ def forward(self, x):
+ x = self.proj(x)
+ if self.alpha_logscale:
+ alpha = torch.exp(self.alpha)
+ beta = torch.exp(self.beta)
+ else:
+ alpha = self.alpha
+ beta = self.beta
+ x = x + (1.0 / (beta + self.no_div_by_zero)) * torch.pow(torch.sin(x * alpha), 2)
+ return x
+
+
+class _MatchaFeedForward(nn.Module):
+ def __init__(self, dim: int, dim_out: Optional[int] = None, mult: int = 4,
+ dropout: float = 0.0, activation_fn: str = "geglu", final_dropout: bool = False):
+ super().__init__()
+ inner_dim = int(dim * mult)
+ dim_out = dim_out if dim_out is not None else dim
+ if activation_fn == "gelu":
+ act_fn = GELU(dim, inner_dim)
+ if activation_fn == "gelu-approximate":
+ act_fn = GELU(dim, inner_dim, approximate="tanh")
+ elif activation_fn == "geglu":
+ act_fn = GEGLU(dim, inner_dim)
+ elif activation_fn == "geglu-approximate":
+ act_fn = ApproximateGELU(dim, inner_dim)
+ elif activation_fn == "snakebeta":
+ act_fn = SnakeBeta(dim, inner_dim)
+ self.net = nn.ModuleList([])
+ self.net.append(act_fn)
+ self.net.append(nn.Dropout(dropout))
+ self.net.append(LoRACompatibleLinear(inner_dim, dim_out))
+ if final_dropout:
+ self.net.append(nn.Dropout(dropout))
+
+ def forward(self, hidden_states):
+ for module in self.net:
+ hidden_states = module(hidden_states)
+ return hidden_states
+
+
+class BasicTransformerBlock(nn.Module):
+ def __init__(
+ self,
+ dim: int,
+ num_attention_heads: int,
+ attention_head_dim: int,
+ dropout=0.0,
+ cross_attention_dim: Optional[int] = None,
+ activation_fn: str = "geglu",
+ num_embeds_ada_norm: Optional[int] = None,
+ attention_bias: bool = False,
+ only_cross_attention: bool = False,
+ double_self_attention: bool = False,
+ upcast_attention: bool = False,
+ norm_elementwise_affine: bool = True,
+ norm_type: str = "layer_norm",
+ final_dropout: bool = False,
+ ):
+ super().__init__()
+ self.only_cross_attention = only_cross_attention
+ self.use_ada_layer_norm_zero = (num_embeds_ada_norm is not None) and norm_type == "ada_norm_zero"
+ self.use_ada_layer_norm = (num_embeds_ada_norm is not None) and norm_type == "ada_norm"
+
+ if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None:
+ raise ValueError(
+ f"`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined."
+ )
+ if self.use_ada_layer_norm:
+ self.norm1 = AdaLayerNorm(dim, num_embeds_ada_norm)
+ elif self.use_ada_layer_norm_zero:
+ self.norm1 = AdaLayerNormZero(dim, num_embeds_ada_norm)
+ else:
+ self.norm1 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine)
+ self.attn1 = Attention(
+ query_dim=dim,
+ heads=num_attention_heads,
+ dim_head=attention_head_dim,
+ dropout=dropout,
+ bias=attention_bias,
+ cross_attention_dim=cross_attention_dim if only_cross_attention else None,
+ upcast_attention=upcast_attention,
+ )
+ if cross_attention_dim is not None or double_self_attention:
+ self.norm2 = (
+ AdaLayerNorm(dim, num_embeds_ada_norm)
+ if self.use_ada_layer_norm
+ else nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine)
+ )
+ self.attn2 = Attention(
+ query_dim=dim,
+ cross_attention_dim=cross_attention_dim if not double_self_attention else None,
+ heads=num_attention_heads,
+ dim_head=attention_head_dim,
+ dropout=dropout,
+ bias=attention_bias,
+ upcast_attention=upcast_attention,
+ )
+ else:
+ self.norm2 = None
+ self.attn2 = None
+ self.norm3 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine)
+ self.ff = _MatchaFeedForward(dim, dropout=dropout, activation_fn=activation_fn,
+ final_dropout=final_dropout)
+ self._chunk_size = None
+ self._chunk_dim = 0
+
+ def set_chunk_feed_forward(self, chunk_size: Optional[int], dim: int):
+ self._chunk_size = chunk_size
+ self._chunk_dim = dim
+
+ def forward(
+ self,
+ hidden_states: torch.FloatTensor,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
+ timestep: Optional[torch.LongTensor] = None,
+ cross_attention_kwargs: Dict[str, Any] = None,
+ class_labels: Optional[torch.LongTensor] = None,
+ ):
+ if self.use_ada_layer_norm:
+ norm_hidden_states = self.norm1(hidden_states, timestep)
+ elif self.use_ada_layer_norm_zero:
+ norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(
+ hidden_states, timestep, class_labels, hidden_dtype=hidden_states.dtype
+ )
+ else:
+ norm_hidden_states = self.norm1(hidden_states)
+
+ cross_attention_kwargs = cross_attention_kwargs if cross_attention_kwargs is not None else {}
+ attn_output = self.attn1(
+ norm_hidden_states,
+ encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,
+ attention_mask=encoder_attention_mask if self.only_cross_attention else attention_mask,
+ **cross_attention_kwargs,
+ )
+ if self.use_ada_layer_norm_zero:
+ attn_output = gate_msa.unsqueeze(1) * attn_output
+ hidden_states = attn_output + hidden_states
+
+ if self.attn2 is not None:
+ norm_hidden_states = (
+ self.norm2(hidden_states, timestep) if self.use_ada_layer_norm else self.norm2(hidden_states)
+ )
+ attn_output = self.attn2(
+ norm_hidden_states,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=encoder_attention_mask,
+ **cross_attention_kwargs,
+ )
+ hidden_states = attn_output + hidden_states
+
+ norm_hidden_states = self.norm3(hidden_states)
+ if self.use_ada_layer_norm_zero:
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
+
+ if self._chunk_size is not None:
+ if norm_hidden_states.shape[self._chunk_dim] % self._chunk_size != 0:
+ raise ValueError(
+ f"`hidden_states` dimension to be chunked: {norm_hidden_states.shape[self._chunk_dim]} "
+ f"has to be divisible by chunk size: {self._chunk_size}."
+ )
+ num_chunks = norm_hidden_states.shape[self._chunk_dim] // self._chunk_size
+ ff_output = torch.cat(
+ [self.ff(hid_slice) for hid_slice in norm_hidden_states.chunk(num_chunks, dim=self._chunk_dim)],
+ dim=self._chunk_dim,
+ )
+ else:
+ ff_output = self.ff(norm_hidden_states)
+
+ if self.use_ada_layer_norm_zero:
+ ff_output = gate_mlp.unsqueeze(1) * ff_output
+ hidden_states = ff_output + hidden_states
+ return hidden_states
+
+
+class SinusoidalPosEmb(torch.nn.Module):
+ def __init__(self, dim):
+ super().__init__()
+ self.dim = dim
+ assert self.dim % 2 == 0
+
+ def forward(self, x, scale=1000):
+ if x.ndim < 1:
+ x = x.unsqueeze(0)
+ device = x.device
+ half_dim = self.dim // 2
+ emb = math.log(10000) / (half_dim - 1)
+ emb = torch.exp(torch.arange(half_dim, device=device).float() * -emb)
+ emb = scale * x.unsqueeze(1) * emb.unsqueeze(0)
+ emb = torch.cat((emb.sin(), emb.cos()), dim=-1)
+ return emb
+
+
+class Block1D(torch.nn.Module):
+ def __init__(self, dim: int, dim_out: int, groups: int = 8):
+ super().__init__()
+ self.block = torch.nn.Sequential(
+ torch.nn.Conv1d(dim, dim_out, 3, padding=1),
+ torch.nn.GroupNorm(groups, dim_out),
+ nn.Mish(),
+ )
+
+ def forward(self, x: torch.Tensor, mask: torch.Tensor):
+ output = self.block(x * mask)
+ return output * mask
+
+
+class ResnetBlock1D(torch.nn.Module):
+ def __init__(self, dim: int, dim_out: int, time_emb_dim: int, groups: int = 8):
+ super().__init__()
+ self.mlp = torch.nn.Sequential(nn.Mish(), torch.nn.Linear(time_emb_dim, dim_out))
+ self.block1 = Block1D(dim, dim_out, groups=groups)
+ self.block2 = Block1D(dim_out, dim_out, groups=groups)
+ self.res_conv = torch.nn.Conv1d(dim, dim_out, 1)
+
+ def forward(self, x, mask, time_emb):
+ h = self.block1(x, mask)
+ h += self.mlp(time_emb).unsqueeze(-1)
+ h = self.block2(h, mask)
+ output = h + self.res_conv(x * mask)
+ return output
+
+
+class Downsample1D(nn.Module):
+ def __init__(self, dim):
+ super().__init__()
+ self.conv = torch.nn.Conv1d(dim, dim, 3, 2, 1)
+
+ def forward(self, x):
+ return self.conv(x)
+
+
+class TimestepEmbedding(nn.Module):
+ def __init__(self, in_channels: int, time_embed_dim: int, act_fn: str = "silu",
+ out_dim: int = None, post_act_fn: Optional[str] = None, cond_proj_dim=None):
+ super().__init__()
+ from diffusers.models.activations import get_activation
+ self.linear_1 = nn.Linear(in_channels, time_embed_dim)
+ if cond_proj_dim is not None:
+ self.cond_proj = nn.Linear(cond_proj_dim, in_channels, bias=False)
+ else:
+ self.cond_proj = None
+ self.act = get_activation(act_fn)
+ time_embed_dim_out = out_dim if out_dim is not None else time_embed_dim
+ self.linear_2 = nn.Linear(time_embed_dim, time_embed_dim_out)
+ self.post_act = get_activation(post_act_fn) if post_act_fn is not None else None
+
+ def forward(self, sample, condition=None):
+ if condition is not None:
+ sample = sample + self.cond_proj(condition)
+ sample = self.linear_1(sample)
+ if self.act is not None:
+ sample = self.act(sample)
+ sample = self.linear_2(sample)
+ if self.post_act is not None:
+ sample = self.post_act(sample)
+ return sample
+
+
+class Upsample1D(nn.Module):
+ """Matcha 1D upsample layer (ConvTranspose1d-based)."""
+
+ def __init__(self, channels, use_conv=False, use_conv_transpose=True, out_channels=None, name="conv"):
+ super().__init__()
+ self.channels = channels
+ self.out_channels = out_channels or channels
+ self.use_conv = use_conv
+ self.use_conv_transpose = use_conv_transpose
+ self.name = name
+ self.conv = None
+ if use_conv_transpose:
+ self.conv = nn.ConvTranspose1d(channels, self.out_channels, 4, 2, 1)
+ elif use_conv:
+ self.conv = nn.Conv1d(self.channels, self.out_channels, 3, padding=1)
+
+ def forward(self, inputs):
+ assert inputs.shape[1] == self.channels
+ if self.use_conv_transpose:
+ return self.conv(inputs)
+ outputs = F.interpolate(inputs, scale_factor=2.0, mode="nearest")
+ if self.use_conv:
+ outputs = self.conv(outputs)
+ return outputs
+
+
+class BASECFM(torch.nn.Module, ABC):
+ def __init__(self, n_feats, cfm_params, n_spks=1, spk_emb_dim=128):
+ super().__init__()
+ self.n_feats = n_feats
+ self.n_spks = n_spks
+ self.spk_emb_dim = spk_emb_dim
+ self.solver = cfm_params.solver
+ self.sigma_min = cfm_params.sigma_min if hasattr(cfm_params, "sigma_min") else 1e-4
+ self.estimator = None
+
+ @torch.inference_mode()
+ def forward(self, mu, mask, n_timesteps, temperature=1.0, spks=None, cond=None):
+ z = torch.randn_like(mu) * temperature
+ t_span = torch.linspace(0, 1, n_timesteps + 1, device=mu.device)
+ return self._solve_euler(z, t_span=t_span, mu=mu, mask=mask, spks=spks, cond=cond)
+
+ def _solve_euler(self, x, t_span, mu, mask, spks, cond):
+ t, _, dt = t_span[0], t_span[-1], t_span[1] - t_span[0]
+ sol = []
+ for step in range(1, len(t_span)):
+ dphi_dt = self.estimator(x, mask, mu, t, spks, cond)
+ x = x + dt * dphi_dt
+ t = t + dt
+ sol.append(x)
+ if step < len(t_span) - 1:
+ dt = t_span[step + 1] - t
+ return sol[-1]
+
+ def compute_loss(self, x1, mask, mu, spks=None, cond=None):
+ b, _, t = mu.shape
+ t = torch.rand([b, 1, 1], device=mu.device, dtype=mu.dtype)
+ z = torch.randn_like(x1)
+ y = (1 - (1 - self.sigma_min) * t) * z + t * x1
+ u = x1 - (1 - self.sigma_min) * z
+ loss = F.mse_loss(self.estimator(y, mask, mu, t.squeeze(), spks), u, reduction="sum") / (
+ torch.sum(mask) * u.shape[1]
+ )
+ return loss, y
+
+
+def _mask_to_bias(mask: torch.Tensor, dtype: torch.dtype) -> torch.Tensor:
+ assert mask.dtype == torch.bool
+ assert dtype in [torch.float32, torch.bfloat16, torch.float16]
+ mask = mask.to(dtype)
+ mask = (1.0 - mask) * -1.0e+10
+ return mask
+
+
+class _Transpose(torch.nn.Module):
+ def __init__(self, dim0: int, dim1: int):
+ super().__init__()
+ self.dim0 = dim0
+ self.dim1 = dim1
+
+ def forward(self, x: torch.Tensor):
+ return torch.transpose(x, self.dim0, self.dim1)
+
+
+class CausalConv1d(torch.nn.Conv1d):
+ def __init__(self, in_channels, out_channels, kernel_size, stride=1, dilation=1,
+ groups=1, bias=True, padding_mode='zeros', device=None, dtype=None):
+ super(CausalConv1d, self).__init__(
+ in_channels, out_channels, kernel_size, stride, padding=0, dilation=dilation,
+ groups=groups, bias=bias, padding_mode=padding_mode, device=device, dtype=dtype
+ )
+ assert stride == 1
+ self.causal_padding = (kernel_size - 1, 0)
+
+ def forward(self, x: torch.Tensor):
+ x = F.pad(x, self.causal_padding)
+ return super(CausalConv1d, self).forward(x)
+
+
+class CausalBlock1D(Block1D):
+ def __init__(self, dim: int, dim_out: int):
+ super(CausalBlock1D, self).__init__(dim, dim_out)
+ self.block = torch.nn.Sequential(
+ CausalConv1d(dim, dim_out, 3),
+ _Transpose(1, 2),
+ nn.LayerNorm(dim_out),
+ _Transpose(1, 2),
+ nn.Mish(),
+ )
+
+ def forward(self, x: torch.Tensor, mask: torch.Tensor):
+ output = self.block(x * mask)
+ return output * mask
+
+
+class CausalResnetBlock1D(ResnetBlock1D):
+ def __init__(self, dim: int, dim_out: int, time_emb_dim: int, groups: int = 8):
+ super(CausalResnetBlock1D, self).__init__(dim, dim_out, time_emb_dim, groups)
+ self.block1 = CausalBlock1D(dim, dim_out)
+ self.block2 = CausalBlock1D(dim_out, dim_out)
+
+
+class ConditionalDecoder(nn.Module):
+ def __init__(
+ self,
+ in_channels=320,
+ out_channels=80,
+ causal=True,
+ channels=[256],
+ dropout=0.0,
+ attention_head_dim=64,
+ n_blocks=4,
+ num_mid_blocks=12,
+ num_heads=8,
+ act_fn="gelu",
+ meanflow=False,
+ ):
+ super().__init__()
+ channels = tuple(channels)
+ self.meanflow = meanflow
+ self.in_channels = in_channels
+ self.out_channels = out_channels
+ self.causal = causal
+ self.time_embeddings = SinusoidalPosEmb(in_channels)
+ time_embed_dim = channels[0] * 4
+ self.time_mlp = TimestepEmbedding(in_channels=in_channels, time_embed_dim=time_embed_dim, act_fn="silu")
+ self.down_blocks = nn.ModuleList([])
+ self.mid_blocks = nn.ModuleList([])
+ self.up_blocks = nn.ModuleList([])
+ self.static_chunk_size = 0
+
+ output_channel = in_channels
+ for i in range(len(channels)):
+ input_channel = output_channel
+ output_channel = channels[i]
+ is_last = i == len(channels) - 1
+ resnet = (
+ CausalResnetBlock1D(dim=input_channel, dim_out=output_channel, time_emb_dim=time_embed_dim)
+ if self.causal
+ else ResnetBlock1D(dim=input_channel, dim_out=output_channel, time_emb_dim=time_embed_dim)
+ )
+ transformer_blocks = nn.ModuleList([
+ BasicTransformerBlock(
+ dim=output_channel, num_attention_heads=num_heads,
+ attention_head_dim=attention_head_dim, dropout=dropout, activation_fn=act_fn,
+ ) for _ in range(n_blocks)
+ ])
+ downsample = (
+ Downsample1D(output_channel) if not is_last else
+ CausalConv1d(output_channel, output_channel, 3) if self.causal
+ else nn.Conv1d(output_channel, output_channel, 3, padding=1)
+ )
+ self.down_blocks.append(nn.ModuleList([resnet, transformer_blocks, downsample]))
+
+ for _ in range(num_mid_blocks):
+ input_channel = channels[-1]
+ resnet = (
+ CausalResnetBlock1D(dim=input_channel, dim_out=output_channel, time_emb_dim=time_embed_dim)
+ if self.causal
+ else ResnetBlock1D(dim=input_channel, dim_out=output_channel, time_emb_dim=time_embed_dim)
+ )
+ transformer_blocks = nn.ModuleList([
+ BasicTransformerBlock(
+ dim=output_channel, num_attention_heads=num_heads,
+ attention_head_dim=attention_head_dim, dropout=dropout, activation_fn=act_fn,
+ ) for _ in range(n_blocks)
+ ])
+ self.mid_blocks.append(nn.ModuleList([resnet, transformer_blocks]))
+
+ channels = channels[::-1] + (channels[0],)
+ for i in range(len(channels) - 1):
+ input_channel = channels[i] * 2
+ output_channel = channels[i + 1]
+ is_last = i == len(channels) - 2
+ resnet = (
+ CausalResnetBlock1D(dim=input_channel, dim_out=output_channel, time_emb_dim=time_embed_dim)
+ if self.causal
+ else ResnetBlock1D(dim=input_channel, dim_out=output_channel, time_emb_dim=time_embed_dim)
+ )
+ transformer_blocks = nn.ModuleList([
+ BasicTransformerBlock(
+ dim=output_channel, num_attention_heads=num_heads,
+ attention_head_dim=attention_head_dim, dropout=dropout, activation_fn=act_fn,
+ ) for _ in range(n_blocks)
+ ])
+ upsample = (
+ Upsample1D(output_channel, use_conv_transpose=True) if not is_last else
+ CausalConv1d(output_channel, output_channel, 3) if self.causal
+ else nn.Conv1d(output_channel, output_channel, 3, padding=1)
+ )
+ self.up_blocks.append(nn.ModuleList([resnet, transformer_blocks, upsample]))
+
+ self.final_block = (
+ CausalBlock1D(channels[-1], channels[-1]) if self.causal else Block1D(channels[-1], channels[-1])
+ )
+ self.final_proj = nn.Conv1d(channels[-1], self.out_channels, 1)
+ self.initialize_weights()
+ self.time_embed_mixer = None
+ if self.meanflow:
+ self.time_embed_mixer = get_intmeanflow_time_mixer(time_embed_dim)
+
+ @property
+ def dtype(self):
+ return self.final_proj.weight.dtype
+
+ def initialize_weights(self):
+ for m in self.modules():
+ if isinstance(m, nn.Conv1d):
+ nn.init.kaiming_normal_(m.weight, nonlinearity="relu")
+ if m.bias is not None:
+ nn.init.constant_(m.bias, 0)
+ elif isinstance(m, nn.GroupNorm):
+ nn.init.constant_(m.weight, 1)
+ nn.init.constant_(m.bias, 0)
+ elif isinstance(m, nn.Linear):
+ nn.init.kaiming_normal_(m.weight, nonlinearity="relu")
+ if m.bias is not None:
+ nn.init.constant_(m.bias, 0)
+
+ def forward(self, x, mask, mu, t, spks=None, cond=None, r=None):
+ t = self.time_embeddings(t).to(t.dtype)
+ t = self.time_mlp(t)
+ if self.meanflow:
+ r = self.time_embeddings(r).to(t.dtype)
+ r = self.time_mlp(r)
+ concat_embed = torch.cat([t, r], dim=1)
+ t = self.time_embed_mixer(concat_embed)
+ x = pack([x, mu], "b * t")[0]
+ if spks is not None:
+ spks = repeat(spks, "b c -> b c t", t=x.shape[-1])
+ x = pack([x, spks], "b * t")[0]
+ if cond is not None:
+ x = pack([x, cond], "b * t")[0]
+ hiddens = []
+ masks = [mask]
+ for resnet, transformer_blocks, downsample in self.down_blocks:
+ mask_down = masks[-1]
+ x = resnet(x, mask_down, t)
+ x = rearrange(x, "b c t -> b t c").contiguous()
+ attn_mask = add_optional_chunk_mask(x, mask_down.bool(), False, False, 0, self.static_chunk_size, -1)
+ attn_mask = _mask_to_bias(attn_mask == 1, x.dtype)
+ for transformer_block in transformer_blocks:
+ x = transformer_block(hidden_states=x, attention_mask=attn_mask, timestep=t)
+ x = rearrange(x, "b t c -> b c t").contiguous()
+ hiddens.append(x)
+ x = downsample(x * mask_down)
+ masks.append(mask_down[:, :, ::2])
+ masks = masks[:-1]
+ mask_mid = masks[-1]
+ for resnet, transformer_blocks in self.mid_blocks:
+ x = resnet(x, mask_mid, t)
+ x = rearrange(x, "b c t -> b t c").contiguous()
+ attn_mask = add_optional_chunk_mask(x, mask_mid.bool(), False, False, 0, self.static_chunk_size, -1)
+ attn_mask = _mask_to_bias(attn_mask == 1, x.dtype)
+ for transformer_block in transformer_blocks:
+ x = transformer_block(hidden_states=x, attention_mask=attn_mask, timestep=t)
+ x = rearrange(x, "b t c -> b c t").contiguous()
+ for resnet, transformer_blocks, upsample in self.up_blocks:
+ mask_up = masks.pop()
+ skip = hiddens.pop()
+ x = pack([x[:, :, :skip.shape[-1]], skip], "b * t")[0]
+ x = resnet(x, mask_up, t)
+ x = rearrange(x, "b c t -> b t c").contiguous()
+ attn_mask = add_optional_chunk_mask(x, mask_up.bool(), False, False, 0, self.static_chunk_size, -1)
+ attn_mask = _mask_to_bias(attn_mask == 1, x.dtype)
+ for transformer_block in transformer_blocks:
+ x = transformer_block(hidden_states=x, attention_mask=attn_mask, timestep=t)
+ x = rearrange(x, "b t c -> b c t").contiguous()
+ x = upsample(x * mask_up)
+ x = self.final_block(x, mask_up)
+ output = self.final_proj(x * mask_up)
+ return output * mask
+
+
+def _cast_all(*args, dtype):
+ return [a if (not a.dtype.is_floating_point) or a.dtype == dtype else a.to(dtype) for a in args]
+
+
+class ConditionalCFM(BASECFM):
+ def __init__(self, in_channels, cfm_params, n_spks=1, spk_emb_dim=64, estimator=None):
+ super().__init__(n_feats=in_channels, cfm_params=cfm_params, n_spks=n_spks, spk_emb_dim=spk_emb_dim)
+ self.t_scheduler = cfm_params.t_scheduler
+ self.training_cfg_rate = cfm_params.training_cfg_rate
+ self.inference_cfg_rate = cfm_params.inference_cfg_rate
+ self.estimator = estimator
+
+ def solve_euler(self, x, t_span, mu, mask, spks, cond, meanflow=False):
+ in_dtype = x.dtype
+ x, t_span, mu, mask, spks, cond = _cast_all(x, t_span, mu, mask, spks, cond, dtype=self.estimator.dtype)
+ B, T = mu.size(0), x.size(2)
+ x_in = torch.zeros([2 * B, 80, T], device=x.device, dtype=x.dtype)
+ mask_in = torch.zeros([2 * B, 1, T], device=x.device, dtype=x.dtype)
+ mu_in = torch.zeros([2 * B, 80, T], device=x.device, dtype=x.dtype)
+ t_in = torch.zeros([2 * B ], device=x.device, dtype=x.dtype)
+ spks_in = torch.zeros([2 * B, 80 ], device=x.device, dtype=x.dtype)
+ cond_in = torch.zeros([2 * B, 80, T], device=x.device, dtype=x.dtype)
+ r_in = torch.zeros([2 * B ], device=x.device, dtype=x.dtype)
+
+ for t, r in zip(t_span[:-1], t_span[1:]):
+ t = t.unsqueeze(dim=0)
+ r = r.unsqueeze(dim=0)
+ x_in[:B] = x_in[B:] = x
+ mask_in[:B] = mask_in[B:] = mask
+ mu_in[:B] = mu
+ t_in[:B] = t_in[B:] = t
+ spks_in[:B] = spks
+ cond_in[:B] = cond
+ r_in[:B] = r_in[B:] = r
+ dxdt = self.estimator.forward(
+ x=x_in, mask=mask_in, mu=mu_in, t=t_in, spks=spks_in, cond=cond_in,
+ r=r_in if meanflow else None,
+ )
+ dxdt, cfg_dxdt = torch.split(dxdt, [B, B], dim=0)
+ dxdt = ((1.0 + self.inference_cfg_rate) * dxdt - self.inference_cfg_rate * cfg_dxdt)
+ dt = r - t
+ x = x + dt * dxdt
+
+ return x.to(in_dtype)
+
+ def compute_loss(self, x1, mask, mu, spks=None, cond=None):
+ b, _, t = mu.shape
+ t = torch.rand([b, 1, 1], device=mu.device, dtype=mu.dtype)
+ if self.t_scheduler == 'cosine':
+ t = 1 - torch.cos(t * 0.5 * torch.pi)
+ z = torch.randn_like(x1)
+ y = (1 - (1 - self.sigma_min) * t) * z + t * x1
+ u = x1 - (1 - self.sigma_min) * z
+ if self.training_cfg_rate > 0:
+ cfg_mask = torch.rand(b, device=x1.device) > self.training_cfg_rate
+ mu = mu * cfg_mask.view(-1, 1, 1)
+ spks = spks * cfg_mask.view(-1, 1)
+ cond = cond * cfg_mask.view(-1, 1, 1)
+ pred = self.estimator(y, mask, mu, t.squeeze(), spks, cond)
+ loss = F.mse_loss(pred * mask, u * mask, reduction="sum") / (torch.sum(mask) * u.shape[1])
+ return loss, y
+
+
+class CausalConditionalCFM(ConditionalCFM):
+ def __init__(self, in_channels=240, cfm_params=CFM_PARAMS, n_spks=1, spk_emb_dim=80, estimator=None):
+ super().__init__(in_channels, cfm_params, n_spks, spk_emb_dim, estimator)
+ self.rand_noise = None
+
+ @torch.inference_mode()
+ def forward(self, mu, mask, n_timesteps, temperature=1.0, spks=None, cond=None,
+ noised_mels=None, meanflow=False):
+ B = mu.size(0)
+ z = torch.randn_like(mu)
+ if noised_mels is not None:
+ prompt_len = mu.size(2) - noised_mels.size(2)
+ z[..., prompt_len:] = noised_mels
+ t_span = torch.linspace(0, 1, n_timesteps + 1, device=mu.device, dtype=mu.dtype)
+ if (not meanflow) and (self.t_scheduler == 'cosine'):
+ t_span = 1 - torch.cos(t_span * 0.5 * torch.pi)
+ if meanflow:
+ return self.basic_euler(z, t_span=t_span, mu=mu, mask=mask, spks=spks, cond=cond), None
+ return self.solve_euler(z, t_span=t_span, mu=mu, mask=mask, spks=spks, cond=cond, meanflow=meanflow), None
+
+ def basic_euler(self, x, t_span, mu, mask, spks, cond):
+ in_dtype = x.dtype
+ x, t_span, mu, mask, spks, cond = _cast_all(x, t_span, mu, mask, spks, cond, dtype=self.estimator.dtype)
+ print("S3 Token -> Mel Inference...")
+ for t, r in tqdm(zip(t_span[..., :-1], t_span[..., 1:]), total=t_span.shape[-1] - 1):
+ t, r = t[None], r[None]
+ dxdt = self.estimator.forward(x, mask=mask, mu=mu, t=t, spks=spks, cond=cond, r=r)
+ dt = r - t
+ x = x + dt * dxdt
+ return x.to(in_dtype)
+
+
+def _repeat_batch_dim(tnsr, B, ndim):
+ if tnsr is not None:
+ while tnsr.ndim < ndim:
+ tnsr = tnsr[None]
+ if B > 1 and tnsr.size(0) == 1:
+ tnsr = tnsr.repeat(B, *([1] * (ndim - 1)))
+ assert tnsr.ndim == ndim
+ return tnsr
+
+
+class CausalMaskedDiffWithXvec(torch.nn.Module):
+ def __init__(
+ self,
+ input_size: int = 512,
+ output_size: int = 80,
+ spk_embed_dim: int = 192,
+ output_type: str = "mel",
+ vocab_size: int = 6561,
+ input_frame_rate: int = 25,
+ only_mask_loss: bool = True,
+ token_mel_ratio: int = 2,
+ pre_lookahead_len: int = 3,
+ encoder: torch.nn.Module = None,
+ decoder: torch.nn.Module = None,
+ decoder_conf: Dict = {
+ 'in_channels': 240, 'out_channel': 80, 'spk_emb_dim': 80, 'n_spks': 1,
+ 'cfm_params': DictConfig({
+ 'sigma_min': 1e-06, 'solver': 'euler', 't_scheduler': 'cosine',
+ 'training_cfg_rate': 0.2, 'inference_cfg_rate': 0.7, 'reg_loss_type': 'l1',
+ }),
+ 'decoder_params': {
+ 'channels': [256, 256], 'dropout': 0.0, 'attention_head_dim': 64,
+ 'n_blocks': 4, 'num_mid_blocks': 12, 'num_heads': 8, 'act_fn': 'gelu',
+ },
+ },
+ mel_feat_conf: Dict = {
+ 'n_fft': 1024, 'num_mels': 80, 'sampling_rate': 22050,
+ 'hop_size': 256, 'win_size': 1024, 'fmin': 0, 'fmax': 8000,
+ },
+ ):
+ super().__init__()
+ self.input_size = input_size
+ self.output_size = output_size
+ self.decoder_conf = decoder_conf
+ self.mel_feat_conf = mel_feat_conf
+ self.vocab_size = vocab_size
+ self.output_type = output_type
+ self.input_frame_rate = input_frame_rate
+ self.input_embedding = nn.Embedding(vocab_size, input_size)
+ self.spk_embed_affine_layer = torch.nn.Linear(spk_embed_dim, output_size)
+ self.encoder = encoder
+ self.encoder_proj = torch.nn.Linear(self.encoder.output_size(), output_size)
+ self.decoder = decoder
+ self.only_mask_loss = only_mask_loss
+ self.token_mel_ratio = token_mel_ratio
+ self.pre_lookahead_len = pre_lookahead_len
+
+ @torch.inference_mode()
+ def inference(self, token, token_len, prompt_token, prompt_token_len, prompt_feat,
+ prompt_feat_len, embedding, finalize, n_timesteps=10, noised_mels=None, meanflow=False):
+ B = token.size(0)
+ embedding = torch.atleast_2d(embedding)
+ embedding = F.normalize(embedding, dim=1)
+ embedding = self.spk_embed_affine_layer(embedding)
+ prompt_token = _repeat_batch_dim(prompt_token, B, ndim=2)
+ prompt_token_len = _repeat_batch_dim(prompt_token_len, B, ndim=1)
+ prompt_feat = _repeat_batch_dim(prompt_feat, B, ndim=3)
+ prompt_feat_len = _repeat_batch_dim(prompt_feat_len, B, ndim=1)
+ embedding = _repeat_batch_dim(embedding, B, ndim=2)
+ token, token_len = torch.concat([prompt_token, token], dim=1), prompt_token_len + token_len
+ mask = (~make_pad_mask(token_len)).unsqueeze(-1).to(embedding)
+ if (token >= self.vocab_size).any():
+ logger.error(f"{token.max()}>{self.vocab_size}\n out-of-range special tokens found in flow!")
+ token = self.input_embedding(token.long()) * mask
+ h, h_masks = self.encoder(token, token_len)
+ if finalize is False:
+ h = h[:, :-self.pre_lookahead_len * self.token_mel_ratio]
+ h_lengths = h_masks.sum(dim=-1).squeeze(dim=-1)
+ mel_len1, mel_len2 = prompt_feat.shape[1], h.shape[1] - prompt_feat.shape[1]
+ h = self.encoder_proj(h)
+ conds = torch.zeros([B, mel_len1 + mel_len2, self.output_size], device=token.device).to(h.dtype)
+ conds[:, :mel_len1] = prompt_feat
+ conds = conds.transpose(1, 2)
+ mask = (~make_pad_mask(h_lengths)).unsqueeze(1).to(h)
+ if mask.shape[0] != B:
+ mask = mask.repeat(B, 1, 1)
+ feat, _ = self.decoder(
+ mu=h.transpose(1, 2).contiguous(),
+ mask=mask,
+ spks=embedding,
+ cond=conds,
+ n_timesteps=n_timesteps,
+ noised_mels=noised_mels,
+ meanflow=meanflow,
+ )
+ feat = feat[:, :, mel_len1:]
+ assert feat.shape[2] == mel_len2
+ return feat, None
+
+
+_SUBSAMPLE_CLASSES = {"linear": LinearNoSubsampling}
+_EMB_CLASSES = {"rel_pos_espnet": EspnetRelPositionalEncoding}
+_ATTENTION_CLASSES = {"rel_selfattn": RelPositionMultiHeadedAttention}
+_ACTIVATION_CLASSES = {"swish": torch.nn.SiLU}
+
+
+# ── construction and the single-step sampler, from s3gen_flow_distill.py ────────
+
+
+N_SILENCE_TOKENS = 3
+
+
+N_MELS = 80
+
+
+ARCH_PRESETS = {
+ # 56.90 M · 501 ms · 8.3x real time
+ "half_params": dict(
+ encoder_output_size=368, encoder_linear_units=1472,
+ encoder_num_blocks=6, encoder_num_up_blocks=4, encoder_attention_heads=8,
+ estimator_channels=176, estimator_n_blocks=4,
+ estimator_num_mid_blocks=12, estimator_num_heads=8,
+ estimator_attention_head_dim=44,
+ ),
+ # 114.65 M · the teacher's own shape. Same capacity, not a smaller model —
+ # only useful paired with quantisation, where the win is bits per weight.
+ "full_params": dict(
+ encoder_output_size=512, encoder_linear_units=2048,
+ encoder_num_blocks=6, encoder_num_up_blocks=4, encoder_attention_heads=8,
+ estimator_channels=256, estimator_n_blocks=4,
+ estimator_num_mid_blocks=12, estimator_num_heads=8,
+ estimator_attention_head_dim=64,
+ ),
+ # 14.40 M · 12.6 % of teacher. exp43's shape, width-tuned to one eighth.
+ "eighth_params": dict(
+ encoder_output_size=168, encoder_linear_units=672,
+ encoder_num_blocks=6, encoder_num_up_blocks=4, encoder_attention_heads=8,
+ estimator_channels=88, estimator_n_blocks=4,
+ estimator_num_mid_blocks=12, estimator_num_heads=8,
+ estimator_attention_head_dim=24,
+ ),
+ # 7.10 M · 6.2 % of teacher. Same again at one sixteenth.
+ "sixteenth_params": dict(
+ encoder_output_size=128, encoder_linear_units=512,
+ encoder_num_blocks=6, encoder_num_up_blocks=4, encoder_attention_heads=8,
+ estimator_channels=56, estimator_n_blocks=4,
+ estimator_num_mid_blocks=12, estimator_num_heads=8,
+ estimator_attention_head_dim=16,
+ ),
+ # 57.14 M · 242 ms · 17.2x real time
+ "f1": dict(
+ encoder_output_size=368, encoder_linear_units=1472,
+ encoder_num_blocks=8, encoder_num_up_blocks=2, encoder_attention_heads=8,
+ estimator_channels=[160, 200, 256], estimator_n_blocks=2,
+ estimator_num_mid_blocks=8, estimator_num_heads=8,
+ estimator_attention_head_dim=64,
+ ),
+ # 57.69 M · 148 ms · 28.1x real time. Five widening stages put the mid
+ # blocks on 27 frames instead of 432; no conformer layer runs at the mel
+ # rate; four heads rather than eight, which CPU BLAS prefers.
+ "fast": dict(
+ encoder_output_size=336, encoder_linear_units=1344,
+ encoder_num_blocks=10, encoder_num_up_blocks=0, encoder_attention_heads=4,
+ estimator_channels=[104, 120, 160, 200, 264], estimator_n_blocks=2,
+ estimator_num_mid_blocks=12, estimator_num_heads=4,
+ estimator_attention_head_dim=64,
+ ),
+}
+
+
+def build_flow(
+ encoder_output_size: int = 512,
+ encoder_linear_units: int = 2048,
+ encoder_num_blocks: int = 6,
+ encoder_num_up_blocks: int = 4,
+ encoder_attention_heads: int = 8,
+ estimator_channels: int = 256,
+ estimator_n_blocks: int = 4,
+ estimator_num_mid_blocks: int = 12,
+ estimator_num_heads: int = 8,
+ estimator_attention_head_dim: int = 64,
+) -> CausalMaskedDiffWithXvec:
+ """Build a meanflow S3Gen flow. Defaults reproduce the released architecture.
+
+ Halving every width argument yields the pruned student. The mel dimension
+ (80) and the x-vector dimension (192) are interfaces to frozen components and
+ stay fixed.
+
+ ``estimator_channels`` takes an int for the released single-stage shape, or a
+ list for a genuinely hierarchical UNet: every entry past the first adds a
+ stride-2 stage, so the mid blocks then run at a fraction of the mel rate.
+ That is the single biggest CPU lever, since mid-block attention is quadratic
+ in sequence length.
+ """
+ encoder = UpsampleConformerEncoder(
+ input_size=encoder_output_size,
+ output_size=encoder_output_size,
+ attention_heads=encoder_attention_heads,
+ linear_units=encoder_linear_units,
+ num_blocks=encoder_num_blocks,
+ num_up_blocks=encoder_num_up_blocks,
+ dropout_rate=0.1,
+ positional_dropout_rate=0.1,
+ attention_dropout_rate=0.1,
+ normalize_before=True,
+ input_layer="linear",
+ pos_enc_layer_type="rel_pos_espnet",
+ selfattention_layer_type="rel_selfattn",
+ use_cnn_module=False,
+ macaron_style=False,
+ )
+ est_channels = (
+ [estimator_channels] if isinstance(estimator_channels, int)
+ else list(estimator_channels)
+ )
+ estimator = ConditionalDecoder(
+ in_channels=4 * N_MELS,
+ out_channels=N_MELS,
+ causal=True,
+ channels=est_channels,
+ dropout=0.0,
+ attention_head_dim=estimator_attention_head_dim,
+ n_blocks=estimator_n_blocks,
+ num_mid_blocks=estimator_num_mid_blocks,
+ num_heads=estimator_num_heads,
+ act_fn="gelu",
+ meanflow=True,
+ )
+ decoder = CausalConditionalCFM(
+ spk_emb_dim=N_MELS, cfm_params=CFM_PARAMS, estimator=estimator
+ )
+ return CausalMaskedDiffWithXvec(
+ input_size=encoder_output_size, encoder=encoder, decoder=decoder
+ )
+
+
+def meanflow_forward(
+ flow: CausalMaskedDiffWithXvec,
+ token,
+ token_len,
+ prompt_token,
+ prompt_token_len,
+ prompt_feat,
+ embedding,
+ z=None,
+ n_steps: int = 1,
+):
+ """Run ``flow`` from noise to mel with ``n_steps`` meanflow Euler steps.
+
+ Mirrors ``CausalMaskedDiffWithXvec.inference`` with ``finalize=True``, minus
+ the ``inference_mode`` decorator, so gradients reach the student's weights.
+ Classifier-free guidance is skipped, matching ``basic_euler``: the meanflow
+ weights are trained without it.
+
+ Args:
+ z: starting noise over prompt *and* speech frames,
+ ``[B, 80, 2 * (prompt_tokens + tokens)]``. Drawn internally when
+ ``None``, which is how the teacher creates the noise it then hands to
+ the student.
+
+ Returns:
+ ``(mel, mask, z)`` — mel ``[B, 80, T_speech]`` and its validity mask
+ ``[B, 80, T_speech]``, both already stripped of the prompt region, plus
+ the noise actually integrated.
+ """
+ B = token.size(0)
+
+ embedding = F.normalize(torch.atleast_2d(embedding), dim=1)
+ embedding = flow.spk_embed_affine_layer(embedding)
+
+ token = torch.cat([prompt_token, token], dim=1)
+ token_len = prompt_token_len + token_len
+ token_mask = (~make_pad_mask(token_len)).unsqueeze(-1).to(embedding)
+ token = flow.input_embedding(token.long()) * token_mask
+
+ h, h_masks = flow.encoder(token, token_len)
+ h_lengths = h_masks.sum(dim=-1).squeeze(dim=-1)
+ mel_len1 = prompt_feat.shape[1]
+ h = flow.encoder_proj(h)
+
+ conds = torch.zeros(B, h.shape[1], flow.output_size, device=h.device, dtype=h.dtype)
+ conds[:, :mel_len1] = prompt_feat
+ conds = conds.transpose(1, 2)
+
+ mask = (~make_pad_mask(h_lengths)).unsqueeze(1).to(h)
+ if mask.shape[0] != B:
+ mask = mask.repeat(B, 1, 1)
+
+ mu = h.transpose(1, 2).contiguous()
+ if z is None:
+ z = torch.randn_like(mu) # encoder_proj makes mu [B, 80, T], same shape as x
+ x = z.to(dtype=mu.dtype)
+
+ estimator = flow.decoder.estimator
+ t_span = torch.linspace(0, 1, n_steps + 1, device=mu.device, dtype=mu.dtype)
+ for t, r in zip(t_span[:-1], t_span[1:]):
+ dxdt = estimator(
+ x, mask=mask, mu=mu, t=t[None], spks=embedding, cond=conds, r=r[None]
+ )
+ x = x + (r - t) * dxdt
+
+ mel = x[:, :, mel_len1:]
+ mel_mask = mask[:, :, mel_len1:].expand(-1, N_MELS, -1)
+ return mel, mel_mask, z
diff --git a/kittenml/kittentts2/ternary.py b/kittenml/kittentts2/ternary.py
new file mode 100644
index 0000000..1ec3bcc
--- /dev/null
+++ b/kittenml/kittentts2/ternary.py
@@ -0,0 +1,120 @@
+"""Lossless 1.58-bit packing for the language model's ternary weights.
+
+The checkpoint's linear weights are ternary: within every 128-wide group, each
+value is exactly one of {-scale, 0, +scale}. Stored as bf16 that costs 16 bits per
+weight to say one of three things, so the file is 3.47 GB when the information in
+it fits in about 0.95 GB.
+
+Packing is therefore **exact, not approximate**. Each weight becomes a trit, five
+trits pack into one byte (3^5 = 243 < 256, so 8/5 = 1.6 bits per weight — the
+"1.58 bit" of log2(3) rounded up to a whole byte boundary), and each group keeps
+its scale at full bf16 precision. Unpacking reproduces the original tensor
+bit-for-bit.
+
+Tensors that are not ternary — the token embedding, the layer norms, the speaker
+projection — are stored unchanged at their original dtype. They are only 0.325B of
+the 1.735B parameters but, being dense, they dominate the packed file.
+
+ lm/model.safetensors 3.47 GB bf16 throughout
+ lm/model-ternary.safetensors 0.95 GB same weights, 3.6x smaller
+"""
+
+import json
+
+import torch
+
+# The group width the checkpoint was quantised with. Each group carries one
+# scale, so this has to match how the weights were produced.
+GROUP_SIZE = 128
+
+# Trits per byte. 3**5 = 243 fits in a byte; 3**6 = 729 does not.
+TRITS_PER_BYTE = 5
+
+_POWERS = torch.tensor([3 ** i for i in range(TRITS_PER_BYTE)], dtype=torch.int32)
+
+
+def is_ternary(tensor, group_size=GROUP_SIZE):
+ """True when every `group_size`-wide group holds only {-s, 0, +s} for some s.
+
+ Checked exactly. A tensor that is merely close to ternary is not packable, and
+ silently treating it as such would lose accuracy.
+ """
+ if tensor.dim() != 2 or tensor.shape[1] % group_size:
+ return False
+ grouped = tensor.float().reshape(tensor.shape[0], -1, group_size)
+ magnitude = grouped.abs()
+ scale = magnitude.amax(dim=2, keepdim=True)
+ nonzero = grouped != 0
+ return bool(torch.all(~nonzero | (magnitude == scale)))
+
+
+def pack_state_dict(state_dict, group_size=GROUP_SIZE):
+ """Split a state dict into packed ternary tensors and untouched dense ones.
+
+ Returns (tensors, metadata) ready to hand to `safetensors.torch.save_file`.
+ """
+ tensors, packed_keys = {}, {}
+ for name, tensor in state_dict.items():
+ if not is_ternary(tensor, group_size):
+ tensors[name] = tensor.contiguous()
+ continue
+ codes, scale = _to_trits(tensor, group_size)
+ tensors[f"{name}::codes"] = _pack_trits(codes)
+ tensors[f"{name}::scale"] = scale
+ packed_keys[name] = {
+ "shape": list(tensor.shape),
+ "dtype": str(tensor.dtype).removeprefix("torch."),
+ }
+ metadata = {
+ "format": "kittenml-ternary-1.58",
+ "group_size": str(group_size),
+ "packed": json.dumps(packed_keys),
+ }
+ return tensors, metadata
+
+
+def unpack_state_dict(tensors, metadata):
+ """Rebuild the original state dict from `pack_state_dict`'s output."""
+ if metadata.get("format") != "kittenml-ternary-1.58":
+ raise ValueError(f"not a packed ternary checkpoint: {metadata.get('format')!r}")
+ group_size = int(metadata["group_size"])
+ packed_keys = json.loads(metadata["packed"])
+
+ state = {k: v for k, v in tensors.items() if "::" not in k}
+ for name, spec in packed_keys.items():
+ shape = torch.Size(spec["shape"])
+ trits = _unpack_trits(tensors[f"{name}::codes"], shape.numel())
+ scale = tensors[f"{name}::scale"]
+ state[name] = _from_trits(trits, scale, shape, group_size,
+ getattr(torch, spec["dtype"]))
+ return state
+
+
+def _to_trits(tensor, group_size):
+ """Ternary weights -> trits in {0, 1, 2} for {-s, 0, +s}, plus per-group scales."""
+ grouped = tensor.reshape(tensor.shape[0], -1, group_size)
+ scale = grouped.abs().amax(dim=2, keepdim=True)
+ # sign() gives -1/0/+1; shift to 0/1/2 so it fits an unsigned base-3 digit.
+ trits = (grouped.sign().to(torch.int8) + 1).reshape(-1)
+ return trits, scale.squeeze(2).contiguous()
+
+
+def _from_trits(trits, scale, shape, group_size, dtype):
+ signs = (trits.to(torch.int8) - 1).reshape(shape[0], -1, group_size)
+ scale = scale.reshape(shape[0], -1, 1)
+ return (signs.to(scale.dtype) * scale).reshape(shape).to(dtype).contiguous()
+
+
+def _pack_trits(trits):
+ """Five base-3 digits per byte."""
+ padding = (-trits.numel()) % TRITS_PER_BYTE
+ if padding:
+ trits = torch.cat([trits, torch.zeros(padding, dtype=trits.dtype)])
+ digits = trits.to(torch.int32).reshape(-1, TRITS_PER_BYTE)
+ return (digits * _POWERS).sum(dim=1).to(torch.uint8).contiguous()
+
+
+def _unpack_trits(packed, numel):
+ values = packed.to(torch.int32).unsqueeze(1)
+ digits = torch.div(values, _POWERS, rounding_mode="floor") % 3
+ return digits.reshape(-1)[:numel]
diff --git a/kittenml/kittentts2/text.py b/kittenml/kittentts2/text.py
new file mode 100644
index 0000000..a516ecf
--- /dev/null
+++ b/kittenml/kittentts2/text.py
@@ -0,0 +1,411 @@
+"""Text handling for KittenTTS 2: expression markup, normalization, chunking, joining.
+
+KittenTTS 2 accepts three expression controls that the ONNX models do not:
+
+ [joyful] We won the grant <laugh> I can (((hardly))) believe it!
+
+A leading `[emotion]` tag, inline `<event>` tags, and `(((emphasis)))` spans. They
+are director's notes for the model, not text to pronounce, so they must reach it
+verbatim — which means protecting them before normalization and restoring them
+after. Any *other* bracketed span is rewritten to plain comma-separated text,
+since the model destabilises on bracket punctuation it was not trained to read.
+
+Long text is split on sentence boundaries and synthesized chunk by chunk. One
+generate() call for a whole script is where the model falls apart — it truncates
+or drifts into repetition — while it is reliable on short inputs, so chunking
+keeps every generation inside the range it handles well.
+
+The written-to-spoken step — expanding numbers, currency, dates and abbreviations
+— is delegated to `_backend`, and this module only owns what wraps it. Several
+regexes below exist to steer that backend away from known misreadings (paired
+quotes read as inches, fused version strings, digit-adjacent ?/!), and are kept
+so the text reaching the model matches what it heard in serving.
+"""
+
+import re
+
+import numpy as np
+
+
+# ── expression markup ─────────────────────────────────────────────────────────
+# Restricted to a known tag vocabulary rather than "any bracketed span", so we know
+# exactly when a span is a real tag. Text that merely looks bracketed — a citation
+# like "section [3]", a comparison like "x < 5" — is normalized like ordinary text
+# instead of being silently exempted. Extend these sets to protect more tags.
+EXPRESSION_TAGS = frozenset({
+ "mundane", "nervous", "tender", "angry", "excited",
+ "stern", "sad", "contemplative", "surprised", "joyful",
+})
+VOCAL_EVENT_TAGS = frozenset({
+ "pause", "sigh", "gasp", "laugh", "giggle",
+ "sob", "scoff", "growl", "um", "gulp",
+})
+
+_TAG_SPAN = re.compile(
+ r"\[(?:" + "|".join(re.escape(t) for t in EXPRESSION_TAGS) + r")\]"
+ r"|<(?:" + "|".join(re.escape(t) for t in VOCAL_EVENT_TAGS) + r")>",
+ re.IGNORECASE,
+)
+_EMPHASIS_SPAN = re.compile(r"\(\(\(([^()\n]{1,80})\)\)\)")
+_PLACEHOLDER = "\ue000{}\ue001" # private-use sentinels; cannot occur in real input
+
+
+def _protect_tags(text):
+ """Swap every tag and emphasis span for a sentinel-wrapped index.
+
+ The normalizer must not see them, and must not be able to reorder or reword
+ them. The default backend passes private-use sentinels through untouched, which
+ makes this safe; the index inside is restored verbatim afterwards.
+ """
+ tags = []
+
+ def _swap(match):
+ tags.append(match.group(0))
+ return _PLACEHOLDER.format(len(tags) - 1)
+
+ return _EMPHASIS_SPAN.sub(_swap, _TAG_SPAN.sub(_swap, text)), tags
+
+
+def _restore_tags(text, tags):
+ for i, tag in enumerate(tags):
+ text = text.replace(_PLACEHOLDER.format(i), tag)
+ return text
+
+
+def has_expression_tag(text):
+ """True when the text uses any expression, vocal-event or emphasis control.
+
+ Drives the `{emo: 1}` conditioning prefix: the control is only spliced into the
+ prompt when the user actually reaches for one of these markers.
+ """
+ s = str(text or "")
+ return bool(_TAG_SPAN.search(s) or _EMPHASIS_SPAN.search(s))
+
+
+# ── written -> spoken ─────────────────────────────────────────────────────────
+_UI_GLYPHS = re.compile(r"[\u2022\u2023\u2043\u25e6\u25b8\u21b3\u2192\u2190\u2191\u2193]+")
+
+# Raw math glyphs reach the model as rare tokens and destabilise it, and the normalizer
+# either passes them through or picks stilted readings ("=" -> "equal sign"). Spoken
+# forms are substituted first so any digits they produce still go through its number
+# grammar. Readings follow how papers are read aloud ("y ~ pi" -> "distributed as")
+# rather than notation-theoretic precision.
+_MATH_GLYPH_WORDS = {
+ "\u03b1": "alpha", "\u03b2": "beta", "\u03b3": "gamma", "\u03b4": "delta", "\u03b5": "epsilon", "\u03b6": "zeta",
+ "\u03b7": "eta", "\u03b8": "theta", "\u03b9": "iota", "\u03ba": "kappa", "\u03bb": "lambda", "\u03bc": "mu",
+ "\u03bd": "nu", "\u03be": "xi", "\u03c0": "pi", "\u03c1": "rho", "\u03c3": "sigma", "\u03c4": "tau",
+ "\u03c5": "upsilon", "\u03c6": "phi", "\u03d5": "phi", "\u03c7": "chi", "\u03c8": "psi", "\u03c9": "omega",
+ "\u0393": "gamma", "\u0394": "delta", "\u0398": "theta", "\u039b": "lambda", "\u039e": "xi", "\u03a0": "pi",
+ "\u03a3": "sigma", "\u03a6": "phi", "\u03a8": "psi", "\u03a9": "omega",
+ "=": "equals", "\u2260": "is not equal to", "\u2248": "approximately equals",
+ "\u2264": "is less than or equal to", "\u2265": "is greater than or equal to",
+ "\u00b1": "plus or minus", "\u00d7": "times", "\u00f7": "divided by", "\u00b7": "dot",
+ "\u2212": "minus", "\u2217": "star", "\u2218": "composed with", "\u22a4": "transpose",
+ "\u223c": "distributed as", "\u221d": "proportional to", "\u2261": "is equivalent to",
+ "\u2208": "in", "\u2209": "not in", "\u2282": "subset of", "\u2286": "subset of", "\u222a": "union",
+ "\u2229": "intersect", "\u2295": "plus", "\u2297": "times", "^": "to the",
+ "\u2211": "sum of", "\u220f": "product of", "\u222b": "integral of", "\u2202": "partial",
+ "\u2207": "gradient of", "\u221a": "square root of", "\u221e": "infinity", "\u2206": "delta",
+ "\u2200": "for all", "\u2203": "there exists", "\u21d2": "implies", "\u21d4": "if and only if",
+ "\u2225": "norm", "\u2016": "norm", "\u230a": "floor of", "\u230b": "", "\u2308": "ceiling of", "\u2309": "",
+ "\u211d": "R", "\u2115": "N", "\u2124": "Z", "\u211a": "Q", "\u2102": "C", "\U0001d53c": "the expectation of",
+}
+# Super/subscript digits -> plain digits, so "x²" becomes "x 2" and normalizes onward.
+_MATH_GLYPH_WORDS.update({c: str(d) for d, pair in
+ enumerate(zip("\u2070\u00b9\u00b2\u00b3\u2074\u2075\u2076\u2077\u2078\u2079", "\u2080\u2081\u2082\u2083\u2084\u2085\u2086\u2087\u2088\u2089")) for c in pair})
+_MATH_GLYPH_RE = re.compile("|".join(re.escape(g) for g in
+ sorted(_MATH_GLYPH_WORDS, key=len, reverse=True)))
+
+# PDF pastes render "…" as spaced periods; either form is a pause, not three spoken dots.
+_ELLIPSIS = re.compile(r"(?:\.\s+){2,}\.|\u2026|\.\.\.")
+
+# A straight double quote right after a digit is ambiguous between a closing quotation
+# mark and inches, and the measure grammar always reads it as inches — silently
+# eating the closing quote. Retyping PAIRED straight quotes as curly disambiguates the
+# common case while leaving a genuinely unpaired one ('the TV is 50" wide') as inches.
+_STRAIGHT_QUOTE_PAIR = re.compile(r'"([^"\n]*)"')
+
+_NONTAG_BRACKET_SPAN = re.compile(r"\[([^\[\]\n]{1,400})\]|<([^<>\n]{1,60})>|\(([^()\n]{1,400})\)")
+# ", VPO,," — a rewritten span's trailing comma colliding with punctuation that already
+# followed the bracket; keep whichever mark came after it.
+_COMMA_COLLISION = re.compile(r",\s*([,.!?;:])")
+
+_TRAILING_NONTERMINAL = re.compile(r"[,;:\-\u2013\u2014]+\s*$")
+_ALREADY_TERMINATED = set('.!?"\u2019\u201d\')]')
+
+# Em/en dashes -> commas. The checkpoint has little dash-delimited training data, and
+# nested em-dashes were the most reliable way to make a chunk run away in testing. A
+# comma carries the same prosodic break with far more support in the data. Hyphens are
+# deliberately left alone: the normalizer writes 21-99 as hyphenated words, so converting
+# them would speak "twenty-six miles" as "twenty, six miles".
+_DASH = re.compile(r"\s*(?:[\u2014\u2013]|--)\s*")
+_DASH_FIX = [
+ (re.compile(r",\s*,+"), ", "),
+ (re.compile(r"\s+([,.!?;:])"), r"\1"),
+ (re.compile(r",\s*([.!?])"), r"\1"),
+ (re.compile(r"\s{2,}"), " "),
+ (re.compile(r"^\s*,\s*"), ""),
+]
+
+
+def _speak_math_glyphs(text):
+ text = _ELLIPSIS.sub(", ", text)
+ text = _MATH_GLYPH_RE.sub(lambda m: f" {_MATH_GLYPH_WORDS[m.group(0)]} ", text)
+ return re.sub(r"[ \t]{2,}", " ", text)
+
+
+def _reformat_nontag_brackets(text):
+ def _swap(match):
+ inner = next(g for g in match.groups() if g is not None).strip()
+ return f", {inner},"
+
+ text = _NONTAG_BRACKET_SPAN.sub(_swap, text)
+ while True: # ", , ," needs repeated passes to collapse
+ collapsed = _COMMA_COLLISION.sub(r"\1", text)
+ if collapsed == text:
+ return collapsed
+ text = collapsed
+
+
+def _smart_quote_pairs(text):
+ return _STRAIGHT_QUOTE_PAIR.sub(lambda m: "\u201c" + m.group(1) + "\u201d", text)
+
+
+def _dashes_to_commas(text):
+ if not text:
+ return text
+ text = _DASH.sub(", ", text)
+ for pattern, replacement in _DASH_FIX:
+ text = pattern.sub(replacement, text)
+ return text.strip()
+
+
+def _capitalize_and_terminate(text):
+ """Capitalize the opening letter and guarantee sentence-final punctuation.
+
+ Runs on the tag-protected text, so the first alphabetic character it finds is
+ always the first real word — a placeholder carries no letters, so this can
+ never reach inside a tag and capitalize its deliberately lowercase contents.
+ """
+ if not text:
+ return text
+ text = re.sub(r"\s+([?!])", r"\1", text) # re-attach marks detached for the number grammar
+ for i, ch in enumerate(text):
+ if ch.isalpha():
+ text = text[:i] + ch.upper() + text[i + 1:]
+ break
+ stripped = text.rstrip()
+ if not stripped:
+ return text
+ if stripped[-1] in _ALREADY_TERMINATED:
+ return stripped
+ stripped = _TRAILING_NONTERMINAL.sub("", stripped).rstrip()
+ return stripped + "." if stripped else stripped
+
+
+# ── the written -> spoken backend ─────────────────────────────────────────────
+# kitten_text_processing reproduces the normalization this checkpoint was served
+# with, which is what makes the text the model hears match production. It is pure
+# Python with no compiled dependencies, so it installs everywhere and is an
+# ordinary requirement rather than something to detect at run time.
+import kitten_text_processing as _backend
+
+# Tags are held out of normalization by wrapping them in private-use sentinels and
+# sending the whole string through in one call — the backend must therefore leave
+# those codepoints alone. It declares that it does; checked here because the
+# failure is silent and ugly if it ever stops being true (the sentinels vanish and
+# the model speaks the placeholder index, so "[joyful]" comes out as "Zero").
+if not getattr(_backend, "PRESERVES_SENTINELS", False):
+ raise RuntimeError(
+ "kitten_text_processing no longer preserves private-use sentinels; "
+ "expression tags would be corrupted. Pin an earlier version.")
+
+
+def warm_normalizer():
+ """Build the backend's grammars now rather than inside the first request."""
+ _backend.warm()
+
+
+def normalize_text(text, normalize=True):
+ """Turn written text into the spoken form the model should hear.
+
+ Never raises: every failure path falls back to the lightly-cleaned text.
+ The written-to-spoken step itself comes from `_backend`.
+ Expression markup is protected before anything else runs and restored on
+ every return path, so it survives identically whether normalization
+ succeeds, fails, or is switched off.
+ """
+ protected, tags = _protect_tags(str(text or ""))
+ # Hard line wraps otherwise reach the sentence splitter as missing spaces:
+ # "require.\nWe" collapses to "require.We", the boundary regex cannot see it, and
+ # the fused pseudo-sentence falls into mid-clause splits that are audible as seams.
+ protected = re.sub(r"\s*\n+\s*", " ", protected)
+ protected = re.sub(r"(?<=[a-z])([.!?;:])(?=[A-Z])", r"\1 ", protected)
+ protected = _speak_math_glyphs(protected)
+ # "V0.8" -> "V 0 point 8": fused version tokens land in the serial grammar and
+ # read as "dot"; split out, the separators stay "point".
+ protected = re.sub(r"\b([vV])(\d+(?:\.\d+)+)",
+ lambda m: m.group(1) + " " + " point ".join(m.group(2).split(".")),
+ protected)
+ # Detach sentence-final ?/! from a trailing digit, which the number grammar would
+ # otherwise consume and speak aloud. _capitalize_and_terminate re-attaches it.
+ protected = re.sub(r"(?<=\d)\s*([?!])(?=\s|$)", r" \1", protected)
+
+ raw = _dashes_to_commas(_UI_GLYPHS.sub(" ", _reformat_nontag_brackets(protected)))
+ if not raw.strip():
+ return _restore_tags(raw, tags)
+ if not normalize:
+ return _restore_tags(_capitalize_and_terminate(raw), tags)
+ try:
+ spoken = (_backend.normalize_text(_smart_quote_pairs(raw)) or "").strip()
+ except Exception as exc: # a normalizer problem must not cost a generation
+ print(f"[normalize] {type(exc).__name__} on {raw[:60]!r}, speaking raw text: {exc}",
+ flush=True)
+ spoken = ""
+ if not spoken:
+ return _restore_tags(_capitalize_and_terminate(raw), tags)
+ return _restore_tags(_capitalize_and_terminate(_dashes_to_commas(spoken)), tags)
+
+
+# ── chunking ──────────────────────────────────────────────────────────────────
+# 380 rather than the ~560 first tried: the model compresses its delivery as a chunk
+# grows, so longer chunks read as rushed even when every word is correct.
+CHUNK_CHARS = 380
+# Undersized chunks are the unstable ones — the model over-generates on short prompts
+# and holds a token instead of terminating — so fold anything below this into a
+# neighbour rather than generating it alone.
+CHUNK_MIN_CHARS = 130
+CHUNK_GAP_S = 0.16
+
+_SENT_END = re.compile(r'(?<=[.!?])["’”\')\]]*\s+')
+_TERMINAL = '.!?,;:'
+
+
+def split_for_synthesis(text, max_chars=CHUNK_CHARS, min_chars=CHUNK_MIN_CHARS):
+ """Sentence-aware greedy packing.
+
+ Returns a single chunk when the text already fits, so short and medium inputs
+ take the unchunked path exactly as they would without this.
+ """
+ stripped = (text or "").strip()
+ if not max_chars or len(stripped) <= max_chars:
+ return [stripped] if stripped else []
+ out, current = [], ""
+ for sentence in [s for s in _SENT_END.split(stripped) if s and s.strip()]:
+ sentence = sentence.strip()
+ while len(sentence) > max_chars:
+ # A sentence longer than the budget: break at the last clause boundary
+ # before the limit, falling back to a hard split so this cannot loop.
+ cut = max(sentence.rfind(", ", 0, max_chars), sentence.rfind("; ", 0, max_chars),
+ sentence.rfind(" — ", 0, max_chars))
+ cut = cut + 1 if cut > max_chars // 3 else max_chars
+ head, sentence = sentence[:cut].strip(), sentence[cut:].strip()
+ if current:
+ out.append(current)
+ current = ""
+ out.append(head)
+ if not current:
+ current = sentence
+ elif len(current) + 1 + len(sentence) <= max_chars:
+ current += " " + sentence
+ else:
+ out.append(current)
+ current = sentence
+ if current:
+ out.append(current)
+ return [_ensure_terminal_punct(c) for c in _merge_short(out, max_chars, min_chars)]
+
+
+def _merge_short(parts, max_chars, min_chars):
+ """Fold undersized chunks into a neighbour, preferring the smaller result.
+
+ Merging only ever removes a boundary, never creates one mid-sentence. The budget
+ stretches to 1.4x rather than refusing to merge, since a slightly long chunk is
+ far safer than a very short one.
+ """
+ if not parts or min_chars <= 0:
+ return parts
+ out = list(parts)
+ limit = int(max_chars * 1.4)
+ changed = True
+ while changed and len(out) > 1:
+ changed = False
+ for i, chunk in enumerate(out):
+ if len(chunk) >= min_chars:
+ continue
+ prev_ok = i > 0 and len(out[i - 1]) + 1 + len(chunk) <= limit
+ next_ok = i < len(out) - 1 and len(chunk) + 1 + len(out[i + 1]) <= limit
+ if prev_ok and (not next_ok or len(out[i - 1]) <= len(out[i + 1])):
+ out[i - 1] = out[i - 1].rstrip() + " " + chunk.lstrip()
+ out.pop(i)
+ elif next_ok:
+ out[i] = chunk.rstrip() + " " + out[i + 1].lstrip()
+ out.pop(i + 1)
+ else:
+ continue # nothing it can merge into; leave it
+ changed = True
+ break
+ return out
+
+
+def _ensure_terminal_punct(chunk):
+ """Give every chunk a closing mark.
+
+ A chunk that ends mid-phrase gives the model no cue that it is done, which is
+ when it holds a token and produces a tail artefact. A clause break gets a comma
+ rather than a full stop, so the prosody stays continuation-like.
+ """
+ c = (chunk or "").rstrip()
+ if not c:
+ return c
+ if c[-1] in _TERMINAL or c[-1] in '"’”\')]':
+ return c
+ return c + ","
+
+
+# ── joining ───────────────────────────────────────────────────────────────────
+def trim_silence(wav, sample_rate, thresh_db=-45.0, keep_s=0.02):
+ """Strip the lead-in and trail-out silence a generation carries.
+
+ Without this, a join stacks one segment's trailing silence onto the next one's
+ leading silence plus the inserted pause — which is what makes chunking audible.
+ """
+ wav = np.asarray(wav, dtype=np.float32)
+ if len(wav) < int(sample_rate * 0.05):
+ return wav
+ hop = max(1, int(sample_rate * 0.01))
+ frames = wav[:len(wav) // hop * hop].reshape(-1, hop)
+ rms = np.sqrt((frames ** 2).mean(axis=1) + 1e-12)
+ loud = np.nonzero(rms > 10 ** (thresh_db / 20.0))[0]
+ if not len(loud):
+ return wav
+ keep = int(sample_rate * keep_s)
+ start = max(0, loud[0] * hop - keep)
+ end = min(len(wav), (loud[-1] + 1) * hop + keep)
+ return wav[start:end]
+
+
+def join_chunks(wavs, sample_rate, gap_s=CHUNK_GAP_S):
+ """Concatenate segments so the seam is inaudible.
+
+ Trim each segment's own edge silence, insert one consistent sentence-length
+ pause, and fade a few milliseconds at each edge — segments rarely begin or end
+ on a zero crossing, and that discontinuity is heard as a click.
+ """
+ wavs = [w for w in wavs if w is not None and len(w)]
+ if not wavs:
+ return None
+ if len(wavs) == 1:
+ return np.asarray(wavs[0], dtype=np.float32)
+ gap = np.zeros(int(sample_rate * gap_s), dtype=np.float32)
+ fade = max(1, int(sample_rate * 0.008))
+ out = []
+ for i, wav in enumerate(wavs):
+ wav = trim_silence(np.asarray(wav, dtype=np.float32), sample_rate).copy()
+ if len(wav) > 2 * fade:
+ wav[:fade] *= np.linspace(0.0, 1.0, fade, dtype=np.float32)
+ wav[-fade:] *= np.linspace(1.0, 0.0, fade, dtype=np.float32)
+ out.append(wav)
+ if i != len(wavs) - 1:
+ out.append(gap)
+ return np.concatenate(out)
diff --git a/kittenml/kittentts2/tl2_emb4.py b/kittenml/kittentts2/tl2_emb4.py
new file mode 100644
index 0000000..ccbb419
--- /dev/null
+++ b/kittenml/kittentts2/tl2_emb4.py
@@ -0,0 +1,160 @@
+"""Reader for the TL2 + 4-bit-embedding checkpoint.
+
+A third packing of the same language model, smaller than `ternary.py`'s at the
+cost of being lossy in one place:
+
+ model.safetensors 3469 MB bf16 throughout
+ model-ternary.safetensors 954 MB lossless, embedding still bf16
+ model-tl2-emb4.safetensors 469 MB lossless body, 4-bit embedding
+
+The body uses TL2 rather than this package's own packing — a different layout for
+the same ternary codeword, 1.8125 bits per weight including scales, and equally
+exact. The saving is almost entirely the embedding: 324M parameters that
+`ternary.py` has to leave at bf16 because they are not ternary, quantised here to
+about 4.2 bits each.
+
+**That embedding step is lossy**, unlike everything else this package ships:
+L2 relative error 0.1184 against the bf16 source, measured by the exporter.
+Reported quality cost at the time of export was perplexity 13.60 against 13.50 on
+h3, and 62.85 against 61.98 on vox_plain. Small, but not nothing — which is why
+this is opt-in and `ternary.py`'s lossless packing stays the default.
+
+Both unpackers are ports of the exporter's own reader, so the weights this
+produces are the weights it was verified against.
+"""
+
+import json
+import math
+
+import numpy as np
+import torch
+
+# TL2 geometry: one block covers 32 output rows x 128 inputs in 928 bytes.
+GROUP = 128
+TL2_ROWS = 32
+TL2_GROUP_BYTES = 928
+
+
+def unpack_tl2(buf, out_features, in_features):
+ """uint8 [out/32, in/128, 928] -> bf16 [out, in], the exact ternary codeword.
+
+ Each block holds 32 fp16 group scales, then four sub-blocks of ten
+ balanced-base-3 triples plus a two-bit tail. A triple stores three trits in
+ one value, which is what gets the body under two bits per weight.
+ """
+ rows, groups = out_features // TL2_ROWS, in_features // GROUP
+ if buf.shape != (rows, groups, TL2_GROUP_BYTES):
+ raise ValueError(f"expected {(rows, groups, TL2_GROUP_BYTES)}, got {buf.shape}")
+
+ gamma = buf[:, :, :TL2_ROWS * 2].copy().view(np.float16).transpose(0, 2, 1)
+ trits = np.empty((rows, TL2_ROWS, groups, GROUP), dtype=np.int8)
+ cursor = TL2_ROWS * 2
+
+ for sub in range(4):
+ segment = buf[:, :, cursor:cursor + 200].reshape(rows, groups, 10, 20)
+ cursor += 200
+ packed = np.ascontiguousarray(segment[..., :16].transpose(0, 3, 1, 2))
+ magnitude = np.empty((rows, TL2_ROWS, groups, 10), dtype=np.uint8)
+ magnitude[:, 0::2] = packed & 0x0F # even rows: low nibble
+ magnitude[:, 1::2] = packed >> 4 # odd rows: high nibble
+
+ signs = np.ascontiguousarray(segment[..., 16:].transpose(0, 3, 1, 2))
+ negative = np.unpackbits(signs, axis=1, count=TL2_ROWS,
+ bitorder="little").astype(bool)
+ balanced = magnitude.astype(np.int16)
+ np.negative(balanced, out=balanced, where=negative)
+
+ n = balanced + 13 # balanced base 3 -> 0..26
+ block = trits[:, :, :, sub * 32:(sub + 1) * 32]
+ triple = np.empty((rows, TL2_ROWS, groups, 10, 3), dtype=np.int8)
+ triple[..., 0] = (n // 9) - 1
+ triple[..., 1] = ((n // 3) % 3) - 1
+ triple[..., 2] = (n % 3) - 1
+ block[..., :30] = triple.reshape(rows, TL2_ROWS, groups, 30)
+
+ tail_bytes = np.ascontiguousarray(buf[:, :, cursor:cursor + 16].transpose(0, 2, 1))
+ cursor += 16
+ tail = np.empty((rows, TL2_ROWS, groups), dtype=np.uint8)
+ tail[:, 0::2] = tail_bytes & 0x0F
+ tail[:, 1::2] = tail_bytes >> 4
+ block[..., 30] = (tail & 0x03).astype(np.int8) - 1
+ block[..., 31] = ((tail >> 2) & 0x03).astype(np.int8) - 1
+
+ values = torch.from_numpy(trits.reshape(out_features, groups, GROUP)).to(torch.bfloat16)
+ scales = torch.from_numpy(
+ np.ascontiguousarray(gamma.reshape(out_features, groups))).to(torch.bfloat16)
+ return (values * scales.unsqueeze(-1)).reshape(out_features, in_features)
+
+
+def _hadamard(n):
+ matrix = torch.tensor([[1.0]])
+ for _ in range(int(round(math.log2(n)))):
+ matrix = torch.cat([torch.cat([matrix, matrix], 1),
+ torch.cat([matrix, -matrix], 1)], 0)
+ return matrix / math.sqrt(n)
+
+
+def _unpack_codes(buf, codebook_size, count):
+ bits = int(math.ceil(math.log2(codebook_size)))
+ if bits == 8:
+ return buf[:count].astype(np.int64)
+ per_byte = 8 // bits
+ out = np.empty(buf.size * per_byte, dtype=np.uint8)
+ for j in range(per_byte):
+ out[j::per_byte] = (buf >> (bits * j)) & ((1 << bits) - 1)
+ return out[:count].astype(np.int64)
+
+
+def dequant_embedding(get_tensor, metadata, chunk=1 << 15):
+ """4-bit codes -> a bf16 embedding matrix.
+
+ Rows are split into frequency tiers with their own codebook sizes — audio
+ tokens get a 256-entry book, rare text rows only 16 — then rotated by a
+ Hadamard matrix and coded per column. Reversing it means looking up each
+ row's centres, rotating back, and undoing the row and column scales.
+ """
+ vocab, dim = int(metadata["V"]), int(metadata["D"])
+ codebook_sizes = json.loads(metadata["Ks"])
+ tier_map = get_tensor("emb4/tier_map").numpy()
+ hadamard = _hadamard(dim)
+
+ weights = torch.empty(vocab, dim, dtype=torch.float32)
+ for tier, codebook_size in enumerate(codebook_sizes):
+ rows = np.flatnonzero(tier_map == tier) # ascending == packing order
+ codes = _unpack_codes(get_tensor(f"emb4/t{tier}_codes").numpy(),
+ codebook_size, rows.size * dim).reshape(rows.size, dim)
+ centres = get_tensor(f"emb4/t{tier}_centers").to(torch.float32).numpy()
+ row_scale = get_tensor(f"emb4/t{tier}_s").to(torch.float32).numpy()
+ col_scale = torch.from_numpy(
+ get_tensor(f"emb4/t{tier}_t").to(torch.float32).numpy())
+ centres_t = np.ascontiguousarray(centres.T)
+ # Chunked: the full rotation would otherwise materialise 158k x 2048 floats.
+ for start in range(0, rows.size, chunk):
+ stop = min(start + chunk, rows.size)
+ rotated = np.take_along_axis(centres_t, codes[start:stop].T, axis=1).T
+ restored = torch.from_numpy(np.ascontiguousarray(rotated)) @ hadamard.T
+ weights[rows[start:stop]] = (restored * col_scale[None, :]
+ * torch.from_numpy(row_scale[start:stop])[:, None])
+ return weights.to(torch.bfloat16)
+
+
+def load_state_dict(path):
+ """Rebuild the full bf16 state dict from a TL2 + emb4 checkpoint."""
+ from safetensors import safe_open
+
+ state = {}
+ with safe_open(str(path), framework="pt") as handle:
+ metadata = dict(handle.metadata() or {})
+ if metadata.get("schema") != "kitten_ternary_tl2_emb4_v1":
+ raise ValueError(f"unexpected schema {metadata.get('schema')!r} in {path}")
+ embedding_metadata = json.loads(metadata.get("embedding_metadata", "{}"))
+ for key in handle.keys():
+ if key.startswith("tl2/"):
+ buf = handle.get_tensor(key).numpy()
+ rows, groups, _ = buf.shape
+ state[key[4:]] = unpack_tl2(buf, rows * TL2_ROWS, groups * GROUP)
+ elif key.startswith("fp/"):
+ state[key[3:]] = handle.get_tensor(key)
+ state["model.embed_tokens.weight"] = dequant_embedding(
+ handle.get_tensor, embedding_metadata)
+ return state
diff --git a/kittenml/kittentts2/tokens.py b/kittenml/kittentts2/tokens.py
new file mode 100644
index 0000000..902a092
--- /dev/null
+++ b/kittenml/kittentts2/tokens.py
@@ -0,0 +1,61 @@
+"""Token layout for the KittenTTS 2 speech language model.
+
+The model shares one vocabulary between text and audio. Text occupies the base
+Qwen3 BPE range, then six named special tokens, then 6561 S3 codec tokens at a
+fixed offset, then optional marker rows appended at the end:
+
+ [0, audio_id_base) base text vocab + named specials
+ [audio_id_base, audio_id_base + 6561) S3 audio codec tokens
+ final_seg end-of-sample cue after the last text
+ reference_* wrappers for the in-context reference
+
+Unlike the text tokens, audio ids are never produced by the text tokenizer — the
+prompt builder emits the raw integers. `TokenMap` is what keeps both sides
+agreeing on where that range starts.
+"""
+
+from dataclasses import dataclass
+
+
+@dataclass(frozen=True)
+class TokenMap:
+ """Resolved token ids for one checkpoint.
+
+ Checkpoints differ in how they wrap the in-context reference, so the
+ `reference_*` ids are optional: when they are 0 the reference reuses the
+ plain text_start/speech_start/speech_end ids instead (see
+ `prompt.build_reference_prefix`).
+ """
+
+ audio_id_base: int
+ num_audio_tokens: int
+ speech_start_id: int
+ speech_end_id: int
+ text_start_id: int
+ text_end_id: int
+ start_id: int
+ stop_id: int
+ final_seg_id: int = 0
+ reference_speech_start_id: int = 0
+ reference_speech_end_id: int = 0
+ reference_text_start_id: int = 0
+ reference_text_end_id: int = 0
+
+ @property
+ def audio_id_end(self) -> int:
+ """One past the last audio codec id."""
+ return self.audio_id_base + self.num_audio_tokens
+
+ @property
+ def uses_reference_role_tokens(self) -> bool:
+ return bool(self.reference_text_start_id)
+
+ @classmethod
+ def from_config(cls, config: dict) -> "TokenMap":
+ """Build from the `token_map` block of a KittenTTS 2 repo's config.json."""
+ tm = config["token_map"]
+ known = {f for f in cls.__dataclass_fields__}
+ unknown = set(tm) - known
+ if unknown:
+ raise ValueError(f"unknown token_map keys: {sorted(unknown)}")
+ return cls(**tm)
diff --git a/kittenml/kittentts2/vocoder.py b/kittenml/kittentts2/vocoder.py
new file mode 100644
index 0000000..1e22690
--- /dev/null
+++ b/kittenml/kittentts2/vocoder.py
@@ -0,0 +1,203 @@
+"""The audio codec ends of the KittenTTS 2 pipeline.
+
+The language model neither reads nor writes waveforms — it consumes and produces
+S3 codec tokens. This module owns both conversions:
+
+ reference wav --tokenizer--> codec tokens (for the in-context prompt)
+ codec tokens --s3gen------> 24 kHz waveform (the generated audio)
+
+Both use ResembleAI's chatterbox-turbo s3gen, vendored in `s3gen.py` with its
+weights fetched from Hugging Face on first use. Only s3gen is loaded; chatterbox's
+own text-to-token model is unused, since that is precisely what KittenTTS 2
+replaces.
+"""
+
+import pathlib
+
+import librosa
+import numpy as np
+import torch
+from huggingface_hub import hf_hub_download
+from safetensors.torch import load_file
+
+from .s3gen import S3_SR, S3GEN_SIL, S3GEN_SR, SPEECH_VOCAB_SIZE, S3Gen
+
+CHATTERBOX_REPO = "ResembleAI/chatterbox-turbo"
+S3GEN_WEIGHTS = "s3gen_meanflow.safetensors"
+
+# s3gen conditions on at most 10 s of reference audio, and its own conditioning
+# path asserts the clip is longer than 5 s.
+DECODER_COND_SECONDS = 10
+DECODER_MIN_SECONDS = 6.0
+
+# The meanflow decoder converges in two CFM steps; more cost time without changing
+# the output audibly.
+CFM_TIMESTEPS = 2
+
+# The optional quantised decoder (see student_flow.py) replaces only the flow, and
+# was distilled against a shorter, truncated voice prompt than the stock flow uses.
+# These are its values, not ours to vary: conditioning it differently is not what
+# it was trained on.
+STUDENT_REF_SECONDS = 4.0
+STUDENT_MAX_PROMPT_TOKENS = 112
+
+
+class S3Codec:
+ """Loads s3gen once and holds the per-reference conditioning it derives."""
+
+ sample_rate = S3GEN_SR
+
+ def __init__(self, device="cuda", cache_dir=None, student_weights=None):
+ """
+ Args:
+ student_weights: path to a packed student flow. When given, the flow
+ stage is replaced by it and the tokenizer, speaker encoder and
+ vocoder are still used from s3gen.
+ """
+ self.device = device
+ weights_path = hf_hub_download(repo_id=CHATTERBOX_REPO, filename=S3GEN_WEIGHTS,
+ cache_dir=cache_dir)
+ self.s3gen = S3Gen(meanflow=True)
+ self.s3gen.load_state_dict(load_file(weights_path), strict=True)
+ self.s3gen.to(device).eval()
+ self._ref_cache = {}
+
+ self.student = None
+ if student_weights is not None:
+ self.student = load_student_flow(student_weights, device=device)
+
+ def encode_reference(self, wav_path):
+ """Reference clip -> S3 codec token ids, for the in-context prompt."""
+ wav16, _ = librosa.load(str(wav_path), sr=S3_SR, mono=True)
+ with torch.inference_mode():
+ tokens, lengths = self.s3gen.tokenizer(
+ torch.from_numpy(wav16).float().unsqueeze(0).to(self.device))
+ return tokens[0, :int(lengths[0].item())].long().cpu().tolist()
+
+ def reference_conditioning(self, wav_path):
+ """Reference clip -> the conditioning dict used when decoding.
+
+ Cached per path: this is pure inference over a fixed clip, and a built-in
+ voice is re-used on every request. The two decoders want different
+ conditioning, so the cache is keyed on which one is active.
+ """
+ key = (str(wav_path), self.student is not None)
+ if key not in self._ref_cache:
+ seconds = STUDENT_REF_SECONDS if self.student is not None else DECODER_COND_SECONDS
+ wav24 = _load_decoder_reference(str(wav_path))[:int(seconds * S3GEN_SR)]
+ with torch.inference_mode():
+ ref = self.s3gen.embed_ref(wav24, S3GEN_SR, device=self.device)
+ self._ref_cache[key] = self._truncate_prompt(ref) if self.student else ref
+ return self._ref_cache[key]
+
+ def _truncate_prompt(self, ref):
+ """The prompt the student flow expects: at most 112 tokens, mel to match.
+
+ The mel runs at twice the token rate, so the two have to be cut together
+ or the flow sees a prompt whose halves disagree.
+ """
+ n = min(ref["prompt_token"].shape[1], ref["prompt_feat"].shape[1] // 2,
+ STUDENT_MAX_PROMPT_TOKENS)
+ return {
+ "prompt_token": ref["prompt_token"][:, :n],
+ "prompt_token_len": torch.tensor([n], device=self.device),
+ "prompt_feat": ref["prompt_feat"][:, :n * 2],
+ "embedding": ref["embedding"],
+ }
+
+ def decode(self, ref_conditioning, audio_ids):
+ """Generated codec tokens -> a 24 kHz waveform.
+
+ Out-of-range ids are dropped rather than raising: a truncated or degenerate
+ generation should still return the audio it did produce.
+ """
+ valid = [t for t in audio_ids if 0 <= t < SPEECH_VOCAB_SIZE]
+ if not valid:
+ return None
+ tokens = torch.tensor(valid, dtype=torch.long, device=self.device)
+ # s3gen drops its last few tokens as streaming lookahead, so pad with silence
+ # to keep the final syllable of the generation.
+ tokens = torch.cat([tokens, torch.full((3,), int(S3GEN_SIL),
+ dtype=torch.long, device=self.device)])
+ with torch.inference_mode():
+ if self.student is not None:
+ wav = self._decode_with_student(ref_conditioning, tokens)
+ else:
+ wav, _ = self.s3gen.inference(speech_tokens=tokens,
+ ref_dict=ref_conditioning,
+ n_cfm_timesteps=CFM_TIMESTEPS)
+ return wav.squeeze().detach().cpu().float().numpy()
+
+ def _decode_with_student(self, cond, tokens):
+ """Student flow to mel in one step, then s3gen's own vocoder to audio."""
+ from .student_flow import meanflow_forward
+
+ tokens = tokens.unsqueeze(0)
+ lengths = torch.tensor([tokens.shape[1]], device=self.device)
+ mel, _, _ = meanflow_forward(self.student, tokens, lengths, n_steps=1, **cond)
+ mel = mel.to(dtype=self.s3gen.dtype)
+ cache = torch.zeros(1, 1, 0, device=self.device, dtype=self.s3gen.dtype)
+ wav, _ = self.s3gen.mel2wav.inference(speech_feat=mel, cache_source=cache)
+ # s3gen applies this fade itself on its own path; the student path calls the
+ # vocoder directly, so it has to be applied here or the clip starts with a click.
+ wav = wav.clone()
+ wav[:, :len(self.s3gen.trim_fade)] *= self.s3gen.trim_fade
+ return wav
+
+
+def _load_decoder_reference(wav_path, min_seconds=DECODER_MIN_SECONDS):
+ """Load a reference at 24 kHz, looping it if it is too short for s3gen.
+
+ Short clips are tiled — the speech is repeated, never silence-padded, because
+ silence in the conditioning degrades the vocoder's timbre estimate.
+ """
+ wav, _ = librosa.load(str(wav_path), sr=S3GEN_SR, mono=True)
+ if len(wav) == 0:
+ raise ValueError(f"reference audio is empty: {wav_path}")
+ needed = int(min_seconds * S3GEN_SR)
+ if len(wav) < needed:
+ wav = np.tile(wav, int(np.ceil(needed / len(wav))))
+ return wav.astype(np.float32)
+
+
+def resolve_reference_path(path):
+ path = pathlib.Path(path)
+ if not path.is_file():
+ raise FileNotFoundError(f"reference audio not found: {path}")
+ return str(path)
+
+
+def load_student_flow(weights_path, device="cuda"):
+ """Rebuild a quantised student flow from packed integer codes and scales.
+
+ The stored weights are already on the quantisation grid, so they are installed
+ as-is rather than being quantised a second time — see the note in
+ student_flow.py about why a dequantise/requantise round trip is not free.
+ """
+ from .student_flow import build_flow, convert_to_bitnet
+
+ blob = torch.load(str(weights_path), map_location="cpu", weights_only=False)
+ flow = build_flow(**blob["arch"])
+ convert_to_bitnet(flow, mode=blob["mode"], norm_input=blob["norm_input"],
+ prequantised=True)
+
+ state = {}
+ for name, entry in blob["quantised"].items():
+ codes = (_unpack4(entry["packed"], entry["numel"]) if blob["bits"] == 4
+ else entry["codes"])
+ scale = entry["scale"].reshape(-1, *([1] * (len(entry["shape"]) - 1)))
+ state[name] = codes.reshape(entry["shape"]).float() / scale
+ state.update({k: v.float() for k, v in blob["dense"].items()})
+
+ missing, unexpected = flow.load_state_dict(state, strict=False)
+ if missing or unexpected:
+ raise ValueError(f"student flow weights do not match the architecture "
+ f"(missing={missing[:3]}, unexpected={unexpected[:3]})")
+ return flow.to(device).eval()
+
+
+def _unpack4(packed, numel):
+ """Two 4-bit codes per byte, each biased by 8 when written."""
+ high = (packed >> 4).to(torch.int16) - 8
+ low = (packed & 0x0F).to(torch.int16) - 8
+ return torch.stack([high, low], dim=1).reshape(-1)[:numel].to(torch.int8)
diff --git a/kittenml/kittentts_legacy/__init__.py b/kittenml/kittentts_legacy/__init__.py
new file mode 100644
index 0000000..cd0ac14
--- /dev/null
+++ b/kittenml/kittentts_legacy/__init__.py
@@ -0,0 +1,23 @@
+"""The original ONNX KittenTTS models (0.8 and earlier).
+
+Loaded through `kittenml.KittenTTS` when a repository's config.json declares
+`"type": "ONNX1"` or `"ONNX2"`. See `model.KittenTTSOnnx` for the API.
+"""
+
+from .model import KittenTTSOnnx, build_onnx_model, download_from_huggingface
+
+__all__ = [
+ "KittenTTSOnnx",
+ "build_onnx_model",
+ "download_from_huggingface",
+]
+
+
+def __getattr__(name):
+ # Imported lazily: the ONNX runtime pulls in espeak and phonemizer, which a
+ # KittenTTS 2 install has no reason to carry.
+ if name == "KittenTTS_1_Onnx":
+ from .onnx_model import KittenTTS_1_Onnx
+
+ return KittenTTS_1_Onnx
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
diff --git a/kittenml/kittentts_legacy/model.py b/kittenml/kittentts_legacy/model.py
new file mode 100644
index 0000000..e3c6020
--- /dev/null
+++ b/kittenml/kittentts_legacy/model.py
@@ -0,0 +1,115 @@
+"""The original ONNX KittenTTS models (0.8 and earlier).
+
+These map phonemes to a waveform directly through a single ONNX graph: 15M-80M
+parameters, 25-80 MB on disk, and fast on CPU with no GPU and no PyTorch. They
+offer eight fixed voices and a speech-speed control, and no voice cloning or
+expression tags — for those, see `kittenml.kittentts2`.
+
+Reached through `kittenml.KittenTTS` when a repository's config.json declares
+`"type": "ONNX1"` or `"ONNX2"`.
+"""
+
+import os
+
+from huggingface_hub import hf_hub_download
+
+from ..preprocess import normalize_text
+from ..repo import ONNX_TYPES, resolve_repo
+
+
+class KittenTTSOnnx:
+ """An ONNX KittenTTS model.
+
+ Constructed by `kittenml.KittenTTS`, which resolves the repository first and
+ hands the result over through `_resolved`.
+ """
+
+ def __init__(self, model_name="KittenML/kitten-tts-nano-0.8", cache_dir=None,
+ backend=None, device=None, hf_token=None):
+ """Initialize an ONNX KittenTTS model.
+
+ Args:
+ model_name: Hugging Face repository ID, bare model name, or local directory
+ cache_dir: Directory to cache downloaded files
+ backend: ONNX execution provider ("cpu", "cuda", "amd_gpu")
+ device: Unused here; accepted so both backends share a signature
+ hf_token: Unused here; accepted so both backends share a signature
+ """
+ local_dir, repo_id, config = getattr(self, "_resolved", None) or \
+ resolve_repo(model_name, cache_dir)
+ self.model = build_onnx_model(config, local_dir, repo_id, cache_dir, backend)
+
+ def normalize_text(self, text, locale="en-US", return_spans=False):
+ """Normalize text for TTS without generating audio."""
+ return normalize_text(text, locale=locale, return_spans=return_spans)
+
+ def generate(self, text, voice="expr-voice-5-m", speed=1.0, clean_text=False):
+ """Generate audio from text.
+
+ Args:
+ text: Input text to synthesize
+ voice: Voice to use for synthesis
+ speed: Speech speed (1.0 = normal)
+
+ Returns:
+ Audio data as numpy array
+ """
+ print(f"Generating audio for text: {text}")
+ return self.model.generate(text, voice=voice, speed=speed, clean_text=clean_text)
+
+ def generate_stream(self, text, voice="expr-voice-5-m", speed=1.0, clean_text=False):
+ """Generate audio as a stream of chunks.
+
+ Yields:
+ numpy.ndarray: Audio data for each text chunk.
+ """
+ yield from self.model.generate_stream(text, voice=voice, speed=speed, clean_text=clean_text)
+
+ def generate_to_file(self, text, output_path, voice="expr-voice-5-m", speed=1.0, sample_rate=24000):
+ """Generate audio from text and save to file.
+
+ Args:
+ text: Input text to synthesize
+ output_path: Path to save the audio file
+ voice: Voice to use for synthesis
+ speed: Speech speed (1.0 = normal)
+ sample_rate: Audio sample rate
+ """
+ return self.model.generate_to_file(text, output_path, voice=voice, speed=speed, sample_rate=sample_rate)
+
+ @property
+ def available_voices(self):
+ """Get list of available voices."""
+ return self.model.all_voice_names
+
+
+def build_onnx_model(config, local_dir, repo_id, cache_dir, backend):
+ """Instantiate KittenTTS_1_Onnx from an already-resolved repository config."""
+ # Imported here, not at module scope: the ONNX runtime pulls in espeak and
+ # phonemizer, which a KittenTTS 2 install has no reason to carry.
+ from .onnx_model import KittenTTS_1_Onnx
+
+ def _fetch(filename):
+ if local_dir is not None:
+ return os.path.join(local_dir, filename)
+ return hf_hub_download(repo_id=repo_id, filename=filename, cache_dir=cache_dir)
+
+ return KittenTTS_1_Onnx(
+ model_path=_fetch(config["model_file"]),
+ voices_path=_fetch(config["voices"]),
+ speed_priors=config.get("speed_priors", {}),
+ voice_aliases=config.get("voice_aliases", {}),
+ backend=backend,
+ )
+
+
+def download_from_huggingface(repo_id="KittenML/kitten-tts-nano-0.1", cache_dir=None, backend=None):
+ """Download an ONNX model's files from Hugging Face and instantiate it.
+
+ Returns:
+ KittenTTS_1_Onnx: Instantiated model ready for use
+ """
+ local_dir, resolved_id, config = resolve_repo(repo_id, cache_dir)
+ if config.get("type") not in ONNX_TYPES:
+ raise ValueError("Unsupported model type.")
+ return build_onnx_model(config, local_dir, resolved_id, cache_dir, backend)
diff --git a/kittentts/onnx_model.py b/kittenml/kittentts_legacy/onnx_model.py
similarity index 98%
rename from kittentts/onnx_model.py
rename to kittenml/kittentts_legacy/onnx_model.py
index b368e4f..130a3ff 100644
--- a/kittentts/onnx_model.py
+++ b/kittenml/kittentts_legacy/onnx_model.py
@@ -7,7 +7,7 @@ import numpy as np
import phonemizer
import soundfile as sf
import onnxruntime as ort
-from .preprocess import TextPreprocessor, chunk_text, normalize_text
+from ..preprocess import TextPreprocessor, chunk_text, normalize_text
def basic_english_tokenize(text):
"""Basic English tokenizer that splits on whitespace and punctuation."""
diff --git a/kittentts/preprocess.py b/kittenml/preprocess.py
similarity index 100%
rename from kittentts/preprocess.py
rename to kittenml/preprocess.py
diff --git a/kittenml/repo.py b/kittenml/repo.py
new file mode 100644
index 0000000..704aa01
--- /dev/null
+++ b/kittenml/repo.py
@@ -0,0 +1,37 @@
+"""Locating a model repository and reading the config that says what it is.
+
+Shared by both backends, and kept separate from `get_model` so the backends can
+resolve a repository without importing the dispatcher that imports them.
+"""
+
+import json
+import os
+
+from huggingface_hub import hf_hub_download
+
+# config.json "type" values, and the backend each selects.
+ONNX_TYPES = ("ONNX1", "ONNX2")
+KITTEN2_TYPE = "KITTEN2"
+
+
+def resolve_repo(model_name, cache_dir=None):
+ """Locate a model repository and read its config.
+
+ Accepts a Hugging Face repo id ("KittenML/kitten-tts-mini-0.8"), a bare model
+ name (assumed to be under KittenML), or a path to a local directory laid out
+ like one of those repos — which is what you have before pushing a repo to the
+ Hub.
+
+ Returns (local_dir_or_none, repo_id_or_none, config).
+ """
+ if os.path.isdir(model_name):
+ config_path = os.path.join(model_name, "config.json")
+ if not os.path.isfile(config_path):
+ raise FileNotFoundError(f"no config.json in {model_name}")
+ with open(config_path) as f:
+ return model_name, None, json.load(f)
+
+ repo_id = model_name if "/" in model_name else f"KittenML/{model_name}"
+ config_path = hf_hub_download(repo_id=repo_id, filename="config.json", cache_dir=cache_dir)
+ with open(config_path) as f:
+ return None, repo_id, json.load(f)
diff --git a/kittentts/__index__.py b/kittentts/__index__.py
deleted file mode 100644
index e178a13..0000000
--- a/kittentts/__index__.py
+++ /dev/null
@@ -1,3 +0,0 @@
-from kittentts.get_model import get_model
-
-
\ No newline at end of file
diff --git a/kittentts/__init__.py b/kittentts/__init__.py
deleted file mode 100644
index 6c39e74..0000000
--- a/kittentts/__init__.py
+++ /dev/null
@@ -1,22 +0,0 @@
-from kittentts.preprocess import NormalizedSpan, NormalizedTextResult, normalize_text, normalize_text_result
-
-__version__ = "0.1.0"
-__author__ = "KittenML"
-__description__ = "Ultra-lightweight text-to-speech model with just 15 million parameters"
-
-__all__ = [
- "get_model",
- "KittenTTS",
- "normalize_text",
- "normalize_text_result",
- "NormalizedSpan",
- "NormalizedTextResult",
-]
-
-
-def __getattr__(name):
- if name in {"get_model", "KittenTTS"}:
- from kittentts.get_model import KittenTTS, get_model
-
- return {"get_model": get_model, "KittenTTS": KittenTTS}[name]
- raise AttributeError(f"module 'kittentts' has no attribute {name!r}")
diff --git a/kittentts/get_model.py b/kittentts/get_model.py
deleted file mode 100644
index d8d2225..0000000
--- a/kittentts/get_model.py
+++ /dev/null
@@ -1,116 +0,0 @@
-import json
-import os
-from huggingface_hub import hf_hub_download
-from .onnx_model import KittenTTS_1_Onnx
-from .preprocess import normalize_text
-
-
-class KittenTTS:
- """Main KittenTTS class for text-to-speech synthesis."""
-
- def __init__(self, model_name="KittenML/kitten-tts-nano-0.8", cache_dir=None, backend=None):
- """Initialize KittenTTS with a model from Hugging Face.
-
- Args:
- model_name: Hugging Face repository ID or model name
- cache_dir: Directory to cache downloaded files
- """
- # Handle different model name formats
- if "/" not in model_name:
- # If just model name provided, assume it's from KittenML
- repo_id = f"KittenML/{model_name}"
- else:
- repo_id = model_name
-
- self.model = download_from_huggingface(repo_id=repo_id, cache_dir=cache_dir, backend=backend)
-
- def normalize_text(self, text, locale="en-US", return_spans=False):
- """Normalize text for TTS without generating audio."""
- return normalize_text(text, locale=locale, return_spans=return_spans)
-
- def generate(self, text, voice="expr-voice-5-m", speed=1.0, clean_text=False):
- """Generate audio from text.
-
- Args:
- text: Input text to synthesize
- voice: Voice to use for synthesis
- speed: Speech speed (1.0 = normal)
-
- Returns:
- Audio data as numpy array
- """
- print(f"Generating audio for text: {text}")
- return self.model.generate(text, voice=voice, speed=speed, clean_text=clean_text)
-
- def generate_stream(self, text, voice="expr-voice-5-m", speed=1.0, clean_text=False):
- """Generate audio as a stream of chunks.
-
- Yields:
- numpy.ndarray: Audio data for each text chunk.
- """
- yield from self.model.generate_stream(text, voice=voice, speed=speed, clean_text=clean_text)
-
- def generate_to_file(self, text, output_path, voice="expr-voice-5-m", speed=1.0, sample_rate=24000):
- """Generate audio from text and save to file.
-
- Args:
- text: Input text to synthesize
- output_path: Path to save the audio file
- voice: Voice to use for synthesis
- speed: Speech speed (1.0 = normal)
- sample_rate: Audio sample rate
- """
- return self.model.generate_to_file(text, output_path, voice=voice, speed=speed, sample_rate=sample_rate)
-
- @property
- def available_voices(self):
- """Get list of available voices."""
- return self.model.all_voice_names
-
-
-def download_from_huggingface(repo_id="KittenML/kitten-tts-nano-0.1", cache_dir=None, backend=None):
- """Download model files from Hugging Face repository.
-
- Args:
- repo_id: Hugging Face repository ID
- cache_dir: Directory to cache downloaded files
-
- Returns:
- KittenTTS_1_Onnx: Instantiated model ready for use
- """
- # Download config file first
- config_path = hf_hub_download(
- repo_id=repo_id,
- filename="config.json",
- cache_dir=cache_dir
- )
-
- # Load config
- with open(config_path, 'r') as f:
- config = json.load(f)
-
- if config.get("type") not in ["ONNX1", "ONNX2"]:
- raise ValueError("Unsupported model type.")
-
- # Download model and voices files based on config
- model_path = hf_hub_download(
- repo_id=repo_id,
- filename=config["model_file"],
- cache_dir=cache_dir
- )
-
- voices_path = hf_hub_download(
- repo_id=repo_id,
- filename=config["voices"],
- cache_dir=cache_dir
- )
-
- # Instantiate and return model
- model = KittenTTS_1_Onnx(model_path=model_path, voices_path=voices_path, speed_priors=config.get("speed_priors", {}) , voice_aliases=config.get("voice_aliases", {}), backend=backend)
-
- return model
-
-
-def get_model(repo_id="KittenML/kitten-tts-nano-0.1", cache_dir=None, backend=None):
- """Get a KittenTTS model (legacy function for backward compatibility)."""
- return KittenTTS(repo_id, cache_dir, backend=backend)
diff --git a/pyproject.toml b/pyproject.toml
index 7c56ded..ccdd384 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -3,37 +3,51 @@ requires = ["setuptools>=45", "wheel"]
build-backend = "setuptools.build_meta"
[project]
-name = "kittentts"
-version = "0.8.1"
-description = "Ultra-lightweight text-to-speech model with just 15 million parameters"
+name = "kittenml"
+version = "0.9.2"
+description = "Text-to-speech with voice cloning and expression control, plus ultra-lightweight models that run on CPU"
readme = "README.md"
-requires-python = ">=3.8"
+requires-python = ">=3.10"
license = {text = "Apache 2.0"}
authors = [
{name = "KittenML"}
]
-keywords = ["text-to-speech", "tts", "speech-synthesis", "neural-networks", "onnx"]
+keywords = ["text-to-speech", "tts", "speech-synthesis", "voice-cloning", "neural-networks", "onnx"]
classifiers = [
"Topic :: Multimedia :: Sound/Audio :: Speech",
"Topic :: Scientific/Engineering :: Artificial Intelligence",
]
dependencies = [
+ "torch>=2.6",
+ "torchaudio>=2.6",
+ "transformers>=4.55",
+ "safetensors",
+ "numpy",
+ "scipy",
+ "soundfile",
+ "librosa",
+ "huggingface_hub",
+ "einops",
+ "diffusers",
+ "omegaconf",
+ "hydra-core",
+ "s3tokenizer",
+ "resemble-perth",
+ "pyloudnorm",
+ "kitten-text-processing>=0.1.0",
"espeakng_loader",
"phonemizer",
"onnxruntime",
- "soundfile",
- "numpy",
- "huggingface_hub",
]
[project.urls]
-Homepage = "https://github.com/kittenml/kittentts"
-Repository = "https://github.com/kittenml/kittentts"
-Issues = "https://github.com/kittenml/kittentts/issues"
+Homepage = "https://github.com/KittenML/KittenTTS"
+Repository = "https://github.com/KittenML/KittenTTS"
+Issues = "https://github.com/KittenML/KittenTTS/issues"
[tool.setuptools.packages.find]
where = ["."]
-include = ["kittentts*"]
+include = ["kittenml*"]
[tool.setuptools.package-data]
-kittentts = ["*.json", "*.txt", "*.onnx"]
+kittenml = ["*.json", "*.txt", "*.onnx"]
diff --git a/requirements.txt b/requirements.txt
index abbfef4..7ce8263 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,6 +1,31 @@
+# Default install: everything KittenTTS 2 needs, including voice cloning, plus the
+# small ONNX runtime so the lightweight models in kittenml/kittentts_legacy work too.
+
+# KittenTTS 2 — speech language model
+torch>=2.6
+torchaudio>=2.6
+transformers>=4.55
+safetensors
+numpy
+scipy
+soundfile
+librosa
+huggingface_hub
+
+# s3gen vocoder (vendored in kittenml/kittentts2/s3gen.py)
+einops
+diffusers
+omegaconf
+hydra-core
+s3tokenizer
+resemble-perth
+pyloudnorm
+
+# Text normalization: reproduces what KittenTTS 2 was served with. Pure Python,
+# no compiled dependencies, so it installs on every platform.
+kitten-text-processing>=0.1.0
+
+# Lightweight ONNX models (kittenml/kittentts_legacy)
espeakng_loader
phonemizer
onnxruntime
-soundfile
-numpy
-huggingface_hub
diff --git a/setup.py b/setup.py
index e75e149..aa8ec45 100644
--- a/setup.py
+++ b/setup.py
@@ -4,41 +4,54 @@ with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setup(
- name="kittentts",
- version="0.8.1",
+ name="kittenml",
+ version="0.9.1",
author="KittenML",
author_email="",
- description="Ultra-lightweight text-to-speech model with just 15 million parameters",
+ description="Text-to-speech with voice cloning and expression control, plus ultra-lightweight models that run on CPU",
long_description=long_description,
long_description_content_type="text/markdown",
- url="https://github.com/kittenml/kittentts",
+ url="https://github.com/KittenML/KittenTTS",
packages=find_packages(),
+ include_package_data=True,
classifiers=[
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3",
- "Programming Language :: Python :: 3.8",
- "Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Topic :: Multimedia :: Sound/Audio :: Speech",
"Topic :: Scientific/Engineering :: Artificial Intelligence",
],
- python_requires=">=3.8",
+ python_requires=">=3.10",
install_requires=[
+ "torch>=2.6",
+ "torchaudio>=2.6",
+ "transformers>=4.55",
+ "safetensors",
+ "numpy",
+ "scipy",
+ "soundfile",
+ "librosa",
+ "huggingface_hub",
+ "einops",
+ "diffusers",
+ "omegaconf",
+ "hydra-core",
+ "s3tokenizer",
+ "resemble-perth",
+ "pyloudnorm",
+ "kitten-text-processing>=0.1.0",
"espeakng_loader",
"phonemizer",
"onnxruntime",
- "soundfile",
- "numpy",
- "huggingface_hub",
],
- keywords="text-to-speech, tts, speech-synthesis, neural-networks, onnx",
+ keywords="text-to-speech, tts, speech-synthesis, voice-cloning, neural-networks, onnx",
project_urls={
- "Bug Reports": "https://github.com/kittenml/kittentts/issues",
- "Source": "https://github.com/kittenml/kittentts",
+ "Bug Reports": "https://github.com/KittenML/KittenTTS/issues",
+ "Source": "https://github.com/KittenML/KittenTTS",
},
)
diff --git a/tests/test_text_normalization.py b/tests/test_text_normalization.py
index 6a9eb92..7a32bd4 100644
--- a/tests/test_text_normalization.py
+++ b/tests/test_text_normalization.py
@@ -1,7 +1,7 @@
import unittest
-from kittentts import NormalizedTextResult, normalize_text
-from kittentts.preprocess import chunk_text
+from kittenml import NormalizedTextResult, normalize_text
+from kittenml.preprocess import chunk_text
class TextNormalizationTests(unittest.TestCase):