A TTS that fits in your CPU (and pocket)
Python
Rust CLI: run the small English models (#388)
gabrieldemarmiesse-ai-agentc985d7a81610
diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 5b8f8ce..850ff24 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -2243,7 +2243,7 @@ dependencies = [[[package]]name = "ptts"version = "0.4.0-rc.3"-source = "git+https://github.com/gradium-ai/xn-ptts?rev=1bfe079c9a4c778dbe4edd9d4d5bca9df3e46b3f#1bfe079c9a4c778dbe4edd9d4d5bca9df3e46b3f"+source = "git+https://github.com/gabrieldemarmiesse/xn-ptts?rev=7efa26973f81bba42cf2ace8da2c1eb9b605d54d#7efa26973f81bba42cf2ace8da2c1eb9b605d54d"dependencies = ["ebur128","rand 0.9.5",diff --git a/rust/Cargo.toml b/rust/Cargo.tomlindex 692c5fc..261d967 100644--- a/rust/Cargo.toml+++ b/rust/Cargo.toml@@ -18,9 +18,11 @@ default = []accelerate = ["ptts/accelerate"][dependencies]-# The model itself: https://github.com/gradium-ai/xn-ptts, pinned to a commit since its API is-# still moving between release candidates.-ptts = { git = "https://github.com/gradium-ai/xn-ptts", rev = "1bfe079c9a4c778dbe4edd9d4d5bca9df3e46b3f", default-features = false, features = ["hf", "audio"] }+# The model itself: https://github.com/gradium-ai/xn-ptts, through a fork that adds what pocket-tts+# models need on top of it (https://github.com/gabrieldemarmiesse/xn-ptts, branch+# pocket-tts-small-models), pinned to a commit since its API is still moving between release+# candidates.+ptts = { git = "https://github.com/gabrieldemarmiesse/xn-ptts", rev = "7efa26973f81bba42cf2ace8da2c1eb9b605d54d", default-features = false, features = ["hf", "audio"] }# Must be the version ptts uses, its tensors cross the boundary.xn = "0.2.11"diff --git a/rust/README.md b/rust/README.mdindex 26860c1..14ce77e 100644--- a/rust/README.md+++ b/rust/README.md@@ -1,8 +1,9 @@# pocket-tts, the standalone binaryA port of the `pocket-tts` CLI (`generate`, `serve`, `export-voice`) that runs without Python,-built on the [xn-ptts](https://github.com/gradium-ai/xn-ptts) implementation of the model. The-release workflow (`.github/workflows/rust-release.yml`) attaches its builds to every GitHub+built on the [xn-ptts](https://github.com/gradium-ai/xn-ptts) implementation of the model,+through [a fork](https://github.com/gabrieldemarmiesse/xn-ptts/tree/pocket-tts-small-models)+that adds what pocket-tts models need. The release workflow (`.github/workflows/rust-release.yml`) attaches its builds to every GitHubrelease.```bashdiff --git a/rust/src/config.rs b/rust/src/config.rsindex 395394a..5548b81 100644--- a/rust/src/config.rs+++ b/rust/src/config.rs@@ -5,6 +5,7 @@//! remote, is read with the same schema, unknown fields being an error as with pydantic.use anyhow::{Context, Result, bail};+pub use ptts::flow_lm::FlowType;use serde::Deserialize;use std::collections::BTreeMap;@@ -15,12 +16,9 @@ include!(concat!(env!("OUT_DIR"), "/embedded.rs"));pub struct FlowConfig {pub dim: usize,pub depth: usize,- #[serde(rename = "type", default = "default_flow_type")]- pub kind: String,-}--fn default_flow_type() -> String {- "lsd".to_string()+ /// The sampler head, under the names pocket-tts gives them.+ #[serde(rename = "type", default)]+ pub kind: FlowType,}#[derive(Debug, Clone, Deserialize)]@@ -31,12 +29,31 @@ pub struct FlowLMTransformerConfig {pub d_model: usize,pub num_heads: usize,pub num_layers: usize,- #[serde(default)]- pub dim_feedforward: Option<usize>,+ /// Width of the queries and of the attention output, `d_model` when `None`.#[serde(default)]pub attn_dim: Option<usize>,+ /// Key/value heads, each shared by `num_heads / num_kv_heads` query heads, `num_heads` when+ /// `None`.#[serde(default)]pub num_kv_heads: Option<usize>,+ /// Hidden width of the feed-forward layers, `d_model * hidden_scale` when `None`.+ #[serde(default)]+ pub dim_feedforward: Option<usize>,+}++impl FlowLMTransformerConfig {+ pub fn num_kv_heads(&self) -> usize {+ self.num_kv_heads.unwrap_or(self.num_heads)+ }++ pub fn head_dim(&self) -> usize {+ self.attn_dim.unwrap_or(self.d_model) / self.num_heads+ }++ pub fn dim_feedforward(&self) -> usize {+ self.dim_feedforward+ .unwrap_or(self.d_model * self.hidden_scale)+ }}#[derive(Debug, Clone, Deserialize)]@@ -46,6 +63,7 @@ pub struct LookupTable {pub n_bins: usize,pub tokenizer: String,pub tokenizer_path: String,+ /// A low-rank table: `rank`-wide embeddings and a bias-free projection to `dim`.#[serde(default)]pub rank: Option<usize>,}@@ -63,6 +81,8 @@ pub struct FlowLMConfig {pub weights_path: Option<String>,#[serde(default)]pub insert_bos_before_voice: bool,+ /// Width of the backbone output the sampler and EOS heads read: a bias-free projection from+ /// `d_model` when set.#[serde(default)]pub z_dim: Option<usize>,}@@ -127,12 +147,30 @@ pub struct MimiConfig {pub inner_dim: Option<usize>,#[serde(default)]pub outer_dim: Option<usize>,+ /// The decoder's SEANet and transformer, when they differ from the encoder's.#[serde(default)]pub decoder_seanet: Option<SEANetConfig>,#[serde(default)]pub decoder_transformer: Option<MimiTransformerConfig>,}+impl MimiConfig {+ pub fn decoder_seanet(&self) -> &SEANetConfig {+ self.decoder_seanet.as_ref().unwrap_or(&self.seanet)+ }++ pub fn decoder_transformer(&self) -> &MimiTransformerConfig {+ self.decoder_transformer+ .as_ref()+ .unwrap_or(&self.transformer)+ }++ /// Whether the decoder has its own dims, which xn-ptts then loads with a config of its own.+ fn has_own_decoder(&self) -> bool {+ self.decoder_seanet.is_some() || self.decoder_transformer.is_some()+ }+}+#[derive(Debug, Clone, Deserialize)]#[serde(deny_unknown_fields)]pub struct Config {@@ -157,10 +195,9 @@ 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>,+ /// The EOS threshold when the caller does not pass one.+ #[serde(default = "default_eos_threshold")]+ pub default_eos_threshold: f32,}fn default_true() -> bool {@@ -171,15 +208,8 @@ fn default_temperature() -> f32 {0.3}-/// The sampler head of the flow LM, from the config's `flow.type`.-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub enum FlowType {- /// Lagrangian Self Distillation: two time conditions.- Lsd,- /// Optimal-transport flow matching: one time condition, Euler integration.- FlowMatching,- /// No time condition, the head maps the noise to a sample in one step.- Drifting,+fn default_eos_threshold() -> f32 {+ crate::defaults::DEFAULT_EOS_THRESHOLD}/// Where a config came from.@@ -258,66 +288,57 @@ impl Config {Ok((config, origin))}- pub fn flow_type(&self) -> Result<FlowType> {- match self.flow_lm.flow.kind.as_str() {- "lsd" => Ok(FlowType::Lsd),- "flow_matching" => Ok(FlowType::FlowMatching),- "drifting" => Ok(FlowType::Drifting),- other => bail!("Unknown flow type: {other}"),- }- }-- /// The width of the speaker latents, which the Mimi encoder's downsampling produces.- pub fn speaker_latent_dim(&self) -> usize {- self.mimi.inner_dim.unwrap_or(self.mimi.seanet.dimension)+ pub fn flow_type(&self) -> FlowType {+ self.flow_lm.flow.kind}/// 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;- // TODO: upstream to xn-ptts. Its Mimi decoder upsamples from `dimension` channels; an- // `outer_dim` (the `in_dimension` of `ConvTrUpsample1d`) other than that needs support- // in `MimiConfig`.+ let decoder_dimension = mimi.decoder_seanet().dimension;+ // TODO: upstream to xn-ptts. Its Mimi decoder upsamples from as many channels as it+ // decodes; an `outer_dim` (the `in_dimension` of `ConvTrUpsample1d`) other than that+ // needs support in `MimiConfig`.if mimi.outer_dim- .is_some_and(|outer_dim| outer_dim != dimension)+ .is_some_and(|outer_dim| outer_dim != decoder_dimension){- bail!("mimi.outer_dim different from mimi.seanet.dimension is not supported")+ bail!("mimi.outer_dim different from the decoder's seanet dimension is not supported")}- // TODO: upstream to xn-ptts. Its SEANet always pads with zeros.- if mimi.seanet.pad_mode != "constant" {- bail!(- "mimi.seanet.pad_mode {:?} is not supported",- mimi.seanet.pad_mode- )+ for (name, seanet) in [+ ("seanet", &mimi.seanet),+ ("decoder_seanet", mimi.decoder_seanet()),+ ] {+ // TODO: upstream to xn-ptts. Its SEANet always pads with zeros.+ if seanet.pad_mode != "constant" {+ bail!(+ "mimi.{name}.pad_mode {:?} is not supported",+ seanet.pad_mode+ )+ }+ if seanet.channels != 1 {+ bail!("only mono Mimi models are supported")+ }}- if mimi.transformer.input_dimension != dimension- || mimi.transformer.output_dimensions != [dimension]- {- bail!("the Mimi transformer must map mimi.seanet.dimension to itself")+ if mimi.decoder_seanet().ratios != mimi.seanet.ratios {+ bail!("mimi.decoder_seanet.ratios must be those of mimi.seanet")}- if mimi.channels != 1 || mimi.seanet.channels != 1 {+ for (name, transformer, dimension) in [+ ("transformer", &mimi.transformer, mimi.seanet.dimension),+ (+ "decoder_transformer",+ mimi.decoder_transformer(),+ decoder_dimension,+ ),+ ] {+ if transformer.input_dimension != dimension+ || transformer.output_dimensions != [dimension]+ {+ bail!("mimi.{name} must map its seanet dimension to itself")+ }+ }+ if mimi.channels != 1 {bail!("only mono Mimi models are supported")}for key in self.replace_characters.keys() {@@ -328,6 +349,43 @@ impl Config {Ok(())}+ /// The `MimiConfig` of xn-ptts for a SEANet and a transformer of `self.mimi`.+ fn mimi_to_ptts(+ &self,+ seanet: &SEANetConfig,+ transformer: &MimiTransformerConfig,+ ) -> serde_json::Value {+ let mimi = &self.mimi;+ serde_json::json!({+ "channels": mimi.channels,+ "sample_rate": mimi.sample_rate,+ "frame_rate": mimi.frame_rate,+ "dimension": seanet.dimension,+ "quantizer_dimension": mimi.quantizer.dimension,+ "quantizer_output_dimension": mimi.quantizer.output_dimension,+ "n_filters": seanet.n_filters,+ "n_residual_layers": seanet.n_residual_layers,+ "ratios": seanet.ratios,+ "kernel_size": seanet.kernel_size,+ "last_kernel_size": seanet.last_kernel_size,+ "residual_kernel_size": seanet.residual_kernel_size,+ "dilation_base": seanet.dilation_base,+ "compress": seanet.compress,+ "transformer_d_model": transformer.d_model,+ "transformer_num_heads": transformer.num_heads,+ "transformer_num_layers": transformer.num_layers,+ "transformer_layer_scale": transformer.layer_scale,+ // pocket-tts (and moshi) count the current key in the `context` keys a query attends+ // to, where xn-ptts counts the `context` positions before it: one less is the same+ // window.+ "transformer_context": transformer.context.saturating_sub(1),+ "transformer_max_period": transformer.max_period,+ "transformer_dim_feedforward": transformer.dim_feedforward,+ "downsample_channel_wise": false,+ "inner_dim": mimi.inner_dim,+ })+ }+/// The `config.json` of xn-ptts that describes the same model.pub fn to_ptts(&self,@@ -341,45 +399,32 @@ impl Config {"d_model": flow_lm.transformer.d_model,"num_heads": flow_lm.transformer.num_heads,"num_layers": flow_lm.transformer.num_layers,- "dim_feedforward": flow_lm.transformer.d_model * flow_lm.transformer.hidden_scale,+ "dim_feedforward": flow_lm.transformer.dim_feedforward(),"max_period": flow_lm.transformer.max_period,"n_bins": flow_lm.lookup_table.n_bins,"lut_dim": flow_lm.lookup_table.dim,"flow_dim": flow_lm.flow.dim,"flow_depth": flow_lm.flow.depth,"ldim": mimi.quantizer.dimension,+ "flow_type": flow_lm.flow.kind,+ "z_dim": flow_lm.z_dim,+ "attn_dim": flow_lm.transformer.attn_dim,+ "num_kv_heads": flow_lm.transformer.num_kv_heads,+ "lut_rank": flow_lm.lookup_table.rank,},- "mimi": {- "channels": mimi.channels,- "sample_rate": mimi.sample_rate,- "frame_rate": mimi.frame_rate,- "dimension": mimi.seanet.dimension,- "quantizer_dimension": mimi.quantizer.dimension,- "quantizer_output_dimension": mimi.quantizer.output_dimension,- "n_filters": mimi.seanet.n_filters,- "n_residual_layers": mimi.seanet.n_residual_layers,- "ratios": mimi.seanet.ratios,- "kernel_size": mimi.seanet.kernel_size,- "last_kernel_size": mimi.seanet.last_kernel_size,- "residual_kernel_size": mimi.seanet.residual_kernel_size,- "dilation_base": mimi.seanet.dilation_base,- "compress": mimi.seanet.compress,- "transformer_d_model": mimi.transformer.d_model,- "transformer_num_heads": mimi.transformer.num_heads,- "transformer_num_layers": mimi.transformer.num_layers,- "transformer_layer_scale": mimi.transformer.layer_scale,- // TODO: upstream to xn-ptts. Its Mimi attention reaches `context` positions back,- // which is `context + 1` keys with the current one, where pocket-tts (and moshi)- // attend to `context` keys in all. One less gives the same window.- "transformer_context": mimi.transformer.context.saturating_sub(1),- "transformer_max_period": mimi.transformer.max_period,- "transformer_dim_feedforward": mimi.transformer.dim_feedforward,- "downsample_channel_wise": false,- },+ "mimi": self.mimi_to_ptts(mimi.decoder_seanet(), mimi.decoder_transformer()),"lsd_decode_steps": sampler_decode_steps,"eos_threshold": eos_threshold,"model_id": null,});+ if mimi.has_own_decoder() {+ // xn-ptts encodes the voice prompt with `speaker_mimi` when it is set and decodes+ // with `mimi`: the encoder's config goes there, under the same weight prefix.+ config["speaker_mimi"] = serde_json::json!({+ "prefix": "mimi",+ "mimi": self.mimi_to_ptts(&mimi.seanet, &mimi.transformer),+ });+ }if flow_lm.insert_bos_before_voice {// pocket-tts prepends `bos_before_voice` to the voice embedding, which is what a// `speaker_wavs` prefix sink does in xn-ptts: `[empty text, sink, voice]`. The check@@ -396,24 +441,9 @@ 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)@@ -422,6 +452,66 @@ mod tests {assert!(available_languages().contains(&"english"));}+ fn english_with(extra: &str) -> Result<Config> {+ let (_, yaml) = CONFIGS.iter().find(|(name, _)| *name == "english").unwrap();+ Config::parse(&format!("{yaml}\n{extra}\n"))+ }++ #[test]+ fn the_eos_threshold_defaults_to_the_python_one() {+ let config = english_with("").unwrap();+ assert_eq!(+ config.default_eos_threshold,+ crate::defaults::DEFAULT_EOS_THRESHOLD+ );+ let config = english_with("default_eos_threshold: -1.0").unwrap();+ assert_eq!(config.default_eos_threshold, -1.0);+ }++ #[test]+ fn the_small_model_options_reach_xn_ptts() {+ let (_, yaml) = CONFIGS.iter().find(|(name, _)| *name == "english").unwrap();+ let mut value: serde_yaml::Value = serde_yaml::from_str(yaml).unwrap();+ let options = serde_yaml::from_str::<serde_yaml::Value>(+ "{type: pointwise, attn_dim: 192, num_kv_heads: 1, dim_feedforward: 96, rank: 32}",+ )+ .unwrap();+ let flow_lm = &mut value["flow_lm"];+ flow_lm["flow"]["type"] = options["type"].clone();+ flow_lm["z_dim"] = 64.into();+ for key in ["attn_dim", "num_kv_heads", "dim_feedforward"] {+ flow_lm["transformer"][key] = options[key].clone();+ }+ flow_lm["lookup_table"]["rank"] = options["rank"].clone();+ let mut decoder_seanet = value["mimi"]["seanet"].clone();+ decoder_seanet["dimension"] = 128.into();+ value["mimi"]["decoder_seanet"] = decoder_seanet;+ value["mimi"]["decoder_transformer"] = serde_yaml::from_str(+ "{d_model: 128, num_heads: 4, num_layers: 4, layer_scale: 0.01, context: 50, \+ dim_feedforward: 384, input_dimension: 128, output_dimensions: [128]}",+ )+ .unwrap();+ value["mimi"]["outer_dim"] = 128.into();++ let config = Config::parse(&serde_yaml::to_string(&value).unwrap()).unwrap();+ let ptts = config.to_ptts(1, -1.0).unwrap();+ let f = &ptts.flow_lm;+ assert_eq!(f.flow_type, FlowType::Pointwise);+ assert_eq!(+ (f.z_dim, f.attn_dim, f.num_kv_heads),+ (Some(64), Some(192), Some(1))+ );+ assert_eq!((f.dim_feedforward, f.lut_rank), (96, Some(32)));+ // The decoder's dims go to `mimi`, the encoder's to `speaker_mimi`.+ assert_eq!(ptts.mimi.dimension, 128);+ assert_eq!(ptts.mimi.transformer_context, 49);+ let speaker_mimi = ptts.speaker_mimi.as_ref().unwrap();+ assert_eq!(+ (speaker_mimi.prefix.as_str(), speaker_mimi.mimi.dimension),+ ("mimi", 512)+ );+ }+#[test]fn unknown_fields_are_rejected() {let (_, yaml) = CONFIGS.iter().find(|(name, _)| *name == "english").unwrap();@@ -435,9 +525,6 @@ mod tests {.iter().find(|(name, _)| *name == "english_drifting_26-09").unwrap();- assert_eq!(- Config::parse(yaml).unwrap().flow_type().unwrap(),- FlowType::Drifting- );+ assert_eq!(Config::parse(yaml).unwrap().flow_type(), FlowType::Drifting);}}diff --git a/rust/src/defaults.rs b/rust/src/defaults.rsindex ce811c0..23ef1f3 100644--- a/rust/src/defaults.rs+++ b/rust/src/defaults.rs@@ -153,7 +153,7 @@ pub fn predefined_voice_names() -> Vec<&'static str> {/// The state of a predefined voice, precomputed with the released weights of `language`.pub fn get_predefined_voice(language: &str, name: &str) -> String {format!(- "hf://kyutai/pocket-tts-without-voice-cloning/languages/{language}/embeddings/{name}.safetensors@ab248779e0718743c013e20b2d812ace7c8f4bf7"+ "hf://kyutai/pocket-tts-without-voice-cloning/languages/{language}/embeddings/{name}.safetensors@a3055dcb533cf2ec90458008a01e7cef550bae2a")}diff --git a/rust/src/main.rs b/rust/src/main.rsindex 401c372..1dc255e 100644--- a/rust/src/main.rs+++ b/rust/src/main.rs@@ -21,7 +21,7 @@ use model::{LoadOptions, TtsModel, VoiceState};use std::process::ExitCode;use std::sync::atomic::AtomicBool;-const LANGUAGE_HELP: &str = "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'. Incompatible with the config argument. Default is 'english', which is the same model as 'english_2026-09_2'.";+const LANGUAGE_HELP: &str = "Language for the TTS model. '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'.";const CONFIG_HELP: &str = "Path to a model config .yaml file: a local path, an https:// URL, or an hf:// path. Incompatible with the language argument. If not provided, will use the default English model.";#[derive(Parser)]@@ -116,9 +116,9 @@ struct GenerateArgs {/// Noise clamp value#[arg(long, allow_negative_numbers = true)]noise_clamp: Option<f32>,- /// EOS threshold- #[arg(long, default_value_t = defaults::DEFAULT_EOS_THRESHOLD, allow_negative_numbers = true)]- eos_threshold: f32,+ /// EOS threshold. Defaults to the model's value from its config (-4.0).+ #[arg(long, allow_negative_numbers = true)]+ eos_threshold: Option<f32>,/// Number of frames to generate after EOS#[arg(long)]frames_after_eos: Option<usize>,diff --git a/rust/src/model.rs b/rust/src/model.rsindex 72d22b6..995930b 100644--- a/rust/src/model.rs+++ b/rust/src/model.rs@@ -7,7 +7,7 @@ use crate::defaults;use crate::rng::NoiseRng;use crate::text::{TextOptions, prepare_text_prompt, split_into_best_sentences};use crate::tokenizer::{SharedTokenizer, Tokenizer};-use crate::weights::SafetensorsFile;+use crate::weights::{SafetensorsFile, WeightFiles};use anyhow::{Context, Result, bail};use ptts::flow_lm::{FlowLMState, StepInput};use ptts::transformer::{LayerAttentionState, StreamingMHAState, StreamingTransformerState};@@ -43,7 +43,8 @@ pub struct LoadOptions {pub temperature: Option<f32>,pub sampler_decode_steps: usize,pub noise_clamp: Option<f32>,- pub eos_threshold: f32,+ /// The config's `default_eos_threshold` when `None`.+ pub eos_threshold: Option<f32>,}impl Default for LoadOptions {@@ -52,7 +53,7 @@ impl Default for LoadOptions {temperature: None,sampler_decode_steps: defaults::DEFAULT_SAMPLER_DECODE_STEPS,noise_clamp: None,- eos_threshold: defaults::DEFAULT_EOS_THRESHOLD,+ eos_threshold: None,}}}@@ -72,7 +73,7 @@ impl<Q: CpuBackend> VoiceState<Q> {}/// Writes the state as the Python package's `export_model_state` does: per attention layer,- /// `{module}/cache` of shape `[2, batch, time, heads, dim]` and `{module}/offset`.+ /// `{module}/cache` of shape `[2, batch, time, kv_heads, dim]` and `{module}/offset`.pub fn export(&self, path: &Path) -> Result<()> {let mut tensors: Vec<(String, safetensors::Dtype, Vec<usize>, Vec<u8>)> = Vec::new();for (i, layer) in self.transformer_state.layer_states.iter().enumerate() {@@ -124,40 +125,50 @@ pub struct TtsModel<Q: CpuBackend> {tokenizer: Arc<Tokenizer>,text_options: TextOptions,has_voice_cloning: bool,- flow_type: FlowType,rng: Mutex<NoiseRng>,num_layers: usize,- num_heads: usize,- d_model: usize,+ num_kv_heads: usize,+ head_dim: usize,}impl<Q: CpuBackend> TtsModel<Q> {/// Port of `TTSModel.load_model`, for the config already read.pub fn load(config: Config, origin: Origin, options: &LoadOptions) -> Result<Self> {- let flow_type = config.flow_type()?;- // TODO: the separate FlowLM and Mimi checkpoints of training runs (weight-normed Mimi,- // un-renamed FlowLM keys) are not converted; export a single `weights_path` instead.- if config.flow_lm.weights_path.is_some() || config.mimi.weights_path.is_some() {- bail!(- "flow_lm.weights_path and mimi.weights_path are not supported by this binary, use a config with a single weights_path"- )- }- let Some(weights_path) = config.weights_path.as_deref() else {- bail!("No weights_path specified for the TTSModel, the model would be uninitialized")- };- log::info!("Loading TTSModel weights from {weights_path}");+ let mut weight_files = WeightFiles::default();let mut has_voice_cloning = true;- let weights_file = match crate::download::download_if_necessary(weights_path) {- Ok(path) => path,- Err(e) => {- let Some(fallback) = config.weights_path_without_voice_cloning.as_deref() else {- return Err(e);- };- log::debug!("falling back to the weights without voice cloning: {e:#}");- has_voice_cloning = false;- crate::download::download_if_necessary(fallback)?+ if let Some(mimi_path) = config.mimi.weights_path.as_deref() {+ if config.flow_lm.weights_path.is_none() && config.weights_path.is_none() {+ bail!(+ "If you specify mimi.weights_path you should specify flow_lm.weights_path or weights_path"+ )}- };+ log::info!("Loading Mimi weights from {mimi_path}");+ weight_files.mimi = Some(crate::download::download_if_necessary(mimi_path)?);+ }+ if let Some(weights_path) = config.weights_path.as_deref() {+ log::info!("Loading TTSModel weights from {weights_path}");+ let path = match crate::download::download_if_necessary(weights_path) {+ Ok(path) => path,+ Err(e) => {+ let Some(fallback) = config.weights_path_without_voice_cloning.as_deref()+ else {+ return Err(e);+ };+ log::debug!("falling back to the weights without voice cloning: {e:#}");+ has_voice_cloning = false;+ crate::download::download_if_necessary(fallback)?+ }+ };+ weight_files.bundle = Some(path);+ } else if let Some(flow_lm_path) = config.flow_lm.weights_path.as_deref() {+ if weight_files.mimi.is_none() {+ bail!("flow_lm.weights_path needs mimi.weights_path, for the Mimi weights")+ }+ log::info!("Loading FlowLM weights from {flow_lm_path}");+ weight_files.flow_lm = Some(crate::download::download_if_necessary(flow_lm_path)?);+ } else {+ bail!("No weights_path specified for the TTSModel, the model would be uninitialized")+ }let lookup_table = &config.flow_lm.lookup_table;let tokenizer = Arc::new(Tokenizer::load(@@ -166,16 +177,20 @@ impl<Q: CpuBackend> TtsModel<Q> {&lookup_table.tokenizer,)?);- // The drifting head maps the noise in one step, whatever the number of steps asked.- let decode_steps = match flow_type {- FlowType::Drifting => 1,- _ => options.sampler_decode_steps,+ // The drifting and pointwise heads map the noise in one step, whatever the number of+ // steps asked.+ let decode_steps = match config.flow_type() {+ FlowType::Drifting | FlowType::Pointwise => 1,+ FlowType::Lsd | FlowType::FlowMatching => options.sampler_decode_steps,};if decode_steps == 0 {bail!("the number of sampler decode steps must be positive")}- let ptts_config = config.to_ptts(decode_steps, options.eos_threshold)?;- let weights = crate::weights::load(&weights_file, &config)?;+ let eos_threshold = options+ .eos_threshold+ .unwrap_or(config.default_eos_threshold);+ let ptts_config = config.to_ptts(decode_steps, eos_threshold)?;+ let weights = crate::weights::load(&weight_files)?;let model = TTSModel::<Q>::load(&weights.vb,Box::new(SharedTokenizer(tokenizer.clone())),@@ -195,8 +210,8 @@ impl<Q: CpuBackend> TtsModel<Q> {let transformer = &config.flow_lm.transformer;Ok(Self {num_layers: transformer.num_layers,- num_heads: transformer.num_heads,- d_model: transformer.d_model,+ num_kv_heads: transformer.num_kv_heads(),+ head_dim: transformer.head_dim(),text_options: TextOptions::from_config(&config),rng: Mutex::new(NoiseRng::new(temperature, options.noise_clamp)?),config,@@ -205,7 +220,6 @@ impl<Q: CpuBackend> TtsModel<Q> {encoder,tokenizer,has_voice_cloning,- flow_type,})}@@ -279,7 +293,8 @@ impl<Q: CpuBackend> TtsModel<Q> {let voice = VoiceState {transformer_state: state.flow_lm_state.transformer_state,};- let size = 2 * self.num_layers * voice.len() * self.d_model * std::mem::size_of::<f32>();+ let kv_dim = self.num_kv_heads * self.head_dim;+ let size = 2 * self.num_layers * voice.len() * kv_dim * std::mem::size_of::<f32>();log::info!("Size of the model state for audio prompt: {} MB",size / 1_000_000@@ -290,7 +305,7 @@ impl<Q: CpuBackend> TtsModel<Q> {/// Reads a state written by `export-voice`, from this binary or the Python package.fn import_state(&self, path: &Path) -> Result<VoiceState<Q>> {let file = SafetensorsFile::open(path)?;- let dim_per_head = self.d_model / self.num_heads;+ let dim_per_head = self.head_dim;let mut layer_states = Vec::with_capacity(self.num_layers);for i in 0..self.num_layers {let module = format!("transformer.layers.{i}.self_attn");@@ -305,10 +320,10 @@ impl<Q: CpuBackend> TtsModel<Q> {let [2, b, capacity, h, d] = shape[..] else {bail!("{cache_name} has shape {shape:?}, expected [2, batch, time, heads, dim]")};- if b != 1 || h != self.num_heads || d != dim_per_head {+ if b != 1 || h != self.num_kv_heads || d != dim_per_head {bail!("{cache_name} has shape {shape:?}, this model needs [2, 1, _, {}, {dim_per_head}]",- self.num_heads+ self.num_kv_heads)}// States written before the offset was stored hold the position in the length of@@ -463,13 +478,7 @@ impl<Q: CpuBackend> TtsModel<Q> {};let (latent, is_eos) = {let mut rng = self.rng.lock().unwrap_or_else(|e| e.into_inner());- rng.take_drawn();- let (latent, is_eos) = self.model.generate_step(state, input, &mut *rng)?;- let latent = match self.flow_type {- FlowType::Drifting => self.subtract_noise(&latent, &rng.take_drawn())?,- FlowType::Lsd | FlowType::FlowMatching => latent,- };- (latent, is_eos)+ self.model.generate_step(state, input, &mut *rng)?};if is_eos && eos_step.is_none() && generation_step >= MIN_FRAMES_BEFORE_EOS {eos_step = Some(generation_step);@@ -501,34 +510,6 @@ impl<Q: CpuBackend> TtsModel<Q> {Ok(())}- // TODO: upstream to xn-ptts. Without a drifting sampler there, the head runs as one LSD step- // with zeroed time embeddings (see `weights.rs`), which returns `noise + head(noise)`; the- // drifting sample is `head(noise)`.- fn subtract_noise(- &self,- latent: &Tensor<Q::T, Q::B>,- noise: &[f32],- ) -> Result<Tensor<Q::T, Q::B>> {- let values = latent.to_vec()?;- if values.len() != noise.len() {- bail!(- "drew {} noise values for a latent of {}",- noise.len(),- values.len()- )- }- let data = values- .iter()- .zip(noise)- .map(|(v, n)| Q::T::from_f32(v.to_f32() - n))- .collect();- Ok(Tensor::from_vec(- data,- latent.dims().to_vec(),- self.model.device(),- )?)- }-/// Decodes the latents as they come, as many as are queued in one call, and hands the audio/// to `on_chunk`. Returns the number of samples decoded.fn decode_worker(diff --git a/rust/src/rng.rs b/rust/src/rng.rsindex f9137df..43c43f1 100644--- a/rust/src/rng.rs+++ b/rust/src/rng.rs@@ -20,8 +20,6 @@ pub struct NoiseRng {rng: rand::rngs::StdRng,normal: Normal<f32>,clamp: Option<f32>,- /// What was drawn since the last [`Self::take_drawn`].- drawn: Vec<f32>,}impl NoiseRng {@@ -31,15 +29,9 @@ impl NoiseRng {rng: rand::rngs::StdRng::seed_from_u64(seed()),normal,clamp: noise_clamp,- drawn: Vec::new(),})}- /// The values drawn since the previous call, in order.- pub fn take_drawn(&mut self) -> Vec<f32> {- std::mem::take(&mut self.drawn)- }-fn draw(&mut self) -> f32 {let Some(clamp) = self.clamp else {return self.normal.sample(&mut self.rng);@@ -62,9 +54,7 @@ impl NoiseRng {impl ptts::flow_lm::Rng for NoiseRng {fn sample(&mut self) -> f32 {- let value = self.draw();- self.drawn.push(value);- value+ self.draw()}}@@ -78,8 +68,6 @@ mod tests {let mut rng = NoiseRng::new(1.0, Some(0.5)).unwrap();let values: Vec<f32> = (0..1000).map(|_| rng.sample()).collect();assert!(values.iter().all(|v| v.abs() <= 0.5));- assert_eq!(rng.take_drawn(), values);- assert!(rng.take_drawn().is_empty());}#[test]diff --git a/rust/src/weights.rs b/rust/src/weights.rsindex af6edf4..09b31ec 100644--- a/rust/src/weights.rs+++ b/rust/src/weights.rs@@ -1,20 +1,12 @@-//! Loading pocket-tts safetensors weights into xn-ptts.-//!-//! The checkpoint keys are renamed with xn-ptts's own key map, and the few tensors xn-ptts cannot-//! take as they are get rewritten into equivalent ones, written to a small side file loaded after-//! the checkpoint. Each rewrite is exact: it only adds zeros, or scales by a power of two. They-//! are stopgaps, marked TODO, for features xn-ptts does not have yet.+//! Loading pocket-tts safetensors weights into xn-ptts, whose names for them differ, and reading+//! the voice states the Python package writes.-use crate::config::{Config, FlowType};use anyhow::{Context, Result, bail};use std::collections::{HashMap, HashSet};use std::io::{Read, Seek, SeekFrom};use std::path::{Path, PathBuf};-/// Names of the rewritten tensors in the side file, before the prefix is stripped.-const PATCH_PREFIX: &str = "pocket_tts_patch.";const SPEAKER_SINK: &str = "flow_lm.condition_provider.conditioners.speaker_wavs.sink";-const DOWNSAMPLE_WEIGHT: &str = "mimi.downsample.conv.conv.weight";/// Where a tensor sits in a safetensors file.#[derive(Debug, Clone)]@@ -152,186 +144,105 @@ fn remap_key(name: &str) -> Option<String> {Some(name)}-/// A rewritten tensor, f32 whatever the checkpoint's dtype.-struct Patch {- name: String,- shape: Vec<usize>,- data: Vec<f32>,+/// The name in a `TTSModel` of a tensor of a separate flow LM checkpoint, as+/// `get_flow_lm_state_dict` of `pocket_tts/utils/weights_loading.py` renames it.+fn flow_lm_file_key(key: &str) -> Option<String> {+ if key.starts_with("flow.w_s_t.")+ || key == "condition_provider.conditioners.transcript_in_segment.learnt_padding"+ || key == "condition_provider.conditioners.speaker_wavs.learnt_padding"+ || key == "num_ema_updates"+ {+ return None;+ }+ let key = match key {+ "condition_provider.conditioners.transcript_in_segment.embed.weight" => {+ "conditioner.embed.weight"+ }+ "condition_provider.conditioners.speaker_wavs.output_proj.weight" => "speaker_proj_weight",+ "fuser.padding_value" => "bos_before_voice",+ key => key,+ };+ let key = key.replace(".self_attn.in_proj_weight", ".self_attn.in_proj.weight");+ Some(format!("flow_lm.{key}"))}-/// Zero-pads dimension `dim` of a row-major tensor to `new_size`.-fn zero_pad(data: &[f32], shape: &[usize], dim: usize, new_size: usize) -> (Vec<f32>, Vec<usize>) {- let outer: usize = shape[..dim].iter().product();- let inner: usize = shape[dim + 1..].iter().product();- let old_block = shape[dim] * inner;- let new_block = new_size * inner;- let mut out = vec![0.0; outer * new_block];- for o in 0..outer {- out[o * new_block..o * new_block + old_block]- .copy_from_slice(&data[o * old_block..(o + 1) * old_block]);- }- let mut new_shape = shape.to_vec();- new_shape[dim] = new_size;- (out, new_shape)+/// The checkpoint files of a config.+#[derive(Debug, Clone, Default)]+pub struct WeightFiles {+ /// The `flow_lm.*` and `mimi.*` tensors of a `TTSModel`: the config's `weights_path`.+ pub bundle: Option<PathBuf>,+ /// The flow LM alone, without the `flow_lm.` prefix: `flow_lm.weights_path`, used without a+ /// bundle only, as the bundle's flow LM would replace it.+ pub flow_lm: Option<PathBuf>,+ /// The `mimi.*` tensors of a `TTSModel`, replacing those of the bundle: `mimi.weights_path`.+ pub mimi: Option<PathBuf>,}-/// The patches `config` needs on top of the checkpoint `file`.-fn patches(config: &Config, file: &SafetensorsFile) -> Result<Vec<Patch>> {- let mut patches = Vec::new();- let dimension = config.mimi.seanet.dimension;- let latent_dim = config.speaker_latent_dim();+/// The weights as xn-ptts loads them.+pub struct Weights {+ pub vb: xn::nn::Path<xn::CpuDevice>,+}- // TODO: upstream to xn-ptts. Its Mimi encoder downsamples to `dimension` channels and its- // speaker projection reads `dimension` of them, where pocket-tts models since 2026-04 have- // `inner_dim: 32`. Padding the downsampling with zero filters and the projection with zero- // columns gives the same voice embedding.- if latent_dim != dimension {- if file.tensors.contains_key(DOWNSAMPLE_WEIGHT) {- let (data, shape) = file.read_f32(DOWNSAMPLE_WEIGHT)?;- if shape.len() != 3 || shape[0] != latent_dim {- bail!("{DOWNSAMPLE_WEIGHT} has shape {shape:?}, expected [{latent_dim}, ...]")- }- let (data, shape) = zero_pad(&data, &shape, 0, dimension);- patches.push(Patch {- name: DOWNSAMPLE_WEIGHT.to_string(),- shape,- data,- });- }- let speaker_proj = ptts::loader::SPEAKER_PROJ_WEIGHT;- if file.tensors.contains_key(speaker_proj) {- let (data, shape) = file.read_f32(speaker_proj)?;- if shape.len() != 2 || shape[1] != latent_dim {- bail!("{speaker_proj} has shape {shape:?}, expected [_, {latent_dim}]")+/// Memory-maps the checkpoint files.+pub fn load(files: &WeightFiles) -> Result<Weights> {+ // The Mimi file's tensors replace the bundle's: xn-ptts loads the files in order, a later+ // tensor of the same name replacing an earlier one, and those only the bundle has are left+ // out.+ let mimi_keys: Option<HashSet<String>> = match &files.mimi {+ None => None,+ Some(path) => {+ let file = SafetensorsFile::open(path)?;+ let keys: HashSet<String> = file+ .tensors+ .into_keys()+ .filter(|key| key.starts_with("mimi."))+ .collect();+ // TODO: the Mimi checkpoints of training runs (weight-normed, `model.` keys), which+ // `get_mimi_state_dict` converts, are not supported.+ if keys.is_empty() {+ bail!(+ "{} has no mimi.* tensors: only Mimi weights as a TTSModel holds them are supported by this binary",+ path.display()+ )}- let (data, shape) = zero_pad(&data, &shape, 1, dimension);- patches.push(Patch {- name: speaker_proj.to_string(),- shape,- data,- });+ Some(keys)}- }-- // TODO: upstream to xn-ptts. Its flow head always has two time embedders whose outputs it- // averages, as LSD needs. Until it supports the other samplers, they are expressed as LSD:- // - flow_matching has one embedder, fed the step's start time `i / n`, which is what LSD- // feeds the first one. Doubling the first one's output (its final norm's scale) and adding- // a second one that outputs zeros keeps the average equal to it, and both samplers then- // take the same Euler steps.- // - drifting has no time embedder, so both get zero ones; the noise is then subtracted from- // the one-step LSD output, see `model.rs`.- let flow_dim = config.flow_lm.flow.dim;- let time_embed = |i: usize| format!("flow_lm.flow_net.time_embed.{i}");- let zero_time_embedder = |i: usize| {- let prefix = time_embed(i);- [- ("mlp.0.weight", vec![flow_dim, 256]),- ("mlp.0.bias", vec![flow_dim]),- ("mlp.2.weight", vec![flow_dim, flow_dim]),- ("mlp.2.bias", vec![flow_dim]),- ("mlp.3.alpha", vec![flow_dim]),- ("freqs", vec![128]),- ]- .into_iter()- .map(|(name, shape)| Patch {- name: format!("{prefix}.{name}"),- data: vec![0.0; shape.iter().product()],- shape,- })- .collect::<Vec<_>>()};- match config.flow_type()? {- FlowType::Lsd => {}- FlowType::FlowMatching => {- let alpha = format!("{}.mlp.3.alpha", time_embed(0));- let (data, shape) = file.read_f32(&alpha)?;- patches.push(Patch {- name: alpha,- shape,- data: data.iter().map(|v| v * 2.0).collect(),- });- patches.extend(zero_time_embedder(1));+ let (first, separate_flow_lm) = match (&files.bundle, &files.flow_lm) {+ (Some(bundle), _) => (bundle, false),+ (None, Some(flow_lm)) => {+ let file = SafetensorsFile::open(flow_lm)?;+ if let Some(key) = file+ .tensors+ .keys()+ .find(|key| key.starts_with("flow_lm.") || key.starts_with("mimi."))+ {+ bail!(+ "{} is not a flow LM checkpoint: it has a tensor {key}, use it as the config's weights_path",+ flow_lm.display()+ )+ }+ (flow_lm, true)}- FlowType::Drifting => {- patches.extend(zero_time_embedder(0));- patches.extend(zero_time_embedder(1));+ (None, None) => {+ bail!("No weights_path specified for the TTSModel, the model would be uninitialized")}- }- Ok(patches)-}--/// The weights as xn-ptts loads them, with the side file of rewritten tensors, which must-/// outlive them.-pub struct Weights {- pub vb: xn::nn::Path<xn::CpuDevice>,- _patch_dir: Option<tempfile::TempDir>,-}--/// Memory-maps the checkpoint at `path`, with the rewrites `config` needs.-pub fn load(path: &Path, config: &Config) -> Result<Weights> {- let file = SafetensorsFile::open(path)?;- let patches = patches(config, &file)?;- let mut files = vec![path.to_path_buf()];- let mut patch_dir = None;- let patched: HashSet<String> = patches.iter().map(|p| p.name.clone()).collect();- if !patches.is_empty() {- let dir = tempfile::tempdir()?;- let patch_path = dir.path().join("patch.safetensors");- let bytes: Vec<(String, Vec<u8>, Vec<usize>)> = patches- .iter()- .map(|p| {- let bytes = p.data.iter().flat_map(|v| v.to_le_bytes()).collect();- (format!("{PATCH_PREFIX}{}", p.name), bytes, p.shape.clone())- })- .collect();- let views = bytes- .iter()- .map(|(name, bytes, shape)| {- let view = safetensors::tensor::TensorView::new(- safetensors::Dtype::F32,- shape.clone(),- bytes,- )?;- Ok((name.clone(), view))- })- .collect::<Result<Vec<_>, safetensors::SafeTensorError>>()?;- safetensors::tensor::serialize_to_file(views, None, &patch_path)?;- files.push(patch_path);- patch_dir = Some(dir);- }+ };+ let mut paths = vec![first.clone()];+ paths.extend(files.mimi.clone());let key_map = move |name: &str| -> Option<String> {- if let Some(name) = name.strip_prefix(PATCH_PREFIX) {- return Some(name.to_string());- }- let name = remap_key(name)?;- if patched.contains(&name) {- None+ if name.starts_with("mimi.") {+ if mimi_keys.as_ref().is_some_and(|keys| !keys.contains(name)) {+ return None;+ }+ remap_key(name)+ } else if separate_flow_lm {+ remap_key(&flow_lm_file_key(name)?)} else {- Some(name)+ remap_key(name)}};- let vb = xn::nn::VB::load_with_key_map(&files, xn::CPU, key_map)- .with_context(|| format!("cannot load the weights in {}", path.display()))?;- Ok(Weights {- vb: vb.root(),- _patch_dir: patch_dir,- })-}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn zero_pad_keeps_values_in_place() {- // [2, 2] padded to [2, 3] on the last dim.- let (data, shape) = zero_pad(&[1.0, 2.0, 3.0, 4.0], &[2, 2], 1, 3);- assert_eq!(shape, [2, 3]);- assert_eq!(data, [1.0, 2.0, 0.0, 3.0, 4.0, 0.0]);- // [1, 2, 2] padded to [2, 2, 2] on the first dim.- let (data, shape) = zero_pad(&[1.0, 2.0, 3.0, 4.0], &[1, 2, 2], 0, 2);- assert_eq!(shape, [2, 2, 2]);- assert_eq!(data, [1.0, 2.0, 3.0, 4.0, 0.0, 0.0, 0.0, 0.0]);- }+ let vb = xn::nn::VB::load_with_key_map(&paths, xn::CPU, key_map)+ .with_context(|| format!("cannot load the weights in {paths:?}"))?;+ Ok(Weights { vb: vb.root() })}