A TTS that fits in your CPU (and pocket)
Python
Replace beartype with ty for type checking (#283)
gabrieldemarmiesse-ai-agent842908a10517
diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.ymlindex 360f799..4575938 100644--- a/.github/workflows/run-tests.yml+++ b/.github/workflows/run-tests.yml@@ -13,6 +13,26 @@ jobs:- name: Run pre-commituses: pre-commit/[email protected]+ ty:+ runs-on: ubuntu-latest+ needs: pre-commit+ strategy:+ fail-fast: false+ matrix:+ python-version: ['3.10', '3.14']+ steps:+ - uses: actions/checkout@v4+ - name: Set up Python ${{ matrix.python-version }}+ uses: actions/setup-python@v4+ with:+ python-version: ${{ matrix.python-version }}+ - name: Install uv+ uses: astral-sh/setup-uv@v7+ - name: Install dependencies+ run: uv sync --dev -p ${{ matrix.python-version }}+ - name: Run ty+ run: uv run -p ${{ matrix.python-version }} ty check+pytest:runs-on: ubuntu-latestneeds: pre-commitdiff --git a/AGENTS.md b/AGENTS.mdindex a03c3f8..f5a3baf 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -118,7 +118,8 @@ This is a pure Python package with Rust extensions in `training/rust_exts/audio_"Running on GPU" section for details.- **Torch Threads**: `torch.set_num_threads(1)` in `tts_model.py` for optimal CPU performance- **dtype**: Models use float32 by default (configurable in YAML)-- **Beartype**: Runtime type checking is enabled via beartype claw in `__init__.py`+- **Type checking**: `ty` checks the whole repo statically (`uv run ty check`, also run in CI).+ There is no runtime type checking.### Adding Featuresdiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex cbd81ab..e9814e5 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -17,6 +17,19 @@ If you want to manually run the pre-commit hooks on all files, use:uvx pre-commit run --all-files```+## Type checking++The code base is type-checked with [ty](https://docs.astral.sh/ty/), which CI runs+alongside the tests:++```bash+uv run ty check+```++There is no runtime type checking: annotations are only verified statically, so keep+them precise (generics need their type arguments, e.g. `dict[str, torch.Tensor]` rather+than `dict`).+## Running tests```bashdiff --git a/pocket_tts/__init__.py b/pocket_tts/__init__.pyindex 05d1d9f..7a839d3 100644--- a/pocket_tts/__init__.py+++ b/pocket_tts/__init__.py@@ -1,22 +1,5 @@-import os--# POCKET_TTS_NO_BEARTYPE=1 disables runtime type-checking: the beartype claw-# wraps every function in the package, which both adds per-call overhead in-# hot training loops and blocks torch.compile (dynamo cannot trace the-# generated wrappers). Inference default is unchanged.-if os.environ.get("POCKET_TTS_NO_BEARTYPE") != "1":- from beartype import BeartypeConf- from beartype.claw import beartype_this_package-- # is_pep484_tower: accept int where float is annotated, as PEP 484 says.- # Without it an `int | float` hint is not redundant and ruff's PYI041- # advice to collapse it would break callers passing ints.- beartype_this_package(conf=BeartypeConf(is_color=False, is_pep484_tower=True))-from pocket_tts.models.model_state import export_model_state-from pocket_tts.models.tts_model import ( # noqa: E402- TTSModel,-)+from pocket_tts.models.tts_model import TTSModel# Public methods:# TTSModel.devicediff --git a/pocket_tts/data/audio.py b/pocket_tts/data/audio.pyindex 734acba..add14e1 100644--- a/pocket_tts/data/audio.py+++ b/pocket_tts/data/audio.py@@ -7,13 +7,13 @@ import loggingimport osimport sysimport wave+from collections.abc import Iteratorfrom contextlib import nullcontextfrom pathlib import Path-from typing import Any+from typing import Any, BinaryIO, TypeGuardimport numpy as npimport torch-from beartype.typing import Iteratorlogger = logging.getLogger(__name__)@@ -65,10 +65,16 @@ class StreamingWAVWriter:def __init__(self, output_stream, sample_rate: int):self.output_stream = output_streamself.sample_rate = sample_rate- self.wave_writer = None- self.first_chunk_buffer = []+ self.wave_writer: wave.Wave_write | None = None+ self.first_chunk_buffer: list[bytes] | None = []self.is_seekable = _is_seekable(output_stream)+ @property+ def _writer(self) -> wave.Wave_write:+ if self.wave_writer is None:+ raise RuntimeError("write_header() must be called before writing audio")+ return self.wave_writer+def write_header(self, sample_rate: int):"""Initialize WAV writer with header."""# For stdout streaming, we need to handle the unseekable stream case@@ -99,11 +105,11 @@ class StreamingWAVWriter:return# Use writeframesraw to avoid frame count validation for streaming- self.wave_writer.writeframesraw(chunk_bytes)+ self._writer.writeframesraw(chunk_bytes)def _flush(self):if self.first_chunk_buffer is not None:- self.wave_writer.writeframesraw(b"".join(self.first_chunk_buffer))+ self._writer.writeframesraw(b"".join(self.first_chunk_buffer))self.first_chunk_buffer = Nonedef finalize(self):@@ -114,16 +120,16 @@ class StreamingWAVWriter:silence_duration_sec = 0.2num_silence_samples = int(self.sample_rate * silence_duration_sec)- self.wave_writer.writeframesraw(bytes(num_silence_samples * 2))+ writer = self._writer+ writer.writeframesraw(bytes(num_silence_samples * 2))- if self.wave_writer:+ if not self.is_seekable:# do not update the header for unseekable streams- if not self.is_seekable:- self.wave_writer._patchheader = lambda: None- self.wave_writer.close()+ writer._patchheader = lambda: None # ty: ignore[unresolved-attribute]+ writer.close()-def is_file_like(obj):+def is_file_like(obj: object) -> TypeGuard[BinaryIO]:"""Check if object has basic file-like methods."""return all(hasattr(obj, attr) for attr in ["write", "close"])@@ -142,6 +148,7 @@ def stream_audio_chunks(path: str | Path | None | Any, audio_chunks: Iterator[torch.Tensor], sample_rate: int):"""Stream audio chunks to a WAV file or stdout, optionally playing them."""+ f: BinaryIO | nullcontext[None]if path == "-":f = sys.stdout.bufferelif path is None:diff --git a/pocket_tts/main.py b/pocket_tts/main.pyindex 72b65df..2152886 100644--- a/pocket_tts/main.py+++ b/pocket_tts/main.py@@ -26,6 +26,7 @@ from pocket_tts.default_parameters import ()from pocket_tts.models.model_state import export_model_statefrom pocket_tts.models.tts_model import TTSModel+from pocket_tts.modules.stateful_module import ModelStatefrom pocket_tts.utils.logging_utils import enable_loggingfrom pocket_tts.utils.utils import _ORIGINS_OF_PREDEFINED_VOICES@@ -44,7 +45,7 @@ cli_app = typer.Typer(tts_model: TTSModel | None = None# State of the voice served when a request doesn't specify one. It is resolved once from the# `serve` options, so that requests never pay for the encoding of the default voice.-default_voice_state: dict | None = None+default_voice_state: ModelState | None = Noneweb_app = FastAPI(title="Kyutai Pocket TTS API", description="Text-to-Speech generation API", version="1.0.0"@@ -62,16 +63,21 @@ web_app.add_middleware()+def _loaded_model() -> TTSModel:+ if tts_model is None:+ raise RuntimeError("no model loaded: `pocket-tts serve` loads it before serving requests")+ return tts_model++@web_app.get("/", response_class=HTMLResponse)async def root():"""Serve the frontend."""static_path = Path(__file__).parent / "static" / "index.html"content = static_path.read_text()# Replace the placeholder with the actual default text prompt- print(str(tts_model.origin))- content = content.replace(- "DEFAULT_TEXT_PROMPT", get_default_text_for_language(str(tts_model.origin))- )+ origin = str(_loaded_model().origin)+ print(origin)+ content = content.replace("DEFAULT_TEXT_PROMPT", get_default_text_for_language(origin))return content@@ -96,13 +102,14 @@ def write_to_queue(queue, text_to_generate, model_state):def close(self):self.queue.put(None)- audio_chunks = tts_model.generate_audio_stream(+ model = _loaded_model()+ audio_chunks = model.generate_audio_stream(model_state=model_state, text_to_generate=text_to_generate)- stream_audio_chunks(FileLikeToQueue(queue), audio_chunks, tts_model.config.mimi.sample_rate)+ stream_audio_chunks(FileLikeToQueue(queue), audio_chunks, model.config.mimi.sample_rate)-def generate_data_with_state(text_to_generate: str, model_state: dict):+def generate_data_with_state(text_to_generate: str, model_state: ModelState):queue = Queue()# Run your function in a thread@@ -152,7 +159,7 @@ def text_to_speech(raise HTTPException(status_code=400, detail="voice_url must start with http://, https://, or hf://")- model_state = tts_model._cached_get_state_for_audio_prompt(voice_url)+ model_state = _loaded_model()._cached_get_state_for_audio_prompt(voice_url)logging.warning("Using voice from URL: %s", voice_url)elif voice_wav is not None:# Use uploaded voice file - preserve extension for format detection@@ -165,7 +172,9 @@ def text_to_speech(# Close the file before reading it back (required on Windows)try:- model_state = tts_model.get_state_for_audio_prompt(Path(temp_file_path), truncate=True)+ model_state = _loaded_model().get_state_for_audio_prompt(+ Path(temp_file_path), truncate=True+ )finally:os.unlink(temp_file_path)elif default_voice_state is not None:@@ -237,7 +246,7 @@ def serve(@cli_app.command()def generate(- text: Annotated[str, typer.Option(help="Text to generate")] = None,+ text: Annotated[str | None, typer.Option(help="Text to generate")] = None,voice: Annotated[str | None,typer.Option(@@ -292,10 +301,12 @@ def generate("value from its config (0.3 for the English model, 0.7 otherwise)."),] = None,- noise_clamp: Annotated[float, typer.Option(help="Noise clamp value")] = DEFAULT_NOISE_CLAMP,+ 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,frames_after_eos: Annotated[- int, typer.Option(help="Number of frames to generate after EOS")+ int | None, typer.Option(help="Number of frames to generate after EOS")] = DEFAULT_FRAMES_AFTER_EOS,output_path: Annotated[str, typer.Option(help="Output path for generated audio")diff --git a/pocket_tts/models/flow_lm.py b/pocket_tts/models/flow_lm.pyindex 8eb0263..259d667 100644--- a/pocket_tts/models/flow_lm.py+++ b/pocket_tts/models/flow_lm.py@@ -1,12 +1,13 @@import logging+from collections.abc import Callablefrom functools import partialimport torch-from beartype.typing import Callablefrom torch import nnfrom typing_extensions import Selffrom pocket_tts.modules.mlp import SimpleMLPAdaLN+from pocket_tts.modules.stateful_module import ModelStatefrom pocket_tts.modules.text_conditioner import LUTConditionerfrom pocket_tts.modules.transformer import StreamingTransformerfrom pocket_tts.utils.config import FlowLMConfig@@ -68,6 +69,15 @@ class FlowLMModel(nn.Module):**kwargs: Additional parameters for the transformer encoder."""+ # Latent normalization buffers (register_buffer in __init__).+ emb_std: torch.Tensor+ emb_mean: torch.Tensor+ # Voice-conditioning projection, created by whoever loads the weights+ # (TTSModel, training.modules.builders) since it only exists with voice cloning.+ speaker_proj_weight: nn.Parameter+ # Only exists when insert_bos_before_voice is set.+ bos_before_voice: nn.Parameter+def __init__(self,conditioner: LUTConditioner,@@ -112,7 +122,7 @@ class FlowLMModel(nn.Module):self,sequence: torch.Tensor,text_embeddings: torch.Tensor,- model_state: dict,+ model_state: ModelState,sampler_decode_steps: int,temp: float,noise_clamp: float | None,@@ -155,7 +165,7 @@ class FlowLMModel(nn.Module):return decode(conditioned_flow, noise, sampler_decode_steps), out_eosdef backbone(- self, input_, text_embeddings: torch.Tensor, sequence, model_state: dict+ self, input_, text_embeddings: torch.Tensor, sequence, model_state: ModelState) -> torch.Tensor:# Most of the time, one of those two tensors is empty, it allows us# to input text or audio embeddings into the model without adding an@@ -176,7 +186,7 @@ class FlowLMModel(nn.Module):self,sequence: torch.Tensor,text_embeddings: torch.Tensor,- model_state: dict,+ model_state: ModelState,sampler_decode_steps: int,temp: float,noise_clamp: float | None,diff --git a/pocket_tts/models/tts_model.py b/pocket_tts/models/tts_model.pyindex 2fb6a7a..2c0e7e1 100644--- a/pocket_tts/models/tts_model.py+++ b/pocket_tts/models/tts_model.py@@ -8,6 +8,7 @@ import threadingimport timefrom functools import lru_cachefrom pathlib import Path+from typing import Anyimport safetensorsimport safetensors.torch@@ -30,7 +31,12 @@ from pocket_tts.models.flow_lm import FlowLMModelfrom pocket_tts.models.mimi import build_mimifrom pocket_tts.models.model_state import _import_model_state, _is_safetensors_sourcefrom pocket_tts.models.text_chunking import prepare_text_prompt, split_into_best_sentences-from pocket_tts.modules.stateful_module import StatefulModule, increment_steps, init_states+from pocket_tts.modules.stateful_module import (+ ModelState,+ StatefulModule,+ increment_steps,+ init_states,+)from pocket_tts.quantization import RECOMMENDED_CONFIG, apply_dynamic_int8from pocket_tts.utils.config import CONFIGS_DIR, Config, load_configfrom pocket_tts.utils.utils import (@@ -50,6 +56,11 @@ from pocket_tts.utils.weights_loading import (torch.set_num_threads(1)logger = logging.getLogger(__name__)+# Generated latents handed to the Mimi decoder thread; None closes the stream.+LatentQueue = queue.Queue[torch.Tensor | None]+# Decoder thread -> generator: ("chunk", audio), ("done", None) or ("error", exception).+ResultQueue = queue.Queue[tuple[str, Any]]+def stamp_state_names(tts_model) -> None:"""StatefulModules find their slice of the state dict by absolute name."""@@ -168,6 +179,8 @@ class TTSModel(nn.Module):try:bundle = download_if_necessary(config.weights_path)except Exception:+ if config.weights_path_without_voice_cloning is None:+ raiseself.has_voice_cloning = Falsebundle = download_if_necessary(config.weights_path_without_voice_cloning)bundled = safetensors.torch.load_file(bundle)@@ -231,6 +244,8 @@ class TTSModel(nn.Module):try:weights_file = download_if_necessary(config.weights_path)except Exception:+ if config.weights_path_without_voice_cloning is None:+ raisetts_model.has_voice_cloning = Falseweights_file = download_if_necessary(config.weights_path_without_voice_cloning)@@ -340,20 +355,20 @@ class TTSModel(nn.Module):)if Path(suffix_source).suffix not in (".yaml", ".yml"):raise ValueError("Config should be a path to a YAML file ending with .yaml")- config = load_config(config_path)+ model_config = load_config(config_path)if temp is None:- temp = config.default_temperature+ temp = model_config.default_temperaturelogger.info(f"Loading model from config at {config_path}...")origin = Path(config_path)if checkpoint is not None:- tts_model = TTSModel._from_pydantic_config(- config, temp, sampler_decode_steps, noise_clamp, eos_threshold, origin=origin+ tts_model = cls._from_pydantic_config(+ model_config, temp, sampler_decode_steps, noise_clamp, eos_threshold, origin=origin)tts_model.load_training_checkpoint(checkpoint)else:- tts_model = TTSModel._from_pydantic_config_with_weights(- config, temp, sampler_decode_steps, noise_clamp, eos_threshold, origin=origin+ tts_model = cls._from_pydantic_config_with_weights(+ model_config, temp, sampler_decode_steps, noise_clamp, eos_threshold, origin=origin)if quantize:@@ -363,7 +378,7 @@ class TTSModel(nn.Module):def _run_flow_lm_and_increment_step(self,- model_state: dict,+ model_state: ModelState,text_tokens: torch.Tensor | None = None,backbone_input_latents: torch.Tensor | None = None,audio_conditioning: torch.Tensor | None = None,@@ -394,7 +409,7 @@ class TTSModel(nn.Module):def _run_flow_lm(self,- model_state: dict,+ model_state: ModelState,text_tokens: torch.Tensor,backbone_input_latents: torch.Tensor,audio_conditioning: torch.Tensor,@@ -430,7 +445,7 @@ class TTSModel(nn.Module):conditioning = F.linear(latents, self.flow_lm.speaker_proj_weight)return conditioning- def _expand_kv_cache(self, model_state: dict, sequence_length: int) -> None:+ def _expand_kv_cache(self, model_state: ModelState, sequence_length: int) -> None:"""Expand KV cache back to full sequence_length for generation.When a model state is retrieved from cache with sliced KV caches,@@ -463,7 +478,7 @@ class TTSModel(nn.Module):expanded_cache[:, :, :current_length, :, :] = cachemodule_state["cache"] = expanded_cache- def _flow_lm_current_end(self, model_state: dict) -> int:+ def _flow_lm_current_end(self, model_state: ModelState) -> int:for module_state in model_state.values():offset = module_state.get("offset")if offset is not None:@@ -476,8 +491,8 @@ class TTSModel(nn.Module):@torch.no_graddef _decode_audio_worker(self,- latents_queue: queue.Queue,- result_queue: queue.Queue,+ latents_queue: LatentQueue,+ result_queue: ResultQueue,mimi_sequence_length: int,mimi_steps_per_latent: int,):@@ -517,7 +532,7 @@ class TTSModel(nn.Module):@torch.no_graddef generate_audio(self,- model_state: dict,+ model_state: ModelState,text_to_generate: str,max_tokens: int = MAX_TOKEN_PER_CHUNK,frames_after_eos: int | None = None,@@ -585,7 +600,7 @@ class TTSModel(nn.Module):@torch.no_graddef generate_audio_stream(self,- model_state: dict,+ model_state: ModelState,text_to_generate: str,max_tokens: int = MAX_TOKEN_PER_CHUNK,frames_after_eos: int | None = None,@@ -673,7 +688,11 @@ class TTSModel(nn.Module):@torch.no_graddef _generate_audio_stream_short_text(- self, model_state: dict, text_to_generate: str, frames_after_eos: int, copy_state: bool+ self,+ model_state: ModelState,+ text_to_generate: str,+ frames_after_eos: int,+ copy_state: bool,):if copy_state:model_state = copy.deepcopy(model_state)@@ -685,8 +704,8 @@ class TTSModel(nn.Module):mimi_sequence_length = max_gen_len * mimi_steps_per_latent# Set up multithreaded generation and decoding- latents_queue = queue.Queue()- result_queue = queue.Queue()+ latents_queue: LatentQueue = queue.Queue()+ result_queue: ResultQueue = queue.Queue()# Start decoder worker threaddecoder_thread = threading.Thread(@@ -748,12 +767,12 @@ class TTSModel(nn.Module):@torch.no_graddef _generate(self,- model_state: dict,+ model_state: ModelState,prepared: torch.Tensor,max_gen_len: int,frames_after_eos: int,- latents_queue: queue.Queue,- result_queue: queue.Queue,+ latents_queue: LatentQueue,+ result_queue: ResultQueue,):token_count = prepared.shape[1]current_end = self._flow_lm_current_end(model_state)@@ -783,7 +802,11 @@ class TTSModel(nn.Module):@torch.no_graddef _autoregressive_generation(- self, model_state: dict, max_gen_len: int, frames_after_eos: int, latents_queue: queue.Queue+ self,+ model_state: ModelState,+ max_gen_len: int,+ frames_after_eos: int,+ latents_queue: LatentQueue,):backbone_input = torch.full((1, 1, self.flow_lm.ldim),@@ -821,13 +844,13 @@ class TTSModel(nn.Module):@lru_cache(maxsize=2)def _cached_get_state_for_audio_prompt(self, audio_conditioning: Path | str | torch.Tensor, truncate: bool = False- ) -> dict:+ ) -> ModelState:return self.get_state_for_audio_prompt(audio_conditioning, truncate)@torch.no_graddef get_state_for_audio_prompt(self, audio_conditioning: Path | str | torch.Tensor, truncate: bool = False- ) -> dict:+ ) -> ModelState:"""Create model state conditioned on audio prompt for continuation.This method processes an audio prompt and creates a model state thatdiff --git a/pocket_tts/modules/attention.py b/pocket_tts/modules/attention.pyindex 87bb8e1..9cce318 100644--- a/pocket_tts/modules/attention.py+++ b/pocket_tts/modules/attention.py@@ -3,7 +3,7 @@ from torch import nnfrom torch.nn import functional as Ffrom pocket_tts.modules.rope import RotaryEmbedding-from pocket_tts.modules.stateful_module import StatefulModule+from pocket_tts.modules.stateful_module import ModelState, StatefulModuledef complete_kv(@@ -154,21 +154,24 @@ class StreamingMultiheadAttention(StatefulModule):def init_state(self, batch_size: int, sequence_length: int) -> dict[str, torch.Tensor]:weight = self.in_proj.weight- if callable(weight):+ if isinstance(weight, torch.Tensor):+ device = weight.device+ dtype = weight.dtype+ else:# torch.ao dynamic-quantized Linear: weight is a method returning a# qint8 tensor, but activations stay float32 — that's what the cache holds.device = weight().devicedtype = torch.float32- else:- device = weight.device- dtype = weight.dtypereturn self._cache_backend.init_state(batch_size, sequence_length, device, dtype)- def increment_step(self, state: dict, increment: int = 1):+ def increment_step(self, state: dict[str, torch.Tensor], increment: int = 1):self._cache_backend.increment_step(state, increment)def forward(- self, query: torch.Tensor, model_state: dict | None, attn_mask: torch.Tensor | None = None+ self,+ query: torch.Tensor,+ model_state: ModelState | None,+ attn_mask: torch.Tensor | None = None,):state = None if model_state is None else self.get_state(model_state)diff --git a/pocket_tts/modules/conv.py b/pocket_tts/modules/conv.pyindex 4a1c8de..56470b7 100644--- a/pocket_tts/modules/conv.py+++ b/pocket_tts/modules/conv.py@@ -5,7 +5,7 @@ import torchfrom torch import nnfrom torch.nn import functional as F-from pocket_tts.modules.stateful_module import StatefulModule+from pocket_tts.modules.stateful_module import ModelState, StatefulModuledef get_extra_padding_for_conv1d(@@ -90,7 +90,7 @@ class StreamingConv1d(StatefulModule):first = torch.ones(batch_size, dtype=torch.bool, device=device)return dict(previous=previous, first=first)- def forward(self, x, model_state: dict | None):+ def forward(self, x, model_state: ModelState | None):B, C, T = x.shapeS = self._strideassert T > 0 and T % S == 0, "Steps must be multiple of stride"@@ -148,7 +148,7 @@ class StreamingConvTranspose1d(StatefulModule):device = self.convtr.weight.devicereturn dict(partial=torch.zeros(batch_size, self.convtr.out_channels, K - S, device=device))- def forward(self, x, mimi_state: dict):+ def forward(self, x, mimi_state: ModelState):layer_state = self.get_state(mimi_state)["partial"]y = self.convtr(x)PT = layer_state.shape[-1]diff --git a/pocket_tts/modules/mlp.py b/pocket_tts/modules/mlp.pyindex 6c4f695..aca0a8a 100644--- a/pocket_tts/modules/mlp.py+++ b/pocket_tts/modules/mlp.py@@ -180,7 +180,7 @@ class SimpleMLPAdaLN(nn.Module):flow_dim = config.dimflow_depth = config.depthnum_time_conds = 1 if config.type == "flow_matching" else 2- return SimpleMLPAdaLN(+ return cls(latent_dim, flow_dim, latent_dim, cond_dim, flow_depth, num_time_conds=num_time_conds)diff --git a/pocket_tts/modules/resample.py b/pocket_tts/modules/resample.pyindex f0dea7c..3b3c427 100644--- a/pocket_tts/modules/resample.py+++ b/pocket_tts/modules/resample.py@@ -2,6 +2,7 @@ import torchfrom torch import nnfrom pocket_tts.modules.conv import StreamingConv1d, StreamingConvTranspose1d+from pocket_tts.modules.stateful_module import ModelStateclass ConvDownsample1d(nn.Module):@@ -25,7 +26,7 @@ class ConvDownsample1d(nn.Module):pad_mode="replicate",)- def forward(self, x: torch.Tensor, model_state: dict | None):+ def forward(self, x: torch.Tensor, model_state: ModelState | None):return self.conv(x, model_state)@@ -47,5 +48,5 @@ class ConvTrUpsample1d(nn.Module):bias=False,)- def forward(self, x: torch.Tensor, model_state: dict | None):+ def forward(self, x: torch.Tensor, model_state: ModelState | None):return self.convtr(x, model_state)diff --git a/pocket_tts/modules/seanet.py b/pocket_tts/modules/seanet.pyindex 9ceff05..bb471ef 100644--- a/pocket_tts/modules/seanet.py+++ b/pocket_tts/modules/seanet.py@@ -3,6 +3,8 @@ from collections.abc import Sequenceimport numpy as npimport torch.nn as nn+from pocket_tts.modules.stateful_module import ModelState+from .conv import StreamingConv1d, StreamingConvTranspose1d@@ -32,7 +34,7 @@ class SEANetResnetBlock(nn.Module):]self.block = block- def forward(self, x, model_state: dict | None):+ def forward(self, x, model_state: ModelState | None):v = xfor layer in self.block:if isinstance(layer, StreamingConv1d):@@ -106,7 +108,7 @@ class SEANetEncoder(nn.Module):self.model = model- def forward(self, x, model_state: dict | None):+ def forward(self, x, model_state: ModelState | None):for layer in self.model:if isinstance(layer, (StreamingConv1d, SEANetResnetBlock)):x = layer(x, model_state)@@ -173,7 +175,7 @@ class SEANetDecoder(nn.Module):]self.model = model- def forward(self, z, model_state: dict | None):+ def forward(self, z, model_state: ModelState | None):for layer in self.model:if isinstance(layer, (StreamingConvTranspose1d, SEANetResnetBlock, StreamingConv1d)):z = layer(z, model_state)diff --git a/pocket_tts/modules/stateful_module.py b/pocket_tts/modules/stateful_module.pyindex 3d030aa..6520de8 100644--- a/pocket_tts/modules/stateful_module.py+++ b/pocket_tts/modules/stateful_module.py@@ -3,11 +3,13 @@ from abc import ABC, abstractmethodimport torchfrom torch import nn+# Streaming state of a whole model: one dict of tensors per StatefulModule, keyed by+# the module's absolute name (see stamp_state_names).+ModelState = dict[str, dict[str, torch.Tensor]]-def init_states(- model: nn.Module, batch_size: int, sequence_length: int-) -> dict[str, dict[str, torch.Tensor]]:- result = {}++def init_states(model: nn.Module, batch_size: int, sequence_length: int) -> ModelState:+ result: ModelState = {}for module_name, module in model.named_modules():if not isinstance(module, StatefulModule):continue@@ -16,9 +18,7 @@ def init_states(return result-def increment_steps(- module: nn.Module, model_state: dict[str, dict[str, torch.Tensor]], increment: int = 1-):+def increment_steps(module: nn.Module, model_state: ModelState, increment: int = 1):# print("incrementing steps by", increment)for module_name, module in module.named_modules():if not isinstance(module, StatefulModule):@@ -28,17 +28,22 @@ def increment_steps(class StatefulModule(ABC, nn.Module):def __init__(self, *args, **kwds):- self._module_absolute_name = None+ self._module_absolute_name: str | None = Nonereturn super().__init__(*args, **kwds)@abstractmethod- def init_state(self, batch_size: int, sequence_length: int):+ def init_state(self, batch_size: int, sequence_length: int) -> dict[str, torch.Tensor]:"""Initialize the state."""raise NotImplementedError- def increment_step(self, state: dict, increment: int = 1):+ def increment_step(self, state: dict[str, torch.Tensor], increment: int = 1):pass- def get_state(self, model_state: dict[str, dict[str, torch.Tensor]]) -> dict[str, torch.Tensor]:+ def get_state(self, model_state: ModelState) -> dict[str, torch.Tensor]:"""Get the state for this module from the model state."""- return model_state[self._module_absolute_name]+ name = self._module_absolute_name+ if name is None:+ raise RuntimeError(+ f"{type(self).__name__} has no absolute name: call stamp_state_names() first"+ )+ return model_state[name]diff --git a/pocket_tts/modules/text_conditioner.py b/pocket_tts/modules/text_conditioner.pyindex 056f28c..3fa5c78 100644--- a/pocket_tts/modules/text_conditioner.py+++ b/pocket_tts/modules/text_conditioner.py@@ -24,8 +24,8 @@ class SentencePieceTokenizer:def __init__(self, nbins: int, tokenizer_path: str) -> None:logger.info("Loading sentencepiece tokenizer from %s", tokenizer_path)- tokenizer_path = download_if_necessary(tokenizer_path)- self.sp = sentencepiece.SentencePieceProcessor(str(tokenizer_path))+ local_path = download_if_necessary(tokenizer_path)+ self.sp = sentencepiece.SentencePieceProcessor(str(local_path))assert nbins == self.sp.vocab_size(), (f"sentencepiece tokenizer has vocab size={self.sp.vocab_size()} but nbins={nbins} was specified")diff --git a/pocket_tts/modules/transformer.py b/pocket_tts/modules/transformer.pyindex 69cdb19..0dcb648 100644--- a/pocket_tts/modules/transformer.py+++ b/pocket_tts/modules/transformer.py@@ -6,10 +6,16 @@ from typing_extensions import Selffrom pocket_tts.modules.attention import StreamingMultiheadAttention, _cached_causal_maskfrom pocket_tts.modules.layer_scale import LayerScalefrom pocket_tts.modules.rope import RotaryEmbedding+from pocket_tts.modules.stateful_module import ModelStatefrom pocket_tts.utils.config import FlowLMTransformerConfigclass StreamingTransformerLayer(nn.Module):+ # nn.Linear when built; quantization (pocket_tts.quantization) swaps in the+ # backend's int8 dynamic Linear, which is not an nn.Linear subclass.+ linear1: nn.Module+ linear2: nn.Module+def __init__(self,d_model: int,@@ -43,7 +49,7 @@ class StreamingTransformerLayer(nn.Module):return x_orig.to(update) + self.layer_scale_2(update)def _sa_block(- self, x: torch.Tensor, model_state: dict | None, attn_mask: torch.Tensor | None = None+ self, x: torch.Tensor, model_state: ModelState | None, attn_mask: torch.Tensor | None = None) -> torch.Tensor:x_orig = xx = self.norm1(x)@@ -51,7 +57,7 @@ class StreamingTransformerLayer(nn.Module):return x_orig.to(update) + self.layer_scale_1(update)def forward(- self, x: torch.Tensor, model_state: dict | None, attn_mask: torch.Tensor | None = None+ self, x: torch.Tensor, model_state: ModelState | None, attn_mask: torch.Tensor | None = None) -> torch.Tensor:x = self._sa_block(x, model_state, attn_mask)x = self._ff_block(x)@@ -65,13 +71,14 @@ class StreamingTransformer(nn.Module):num_heads: int,num_layers: int,layer_scale: float | None = None,- dim_feedforward: int | list[int] = 2048,+ dim_feedforward: int = 2048,context: int | None = None,max_period: float = 10_000.0,):super().__init__()assert d_model % num_heads == 0self.max_period = max_period+ self.context = contextself.rope = RotaryEmbedding(max_period=max_period)@@ -99,12 +106,12 @@ class StreamingTransformer(nn.Module):max_period=float(config.max_period),)- def forward(self, x: torch.Tensor, model_state: dict | None):+ def forward(self, x: torch.Tensor, model_state: ModelState | None):attn_mask = Noneif model_state is None:# Stateless (training) path: one shared mask for all layers, built# outside any compiled region.- attn_mask = _cached_causal_mask(x.shape[1], self.layers[0].self_attn.context, x.device)+ attn_mask = _cached_causal_mask(x.shape[1], self.context, x.device)for layer in self.layers:x = layer(x, model_state, attn_mask=attn_mask)return x@@ -146,7 +153,7 @@ class ProjectedTransformer(nn.Module):else:self.output_projs.append(nn.Linear(d_model, output_dimension, bias=False))- def forward(self, x, model_state: dict | None):+ def forward(self, x, model_state: ModelState | None):x = x.transpose(1, 2)if self.input_proj is not None:x = self.input_proj(x)diff --git a/pocket_tts/quantization.py b/pocket_tts/quantization.pyindex 9436fc4..f037208 100644--- a/pocket_tts/quantization.py+++ b/pocket_tts/quantization.py@@ -15,6 +15,9 @@ import platformimport torchimport torch.nn as nn+from pocket_tts.models.flow_lm import FlowLMModel+from pocket_tts.modules.transformer import StreamingTransformerLayer+logger = logging.getLogger(__name__)# Used by load_model(quantize=True) to specify which layer groups to quantize.@@ -33,7 +36,7 @@ def _get_backend():if importlib.util.find_spec("torchao") is None:return "torch.ao"- import torchao+ import torchao # ty: ignore[unresolved-import] -- optional extraif hasattr(torchao, "_C") or not getattr(torchao, "_SKIPPED_CPP_EXTENSIONS", False):return "torchao"@@ -44,7 +47,10 @@ def _get_backend():def _quantize_module_torchao(module: nn.Module):"""Apply int8 dynamic quantization using torchao."""- from torchao.quantization import Int8DynamicActivationInt8WeightConfig, quantize_+ from torchao.quantization import ( # ty: ignore[unresolved-import] -- optional extra+ Int8DynamicActivationInt8WeightConfig,+ quantize_,+ )quantize_(module, Int8DynamicActivationInt8WeightConfig())@@ -57,7 +63,7 @@ def _ensure_quantization_engine():torch.backends.quantized.engine = "fbgemm"-def apply_dynamic_int8(flow_lm: nn.Module, quantize_groups: set[str]) -> nn.Module:+def apply_dynamic_int8(flow_lm: FlowLMModel, quantize_groups: set[str]) -> FlowLMModel:"""Apply dynamic int8 quantization to the specified layer groups of a FlowLM model.@@ -88,12 +94,13 @@ def apply_dynamic_int8(flow_lm: nn.Module, quantize_groups: set[str]) -> nn.Modureturn flow_lm-def _apply_torchao(flow_lm: nn.Module, quantize_groups: set[str]) -> None:+def _apply_torchao(flow_lm: FlowLMModel, quantize_groups: set[str]) -> None:"""Apply quantization using torchao backend."""if "flow_net" in quantize_groups:_quantize_module_torchao(flow_lm.flow_net)for layer in flow_lm.transformer.layers:+ assert isinstance(layer, StreamingTransformerLayer)if "attention" in quantize_groups:_quantize_module_torchao(layer.self_attn)@@ -106,7 +113,7 @@ def _apply_torchao(flow_lm: nn.Module, quantize_groups: set[str]) -> None:layer.linear2 = wrapper2[0]-def _apply_torch_ao(flow_lm: nn.Module, quantize_groups: set[str]) -> None:+def _apply_torch_ao(flow_lm: FlowLMModel, quantize_groups: set[str]) -> None:"""Apply quantization using deprecated torch.ao backend (fallback)."""from torch.ao.quantization import quantize_dynamic@@ -116,6 +123,7 @@ def _apply_torch_ao(flow_lm: nn.Module, quantize_groups: set[str]) -> None:quantize_dynamic(flow_lm.flow_net, {nn.Linear}, dtype=torch.qint8, inplace=True)for layer in flow_lm.transformer.layers:+ assert isinstance(layer, StreamingTransformerLayer)if "attention" in quantize_groups:quantize_dynamic(layer.self_attn, {nn.Linear}, dtype=torch.qint8, inplace=True)diff --git a/pocket_tts/utils/utils.py b/pocket_tts/utils/utils.pyindex 78edad4..da55348 100644--- a/pocket_tts/utils/utils.py+++ b/pocket_tts/utils/utils.py@@ -3,6 +3,7 @@ import loggingimport osimport timefrom pathlib import Path+from typing import Anyfrom urllib.parse import urlparseimport requests@@ -63,7 +64,7 @@ def print_nb_parameters(model: nn.Module, model_name: str):logger.info("Total number of parameters in %s: %,d", model_name, total)-def size_of_dict(state_dict: dict) -> int:+def size_of_dict(state_dict: dict[str, Any]) -> int:total_size = 0for value in state_dict.values():if isinstance(value, torch.Tensor):@@ -77,8 +78,8 @@ class display_execution_time:def __init__(self, task_name: str, print_output: bool = True):self.task_name = task_nameself.print_output = print_output- self.start_time = None- self.elapsed_time_ms = None+ self.start_time: float | None = None+ self.elapsed_time_ms: int | None = Noneself.logger = logging.getLogger(__name__)def __enter__(self):@@ -87,6 +88,7 @@ class display_execution_time:def __exit__(self, exc_type, exc_val, exc_tb):end_time = time.monotonic()+ assert self.start_time is not None, "__exit__ without __enter__"self.elapsed_time_ms = int((end_time - self.start_time) * 1000)if self.print_output:self.logger.info("%s took %d ms", self.task_name, self.elapsed_time_ms)diff --git a/pocket_tts/utils/weights_loading.py b/pocket_tts/utils/weights_loading.pyindex 78224ce..23d22d7 100644--- a/pocket_tts/utils/weights_loading.py+++ b/pocket_tts/utils/weights_loading.py@@ -4,8 +4,8 @@ import safetensorsimport torch-def get_flow_lm_state_dict(path: Path) -> dict:- state_dict = {}+def get_flow_lm_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:for key in f.keys():if (@@ -30,8 +30,8 @@ def get_flow_lm_state_dict(path: Path) -> dict:return state_dict-def get_mimi_state_dict(path: Path) -> dict:- state_dict = {}+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:for key in f.keys():if (@@ -81,7 +81,7 @@ def get_mimi_state_dict(path: Path) -> dict:def get_training_checkpoint_state_dicts(path: str | Path, use_ema: bool = True-) -> tuple[dict, dict]:+) -> tuple[dict[str, torch.Tensor], dict[str, torch.Tensor]]:"""(flow_lm, mimi) state dicts from a training checkpoint (.pt).Training checkpoints hold the trainable model under "model" and, when thediff --git a/pyproject.toml b/pyproject.tomlindex 4d1127b..8a98d34 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -10,7 +10,6 @@ dependencies = ["torch>=2.5.0","pydantic>=2","sentencepiece>=0.2.1",- "beartype>=0.22.5","safetensors>=0.4.0","typer>=0.10.0","typing_extensions>=4.0.0",@@ -50,6 +49,7 @@ dev = ["tqdm>=4.60","utmos-pytorch>=0.1.0","whisper-normalizer>=0.0.10",+ "ty>=0.0.77",]@@ -79,3 +79,17 @@ python-preference = "only-managed"[tool.ruff.lint.flake8-tidy-imports]ban-relative-imports = "all"++[tool.ty.src]+# The example notebook imports IPython, which is not a dependency.+exclude = ["docs/"]++[tool.ty.rules]+missing-type-argument = "error"++[[tool.ty.overrides]]+# The torch.ao fallback is deliberately on a deprecated API (see the module docstring).+include = ["pocket_tts/quantization.py"]++[tool.ty.overrides.rules]+deprecated = "ignore"diff --git a/scripts/evaluate_quantization.py b/scripts/evaluate_quantization.pyindex 4906f0d..2c31be2 100644--- a/scripts/evaluate_quantization.py+++ b/scripts/evaluate_quantization.py@@ -23,9 +23,10 @@ import timefrom dataclasses import asdict, dataclass, fieldfrom datetime import datetimefrom pathlib import Path-from typing import Optional+from typing import Any, Optionalimport numpy as np+import numpy.typing as nptimport scipy.io.wavfileimport torch@@ -115,7 +116,7 @@ class QualityResult:@dataclassclass ConfigSummary:config_id: str- quantize_groups: list+ quantize_groups: list[str]model_size_mb: floatload_time_sec: floatmean_rts: float@@ -126,8 +127,8 @@ class ConfigSummary:mean_pesq: Optional[float] = Nonemean_wer_baseline: Optional[float] = Nonemean_wer_quantized: Optional[float] = None- results: list = field(default_factory=list)- quality_results: list = field(default_factory=list)+ results: list[GenerationResult] = field(default_factory=list)+ quality_results: list[QualityResult] = field(default_factory=list)def load_and_quantize_model(config_id: str):@@ -229,11 +230,11 @@ def compute_snr(baseline_audio: torch.Tensor, quantized_audio: torch.Tensor) ->def compute_pesq(- baseline_audio: np.ndarray, quantized_audio: np.ndarray, sample_rate: int+ baseline_audio: npt.NDArray[Any], quantized_audio: npt.NDArray[Any], sample_rate: int) -> Optional[float]:"""Compute PESQ score. Returns None if pesq is not installed."""try:- from pesq import pesq+ from pesq import pesq # ty: ignore[unresolved-import] -- optionalexcept ImportError:return None@@ -266,7 +267,7 @@ def compute_pesq(return None-def compute_wer(audio_path: str, reference_text: str, whisper_model) -> tuple[float, str]:+def compute_wer(audio_path: str, reference_text: str, whisper_model) -> tuple[Optional[float], str]:"""Compute Word Error Rate using Whisper. Returns (wer, transcript)."""try:from jiwer import wer@@ -561,7 +562,7 @@ def main():# Load Whisper model oncewhisper_model = Nonetry:- import whisper+ import whisper # ty: ignore[unresolved-import] -- optionallogger.info("Loading Whisper model for WER evaluation...")whisper_model = whisper.load_model("base")diff --git a/tests/test_generation_regressions.py b/tests/test_generation_regressions.pyindex 04eb59f..e0976b8 100644--- a/tests/test_generation_regressions.py+++ b/tests/test_generation_regressions.py@@ -1,5 +1,6 @@import queuefrom types import SimpleNamespace+from typing import castimport pytestimport torch@@ -25,12 +26,15 @@ def test_generate_audio_stream_uses_prepared_chunk_text(monkeypatch):monkeypatch.setattr(tts_model_module, "split_into_best_sentences", fake_split_into_best_sentences)- model = SimpleNamespace(- flow_lm=SimpleNamespace(conditioner=SimpleNamespace(tokenizer=object())),- model_recommended_frames_after_eos=None,- pad_with_spaces_for_short_inputs=True,- remove_semicolons=False,- _generate_audio_stream_short_text=fake_generate_audio_stream_short_text,+ model = cast(+ TTSModel,+ SimpleNamespace(+ flow_lm=SimpleNamespace(conditioner=SimpleNamespace(tokenizer=object())),+ model_recommended_frames_after_eos=None,+ pad_with_spaces_for_short_inputs=True,+ remove_semicolons=False,+ _generate_audio_stream_short_text=fake_generate_audio_stream_short_text,+ ),)chunks = list(TTSModel.generate_audio_stream(model, {}, "hi"))@@ -47,11 +51,14 @@ def test_generate_reports_autoregressive_errors_before_decoder_done():def raise_generation(*args, **kwargs):raise error- model = SimpleNamespace(- _flow_lm_current_end=lambda model_state: 0,- _expand_kv_cache=lambda model_state, sequence_length: None,- _run_flow_lm_and_increment_step=lambda model_state, text_tokens: None,- _autoregressive_generation=raise_generation,+ model = cast(+ TTSModel,+ SimpleNamespace(+ _flow_lm_current_end=lambda model_state: 0,+ _expand_kv_cache=lambda model_state, sequence_length: None,+ _run_flow_lm_and_increment_step=lambda model_state, text_tokens: None,+ _autoregressive_generation=raise_generation,+ ),)latents_queue = queue.Queue()result_queue = queue.Queue()diff --git a/tests/test_quantization.py b/tests/test_quantization.pyindex 9b33205..5dae240 100644--- a/tests/test_quantization.py+++ b/tests/test_quantization.py@@ -13,6 +13,7 @@ from typer.testing import CliRunnerfrom pocket_tts import TTSModelfrom pocket_tts.main import cli_app+from pocket_tts.modules.transformer import StreamingTransformerLayerfrom pocket_tts.quantization import _get_backendSHORT_TEXT = "Hello, this is a test."@@ -38,6 +39,8 @@ def test_quantize_flag_applies_quantization():# Quantized model's Linear layers should have different weight types than baselinelayer_q = model_q.flow_lm.transformer.layers[0]layer_b = model_b.flow_lm.transformer.layers[0]+ assert isinstance(layer_q, StreamingTransformerLayer)+ assert isinstance(layer_b, StreamingTransformerLayer)weight_type_q = type(layer_q.self_attn.in_proj.weight).__name__weight_type_b = type(layer_b.self_attn.in_proj.weight).__name__assert weight_type_q != weight_type_b, (diff --git a/tests/test_serve_default_voice.py b/tests/test_serve_default_voice.pyindex e7050b5..69f7bf8 100644--- a/tests/test_serve_default_voice.py+++ b/tests/test_serve_default_voice.py@@ -1,6 +1,7 @@"""Tests for the default voice of the `serve` command and of the /tts endpoint."""from types import SimpleNamespace+from typing import Anyimport torchfrom fastapi.testclient import TestClient@@ -19,16 +20,18 @@ class FakeTTSModel:self.voices_requested = []self.states_used = []- def get_state_for_audio_prompt(self, audio_conditioning, truncate: bool = False) -> dict:+ def get_state_for_audio_prompt(+ self, audio_conditioning, truncate: bool = False+ ) -> dict[str, Any]:self.voices_requested.append(audio_conditioning)return {"voice": audio_conditioning}def _cached_get_state_for_audio_prompt(self, audio_conditioning, truncate: bool = False- ) -> dict:+ ) -> dict[str, Any]:return self.get_state_for_audio_prompt(audio_conditioning, truncate)- def generate_audio_stream(self, model_state: dict, text_to_generate: str):+ def generate_audio_stream(self, model_state: dict[str, Any], text_to_generate: str):self.states_used.append(model_state)yield torch.zeros(2400)diff --git a/training/args.py b/training/args.pyindex 0cad348..c28e3b7 100644--- a/training/args.py+++ b/training/args.py@@ -94,10 +94,7 @@ class TrainArgs:valid_freq: int = 2000# torch.compile the backbone layers + flow head (and the distill teacher's# backbone) in place. +24% throughput on one GPU, +7% steady-state under- # DDP (~9 min one-time warmup -- a wash on runs under ~2h). Dynamo cannot- # trace the beartype wrappers, so train.py disables the claw at import- # time; POCKET_TTS_NO_BEARTYPE=0 forces it back on and requires- # compile: false.+ # DDP (~9 min one-time warmup -- a wash on runs under ~2h).compile: bool = Truenum_valid_batches: int = 50# Rank 0 synthesizes these sentences every sample_freq steps intodiff --git a/training/checkpointing.py b/training/checkpointing.pyindex f3f287d..e5ee779 100644--- a/training/checkpointing.py+++ b/training/checkpointing.py@@ -13,6 +13,8 @@ import safetensors.torchimport torchfrom torch import nn+from training.modules.model import TrainableTTS+logger = logging.getLogger(__name__)@@ -22,7 +24,7 @@ class EMA:self.shadow = {k: p.detach().clone().float() for k, p in model.named_parameters() if p.requires_grad}- self._tracked: tuple[list, list] | None = None+ self._tracked: tuple[list[torch.Tensor], list[torch.Tensor]] | None = Nonedef update(self, model: nn.Module) -> None:with torch.no_grad():@@ -61,7 +63,7 @@ class EMA:def save_checkpoint(run_dir: Path,step: int,- model: nn.Module,+ model: TrainableTTS,optimizer,ema: EMA | None,num_keep: int,diff --git a/training/dataloader.py b/training/dataloader.pyindex 2d54b9a..fda2771 100644--- a/training/dataloader.py+++ b/training/dataloader.py@@ -15,8 +15,10 @@ from collections.abc import Callable, Iteratorfrom concurrent.futures import ThreadPoolExecutorfrom dataclasses import dataclassfrom pathlib import Path+from typing import Anyimport numpy as np+import numpy.typing as nptimport sphnimport torchimport torch.multiprocessing as torch_mp@@ -32,7 +34,7 @@ class Entry:path: strduration: floattranscript: str- words: list | None = None # [{"word", "start", "end"}] from training.scripts.align_data+ words: list[dict[str, Any]] | None = None # [{"word", "start", "end"}] from align_datastart: float = 0.0 # offset of the utterance inside the audio file (long recordings)latents_file: str | None = None@@ -61,7 +63,9 @@ def load_entries(path: str, rank: int, world_size: int) -> list[str]:return entries-def _load_window(path: str, start_sec: float, duration_sec: float, sample_rate: int) -> np.ndarray:+def _load_window(+ path: str, start_sec: float, duration_sec: float, sample_rate: int+) -> npt.NDArray[np.float32]:wav, sr = sphn.read(path, start_sec=start_sec, duration_sec=duration_sec)wav = wav.mean(axis=0) # monoif sr != sample_rate:@@ -110,7 +114,7 @@ class DataLoader:MIN_CUT_SEC = 1.0 # keep at least this much audio on both sides of a cutTRAIL_SEC = 0.2 # silence kept after the last word, so EOS has a consistent target- def _cap_prompt(self, prompt: np.ndarray) -> tuple[np.ndarray, int]:+ def _cap_prompt(self, prompt: npt.NDArray[np.float32]) -> tuple[npt.NDArray[np.float32], int]:"""Truncate the prompt to the configured cap; collation pads to batch max."""if self.max_voice_prompt_sec > 0:prompt_samples = int(self.max_voice_prompt_sec * self.sample_rate)@@ -129,7 +133,8 @@ class DataLoader:ends = [w["end"] for w in entry.words if w.get("end") is not None]return max(ends) if ends else None- def _choose_cut(self, entry: Entry) -> tuple[float, int] | None:+ def _choose_cut(self, entry: Entry) -> tuple[float, str] | None:+ """(cut in seconds, transcript of the words after it), None without alignment."""# Cut the utterance at a random point between two aligned words:# audio before the cut = voice conditioning, audio after = target,# paired with the remaining words as text (see training/scripts/align_data.py).@@ -158,15 +163,16 @@ class DataLoader:cuts = eligible or cuts[:1] # degenerate windows: earliest valid cutif not cuts:return None- return self.rng.choice(cuts)+ cut, i = self.rng.choice(cuts)+ return cut, " ".join(w["word"] for w in entry.words[i:])- def _sample(self, entry: Entry) -> tuple:+ def _sample(self, entry: Entry) -> tuple[Any, ...]:+ """(wav, tokens, prompt wav, prompt samples), or _sample_latent's tuple."""if entry.latents_file is not None:return self._sample_latent(entry)chosen = self._choose_cut(entry)if chosen is not None:- cut, i = chosen- text = " ".join(w["word"] for w in entry.words[i:])+ cut, text = chosentokens = torch.tensor(self.tokenize(text), dtype=torch.long)# Trim to the last word (plus a short tail) rather than the end# of the file: 12% of utterances carry >1s of trailing silence,@@ -202,8 +208,8 @@ class DataLoader:)return wav, tokens, prompt, length- def _load_latents(self, entry: Entry) -> torch.Tensor:- path = self.latents_root / entry.latents_file+ def _load_latents(self, latents_file: str) -> torch.Tensor:+ path = self.latents_root / latents_filewith safe_open(str(path), framework="pt") as f:return f.get_tensor("latents")@@ -211,9 +217,9 @@ class DataLoader:chosen = self._choose_cut(entry)if chosen is None or stored <= 1:return 0, entry.transcript- cut, i = chosen+ cut, text = chosencut_frames = min(max(round(cut * self.frame_rate), 1), stored - 1)- return cut_frames, " ".join(w["word"] for w in entry.words[i:])+ return cut_frames, textdef _latent_target_frames(self, entry: Entry, cut_frames: int, stored: int) -> int:cut_sec = cut_frames / self.frame_rate@@ -236,9 +242,11 @@ class DataLoader:start = self.rng.randint(0, max(0, stored - cap))return lat[start : start + cap]- def _sample_latent(self, entry: Entry) -> tuple:+ def _sample_latent(self, entry: Entry) -> tuple[Any, ...]:+ """(stitch wav, tokens, prompt latents, tail latents, target frames)."""assert self.stitch_frames > 0, f"{entry.path}: latents entry but no meta file loaded"- lat = self._load_latents(entry)+ assert entry.latents_file is not None, f"{entry.path}: not a latents entry"+ lat = self._load_latents(entry.latents_file)cut_frames, text = self._latent_cut(entry, lat.shape[0])tokens = torch.tensor(self.tokenize(text), dtype=torch.long)target_frames = self._latent_target_frames(entry, cut_frames, lat.shape[0])@@ -253,14 +261,14 @@ class DataLoader:return stitch, tokens, self._latent_prompt(lat, cut_frames), tail, target_frames@staticmethod- def _pad_latents(seqs: tuple, min_len: int) -> torch.Tensor:+ def _pad_latents(seqs: tuple[torch.Tensor, ...], min_len: int) -> torch.Tensor:length = max(min_len, max(s.shape[0] for s in seqs))out = torch.zeros(len(seqs), length, seqs[0].shape[-1])for b, s in enumerate(seqs):out[b, : s.shape[0]] = sreturn out- def _collate_stitch_audio(self, stitches: tuple) -> torch.Tensor:+ def _collate_stitch_audio(self, stitches: tuple[npt.NDArray[np.float32], ...]) -> torch.Tensor:stitch_samples = self.stitch_frames * self.frame_sizeaudio = torch.zeros(len(stitches), 1, stitch_samples)for b, w in enumerate(stitches):@@ -268,7 +276,7 @@ class DataLoader:audio[b, 0, :n] = torch.from_numpy(w[:n])return audio- def _collate_latent(self, batch: list[tuple]) -> Batch:+ def _collate_latent(self, batch: list[tuple[Any, ...]]) -> Batch:stitches, tokens, prompts, tails, target_frames = zip(*batch, strict=True)num_prompt_frames = torch.tensor([max(1, p.shape[0]) for p in prompts], dtype=torch.long)return Batch(@@ -292,7 +300,7 @@ class DataLoader:d.get("latents_file"),)- def _sample_or_none(self, entry: Entry) -> tuple | None:+ def _sample_or_none(self, entry: Entry) -> tuple[Any, ...] | None:try:return self._sample(entry)except Exception as exc: # noqa: BLE001 — skip unreadable samples, whatever the cause@@ -363,7 +371,7 @@ class DataLoader:)-def _feed_queue(q, sentence_piece_proto: bytes, loader_kwargs: dict) -> None:+def _feed_queue(q, sentence_piece_proto: bytes, loader_kwargs: dict[str, Any]) -> None:import sentencepiecetorch_mp.set_sharing_strategy("file_system")@@ -442,7 +450,7 @@ class SubprocessDataLoader:def _prefetch(iterator: Iterator[Batch], depth: int = 4) -> Iterator[Batch]:"""Run the (synchronous, IO-bound) loader in a background thread."""- q: queue.Queue = queue.Queue(maxsize=depth)+ q: queue.Queue[Batch | None] = queue.Queue(maxsize=depth)def worker():for item in iterator:diff --git a/training/eval/librispeech.py b/training/eval/librispeech.pyindex f7f5e67..3bb9a98 100644--- a/training/eval/librispeech.py+++ b/training/eval/librispeech.py@@ -22,11 +22,14 @@ import loggingimport multiprocessingimport osimport re+from collections.abc import Sequencefrom concurrent.futures import ProcessPoolExecutorfrom pathlib import Path+from typing import Anyimport huggingface_hubimport jiwer+import numpy.typing as nptimport sphnimport torchfrom pydantic import BaseModel@@ -89,7 +92,9 @@ def eval_dir_name(args, step: int) -> str:return name-def read_lst(path: str, root: str, limit: int | None, prompt_root: str | None = None) -> list[dict]:+def read_lst(+ path: str, root: str, limit: int | None, prompt_root: str | None = None+) -> list[dict[str, Any]]:items = []with open(path) as f:for line in f:@@ -145,7 +150,7 @@ def build_transcriber(asr_name: str, device):add_generation_prompt=True,)- def transcribe(wavs: list) -> list[str]:+ def transcribe(wavs: list[npt.NDArray[Any]]) -> list[str]:n = len(wavs)longest = max(len(w) for w in wavs)audio = torch.stack(@@ -169,9 +174,9 @@ def build_transcriber(asr_name: str, device):"automatic-speech-recognition", model=asr_name, device=device, torch_dtype=torch.float16)- def transcribe(wavs: list) -> list[str]:+ def transcribe(wavs: list[npt.NDArray[Any]]) -> list[str]:outs = asr(- [{"array": w, "sampling_rate": 16000} for w in wavs],+ [{"array": w, "sampling_rate": 16000} for w in wavs], # ty: ignore[invalid-argument-type] -- batched callreturn_timestamps=True,batch_size=len(wavs),)@@ -223,7 +228,7 @@ def latents_to_wav(mimi, latents: torch.Tensor, device) -> torch.Tensor | None:return mimi.decode_from_latent(latents[None].to(device), state)[0, 0]-def score_items(items: list[dict], device, args) -> tuple[list[dict], int]:+def score_items(items: list[dict[str, Any]], device, args) -> tuple[list[dict[str, Any]], int]:"""Generate and score `items` on one device. Returns per-item records."""from whisper_normalizer.english import EnglishTextNormalizer@@ -246,7 +251,7 @@ def score_items(items: list[dict], device, args) -> tuple[list[dict], int]:WavLMForXVector.from_pretrained("microsoft/wavlm-base-plus-sv").to(device).eval())- def embed(wavs: list) -> torch.Tensor:+ def embed(wavs: Sequence[npt.NDArray[Any] | torch.Tensor]) -> torch.Tensor:"""Batched x-vectors; the feature extractor emits an attention mask,so padding does not affect the embeddings."""inputs = spk_fe(@@ -285,7 +290,9 @@ def score_items(items: list[dict], device, args) -> tuple[list[dict], int]:return wavdef decode(latents: torch.Tensor) -> torch.Tensor:- return latents_to_wav(mimi, latents, device)+ wav = latents_to_wav(mimi, latents, device)+ assert wav is not None, "generations shorter than MIN_FRAMES are skipped above"+ return wavrecords = []bs = max(1, args.batch_size)diff --git a/training/modules/builders.py b/training/modules/builders.pyindex b0110cc..eea3bd4 100644--- a/training/modules/builders.py+++ b/training/modules/builders.py@@ -12,6 +12,7 @@ import torchimport yamlfrom torch import nn+from pocket_tts.models.flow_lm import FlowLMModelfrom pocket_tts.models.mimi import MimiModel, build_mimifrom pocket_tts.models.tts_model import TTSModelfrom pocket_tts.modules.mlp import SimpleMLPAdaLN@@ -27,7 +28,7 @@ from .utils import disable_grad, dit_init, gaussian_init, stamp_state_nameslogger = logging.getLogger(__name__)-def load_model_config(path: str, overrides: dict[str, tp.Any]):+def load_model_config(path: str, overrides: dict[str, tp.Any]) -> Config:"""A pocket-tts model config with dotted-path fields replaced.Lets one released config serve as the architecture for any variant of it@@ -50,7 +51,7 @@ def load_model_config(path: str, overrides: dict[str, tp.Any]):return Config(**raw)-def attach_distillation(model: TrainableTTS, flow_lm: nn.Module, args: TrainArgs) -> None:+def attach_distillation(model: TrainableTTS, flow_lm: FlowLMModel, args: TrainArgs) -> None:"""Give `model` a frozen teacher and freeze what distillation must not move.Two shapes share this path: a separately trained (usually deeper) teacher@@ -124,7 +125,7 @@ def attach_distillation(model: TrainableTTS, flow_lm: nn.Module, args: TrainArgsdisable_grad(model.flow)-def build_models(args: TrainArgs) -> tuple[TrainableTTS, MimiModel, tp.Any]:+def build_models(args: TrainArgs) -> tuple[TrainableTTS, MimiModel, Config]:"""Build (trainable model, frozen mimi, pocket config) from a pocket-tts config."""config = load_model_config(args.model_config, args.model_overrides)tts_model = TTSModel._from_pydantic_config(diff --git a/training/modules/conditioner.py b/training/modules/conditioner.pyindex 44bd77d..38520b3 100644--- a/training/modules/conditioner.py+++ b/training/modules/conditioner.py@@ -7,7 +7,8 @@ placement) with no learnable logic of its own.import torchimport torch.nn.functional as F-from torch import nn++from pocket_tts.models.flow_lm import FlowLMModelfrom ..args import TrainArgs@@ -18,8 +19,8 @@ def build_sequences_with_conditions(text_tokens: list[torch.Tensor],voice_latents: torch.Tensor,cfg_dropout: bool,+ fl: FlowLMModel,num_voice_prompt_frames: torch.Tensor | None = None,- fl: nn.Module = None,force_null: bool = False,) -> tuple[torch.Tensor, torch.Tensor]:"""Assemble per-sample [beginning_of_prefix, voice_conditioning,diff --git a/training/modules/model.py b/training/modules/model.pyindex 3c8e36d..6f4174f 100644--- a/training/modules/model.py+++ b/training/modules/model.py@@ -16,7 +16,8 @@ import torchimport torch.nn.functional as Ffrom torch import nn-from pocket_tts.modules.stateful_module import increment_steps, init_states+from pocket_tts.models.flow_lm import FlowLMModel+from pocket_tts.modules.stateful_module import ModelState, increment_steps, init_statesfrom ..args import TrainArgsfrom .conditioner import build_sequences_with_conditions@@ -25,7 +26,11 @@ from .utils import set_state_padding, stamp_state_namesclass TrainableTTS(nn.Module):- def __init__(self, flow_lm: nn.Module, flow: FlowType, args: TrainArgs):+ # Frozen teacher for distillation runs, kept out of the submodule registry+ # (see build_models); None otherwise.+ distill_teacher: FlowLMModel | None++ def __init__(self, flow_lm: FlowLMModel, flow: FlowType, args: TrainArgs):super().__init__()self.flow_lm = flow_lmself.flow = flow@@ -61,7 +66,9 @@ class TrainableTTS(nn.Module):self._update_latent_stats(latents, mask)normalized_latents = (latents - fl.emb_mean) / fl.emb_std- def backbone_z(module, cfg_dropout: bool, force_null: bool = False) -> torch.Tensor:+ 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,@@ -163,22 +170,24 @@ class TrainableTTS(nn.Module):prefixes.append(fl.bos_before_voice.expand(B, -1, -1))pads.append(torch.zeros(B, device=device, dtype=torch.long))- states = []+ states: list[ModelState] = []for p, pd in zip(prefixes, pads, strict=True):st = init_states(fl, B, p.shape[1] + max_frames + 2)set_state_padding(st, pd)- states.append({"state": st, "first": True})+ states.append(st)+ first_step = True # the prefixes are fed along with the first latentdef run(x_lat: torch.Tensor) -> torch.Tensor:+ nonlocal first_stepzs = []for i, st in enumerate(states):inp = fl.input_linear(x_lat)- if st["first"]:+ if first_step:inp = torch.cat([prefixes[i], inp], dim=1)- out = fl.out_norm(fl.transformer(inp, st["state"]))- increment_steps(fl, st["state"], increment=inp.shape[1])- st["first"] = False+ out = fl.out_norm(fl.transformer(inp, st))+ increment_steps(fl, st, increment=inp.shape[1])zs.append(out[:, -1].float())+ first_step = Falsereturn zs[0] if len(zs) == 1 else zs[1] + cfg_coef * (zs[0] - zs[1])x_lat = fl.bos_emb.view(1, 1, -1).expand(B, 1, -1)diff --git a/training/modules/samplers.py b/training/modules/samplers.pyindex 544b838..9122760 100644--- a/training/modules/samplers.py+++ b/training/modules/samplers.py@@ -137,7 +137,8 @@ class LSD(FlowType):return self.p_equal * flow_diag, metrics, ts, t = self.sample_s_t(x)x_s = s * x + (1 - s) * e- vt, dvdt = torch.func.jvp(+ # The stub's has_aux=True 3-tuple leaks into the return type.+ vt, dvdt = torch.func.jvp( # ty: ignore[invalid-assignment]v_t, (s, t, x_s), (torch.zeros_like(s), torch.ones_like(t), torch.zeros_like(x_s)))x_t = x_s + (t - s) * vtdiff --git a/training/modules/utils.py b/training/modules/utils.pyindex d4251a5..cea9442 100644--- a/training/modules/utils.py+++ b/training/modules/utils.py@@ -6,10 +6,22 @@ import mathimport torchfrom torch import nn-from pocket_tts.modules.stateful_module import StatefulModule+from pocket_tts.modules.mlp import ResBlock, SimpleMLPAdaLN, TimestepEmbedder+from pocket_tts.modules.stateful_module import ModelState, StatefulModule-def dit_init(head: nn.Module) -> None:+def _as_linear(module: nn.Module) -> nn.Linear:+ assert isinstance(module, nn.Linear), type(module)+ return module+++def _zero_linear(module: nn.Module) -> None:+ linear = _as_linear(module)+ nn.init.constant_(linear.weight, 0)+ nn.init.constant_(linear.bias, 0)+++def dit_init(head: SimpleMLPAdaLN) -> None:"""The MAR/DiT init: xavier everywhere, zero adaLN modulations and output."""def _basic_init(module):@@ -20,15 +32,14 @@ def dit_init(head: nn.Module) -> None:head.apply(_basic_init)for emb in head.time_embed:- nn.init.normal_(emb.mlp[0].weight, std=0.02)- nn.init.normal_(emb.mlp[2].weight, std=0.02)+ assert isinstance(emb, TimestepEmbedder)+ nn.init.normal_(_as_linear(emb.mlp[0]).weight, std=0.02)+ nn.init.normal_(_as_linear(emb.mlp[2]).weight, std=0.02)for block in head.res_blocks:- nn.init.constant_(block.adaLN_modulation[-1].weight, 0)- nn.init.constant_(block.adaLN_modulation[-1].bias, 0)- nn.init.constant_(head.final_layer.adaLN_modulation[-1].weight, 0)- nn.init.constant_(head.final_layer.adaLN_modulation[-1].bias, 0)- nn.init.constant_(head.final_layer.linear.weight, 0)- nn.init.constant_(head.final_layer.linear.bias, 0)+ assert isinstance(block, ResBlock)+ _zero_linear(block.adaLN_modulation[-1])+ _zero_linear(head.final_layer.adaLN_modulation[-1])+ _zero_linear(head.final_layer.linear)def gaussian_init(module: nn.Module) -> None:@@ -49,7 +60,7 @@ def disable_grad(module: nn.Module) -> None:p.requires_grad = False-def set_state_padding(model_state: dict, pad: torch.Tensor) -> None:+def set_state_padding(model_state: ModelState, pad: torch.Tensor) -> None:"""Tell every attention layer how many leading slots per row are padding."""for st in model_state.values():if isinstance(st, dict) and "pad" in st:@@ -73,8 +84,8 @@ class MLP(nn.Sequential):layers.append(nn.Linear(dim, hidden_channels[-1]))super().__init__(*layers)- def forward(self, *args) -> torch.Tensor:- return super().forward(torch.cat(args, dim=-1))+ def forward(self, input: torch.Tensor, *rest: torch.Tensor) -> torch.Tensor:+ return super().forward(torch.cat((input, *rest), dim=-1))def zero_init(m: nn.Module) -> None:@@ -95,7 +106,8 @@ class RunOnlyInputGrad(torch.autograd.Function):return y.detach()@staticmethod- def backward(ctx, grad_output):+ def backward(ctx, *grad_outputs):+ (grad_output,) = grad_outputsx, y = ctx.saved_tensorsgx = torch.autograd.grad(outputs=y, inputs=x, grad_outputs=grad_output, retain_graph=False)[0diff --git a/training/scripts/align_data.py b/training/scripts/align_data.pyindex 3c20d98..f41f549 100644--- a/training/scripts/align_data.py+++ b/training/scripts/align_data.py@@ -27,7 +27,7 @@ import queueimport reimport threadingfrom collections.abc import Callable-from typing import Annotated+from typing import Annotated, Anyimport sphnimport torch@@ -56,7 +56,7 @@ def batched_word_spans(token_lists: list[list[int]],word_of_lists: list[list[int]],blank: int,-) -> list[list[tuple[int, int]] | None]:+) -> list[list[tuple[int, int] | None] | None]:"""Viterbi CTC alignment for a whole batch: one time-loop over Tmax.Returns, per item, per-token (start_frame, end_frame) spans grouped into@@ -85,7 +85,7 @@ def batched_word_spans(# Items shorter than t keep their final row frozen.trellis[t + 1] = torch.where((t < T).view(B, 1), new, prev)- results: list[list[tuple[int, int]] | None] = []+ results: list[list[tuple[int, int] | None] | None] = []trellis_cpu = trellis.permute(1, 0, 2).cpu() # [B, Tmax+1, Nmax+1]blank_cpu = blank_em.cpu()tok_em_cpu = tok_em.cpu()@@ -116,7 +116,7 @@ def batched_word_spans(return results-def case_fold_for(vocab: dict) -> Callable[[str], str]:+def case_fold_for(vocab: dict[str, int]) -> Callable[[str], str]:"""Match the transcript's case to the model's vocabulary.English CTC checkpoints spell their vocabulary in upper case, almost every@@ -134,7 +134,7 @@ def case_fold_for(vocab: dict) -> Callable[[str], str]:return lambda s: s-def _tokens_for(words: list[str], vocab: dict, delim: int) -> tuple[list[int], list[int]]:+def _tokens_for(words: list[str], vocab: dict[str, int], delim: int) -> tuple[list[int], list[int]]:tokens, word_of = [], []for w_idx, w in enumerate(words):if w_idx > 0:@@ -157,7 +157,8 @@ def _load_ctc_model(model_name: str, device: torch.device):from transformers import Wav2Vec2ForCTC, Wav2Vec2Processorprocessor = Wav2Vec2Processor.from_pretrained(model_name)- model = Wav2Vec2ForCTC.from_pretrained(model_name).to(device).eval()+ # transformers wraps .to() in a way that loses the bound self.+ model = Wav2Vec2ForCTC.from_pretrained(model_name).to(device).eval() # ty: ignore[invalid-argument-type]use_bf16 = device.type == "cuda"if use_bf16:model = model.to(torch.bfloat16)@@ -276,7 +277,8 @@ def main()with open(input_jsonl) as fin, open(output_jsonl, "a" if resume else "w", buffering=1) as fout:- q: queue.Queue = queue.Queue(maxsize=sort_window * 2)+ # (entry, wav) or (entry, exception); None once the manifest is exhausted.+ q: queue.Queue[tuple[Any, Any] | None] = queue.Queue(maxsize=sort_window * 2)threading.Thread(target=read_entries, args=(fin, q), daemon=True).start()def windows():@@ -337,11 +339,12 @@ def main(sec_per_frame = (n_samples / sr) / t_framestimed, k = [], 0for w, nw in zip(words, norm, strict=True):- if not nw or spans[k] is None:+ span = spans[k] if nw else None+ if span is None:timed.append({"word": w, "start": None, "end": None})k += bool(nw)continue- s, e = spans[k]+ s, e = spank += 1timed.append({diff --git a/training/scripts/precompute_latents.py b/training/scripts/precompute_latents.pyindex 87439ea..6573c5d 100644--- a/training/scripts/precompute_latents.py+++ b/training/scripts/precompute_latents.py@@ -4,12 +4,11 @@ import loggingimport multiprocessingimport osimport time--os.environ.setdefault("POCKET_TTS_NO_BEARTYPE", "1")from concurrent.futures import ProcessPoolExecutorfrom pathlib import Pathimport numpy as np+import numpy.typing as nptimport safetensors.torchimport torchimport typer@@ -32,12 +31,16 @@ def default_decode_workers() -> int:return max(4, len(os.sched_getaffinity(0)) - 2)-def _decode_one(job: tuple) -> np.ndarray:+# (path, start_sec, duration_sec, sample_rate): the arguments of _load_window.+DecodeJob = tuple[str, float, float, int]+++def _decode_one(job: DecodeJob) -> npt.NDArray[np.float32]:path, start, duration, sample_rate = jobreturn _load_window(path, start, duration, sample_rate)-def _decode_chunk(jobs: list[tuple]) -> tuple[np.ndarray, list[int]]:+def _decode_chunk(jobs: list[DecodeJob]) -> tuple[npt.NDArray[np.float32], list[int]]:wavs = [_load_window(p, s, d, sr) for (p, s, d, sr) in jobs]max_len = max(len(w) for w in wavs)batch = np.zeros((len(wavs), 1, max_len), dtype=np.float32)@@ -53,7 +56,7 @@ def _parse_entry(line: str) -> Entry:)-def _chunk_jobs(lines: list[str], idxs: list[int], sample_rate: int) -> list[tuple]:+def _chunk_jobs(lines: list[str], idxs: list[int], sample_rate: int) -> list[DecodeJob]:chunk = [lines[i] for i in idxs]return [(e.path, e.start, e.duration, sample_rate) for e in map(_parse_entry, chunk)]diff --git a/training/scripts/prepare_data.py b/training/scripts/prepare_data.pyindex 2da22e8..7bfd807 100644--- a/training/scripts/prepare_data.py+++ b/training/scripts/prepare_data.py@@ -27,10 +27,10 @@ import loggingimport subprocessimport sysimport time-from collections import Counter+from collections import Counter, defaultdictfrom concurrent.futures import ThreadPoolExecutorfrom pathlib import Path-from typing import Annotated+from typing import Annotated, Anyimport huggingface_hubimport requests@@ -140,7 +140,7 @@ def attach_hf_alignments(manifest: Path, out: Path, repo: str, audio_root: Path)`audio_filepath` (bring-your-own-data manifests with one utterance perfile) fall back to the path relative to the audio root."""snap = Path(huggingface_hub.snapshot_download(repo.removeprefix("hf://"), repo_type="dataset"))- wanted: dict[str, dict] = {}+ wanted: dict[str, dict[str, Any]] = {}with open(manifest) as f:for line in f:d = json.loads(line)@@ -148,7 +148,7 @@ def attach_hf_alignments(manifest: Path, out: Path, repo: str, audio_root: Path)Path(d["path"]).resolve().relative_to(audio_root.resolve()))wanted[key] = d- found: dict[str, list] = {}+ found: dict[str, list[dict[str, Any]]] = {}files = sorted(glob.glob(str(snap / "train" / "*.jsonl.gz"))) + [str(snap / "eval_aligned.jsonl.gz")]@@ -201,7 +201,7 @@ def prepare_hifitts2(for line in f:chapters.append(json.loads(line))- def held_out(u: dict) -> bool:+ def held_out(u: dict[str, Any]) -> bool:"""Whether utterance `u` is in meta and outside the train split."""r = meta.get(u["audio_filepath"])return r is not None and r.set != "train"@@ -254,10 +254,10 @@ def prepare_hifitts2(audio_root = audio_out / "hifitts2_audio"- def chapter_path(ch: dict) -> Path:+ def chapter_path(ch: dict[str, Any]) -> Path:return audio_root / (Path(ch["chapter_filepath"]).stem + ".mp3")- def fetch_chapter(ch: dict) -> None:+ def fetch_chapter(ch: dict[str, Any]) -> None:"""Download chapter `ch`'s whole audio file, if not already present.One download per chapter, shared by every utterance in it: the@@ -271,7 +271,7 @@ def prepare_hifitts2(download(ch["url"], Path(str(path) + ".part"))Path(str(path) + ".part").rename(path)- def guarded(ch: dict) -> tuple[dict, Exception | None]:+ def guarded(ch: dict[str, Any]) -> tuple[dict[str, Any], Exception | None]:try:fetch_chapter(ch)return ch, None@@ -289,7 +289,7 @@ def prepare_hifitts2(bar_format="{l_bar}{bar}| {n:.0f}/{total:.0f}h [{elapsed}<{remaining}{postfix}]",)for ch, exc in pool.map(guarded, chapters):- bar.update(min(float(ch["duration"]) / 3600, bar.total - bar.n))+ bar.update(min(float(ch["duration"]) / 3600, kept_h - bar.n))if exc is None:ok_chapters.append(ch)else:@@ -308,7 +308,8 @@ def prepare_hifitts2(logger.info(f" {n} x {label}")chapters = ok_chapters- written, written_h = Counter(), Counter()+ written: Counter[bool] = Counter()+ written_h: defaultdict[bool, float] = defaultdict(float)train_manifest = out_dir / "train.jsonl"valid_manifest = out_dir / "valid.jsonl"with open(train_manifest, "w") as ftr, open(valid_manifest, "w") as fev:diff --git a/training/tests/test_config_invariants.py b/training/tests/test_config_invariants.pyindex b724c8a..0f9d2c1 100644--- a/training/tests/test_config_invariants.py+++ b/training/tests/test_config_invariants.py@@ -6,6 +6,7 @@ and a teacher path pointing at an architecture the distill step cannot load."""from pathlib import Path+from typing import Anyimport pytest@@ -72,8 +73,9 @@ class TestArgValidation:def test_zero_frequencies_are_rejected(self):for field in ("valid_freq", "ckpt_freq", "log_freq"):+ kwargs: dict[str, Any] = {field: 0}with pytest.raises(ValueError, match=field):- TrainArgs(**{field: 0})+ TrainArgs(**kwargs)def test_distillation_without_a_teacher_is_rejected(self):with pytest.raises(ValueError, match="teacher"):diff --git a/training/tests/test_smoke.py b/training/tests/test_smoke.pyindex 9d7d285..a387c28 100644--- a/training/tests/test_smoke.py+++ b/training/tests/test_smoke.py@@ -200,8 +200,8 @@ def test_generate_ragged_matches_batch_of_one():def test_generate_per_row_eos():"""A row whose EOS fires early must come back shorter than the others."""model = tiny_model("lsd")- tokens = torch.randint(0, 10, (2, 4))- voice = torch.randn(2, 4, LDIM)+ tokens = list(torch.randint(0, 10, (2, 4)))+ voice = list(torch.randn(2, 4, LDIM))# eos_threshold very low => EOS fires immediately for every row.out = model.generate(tokens, voice, max_frames=8, temp=0.7, n_steps=1, cfg_coef=1.0, eos_threshold=-1e9@@ -265,7 +265,7 @@ def test_ema_load_drops_untracked_keys():torch.testing.assert_close(model.state_dict()[k], v)-def test_prefix_prompt():+def test_prefix_prompt(monkeypatch):"""The cut lands inside the window, the prompt is the utterance start,and the target keeps the rest of the utterance."""dl = DataLoader.__new__(DataLoader)@@ -281,23 +281,21 @@ def test_prefix_prompt():words = [{"word": f"w{i}", "start": float(i), "end": i + 0.8} for i in range(20)]entry = Entry(path="x", duration=20.0, transcript="t", words=words)- orig = td._load_windowcalls = []- td._load_window = lambda path, start, dur, sr: (- calls.append((start, dur)),- np.zeros(max(1, int(dur * sr)), dtype=np.float32),- )[1]- try:- for _ in range(50):- calls.clear()- wav, tokens, prompt, plen = dl._sample(entry)- (t_start, t_dur), (p_start, p_dur) = calls[0], calls[1]- assert p_start == 0.0, "prefix prompt must start at the utterance start"- assert t_start <= 5.5, f"cut must sit inside the window, got {t_start}"- assert p_dur == t_start, "prompt must run exactly up to the cut"- assert t_dur >= 20.0 - 5.5 - 0.5, "target keeps most of the utterance"- finally:- td._load_window = orig++ def fake_load_window(path, start, dur, sr):+ calls.append((start, dur))+ return np.zeros(max(1, int(dur * sr)), dtype=np.float32)++ monkeypatch.setattr(td, "_load_window", fake_load_window)+ for _ in range(50):+ calls.clear()+ wav, tokens, prompt, plen = dl._sample(entry)+ (t_start, t_dur), (p_start, p_dur) = calls[0], calls[1]+ assert p_start == 0.0, "prefix prompt must start at the utterance start"+ assert t_start <= 5.5, f"cut must sit inside the window, got {t_start}"+ assert p_dur == t_start, "prompt must run exactly up to the cut"+ assert t_dur >= 20.0 - 5.5 - 0.5, "target keeps most of the utterance"def test_train_tokenizer(tmp_path):@@ -334,12 +332,16 @@ def test_grad_accum_matches_big_batch():def loss_of(x, y):return torch.nn.functional.mse_loss(net(x), y, reduction="mean")+ def grad_of(p: torch.nn.Parameter) -> torch.Tensor:+ assert p.grad is not None+ return p.grad+net.zero_grad()loss_of(xs, ys).backward()- big = [p.grad.clone() for p in net.parameters()]+ big = [grad_of(p).clone() for p in net.parameters()]net.zero_grad()for half in (slice(0, 4), slice(4, 8)):(loss_of(xs[half], ys[half]) / 2).backward()for g, p in zip(big, net.parameters(), strict=True):- assert torch.allclose(g, p.grad, atol=1e-6)+ assert torch.allclose(g, grad_of(p), atol=1e-6)diff --git a/training/train.py b/training/train.pyindex 904e861..43b5638 100644--- a/training/train.py+++ b/training/train.py@@ -6,12 +6,6 @@ Usage:import os-# The package-wide beartype claw must be disabled before pocket_tts is first-# imported: dynamo cannot trace the beartype wrappers and `compile` defaults-# to on. Export POCKET_TTS_NO_BEARTYPE=0 to force type checking back on-# (requires `compile: false`).-os.environ.setdefault("POCKET_TTS_NO_BEARTYPE", "1")-# Utterances are variable-length, so the default caching allocator fragments and# a batch that fits can still fail to allocate; expandable segments keep the# reserved memory flat at no throughput cost. Set only from the entry point,@@ -30,6 +24,7 @@ import torchfrom torch import nnfrom torch.nn.parallel import DistributedDataParallel as DDP+from pocket_tts.models.mimi import MimiModelfrom training.args import TrainArgs, dump_args, load_args, save_argsfrom training.checkpointing import EMA, latest_checkpoint, load_checkpoint, save_checkpointfrom training.dataloader import DataLoader, SubprocessDataLoader, encode_batch@@ -42,6 +37,7 @@ from training.distributed import (shutdown_distributed,)from training.modules.builders import build_models+from training.modules.model import TrainableTTSfrom training.train_utils import (ProgressLog,_compile_models,@@ -63,9 +59,9 @@ class Run:"""Everything the training loop needs, assembled before the first step."""args: TrainArgs- model: nn.Module # unwrapped, for EMA/checkpointing+ model: TrainableTTS # unwrapped, for EMA/checkpointingwrapped: nn.Module # DDP-wrapped when distributed, else the model itself- mimi: nn.Module+ mimi: MimiModeloptimizer: torch.optim.Optimizerema: EMA | Nonestart_step: int@@ -234,7 +230,7 @@ def main(config_path: str) -> None:# Under DDP, allreduce only on the last micro-batch.last_micro = micro == args.grad_accum_steps - 1scaled = loss / args.grad_accum_steps- if not last_micro and hasattr(run.wrapped, "no_sync"):+ if not last_micro and isinstance(run.wrapped, DDP):with run.wrapped.no_sync():scaled.backward()else:diff --git a/training/train_utils.py b/training/train_utils.pyindex 991df37..f221830 100644--- a/training/train_utils.py+++ b/training/train_utils.py@@ -6,6 +6,7 @@ import mathimport subprocessimport timefrom pathlib import Path+from typing import Anyimport soundfileimport torch@@ -44,7 +45,7 @@ class ProgressLog:self.path = Path(path)self.enabled = enabled- def log(self, event: str, step: int, metrics: dict | None = None, **fields) -> None:+ def log(self, event: str, step: int, metrics: dict[str, Any] | None = None, **fields) -> None:if not self.enabled:returnrecord = {diff --git a/uv.lock b/uv.lockindex c891529..b3c34b7 100644--- a/uv.lock+++ b/uv.lock@@ -64,15 +64,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/1c/cf/e5f9b68a5b0e939a2fb933a66c20180d0c9241bf8927f7a47fa48c1675e9/backrefs-8.0-py314-none-any.whl", hash = "sha256:9ec96efa080938be92323e8e730e57718c9c88eb15ad70bbef4e1766df591408", size = 411903, upload-time = "2026-07-26T19:54:23.221Z" },]-[[package]]-name = "beartype"-version = "0.22.9"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/c7/94/1009e248bbfbab11397abca7193bea6626806be9a327d399810d523a07cb/beartype-0.22.9.tar.gz", hash = "sha256:8f82b54aa723a2848a56008d18875f91c1db02c32ef6a62319a002e3e25a975f", size = 1608866, upload-time = "2025-12-13T06:50:30.72Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/71/cc/18245721fa7747065ab478316c7fea7c74777d07f37ae60db2e84f8172e8/beartype-0.22.9-py3-none-any.whl", hash = "sha256:d16c9bbc61ea14637596c5f6fbff2ee99cbe3573e46a716401734ef50c3060c2", size = 1333658, upload-time = "2025-12-13T06:50:28.266Z" },-]-[[package]]name = "certifi"version = "2026.7.22"@@ -1474,7 +1465,6 @@ name = "pocket-tts"version = "3.0.2"source = { editable = "." }dependencies = [- { name = "beartype" },{ name = "einops" },{ name = "fastapi" },{ name = "huggingface-hub" },@@ -1520,13 +1510,13 @@ dev = [{ name = "torchaudio" },{ name = "tqdm" },{ name = "transformers" },+ { name = "ty" },{ name = "utmos-pytorch" },{ name = "whisper-normalizer" },][package.metadata]requires-dist = [- { name = "beartype", specifier = ">=0.22.5" },{ name = "einops", specifier = ">=0.4.0" },{ name = "fastapi", specifier = ">=0.100" },{ name = "huggingface-hub", specifier = ">=0.13.0" },@@ -1563,6 +1553,7 @@ dev = [{ name = "torchaudio" },{ name = "tqdm", specifier = ">=4.60" },{ name = "transformers", specifier = ">=4.40" },+ { name = "ty", specifier = ">=0.0.77" },{ name = "utmos-pytorch", specifier = ">=0.1.0" },{ name = "whisper-normalizer", specifier = ">=0.0.10" },]@@ -2788,6 +2779,31 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/f0/ac/229b7d4589d2e5937310e72c6d46e89599d16a4a12b479ffa1499fee8eb8/triton-3.7.1-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:10ba85fa2cca4a2fbdeb36bf1cb082f2c252bda55bf9fccd74f65ec5bc647e68", size = 197824404, upload-time = "2026-06-17T19:53:42.772Z" },]+[[package]]+name = "ty"+version = "0.0.77"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/bb/ef/a2024d1d33d5ba8436677a6fd734f87a137150aba99906fc009f7c5de956/ty-0.0.77.tar.gz", hash = "sha256:8898f3097610f4a772ead6bfad7b204c7d76e8eb3a010c7285b9186278e0fb82", size = 7005734, upload-time = "2026-09-01T00:26:26.901Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/48/03/930f7454a6d797abc09aebbf537017825ebb08d9f8c2e2d905e74341dbb1/ty-0.0.77-py3-none-linux_armv6l.whl", hash = "sha256:ea76012f1ed387b6fc6500894fb8a7654b724c38713e263a23f12756f00e2469", size = 13241626, upload-time = "2026-09-01T00:25:51.02Z" },+ { url = "https://files.pythonhosted.org/packages/65/41/7e064045775718673851f6c0e1cfde70d6e380b0db9d91d4484a362f2d67/ty-0.0.77-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:237a58c389e01d65c4693e0394feb0f0adea3fba0345c3b932d209084372f3d3", size = 12830037, upload-time = "2026-09-01T00:25:53.172Z" },+ { url = "https://files.pythonhosted.org/packages/5b/64/66f0b0dc89bd239922bdf12fa3e6d066aa7a425e8b70414368c4eb44a6e6/ty-0.0.77-py3-none-macosx_11_0_arm64.whl", hash = "sha256:bbb8ae7a753b9a6af25725c314d0eca967e5fde5eebb7a35b04b0d763dfb9d7c", size = 12612071, upload-time = "2026-09-01T00:25:55.116Z" },+ { url = "https://files.pythonhosted.org/packages/fd/5c/bef8b1f471931a9395792be023613b6cee0ef1449815bf97b18be07f883c/ty-0.0.77-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:603620c063b718ddbe302f83fb0d7c01a13f1941c3b9763512a89c9bbfabba96", size = 12641403, upload-time = "2026-09-01T00:25:57.305Z" },+ { url = "https://files.pythonhosted.org/packages/43/66/e4d32a0145162f79bc3dd6fca4770f88966c3b5206121ffeecd5f7b05e8b/ty-0.0.77-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:03f128cb8b204e22a18f4b01ef0194aa445f4edb080cb7d77621cb2ab353885c", size = 13013526, upload-time = "2026-09-01T00:25:59.278Z" },+ { url = "https://files.pythonhosted.org/packages/aa/be/33493ee43d4db7d402ceaee55c5d6c22e2b1105f10b1ac5928c220f79650/ty-0.0.77-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:97d1600ef69fc8e3b2310de1915cd34ba3b712fdc730cb02b713520956baec0a", size = 13828076, upload-time = "2026-09-01T00:26:01.343Z" },+ { url = "https://files.pythonhosted.org/packages/cf/d5/b6335fdc8c09aaaaf6541322076c5a7205fa16c29dbeddc1f24dd89b3894/ty-0.0.77-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:dced0924a83b6d945fd48a29aa85e131fb98dc574f4c9a0e7c43d03eff373402", size = 14247770, upload-time = "2026-09-01T00:26:03.388Z" },+ { url = "https://files.pythonhosted.org/packages/11/64/bbe96c1da26585919ac10f33df1d337d9b498013fc60c5178e76955c2a53/ty-0.0.77-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:b14b002233a954115a04932b3a93d75a387569848276cf7bb0b5dc6b040001c4", size = 13926528, upload-time = "2026-09-01T00:26:05.587Z" },+ { url = "https://files.pythonhosted.org/packages/4f/e2/cdc94e9a1b69e9b7dd0ec3ad3ca75741245b8b5b2e3ffe9b365ca31d8052/ty-0.0.77-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:581adf1ae1e48e00e89ec162913d559ddf75a7805646a13ffd68943c1b5e8daa", size = 13290834, upload-time = "2026-09-01T00:26:07.912Z" },+ { url = "https://files.pythonhosted.org/packages/92/8c/4929dd8e924ddbd6284dcb3cfbda488bd6cb091e5384f8b7fb5dd3de9122/ty-0.0.77-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:9bda523b40e06c643feb6d5d5bcbacc56a2bd9eed3d7cae1119452502bcd69b0", size = 13829048, upload-time = "2026-09-01T00:26:10.093Z" },+ { url = "https://files.pythonhosted.org/packages/9b/f4/441a74ddc5e2db2690264c1ee0e478d46b8e42bd529472fdb1656b63bff2/ty-0.0.77-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:4b8b04d8c3af8148e963e950094bd53c8cc4d3a11f5f8764ff8d39627bd6e64a", size = 12803755, upload-time = "2026-09-01T00:26:12.055Z" },+ { url = "https://files.pythonhosted.org/packages/85/39/875bb7092ee1edb090b62eca74b7311f6416dc3aa7da442b4a1f95408251/ty-0.0.77-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:33a9ff9be488edf4d6fac46c456198cc848d9641f418f1a83aa123825e93c6ec", size = 13028244, upload-time = "2026-09-01T00:26:14.212Z" },+ { url = "https://files.pythonhosted.org/packages/e3/76/4b0a48f118dca6a32e1609f2d0bea2c3f7be9051af645fe5044ca35cbbb4/ty-0.0.77-py3-none-musllinux_1_2_i686.whl", hash = "sha256:61ad5467206e5ea6531c8aebebf1276c6150989a94a1d5974a84d9e0eeed5c38", size = 13321068, upload-time = "2026-09-01T00:26:16.418Z" },+ { url = "https://files.pythonhosted.org/packages/8d/46/cd21bc6441df4b221d9e131551bab2a5f9c0b724e60e1c960622ee175128/ty-0.0.77-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:1293b94f26d1f330424e3b97c20b434f7e2ac1938287b8588466c75ece6c0b10", size = 13609112, upload-time = "2026-09-01T00:26:18.424Z" },+ { url = "https://files.pythonhosted.org/packages/21/7b/0da4537a7eca4eb3ca72a2cb4539cfbb6fb3138d1dc4ae7a66299b941fb3/ty-0.0.77-py3-none-win32.whl", hash = "sha256:cb71152bdf56860375c790682cc3efc120aaf8e36f1cd6367773312905e82b50", size = 12573821, upload-time = "2026-09-01T00:26:20.404Z" },+ { url = "https://files.pythonhosted.org/packages/96/91/aec75b11bfaa5a358f5a505afa6307fc4bee1c5f4c6444e18fa82c25f3be/ty-0.0.77-py3-none-win_amd64.whl", hash = "sha256:86f01d4af8b006c9442a2de0ab949cc24462f8f9431bebc0b73f6166fbbca19f", size = 13154851, upload-time = "2026-09-01T00:26:22.389Z" },+ { url = "https://files.pythonhosted.org/packages/bf/e5/77772f95ff81bf7c817595cd08b52d007acab90dac0f2339faa486e6a525/ty-0.0.77-py3-none-win_arm64.whl", hash = "sha256:942a3bb2a4786c80bd8ef4503e5024046617cdfcc550b56c1acc4817ce7ac144", size = 12992392, upload-time = "2026-09-01T00:26:24.44Z" },+]+[[package]]name = "typer"version = "0.27.1"