Skip to content

A TTS that fits in your CPU (and pocket)

Python
5.7 KB
Raw Blame
"""Configuration models for loading YAML config files."""

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"


class StrictModel(BaseModel):
    model_config = ConfigDict(extra="forbid")


# Flow configuration
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), "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"


# Transformer configuration for FlowLM
class FlowLMTransformerConfig(StrictModel):
    hidden_scale: int
    max_period: int
    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):
    dim: int
    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
class FlowLMConfig(StrictModel):
    """Root configuration model for YAML config files."""

    dtype: str

    # 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
    weights_path: str | None = None
    insert_bos_before_voice: bool = False


# SEANet configuration
class SEANetConfig(StrictModel):
    dimension: int
    channels: int
    n_filters: int
    n_residual_layers: int
    ratios: list[int]
    kernel_size: int
    residual_kernel_size: int
    last_kernel_size: int
    dilation_base: int
    pad_mode: str
    compress: int


# Transformer configuration for Mimi
class MimiTransformerConfig(StrictModel):
    d_model: int
    input_dimension: int
    output_dimensions: tuple[int, ...]
    num_heads: int
    num_layers: int
    layer_scale: float
    context: int
    max_period: float = 10000.0
    dim_feedforward: int


# Quantizer configuration
class QuantizerConfig(StrictModel):
    dimension: int
    output_dimension: int


# Root configuration
class MimiConfig(StrictModel):
    """Root configuration model for Mimi YAML config files."""

    dtype: str

    # Sample rate and channels
    sample_rate: int
    channels: int
    frame_rate: float

    # SEANet configurations
    seanet: SEANetConfig

    # Transformer
    transformer: MimiTransformerConfig

    # Quantizer
    quantizer: QuantizerConfig
    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):
    flow_lm: FlowLMConfig
    mimi: MimiConfig
    weights_path: str | None = None
    weights_path_without_voice_cloning: str | None = None
    pad_with_spaces_for_short_inputs: bool = False
    remove_semicolons: bool = False
    append_terminal_punctuation: bool = True
    # Upper-casing the first letter is an orthographic convention of the
    # Latin-script languages this model shipped with. A model whose text is
    # romanised phonemes must switch it off: the capital is not in the phoneme
    # inventory, so the first word's onset becomes the unknown token, and where
    # a capital *is* a phoneme it silently changes the sound ("salAm" -> "SalAm"
    # is /salaam/ -> /shalaam/).
    capitalize_first_letter: bool = True
    # Per-character rewrites applied before tokenization ("" deletes). For characters the model's
    # training text never contained (straight quotes, curly apostrophes in CML-TTS/MLS): their
    # embeddings are untrained and the model speaks filler syllables where they occur.
    replace_characters: dict[str, str] = {}
    model_recommended_frames_after_eos: int | None = None
    # 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:
    yaml_path = download_if_necessary(str(yaml_path))

    if not yaml_path.exists():
        if yaml_path.is_relative_to(CONFIGS_DIR):
            raise FileNotFoundError(
                f"Config file not found: {yaml_path}. "
                f"Did you make a typo? Available languages: {[p.stem for p in CONFIGS_DIR.glob('*.yaml')]}"
            )
        raise FileNotFoundError(f"Config file not found: {yaml_path}. Did you make a typo?")

    with open(yaml_path, encoding="utf-8") as f:
        config_dict = yaml.safe_load(f)

    return Config(**config_dict)