Skip to content

A TTS that fits in your CPU (and pocket)

Python

Small models: z_dim, attention options, low-rank text table, one-step heads, decoder dims, small English models (#360)

manu-lm8b34332a8f6f
diff --git a/README.md b/README.md
index 813dfb7..64491aa 100644
--- a/README.md
+++ b/README.md
@@ -55,6 +55,7 @@ pocket-tts generate
Modify the voice with `--voice` and the text with `--text`. We provide a small catalog of voices.
Choose a pretrained language model with `--language` when running `generate`, `export-voice`, or `serve` (default: `english`). Non-english languages have also biggers 24 layers variants that are higher quality but slower. You can select them by using for example `--language italian_24l`.
`--language english_drifting_26-09` selects an English model whose sampler head was trained with drifting instead of LSD (see [training/README.md](training/README.md) for the recipe).
+`--language english_18m_2026-10`, `english_7m_2026-10` and `english_2m_2026-10` select small English models with 18.2M, 6.9M and 1.9M parameters (decoder included). The `_refl` variants, such as `english_7m_refl_2026-10`, add reward fine-tuning.
The `--config` option accepts a local YAML path, an `https://` URL, or an `hf://` path (e.g. `hf://<repo_id>/<path>[@revision]`) for custom weights.
You can take a look at [this page](https://huggingface.co/kyutai/tts-voices) which details the licenses
diff --git a/docs/API Reference/python-api.md b/docs/API Reference/python-api.md
index 7af6be9..08baf43 100644
--- a/docs/API Reference/python-api.md
+++ b/docs/API Reference/python-api.md
@@ -42,7 +42,7 @@ The main class for text-to-speech generation.
Load and return a TTSModel instance with pre-trained weights.
**Parameters:**
-- `language` (str | None): Name of built-in language config to load. Supported values: `"english_2026-01"`, `"english_2026-04"`, `"english_2026-09"`, `"english_2026-09_2"`, `"english_drifting_26-09"`, `"english"`, `"french"`, `"french_24l"`, `"german"`, `"german_24l"`, `"portuguese"`, `"portuguese_24l"`, `"italian"`, `"italian_24l"`, `"spanish"`, `"spanish_24l"`, `"dutch"`, `"dutch_24l"`. If both `language` and `config` are omitted, defaults to `"english"`, which is the same model as `"english_2026-09_2"`. The "24l" variants are larger models that are not distilled yet and are here only as a preview.
+- `language` (str | None): Name of built-in language config to load. Supported values: `"english_2026-01"`, `"english_2026-04"`, `"english_2026-09"`, `"english_2026-09_2"`, `"english_drifting_26-09"`, `"english_18m_2026-10"`, `"english_18m_refl_2026-10"`, `"english_7m_2026-10"`, `"english_7m_refl_2026-10"`, `"english_2m_2026-10"`, `"english_2m_refl_2026-10"`, `"english"`, `"french"`, `"french_24l"`, `"german"`, `"german_24l"`, `"portuguese"`, `"portuguese_24l"`, `"italian"`, `"italian_24l"`, `"spanish"`, `"spanish_24l"`, `"dutch"`, `"dutch_24l"`. If both `language` and `config` are omitted, defaults to `"english"`, which is the same model as `"english_2026-09_2"`. The "24l" variants are larger models that are not distilled yet and are here only as a preview.
- `config` (str | None): Path to model config YAML file. Incompatible with `language`.
- `temp` (float | None): Sampling temperature for generation. `None` uses the model's recommended default from its config file (`default_temperature`, 0.3).
- `sampler_decode_steps` (int): Number of generation steps (default: 1)
diff --git a/docs/CLI Commands/export_voice.md b/docs/CLI Commands/export_voice.md
index 0e9139f..6046c57 100644
--- a/docs/CLI Commands/export_voice.md
+++ b/docs/CLI Commands/export_voice.md
@@ -24,7 +24,7 @@ Only the first 30 seconds of the audio file will be processed.
### Options
- `--quiet`: Do not print any output except errors.
-- `--language`: Language for the TTS model, one of `'english_2026-01'`, `'english_2026-04'`, `'english_2026-09'`, `'english_2026-09_2'`, `'english_drifting_26-09'`, `'english'`, `'french'`, `'french_24l'`, `'german'`, `'german_24l'`, `'portuguese'`, `'portuguese_24l'`, `'italian'`, `'italian_24l'`, `'spanish'`, `'spanish_24l'`, `'dutch'`, `'dutch_24l'` (default: `english`, which is the same model as `'english_2026-09_2'`). Incompatible with `--config`. The "24l" variants are bigger models, not distilled yet and here only as preview.
+- `--language`: Language for the TTS model, one of `'english_2026-01'`, `'english_2026-04'`, `'english_2026-09'`, `'english_2026-09_2'`, `'english_drifting_26-09'`, `'english_18m_2026-10'`, `'english_18m_refl_2026-10'`, `'english_7m_2026-10'`, `'english_7m_refl_2026-10'`, `'english_2m_2026-10'`, `'english_2m_refl_2026-10'`, `'english'`, `'french'`, `'french_24l'`, `'german'`, `'german_24l'`, `'portuguese'`, `'portuguese_24l'`, `'italian'`, `'italian_24l'`, `'spanish'`, `'spanish_24l'`, `'dutch'`, `'dutch_24l'` (default: `english`, which is the same model as `'english_2026-09_2'`). Incompatible with `--config`. The "24l" variants are bigger models, not distilled yet and here only as preview.
- `--config`: Model config yaml path — a local path, an `https://` URL, or an `hf://` path. Incompatible with `--language`.
## Examples
diff --git a/docs/CLI Commands/generate.md b/docs/CLI Commands/generate.md
index fcea971..781ee4f 100644
--- a/docs/CLI Commands/generate.md
+++ b/docs/CLI Commands/generate.md
@@ -19,7 +19,7 @@ This will generate a WAV file `./tts_output.wav` with the default text and voice
- `--text TEXT`: Text to generate (default: "Hello world! I am Kyutai Pocket TTS. I'm fast enough to run on small CPUs. I hope you'll like me.")
- `--voice VOICE`: Path to audio conditioning file (voice to clone). Defaults to a built-in voice chosen from the language: `giovanni` (it) for italian, `lola` (es) for spanish, `juergen` (de) for german, `rafael` (pt) for portuguese, `estelle` (fr) for french, `alba` (en) otherwise. With `--config` or `--checkpoint`, defaults to [alba's audio file](https://huggingface.co/kyutai/tts-voices/blob/main/alba-mackenna/casual.wav) instead of the voice name, since the pre-made voices only exist for the released language models. Urls and local paths are supported.
- `--output-path OUTPUT_PATH`: Output path for generated audio (default: "./tts_output.wav")
-- `--language LANGUAGE`: Language for the TTS model, one of `'english_2026-01'`, `'english_2026-04'`, `'english_2026-09'`, `'english_2026-09_2'`, `'english_drifting_26-09'`, `'english'`, `'french'`, `'french_24l'`, `'german'`, `'german_24l'`, `'portuguese'`, `'portuguese_24l'`, `'italian'`, `'italian_24l'`, `'spanish'`, `'spanish_24l'`, `'dutch'`, `'dutch_24l'` (default: `english`, which is the same model as `'english_2026-09_2'`). Incompatible with `--config`. The "24l" variants are bigger models, not distilled yet and here only as preview.
+- `--language LANGUAGE`: Language for the TTS model, one of `'english_2026-01'`, `'english_2026-04'`, `'english_2026-09'`, `'english_2026-09_2'`, `'english_drifting_26-09'`, `'english_18m_2026-10'`, `'english_18m_refl_2026-10'`, `'english_7m_2026-10'`, `'english_7m_refl_2026-10'`, `'english_2m_2026-10'`, `'english_2m_refl_2026-10'`, `'english'`, `'french'`, `'french_24l'`, `'german'`, `'german_24l'`, `'portuguese'`, `'portuguese_24l'`, `'italian'`, `'italian_24l'`, `'spanish'`, `'spanish_24l'`, `'dutch'`, `'dutch_24l'` (default: `english`, which is the same model as `'english_2026-09_2'`). Incompatible with `--config`. The "24l" variants are bigger models, not distilled yet and here only as preview.
### Generation Parameters
diff --git a/docs/CLI Commands/serve.md b/docs/CLI Commands/serve.md
index 11f1684..8152f12 100644
--- a/docs/CLI Commands/serve.md
+++ b/docs/CLI Commands/serve.md
@@ -17,7 +17,7 @@ This starts a server on `http://localhost:8000` with the default voice model.
- `--host HOST`: Host to bind to (default: "localhost")
- `--port PORT`: Port to bind to (default: 8000)
- `--reload`: Enable auto-reload for development
-- `--language`: Language for the TTS model, one of `'english_2026-01'`, `'english_2026-04'`, `'english_2026-09'`, `'english_2026-09_2'`, `'english_drifting_26-09'`, `'english'`, `'french'`, `'french_24l'`, `'german'`, `'german_24l'`, `'portuguese'`, `'portuguese_24l'`, `'italian'`, `'italian_24l'`, `'spanish'`, `'spanish_24l'`, `'dutch'`, `'dutch_24l'` (default: `english`, which is the same model as `'english_2026-09_2'`). Incompatible with `--config`. The "24l" variants are bigger models, not distilled yet and here only as preview.
+- `--language`: Language for the TTS model, one of `'english_2026-01'`, `'english_2026-04'`, `'english_2026-09'`, `'english_2026-09_2'`, `'english_drifting_26-09'`, `'english_18m_2026-10'`, `'english_18m_refl_2026-10'`, `'english_7m_2026-10'`, `'english_7m_refl_2026-10'`, `'english_2m_2026-10'`, `'english_2m_refl_2026-10'`, `'english'`, `'french'`, `'french_24l'`, `'german'`, `'german_24l'`, `'portuguese'`, `'portuguese_24l'`, `'italian'`, `'italian_24l'`, `'spanish'`, `'spanish_24l'`, `'dutch'`, `'dutch_24l'` (default: `english`, which is the same model as `'english_2026-09_2'`). Incompatible with `--config`. The "24l" variants are bigger models, not distilled yet and here only as preview.
- `--config`: Path to a custom config .yaml — a local path, an `https://` URL, or an `hf://` path. Incompatible with `--language`.
- `--default-voice`: Voice used by the requests that don't ask for one (default: the built-in voice of the language). It accepts anything the `generate --voice` option accepts: a built-in voice name, a local path to an audio file or to a `.safetensors` voice, an `https://` URL, or an `hf://` path. It is loaded at startup, so a voice that cannot be read fails the server immediately instead of the first request.
- `--quantize`: Use int8 quantization for the model (default: False). This can reduce memory usage and increase speed, with minimal impact on audio quality.
diff --git a/pocket_tts/config/english_18m_2026-10.yaml b/pocket_tts/config/english_18m_2026-10.yaml
new file mode 100644
index 0000000..98566df
--- /dev/null
+++ b/pocket_tts/config/english_18m_2026-10.yaml
@@ -0,0 +1,88 @@
+# English model with 18.2M parameters: a 15.6M flow LM and a 2.6M decoder.
+
+weights_path: hf://kyutai/pocket-tts/languages/english_18m_2026-10/model.safetensors@a0172fa05a0725a745539c88e4b58f1ee19cb9a7
+weights_path_without_voice_cloning: hf://kyutai/pocket-tts-without-voice-cloning/languages/english_18m_2026-10/model.safetensors@08ffc58775e62aad9409511b9591c9af626270f3
+default_temperature: 0.3
+flow_lm:
+ insert_bos_before_voice: true
+ dtype: float32
+ flow:
+ depth: 4
+ dim: 192
+ type: drifting
+ transformer:
+ d_model: 512
+ hidden_scale: 1
+ max_period: 10000
+ num_heads: 8
+ num_layers: 8
+ attn_dim: null
+ num_kv_heads: null
+ lookup_table:
+ dim: 512
+ n_bins: 4000
+ tokenizer: sentencepiece
+ tokenizer_path: hf://kyutai/pocket-tts-without-voice-cloning/languages/english_18m_2026-10/tokenizer.model@08ffc58775e62aad9409511b9591c9af626270f3
+ rank: null
+ z_dim: 64
+mimi:
+ dtype: float32
+ sample_rate: 24000
+ inner_dim: 32
+ outer_dim: 128
+ channels: 1
+ frame_rate: 12.5
+ seanet:
+ dimension: 512
+ channels: 1
+ n_filters: 64
+ n_residual_layers: 1
+ ratios:
+ - 6
+ - 5
+ - 4
+ kernel_size: 7
+ residual_kernel_size: 3
+ last_kernel_size: 3
+ dilation_base: 2
+ pad_mode: constant
+ compress: 2
+ transformer:
+ d_model: 512
+ num_heads: 8
+ num_layers: 2
+ layer_scale: 0.01
+ context: 250
+ dim_feedforward: 2048
+ input_dimension: 512
+ output_dimensions:
+ - 512
+ quantizer:
+ dimension: 32
+ output_dimension: 128
+ decoder_seanet:
+ dimension: 128
+ channels: 1
+ n_filters: 32
+ n_residual_layers: 1
+ ratios:
+ - 6
+ - 5
+ - 4
+ kernel_size: 3
+ residual_kernel_size: 3
+ last_kernel_size: 3
+ dilation_base: 2
+ pad_mode: constant
+ compress: 2
+ decoder_transformer:
+ d_model: 128
+ num_heads: 4
+ num_layers: 12
+ layer_scale: 0.01
+ context: 50
+ dim_feedforward: 384
+ input_dimension: 128
+ output_dimensions:
+ - 128
+default_eos_threshold: -1.0
diff --git a/pocket_tts/config/english_18m_refl_2026-10.yaml b/pocket_tts/config/english_18m_refl_2026-10.yaml
new file mode 100644
index 0000000..f60817a
--- /dev/null
+++ b/pocket_tts/config/english_18m_refl_2026-10.yaml
@@ -0,0 +1,88 @@
+# english_18m_2026-10 after reward fine-tuning (REFL).
+
+weights_path: hf://kyutai/pocket-tts/languages/english_18m_refl_2026-10/model.safetensors@a0172fa05a0725a745539c88e4b58f1ee19cb9a7
+weights_path_without_voice_cloning: hf://kyutai/pocket-tts-without-voice-cloning/languages/english_18m_refl_2026-10/model.safetensors@08ffc58775e62aad9409511b9591c9af626270f3
+default_temperature: 0.3
+flow_lm:
+ insert_bos_before_voice: true
+ dtype: float32
+ flow:
+ depth: 4
+ dim: 192
+ type: drifting
+ transformer:
+ d_model: 512
+ hidden_scale: 1
+ max_period: 10000
+ num_heads: 8
+ num_layers: 8
+ attn_dim: null
+ num_kv_heads: null
+ lookup_table:
+ dim: 512
+ n_bins: 4000
+ tokenizer: sentencepiece
+ tokenizer_path: hf://kyutai/pocket-tts-without-voice-cloning/languages/english_18m_refl_2026-10/tokenizer.model@08ffc58775e62aad9409511b9591c9af626270f3
+ rank: null
+ z_dim: 64
+mimi:
+ dtype: float32
+ sample_rate: 24000
+ inner_dim: 32
+ outer_dim: 128
+ channels: 1
+ frame_rate: 12.5
+ seanet:
+ dimension: 512
+ channels: 1
+ n_filters: 64
+ n_residual_layers: 1
+ ratios:
+ - 6
+ - 5
+ - 4
+ kernel_size: 7
+ residual_kernel_size: 3
+ last_kernel_size: 3
+ dilation_base: 2
+ pad_mode: constant
+ compress: 2
+ transformer:
+ d_model: 512
+ num_heads: 8
+ num_layers: 2
+ layer_scale: 0.01
+ context: 250
+ dim_feedforward: 2048
+ input_dimension: 512
+ output_dimensions:
+ - 512
+ quantizer:
+ dimension: 32
+ output_dimension: 128
+ decoder_seanet:
+ dimension: 128
+ channels: 1
+ n_filters: 32
+ n_residual_layers: 1
+ ratios:
+ - 6
+ - 5
+ - 4
+ kernel_size: 3
+ residual_kernel_size: 3
+ last_kernel_size: 3
+ dilation_base: 2
+ pad_mode: constant
+ compress: 2
+ decoder_transformer:
+ d_model: 128
+ num_heads: 4
+ num_layers: 12
+ layer_scale: 0.01
+ context: 50
+ dim_feedforward: 384
+ input_dimension: 128
+ output_dimensions:
+ - 128
+default_eos_threshold: -1.0
diff --git a/pocket_tts/config/english_2m_2026-10.yaml b/pocket_tts/config/english_2m_2026-10.yaml
new file mode 100644
index 0000000..542b963
--- /dev/null
+++ b/pocket_tts/config/english_2m_2026-10.yaml
@@ -0,0 +1,89 @@
+# English model with 1.9M parameters: a 0.9M flow LM and a 1.0M decoder.
+
+weights_path: hf://kyutai/pocket-tts/languages/english_2m_2026-10/model.safetensors@a72dba0d1a5f1387c104f9d3e17abb8ab60b4fae
+weights_path_without_voice_cloning: hf://kyutai/pocket-tts-without-voice-cloning/languages/english_2m_2026-10/model.safetensors@a3055dcb533cf2ec90458008a01e7cef550bae2a
+default_temperature: 0.3
+flow_lm:
+ insert_bos_before_voice: true
+ dtype: float32
+ flow:
+ depth: 4
+ dim: 64
+ type: pointwise
+ transformer:
+ d_model: 112
+ hidden_scale: 1
+ max_period: 10000
+ num_heads: 3
+ num_layers: 8
+ dim_feedforward: 96
+ attn_dim: 192
+ num_kv_heads: 1
+ lookup_table:
+ dim: 112
+ n_bins: 4000
+ tokenizer: sentencepiece
+ tokenizer_path: hf://kyutai/pocket-tts-without-voice-cloning/languages/english_2m_2026-10/tokenizer.model@08ffc58775e62aad9409511b9591c9af626270f3
+ rank: 32
+ z_dim: 64
+mimi:
+ dtype: float32
+ sample_rate: 24000
+ inner_dim: 32
+ outer_dim: 128
+ channels: 1
+ frame_rate: 12.5
+ seanet:
+ dimension: 512
+ channels: 1
+ n_filters: 64
+ n_residual_layers: 1
+ ratios:
+ - 6
+ - 5
+ - 4
+ kernel_size: 7
+ residual_kernel_size: 3
+ last_kernel_size: 3
+ dilation_base: 2
+ pad_mode: constant
+ compress: 2
+ transformer:
+ d_model: 512
+ num_heads: 8
+ num_layers: 2
+ layer_scale: 0.01
+ context: 250
+ dim_feedforward: 2048
+ input_dimension: 512
+ output_dimensions:
+ - 512
+ quantizer:
+ dimension: 32
+ output_dimension: 128
+ decoder_seanet:
+ dimension: 128
+ channels: 1
+ n_filters: 24
+ n_residual_layers: 1
+ ratios:
+ - 6
+ - 5
+ - 4
+ kernel_size: 3
+ residual_kernel_size: 3
+ last_kernel_size: 3
+ dilation_base: 2
+ pad_mode: constant
+ compress: 2
+ decoder_transformer:
+ d_model: 128
+ num_heads: 4
+ num_layers: 4
+ layer_scale: 0.01
+ context: 50
+ dim_feedforward: 384
+ input_dimension: 128
+ output_dimensions:
+ - 128
+default_eos_threshold: -1.0
diff --git a/pocket_tts/config/english_2m_refl_2026-10.yaml b/pocket_tts/config/english_2m_refl_2026-10.yaml
new file mode 100644
index 0000000..ad6e961
--- /dev/null
+++ b/pocket_tts/config/english_2m_refl_2026-10.yaml
@@ -0,0 +1,89 @@
+# english_2m_2026-10 after reward fine-tuning (REFL).
+
+weights_path: hf://kyutai/pocket-tts/languages/english_2m_refl_2026-10/model.safetensors@a72dba0d1a5f1387c104f9d3e17abb8ab60b4fae
+weights_path_without_voice_cloning: hf://kyutai/pocket-tts-without-voice-cloning/languages/english_2m_refl_2026-10/model.safetensors@a3055dcb533cf2ec90458008a01e7cef550bae2a
+default_temperature: 0.3
+flow_lm:
+ insert_bos_before_voice: true
+ dtype: float32
+ flow:
+ depth: 4
+ dim: 64
+ type: pointwise
+ transformer:
+ d_model: 112
+ hidden_scale: 1
+ max_period: 10000
+ num_heads: 3
+ num_layers: 8
+ dim_feedforward: 96
+ attn_dim: 192
+ num_kv_heads: 1
+ lookup_table:
+ dim: 112
+ n_bins: 4000
+ tokenizer: sentencepiece
+ tokenizer_path: hf://kyutai/pocket-tts-without-voice-cloning/languages/english_2m_refl_2026-10/tokenizer.model@08ffc58775e62aad9409511b9591c9af626270f3
+ rank: 32
+ z_dim: 64
+mimi:
+ dtype: float32
+ sample_rate: 24000
+ inner_dim: 32
+ outer_dim: 128
+ channels: 1
+ frame_rate: 12.5
+ seanet:
+ dimension: 512
+ channels: 1
+ n_filters: 64
+ n_residual_layers: 1
+ ratios:
+ - 6
+ - 5
+ - 4
+ kernel_size: 7
+ residual_kernel_size: 3
+ last_kernel_size: 3
+ dilation_base: 2
+ pad_mode: constant
+ compress: 2
+ transformer:
+ d_model: 512
+ num_heads: 8
+ num_layers: 2
+ layer_scale: 0.01
+ context: 250
+ dim_feedforward: 2048
+ input_dimension: 512
+ output_dimensions:
+ - 512
+ quantizer:
+ dimension: 32
+ output_dimension: 128
+ decoder_seanet:
+ dimension: 128
+ channels: 1
+ n_filters: 24
+ n_residual_layers: 1
+ ratios:
+ - 6
+ - 5
+ - 4
+ kernel_size: 3
+ residual_kernel_size: 3
+ last_kernel_size: 3
+ dilation_base: 2
+ pad_mode: constant
+ compress: 2
+ decoder_transformer:
+ d_model: 128
+ num_heads: 4
+ num_layers: 4
+ layer_scale: 0.01
+ context: 50
+ dim_feedforward: 384
+ input_dimension: 128
+ output_dimensions:
+ - 128
+default_eos_threshold: -1.0
diff --git a/pocket_tts/config/english_7m_2026-10.yaml b/pocket_tts/config/english_7m_2026-10.yaml
new file mode 100644
index 0000000..f1dbcca
--- /dev/null
+++ b/pocket_tts/config/english_7m_2026-10.yaml
@@ -0,0 +1,88 @@
+# English model with 6.9M parameters: a 4.3M flow LM and a 2.6M decoder.
+
+weights_path: hf://kyutai/pocket-tts/languages/english_7m_2026-10/model.safetensors@a0172fa05a0725a745539c88e4b58f1ee19cb9a7
+weights_path_without_voice_cloning: hf://kyutai/pocket-tts-without-voice-cloning/languages/english_7m_2026-10/model.safetensors@08ffc58775e62aad9409511b9591c9af626270f3
+default_temperature: 0.3
+flow_lm:
+ insert_bos_before_voice: true
+ dtype: float32
+ flow:
+ depth: 4
+ dim: 192
+ type: drifting
+ transformer:
+ d_model: 224
+ hidden_scale: 1
+ max_period: 10000
+ num_heads: 8
+ num_layers: 8
+ attn_dim: 512
+ num_kv_heads: 2
+ lookup_table:
+ dim: 224
+ n_bins: 4000
+ tokenizer: sentencepiece
+ tokenizer_path: hf://kyutai/pocket-tts-without-voice-cloning/languages/english_7m_2026-10/tokenizer.model@08ffc58775e62aad9409511b9591c9af626270f3
+ rank: 64
+ z_dim: 64
+mimi:
+ dtype: float32
+ sample_rate: 24000
+ inner_dim: 32
+ outer_dim: 128
+ channels: 1
+ frame_rate: 12.5
+ seanet:
+ dimension: 512
+ channels: 1
+ n_filters: 64
+ n_residual_layers: 1
+ ratios:
+ - 6
+ - 5
+ - 4
+ kernel_size: 7
+ residual_kernel_size: 3
+ last_kernel_size: 3
+ dilation_base: 2
+ pad_mode: constant
+ compress: 2
+ transformer:
+ d_model: 512
+ num_heads: 8
+ num_layers: 2
+ layer_scale: 0.01
+ context: 250
+ dim_feedforward: 2048
+ input_dimension: 512
+ output_dimensions:
+ - 512
+ quantizer:
+ dimension: 32
+ output_dimension: 128
+ decoder_seanet:
+ dimension: 128
+ channels: 1
+ n_filters: 32
+ n_residual_layers: 1
+ ratios:
+ - 6
+ - 5
+ - 4
+ kernel_size: 3
+ residual_kernel_size: 3
+ last_kernel_size: 3
+ dilation_base: 2
+ pad_mode: constant
+ compress: 2
+ decoder_transformer:
+ d_model: 128
+ num_heads: 4
+ num_layers: 12
+ layer_scale: 0.01
+ context: 50
+ dim_feedforward: 384
+ input_dimension: 128
+ output_dimensions:
+ - 128
+default_eos_threshold: -1.0
diff --git a/pocket_tts/config/english_7m_refl_2026-10.yaml b/pocket_tts/config/english_7m_refl_2026-10.yaml
new file mode 100644
index 0000000..9cda00d
--- /dev/null
+++ b/pocket_tts/config/english_7m_refl_2026-10.yaml
@@ -0,0 +1,88 @@
+# english_7m_2026-10 after reward fine-tuning (REFL).
+
+weights_path: hf://kyutai/pocket-tts/languages/english_7m_refl_2026-10/model.safetensors@a0172fa05a0725a745539c88e4b58f1ee19cb9a7
+weights_path_without_voice_cloning: hf://kyutai/pocket-tts-without-voice-cloning/languages/english_7m_refl_2026-10/model.safetensors@08ffc58775e62aad9409511b9591c9af626270f3
+default_temperature: 0.3
+flow_lm:
+ insert_bos_before_voice: true
+ dtype: float32
+ flow:
+ depth: 4
+ dim: 192
+ type: drifting
+ transformer:
+ d_model: 224
+ hidden_scale: 1
+ max_period: 10000
+ num_heads: 8
+ num_layers: 8
+ attn_dim: 512
+ num_kv_heads: 2
+ lookup_table:
+ dim: 224
+ n_bins: 4000
+ tokenizer: sentencepiece
+ tokenizer_path: hf://kyutai/pocket-tts-without-voice-cloning/languages/english_7m_refl_2026-10/tokenizer.model@08ffc58775e62aad9409511b9591c9af626270f3
+ rank: 64
+ z_dim: 64
+mimi:
+ dtype: float32
+ sample_rate: 24000
+ inner_dim: 32
+ outer_dim: 128
+ channels: 1
+ frame_rate: 12.5
+ seanet:
+ dimension: 512
+ channels: 1
+ n_filters: 64
+ n_residual_layers: 1
+ ratios:
+ - 6
+ - 5
+ - 4
+ kernel_size: 7
+ residual_kernel_size: 3
+ last_kernel_size: 3
+ dilation_base: 2
+ pad_mode: constant
+ compress: 2
+ transformer:
+ d_model: 512
+ num_heads: 8
+ num_layers: 2
+ layer_scale: 0.01
+ context: 250
+ dim_feedforward: 2048
+ input_dimension: 512
+ output_dimensions:
+ - 512
+ quantizer:
+ dimension: 32
+ output_dimension: 128
+ decoder_seanet:
+ dimension: 128
+ channels: 1
+ n_filters: 32
+ n_residual_layers: 1
+ ratios:
+ - 6
+ - 5
+ - 4
+ kernel_size: 3
+ residual_kernel_size: 3
+ last_kernel_size: 3
+ dilation_base: 2
+ pad_mode: constant
+ compress: 2
+ decoder_transformer:
+ d_model: 128
+ num_heads: 4
+ num_layers: 12
+ layer_scale: 0.01
+ context: 50
+ dim_feedforward: 384
+ input_dimension: 128
+ output_dimensions:
+ - 128
+default_eos_threshold: -1.0
diff --git a/pocket_tts/main.py b/pocket_tts/main.py
index 0b80108..2378428 100644
--- a/pocket_tts/main.py
+++ b/pocket_tts/main.py
@@ -17,7 +17,6 @@ from fastapi.responses import HTMLResponse, StreamingResponse
from pocket_tts.data.audio import stream_audio_chunks
from pocket_tts.default_parameters import (
- DEFAULT_EOS_THRESHOLD,
DEFAULT_FRAMES_AFTER_EOS,
DEFAULT_NOISE_CLAMP,
DEFAULT_SAMPLER_DECODE_STEPS,
@@ -217,7 +216,7 @@ def serve(
str | None,
typer.Option(
help="Language for the TTS model. "
- "'english_2026-01', 'english_2026-04', 'english_2026-09', 'english_2026-09_2', 'english_drifting_26-09', 'english', 'french', 'french_24l', 'german', 'german_24l', 'portuguese', 'portuguese_24l', 'italian', 'italian_24l', 'spanish', 'spanish_24l', 'dutch', 'dutch_24l'."
+ "'english_2026-01', 'english_2026-04', 'english_2026-09', 'english_2026-09_2', 'english_drifting_26-09', 'english_18m_2026-10', 'english_18m_refl_2026-10', 'english_7m_2026-10', 'english_7m_refl_2026-10', 'english_2m_2026-10', 'english_2m_refl_2026-10', 'english', 'french', 'french_24l', 'german', 'german_24l', 'portuguese', 'portuguese_24l', 'italian', 'italian_24l', 'spanish', 'spanish_24l', 'dutch', 'dutch_24l'."
" Incompatible with the config argument. Default is 'english', which is the same model as 'english_2026-09_2'.",
show_default=False,
),
@@ -283,7 +282,7 @@ def generate(
typer.Option(
help=(
"Language for the TTS model. "
- "'english_2026-01', 'english_2026-04', 'english_2026-09', 'english_2026-09_2', 'english_drifting_26-09', 'english', 'french', 'french_24l', 'german', 'german_24l', 'portuguese', 'portuguese_24l', 'italian', 'italian_24l', 'spanish', 'spanish_24l', 'dutch', 'dutch_24l'."
+ "'english_2026-01', 'english_2026-04', 'english_2026-09', 'english_2026-09_2', 'english_drifting_26-09', 'english_18m_2026-10', 'english_18m_refl_2026-10', 'english_7m_2026-10', 'english_7m_refl_2026-10', 'english_2m_2026-10', 'english_2m_refl_2026-10', 'english', 'french', 'french_24l', 'german', 'german_24l', 'portuguese', 'portuguese_24l', 'italian', 'italian_24l', 'spanish', 'spanish_24l', 'dutch', 'dutch_24l'."
" Incompatible with the config argument. Default is 'english', which is the same model as 'english_2026-09_2'. "
"The '24l' variants are bigger models, "
"not distilled yet and here only as preview. They're not the final "
@@ -319,7 +318,10 @@ def generate(
noise_clamp: Annotated[
float | None, typer.Option(help="Noise clamp value")
] = DEFAULT_NOISE_CLAMP,
- eos_threshold: Annotated[float, typer.Option(help="EOS threshold")] = DEFAULT_EOS_THRESHOLD,
+ eos_threshold: Annotated[
+ float | None,
+ typer.Option(help="EOS threshold. Defaults to the model's value from its config (-4.0)."),
+ ] = None,
frames_after_eos: Annotated[
int | None, typer.Option(help="Number of frames to generate after EOS")
] = DEFAULT_FRAMES_AFTER_EOS,
@@ -403,7 +405,7 @@ def export_voice(
typer.Option(
help=(
"Language for the TTS model. "
- "'english_2026-01', 'english_2026-04', 'english_2026-09', 'english_2026-09_2', 'english_drifting_26-09', 'english', 'french', 'french_24l', 'german', 'german_24l', 'portuguese', 'portuguese_24l', 'italian', 'italian_24l', 'spanish', 'spanish_24l', 'dutch', 'dutch_24l'."
+ "'english_2026-01', 'english_2026-04', 'english_2026-09', 'english_2026-09_2', 'english_drifting_26-09', 'english_18m_2026-10', 'english_18m_refl_2026-10', 'english_7m_2026-10', 'english_7m_refl_2026-10', 'english_2m_2026-10', 'english_2m_refl_2026-10', 'english', 'french', 'french_24l', 'german', 'german_24l', 'portuguese', 'portuguese_24l', 'italian', 'italian_24l', 'spanish', 'spanish_24l', 'dutch', 'dutch_24l'."
" Incompatible with the config argument. Default is 'english', which is the same model as 'english_2026-09_2'. "
"The '24l' variants are bigger models, "
"not distilled yet and here only as preview."
diff --git a/pocket_tts/models/flow_lm.py b/pocket_tts/models/flow_lm.py
index 6560032..99e0cfd 100644
--- a/pocket_tts/models/flow_lm.py
+++ b/pocket_tts/models/flow_lm.py
@@ -46,6 +46,11 @@ def drifting_decode(v_t: FlowNet, x_0: torch.Tensor, num_steps: int = 1) -> torc
return v_t(x_0)
+def pointwise_decode(v_t: FlowNet, x_0: torch.Tensor, num_steps: int = 1) -> torch.Tensor:
+ """One-step head without time conditions, LSD-style: the noise plus the head's output."""
+ return x_0 + v_t(x_0)
+
+
def ot_decode(v_t: FlowNet, x_0: torch.Tensor, num_steps: int = 16) -> torch.Tensor:
"""Euler integration of an optimal-transport conditional flow.
@@ -95,6 +100,7 @@ class FlowLMModel(nn.Module):
dtype: torch.dtype | None = None,
insert_bos_before_voice: bool = False,
flow_type: str = "lsd",
+ z_dim: int | None = None,
):
super().__init__()
self.flow_type = flow_type
@@ -117,7 +123,8 @@ class FlowLMModel(nn.Module):
self.input_linear = nn.Linear(self.ldim, dim, bias=False, dtype=dtype)
self.transformer = transformer
self.out_norm = nn.LayerNorm(dim, eps=1e-5)
- self.out_eos = nn.Linear(dim, 1, dtype=dtype)
+ self.z_proj = None if z_dim is None else nn.Linear(dim, z_dim, bias=False, dtype=dtype)
+ self.out_eos = nn.Linear(z_dim or dim, 1, dtype=dtype)
@property
def device(self) -> str:
@@ -172,6 +179,8 @@ class FlowLMModel(nn.Module):
decode = ot_decode
elif self.flow_type == "drifting":
decode = drifting_decode
+ elif self.flow_type == "pointwise":
+ decode = pointwise_decode
else:
raise ValueError(f"Unknown flow type: {self.flow_type}")
return decode(conditioned_flow, noise, sampler_decode_steps), out_eos
@@ -196,6 +205,8 @@ class FlowLMModel(nn.Module):
transformer_out = self.out_norm(transformer_out)
# remove the prefix from the model outputs (condition is prepended)
transformer_out = transformer_out[:, -sequence.shape[1] :]
+ if self.z_proj is not None:
+ transformer_out = self.z_proj(transformer_out)
return transformer_out
def _sample_next_latent(
@@ -236,7 +247,7 @@ class FlowLMModel(nn.Module):
cls, config: FlowLMConfig, latent_dim: int, insert_bos_before_voice: bool
) -> Self:
d_model = config.transformer.d_model
- flow_mlp = SimpleMLPAdaLN.from_pydantic_config(config, latent_dim, d_model)
+ flow_mlp = SimpleMLPAdaLN.from_pydantic_config(config, latent_dim, config.z_dim or d_model)
conditioner = LUTConditioner(
n_bins=config.lookup_table.n_bins,
@@ -244,6 +255,7 @@ class FlowLMModel(nn.Module):
dim=config.lookup_table.dim,
output_dim=d_model,
tokenizer=config.lookup_table.tokenizer,
+ rank=config.lookup_table.rank,
)
transformer = StreamingTransformer.from_pydantic_config(config.transformer)
@@ -257,4 +269,5 @@ class FlowLMModel(nn.Module):
dtype=getattr(torch, config.dtype),
insert_bos_before_voice=insert_bos_before_voice,
flow_type=config.flow.type,
+ z_dim=config.z_dim,
)
diff --git a/pocket_tts/models/mimi.py b/pocket_tts/models/mimi.py
index 2656cd5..6a5a490 100644
--- a/pocket_tts/models/mimi.py
+++ b/pocket_tts/models/mimi.py
@@ -61,7 +61,7 @@ class MimiModel(nn.Module):
int(downsample_stride), dimension=dimension, out_dimension=inner_dim
)
self.upsample = ConvTrUpsample1d(
- int(downsample_stride), dimension=dimension, in_dimension=outer_dim
+ int(downsample_stride), dimension=decoder.dimension, in_dimension=outer_dim
)
@property
@@ -133,7 +133,7 @@ def build_mimi(config: MimiConfig) -> MimiModel:
mimi_config = config.model_dump()
encoder = SEANetEncoder(**mimi_config["seanet"])
- decoder = SEANetDecoder(**mimi_config["seanet"])
+ decoder = SEANetDecoder(**(mimi_config["decoder_seanet"] or mimi_config["seanet"]))
return MimiModel(
encoder,
decoder,
@@ -145,5 +145,7 @@ def build_mimi(config: MimiConfig) -> MimiModel:
inner_dim=mimi_config["inner_dim"],
outer_dim=mimi_config["outer_dim"],
encoder_transformer=transformer.ProjectedTransformer(**mimi_config["transformer"]),
- decoder_transformer=transformer.ProjectedTransformer(**mimi_config["transformer"]),
+ decoder_transformer=transformer.ProjectedTransformer(
+ **(mimi_config["decoder_transformer"] or mimi_config["transformer"])
+ ),
)
diff --git a/pocket_tts/models/tts_model.py b/pocket_tts/models/tts_model.py
index ea2b1a9..535b193 100644
--- a/pocket_tts/models/tts_model.py
+++ b/pocket_tts/models/tts_model.py
@@ -22,7 +22,6 @@ from typing_extensions import Self
from pocket_tts.data.audio import audio_read
from pocket_tts.data.audio_utils import convert_audio, end_on_pause
from pocket_tts.default_parameters import (
- DEFAULT_EOS_THRESHOLD,
DEFAULT_LANGUAGE,
DEFAULT_NOISE_CLAMP,
DEFAULT_SAMPLER_DECODE_STEPS,
@@ -244,9 +243,10 @@ class TTSModel(nn.Module):
# Load mimi weights from the config safetensors file with complete mapping for strict loading
if config.mimi.weights_path is not None:
- if config.flow_lm.weights_path is None:
+ if config.flow_lm.weights_path is None and config.weights_path is None:
raise ValueError(
- "If you specify mimi.weights_path you should specify flow_lm.weights_path"
+ "If you specify mimi.weights_path you should specify flow_lm.weights_path "
+ "or weights_path"
)
logger.info(f"Loading Mimi weights from {config.mimi.weights_path}")
mimi_state = get_mimi_state_dict(download_if_necessary(config.mimi.weights_path))
@@ -265,6 +265,10 @@ class TTSModel(nn.Module):
weights_file = download_if_necessary(config.weights_path_without_voice_cloning)
state_dict = safetensors.torch.load_file(weights_file)
+ if config.mimi.weights_path is not None:
+ # mimi.weights_path, loaded above, replaces the Mimi weights of the bundle.
+ state_dict = {k: v for k, v in state_dict.items() if not k.startswith("mimi.")}
+ state_dict.update({f"mimi.{k}": v for k, v in tts_model.mimi.state_dict().items()})
tts_model.load_state_dict(state_dict, strict=True)
if config.flow_lm.weights_path is None and config.weights_path is None:
@@ -289,7 +293,7 @@ class TTSModel(nn.Module):
temp: float | None = None,
sampler_decode_steps: int = DEFAULT_SAMPLER_DECODE_STEPS,
noise_clamp: float | None = DEFAULT_NOISE_CLAMP,
- eos_threshold: float = DEFAULT_EOS_THRESHOLD,
+ eos_threshold: float | None = None,
quantize: bool = False,
checkpoint: str | Path | None = None,
lsd_decode_steps: int | None = None,
@@ -303,7 +307,7 @@ class TTSModel(nn.Module):
Args:
language: Optional language identifier to select a predefined config. Incompatible with
the `config` argument. Available options
- are `"english_2026-01"`, `"english_2026-04"`, `"english_2026-09"`, `"english_2026-09_2"`, `"english_drifting_26-09"`, `"english"`, `"french"`, `"french_24l"`, `"german"`, `"german_24l"`, `"portuguese"`, `"portuguese_24l"`, `"italian"`, `"italian_24l"`, `"spanish"`, `"spanish_24l"`, `"dutch"`, `"dutch_24l"`.
+ are `"english_2026-01"`, `"english_2026-04"`, `"english_2026-09"`, `"english_2026-09_2"`, `"english_drifting_26-09"`, `"english_18m_2026-10"`, `"english_18m_refl_2026-10"`, `"english_7m_2026-10"`, `"english_7m_refl_2026-10"`, `"english_2m_2026-10"`, `"english_2m_refl_2026-10"`, `"english"`, `"french"`, `"french_24l"`, `"german"`, `"german_24l"`, `"portuguese"`, `"portuguese_24l"`, `"italian"`, `"italian_24l"`, `"spanish"`, `"spanish_24l"`, `"dutch"`, `"dutch_24l"`.
If neither `config` nor `language` is provided, defaults to `"english", which is the same model as 'english_2026-09_2'`.
config: A path to a custom YAML config file: a local path (e.g., `"C://pocket_tts/pocket_tts_config.yaml"`),
an `https://` URL, or an `hf://` path (e.g. `"hf://<repo_id>/<path>[@revision]"`).
@@ -316,7 +320,8 @@ class TTSModel(nn.Module):
noise_clamp: Maximum value for noise sampling. If None, no clamping
is applied. Helps prevent extreme values in generation.
eos_threshold: Threshold for end-of-sequence detection. Higher values
- make the model more likely to continue generating.
+ make the model more likely to continue generating. If None, defaults to
+ the model's value from its config file (``default_eos_threshold``, -4.0).
checkpoint: Optional training checkpoint (.pt) to load instead of the
config's safetensors weights, so any step of a run can be played
without exporting first. EMA weights are used when the checkpoint
@@ -369,6 +374,8 @@ class TTSModel(nn.Module):
model_config = load_config(config_path)
if temp is None:
temp = model_config.default_temperature
+ if eos_threshold is None:
+ eos_threshold = model_config.default_eos_threshold
logger.info(f"Loading model from config at {config_path}...")
origin = Path(config_path)
@@ -469,7 +476,7 @@ class TTSModel(nn.Module):
for module_name, module_state in model_state.items():
if "cache" in module_state:
cache = module_state["cache"]
- # KV cache has shape [2, batch_size, current_length, num_heads, dim_per_head]
+ # KV cache has shape [2, batch_size, current_length, num_kv_heads, dim_per_head]
current_length = cache.shape[2]
if current_length < sequence_length:
# Create expanded cache filled with NaN for unused positions
diff --git a/pocket_tts/modules/attention.py b/pocket_tts/modules/attention.py
index 1a87b4c..75aeebe 100644
--- a/pocket_tts/modules/attention.py
+++ b/pocket_tts/modules/attention.py
@@ -133,7 +133,13 @@ class StreamingMultiheadAttention(StatefulModule):
"""
def __init__(
- self, embed_dim: int, num_heads: int, rope: RotaryEmbedding, context: int | None = None
+ self,
+ embed_dim: int,
+ num_heads: int,
+ rope: RotaryEmbedding,
+ context: int | None = None,
+ attn_dim: int | None = None,
+ num_kv_heads: int | None = None,
):
super().__init__()
@@ -141,16 +147,18 @@ class StreamingMultiheadAttention(StatefulModule):
self.rope = rope
self.num_heads = num_heads
self.context = context
- self.dim_per_head = embed_dim // num_heads
- self._cache_backend = _LinearKVCacheBackend(self.num_heads, self.dim_per_head)
-
- out_dim = embed_dim
- num_kv = num_heads
- kv_dim = (embed_dim // num_heads) * num_kv
- out_dim += 2 * kv_dim
- mult = 1
- self.in_proj = nn.Linear(embed_dim, mult * out_dim, bias=False)
- self.out_proj = nn.Linear(embed_dim, mult * embed_dim, bias=False)
+ # Queries and the attention output are attn_dim wide (embed_dim by default). Keys and
+ # values have num_kv_heads heads (num_heads by default), each shared by
+ # num_heads // num_kv_heads query heads (grouped-query attention); the cache holds those.
+ self.attn_dim = attn_dim or embed_dim
+ self.num_kv_heads = num_kv_heads or num_heads
+ assert self.attn_dim % num_heads == 0 and num_heads % self.num_kv_heads == 0
+ self.dim_per_head = self.attn_dim // num_heads
+ self._cache_backend = _LinearKVCacheBackend(self.num_kv_heads, self.dim_per_head)
+
+ kv_dim = self.dim_per_head * self.num_kv_heads
+ self.in_proj = nn.Linear(embed_dim, self.attn_dim + 2 * kv_dim, bias=False)
+ self.out_proj = nn.Linear(self.attn_dim, embed_dim, bias=False)
def init_state(self, batch_size: int, sequence_length: int) -> dict[str, torch.Tensor]:
weight = self.in_proj.weight
@@ -176,16 +184,20 @@ class StreamingMultiheadAttention(StatefulModule):
state = None if model_state is None else self.get_state(model_state)
projected = self.in_proj(query)
- # Reshape from (b, t, p*h*d) to (b, t, p, h, d) where p=3, h=num_heads
+ # Split (b, t, q + 2 * kv) into q (b, t, h, d) and k, v (b, t, h_kv, d)
b, t, _ = projected.shape
d = self.dim_per_head
- packed = projected.view(b, t, 3, self.num_heads, d)
- q, k, v = torch.unbind(packed, dim=2)
+ q = projected[..., : self.attn_dim].view(b, t, self.num_heads, d)
+ kv = projected[..., self.attn_dim :].view(b, t, 2, self.num_kv_heads, d)
+ k, v = torch.unbind(kv, dim=2)
rope_offset = self._cache_backend.rope_offset(state, b, q.device)
q, k = self.rope(q, k, offset=rope_offset)
q = q.transpose(1, 2)
k_attn, v_attn, pos_k, offset = self._cache_backend.append_and_get(k, v, state)
+ if self.num_kv_heads != self.num_heads:
+ k_attn = k_attn.repeat_interleave(self.num_heads // self.num_kv_heads, dim=1)
+ v_attn = v_attn.repeat_interleave(self.num_heads // self.num_kv_heads, dim=1)
if attn_mask is not None:
pass # precomputed by the caller (stateless path)
elif state is None:
diff --git a/pocket_tts/modules/mlp.py b/pocket_tts/modules/mlp.py
index ac6a640..937fe43 100644
--- a/pocket_tts/modules/mlp.py
+++ b/pocket_tts/modules/mlp.py
@@ -185,7 +185,7 @@ class SimpleMLPAdaLN(nn.Module):
num_time_conds = 2
elif config.type == "flow_matching":
num_time_conds = 1
- elif config.type == "drifting":
+ elif config.type in ("drifting", "pointwise"):
num_time_conds = 0
else:
raise ValueError(f"Unknown flow type: {config.type}")
diff --git a/pocket_tts/modules/text_conditioner.py b/pocket_tts/modules/text_conditioner.py
index f72d689..0367ac3 100644
--- a/pocket_tts/modules/text_conditioner.py
+++ b/pocket_tts/modules/text_conditioner.py
@@ -119,7 +119,8 @@ class LUTConditioner(nn.Module):
dim (int): Hidden dim of the model (text-encoder/LUT).
output_dim (int): Output dim of the conditioner.
tokenizer (str): Name of the tokenizer.
- possible_values (list[str] or None): list of possible values for the tokenizer.
+ rank (int or None): If set, the table is low-rank: `rank`-wide embeddings followed by
+ a bias-free projection to `dim`.
"""
def __init__(
@@ -129,15 +130,18 @@ class LUTConditioner(nn.Module):
dim: int,
output_dim: int,
tokenizer: str = "sentencepiece",
+ rank: int | None = None,
):
super().__init__()
self.dim = dim
self.output_dim = output_dim
self.tokenizer = build_tokenizer(n_bins, tokenizer_path, tokenizer)
- self.embed = nn.Embedding(n_bins + 1, self.dim) # n_bins + 1 for padding.
+ self.embed = nn.Embedding(n_bins + 1, rank or self.dim) # n_bins + 1 for padding.
+ self.proj = None if rank is None else nn.Linear(rank, self.dim, bias=False)
def prepare(self, x: str) -> torch.Tensor:
return self.tokenizer(x).to(self.embed.weight.device)
def forward(self, tokens: torch.Tensor) -> torch.Tensor:
- return self.embed(tokens)
+ x = self.embed(tokens)
+ return x if self.proj is None else self.proj(x)
diff --git a/pocket_tts/modules/transformer.py b/pocket_tts/modules/transformer.py
index 16b1034..0bc6106 100644
--- a/pocket_tts/modules/transformer.py
+++ b/pocket_tts/modules/transformer.py
@@ -24,10 +24,17 @@ class StreamingTransformerLayer(nn.Module):
context: int | None,
rope: RotaryEmbedding,
layer_scale: float | None = None,
+ attn_dim: int | None = None,
+ num_kv_heads: int | None = None,
):
super().__init__()
self.self_attn = StreamingMultiheadAttention(
- rope=rope, embed_dim=d_model, num_heads=num_heads, context=context
+ rope=rope,
+ embed_dim=d_model,
+ num_heads=num_heads,
+ context=context,
+ attn_dim=attn_dim,
+ num_kv_heads=num_kv_heads,
)
self.norm1 = nn.LayerNorm(d_model, eps=1e-5)
self.norm2 = nn.LayerNorm(d_model, eps=1e-5)
@@ -74,9 +81,11 @@ class StreamingTransformer(nn.Module):
dim_feedforward: int = 2048,
context: int | None = None,
max_period: float = 10_000.0,
+ attn_dim: int | None = None,
+ num_kv_heads: int | None = None,
):
super().__init__()
- assert d_model % num_heads == 0
+ assert (attn_dim or d_model) % num_heads == 0
self.max_period = max_period
self.context = context
@@ -92,18 +101,22 @@ class StreamingTransformer(nn.Module):
context=context,
rope=self.rope,
layer_scale=layer_scale,
+ attn_dim=attn_dim,
+ num_kv_heads=num_kv_heads,
)
)
@classmethod
def from_pydantic_config(cls, config: FlowLMTransformerConfig) -> Self:
- dim_feedforward = int(config.d_model * config.hidden_scale)
+ dim_feedforward = config.dim_feedforward or int(config.d_model * config.hidden_scale)
return cls(
d_model=config.d_model,
num_heads=config.num_heads,
num_layers=config.num_layers,
dim_feedforward=dim_feedforward,
max_period=float(config.max_period),
+ attn_dim=config.attn_dim,
+ num_kv_heads=config.num_kv_heads,
)
def forward(self, x: torch.Tensor, model_state: ModelState | None) -> torch.Tensor:
diff --git a/pocket_tts/utils/config.py b/pocket_tts/utils/config.py
index 2068b49..e74efb6 100644
--- a/pocket_tts/utils/config.py
+++ b/pocket_tts/utils/config.py
@@ -5,6 +5,7 @@ from pathlib import Path
import yaml
from pydantic import BaseModel, ConfigDict
+from pocket_tts.default_parameters import DEFAULT_EOS_THRESHOLD
from pocket_tts.utils.utils import download_if_necessary
CONFIGS_DIR = Path(__file__).parent.parent / "config"
@@ -19,8 +20,9 @@ class FlowConfig(StrictModel):
dim: int
depth: int
# "lsd" (2 time conditions, 1-step decode), "flow_matching" (1 time
- # condition, Euler integration; needs >= 16 decode steps) or "drifting"
- # (no time condition, the head maps noise to a sample in one step).
+ # condition, Euler integration; needs >= 16 decode steps), "drifting"
+ # (no time condition, the head maps noise to a sample in one step) or "pointwise"
+ # (no time condition, one step: the noise plus the head's output, i.e. LSD's 0 -> 1 step).
type: str = "lsd"
@@ -31,6 +33,12 @@ class FlowLMTransformerConfig(StrictModel):
d_model: int
num_heads: int
num_layers: int
+ # Width of queries and of the attention output; d_model when None.
+ attn_dim: int | None = None
+ # Key/value heads, each shared by num_heads // num_kv_heads query heads; num_heads when None.
+ num_kv_heads: int | None = None
+ # Hidden width of the feed-forward layers; d_model * hidden_scale when None.
+ dim_feedforward: int | None = None
class LookupTable(StrictModel):
@@ -38,6 +46,8 @@ class LookupTable(StrictModel):
n_bins: int
tokenizer: str
tokenizer_path: str
+ # Low-rank table: rank-wide embeddings and a bias-free projection to dim; full when None.
+ rank: int | None = None
# Root configuration
@@ -49,6 +59,9 @@ class FlowLMConfig(StrictModel):
# Nested configurations
flow: FlowConfig
transformer: FlowLMTransformerConfig
+ # Width of the backbone output fed to the sampler and EOS heads: a bias-free projection
+ # from d_model when set, the transformer output itself when None.
+ z_dim: int | None = None
# conditioning
lookup_table: LookupTable
@@ -112,6 +125,10 @@ class MimiConfig(StrictModel):
weights_path: str | None = None
inner_dim: int | None = None
outer_dim: int | None = None
+ # Decoder-side SEANet and transformer, when they differ from the encoder's (seanet and
+ # transformer). The decoder side also includes quantizer.output_dimension and outer_dim.
+ decoder_seanet: SEANetConfig | None = None
+ decoder_transformer: MimiTransformerConfig | None = None
class Config(StrictModel):
@@ -137,6 +154,9 @@ class Config(StrictModel):
# 0.3 beats 0.7 on WER and UTMOS for every shipped model (human evals agreed for English, #223);
# a config sets its own value only if it was tuned elsewhere.
default_temperature: float = 0.3
+ # EOS threshold used when the caller does not pass one (generation stops once the EOS logit
+ # exceeds it); a config sets its own value if its model was evaluated with another one.
+ default_eos_threshold: float = DEFAULT_EOS_THRESHOLD
def load_config(yaml_path: str | Path) -> Config:
diff --git a/pocket_tts/utils/utils.py b/pocket_tts/utils/utils.py
index e042c7d..bb505af 100644
--- a/pocket_tts/utils/utils.py
+++ b/pocket_tts/utils/utils.py
@@ -48,7 +48,7 @@ _ORIGINS_OF_PREDEFINED_VOICES = {
def get_predefined_voice(language: str, name: str) -> str:
- return f"hf://kyutai/pocket-tts-without-voice-cloning/languages/{language}/embeddings/{name}.safetensors@ab248779e0718743c013e20b2d812ace7c8f4bf7"
+ return f"hf://kyutai/pocket-tts-without-voice-cloning/languages/{language}/embeddings/{name}.safetensors@a3055dcb533cf2ec90458008a01e7cef550bae2a"
def make_cache_directory() -> Path:
diff --git a/pocket_tts/utils/weights_loading.py b/pocket_tts/utils/weights_loading.py
index 23d22d7..e1a86c7 100644
--- a/pocket_tts/utils/weights_loading.py
+++ b/pocket_tts/utils/weights_loading.py
@@ -33,6 +33,11 @@ def get_flow_lm_state_dict(path: Path) -> dict[str, torch.Tensor]:
def get_mimi_state_dict(path: Path) -> dict[str, torch.Tensor]:
state_dict: dict[str, torch.Tensor] = {}
with safetensors.safe_open(path, framework="pt", device="cpu") as f:
+ if any(key.startswith("mimi.") for key in f.keys()):
+ # Already in this package's layout, e.g. the mimi.* tensors of a TTSModel.
+ return {
+ k.removeprefix("mimi."): f.get_tensor(k) for k in f.keys() if k.startswith("mimi.")
+ }
for key in f.keys():
if (
key.startswith("model.quantizer.vq.")
diff --git a/rust/src/config.rs b/rust/src/config.rs
index b1e43d4..395394a 100644
--- a/rust/src/config.rs
+++ b/rust/src/config.rs
@@ -31,6 +31,12 @@ pub struct FlowLMTransformerConfig {
pub d_model: usize,
pub num_heads: usize,
pub num_layers: usize,
+ #[serde(default)]
+ pub dim_feedforward: Option<usize>,
+ #[serde(default)]
+ pub attn_dim: Option<usize>,
+ #[serde(default)]
+ pub num_kv_heads: Option<usize>,
}
#[derive(Debug, Clone, Deserialize)]
@@ -40,6 +46,8 @@ pub struct LookupTable {
pub n_bins: usize,
pub tokenizer: String,
pub tokenizer_path: String,
+ #[serde(default)]
+ pub rank: Option<usize>,
}
#[derive(Debug, Clone, Deserialize)]
@@ -55,6 +63,8 @@ pub struct FlowLMConfig {
pub weights_path: Option<String>,
#[serde(default)]
pub insert_bos_before_voice: bool,
+ #[serde(default)]
+ pub z_dim: Option<usize>,
}
#[derive(Debug, Clone, Deserialize)]
@@ -117,6 +127,10 @@ pub struct MimiConfig {
pub inner_dim: Option<usize>,
#[serde(default)]
pub outer_dim: Option<usize>,
+ #[serde(default)]
+ pub decoder_seanet: Option<SEANetConfig>,
+ #[serde(default)]
+ pub decoder_transformer: Option<MimiTransformerConfig>,
}
#[derive(Debug, Clone, Deserialize)]
@@ -143,6 +157,10 @@ pub struct Config {
pub model_recommended_frames_after_eos: Option<usize>,
#[serde(default = "default_temperature")]
pub default_temperature: f32,
+ /// Unused: only the small models set it, and they are rejected until xn-ptts supports them.
+ #[allow(dead_code)]
+ #[serde(default)]
+ pub default_eos_threshold: Option<f32>,
}
fn default_true() -> bool {
@@ -257,6 +275,24 @@ impl Config {
/// The configuration is checked up front against what xn-ptts can run, so that a model it
/// cannot represent fails with an explanation rather than a shape mismatch.
fn validate(&self) -> Result<()> {
+ // TODO: upstream to xn-ptts (gradium-ai/xn-ptts#210), then translate these fields.
+ let flow_lm = &self.flow_lm;
+ let transformer = &flow_lm.transformer;
+ if flow_lm.flow.kind == "pointwise"
+ || flow_lm.z_dim.is_some()
+ || flow_lm.lookup_table.rank.is_some()
+ || transformer.dim_feedforward.is_some()
+ || transformer.attn_dim.is_some()
+ || transformer.num_kv_heads.is_some()
+ || self.mimi.decoder_seanet.is_some()
+ || self.mimi.decoder_transformer.is_some()
+ {
+ bail!(
+ "this model uses small-model options (pointwise head, z_dim, attn_dim, num_kv_heads, \
+ a low-rank text table, an explicit feed-forward width or a separate Mimi decoder) \
+ that the pinned xn-ptts does not support yet"
+ )
+ }
self.flow_type()?;
let mimi = &self.mimi;
let dimension = mimi.seanet.dimension;
@@ -360,9 +396,24 @@ impl Config {
mod tests {
use super::*;
+ /// Embedded configs the pinned xn-ptts cannot run yet; they must fail with an explanation.
+ const SMALL_MODELS: [&str; 6] = [
+ "english_18m_2026-10",
+ "english_18m_refl_2026-10",
+ "english_7m_2026-10",
+ "english_7m_refl_2026-10",
+ "english_2m_2026-10",
+ "english_2m_refl_2026-10",
+ ];
+
#[test]
fn every_embedded_config_parses_and_translates() {
for (name, yaml) in CONFIGS {
+ if SMALL_MODELS.contains(name) {
+ let err = Config::parse(yaml).expect_err(name).to_string();
+ assert!(err.contains("small-model options"), "{name}: {err}");
+ continue;
+ }
let config = Config::parse(yaml).unwrap_or_else(|e| panic!("{name}: {e:#}"));
config
.to_ptts(1, -4.0)
diff --git a/tests/test_model_options.py b/tests/test_model_options.py
new file mode 100644
index 0000000..fbf1ec3
--- /dev/null
+++ b/tests/test_model_options.py
@@ -0,0 +1,170 @@
+"""Architecture options, on small randomly initialized models."""
+
+from pathlib import Path
+from typing import TypeVar
+
+import safetensors.torch
+import torch
+
+from pocket_tts.models.flow_lm import FlowLMModel
+from pocket_tts.models.mimi import build_mimi
+from pocket_tts.modules.attention import StreamingMultiheadAttention
+from pocket_tts.modules.rope import RotaryEmbedding
+from pocket_tts.modules.stateful_module import StatefulModule, increment_steps, init_states
+from pocket_tts.utils.config import CONFIGS_DIR, FlowLMConfig, load_config
+from pocket_tts.utils.weights_loading import get_mimi_state_dict
+
+M = TypeVar("M", bound=torch.nn.Module)
+
+
+def build_flow_lm(**overrides: object) -> FlowLMModel:
+ """A 2-layer, 64-wide english flow LM with `overrides` ("transformer.num_kv_heads": 2, ...)."""
+ torch.manual_seed(0)
+ config = load_config(CONFIGS_DIR / "english.yaml").flow_lm.model_dump()
+ config["transformer"].update(d_model=64, num_heads=4, num_layers=2)
+ config["lookup_table"]["dim"] = 64
+ config["flow"].update(dim=32, depth=1)
+ for key, value in overrides.items():
+ *path, leaf = key.split(".")
+ section = config
+ for part in path:
+ section = section[part]
+ section[leaf] = value
+ flow_lm = FlowLMModel.from_pydantic_config(
+ FlowLMConfig(**config), latent_dim=32, insert_bos_before_voice=True
+ )
+ return stamp(flow_lm).eval()
+
+
+def stamp(model: M) -> M:
+ for name, module in model.named_modules():
+ if isinstance(module, StatefulModule):
+ module._module_absolute_name = name
+ return model
+
+
+def sample_latents(flow_lm: FlowLMModel, num_frames: int = 3) -> torch.Tensor:
+ """[num_frames, ldim] latents generated after a short text, streaming one frame at a time."""
+ torch.manual_seed(1)
+ state = init_states(flow_lm, batch_size=1, sequence_length=32)
+ text = flow_lm.conditioner(flow_lm.conditioner.prepare("Hello world."))
+ latent = torch.full((1, 1, flow_lm.ldim), float("nan"))
+ latents = []
+ for _ in range(num_frames):
+ latent, _ = flow_lm(latent, text, state, 1, 0.3, None, -4.0)
+ latent = latent[:, None]
+ increment_steps(flow_lm, state, increment=text.shape[1] + 1)
+ text = text[:, :0]
+ latents.append(latent[0, 0])
+ return torch.stack(latents)
+
+
+def test_z_dim_projects_backbone_output_for_both_heads():
+ flow_lm = build_flow_lm(z_dim=16)
+ assert flow_lm.z_proj is not None
+ assert flow_lm.z_proj.weight.shape == (16, 64)
+ assert flow_lm.out_eos.in_features == 16
+ assert flow_lm.flow_net.cond_embed.in_features == 16
+ assert sample_latents(flow_lm).isfinite().all()
+
+
+def test_z_dim_defaults_to_no_projection():
+ flow_lm = build_flow_lm()
+ assert flow_lm.z_proj is None
+ assert not any(k.startswith("z_proj") for k in flow_lm.state_dict())
+
+
+def test_grouped_query_attention_matches_repeated_kv_heads():
+ torch.manual_seed(0)
+ rope = RotaryEmbedding()
+ gqa = StreamingMultiheadAttention(64, 4, rope, attn_dim=32, num_kv_heads=2)
+ mha = StreamingMultiheadAttention(64, 4, rope, attn_dim=32)
+ q, k, v = gqa.in_proj.weight.detach().split([32, 16, 16])
+
+ def repeat_heads(w: torch.Tensor) -> torch.Tensor:
+ return w.view(2, 8, 64).repeat_interleave(2, dim=0).reshape(32, 64)
+
+ mha.in_proj.weight.data = torch.cat([q, repeat_heads(k), repeat_heads(v)])
+ mha.out_proj.weight.data = gqa.out_proj.weight.data
+ x = torch.randn(1, 5, 64)
+ torch.testing.assert_close(gqa(x, None), mha(x, None))
+
+
+def test_attn_dim_and_kv_heads_in_the_flow_lm():
+ flow_lm = build_flow_lm(**{"transformer.attn_dim": 32, "transformer.num_kv_heads": 2})
+ weights = flow_lm.state_dict()
+ assert weights["transformer.layers.0.self_attn.in_proj.weight"].shape == (32 + 2 * 16, 64)
+ assert weights["transformer.layers.0.self_attn.out_proj.weight"].shape == (64, 32)
+ state = init_states(flow_lm, batch_size=1, sequence_length=8)
+ assert state["transformer.layers.0.self_attn"]["cache"].shape == (2, 1, 8, 2, 8)
+ assert sample_latents(flow_lm).isfinite().all()
+
+
+def test_low_rank_text_table():
+ flow_lm = build_flow_lm(**{"lookup_table.rank": 8})
+ conditioner = flow_lm.conditioner
+ assert conditioner.embed.weight.shape == (4001, 8)
+ assert conditioner.proj is not None and conditioner.proj.weight.shape == (64, 8)
+ tokens = conditioner.prepare("Hello world.")
+ expected = conditioner.embed.weight[tokens] @ conditioner.proj.weight.T
+ torch.testing.assert_close(conditioner(tokens), expected)
+ assert sample_latents(flow_lm).isfinite().all()
+
+
+def test_mimi_decoder_with_its_own_dims(tmp_path: Path):
+ config = load_config(CONFIGS_DIR / "english.yaml").mimi
+ small = config.model_copy(
+ update={
+ "outer_dim": 64,
+ "quantizer": config.quantizer.model_copy(update={"output_dimension": 64}),
+ "decoder_seanet": config.seanet.model_copy(
+ update={"dimension": 64, "n_filters": 8, "kernel_size": 3}
+ ),
+ "decoder_transformer": config.transformer.model_copy(
+ update={
+ "d_model": 64,
+ "num_heads": 4,
+ "num_layers": 1,
+ "dim_feedforward": 128,
+ "input_dimension": 64,
+ "output_dimensions": (64,),
+ }
+ ),
+ }
+ )
+ mimi = stamp(build_mimi(small)).eval()
+ assert mimi.decoder.dimension == 64 and mimi.encoder.dimension == 512
+ latents = torch.randn(1, 3, config.quantizer.dimension)
+ audio = mimi.decode_from_latent(latents, init_states(mimi, 1, 100))
+ assert audio.shape == (1, 1, 3 * mimi.frame_size)
+
+ # A Mimi in this package's layout loads as mimi.weights_path.
+ path = tmp_path / "mimi.safetensors"
+ safetensors.torch.save_file({f"mimi.{k}": v for k, v in mimi.state_dict().items()}, path)
+ build_mimi(small).load_state_dict(get_mimi_state_dict(path), strict=True)
+
+
+def test_explicit_feed_forward_width():
+ flow_lm = build_flow_lm(**{"transformer.dim_feedforward": 48})
+ weights = flow_lm.state_dict()
+ assert weights["transformer.layers.0.linear1.weight"].shape == (48, 64)
+ assert weights["transformer.layers.0.linear2.weight"].shape == (64, 48)
+ default = build_flow_lm().state_dict()["transformer.layers.0.linear1.weight"]
+ assert default.shape == (64 * 4, 64) # d_model * hidden_scale
+ assert sample_latents(flow_lm).isfinite().all()
+
+
+def test_pointwise_head_is_lsd_one_step_without_time_conditions():
+ pointwise = build_flow_lm(**{"flow.type": "pointwise"})
+ assert pointwise.flow_net.num_time_conds == 0
+ # The same head as an LSD head whose time embeddings are zero: one LSD step is then
+ # the noise plus the head's output for it.
+ lsd = build_flow_lm()
+ state = lsd.state_dict()
+ for k, v in state.items():
+ if k.startswith("flow_net.time_embed.") and not k.endswith("freqs"):
+ v.zero_()
+ lsd.load_state_dict({**state, **pointwise.state_dict()}, strict=True)
+ assert torch.equal(sample_latents(pointwise), sample_latents(lsd))
diff --git a/tests/test_utils.py b/tests/test_utils.py
index c7c8904..81ea210 100644
--- a/tests/test_utils.py
+++ b/tests/test_utils.py
@@ -33,3 +33,27 @@ def test_shipped_configs_sample_at_the_tuned_temperature(config_path: Path):
from pocket_tts.utils.config import load_config
assert load_config(config_path).default_temperature == 0.3
+
+
+def test_eos_threshold_defaults_to_the_config(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
+ """load_model takes the EOS threshold from the config unless the caller passes one."""
+ import yaml
+
+ from pocket_tts import TTSModel
+ from pocket_tts.default_parameters import DEFAULT_EOS_THRESHOLD
+
+ config = Path(__file__).parent.parent / "pocket_tts" / "config" / "english.yaml"
+ custom = tmp_path / "custom.yaml"
+ custom.write_text(
+ yaml.safe_dump({**yaml.safe_load(config.read_text()), "default_eos_threshold": -1.0})
+ )
+ seen = []
+ monkeypatch.setattr(
+ TTSModel,
+ "_from_pydantic_config_with_weights",
+ classmethod(lambda cls, cfg, temp, steps, clamp, eos, origin: seen.append(eos)),
+ )
+ TTSModel.load_model(config=config)
+ TTSModel.load_model(config=custom)
+ TTSModel.load_model(config=custom, eos_threshold=-2.0)
+ assert seen == [DEFAULT_EOS_THRESHOLD, -1.0, -2.0]
diff --git a/training/args.py b/training/args.py
index 3a44e92..53bf0b7 100644
--- a/training/args.py
+++ b/training/args.py
@@ -81,11 +81,37 @@ class OptimArgs:
muon_polar_steps: int = 6
+@dataclass
+class ReflArgs:
+ """Reward fine-tuning (training/refl.py). Each step rolls out up to `rows` rows of the batch
+ without gradients, re-runs the backbone teacher-forced on the rollout with gradients,
+ re-applies the sampler head on the rollout's own noise, decodes with the frozen Mimi decoder
+ and backpropagates the rewards. The batch's usual loss (the distillation loss in a
+ distillation run) stays on as the anchor on the real rows. Needs the `utmos-pytorch`,
+ `transformers` and `torchaudio` packages (the dev dependency group)."""
+
+ enabled: bool = False
+ rows: int = 4 # rolled-out rows per GPU; only rows whose text the CTC model can score
+ temp: float = 0.3
+ max_sec: float = 20.0 # rollouts that emit no EOS by then get no reward
+ utmos_weight: float = 0.0 # loss -= utmos_weight * mean UTMOS
+ ctc_weight: float = 0.0 # loss += ctc_weight * mean per-character CTC loss of the text
+ ctc_model: str = "facebook/wav2vec2-large-960h-lv60-self" # a character-level wav2vec2 CTC
+ # A pocket-tts model config whose Mimi decodes the rollouts for the rewards instead of
+ # model_config's (e.g. one with its own decoder dims and mimi.weights_path). It must read
+ # the same latents; only the audio the rewards score changes.
+ reward_decoder: str = ""
+ # Random leading trim (samples) before scoring, so that a perturbation tuned to one
+ # alignment of the scorers does not pay.
+ max_shift: int = 480
+
+
@dataclass
class TrainArgs:
data: DataArgs = field(default_factory=DataArgs)
flow: FlowArgs = field(default_factory=FlowArgs)
optim: OptimArgs = field(default_factory=OptimArgs)
+ refl: ReflArgs = field(default_factory=ReflArgs)
# A pocket-tts model config (e.g. pocket_tts/config/english.yaml or a local
# variant). Defines the FlowLM/Mimi architecture, the tokenizer, and the
@@ -160,7 +186,9 @@ class TrainArgs:
# Depth distillation: point these at a bigger trained model and the student
# (built from `model_config`, typically fewer layers) learns to reproduce its
# backbone activations. Leave empty to distill a frozen copy of the student's
- # own architecture (guidance baking only).
+ # own architecture (guidance baking only). A narrower student (d_model, attention,
+ # FFN, text table) is seeded from the teacher by shrink_checkpoint.shrink_width; it must
+ # share the teacher's z width (flow_lm.z_dim), so the frozen heads read the same space.
distill_teacher_config: str = ""
distill_teacher_overrides: dict[str, tp.Any] = field(default_factory=dict)
distill_teacher_weights: str = ""
@@ -169,8 +197,29 @@ class TrainArgs:
distill_teacher_use_ema: bool = True
# Warm-start the student's backbone and conditioning from these weights (a training
# checkpoint, or a released model.safetensors, local or hf://) instead of the
- # teacher's bottom+top layers; the per-frame heads still come from the teacher.
+ # teacher's bottom+top layers; the per-frame heads still come from the teacher. A
+ # wider source is narrowed like the teacher (shrink_checkpoint.shrink_width).
student_init_from: str = ""
+ # Seed from student_init_from's (and head_init_from's) EMA shadow instead of its raw
+ # weights (raw weights when the checkpoint carries no EMA).
+ init_from_use_ema: bool = True
+
+ # Head distillation: train a new sampler head (flow_net, shaped by the config's flow_lm.flow,
+ # any flow.type) against a frozen one, on the frozen backbone's outputs; nothing else
+ # trains. The backbone and the frozen head come from head_distill_from (a training
+ # checkpoint or a model.safetensors), or from the config's weights when it is empty; the
+ # frozen head's shape and type (0, 1 or 2 time conditions) are read from its weights.
+ # head_distill_loss picks the objective, whatever the head types: "mse" regresses the new
+ # head's one-step output on the frozen head's for the same noise; "drifting" (needs
+ # flow.type drifting) attracts the new head to head_distill_samples draws of the frozen
+ # head per position. Noise is drawn at temperature head_distill_temp.
+ head_distill: bool = False
+ head_distill_from: str = ""
+ head_distill_loss: str = "mse"
+ head_distill_samples: int = 1
+ head_distill_temp: float = 1.0
+ # Start the new head from this checkpoint's flow_net (same shape) instead of a fresh one.
+ head_init_from: str = ""
# Which teacher layers seed the student backbone: "spaced" (evenly across
# the depth) or "first" (the bottom N). No evidence either way -- "first"
# keeps the early feature extractors contiguous.
@@ -193,12 +242,22 @@ class TrainArgs:
"distillation needs a teacher: set distill_teacher_config, or "
"start_from_pretrained: true to distil a frozen copy of the model itself"
)
+ if self.head_distill and self.distill_cfg_coef > 0:
+ raise ValueError("head_distill and distill_cfg_coef are separate runs: set one")
+ if self.head_distill_loss not in ("mse", "drifting"):
+ raise ValueError(
+ f"head_distill_loss must be mse or drifting, not {self.head_distill_loss}"
+ )
if self.distill_teacher_config and not self.distill_teacher_weights:
raise ValueError("distill_teacher_config is set but distill_teacher_weights is not")
+ if self.refl.enabled and self.head_distill:
+ raise ValueError("refl and head_distill are separate runs: set one")
+ if self.refl.enabled and not (self.refl.utmos_weight > 0 or self.refl.ctc_weight > 0):
+ raise ValueError("refl.enabled needs refl.utmos_weight or refl.ctc_weight > 0")
def _from_dict(cls: type[T], data: dict[str, Any]) -> T:
- sub = {"data": DataArgs, "flow": FlowArgs, "optim": OptimArgs}
+ sub = {"data": DataArgs, "flow": FlowArgs, "optim": OptimArgs, "refl": ReflArgs}
kwargs = {}
fields = {f.name: f for f in dataclasses.fields(cls)}
for key, value in data.items():
diff --git a/training/distributed.py b/training/distributed.py
index d6fe871..2d2185c 100644
--- a/training/distributed.py
+++ b/training/distributed.py
@@ -65,3 +65,13 @@ def avg_across_ranks(value: float) -> float:
t = torch.tensor(value, device="cuda")
dist.all_reduce(t, op=dist.ReduceOp.AVG)
return t.item()
+
+
+def average_grads(params: list[torch.nn.Parameter]):
+ """Mean of the gradients across ranks (missing gradients count as zeros), in one all_reduce."""
+ flat = torch.cat(
+ [(p.grad if p.grad is not None else torch.zeros_like(p)).flatten() for p in params]
+ )
+ dist.all_reduce(flat, op=dist.ReduceOp.AVG)
+ for p, g in zip(params, flat.split([p.numel() for p in params]), strict=True):
+ p.grad = g.view_as(p)
diff --git a/training/modules/builders.py b/training/modules/builders.py
index 1ec2658..386eeea 100644
--- a/training/modules/builders.py
+++ b/training/modules/builders.py
@@ -20,9 +20,9 @@ from pocket_tts.utils.config import Config, load_config
from pocket_tts.utils.utils import download_if_necessary
from ..args import TrainArgs
-from ..scripts.shrink_checkpoint import shrink
+from ..scripts.shrink_checkpoint import shrink, shrink_width
from .model import TrainableTTS
-from .samplers import build_flow
+from .samplers import Drifting, build_flow
from .utils import disable_grad, dit_init, gaussian_init, stamp_state_names
logger = logging.getLogger(__name__)
@@ -45,8 +45,8 @@ def load_model_config(path: str, overrides: dict[str, tp.Any]) -> Config:
if key not in node:
raise KeyError(f"{path} has no section {key!r} (from override {dotted!r})")
node = node[key]
- if leaf not in node:
- raise KeyError(f"{path} has no field {dotted!r} to override")
+ # A field the yaml leaves at its default (e.g. flow_lm.z_dim) can be set too: the
+ # config model still rejects names it does not define.
node[leaf] = value
return Config(**raw)
@@ -84,25 +84,17 @@ def attach_distillation(model: TrainableTTS, flow_lm: FlowLMModel, args: TrainAr
teacher = teacher.eval()
# Seed the student from the teacher: non-backbone tensors verbatim,
# backbone from the teacher's bottom+top layers — far faster to
- # converge than a random init.
+ # converge than a random init. A narrower student gets the teacher's
+ # strongest channels, heads and FFN units.
seeded, kept = shrink(teacher.state_dict(), len(flow_lm.transformer.layers))
student_state = flow_lm.state_dict()
- copied = {
- k: v
- for k, v in seeded.items()
- if k in student_state and student_state[k].shape == v.shape
- }
+ transformer = load_model_config(args.model_config, args.model_overrides).flow_lm.transformer
+ head_dim = (transformer.attn_dim or transformer.d_model) // transformer.num_heads
+ copied = shrink_width(seeded, student_state, head_dim)
if args.student_init_from:
- src = _load_flow_lm_state(args.student_init_from, use_ema=False)
- copied.update(
- {
- k: v
- for k, v in src.items()
- if not k.startswith(("flow_net.", "out_eos."))
- and k in student_state
- and student_state[k].shape == v.shape
- }
- )
+ src = _load_flow_lm_state(args.student_init_from, args.init_from_use_ema)
+ src = {k: v for k, v in src.items() if not k.startswith(("flow_net.", "out_eos."))}
+ copied.update(shrink_width(src, student_state, head_dim))
logger.info(f"student backbone seeded from {args.student_init_from}")
flow_lm.load_state_dict(copied, strict=False)
logger.info(
@@ -124,6 +116,11 @@ def attach_distillation(model: TrainableTTS, flow_lm: FlowLMModel, args: TrainAr
# the teacher's weights so single-pass generation stays calibrated.
disable_grad(flow_lm.flow_net)
disable_grad(flow_lm.out_eos)
+ if flow_lm.out_eos.in_features != teacher.out_eos.in_features:
+ raise ValueError(
+ "distillation needs the student's heads to read the teacher's width: give both the "
+ f"same z_dim (student {flow_lm.out_eos.in_features}, teacher {teacher.out_eos.in_features})"
+ )
# The flow objective (e.g. LSD's w_s_t weighting net) never runs in
# distill mode; freeze its params so DDP with
# find_unused_parameters=False sees no grad-less trainables.
@@ -166,13 +163,14 @@ def build_models(args: TrainArgs) -> tuple[TrainableTTS, MimiModel, Config]:
latent_dim,
config.flow_lm.flow.dim,
latent_dim,
- d_model,
+ config.flow_lm.z_dim or d_model, # the head reads the backbone output z
config.flow_lm.flow.depth,
flow.num_time_conds,
)
mimi = build_mimi(config.mimi)
state = None
+ head_state: dict[str, torch.Tensor] = {}
if config.weights_path is not None:
weights_file = download_if_necessary(str(config.weights_path))
state = safetensors.torch.load_file(weights_file)
@@ -183,7 +181,21 @@ def build_models(args: TrainArgs) -> tuple[TrainableTTS, MimiModel, Config]:
"model_config must define weights_path (used at least for the Mimi codec weights)."
)
- if args.start_from_pretrained:
+ if args.head_distill:
+ source = args.head_distill_from or str(config.weights_path)
+ flow_state = _load_flow_lm_state(source, args.init_from_use_ema)
+ head_state = {
+ k.removeprefix("flow_net."): v
+ for k, v in flow_state.items()
+ if k.startswith("flow_net.")
+ }
+ backbone = {k: v for k, v in flow_state.items() if not k.startswith("flow_net.")}
+ missing, unexpected = flow_lm.load_state_dict(backbone, strict=False)
+ assert not unexpected, unexpected
+ assert all(k.startswith("flow_net.") for k in missing), missing
+ dit_init(flow_lm.flow_net)
+ logger.info(f"head distillation: backbone and frozen head from {source}")
+ elif args.start_from_pretrained:
flow_state = {
k.removeprefix("flow_lm."): v for k, v in state.items() if k.startswith("flow_lm.")
}
@@ -219,4 +231,41 @@ def build_models(args: TrainArgs) -> tuple[TrainableTTS, MimiModel, Config]:
model = TrainableTTS(flow_lm, flow, args)
if args.distill_cfg_coef > 0:
attach_distillation(model, flow_lm, args)
+ if args.head_distill:
+ attach_head_distillation(model, head_state, args)
return model, mimi, config
+
+
+def head_from_state(state: dict[str, torch.Tensor]) -> SimpleMLPAdaLN:
+ """A sampler head built to the shape of its weights (flow_net.* without the prefix)."""
+ channels, cond_dim = state["cond_embed.weight"].shape
+ latent_dim = state["input_proj.weight"].shape[1]
+ depth = len({k.split(".")[1] for k in state if k.startswith("res_blocks.")})
+ time_conds = len({k.split(".")[1] for k in state if k.startswith("time_embed.")})
+ head = SimpleMLPAdaLN(latent_dim, channels, latent_dim, cond_dim, depth, time_conds)
+ head.load_state_dict(state, strict=True)
+ return head
+
+
+def attach_head_distillation(
+ model: TrainableTTS, head_state: dict[str, torch.Tensor], args: TrainArgs
+):
+ """Give `model` the frozen head to learn from, and freeze everything but the new head
+ (and the objective's own parameters, e.g. a learned drifting temperature)."""
+ teacher = head_from_state(head_state).eval()
+ disable_grad(teacher)
+ # Kept out of the submodule registry, like the distillation teacher.
+ model.__dict__["head_teacher"] = teacher
+ disable_grad(model.flow_lm)
+ model.flow_lm.flow_net.requires_grad_(True)
+ if not isinstance(model.flow, Drifting):
+ disable_grad(model.flow) # only the drifting loss runs the objective's own parameters
+ if args.head_init_from:
+ state = _load_flow_lm_state(args.head_init_from, args.init_from_use_ema)
+ model.flow_lm.flow_net.load_state_dict(
+ {k.removeprefix("flow_net."): v for k, v in state.items() if k.startswith("flow_net.")}
+ )
+ logger.info(f"new head initialized from {args.head_init_from}")
+ n_new = sum(p.numel() for p in model.flow_lm.flow_net.parameters())
+ n_frozen = sum(p.numel() for p in teacher.parameters())
+ logger.info(f"head distillation: {n_new / 1e6:.2f}M params <- {n_frozen / 1e6:.2f}M frozen")
diff --git a/training/modules/model.py b/training/modules/model.py
index 97a1ca4..0a96553 100644
--- a/training/modules/model.py
+++ b/training/modules/model.py
@@ -16,12 +16,13 @@ import torch
import torch.nn.functional as F
from torch import nn
-from pocket_tts.models.flow_lm import FlowLMModel
+from pocket_tts.models.flow_lm import FlowLMModel, drifting_decode, lsd_decode, ot_decode
+from pocket_tts.modules.mlp import SimpleMLPAdaLN
from pocket_tts.modules.stateful_module import ModelState, increment_steps, init_states
from ..args import TrainArgs
from .conditioner import build_sequences_with_conditions
-from .samplers import FlowType
+from .samplers import Drifting, FlowType
from .utils import set_state_padding, stamp_state_names
@@ -29,6 +30,8 @@ class TrainableTTS(nn.Module):
# Frozen teacher for distillation runs, kept out of the submodule registry
# (see build_models); None otherwise.
distill_teacher: FlowLMModel | None
+ # Frozen sampler head for head distillation (see build_models); None otherwise.
+ head_teacher: SimpleMLPAdaLN | None
def __init__(self, flow_lm: FlowLMModel, flow: FlowType, args: TrainArgs):
super().__init__()
@@ -36,6 +39,7 @@ class TrainableTTS(nn.Module):
self.flow = flow
self.args = args
self.__dict__["distill_teacher"] = None # set by build_models; not a submodule
+ self.__dict__["head_teacher"] = None
stamp_state_names(self.flow_lm)
@property
@@ -50,6 +54,34 @@ class TrainableTTS(nn.Module):
fl.emb_mean.mul_(gamma).add_(sel.mean(dim=0), alpha=1 - gamma)
fl.emb_std.mul_(gamma).add_(sel.std(dim=0), alpha=1 - gamma)
+ def backbone_z(
+ self,
+ module: FlowLMModel,
+ normalized_latents: torch.Tensor, # [B, T, C]
+ text_tokens: list[torch.Tensor],
+ voice_latents: torch.Tensor,
+ num_voice_prompt_frames: torch.Tensor | None,
+ cfg_dropout: bool,
+ force_null: bool = False,
+ ) -> torch.Tensor:
+ """Teacher-forced backbone output [B, T, dim]: z[:, t] conditions the heads for frame t."""
+ x, prefix_lengths = build_sequences_with_conditions(
+ self.args,
+ normalized_latents,
+ text_tokens,
+ voice_latents,
+ cfg_dropout=cfg_dropout,
+ num_voice_prompt_frames=num_voice_prompt_frames,
+ fl=module,
+ force_null=force_null,
+ )
+ out = module.out_norm(module.transformer(x, model_state=None))
+ if module.z_proj is not None:
+ out = module.z_proj(out)
+ T = normalized_latents.shape[1]
+ idx = prefix_lengths[:, None] + torch.arange(T, device=out.device)[None, :]
+ return out.gather(1, idx[:, :, None].expand(-1, -1, out.shape[-1]))
+
def forward(
self,
latents: torch.Tensor, # [B, T, C] raw codec latents
@@ -61,41 +93,36 @@ class TrainableTTS(nn.Module):
| None = None, # [B] valid voice frames (rest is padding)
) -> tuple[torch.Tensor, dict[str, torch.Tensor]]:
fl = self.flow_lm
- _, T, C = latents.shape
+ C = latents.shape[-1]
if update_stats and self.training:
self._update_latent_stats(latents, mask)
normalized_latents = (latents - fl.emb_mean) / fl.emb_std
- def backbone_z(
- module: FlowLMModel, cfg_dropout: bool, force_null: bool = False
- ) -> torch.Tensor:
- x, prefix_lengths = build_sequences_with_conditions(
- self.args,
- normalized_latents,
- text_tokens,
- voice_latents,
- cfg_dropout=cfg_dropout,
- num_voice_prompt_frames=num_voice_prompt_frames,
- fl=module,
- force_null=force_null,
- )
- out = module.out_norm(module.transformer(x, model_state=None))
- idx = prefix_lengths[:, None] + torch.arange(T, device=out.device)[None, :]
- return out.gather(1, idx[:, :, None].expand(-1, -1, out.shape[-1]))
-
- z = backbone_z(fl, cfg_dropout=self.training) # [B, T, dim]
+ inputs = (normalized_latents, text_tokens, voice_latents, num_voice_prompt_frames)
+
+ if self.head_teacher is not None:
+ with torch.no_grad():
+ z = self.backbone_z(fl, *inputs, cfg_dropout=False)
+ return self._head_distill(z[mask])
+
+ z = self.backbone_z(fl, *inputs, cfg_dropout=self.training) # [B, T, dim]
if self.distill_teacher is not None:
# Latent CFG distillation: the student's backbone regresses onto the
# teacher's guidance-combined output; flow/EOS heads stay frozen.
teacher = self.distill_teacher.to(latents.device)
with torch.no_grad():
- z_cond = backbone_z(teacher, cfg_dropout=False)
- z_null = backbone_z(teacher, cfg_dropout=False, force_null=True)
- z_t = z_null + self.args.distill_cfg_coef * (z_cond - z_null)
+ z_t = self.backbone_z(teacher, *inputs, cfg_dropout=False)
+ if self.args.distill_cfg_coef != 1.0:
+ z_null = self.backbone_z(teacher, *inputs, cfg_dropout=False, force_null=True)
+ z_t = z_null + self.args.distill_cfg_coef * (z_t - z_null)
shifted_mask = torch.cat([mask[:, :1], mask[:, :-1]], dim=1)
denom = shifted_mask.sum().clamp(min=1)
- loss = ((z - z_t).square().mean(dim=-1) * shifted_mask).sum() / denom
+
+ def mse(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
+ return ((x - y).square().mean(dim=-1) * shifted_mask).sum() / denom
+
+ loss = mse(z, z_t)
return loss, {"distill_mse": loss.detach(), "loss": loss.detach()}
# EOS loss: 1 on the first invalid position, computed over valid
@@ -132,6 +159,40 @@ class TrainableTTS(nn.Module):
metrics.update(flow_loss=flow_loss.detach(), eos_loss=eos_loss.detach(), loss=loss.detach())
return loss, metrics
+ def _head_distill(self, z: torch.Tensor) -> tuple[torch.Tensor, dict[str, torch.Tensor]]:
+ """The new head (flow_lm.flow_net) learns the frozen head's samples for the backbone
+ outputs `z` [N, dim] of the valid frames."""
+ fl, args = self.flow_lm, self.args
+ teacher = self.head_teacher
+ assert teacher is not None
+ teacher = teacher.to(z.device) # outside the module tree, so not moved with the model
+ decode = {0: drifting_decode, 1: ot_decode, 2: lsd_decode}[teacher.num_time_conds]
+ std = args.head_distill_temp**0.5
+ drifting = args.head_distill_loss == "drifting"
+ assert not drifting or isinstance(self.flow, Drifting), (
+ "head_distill_loss drifting needs flow.type drifting"
+ )
+ k = args.head_distill_samples if drifting else 1
+ with torch.no_grad():
+ noise = std * torch.randn(k, z.shape[0], fl.ldim, device=z.device, dtype=z.dtype)
+ z_k = z.expand(k, -1, -1).reshape(-1, z.shape[-1])
+ target = decode(partial(teacher, z_k), noise.reshape(-1, fl.ldim))
+ target = target.reshape(k, z.shape[0], -1).transpose(0, 1) # [N, k, D]
+ if drifting:
+ with torch.autocast(device_type=z.device.type, enabled=False):
+ loss, metrics, _ = self.flow.loss(
+ partial(fl.flow_net, z.float()), noise[0].float(), target.float()
+ )
+ loss = loss.mean()
+ else:
+ # The one-step map on the same noise draw.
+ sample = self.flow.decode(partial(fl.flow_net, z), noise[0], 1)
+ loss = (sample - target[:, 0]).square().mean()
+ metrics = {}
+ metrics = {k: v.detach() if torch.is_tensor(v) else v for k, v in metrics.items()}
+ metrics.update(head_loss=loss.detach(), loss=loss.detach())
+ return loss, metrics
+
@torch.no_grad()
def generate(
self,
@@ -143,6 +204,7 @@ class TrainableTTS(nn.Module):
cfg_coef: float = 1.0,
eos_threshold: float = -1.0,
eos_countdown: int = 1,
+ noises: list[torch.Tensor] | None = None, # if given, collects each step's [B, C] noise
) -> list[torch.Tensor]:
"""Sample a batch of utterances with arbitrary prefix lengths.
@@ -191,6 +253,8 @@ class TrainableTTS(nn.Module):
if first_step:
inp = torch.cat([prefixes[i], inp], dim=1)
out = fl.out_norm(fl.transformer(inp, st))
+ if fl.z_proj is not None:
+ out = fl.z_proj(out)
increment_steps(fl, st, increment=inp.shape[1])
zs.append(out[:, -1].float())
first_step = False
@@ -203,6 +267,8 @@ class TrainableTTS(nn.Module):
for t in range(max_frames):
z = run(x_lat)
noise = temp**0.5 * torch.randn(B, self.ldim, device=device, dtype=z.dtype)
+ if noises is not None:
+ noises.append(noise)
latent = self.flow.decode(partial(fl.flow_net, z), noise, n_steps)
fired = (fl.out_eos(z).squeeze(-1) > eos_threshold) & (countdown < 0)
countdown = torch.where(fired, torch.full_like(countdown, eos_countdown), countdown)
diff --git a/training/modules/samplers.py b/training/modules/samplers.py
index 70de6e8..0fb4f85 100644
--- a/training/modules/samplers.py
+++ b/training/modules/samplers.py
@@ -194,6 +194,9 @@ class Drifting(FlowType):
learned by maximizing the data sample's share of the kernel mass; with 0 it
stays fixed (at `temp`, or at the learned value when resuming a run that
learned it).
+
+ The target may be several samples per position (e.g. draws from another head),
+ which attract together as one data cloud.
"""
num_time_conds = 0
@@ -227,11 +230,13 @@ class Drifting(FlowType):
y_neg: torch.Tensor,
temp: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
- logit = -dists / temp # [N, num_neg, 1 + num_neg]: each generation vs data + generations
- # Log-mass of the data sample relative to a flat kernel (0 = chance).
- pos_log_mass = logit.log_softmax(dim=-1)[..., 0] + math.log(self.num_neg)
+ k = y_pos.shape[1]
+ logit = -dists / temp # [N, num_neg, k + num_neg]: each generation vs data + generations
+ # Log-mass of the data samples relative to a flat kernel (0 = chance).
+ log_mass = logit.log_softmax(dim=-1)[..., :k].logsumexp(dim=-1)
+ pos_log_mass = log_mass + math.log(self.num_neg / k)
A = (logit.softmax(dim=-1) * logit.softmax(dim=-2)).clamp(min=1e-6).sqrt().detach()
- A_pos, A_neg = A[..., :1], A[..., 1:]
+ A_pos, A_neg = A[..., :k], A[..., k:]
W_pos = A_pos * A_neg.sum(dim=-1, keepdim=True)
W_neg = A_neg * A_pos.sum(dim=-1, keepdim=True)
force = W_pos @ y_pos - W_neg @ y_neg
@@ -249,15 +254,17 @@ class Drifting(FlowType):
e = torch.randn(self.num_neg, *x_0.shape, device=x_0.device, dtype=x_0.dtype)
x = torch.vmap(v_t, out_dims=1)(e) # [N, num_neg, D]
y_neg = x.detach()
- y_pos = x_1[:, None] # [N, 1, D]
+ # x_1 is [N, D], or [N, k, D] for k samples of the target per position.
+ y_pos = x_1 if x_1.dim() == 3 else x_1[:, None]
+ k = y_pos.shape[1]
with torch.no_grad():
dists = torch.cat([cdist(y_neg, y_pos), cdist(y_neg, y_neg)], dim=-1)
- n = self.num_neg + 1
+ n = self.num_neg + k
scale = (dists * n / (n - 1)).mean(dim=(-1, -2), keepdim=True).clamp(min=self.min_scale)
# A generation never attracts or repels itself.
self_mask = torch.eye(self.num_neg, device=x.device) * 100.0
dists = dists / scale + torch.cat(
- [torch.zeros_like(dists[..., :1]), self_mask.expand_as(dists[..., 1:])], dim=-1
+ [torch.zeros_like(dists[..., :k]), self_mask.expand_as(dists[..., k:])], dim=-1
)
scale_input = scale / x.shape[-1] ** 0.5
x, y_pos, y_neg = (z / scale_input for z in (x, y_pos, y_neg))
diff --git a/training/refl.py b/training/refl.py
new file mode 100644
index 0000000..bae85b1
--- /dev/null
+++ b/training/refl.py
@@ -0,0 +1,170 @@
+"""Reward fine-tuning (ReFL / DRaFT style): differentiable rewards through the sampler head and
+the Mimi decoder.
+
+The model is rolled out without gradients. The generated frames are then the teacher-forced
+context of one backbone pass with gradients, the sampler head is re-applied on the rollout's own
+noise (its output is the rollout itself, now differentiable), the frozen Mimi decoder turns it
+into audio, and the rewards are backpropagated: UTMOS, and the CTC log-likelihood of the text
+under a frozen character-level ASR.
+
+Only rows whose text the ASR can score are rolled out: it cannot score digits or symbols, whose
+spoken form is unknown.
+"""
+
+import random
+import re
+from collections.abc import Callable
+from functools import partial
+from pathlib import Path
+
+import torch
+import torch.nn.functional as F
+
+from pocket_tts.models.mimi import MimiModel, build_mimi
+from pocket_tts.modules.stateful_module import init_states
+from pocket_tts.utils.config import load_config
+from pocket_tts.utils.utils import download_if_necessary
+from pocket_tts.utils.weights_loading import get_mimi_state_dict
+from training.args import ReflArgs
+from training.eval.librispeech import MIN_FRAMES
+from training.modules.model import TrainableTTS
+from training.modules.utils import disable_grad, stamp_state_names
+
+UNSCORABLE = re.compile(r"[\d@/_#%$&+=*<>\\|~^]")
+
+
+class Rewards:
+ """The frozen scorers, and the Mimi that decodes the rollouts for them."""
+
+ def __init__(self, ra: ReflArgs, device: torch.device, mimi: MimiModel):
+ try:
+ import torchaudio
+ from transformers import Wav2Vec2CTCTokenizer, Wav2Vec2ForCTC
+ from utmos_pytorch import UTMOSScoreTorch
+ except ImportError as e:
+ raise ImportError(
+ f"refl needs utmos-pytorch, transformers and torchaudio ({e}); they are in the "
+ "dev dependency group: uv sync"
+ ) from e
+
+ self.mimi = mimi
+ if ra.reward_decoder:
+ config = load_config(Path(ra.reward_decoder))
+ weights = config.mimi.weights_path or config.weights_path
+ assert weights, f"{ra.reward_decoder} names no Mimi weights"
+ self.mimi = build_mimi(config.mimi)
+ self.mimi.load_state_dict(get_mimi_state_dict(download_if_necessary(weights)))
+ self.mimi.to(device).eval()
+ stamp_state_names(self.mimi)
+ disable_grad(self.mimi)
+ self.resample = partial(
+ torchaudio.functional.resample, orig_freq=self.mimi.sample_rate, new_freq=16000
+ )
+ self.utmos = UTMOSScoreTorch(device=str(device)).model
+ self.ctc = Wav2Vec2ForCTC.from_pretrained(ra.ctc_model).to(device).eval() # ty: ignore[invalid-argument-type]
+ disable_grad(self.utmos)
+ disable_grad(self.ctc)
+ # cuDNN's RNN backward refuses eval mode; the single-layer LSTM has no dropout.
+ for m in self.utmos.modules():
+ if isinstance(m, torch.nn.LSTM):
+ m.train()
+ self.vocab = Wav2Vec2CTCTokenizer.from_pretrained(ra.ctc_model).get_vocab()
+ self.blank = self.ctc.config.pad_token_id
+
+ def utmos_score(self, wav16: torch.Tensor) -> torch.Tensor:
+ x = wav16[None, None]
+ one = torch.ones(1, dtype=torch.int, device=x.device)
+ return self.utmos(x, domains=0 * one, judge_id=288 * one).mean() * 2 + 3
+
+ def ctc_targets(self, text: str) -> list[int] | None:
+ """Character targets; None when the text has digits or symbols."""
+ if UNSCORABLE.search(text):
+ return None
+ t = re.sub(r"[^A-Z']+", " ", text.upper().replace("’", "'")).strip()
+ return [self.vocab["|" if c == " " else c] for c in t] or None
+
+ def ctc_loss(self, wav16: torch.Tensor, tgt: list[int]) -> torch.Tensor:
+ """Per-character CTC negative log-likelihood of the target text."""
+ x = (wav16 - wav16.mean()) / torch.sqrt(wav16.var() + 1e-7)
+ logp = self.ctc(x[None]).logits.float().log_softmax(-1)[0]
+ return F.ctc_loss(
+ logp[:, None],
+ torch.tensor(tgt, device=logp.device)[None],
+ torch.tensor([logp.shape[0]]),
+ torch.tensor([len(tgt)]),
+ blank=self.blank,
+ reduction="sum",
+ zero_infinity=True,
+ ) / len(tgt)
+
+
+def refl_loss(
+ model: TrainableTTS,
+ decode_text: Callable[[list[int]], str],
+ text_tokens: list[torch.Tensor],
+ voice: torch.Tensor, # [B, Tv, C] voice prompt latents
+ num_voice_prompt_frames: torch.Tensor, # [B]
+ mask: torch.Tensor, # [B, T] the real rows' valid frames
+ rewards: Rewards,
+ ra: ReflArgs,
+) -> tuple[torch.Tensor | None, dict[str, torch.Tensor]]:
+ """Roll out up to ra.rows scorable rows; return (weighted reward loss or None, stats)."""
+ fl, mimi = model.flow_lm, rewards.mimi
+ device = voice.device
+ targets = [rewards.ctc_targets(decode_text(t.tolist())) for t in text_tokens]
+ scorable = [(b, t) for b, t in enumerate(targets) if t is not None][: ra.rows]
+ rows = [b for b, _ in scorable]
+ stats = {"refl_rows": torch.tensor(float(len(rows)))}
+ if not rows:
+ return None, stats
+ R = len(rows)
+ toks = [text_tokens[b] for b in rows]
+ voice, nvf = voice[rows], num_voice_prompt_frames[rows]
+ max_frames = int(ra.max_sec * mimi.frame_rate)
+ noises: list[torch.Tensor] = []
+ outs = model.generate(
+ toks,
+ [voice[b, : int(nvf[b])] for b in range(R)],
+ max_frames=max_frames,
+ temp=ra.temp,
+ noises=noises,
+ )
+ lens = [o.shape[0] for o in outs]
+ ok = [MIN_FRAMES <= n < max_frames for n in lens]
+ gen = torch.tensor(lens, device=device, dtype=torch.float)
+ stats["refl_ok"] = torch.tensor(sum(ok) / R) # rows that emitted EOS in time
+ stats["refl_len_ratio"] = (gen / mask[rows].sum(1)).mean() # rollout / real utterance length
+ if not any(ok):
+ return None, stats
+
+ T = max(lens)
+ lat = torch.stack([F.pad(o, (0, 0, 0, T - o.shape[0])) for o in outs])
+ norm = (lat - fl.emb_mean) / fl.emb_std
+ noise = torch.stack(noises[:T], dim=1)
+ lens_t = torch.tensor(lens, device=device)
+ valid = torch.arange(T, device=device)[None, :] < lens_t[:, None]
+ z = model.backbone_z(fl, norm, toks, voice, nvf, cfg_dropout=False)
+ x = model.flow.decode(partial(fl.flow_net, z.float()), noise.float(), 1)
+ stats["refl_parity"] = (x.detach() - norm)[valid].abs().max() # ~0: x is the rollout
+ # Frames past a row's end repeat its last frame; the decoder is causal, so they
+ # cannot reach the row's own samples, which are cut at its length.
+ last = norm[torch.arange(R, device=device), (lens_t - 1).clamp(min=0)]
+ x = torch.where(valid[..., None], x, last[:, None])
+ ratio = round(mimi.encoder_frame_rate / mimi.frame_rate)
+ state = init_states(mimi, R, (T + MIN_FRAMES) * ratio)
+ audio = mimi.decode_from_latent(x * fl.emb_std + fl.emb_mean, state)[:, 0]
+
+ moses, ctcs = [], []
+ for b in range(R):
+ if not ok[b]:
+ continue
+ w16 = rewards.resample(
+ audio[b, random.randint(0, ra.max_shift) : lens[b] * mimi.frame_size]
+ )
+ with torch.set_grad_enabled(ra.utmos_weight > 0):
+ moses.append(rewards.utmos_score(w16))
+ with torch.set_grad_enabled(ra.ctc_weight > 0):
+ ctcs.append(rewards.ctc_loss(w16, scorable[b][1]))
+ mos, ctc = torch.stack(moses).mean(), torch.stack(ctcs).mean()
+ stats["refl_utmos"], stats["refl_ctc"] = mos.detach(), ctc.detach()
+ return ra.ctc_weight * ctc - ra.utmos_weight * mos, stats
diff --git a/training/scripts/residual_cov.py b/training/scripts/residual_cov.py
new file mode 100644
index 0000000..3a3ad3b
--- /dev/null
+++ b/training/scripts/residual_cov.py
@@ -0,0 +1,99 @@
+"""Residual-stream covariance of a trained flow LM, for shrinking d_model by PCA.
+
+For every backbone LayerNorm (each layer's norm1 and norm2, and out_norm), accumulates
+the second moment of its per-token normalized input (x - mean(x)) / std(x), i.e. what
+the following linear reads, over a few batches of the run's validation manifest
+(data.valid_jsonl). shrink_checkpoint --cov turns it into one rotation of the residual
+stream before cutting it (see pca_channels).
+
+ python -m training.scripts.residual_cov runs/big/args.yaml \
+ runs/big/checkpoint_00200000.pt runs/big/residual_cov.pt --batches 32 --ema
+"""
+
+import argparse
+from collections.abc import Callable
+from typing import Any
+
+import torch
+from torch import nn
+
+from training.args import load_args
+from training.dataloader import DataLoader, encode_batch
+from training.modules.builders import _load_flow_lm_state, build_models
+
+
+def residual_cov(config: str, checkpoint: str, num_batches: int, use_ema: bool) -> dict[str, Any]:
+ args = load_args(config)
+ args.distill_cfg_coef = 0.0 # only the model itself runs
+ args.start_from_pretrained = False
+ model, mimi, _ = build_models(args)
+ missing, unexpected = model.flow_lm.load_state_dict(
+ _load_flow_lm_state(checkpoint, use_ema), strict=False
+ )
+ assert not unexpected and all(k.startswith("flow_net.") for k in missing), missing
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
+ model.to(device).eval()
+ mimi.to(device)
+
+ fl = model.flow_lm
+ names = [
+ f"transformer.layers.{i}.{n}"
+ for i in range(len(fl.transformer.layers))
+ for n in ("norm1", "norm2")
+ ]
+ names.append("out_norm")
+ d = fl.out_norm.weight.shape[0]
+ sums = {n: torch.zeros(d, d, dtype=torch.float64, device=device) for n in names}
+ counts = dict.fromkeys(names, 0)
+
+ def hook(name: str) -> Callable[[nn.Module, tuple[torch.Tensor, ...]], None]:
+ def accumulate(_module: nn.Module, inputs: tuple[torch.Tensor, ...]):
+ x = inputs[0].float().reshape(-1, d)
+ x = x - x.mean(dim=-1, keepdim=True)
+ x = x / x.square().mean(dim=-1, keepdim=True).clamp(min=1e-12).sqrt()
+ sums[name] += (x.T @ x).double()
+ counts[name] += x.shape[0]
+
+ return accumulate
+
+ modules = dict(fl.named_modules())
+ handles = [modules[n].register_forward_pre_hook(hook(n)) for n in names]
+ loader = iter(
+ DataLoader(
+ args.data.valid_jsonl,
+ fl.conditioner.tokenizer.encode,
+ args.batch_size,
+ mimi.sample_rate,
+ mimi.frame_rate,
+ args.data.max_duration_sec,
+ args.data.max_voice_prompt_sec,
+ rank=0,
+ world_size=1,
+ seed=0,
+ )
+ )
+ for _ in range(num_batches):
+ batch = next(loader)
+ latents, mask, voice, num_voice_frames = encode_batch(mimi, batch, device)
+ model(latents, mask, batch.text_tokens, voice, num_voice_prompt_frames=num_voice_frames)
+ for h in handles:
+ h.remove()
+ return {"cov": {n: (sums[n] / counts[n]).cpu() for n in names}, "tokens": counts["out_norm"]}
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("config", help="the training config (args.yaml) of the checkpoint")
+ parser.add_argument("checkpoint")
+ parser.add_argument("out")
+ parser.add_argument("--batches", type=int, default=32)
+ parser.add_argument("--ema", action="store_true", help="use the checkpoint's EMA weights")
+ args = parser.parse_args()
+ result = residual_cov(args.config, args.checkpoint, args.batches, args.ema)
+ torch.save(result, args.out)
+ print(f"{args.out}: {len(result['cov'])} norms, {result['tokens']} tokens each")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/training/scripts/shrink_checkpoint.py b/training/scripts/shrink_checkpoint.py
index c764317..575d15c 100644
--- a/training/scripts/shrink_checkpoint.py
+++ b/training/scripts/shrink_checkpoint.py
@@ -1,19 +1,36 @@
-"""Build a shallower checkpoint from a deeper one by selecting layers.
+"""Build a smaller checkpoint from a bigger one: fewer layers, and optionally narrower.
-Every tensor outside the backbone is copied unchanged; the backbone keeps the
-teacher's bottom and top layers (see select_layers). Use it to initialize a
+Depth: every tensor outside the backbone is copied unchanged; the backbone keeps
+the teacher's bottom and top layers (see select_layers). Use it to initialize a
depth-distillation student -- starting from the teacher's own layers converges
far faster than a random backbone -- or to get a standalone shallow checkpoint.
python -m training.scripts.shrink_checkpoint runs/teacher/checkpoint_00200000.pt \
--layers 6 --out runs/student_init.pt
+
+Width: with --config (a pocket-tts model config, edited by --override) the flow LM
+is seeded for that architecture instead, see shrink_width: its depth, a narrower
+d_model, fewer or grouped attention heads (attn_dim, num_kv_heads), a narrower FFN
+and a low-rank text table. With --cov (from training.scripts.residual_cov), d_model
+is cut along the principal components of the residual stream instead (pca_channels).
+Tensors that cannot be seeded (e.g. a sampler head of another size) are left out and
+listed.
+
+ python -m training.scripts.shrink_checkpoint runs/teacher/checkpoint_00200000.pt \
+ --config pocket_tts/config/english.yaml \
+ --override flow_lm.transformer.d_model=512 --override flow_lm.lookup_table.dim=512 \
+ --out runs/narrow_init.pt
"""
import argparse
import re
from pathlib import Path
+from typing import Any
import torch
+import yaml
+
+Tensors = dict[str, torch.Tensor]
def select_layers(n_teacher: int, n_student: int) -> list[int]:
@@ -30,15 +47,13 @@ def select_layers(n_teacher: int, n_student: int) -> list[int]:
return list(range(head)) + list(range(n_teacher - tail, n_teacher))
-def shrink(
- state: dict[str, torch.Tensor], n_student: int
-) -> tuple[dict[str, torch.Tensor], list[int]]:
+def shrink(state: Tensors, n_student: int) -> tuple[Tensors, list[int]]:
pattern = re.compile(r"^(flow_lm\.)?transformer\.layers\.(\d+)\.(.*)$")
depth = max((int(m.group(2)) for m in (pattern.match(k) for k in state) if m), default=-1) + 1
assert depth > 0, "no transformer layers found in the checkpoint"
keep = select_layers(depth, n_student)
remap = {old: new for new, old in enumerate(keep)}
- out: dict[str, torch.Tensor] = {}
+ out: Tensors = {}
for k, v in state.items():
m = pattern.match(k)
if not m:
@@ -51,23 +66,276 @@ def shrink(
return out, keep
+def layer_prefixes(state: Tensors) -> list[str]:
+ """The "transformer.layers.<i>" prefixes of a flow LM state dict (no "flow_lm.")."""
+ n = 0
+ while f"transformer.layers.{n}.norm1.weight" in state:
+ n += 1
+ return [f"transformer.layers.{i}" for i in range(n)]
+
+
+def narrow_attention(src: Tensors, dst: Tensors, head_dim: int) -> Tensors:
+ """Fewer query heads and/or grouped kv heads, at the source's d_model.
+
+ Per layer, keeps the query heads with the largest q/k/v weight norm; each kv head
+ of the result is the mean of the source kv heads its query heads read. Both sides
+ must have the same head width. Rows of in_proj are [q | k | v].
+ """
+ out: Tensors = {}
+ for layer in layer_prefixes(dst):
+ k_in, k_out = f"{layer}.self_attn.in_proj.weight", f"{layer}.self_attn.out_proj.weight"
+ if k_in not in src or src[k_in].shape[0] == dst[k_in].shape[0]:
+ continue
+ w, d = src[k_in], src[k_in].shape[1]
+ heads_t, heads_s = src[k_out].shape[1] // head_dim, dst[k_out].shape[1] // head_dim
+ kv_t = (w.shape[0] - heads_t * head_dim) // (2 * head_dim)
+ kv_s = (dst[k_in].shape[0] - heads_s * head_dim) // (2 * head_dim)
+ if min(kv_t, kv_s) < 1 or heads_s > heads_t or heads_t % kv_t or heads_s % kv_s:
+ raise ValueError(f"{layer}: cannot seed {heads_s}/{kv_s} heads from {heads_t}/{kv_t}")
+ q, k, v = w.split([heads_t * head_dim, kv_t * head_dim, kv_t * head_dim])
+ q, k, v = (x.reshape(-1, head_dim, d) for x in (q, k, v))
+ group = torch.arange(heads_t) // (heads_t // kv_t) # the kv head each query head reads
+ score = q.square().sum((1, 2)) + k[group].square().sum((1, 2))
+ score = score + v[group].square().sum((1, 2))
+ keep = score.topk(heads_s).indices.sort().values
+ k = k[group[keep]].reshape(kv_s, heads_s // kv_s, head_dim, d).mean(1)
+ v = v[group[keep]].reshape(kv_s, heads_s // kv_s, head_dim, d).mean(1)
+ out[k_in] = torch.cat([q[keep].reshape(-1, d), k.reshape(-1, d), v.reshape(-1, d)])
+ o = src[k_out].reshape(src[k_out].shape[0], heads_t, head_dim)[:, keep]
+ out[k_out] = o.reshape(o.shape[0], heads_s * head_dim)
+ return out
+
+
+def residual_axes(state: Tensors) -> dict[str, int]:
+ """Every tensor with a d_model (residual stream) axis: key -> that axis."""
+ axes = {
+ "out_norm.weight": 0,
+ "out_norm.bias": 0,
+ "bos_before_voice": 2,
+ "speaker_proj_weight": 0,
+ "input_linear.weight": 0,
+ "conditioner.proj.weight": 0, # low-rank text table
+ # The full text table, unless the low-rank one's projection carries d_model.
+ **({} if "conditioner.proj.weight" in state else {"conditioner.embed.weight": 1}),
+ # Readers of the backbone output: the z bottleneck, else both heads.
+ **(
+ {"z_proj.weight": 1}
+ if "z_proj.weight" in state
+ else {"out_eos.weight": 1, "flow_net.cond_embed.weight": 1}
+ ),
+ }
+ for layer in layer_prefixes(state):
+ axes.update(
+ {
+ f"{layer}.norm1.weight": 0,
+ f"{layer}.norm1.bias": 0,
+ f"{layer}.norm2.weight": 0,
+ f"{layer}.norm2.bias": 0,
+ f"{layer}.self_attn.in_proj.weight": 1,
+ f"{layer}.self_attn.out_proj.weight": 0,
+ f"{layer}.linear1.weight": 1,
+ f"{layer}.linear2.weight": 0,
+ }
+ )
+ return {k: a for k, a in axes.items() if k in state}
+
+
+def slice_channels(src: Tensors, d_student: int) -> Tensors:
+ """Narrower d_model: keep the residual channels with the largest LayerNorm gains
+ (summed over every norm of the backbone), in their original order."""
+ score = src["out_norm.weight"].abs().clone()
+ for layer in layer_prefixes(src):
+ score += src[f"{layer}.norm1.weight"].abs() + src[f"{layer}.norm2.weight"].abs()
+ keep = score.topk(d_student).indices.sort().values
+ return {k: src[k].index_select(axis, keep) for k, axis in residual_axes(src).items()}
+
+
+def pca_channels(src: Tensors, d_student: int, cov: Tensors) -> Tensors:
+ """Narrower d_model along the principal components of the residual stream (as in
+ SliceGPT) instead of a subset of its channels.
+
+ `cov` holds, per backbone LayerNorm ("transformer.layers.<i>.norm1", ..., "out_norm"),
+ the second moment of its normalized input (training/scripts/residual_cov.py). The
+ stream is only read through LayerNorms, so its mean direction is invisible: writers
+ are centred, then mapped by M^T, with M (d, d_student) orthonormal, spanning the top
+ d_student - 1 components plus the mean direction, which lands on the student's own
+ mean direction. Norm gains are folded into the linears that read them (the student's
+ gains are 1, rescaled for the variance the cut keeps) and each norm's bias is refit
+ by least squares on its readers.
+ """
+ f64 = torch.float64
+ d = src["out_norm.weight"].shape[0]
+ sigma = sum(c.to(f64) for c in cov.values()) / len(cov)
+ center = torch.eye(d, dtype=f64) - 1.0 / d
+ evals, evecs = torch.linalg.eigh(center @ sigma @ center)
+ top = evecs[:, evals.argsort(descending=True)[: d_student - 1]]
+ basis = torch.cat([torch.full((d, 1), d**-0.5, dtype=f64), top], dim=1)
+ # Householder reflection taking e_1 to the student's mean direction.
+ w = torch.zeros(d_student, dtype=f64)
+ w[0] = 1.0
+ w = w - d_student**-0.5
+ reflect = torch.eye(d_student, dtype=f64) - 2 * torch.outer(w, w) / w.dot(w)
+ M = basis @ reflect # (d, d_student)
+ to_student = M.T @ center # applied to everything written into the stream
+
+ axes = residual_axes(src)
+ out: Tensors = {}
+
+ def put(key: str, value: torch.Tensor):
+ out[key] = value.to(src[key].dtype)
+
+ norms = [f"{layer}.{n}" for layer in layer_prefixes(src) for n in ("norm1", "norm2")]
+ norms.append("out_norm")
+ readers = {
+ f"{layer}.norm1": [f"{layer}.self_attn.in_proj.weight"] for layer in layer_prefixes(src)
+ }
+ readers.update({f"{layer}.norm2": [f"{layer}.linear1.weight"] for layer in layer_prefixes(src)})
+ readers["out_norm"] = [
+ k for k in ("z_proj.weight", "out_eos.weight", "flow_net.cond_embed.weight") if k in axes
+ ]
+ norm_keys = {f"{n}.{p}" for n in norms for p in ("weight", "bias")}
+ read_keys = {k for ks in readers.values() for k in ks}
+ for key, axis in axes.items():
+ if key in norm_keys or key in read_keys:
+ continue
+ value = src[key].to(f64)
+ # Writers: rows of a linear (axis 0), or the last axis of an embedding-like tensor.
+ put(key, to_student @ value if axis == 0 else value @ to_student.T)
+
+ for norm in norms:
+ gain, bias = src[f"{norm}.weight"].to(f64), src[f"{norm}.bias"].to(f64)
+ c = cov[norm].to(f64)
+ kept = torch.trace(M.T @ c @ M) / torch.trace(c) # share of the variance the cut keeps
+ scale = (d * kept / d_student) ** 0.5
+ weights, targets = [], []
+ for key in readers[norm]:
+ reader = src[key].to(f64)
+ weights.append((reader * gain) @ M * scale)
+ targets.append(reader @ bias)
+ put(key, weights[-1])
+ fit = torch.linalg.lstsq(torch.cat(weights), torch.cat(targets)[:, None]).solution
+ put(f"{norm}.weight", torch.ones(d_student, dtype=f64))
+ put(f"{norm}.bias", fit[:, 0])
+ return out
+
+
+def prune_ffn(src: Tensors, dst: Tensors) -> Tensors:
+ """Narrower FFN: keep the hidden units with the largest ||linear1 row|| * ||linear2 col||."""
+ out: Tensors = {}
+ for layer in layer_prefixes(dst):
+ k1, k2 = f"{layer}.linear1.weight", f"{layer}.linear2.weight"
+ hidden = dst[k1].shape[0]
+ if k1 not in src or src[k1].shape[0] <= hidden:
+ continue
+ l1, l2 = src[k1], src[k2]
+ keep = (l1.norm(dim=1) * l2.norm(dim=0)).topk(hidden).indices.sort().values
+ out[k1], out[k2] = l1[keep], l2[:, keep]
+ return out
+
+
+def low_rank_text_table(src: Tensors, dst: Tensors) -> Tensors:
+ """A low-rank text table from a full one: its best rank-r approximation (SVD),
+ E ~= (U_r S_r) @ Vh_r, as conditioner.embed (U_r S_r) and conditioner.proj (Vh_r^T).
+ A source table that is already low-rank is re-cut from E = embed @ proj^T when the
+ rank changes (otherwise the smaller table would be left at its random init)."""
+ if "conditioner.proj.weight" not in dst:
+ return {}
+ full = src["conditioner.embed.weight"]
+ rank = dst["conditioner.embed.weight"].shape[1]
+ if "conditioner.proj.weight" in src:
+ if rank == full.shape[1]:
+ return {}
+ full = full.float() @ src["conditioner.proj.weight"].float().T
+ u, s, vh = torch.linalg.svd(full.float(), full_matrices=False)
+ return {
+ "conditioner.embed.weight": (u[:, :rank] * s[:rank]).to(full.dtype),
+ "conditioner.proj.weight": vh[:rank].T.contiguous().to(full.dtype),
+ }
+
+
+def shrink_width(src: Tensors, dst: Tensors, head_dim: int, cov: Tensors | None = None) -> Tensors:
+ """Seed the flow LM state `dst` (only its shapes are read) from `src` of the same depth.
+
+ Attention heads are narrowed first (narrow_attention), then the residual stream
+ (slice_channels, or pca_channels given the residual covariance `cov`), the FFN
+ (prune_ffn) and the text table (low_rank_text_table). Returns the tensors that end
+ up with `dst`'s shapes.
+ """
+ state = {**src, **narrow_attention(src, dst, head_dim)}
+ d_dst = dst["out_norm.weight"].shape[0]
+ if state["out_norm.weight"].shape[0] != d_dst:
+ if cov is None:
+ state.update(slice_channels(state, d_dst))
+ else:
+ state.update(pca_channels(state, d_dst, cov))
+ state.update(prune_ffn(state, dst))
+ state.update(low_rank_text_table(state, dst))
+ return {k: v for k, v in state.items() if k in dst and dst[k].shape == v.shape}
+
+
+def flow_lm_shapes(config_path: str, overrides: dict[str, Any]) -> tuple[Tensors, int]:
+ """(state dict, attention head width) of the flow LM a pocket-tts config builds."""
+ from pocket_tts.models.flow_lm import FlowLMModel
+ from training.modules.builders import load_model_config
+
+ config = load_model_config(config_path, overrides)
+ fl = config.flow_lm
+ flow_lm = FlowLMModel.from_pydantic_config(
+ fl, config.mimi.quantizer.dimension, fl.insert_bos_before_voice
+ )
+ state = flow_lm.state_dict()
+ latent_dim = config.mimi.inner_dim or config.mimi.seanet.dimension
+ state["speaker_proj_weight"] = torch.empty(fl.transformer.d_model, latent_dim)
+ attn_dim = fl.transformer.attn_dim or fl.transformer.d_model
+ return state, attn_dim // fl.transformer.num_heads
+
+
def main():
parser = argparse.ArgumentParser()
parser.add_argument("checkpoint")
- parser.add_argument("--layers", type=int, required=True, help="student depth")
+ parser.add_argument("--layers", type=int, help="student depth (depth-only shrinking)")
+ parser.add_argument("--config", help="student model config (width shrinking)")
+ parser.add_argument(
+ "--override", action="append", default=[], help="dotted.key=value edit of --config"
+ )
+ parser.add_argument(
+ "--ema", action="store_true", help="with --config: seed from the EMA weights"
+ )
+ parser.add_argument(
+ "--cov",
+ help="with --config: residual covariance (training.scripts.residual_cov) to cut "
+ "d_model along its principal components",
+ )
parser.add_argument("--out", required=True)
args = parser.parse_args()
+ if (args.layers is None) == (args.config is None):
+ parser.error("give exactly one of --layers and --config")
payload = torch.load(args.checkpoint, map_location="cpu", weights_only=True)
model = payload.get("model", payload)
- shrunk, keep = shrink(model, args.layers)
ema = payload.get("ema")
- if ema:
- ema = shrink(ema, args.layers)[0]
+ if args.config is None:
+ shrunk, keep = shrink(model, args.layers)
+ if ema:
+ ema = shrink(ema, args.layers)[0]
+ print(f"kept teacher layers {keep}")
+ else:
+ if args.ema and ema:
+ model = {**model, **ema}
+ overrides = {k: yaml.safe_load(v) for k, v in (kv.split("=", 1) for kv in args.override)}
+ dst, head_dim = flow_lm_shapes(args.config, overrides)
+ src = {k.removeprefix("flow_lm."): v for k, v in model.items() if k.startswith("flow_lm.")}
+ src, keep = shrink(src, len(layer_prefixes(dst)))
+ cov = torch.load(args.cov, weights_only=True)["cov"] if args.cov else None
+ seeded = shrink_width(src, dst, head_dim, cov)
+ shrunk = {k: v for k, v in model.items() if not k.startswith("flow_lm.")}
+ shrunk.update({f"flow_lm.{k}": v for k, v in seeded.items()})
+ ema = None
+ print(f"kept teacher layers {keep}; not seeded: {sorted(set(dst) - set(seeded))}")
out = {"step": 0, "model": shrunk, "optimizer": None, "ema": ema}
Path(args.out).parent.mkdir(parents=True, exist_ok=True)
torch.save(out, args.out)
- print(f"kept teacher layers {keep} -> {args.out}")
+ print(f"-> {args.out}")
if __name__ == "__main__":
diff --git a/training/tests/test_smoke.py b/training/tests/test_smoke.py
index 4c06165..d6ba699 100644
--- a/training/tests/test_smoke.py
+++ b/training/tests/test_smoke.py
@@ -5,7 +5,10 @@ import json
import random
import subprocess
import sys
+from functools import partial
from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
import numpy as np
import numpy.typing as npt
@@ -20,17 +23,31 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
import training.dataloader.audio as td_audio
from pocket_tts.models.flow_lm import FlowLMModel
+from pocket_tts.models.mimi import build_mimi
+from pocket_tts.modules.attention import StreamingMultiheadAttention
from pocket_tts.modules.mlp import SimpleMLPAdaLN
+from pocket_tts.modules.rope import RotaryEmbedding
from pocket_tts.modules.stateful_module import init_states
from pocket_tts.modules.text_conditioner import LUTConditioner
from pocket_tts.modules.transformer import StreamingTransformer
-from training.args import TrainArgs
+from pocket_tts.utils.config import CONFIGS_DIR, load_config
+from training.args import ReflArgs, TrainArgs
from training.checkpointing import EMA
from training.dataloader import DataLoader, Entry
+from training.modules.builders import head_from_state
from training.modules.model import TrainableTTS
from training.modules.samplers import build_flow
from training.modules.utils import dit_init, stamp_state_names
-from training.scripts.shrink_checkpoint import select_layers, shrink
+from training.refl import Rewards, refl_loss
+from training.scripts.shrink_checkpoint import (
+ low_rank_text_table,
+ narrow_attention,
+ pca_channels,
+ select_layers,
+ shrink,
+ shrink_width,
+)
+from training.train_utils import build_optimizer
LDIM, DIM = 8, 32
@@ -38,33 +55,49 @@ LDIM, DIM = 8, 32
class DummyConditioner(LUTConditioner):
"""LUTConditioner without the sentencepiece download (tests only)."""
- def __init__(self, n_bins: int, dim: int):
+ def __init__(self, n_bins: int, dim: int, rank: int | None = None):
nn.Module.__init__(self)
self.dim = dim
self.output_dim = dim
- self.embed = nn.Embedding(n_bins + 1, dim)
-
- def forward(self, tokens: torch.Tensor) -> torch.Tensor:
- return self.embed(tokens)
-
-
-def tiny_model(flow_type: str, context: int | None = None) -> TrainableTTS:
+ self.embed = nn.Embedding(n_bins + 1, rank or dim)
+ self.proj = None if rank is None else nn.Linear(rank, dim, bias=False)
+
+
+def tiny_model(
+ flow_type: str,
+ context: int | None = None,
+ dim: int = DIM,
+ num_layers: int = 2,
+ num_heads: int = 2,
+ z_dim: int | None = None,
+ attn_dim: int | None = None,
+ num_kv_heads: int | None = None,
+ rank: int | None = None,
+ hidden: int = 64,
+) -> TrainableTTS:
torch.manual_seed(0)
flow = build_flow(flow_type)
transformer = StreamingTransformer(
- d_model=DIM, num_heads=2, num_layers=2, dim_feedforward=64, context=context
+ d_model=dim,
+ num_heads=num_heads,
+ num_layers=num_layers,
+ dim_feedforward=hidden,
+ context=context,
+ attn_dim=attn_dim,
+ num_kv_heads=num_kv_heads,
)
- head = SimpleMLPAdaLN(LDIM, 16, LDIM, DIM, 2, flow.num_time_conds)
+ head = SimpleMLPAdaLN(LDIM, 16, LDIM, z_dim or dim, 2, flow.num_time_conds)
dit_init(head)
flow_lm = FlowLMModel(
- conditioner=DummyConditioner(11, DIM),
+ conditioner=DummyConditioner(11, dim, rank),
flow_net=head,
transformer=transformer,
- dim=DIM,
+ dim=dim,
ldim=LDIM,
insert_bos_before_voice=True,
+ z_dim=z_dim,
)
- flow_lm.speaker_proj_weight = torch.nn.Parameter(torch.randn(DIM, LDIM) * 0.1)
+ flow_lm.speaker_proj_weight = torch.nn.Parameter(torch.randn(dim, LDIM) * 0.1)
args = TrainArgs()
args.flow.type = flow_type
args.flow_batch_multiplier = 2
@@ -94,6 +127,32 @@ def test_train_step(flow_type: str):
assert "flow_loss" in metrics and "eos_loss" in metrics
+SMALL_OPTIONS = {"z_dim": 8, "attn_dim": 16, "num_kv_heads": 1, "rank": 4}
+
+
[email protected]("flow_type", ["lsd", "drifting"])
+def test_train_step_and_generate_with_small_model_options(flow_type: str):
+ """z bottleneck, narrower attention with grouped kv heads and a low-rank text table."""
+ model = tiny_model(flow_type, **SMALL_OPTIONS)
+ model.train()
+ loss, _ = model(*make_batch())
+ loss.backward()
+ assert loss.isfinite()
+ assert model.flow_lm.z_proj is not None and model.flow_lm.z_proj.weight.grad is not None
+ latents = model.generate(
+ [torch.randint(0, 10, (5,))], [torch.randn(4, LDIM)], max_frames=3, eos_threshold=1e9
+ )
+ assert latents[0].shape == (3, LDIM)
+
+
+def test_muon_splits_narrow_grouped_attention():
+ model = tiny_model("lsd", **SMALL_OPTIONS)
+ model.args.optim.type = "muon"
+ optimizer = build_optimizer(model, model.args, torch.device("cpu"), rank=0)
+ sizes = [g["split_sizes"] for g in optimizer.param_groups if g.get("split_sizes")]
+ assert [16, 8, 8] in sizes, sizes
+
+
@pytest.mark.parametrize("flow_type,cfg", [("lsd", 1.0), ("flow_matching", 1.0), ("drifting", 1.0)])
def test_generate(flow_type: str, cfg: float):
model = tiny_model(flow_type)
@@ -137,6 +196,60 @@ def test_cfg_distill():
assert backbone_grads and torch.isfinite(torch.cat([g.flatten() for g in backbone_grads])).all()
+def test_distill_into_a_narrower_student():
+ """A narrower student seeded from the teacher, sharing its z width: the loss is on z,
+ the heads stay frozen and the backbone learns."""
+ teacher = tiny_model("lsd", dim=48, num_heads=6, hidden=96, z_dim=8).flow_lm.eval()
+ model = tiny_model("lsd", num_heads=4, z_dim=8)
+ model.args.distill_cfg_coef = 1.0
+ model.args.text_dropout = model.args.voice_dropout = 0.0
+ seeded = shrink_width(teacher.state_dict(), model.flow_lm.state_dict(), head_dim=8)
+ model.flow_lm.load_state_dict(seeded)
+ teacher.requires_grad_(False)
+ model.__dict__["distill_teacher"] = teacher
+ model.flow_lm.flow_net.requires_grad_(False)
+ model.flow_lm.out_eos.requires_grad_(False)
+ model.train()
+ loss, metrics = model(*make_batch())
+ assert loss.isfinite() and "distill_mse" in metrics
+ loss.backward()
+ grads = {k: p.grad for k, p in model.flow_lm.named_parameters()}
+ assert grads["transformer.layers.0.linear1.weight"] is not None
+ assert model.flow_lm.out_eos.weight.grad is None
+
+
+ "flow_type,loss_name", [("lsd", "mse"), ("drifting", "mse"), ("drifting", "drifting")]
+)
+def test_head_distillation_trains_only_the_new_head(flow_type: str, loss_name: str):
+ """A smaller head learns a frozen bigger one's samples, with either objective whatever the
+ head type; the backbone gets no gradient."""
+ model = tiny_model(flow_type)
+ model.args.head_distill_loss = loss_name
+ model.args.head_distill_samples = 3
+ frozen = SimpleMLPAdaLN(LDIM, 32, LDIM, DIM, 3, num_time_conds=2)
+ model.__dict__["head_teacher"] = head_from_state(frozen.state_dict())
+ model.flow_lm.requires_grad_(False)
+ model.flow_lm.flow_net.requires_grad_(True)
+ model.train()
+ loss, metrics = model(*make_batch())
+ assert loss.isfinite() and "head_loss" in metrics
+ loss.backward()
+ assert all(p.grad is not None for p in model.flow_lm.flow_net.parameters())
+ assert model.flow_lm.input_linear.weight.grad is None
+
+
+def test_drifting_single_target_sample_is_unchanged():
+ """[N, 1, D] targets give the same loss as [N, D] ones."""
+ flow, head = build_flow("drifting"), SimpleMLPAdaLN(LDIM, 16, LDIM, DIM, 1, 0)
+ z, x_1 = torch.randn(5, DIM), torch.randn(5, LDIM)
+ losses = []
+ for target in (x_1, x_1[:, None]):
+ torch.manual_seed(0)
+ losses.append(flow.loss(partial(head, z), torch.randn(5, LDIM), target)[0])
+ torch.testing.assert_close(losses[0], losses[1], rtol=0, atol=0)
+
+
@pytest.mark.parametrize("num_time_conds", [0, 1, 2])
def test_head_supports_every_time_cond_count(num_time_conds: int):
"""The head runs with 0, 1 or 2 time conditions."""
@@ -176,6 +289,64 @@ def test_shrink_checkpoint():
assert out[f"flow_lm.transformer.layers.{new}.norm1.weight"][0].item() == float(old)
+def test_shrink_width_seeds_a_narrower_model():
+ """Every backbone tensor of a narrower, grouped-attention, low-rank model is seeded."""
+ big = tiny_model("lsd", dim=48, num_heads=6, hidden=96).flow_lm
+ small = tiny_model("lsd", num_heads=4, attn_dim=32, num_kv_heads=2, rank=8, hidden=64)
+ seeded = shrink_width(big.state_dict(), small.flow_lm.state_dict(), head_dim=8)
+ missing = set(small.flow_lm.state_dict()) - set(seeded)
+ assert not missing, missing
+ small.flow_lm.load_state_dict(seeded)
+ loss, _ = small(*make_batch())
+ assert loss.isfinite()
+
+
+def test_narrow_attention_is_exact_for_duplicated_kv_heads():
+ """Grouping kv heads that are already equal within each group changes nothing."""
+ rope = RotaryEmbedding()
+ full = StreamingMultiheadAttention(32, 4, rope)
+ k = full.in_proj.weight.data[32:].view(2, 4, 8, 32) # [k | v] x 4 heads
+ k[:, 1], k[:, 3] = k[:, 0], k[:, 2]
+ grouped = StreamingMultiheadAttention(32, 4, rope, num_kv_heads=2)
+
+ def as_layer(attn: nn.Module) -> dict[str, torch.Tensor]:
+ state = {f"transformer.layers.0.self_attn.{k}": v for k, v in attn.state_dict().items()}
+ return {"transformer.layers.0.norm1.weight": torch.ones(32), **state}
+
+ seeded = narrow_attention(as_layer(full), as_layer(grouped), head_dim=8)
+ grouped.load_state_dict({k.split("self_attn.")[1]: v for k, v in seeded.items()})
+ x = torch.randn(1, 5, 32)
+ torch.testing.assert_close(grouped(x, None), full(x, None))
+
+
[email protected]("z_dim", [None, 8])
+def test_pca_channels_at_full_width_is_exact(z_dim: int | None):
+ """Rotating the residual stream without cutting it leaves the model's function unchanged."""
+ model = tiny_model("lsd", z_dim=z_dim).eval()
+ state = model.flow_lm.state_dict()
+ norms = [f"transformer.layers.{i}.norm{j}" for i in range(2) for j in (1, 2)] + ["out_norm"]
+ a = torch.randn(len(norms), DIM, DIM, dtype=torch.float64)
+ cov = {n: a[i] @ a[i].T for i, n in enumerate(norms)}
+ rotated = copy.deepcopy(model)
+ rotated.flow_lm.load_state_dict({**state, **pca_channels(state, DIM, cov)})
+ losses = []
+ for module in (model, rotated):
+ torch.manual_seed(0)
+ losses.append(module(*make_batch())[0])
+ torch.testing.assert_close(losses[1], losses[0])
+
+
+def test_low_rank_text_table_at_full_rank_is_exact():
+ table = {"conditioner.embed.weight": torch.randn(11, 6)}
+ dst = {
+ "conditioner.embed.weight": torch.empty(11, 6),
+ "conditioner.proj.weight": torch.empty(6, 6),
+ }
+ seeded = low_rank_text_table(table, dst)
+ product = seeded["conditioner.embed.weight"] @ seeded["conditioner.proj.weight"].T
+ torch.testing.assert_close(product, table["conditioner.embed.weight"], atol=1e-5, rtol=1e-5)
+
+
def test_generate_ragged_matches_batch_of_one():
"""Ragged prefixes: batched rows must equal the batch-of-1 path exactly."""
model = tiny_model("lsd")
@@ -388,3 +559,84 @@ def test_train_tokenizer_matches_the_released_spec(tmp_path: Path):
assert trainer[43][0] == 3 # pad_id
assert normalizer.get(4, [1])[0] == 0 # remove_extra_whitespaces off
assert not normalizer.get(2, [b""])[0] # identity: no precompiled charsmap
+
+
+class StubUTMOS(nn.Module):
+ def forward(
+ self, wav: torch.Tensor, domains: torch.Tensor, judge_id: torch.Tensor
+ ) -> torch.Tensor:
+ return wav.abs().mean()[None]
+
+
+class StubCTC(nn.Module):
+ """Character logits from 320-sample windows, over a blank and "|'A..Z"."""
+
+ def __init__(self):
+ super().__init__()
+ self.proj = nn.Linear(320, 29)
+
+ def forward(self, x: torch.Tensor) -> SimpleNamespace:
+ return SimpleNamespace(logits=self.proj(x.unfold(-1, 320, 320)))
+
+
+def test_refl_step(monkeypatch: pytest.MonkeyPatch):
+ """One REFL step through a tiny Mimi decoder with stub scorers: the head re-applied on the
+ rollout's noise reproduces the rollout, and the rewards reach the backbone."""
+ model = tiny_model("lsd")
+ for p in model.flow_lm.flow_net.parameters(): # a head that reads its conditioning
+ nn.init.normal_(p, std=0.1)
+ config = load_config(CONFIGS_DIR / "english.yaml").mimi
+ small = config.model_copy(
+ update={
+ "outer_dim": 64,
+ "quantizer": config.quantizer.model_copy(
+ update={"dimension": LDIM, "output_dimension": 64}
+ ),
+ "decoder_seanet": config.seanet.model_copy(
+ update={"dimension": 64, "n_filters": 8, "kernel_size": 3}
+ ),
+ "decoder_transformer": config.transformer.model_copy(
+ update={
+ "d_model": 64,
+ "num_heads": 4,
+ "num_layers": 1,
+ "dim_feedforward": 128,
+ "input_dimension": 64,
+ "output_dimensions": (64,),
+ }
+ ),
+ }
+ )
+ rewards: Any = Rewards.__new__(Rewards)
+ rewards.mimi = build_mimi(small).eval().requires_grad_(False)
+ stamp_state_names(rewards.mimi)
+ rewards.resample = lambda w: w
+ rewards.utmos, rewards.ctc = StubUTMOS(), StubCTC()
+ rewards.vocab = {c: i + 1 for i, c in enumerate("|'ABCDEFGHIJKLMNOPQRSTUVWXYZ")}
+ rewards.blank = 0
+ ra = ReflArgs(enabled=True, rows=2, max_sec=2.0, utmos_weight=1.0, ctc_weight=1.0)
+ # Rollouts of 10 frames, ending before max_sec as if they had emitted EOS.
+ generate = model.generate
+ monkeypatch.setattr(
+ model,
+ "generate",
+ lambda *a, **kw: generate(*a, **{**kw, "max_frames": 10, "eos_threshold": 1e9}),
+ )
+ _, mask, text, voice = make_batch()
+ model.train()
+ loss, stats = refl_loss(
+ model,
+ lambda tokens: " ".join("ABCDEFGHIJ"[t] for t in tokens),
+ text,
+ voice,
+ torch.tensor([5, 3, 0]),
+ mask,
+ rewards,
+ ra,
+ )
+ assert loss is not None and loss.isfinite()
+ assert stats["refl_rows"] == 2 and stats["refl_ok"] == 1
+ assert stats["refl_parity"] < 1e-4
+ loss.backward()
+ grad = dict(model.flow_lm.named_parameters())["transformer.layers.0.linear1.weight"].grad
+ assert grad is not None and grad.abs().sum() > 0
diff --git a/training/tests/test_units.py b/training/tests/test_units.py
index 74d6372..c413baa 100644
--- a/training/tests/test_units.py
+++ b/training/tests/test_units.py
@@ -9,7 +9,7 @@ from torch import nn
from training.args import OptimArgs, TrainArgs
from training.checkpointing import EMA
from training.modules.samplers import LSD, Drifting
-from training.scripts.shrink_checkpoint import select_layers, shrink
+from training.scripts.shrink_checkpoint import low_rank_text_table, select_layers, shrink
from training.train_utils import lr_at
@@ -66,6 +66,20 @@ class TestSelectLayers:
assert out["transformer.layers.3.w"].item() == 21.0
assert "out_eos.weight" in out, "non-backbone tensors are copied unchanged"
+ def test_low_rank_table_recuts_an_already_low_rank_table(self):
+ torch.manual_seed(0)
+ embed, proj = torch.randn(50, 8), torch.randn(16, 8) # rank-8 table for d_model 16
+ dst = {
+ "conditioner.embed.weight": torch.zeros(50, 4),
+ "conditioner.proj.weight": torch.zeros(16, 4),
+ }
+ out = low_rank_text_table(
+ {"conditioner.embed.weight": embed, "conditioner.proj.weight": proj}, dst
+ )
+ e4 = out["conditioner.embed.weight"] @ out["conditioner.proj.weight"].T
+ u, s, vh = torch.linalg.svd(embed @ proj.T, full_matrices=False)
+ assert torch.allclose(e4, (u[:, :4] * s[:4]) @ vh[:4], atol=1e-4)
+
class TestEMA:
def _model(self) -> nn.Linear:
diff --git a/training/train.py b/training/train.py
index fa3529d..b2f17d3 100644
--- a/training/train.py
+++ b/training/train.py
@@ -30,6 +30,7 @@ from training.args import TrainArgs, dump_args, load_args, save_args
from training.checkpointing import EMA, latest_checkpoint, load_checkpoint, save_checkpoint
from training.dataloader import DataLoader, SubprocessDataLoader, encode_batch
from training.distributed import (
+ average_grads,
avg_across_ranks,
get_rank,
get_world_size,
@@ -39,6 +40,7 @@ from training.distributed import (
)
from training.modules.builders import build_models
from training.modules.model import TrainableTTS
+from training.refl import Rewards, refl_loss
from training.train_utils import (
ProgressLog,
_compile_models,
@@ -143,7 +145,11 @@ def setup(config_path: str) -> Run:
)
wrapped: nn.Module = model
- if is_torchrun():
+ if is_torchrun() and args.refl.enabled:
+ # REFL averages its gradients itself; the ranks start from rank 0's weights, as under DDP.
+ for t in model.state_dict().values():
+ torch.distributed.broadcast(t, 0)
+ elif is_torchrun():
wrapped = DDP(model, device_ids=[device.index], find_unused_parameters=not args.compile)
if args.compile:
_compile_models(model, mimi)
@@ -197,6 +203,7 @@ def main(config_path: str):
autocast = torch.autocast(
device_type=device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"
)
+ refl_rewards = Rewards(args.refl, device, mimi) if args.refl.enabled else None
model.train()
# scancel sends SIGTERM 30s (KillWait) before SIGKILL; finish the step and
# checkpoint inside that window so a cancelled job resumes losslessly.
@@ -233,6 +240,20 @@ def main(config_path: str):
update_stats=step < args.stats_ema_steps,
num_voice_prompt_frames=num_voice_prompt_frames,
)
+ if refl_rewards is not None:
+ reward_loss, refl_stats = refl_loss(
+ model,
+ sentence_piece.decode,
+ batch.text_tokens,
+ voice_prompt_latents,
+ num_voice_prompt_frames,
+ mask,
+ refl_rewards,
+ args.refl,
+ )
+ metrics.update(refl_stats)
+ if reward_loss is not None:
+ loss = loss + reward_loss
# Under DDP, allreduce only on the last micro-batch.
last_micro = micro == args.grad_accum_steps - 1
scaled = loss / args.grad_accum_steps
@@ -241,6 +262,8 @@ def main(config_path: str):
scaled.backward()
else:
scaled.backward()
+ if refl_rewards is not None and run.world_size > 1:
+ average_grads([p for p in model.parameters() if p.requires_grad])
grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), args.optim.max_norm)
if not torch.isfinite(grad_norm):
# Stop before the NaN reaches the weights: the run would otherwise
diff --git a/training/train_utils.py b/training/train_utils.py
index 5a45c2f..66b8e7d 100644
--- a/training/train_utils.py
+++ b/training/train_utils.py
@@ -262,8 +262,8 @@ def build_optimizer(
fused: dict[int, tuple[int, ...]] = {}
for module in layer.modules():
if isinstance(module, StreamingMultiheadAttention):
- kv_dim = (module.in_proj.weight.size(0) - module.embed_dim) // 2
- fused[id(module.in_proj.weight)] = (module.embed_dim, kv_dim, kv_dim)
+ kv_dim = (module.in_proj.weight.size(0) - module.attn_dim) // 2
+ fused[id(module.in_proj.weight)] = (module.attn_dim, kv_dim, kv_dim)
for p in layer.parameters():
add(p, fused.get(id(p), ()))
if args.optim.muon_head: