Skip to content

A TTS that fits in your CPU (and pocket)

Python

Enable ruff's ANN rules and annotate every function (#284)

gabrieldemarmiesse-ai-agent6c0ac8f6ee6b
diff --git a/pocket_tts/data/audio.py b/pocket_tts/data/audio.py
index add14e1..6fe01c9 100644
--- a/pocket_tts/data/audio.py
+++ b/pocket_tts/data/audio.py
@@ -10,10 +10,11 @@ import wave
from collections.abc import Iterator
from contextlib import nullcontext
from pathlib import Path
-from typing import Any, BinaryIO, TypeGuard
+from typing import BinaryIO
import numpy as np
import torch
+from typing_extensions import TypeIs
logger = logging.getLogger(__name__)
@@ -62,7 +63,7 @@ def _audio_read_with_soundfile(filepath: Path) -> tuple[torch.Tensor, int]:
class StreamingWAVWriter:
"""WAV writer using Python's standard library wave module."""
- def __init__(self, output_stream, sample_rate: int):
+ def __init__(self, output_stream: BinaryIO, sample_rate: int):
self.output_stream = output_stream
self.sample_rate = sample_rate
self.wave_writer: wave.Wave_write | None = None
@@ -129,12 +130,12 @@ class StreamingWAVWriter:
writer.close()
-def is_file_like(obj: object) -> TypeGuard[BinaryIO]:
+def is_file_like(obj: object) -> TypeIs[BinaryIO]:
"""Check if object has basic file-like methods."""
return all(hasattr(obj, attr) for attr in ["write", "close"])
-def _is_seekable(obj) -> bool:
+def _is_seekable(obj: object) -> bool:
seekable = getattr(obj, "seekable", None)
if seekable is not None:
try:
@@ -145,7 +146,7 @@ def _is_seekable(obj) -> bool:
def stream_audio_chunks(
- path: str | Path | None | Any, audio_chunks: Iterator[torch.Tensor], sample_rate: int
+ path: str | Path | BinaryIO | None, audio_chunks: Iterator[torch.Tensor], sample_rate: int
):
"""Stream audio chunks to a WAV file or stdout, optionally playing them."""
f: BinaryIO | nullcontext[None]
@@ -160,6 +161,7 @@ def stream_audio_chunks(
with f:
if path is not None:
+ assert not isinstance(f, nullcontext)
writer = StreamingWAVWriter(f, sample_rate)
writer.write_header(sample_rate)
diff --git a/pocket_tts/main.py b/pocket_tts/main.py
index 2152886..9e1ed29 100644
--- a/pocket_tts/main.py
+++ b/pocket_tts/main.py
@@ -4,9 +4,10 @@ import os
import sys
import tempfile
import threading
+from collections.abc import Iterator
from pathlib import Path
from queue import Queue
-from typing import Annotated
+from typing import Annotated, BinaryIO, cast
import typer
import uvicorn
@@ -70,7 +71,7 @@ def _loaded_model() -> TTSModel:
@web_app.get("/", response_class=HTMLResponse)
-async def root():
+async def root() -> str:
"""Serve the frontend."""
static_path = Path(__file__).parent / "static" / "index.html"
content = static_path.read_text()
@@ -82,18 +83,18 @@ async def root():
@web_app.get("/health")
-async def health():
+async def health() -> dict[str, str]:
return {"status": "healthy"}
-def write_to_queue(queue, text_to_generate, model_state):
+def write_to_queue(queue: Queue[bytes | None], text_to_generate: str, model_state: ModelState):
"""Allows writing to the StreamingResponse as if it were a file."""
class FileLikeToQueue(io.IOBase):
- def __init__(self, queue):
+ def __init__(self, queue: Queue[bytes | None]):
self.queue = queue
- def write(self, data):
+ def write(self, data: bytes):
self.queue.put(data)
def flush(self):
@@ -106,11 +107,14 @@ def write_to_queue(queue, text_to_generate, model_state):
audio_chunks = model.generate_audio_stream(
model_state=model_state, text_to_generate=text_to_generate
)
- stream_audio_chunks(FileLikeToQueue(queue), audio_chunks, model.config.mimi.sample_rate)
+ # FileLikeToQueue only implements the write/close subset that StreamingWAVWriter uses.
+ stream_audio_chunks(
+ cast(BinaryIO, FileLikeToQueue(queue)), audio_chunks, model.config.mimi.sample_rate
+ )
-def generate_data_with_state(text_to_generate: str, model_state: ModelState):
- queue = Queue()
+def generate_data_with_state(text_to_generate: str, model_state: ModelState) -> Iterator[bytes]:
+ queue: Queue[bytes | None] = Queue()
# Run your function in a thread
thread = threading.Thread(target=write_to_queue, args=(queue, text_to_generate, model_state))
@@ -133,7 +137,7 @@ def text_to_speech(
text: str = Form(...),
voice_url: str | None = Form(None),
voice_wav: UploadFile | None = File(None),
-):
+) -> StreamingResponse:
"""
Generate speech from text using the pre-loaded voice prompt or a custom voice.
diff --git a/pocket_tts/models/flow_lm.py b/pocket_tts/models/flow_lm.py
index 259d667..e831b12 100644
--- a/pocket_tts/models/flow_lm.py
+++ b/pocket_tts/models/flow_lm.py
@@ -87,7 +87,7 @@ class FlowLMModel(nn.Module):
ldim: int = 64,
stats_ema_decay: float = 0.999,
text_padding_weight: float = 1.0,
- dtype=None,
+ dtype: torch.dtype | None = None,
insert_bos_before_voice: bool = False,
flow_type: str = "lsd",
):
@@ -165,7 +165,11 @@ class FlowLMModel(nn.Module):
return decode(conditioned_flow, noise, sampler_decode_steps), out_eos
def backbone(
- self, input_, text_embeddings: torch.Tensor, sequence, model_state: ModelState
+ self,
+ input_: torch.Tensor,
+ text_embeddings: torch.Tensor,
+ sequence: torch.Tensor,
+ 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
diff --git a/pocket_tts/models/mimi.py b/pocket_tts/models/mimi.py
index 8e3d02e..2656cd5 100644
--- a/pocket_tts/models/mimi.py
+++ b/pocket_tts/models/mimi.py
@@ -1,4 +1,5 @@
import logging
+from typing import NoReturn
import torch
from torch import nn
@@ -7,7 +8,9 @@ from pocket_tts.modules.conv import pad_for_conv1d
from pocket_tts.modules.dummy_quantizer import DummyQuantizer
from pocket_tts.modules.resample import ConvDownsample1d, ConvTrUpsample1d
from pocket_tts.modules.seanet import SEANetDecoder, SEANetEncoder
+from pocket_tts.modules.stateful_module import ModelState
from pocket_tts.modules.transformer import ProjectedTransformer
+from pocket_tts.utils.config import MimiConfig
logger = logging.getLogger()
@@ -65,7 +68,7 @@ class MimiModel(nn.Module):
def frame_size(self) -> int:
return int(self.sample_rate / self.frame_rate)
- def _to_framerate(self, x: torch.Tensor):
+ def _to_framerate(self, x: torch.Tensor) -> torch.Tensor:
# Convert from the encoder frame rate to the overall framerate.
_, _, length = x.shape
frame_rate = self.encoder_frame_rate
@@ -74,7 +77,7 @@ class MimiModel(nn.Module):
return x
return self.downsample(x, model_state=None)
- def _to_encoder_framerate(self, x: torch.Tensor, mimi_state) -> torch.Tensor:
+ def _to_encoder_framerate(self, x: torch.Tensor, mimi_state: ModelState) -> torch.Tensor:
# Convert from overall framerate to the encoder frame rate.
_, _, length = x.shape
frame_rate = self.encoder_frame_rate
@@ -83,10 +86,10 @@ class MimiModel(nn.Module):
return x
return self.upsample(x, mimi_state)
- def forward(self, x: torch.Tensor):
+ def forward(self, x: torch.Tensor) -> NoReturn:
raise NotImplementedError()
- def decode_from_latent(self, latent: torch.Tensor, mimi_state) -> torch.Tensor:
+ def decode_from_latent(self, latent: torch.Tensor, mimi_state: ModelState) -> torch.Tensor:
"""Decodes [B, T, C] quantizer-space latents (as produced by
encode_to_latent or the flow LM) back to audio."""
latent = self.quantizer(latent.transpose(-1, -2))
@@ -122,7 +125,7 @@ class MimiModel(nn.Module):
return emb.transpose(-1, -2)
-def build_mimi(config) -> MimiModel:
+def build_mimi(config: MimiConfig) -> MimiModel:
"""MimiModel from a pocket-tts config's `mimi` section."""
from pocket_tts.modules import transformer
from pocket_tts.modules.dummy_quantizer import DummyQuantizer
diff --git a/pocket_tts/models/text_chunking.py b/pocket_tts/models/text_chunking.py
index 1d48f6c..4255ef9 100644
--- a/pocket_tts/models/text_chunking.py
+++ b/pocket_tts/models/text_chunking.py
@@ -6,6 +6,8 @@ boundaries and regrouped into chunks that fit `max_tokens`.
import logging
+from pocket_tts.modules.text_conditioner import SentencePieceTokenizer
+
logger = logging.getLogger(__name__)
@@ -42,7 +44,7 @@ def prepare_text_prompt(
def _is_decimal_period_boundary(
- list_of_tokens: list[int], segment_start_idx: int, tokenizer
+ list_of_tokens: list[int], segment_start_idx: int, tokenizer: SentencePieceTokenizer
) -> bool:
"""Return True when segment_start_idx begins right after a decimal period."""
prefix = tokenizer.sp.decode(list_of_tokens[:segment_start_idx])
@@ -59,7 +61,7 @@ def _is_decimal_period_boundary(
def _find_boundary_indices(
list_of_tokens: list[int],
boundary_tokens: list[int],
- tokenizer=None,
+ tokenizer: SentencePieceTokenizer | None = None,
skip_decimal_periods: bool = False,
) -> list[int]:
"""Find token indices where text should be split based on boundary tokens.
@@ -90,7 +92,7 @@ def _find_boundary_indices(
def _segments_from_boundaries(
- list_of_tokens: list[int], boundary_indices: list[int], tokenizer
+ list_of_tokens: list[int], boundary_indices: list[int], tokenizer: SentencePieceTokenizer
) -> list[tuple[int, str]]:
"""Decode token segments between boundary indices into (token_count, text) pairs."""
segments = []
@@ -103,7 +105,7 @@ def _segments_from_boundaries(
def split_into_best_sentences(
- tokenizer,
+ tokenizer: SentencePieceTokenizer,
text_to_generate: str,
max_tokens: int,
pad_with_spaces_for_short_inputs: bool,
diff --git a/pocket_tts/models/tts_model.py b/pocket_tts/models/tts_model.py
index 2c0e7e1..5db7af9 100644
--- a/pocket_tts/models/tts_model.py
+++ b/pocket_tts/models/tts_model.py
@@ -6,6 +6,7 @@ import queue
import statistics
import threading
import time
+from collections.abc import Iterator
from functools import lru_cache
from pathlib import Path
from typing import Any
@@ -62,7 +63,7 @@ LatentQueue = queue.Queue[torch.Tensor | None]
ResultQueue = queue.Queue[tuple[str, Any]]
-def stamp_state_names(tts_model) -> None:
+def stamp_state_names(tts_model: "TTSModel"):
"""StatefulModules find their slice of the state dict by absolute name."""
for top_module in (tts_model.flow_lm, tts_model.mimi):
for module_name, module in top_module.named_modules():
@@ -90,7 +91,7 @@ class TTSModel(nn.Module):
temp: float,
sampler_decode_steps: int,
noise_clamp: float | None,
- eos_threshold,
+ eos_threshold: float,
config: Config,
origin: Path | None = None,
pad_with_spaces_for_short_inputs: bool = False,
@@ -122,10 +123,10 @@ class TTSModel(nn.Module):
def _from_pydantic_config(
cls,
config: Config,
- temp,
- sampler_decode_steps,
+ temp: float,
+ sampler_decode_steps: int,
noise_clamp: float | None,
- eos_threshold,
+ eos_threshold: float,
origin: Path | None,
) -> Self:
flow_lm = FlowLMModel.from_pydantic_config(
@@ -149,7 +150,7 @@ class TTSModel(nn.Module):
has_custom_weights: bool = False
- def load_training_checkpoint(self, path: str | Path, use_ema: bool = True) -> None:
+ def load_training_checkpoint(self, path: str | Path, use_ema: bool = True):
"""Load weights from a training checkpoint (.pt) into a config-built model."""
self.has_custom_weights = True
flow_lm_state, mimi_state = get_training_checkpoint_state_dicts(Path(path), use_ema)
@@ -195,10 +196,10 @@ class TTSModel(nn.Module):
def _from_pydantic_config_with_weights(
cls,
config: Config,
- temp,
- sampler_decode_steps,
+ temp: float,
+ sampler_decode_steps: int,
noise_clamp: float | None,
- eos_threshold,
+ eos_threshold: float,
origin: Path | None = None,
) -> Self:
tts_model = cls._from_pydantic_config(
@@ -445,7 +446,7 @@ class TTSModel(nn.Module):
conditioning = F.linear(latents, self.flow_lm.speaker_proj_weight)
return conditioning
- def _expand_kv_cache(self, model_state: ModelState, sequence_length: int) -> None:
+ def _expand_kv_cache(self, model_state: ModelState, sequence_length: int):
"""Expand KV cache back to full sequence_length for generation.
When a model state is retrieved from cache with sliced KV caches,
@@ -605,7 +606,7 @@ class TTSModel(nn.Module):
max_tokens: int = MAX_TOKEN_PER_CHUNK,
frames_after_eos: int | None = None,
copy_state: bool = True,
- ):
+ ) -> Iterator[torch.Tensor]:
"""Generate audio streaming chunks from text input.
This method generates audio from text and yields chunks as they become
@@ -693,7 +694,7 @@ class TTSModel(nn.Module):
text_to_generate: str,
frames_after_eos: int,
copy_state: bool,
- ):
+ ) -> Iterator[torch.Tensor]:
if copy_state:
model_state = copy.deepcopy(model_state)
@@ -829,6 +830,7 @@ class TTSModel(nn.Module):
# Add generated latent to queue for immediate decoding
latents_queue.put(next_latent)
backbone_input = next_latent
+ assert timer.elapsed_time_ms is not None
steps_times.append(timer.elapsed_time_ms)
else:
if os.environ.get("KPOCKET_TTS_ERROR_WITHOUT_EOS", "0") == "1":
diff --git a/pocket_tts/modules/attention.py b/pocket_tts/modules/attention.py
index 9cce318..1a87b4c 100644
--- a/pocket_tts/modules/attention.py
+++ b/pocket_tts/modules/attention.py
@@ -80,7 +80,7 @@ class _LinearKVCacheBackend:
),
)
- def increment_step(self, state: dict[str, torch.Tensor], increment: int) -> None:
+ def increment_step(self, state: dict[str, torch.Tensor], increment: int):
state["offset"] += increment
def rope_offset(
@@ -172,7 +172,7 @@ class StreamingMultiheadAttention(StatefulModule):
query: torch.Tensor,
model_state: ModelState | None,
attn_mask: torch.Tensor | None = None,
- ):
+ ) -> torch.Tensor:
state = None if model_state is None else self.get_state(model_state)
projected = self.in_proj(query)
diff --git a/pocket_tts/modules/conv.py b/pocket_tts/modules/conv.py
index 56470b7..00ae53f 100644
--- a/pocket_tts/modules/conv.py
+++ b/pocket_tts/modules/conv.py
@@ -18,7 +18,9 @@ def get_extra_padding_for_conv1d(
return ideal_length - length
-def pad_for_conv1d(x: torch.Tensor, kernel_size: int, stride: int, padding_total: int = 0):
+def pad_for_conv1d(
+ x: torch.Tensor, kernel_size: int, stride: int, padding_total: int = 0
+) -> torch.Tensor:
"""Pad for a convolution to make sure that the last window is full.
Extra padding is added at the end. This is required to ensure that we can rebuild
an output of the same length, as otherwise, even with padding, some time steps
@@ -90,7 +92,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: ModelState | None):
+ def forward(self, x: torch.Tensor, model_state: ModelState | None) -> torch.Tensor:
B, C, T = x.shape
S = self._stride
assert T > 0 and T % S == 0, "Steps must be multiple of stride"
@@ -148,7 +150,7 @@ class StreamingConvTranspose1d(StatefulModule):
device = self.convtr.weight.device
return dict(partial=torch.zeros(batch_size, self.convtr.out_channels, K - S, device=device))
- def forward(self, x, mimi_state: ModelState):
+ def forward(self, x: torch.Tensor, mimi_state: ModelState) -> torch.Tensor:
layer_state = self.get_state(mimi_state)["partial"]
y = self.convtr(x)
PT = layer_state.shape[-1]
diff --git a/pocket_tts/modules/layer_scale.py b/pocket_tts/modules/layer_scale.py
index 67443d0..36bb263 100644
--- a/pocket_tts/modules/layer_scale.py
+++ b/pocket_tts/modules/layer_scale.py
@@ -7,5 +7,5 @@ class LayerScale(nn.Module):
super().__init__()
self.scale = nn.Parameter(torch.full((channels,), init))
- def forward(self, x: torch.Tensor):
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.scale * x
diff --git a/pocket_tts/modules/mlp.py b/pocket_tts/modules/mlp.py
index aca0a8a..8853597 100644
--- a/pocket_tts/modules/mlp.py
+++ b/pocket_tts/modules/mlp.py
@@ -13,11 +13,11 @@ from typing_extensions import Self
from pocket_tts.utils.config import FlowLMConfig
-def modulate(x, shift, scale):
+def modulate(x: torch.Tensor, shift: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:
return x * (1 + scale) + shift
-def _rms_norm(x: torch.Tensor, alpha: torch.Tensor, eps: float):
+def _rms_norm(x: torch.Tensor, alpha: torch.Tensor, eps: float) -> torch.Tensor:
assert x.dim() >= alpha.dim()
x_dtype = x.dtype
var = eps + x.var(dim=-1, keepdim=True)
@@ -32,21 +32,21 @@ class RMSNorm(nn.Module):
alpha_shape = (dim,)
self.alpha = nn.Parameter(torch.full(alpha_shape, 1.0, requires_grad=True))
- def forward(self, x: torch.Tensor):
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
return _rms_norm(x, self.alpha, self.eps)
class LayerNorm(nn.Module):
"""Reimplementation of LayerNorm because the default one doesn't support jvp."""
- def __init__(self, channels, eps=1e-6, elementwise_affine=True):
+ def __init__(self, channels: int, eps: float = 1e-6, elementwise_affine: bool = True):
super().__init__()
self.eps = eps
if elementwise_affine:
self.weight = nn.Parameter(torch.ones(channels))
self.bias = nn.Parameter(torch.zeros(channels))
- def forward(self, x):
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
mean = x.mean(dim=-1, keepdim=True)
var = x.var(dim=-1, unbiased=False, keepdim=True)
x = (x - mean) / torch.sqrt(var + self.eps)
@@ -58,6 +58,8 @@ class LayerNorm(nn.Module):
class TimestepEmbedder(nn.Module):
"""Embeds scalar timesteps into vector representations."""
+ freqs: torch.Tensor
+
def __init__(
self, hidden_size: int, frequency_embedding_size: int = 256, max_period: int = 10000
):
@@ -75,7 +77,7 @@ class TimestepEmbedder(nn.Module):
"freqs", torch.exp(-math.log(max_period) * torch.arange(start=0, end=half) / half)
)
- def forward(self, t):
+ def forward(self, t: torch.Tensor) -> torch.Tensor:
args = t * self.freqs.to(t.dtype)
embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
assert not (self.frequency_embedding_size % 2)
@@ -89,7 +91,7 @@ class ResBlock(nn.Module):
:param channels: the number of input channels.
"""
- def __init__(self, channels):
+ def __init__(self, channels: int):
super().__init__()
self.channels = channels
@@ -104,7 +106,7 @@ class ResBlock(nn.Module):
nn.SiLU(), nn.Linear(channels, 3 * channels, bias=True)
)
- def forward(self, x, y):
+ def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(y).chunk(3, dim=-1)
h = modulate(self.in_ln(x), shift_mlp, scale_mlp)
h = self.mlp(h)
@@ -116,7 +118,7 @@ class FinalLayer(nn.Module):
The final layer adopted from DiT.
"""
- def __init__(self, model_channels, out_channels):
+ def __init__(self, model_channels: int, out_channels: int):
super().__init__()
self.norm_final = LayerNorm(model_channels, elementwise_affine=False, eps=1e-6)
self.linear = nn.Linear(model_channels, out_channels, bias=True)
@@ -124,7 +126,7 @@ class FinalLayer(nn.Module):
nn.SiLU(), nn.Linear(model_channels, 2 * model_channels, bias=True)
)
- def forward(self, x, c):
+ def forward(self, x: torch.Tensor, c: torch.Tensor) -> torch.Tensor:
shift, scale = self.adaLN_modulation(c).chunk(2, dim=-1)
x = modulate(self.norm_final(x), shift, scale)
x = self.linear(x)
@@ -144,12 +146,12 @@ class SimpleMLPAdaLN(nn.Module):
def __init__(
self,
- in_channels,
- model_channels,
- out_channels,
- cond_channels,
- num_res_blocks,
- num_time_conds=1,
+ in_channels: int,
+ model_channels: int,
+ out_channels: int,
+ cond_channels: int,
+ num_res_blocks: int,
+ num_time_conds: int = 1,
):
super().__init__()
diff --git a/pocket_tts/modules/resample.py b/pocket_tts/modules/resample.py
index 3b3c427..054521e 100644
--- a/pocket_tts/modules/resample.py
+++ b/pocket_tts/modules/resample.py
@@ -26,7 +26,7 @@ class ConvDownsample1d(nn.Module):
pad_mode="replicate",
)
- def forward(self, x: torch.Tensor, model_state: ModelState | None):
+ def forward(self, x: torch.Tensor, model_state: ModelState | None) -> torch.Tensor:
return self.conv(x, model_state)
@@ -48,5 +48,5 @@ class ConvTrUpsample1d(nn.Module):
bias=False,
)
- def forward(self, x: torch.Tensor, model_state: ModelState | None):
+ def forward(self, x: torch.Tensor, model_state: ModelState | None) -> torch.Tensor:
return self.convtr(x, model_state)
diff --git a/pocket_tts/modules/rope.py b/pocket_tts/modules/rope.py
index 2c15575..25f70d3 100644
--- a/pocket_tts/modules/rope.py
+++ b/pocket_tts/modules/rope.py
@@ -6,7 +6,7 @@ from torch import nn
def apply_rope(
q: torch.Tensor, k: torch.Tensor, offset: int | torch.Tensor = 0, max_period: float = 10_000
-):
+) -> tuple[torch.Tensor, torch.Tensor]:
"""
Args:
q (torch.Tensor): Queries, shape `[B, T, H, D]`.
@@ -66,6 +66,8 @@ class RotaryEmbedding(nn.Module):
super().__init__()
self.max_period = max_period
- def forward(self, q: torch.Tensor, k: torch.Tensor, offset: torch.Tensor | int):
+ def forward(
+ self, q: torch.Tensor, k: torch.Tensor, offset: torch.Tensor | int
+ ) -> tuple[torch.Tensor, torch.Tensor]:
"""Apply rope rotation to query or key tensor."""
return apply_rope(q, k, offset, self.max_period)
diff --git a/pocket_tts/modules/seanet.py b/pocket_tts/modules/seanet.py
index bb471ef..92ee987 100644
--- a/pocket_tts/modules/seanet.py
+++ b/pocket_tts/modules/seanet.py
@@ -1,6 +1,7 @@
from collections.abc import Sequence
import numpy as np
+import torch
import torch.nn as nn
from pocket_tts.modules.stateful_module import ModelState
@@ -34,7 +35,7 @@ class SEANetResnetBlock(nn.Module):
]
self.block = block
- def forward(self, x, model_state: ModelState | None):
+ def forward(self, x: torch.Tensor, model_state: ModelState | None) -> torch.Tensor:
v = x
for layer in self.block:
if isinstance(layer, StreamingConv1d):
@@ -108,7 +109,7 @@ class SEANetEncoder(nn.Module):
self.model = model
- def forward(self, x, model_state: ModelState | None):
+ def forward(self, x: torch.Tensor, model_state: ModelState | None) -> torch.Tensor:
for layer in self.model:
if isinstance(layer, (StreamingConv1d, SEANetResnetBlock)):
x = layer(x, model_state)
@@ -175,7 +176,7 @@ class SEANetDecoder(nn.Module):
]
self.model = model
- def forward(self, z, model_state: ModelState | None):
+ def forward(self, z: torch.Tensor, model_state: ModelState | None) -> torch.Tensor:
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.py
index 6520de8..9aa738e 100644
--- a/pocket_tts/modules/stateful_module.py
+++ b/pocket_tts/modules/stateful_module.py
@@ -27,9 +27,9 @@ def increment_steps(module: nn.Module, model_state: ModelState, increment: int =
class StatefulModule(ABC, nn.Module):
- def __init__(self, *args, **kwds):
+ def __init__(self, *args: object, **kwds: object):
self._module_absolute_name: str | None = None
- return super().__init__(*args, **kwds)
+ super().__init__(*args, **kwds)
@abstractmethod
def init_state(self, batch_size: int, sequence_length: int) -> dict[str, torch.Tensor]:
diff --git a/pocket_tts/modules/text_conditioner.py b/pocket_tts/modules/text_conditioner.py
index 3fa5c78..f98a7e1 100644
--- a/pocket_tts/modules/text_conditioner.py
+++ b/pocket_tts/modules/text_conditioner.py
@@ -22,7 +22,7 @@ class SentencePieceTokenizer:
"""
- def __init__(self, nbins: int, tokenizer_path: str) -> None:
+ def __init__(self, nbins: int, tokenizer_path: str):
logger.info("Loading sentencepiece tokenizer from %s", tokenizer_path)
local_path = download_if_necessary(tokenizer_path)
self.sp = sentencepiece.SentencePieceProcessor(str(local_path))
diff --git a/pocket_tts/modules/transformer.py b/pocket_tts/modules/transformer.py
index 0dcb648..16b1034 100644
--- a/pocket_tts/modules/transformer.py
+++ b/pocket_tts/modules/transformer.py
@@ -106,7 +106,7 @@ class StreamingTransformer(nn.Module):
max_period=float(config.max_period),
)
- def forward(self, x: torch.Tensor, model_state: ModelState | None):
+ def forward(self, x: torch.Tensor, model_state: ModelState | None) -> torch.Tensor:
attn_mask = None
if model_state is None:
# Stateless (training) path: one shared mask for all layers, built
@@ -153,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: ModelState | None):
+ def forward(self, x: torch.Tensor, model_state: ModelState | None) -> list[torch.Tensor]:
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.py
index f037208..aa1f878 100644
--- a/pocket_tts/quantization.py
+++ b/pocket_tts/quantization.py
@@ -24,7 +24,7 @@ logger = logging.getLogger(__name__)
RECOMMENDED_CONFIG = {"attention", "ffn"}
-def _get_backend():
+def _get_backend() -> str:
"""Detect the best available quantization backend.
Returns "torchao" if torchao is installed with working C++ extensions,
@@ -94,7 +94,7 @@ def apply_dynamic_int8(flow_lm: FlowLMModel, quantize_groups: set[str]) -> FlowL
return flow_lm
-def _apply_torchao(flow_lm: FlowLMModel, quantize_groups: set[str]) -> None:
+def _apply_torchao(flow_lm: FlowLMModel, quantize_groups: set[str]):
"""Apply quantization using torchao backend."""
if "flow_net" in quantize_groups:
_quantize_module_torchao(flow_lm.flow_net)
@@ -113,7 +113,7 @@ def _apply_torchao(flow_lm: FlowLMModel, quantize_groups: set[str]) -> None:
layer.linear2 = wrapper2[0]
-def _apply_torch_ao(flow_lm: FlowLMModel, quantize_groups: set[str]) -> None:
+def _apply_torch_ao(flow_lm: FlowLMModel, quantize_groups: set[str]):
"""Apply quantization using deprecated torch.ao backend (fallback)."""
from torch.ao.quantization import quantize_dynamic
diff --git a/pocket_tts/utils/debugging.py b/pocket_tts/utils/debugging.py
index 9c13c10..440d55d 100644
--- a/pocket_tts/utils/debugging.py
+++ b/pocket_tts/utils/debugging.py
@@ -1,8 +1,11 @@
+from collections.abc import Callable, Mapping, Sequence
+from typing import Any
+
import torch
from torch.utils._python_dispatch import TorchDispatchMode
-def to_str(obj):
+def to_str(obj: object) -> str:
if isinstance(obj, (torch.Tensor, torch.nn.Parameter)):
return f"T(s={list(obj.shape)})"
elif isinstance(obj, (list, tuple)):
@@ -16,7 +19,13 @@ def to_str(obj):
class LoggingMode(TorchDispatchMode):
"""Useful to check implementation differences."""
- def __torch_dispatch__(self, func, types, args=(), kwargs=None):
+ def __torch_dispatch__(
+ self,
+ func: Callable[..., Any],
+ types: Sequence[type],
+ args: Sequence[Any] = (),
+ kwargs: Mapping[str, Any] | None = None,
+ ) -> Any: # noqa: ANN401 -- aten ops return arbitrary values
output = func(*args, **kwargs or {})
print(
f"Aten function called: {func}, args: "
diff --git a/pocket_tts/utils/logging_utils.py b/pocket_tts/utils/logging_utils.py
index 58b328e..d29e87a 100644
--- a/pocket_tts/utils/logging_utils.py
+++ b/pocket_tts/utils/logging_utils.py
@@ -1,14 +1,15 @@
import logging
+from collections.abc import Iterator
from contextlib import contextmanager
class PocketTTSFilter(logging.Filter):
- def filter(self, record):
+ def filter(self, record: logging.LogRecord) -> bool:
return record.name.startswith("pocket_tts")
@contextmanager
-def enable_logging(library_name, level):
+def enable_logging(library_name: str, level: int | str) -> Iterator[logging.Logger]:
# Get the specific logger and its parent
logger = logging.getLogger(library_name)
parent_logger = logging.getLogger("pocket_tts")
diff --git a/pocket_tts/utils/utils.py b/pocket_tts/utils/utils.py
index da55348..3494128 100644
--- a/pocket_tts/utils/utils.py
+++ b/pocket_tts/utils/utils.py
@@ -3,6 +3,7 @@ import logging
import os
import time
from pathlib import Path
+from types import TracebackType
from typing import Any
from urllib.parse import urlparse
@@ -10,6 +11,7 @@ import requests
import torch
from huggingface_hub import hf_hub_download
from torch import nn
+from typing_extensions import Self
PROJECT_ROOT = Path(__file__).parent.parent.parent
DEBUG_MIMI = os.environ.get("DEBUG_MIMI", "0") == "1"
@@ -82,11 +84,16 @@ class display_execution_time:
self.elapsed_time_ms: int | None = None
self.logger = logging.getLogger(__name__)
- def __enter__(self):
+ def __enter__(self) -> Self:
self.start_time = time.monotonic()
return self
- def __exit__(self, exc_type, exc_val, exc_tb):
+ def __exit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_val: BaseException | None,
+ exc_tb: TracebackType | None,
+ ) -> bool:
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)
diff --git a/pyproject.toml b/pyproject.toml
index 8a98d34..f926017 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -12,7 +12,7 @@ dependencies = [
"sentencepiece>=0.2.1",
"safetensors>=0.4.0",
"typer>=0.10.0",
- "typing_extensions>=4.0.0",
+ "typing_extensions>=4.10.0",
"fastapi>=0.100",
"uvicorn>=0.13.0",
"python-multipart>=0.0.21",
@@ -56,6 +56,12 @@ dev = [
[tool.ruff]
line-length = 100
+[tool.ruff.lint]
+extend-select = ["ANN"]
+
+[tool.ruff.lint.flake8-annotations]
+suppress-none-returning = true
+
[tool.ruff.format]
line-ending = "lf"
# avoid having a trailing comma changing
diff --git a/scripts/evaluate_quantization.py b/scripts/evaluate_quantization.py
index 2c31be2..e0005b2 100644
--- a/scripts/evaluate_quantization.py
+++ b/scripts/evaluate_quantization.py
@@ -23,7 +23,7 @@ import time
from dataclasses import asdict, dataclass, field
from datetime import datetime
from pathlib import Path
-from typing import Any, Optional
+from typing import Any, Optional, Protocol
import numpy as np
import numpy.typing as npt
@@ -46,6 +46,12 @@ CONFIGS = {
}
+class Transcriber(Protocol):
+ """The part of a Whisper model that compute_wer uses."""
+
+ def transcribe(self, audio: str, language: str) -> dict[str, Any]: ...
+
+
def get_model_size_mb(model: torch.nn.Module) -> float:
"""Returns model size in MB by serializing to a byte buffer."""
import io
@@ -131,7 +137,7 @@ class ConfigSummary:
quality_results: list[QualityResult] = field(default_factory=list)
-def load_and_quantize_model(config_id: str):
+def load_and_quantize_model(config_id: str) -> tuple[TTSModel, float, float]:
"""Load and quantize model. Returns (model, load_time, model_size_mb)."""
quantize_groups = CONFIGS[config_id]
@@ -149,14 +155,16 @@ def load_and_quantize_model(config_id: str):
return tts_model, load_time, model_size
-def save_audio(audio_tensor, sample_rate, output_path):
+def save_audio(audio_tensor: torch.Tensor, sample_rate: int, output_path: Path):
"""Save audio tensor to WAV file."""
audio_np = audio_tensor.numpy() if hasattr(audio_tensor, "numpy") else np.array(audio_tensor)
audio_int16 = (audio_np * 32767).clip(-32768, 32767).astype(np.int16)
scipy.io.wavfile.write(str(output_path), sample_rate, audio_int16)
-def generate_for_voice(tts_model, voice, config_id, output_dir):
+def generate_for_voice(
+ tts_model: TTSModel, voice: str, config_id: str, output_dir: Path
+) -> GenerationResult:
"""Generate audio for a single voice and return metrics."""
logger.info("[%s] Generating for voice: %s", config_id, voice)
@@ -267,7 +275,9 @@ def compute_pesq(
return None
-def compute_wer(audio_path: str, reference_text: str, whisper_model) -> tuple[Optional[float], str]:
+def compute_wer(
+ audio_path: str | Path, reference_text: str, whisper_model: Transcriber
+) -> tuple[Optional[float], str]:
"""Compute Word Error Rate using Whisper. Returns (wer, transcript)."""
try:
from jiwer import wer
@@ -281,8 +291,13 @@ def compute_wer(audio_path: str, reference_text: str, whisper_model) -> tuple[Op
def run_quality_eval(
- baseline_model, quantized_model, config_id, voice, output_dir, whisper_model=None
-):
+ baseline_model: TTSModel,
+ quantized_model: TTSModel,
+ config_id: str,
+ voice: str,
+ output_dir: Path,
+ whisper_model: Transcriber | None = None,
+) -> list[QualityResult]:
"""Run quality evaluation for a single voice across all quality sentences."""
results = []
voice_state_b = baseline_model.get_state_for_audio_prompt(voice)
@@ -355,7 +370,7 @@ def run_quality_eval(
# ---------------------------------------------------------------------------
-def run_config(config_id, output_dir, voices):
+def run_config(config_id: str, output_dir: Path, voices: list[str]) -> ConfigSummary:
"""Run full evaluation for a single quantization config."""
logger.info("=" * 60)
logger.info("Evaluating config: %s (groups: %s)", config_id, CONFIGS[config_id] or "none")
@@ -392,7 +407,7 @@ def run_config(config_id, output_dir, voices):
# ---------------------------------------------------------------------------
-def write_csv(summaries, output_dir):
+def write_csv(summaries: list[ConfigSummary], output_dir: Path):
csv_path = output_dir / "results.csv"
with open(csv_path, "w", newline="") as f:
writer = csv.DictWriter(
@@ -430,7 +445,7 @@ def write_csv(summaries, output_dir):
logger.info("CSV written: %s", csv_path)
-def write_quality_csv(summaries, output_dir):
+def write_quality_csv(summaries: list[ConfigSummary], output_dir: Path):
csv_path = output_dir / "quality_results.csv"
rows = []
for s in summaries:
@@ -445,7 +460,7 @@ def write_quality_csv(summaries, output_dir):
logger.info("Quality CSV written: %s", csv_path)
-def write_markdown_report(summaries, output_dir):
+def write_markdown_report(summaries: list[ConfigSummary], output_dir: Path):
report_path = output_dir / "report.md"
lines = [
"# pocket-tts int8 Quantization Evaluation Report",
@@ -503,7 +518,7 @@ def write_markdown_report(summaries, output_dir):
logger.info("Report written: %s", report_path)
-def write_json_summary(summaries, output_dir):
+def write_json_summary(summaries: list[ConfigSummary], output_dir: Path):
json_path = output_dir / "summary.json"
json_path.write_text(json.dumps([asdict(s) for s in summaries], indent=2))
logger.info("JSON summary written: %s", json_path)
diff --git a/tests/test_audio.py b/tests/test_audio.py
index b36b898..b4b5aad 100644
--- a/tests/test_audio.py
+++ b/tests/test_audio.py
@@ -1,11 +1,12 @@
import wave
+from pathlib import Path
import torch
from pocket_tts.data.audio import audio_read, stream_audio_chunks
-def test_stream_audio_chunks_patches_seekable_wav_header(tmp_path):
+def test_stream_audio_chunks_patches_seekable_wav_header(tmp_path: Path):
output_file = tmp_path / "output.wav"
samples = torch.zeros(24000)
@@ -16,7 +17,7 @@ def test_stream_audio_chunks_patches_seekable_wav_header(tmp_path):
assert wav_file.getnframes() == 28800
-def test_audio_read_uses_soundfile_for_8_bit_wav(tmp_path):
+def test_audio_read_uses_soundfile_for_8_bit_wav(tmp_path: Path):
output_file = tmp_path / "silence_u8.wav"
with wave.open(str(output_file), "wb") as wav_file:
wav_file.setnchannels(1)
diff --git a/tests/test_cli_generate.py b/tests/test_cli_generate.py
index d8ca733..24ffd51 100644
--- a/tests/test_cli_generate.py
+++ b/tests/test_cli_generate.py
@@ -1,6 +1,7 @@
"""Integration tests for the CLI generate command using real implementation."""
import os
+from pathlib import Path
import pytest
from typer.testing import CliRunner
@@ -16,7 +17,7 @@ IS_CI = os.environ.get("CI") == "true"
CI_SKIP_REASON = "Voice cloning is not publicly available, skipping in the CI"
-def test_generate_basic_usage(tmp_path):
+def test_generate_basic_usage(tmp_path: Path):
"""Test basic generate command with default parameters."""
output_file = tmp_path / "test_output.wav"
@@ -38,7 +39,7 @@ def test_generate_basic_usage(tmp_path):
@pytest.mark.skipif(IS_CI, reason=CI_SKIP_REASON)
-def test_generate_with_custom_voice(tmp_path):
+def test_generate_with_custom_voice(tmp_path: Path):
"""Test generate command with custom voice prompt."""
output_file = tmp_path / "custom_voice_test.wav"
@@ -65,7 +66,7 @@ def test_generate_with_custom_voice(tmp_path):
assert sample_rate == 24000
-def test_generate_with_custom_parameters(tmp_path):
+def test_generate_with_custom_parameters(tmp_path: Path):
"""Test generate command with custom generation parameters."""
output_file = tmp_path / "custom_params_test.wav"
@@ -99,7 +100,7 @@ def test_generate_with_custom_parameters(tmp_path):
assert sample_rate == 24000
-def test_generate_verbose_mode(tmp_path):
+def test_generate_verbose_mode(tmp_path: Path):
"""Test generate command with verbose logging."""
output_file = tmp_path / "verbose_test.wav"
@@ -112,7 +113,7 @@ def test_generate_verbose_mode(tmp_path):
assert output_file.exists()
-def test_generate_default_text(tmp_path):
+def test_generate_default_text(tmp_path: Path):
"""Test generate command with default text when no text provided."""
output_file = tmp_path / "default_text_test.wav"
@@ -127,7 +128,7 @@ def test_generate_default_text(tmp_path):
assert sample_rate == 24000
-def test_generate_long_text(tmp_path):
+def test_generate_long_text(tmp_path: Path):
"""Test generate command with longer text."""
long_text = "This is a longer text to test the TTS system. " * 5
output_file = tmp_path / "long_text_test.wav"
@@ -147,7 +148,7 @@ def test_generate_long_text(tmp_path):
assert audio.shape[1] > 24000 * 10 # At least 10 second of audio
-def test_generate_multiple_runs(tmp_path):
+def test_generate_multiple_runs(tmp_path: Path):
"""Test multiple consecutive generate commands."""
for i in range(3):
output_file = tmp_path / f"test_run_{i + 1}.wav"
diff --git a/tests/test_generation_regressions.py b/tests/test_generation_regressions.py
index e0976b8..e0155cc 100644
--- a/tests/test_generation_regressions.py
+++ b/tests/test_generation_regressions.py
@@ -1,25 +1,31 @@
import queue
+from collections.abc import Iterator
from types import SimpleNamespace
-from typing import cast
+from typing import NoReturn, cast
import pytest
import torch
import pocket_tts.models.tts_model as tts_model_module
from pocket_tts.models.tts_model import TTSModel, _is_safetensors_source
+from pocket_tts.modules.text_conditioner import SentencePieceTokenizer
-def test_generate_audio_stream_uses_prepared_chunk_text(monkeypatch):
- calls = []
+def test_generate_audio_stream_uses_prepared_chunk_text(monkeypatch: pytest.MonkeyPatch):
+ calls: list[dict[str, object]] = []
def fake_split_into_best_sentences(
- tokenizer, text_to_generate, max_tokens, pad_with_spaces_for_short_inputs, remove_semicolons
- ):
+ tokenizer: SentencePieceTokenizer,
+ text_to_generate: str,
+ max_tokens: int,
+ pad_with_spaces_for_short_inputs: bool,
+ remove_semicolons: bool,
+ ) -> list[str]:
assert text_to_generate == "hi"
assert pad_with_spaces_for_short_inputs is True
return ["hi"]
- def fake_generate_audio_stream_short_text(**kwargs):
+ def fake_generate_audio_stream_short_text(**kwargs: object) -> Iterator[torch.Tensor]:
calls.append(kwargs)
yield torch.tensor([0.0])
@@ -48,7 +54,7 @@ def test_generate_audio_stream_uses_prepared_chunk_text(monkeypatch):
def test_generate_reports_autoregressive_errors_before_decoder_done():
error = RuntimeError("generation failed")
- def raise_generation(*args, **kwargs):
+ def raise_generation(*args: object, **kwargs: object) -> NoReturn:
raise error
model = cast(
@@ -88,5 +94,5 @@ def test_generate_reports_autoregressive_errors_before_decoder_done():
("https://example.com/voice.wav?format=safetensors", False),
],
)
-def test_is_safetensors_source_handles_revisions_and_query_strings(source, expected):
+def test_is_safetensors_source_handles_revisions_and_query_strings(source: str, expected: bool):
assert _is_safetensors_source(source) is expected
diff --git a/tests/test_quantization.py b/tests/test_quantization.py
index 5dae240..83a47d1 100644
--- a/tests/test_quantization.py
+++ b/tests/test_quantization.py
@@ -8,6 +8,8 @@ Verifies:
4. Backend detection works
"""
+from pathlib import Path
+
import torch
from typer.testing import CliRunner
@@ -48,7 +50,7 @@ def test_quantize_flag_applies_quantization():
)
-def test_cli_quantize_flag(tmp_path):
+def test_cli_quantize_flag(tmp_path: Path):
output_file = tmp_path / "quantized_output.wav"
result = runner.invoke(
cli_app,
diff --git a/tests/test_serve_default_voice.py b/tests/test_serve_default_voice.py
index 69f7bf8..24732eb 100644
--- a/tests/test_serve_default_voice.py
+++ b/tests/test_serve_default_voice.py
@@ -1,8 +1,11 @@
"""Tests for the default voice of the `serve` command and of the /tts endpoint."""
+from collections.abc import Iterator
+from pathlib import Path
from types import SimpleNamespace
from typing import Any
+import pytest
import torch
from fastapi.testclient import TestClient
from typer.testing import CliRunner
@@ -17,26 +20,28 @@ class FakeTTSModel:
def __init__(self):
self.config = SimpleNamespace(mimi=SimpleNamespace(sample_rate=24000))
- self.voices_requested = []
- self.states_used = []
+ self.voices_requested: list[Path | str | torch.Tensor] = []
+ self.states_used: list[dict[str, Any]] = []
def get_state_for_audio_prompt(
- self, audio_conditioning, truncate: bool = False
+ self, audio_conditioning: Path | str | torch.Tensor, 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
+ self, audio_conditioning: Path | str | torch.Tensor, truncate: bool = False
) -> dict[str, Any]:
return self.get_state_for_audio_prompt(audio_conditioning, truncate)
- def generate_audio_stream(self, model_state: dict[str, Any], text_to_generate: str):
+ def generate_audio_stream(
+ self, model_state: dict[str, Any], text_to_generate: str
+ ) -> Iterator[torch.Tensor]:
self.states_used.append(model_state)
yield torch.zeros(2400)
-def make_serve_runnable(monkeypatch) -> FakeTTSModel:
+def make_serve_runnable(monkeypatch: pytest.MonkeyPatch) -> FakeTTSModel:
"""Make `serve` return right before listening, with a fake model."""
fake_model = FakeTTSModel()
monkeypatch.setattr(main, "TTSModel", SimpleNamespace(load_model=lambda **kwargs: fake_model))
@@ -46,7 +51,7 @@ def make_serve_runnable(monkeypatch) -> FakeTTSModel:
return fake_model
-def test_serve_loads_the_voice_given_by_the_default_voice_option(monkeypatch):
+def test_serve_loads_the_voice_given_by_the_default_voice_option(monkeypatch: pytest.MonkeyPatch):
fake_model = make_serve_runnable(monkeypatch)
result = runner.invoke(main.cli_app, ["serve", "--default-voice", "./my_voice.safetensors"])
@@ -56,7 +61,7 @@ def test_serve_loads_the_voice_given_by_the_default_voice_option(monkeypatch):
assert main.default_voice_state == {"voice": "./my_voice.safetensors"}
-def test_serve_falls_back_to_the_voice_of_the_language(monkeypatch):
+def test_serve_falls_back_to_the_voice_of_the_language(monkeypatch: pytest.MonkeyPatch):
fake_model = make_serve_runnable(monkeypatch)
result = runner.invoke(main.cli_app, ["serve", "--language", "french_24l"])
@@ -66,7 +71,9 @@ def test_serve_falls_back_to_the_voice_of_the_language(monkeypatch):
assert main.default_voice_state == {"voice": "estelle"}
-def test_tts_endpoint_uses_the_default_voice_when_the_request_has_none(monkeypatch):
+def test_tts_endpoint_uses_the_default_voice_when_the_request_has_none(
+ monkeypatch: pytest.MonkeyPatch,
+):
fake_model = FakeTTSModel()
monkeypatch.setattr(main, "tts_model", fake_model)
monkeypatch.setattr(main, "default_voice_state", {"voice": "./my_voice.wav"})
@@ -79,7 +86,9 @@ def test_tts_endpoint_uses_the_default_voice_when_the_request_has_none(monkeypat
assert fake_model.states_used == [{"voice": "./my_voice.wav"}]
-def test_tts_endpoint_prefers_the_voice_of_the_request_over_the_default(monkeypatch):
+def test_tts_endpoint_prefers_the_voice_of_the_request_over_the_default(
+ monkeypatch: pytest.MonkeyPatch,
+):
fake_model = FakeTTSModel()
monkeypatch.setattr(main, "tts_model", fake_model)
monkeypatch.setattr(main, "default_voice_state", {"voice": "./my_voice.wav"})
@@ -93,7 +102,9 @@ def test_tts_endpoint_prefers_the_voice_of_the_request_over_the_default(monkeypa
assert fake_model.states_used == [{"voice": "marius"}]
-def test_tts_endpoint_still_rejects_a_voice_url_that_is_not_a_voice(monkeypatch):
+def test_tts_endpoint_still_rejects_a_voice_url_that_is_not_a_voice(
+ monkeypatch: pytest.MonkeyPatch,
+):
fake_model = FakeTTSModel()
monkeypatch.setattr(main, "tts_model", fake_model)
monkeypatch.setattr(main, "default_voice_state", {"voice": "./my_voice.wav"})
diff --git a/tests/test_split_sentences.py b/tests/test_split_sentences.py
index aa2abff..6fc28f2 100644
--- a/tests/test_split_sentences.py
+++ b/tests/test_split_sentences.py
@@ -3,15 +3,15 @@
import pytest
from pocket_tts.models.tts_model import split_into_best_sentences
-from pocket_tts.modules.text_conditioner import get_default_tokenizer
+from pocket_tts.modules.text_conditioner import SentencePieceTokenizer, get_default_tokenizer
@pytest.fixture(scope="session")
-def tokenizer():
+def tokenizer() -> SentencePieceTokenizer:
return get_default_tokenizer()
-def test_short_text_single_chunk(tokenizer):
+def test_short_text_single_chunk(tokenizer: SentencePieceTokenizer):
"""Short text should produce a single chunk."""
chunks = split_into_best_sentences(
tokenizer,
@@ -23,7 +23,7 @@ def test_short_text_single_chunk(tokenizer):
assert len(chunks) == 1
-def test_multiple_sentences_split(tokenizer):
+def test_multiple_sentences_split(tokenizer: SentencePieceTokenizer):
"""Multiple sentences should be split when they exceed max_tokens."""
text = "First sentence here. Second sentence here. Third sentence here. Fourth sentence here."
chunks = split_into_best_sentences(
@@ -32,7 +32,7 @@ def test_multiple_sentences_split(tokenizer):
assert len(chunks) > 1
-def test_long_sentence_with_commas_is_split(tokenizer):
+def test_long_sentence_with_commas_is_split(tokenizer: SentencePieceTokenizer):
"""A long sentence with only commas (no periods) should be split on commas."""
# This is the core bug from issue #38 - the Tale of Two Cities example
text = (
@@ -53,7 +53,7 @@ def test_long_sentence_with_commas_is_split(tokenizer):
assert phrase in rejoined, f"'{phrase}' should be preserved after splitting"
-def test_long_sentence_with_commas_respects_max_tokens(tokenizer):
+def test_long_sentence_with_commas_respects_max_tokens(tokenizer: SentencePieceTokenizer):
"""Each chunk from comma splitting should respect max_tokens (when possible)."""
text = (
"It was the best of times, it was the worst of times, "
@@ -72,7 +72,7 @@ def test_long_sentence_with_commas_respects_max_tokens(tokenizer):
)
-def test_mixed_sentences_and_commas(tokenizer):
+def test_mixed_sentences_and_commas(tokenizer: SentencePieceTokenizer):
"""Text with both sentence boundaries and long comma-separated clauses."""
text = (
"Short sentence. "
@@ -87,7 +87,7 @@ def test_mixed_sentences_and_commas(tokenizer):
assert len(chunks) >= 3
-def test_no_commas_no_periods_stays_single_chunk(tokenizer):
+def test_no_commas_no_periods_stays_single_chunk(tokenizer: SentencePieceTokenizer):
"""Text with no splitting characters stays as a single chunk."""
text = "one two three four five six seven eight nine ten eleven twelve"
chunks = split_into_best_sentences(
@@ -97,7 +97,7 @@ def test_no_commas_no_periods_stays_single_chunk(tokenizer):
assert len(chunks) == 1
-def test_semicolons_and_colons_also_split(tokenizer):
+def test_semicolons_and_colons_also_split(tokenizer: SentencePieceTokenizer):
"""Semicolons and colons should also serve as fallback split points."""
text = (
"First clause here; second clause here; third clause here; "
@@ -109,7 +109,7 @@ def test_semicolons_and_colons_also_split(tokenizer):
assert len(chunks) > 1
-def test_short_sentence_not_affected_by_comma_splitting(tokenizer):
+def test_short_sentence_not_affected_by_comma_splitting(tokenizer: SentencePieceTokenizer):
"""Sentences under max_tokens should not be affected by comma logic."""
text = "Hello, world."
chunks = split_into_best_sentences(
@@ -120,7 +120,7 @@ def test_short_sentence_not_affected_by_comma_splitting(tokenizer):
assert "world" in chunks[0].lower()
-def test_empty_string_raises(tokenizer):
+def test_empty_string_raises(tokenizer: SentencePieceTokenizer):
"""Empty input should raise ValueError from prepare_text_prompt."""
with pytest.raises(ValueError, match="empty"):
split_into_best_sentences(
@@ -128,7 +128,7 @@ def test_empty_string_raises(tokenizer):
)
-def test_decimals_are_not_split_on_period(tokenizer):
+def test_decimals_are_not_split_on_period(tokenizer: SentencePieceTokenizer):
"""Decimal periods must not be treated as sentence boundaries (issue #162)."""
text = (
"The average human body temperature is 98.6°F, which is a common decimal used in medicine."
@@ -141,7 +141,7 @@ def test_decimals_are_not_split_on_period(tokenizer):
assert "98. 6" not in chunks[0]
-def test_multiple_decimals_in_one_sentence(tokenizer):
+def test_multiple_decimals_in_one_sentence(tokenizer: SentencePieceTokenizer):
"""Several decimals in one sentence should stay intact."""
text = "Pi is 3.14 and e is 2.718."
chunks = split_into_best_sentences(
@@ -154,7 +154,7 @@ def test_multiple_decimals_in_one_sentence(tokenizer):
assert "2. 718" not in chunks[0]
-def test_decimal_followed_by_sentence_boundary(tokenizer):
+def test_decimal_followed_by_sentence_boundary(tokenizer: SentencePieceTokenizer):
"""Decimals should be preserved while real sentence boundaries still split."""
text = (
"The average human body temperature is 98.6°F, "
@@ -173,7 +173,7 @@ def test_decimal_followed_by_sentence_boundary(tokenizer):
assert "3. 14" not in rejoined
-def test_sentence_period_after_decimal_still_splits(tokenizer):
+def test_sentence_period_after_decimal_still_splits(tokenizer: SentencePieceTokenizer):
"""A period ending a sentence after a decimal is still a boundary."""
text = "Version 2.0 is out. Pi is 3.14."
chunks = split_into_best_sentences(
@@ -185,7 +185,7 @@ def test_sentence_period_after_decimal_still_splits(tokenizer):
assert "2. 0" not in chunks[0]
-def test_oversized_clause_without_commas_still_returns(tokenizer):
+def test_oversized_clause_without_commas_still_returns(tokenizer: SentencePieceTokenizer):
"""A long clause with no split points should still be returned (not dropped)."""
# 20 words with no punctuation at all - no way to split
text = " ".join(f"word{i}" for i in range(20))
diff --git a/tests/test_utils.py b/tests/test_utils.py
index 615e52a..070db9b 100644
--- a/tests/test_utils.py
+++ b/tests/test_utils.py
@@ -1,7 +1,13 @@
+from pathlib import Path
+
+import pytest
+
from pocket_tts.utils import utils
-def test_download_http_cache_suffix_ignores_query_string(monkeypatch, tmp_path):
+def test_download_http_cache_suffix_ignores_query_string(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+):
class Response:
content = b"data"
diff --git a/training/args.py b/training/args.py
index c28e3b7..3c34a96 100644
--- a/training/args.py
+++ b/training/args.py
@@ -2,10 +2,15 @@ import dataclasses
import typing as tp
from dataclasses import dataclass, field
from pathlib import Path
-from typing import Any
+from typing import TYPE_CHECKING, Any
import yaml
+if TYPE_CHECKING:
+ from _typeshed import DataclassInstance
+
+T = tp.TypeVar("T", bound="DataclassInstance")
+
@dataclass
class DataArgs:
@@ -135,7 +140,7 @@ class TrainArgs:
# the depth) or "first" (the bottom N). No evidence either way -- "first"
# keeps the early feature extractors contiguous.
- def __post_init__(self) -> None:
+ def __post_init__(self):
if self.grad_accum_steps < 1:
raise ValueError(f"grad_accum_steps must be >= 1, got {self.grad_accum_steps}")
if self.num_ckpt_keep < 1:
@@ -157,7 +162,7 @@ class TrainArgs:
raise ValueError("distill_teacher_config is set but distill_teacher_weights is not")
-def _from_dict(cls, data: dict[str, Any]):
+def _from_dict(cls: type[T], data: dict[str, Any]) -> T:
sub = {"data": DataArgs, "flow": FlowArgs, "optim": OptimArgs}
kwargs = {}
fields = {f.name: f for f in dataclasses.fields(cls)}
@@ -187,7 +192,7 @@ def load_args(path: str | Path) -> TrainArgs:
def dump_args(args: TrainArgs) -> str:
"""The resolved config (defaults included) as yaml."""
- def plain(value):
+ def plain(value: object) -> object:
if isinstance(value, Path):
return str(value)
if isinstance(value, dict):
@@ -199,6 +204,6 @@ def dump_args(args: TrainArgs) -> str:
return yaml.safe_dump(plain(dataclasses.asdict(args)), sort_keys=False)
-def save_args(args: TrainArgs, path: str | Path) -> None:
+def save_args(args: TrainArgs, path: str | Path):
with open(path, "w") as f:
f.write(dump_args(args))
diff --git a/training/checkpointing.py b/training/checkpointing.py
index e5ee779..b0bd3fe 100644
--- a/training/checkpointing.py
+++ b/training/checkpointing.py
@@ -26,7 +26,7 @@ class EMA:
}
self._tracked: tuple[list[torch.Tensor], list[torch.Tensor]] | None = None
- def update(self, model: nn.Module) -> None:
+ def update(self, model: nn.Module):
with torch.no_grad():
if self._tracked is None:
named = dict(model.named_parameters())
@@ -37,10 +37,10 @@ class EMA:
torch._foreach_mul_(shadows, self.decay)
torch._foreach_add_(shadows, params, alpha=1 - self.decay)
- def state_dict(self):
+ def state_dict(self) -> dict[str, torch.Tensor]:
return self.shadow
- def load_state_dict(self, state):
+ def load_state_dict(self, state: dict[str, torch.Tensor]):
self._tracked = None
# The shadow ends up holding exactly what the checkpoint stored. Keys the
# checkpoint does not carry are dropped rather than left at their freshly
@@ -64,11 +64,11 @@ def save_checkpoint(
run_dir: Path,
step: int,
model: TrainableTTS,
- optimizer,
+ optimizer: torch.optim.Optimizer,
ema: EMA | None,
num_keep: int,
mimi: nn.Module | None = None,
-) -> None:
+):
"""Write the resumable training state; with `mimi`, also refresh the
pocket-tts-format export (run_dir/model.safetensors)."""
run_dir.mkdir(parents=True, exist_ok=True)
@@ -105,7 +105,12 @@ def latest_checkpoint(run_dir: Path) -> Path | None:
return checkpoints[-1] if checkpoints else None
-def load_checkpoint(path: Path, model: nn.Module, optimizer=None, ema: EMA | None = None) -> int:
+def load_checkpoint(
+ path: Path,
+ model: nn.Module,
+ optimizer: torch.optim.Optimizer | None = None,
+ ema: EMA | None = None,
+) -> int:
payload = torch.load(path, map_location="cpu", weights_only=True)
model.load_state_dict(payload["model"])
if optimizer is not None:
@@ -126,7 +131,7 @@ def load_checkpoint(path: Path, model: nn.Module, optimizer=None, ema: EMA | Non
def export_pocket_safetensors(
path: Path, flow_lm: nn.Module, mimi: nn.Module, ema: EMA | None = None
-) -> None:
+):
flow_state = {k: v.detach().float().cpu() for k, v in flow_lm.state_dict().items()}
if ema is not None:
for k, v in ema.shadow.items():
diff --git a/training/dataloader.py b/training/dataloader.py
index fda2771..b4107a9 100644
--- a/training/dataloader.py
+++ b/training/dataloader.py
@@ -8,6 +8,7 @@ ranks by line index.
import json
import logging
+import multiprocessing.queues
import queue
import random
import threading
@@ -19,12 +20,14 @@ from typing import Any
import numpy as np
import numpy.typing as npt
+import sentencepiece
import sphn
import torch
import torch.multiprocessing as torch_mp
from safetensors import safe_open
from pocket_tts.data.audio_utils import convert_audio
+from pocket_tts.models.mimi import MimiModel
logger = logging.getLogger(__name__)
@@ -371,9 +374,11 @@ class DataLoader:
)
-def _feed_queue(q, sentence_piece_proto: bytes, loader_kwargs: dict[str, Any]) -> None:
- import sentencepiece
-
+def _feed_queue(
+ q: "multiprocessing.queues.Queue[Batch]", # not subscriptable at runtime on 3.10
+ sentence_piece_proto: bytes,
+ loader_kwargs: dict[str, Any],
+):
torch_mp.set_sharing_strategy("file_system")
sentence_piece = sentencepiece.SentencePieceProcessor()
sentence_piece.load_from_serialized_proto(sentence_piece_proto)
@@ -386,7 +391,7 @@ class SubprocessDataLoader:
def __init__(
self,
jsonl: str,
- sentence_piece,
+ sentence_piece: sentencepiece.SentencePieceProcessor,
batch_size: int,
sample_rate: int,
frame_rate: float,
@@ -426,7 +431,7 @@ class SubprocessDataLoader:
proc.start()
self._procs.append(proc)
- def _check_procs(self) -> None:
+ def _check_procs(self):
dead = [p for p in self._procs if not p.is_alive()]
if dead:
raise RuntimeError(
@@ -466,13 +471,16 @@ def _prefetch(iterator: Iterator[Batch], depth: int = 4) -> Iterator[Batch]:
@torch.no_grad()
-def encode_batch(mimi, batch, device):
+def encode_batch(
+ mimi: MimiModel, batch: Batch, device: torch.device
+) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
if batch.tail_latents is not None:
stitch = mimi.encode_to_latent(batch.audio.to(device))
latents = torch.cat([stitch, batch.tail_latents.to(device)], dim=1)
T = latents.shape[1]
num_audio_frames = batch.num_audio_frames.to(device).clamp(max=T)
mask = torch.arange(T, device=device)[None, :] < num_audio_frames[:, None]
+ assert batch.prompt_latents is not None # set together with tail_latents
voice_prompt_latents = batch.prompt_latents.to(device)
num_voice_prompt_frames = batch.num_voice_prompt_frames.to(device).clamp(
max=voice_prompt_latents.shape[1]
diff --git a/training/distributed.py b/training/distributed.py
index 82c593c..d6fe871 100644
--- a/training/distributed.py
+++ b/training/distributed.py
@@ -16,7 +16,7 @@ def get_world_size() -> int:
return dist.get_world_size() if dist.is_initialized() else 1
-def _require_cuda() -> None:
+def _require_cuda():
"""Training on CPU is accidental (a mismatched torch build), not a use case."""
if torch.cuda.is_available() or os.environ.get("POCKET_TTS_ALLOW_CPU") == "1":
return
@@ -48,7 +48,7 @@ def init_distributed() -> torch.device:
return torch.device("cuda" if torch.cuda.is_available() else "cpu")
-def shutdown_distributed() -> None:
+def shutdown_distributed():
"""Hold every rank until all are done, then tear NCCL down.
Without the barrier, multi-GPU training can crash at the end.
diff --git a/training/eval/librispeech.py b/training/eval/librispeech.py
index 3bb9a98..3026a6d 100644
--- a/training/eval/librispeech.py
+++ b/training/eval/librispeech.py
@@ -22,7 +22,7 @@ import logging
import multiprocessing
import os
import re
-from collections.abc import Sequence
+from collections.abc import Callable, Sequence
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path
from typing import Any
@@ -34,10 +34,12 @@ import sphn
import torch
from pydantic import BaseModel
+from pocket_tts.models.mimi import MimiModel
from pocket_tts.modules.stateful_module import init_states
from training.args import load_args
from training.checkpointing import EMA, latest_checkpoint, load_checkpoint
from training.modules.builders import build_models
+from training.modules.model import TrainableTTS
logger = logging.getLogger("eval_librispeech")
DEFAULT_ASR = "ibm-granite/granite-speech-4.1-2b"
@@ -67,7 +69,7 @@ class EvalResults(BaseModel):
n_steps: int
-def eval_dir_name(args, step: int) -> str:
+def eval_dir_name(args: argparse.Namespace, step: int) -> str:
"""Output directory for one eval.
Anything that changes the numbers belongs in the name, so two evals of the
@@ -103,7 +105,7 @@ def read_lst(
continue
id0, _, _, id1, _, txt1 = line.split("\t")
- def p(utt, r=root, exts=(".flac",)):
+ def p(utt: str, r: str = root, exts: tuple[str, ...] = (".flac",)) -> str:
base = os.path.join(r, "/".join(utt.split("-")[:-1]), utt)
for ext in exts:
if os.path.exists(base + ext):
@@ -121,7 +123,7 @@ def read_lst(
return items
-def load_16k(path: str, device) -> torch.Tensor:
+def load_16k(path: str, device: torch.device) -> torch.Tensor:
wav, sr = sphn.read(path)
wav = wav.mean(axis=0)
if sr != 16000:
@@ -129,7 +131,9 @@ def load_16k(path: str, device) -> torch.Tensor:
return torch.from_numpy(wav).float().to(device)
-def build_transcriber(asr_name: str, device):
+def build_transcriber(
+ asr_name: str, device: torch.device
+) -> Callable[[list[npt.NDArray[Any]]], list[str]]:
"""Granite is a chat-prompted speech-seq2seq model; whisper is a pipeline."""
if "granite" in asr_name:
from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor
@@ -188,7 +192,12 @@ def build_transcriber(asr_name: str, device):
MIN_FRAMES = 8
-def load_run(run_dir, device, use_ema: bool = False, checkpoint=None):
+def load_run(
+ run_dir: str | Path,
+ device: torch.device,
+ use_ema: bool = False,
+ checkpoint: str | Path | None = None,
+) -> tuple[TrainableTTS, MimiModel, int]:
"""(model, mimi, step) from a run dir, weights on `device`, in eval mode."""
run_dir = Path(run_dir)
args = load_args(run_dir / "args.yaml")
@@ -218,7 +227,9 @@ def load_mono(path: str, sample_rate: int) -> torch.Tensor:
return torch.from_numpy(wav.copy()).float()
-def latents_to_wav(mimi, latents: torch.Tensor, device) -> torch.Tensor | None:
+def latents_to_wav(
+ mimi: MimiModel, latents: torch.Tensor, device: torch.device
+) -> torch.Tensor | None:
"""[T, C] latents to a mono waveform; None when the generation was empty."""
if latents.shape[0] < MIN_FRAMES:
return None
@@ -228,7 +239,9 @@ 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[str, Any]], device, args) -> tuple[list[dict[str, Any]], int]:
+def score_items(
+ items: list[dict[str, Any]], device: torch.device, args: argparse.Namespace
+) -> tuple[list[dict[str, Any]], int]:
"""Generate and score `items` on one device. Returns per-item records."""
from whisper_normalizer.english import EnglishTextNormalizer
@@ -248,7 +261,8 @@ def score_items(items: list[dict[str, Any]], device, args) -> tuple[list[dict[st
spk_fe = AutoFeatureExtractor.from_pretrained("microsoft/wavlm-base-plus-sv")
spk_model = (
- WavLMForXVector.from_pretrained("microsoft/wavlm-base-plus-sv").to(device).eval()
+ # transformers wraps .to() in a way that loses the bound self.
+ WavLMForXVector.from_pretrained("microsoft/wavlm-base-plus-sv").to(device).eval() # ty: ignore[invalid-argument-type]
)
def embed(wavs: Sequence[npt.NDArray[Any] | torch.Tensor]) -> torch.Tensor:
@@ -275,7 +289,7 @@ def score_items(items: list[dict[str, Any]], device, args) -> tuple[list[dict[st
sp_encode = model.flow_lm.conditioner.tokenizer.sp.encode
if args.match_train_text:
- def tokenize(text: str):
+ def tokenize(text: str) -> list[int]:
return sp_encode(re.sub(r"[^a-z' ]", "", text.lower()).strip())
else:
tokenize = sp_encode
@@ -375,13 +389,15 @@ def score_items(items: list[dict[str, Any]], device, args) -> tuple[list[dict[st
return records, step
-def _shard_worker(payload):
+def _shard_worker(
+ payload: tuple[int, list[dict[str, Any]], argparse.Namespace],
+) -> tuple[list[dict[str, Any]], int]:
device_idx, items, args = payload
torch.cuda.set_device(device_idx)
return score_items(items, torch.device("cuda", device_idx), args)
-def main() -> None:
+def main():
logging.basicConfig(
level=logging.INFO,
format="[%(asctime)s %(levelname)s %(name)s] %(message)s",
diff --git a/training/modules/builders.py b/training/modules/builders.py
index eea3bd4..624fbef 100644
--- a/training/modules/builders.py
+++ b/training/modules/builders.py
@@ -51,7 +51,7 @@ def load_model_config(path: str, overrides: dict[str, tp.Any]) -> Config:
return Config(**raw)
-def attach_distillation(model: TrainableTTS, flow_lm: FlowLMModel, args: TrainArgs) -> None:
+def attach_distillation(model: TrainableTTS, flow_lm: FlowLMModel, args: TrainArgs):
"""Give `model` a frozen teacher and freeze what distillation must not move.
Two shapes share this path: a separately trained (usually deeper) teacher
diff --git a/training/modules/model.py b/training/modules/model.py
index 6f4174f..cc0390e 100644
--- a/training/modules/model.py
+++ b/training/modules/model.py
@@ -42,7 +42,7 @@ class TrainableTTS(nn.Module):
def ldim(self) -> int:
return self.flow_lm.ldim
- def _update_latent_stats(self, latents: torch.Tensor, mask: torch.Tensor) -> None:
+ def _update_latent_stats(self, latents: torch.Tensor, mask: torch.Tensor):
fl = self.flow_lm
with torch.no_grad():
sel = latents[mask]
diff --git a/training/modules/samplers.py b/training/modules/samplers.py
index 9122760..7fa9820 100644
--- a/training/modules/samplers.py
+++ b/training/modules/samplers.py
@@ -28,7 +28,9 @@ from .utils import MLP, f_grad_x_only, zero_init
class FlowType(nn.Module):
num_time_conds: int = 1
- def loss(self, v_t: FlowNet, x_0: torch.Tensor, x_1: torch.Tensor):
+ def loss(
+ self, v_t: FlowNet, x_0: torch.Tensor, x_1: torch.Tensor
+ ) -> tuple[torch.Tensor, dict[str, torch.Tensor], torch.Tensor]:
raise NotImplementedError
def decode(self, v_t: FlowNet, x_0: torch.Tensor, num_steps: int = 1) -> torch.Tensor:
@@ -44,7 +46,9 @@ class FlowMatching(FlowType):
super().__init__()
self.sig_min = sig_min
- def loss(self, v_t, x_0, x_1):
+ def loss(
+ self, v_t: FlowNet, x_0: torch.Tensor, x_1: torch.Tensor
+ ) -> tuple[torch.Tensor, dict[str, torch.Tensor], torch.Tensor]:
t = torch.rand_like(x_1[..., :1])
x_t = (1 - (1 - self.sig_min) * t) * x_0 + t * x_1
v_psi = v_t(t, x_t)
@@ -52,7 +56,7 @@ class FlowMatching(FlowType):
loss = ((v_psi - d_psi) ** 2).mean(dim=-1)
return loss, {"loss": loss.mean()}, t
- def decode(self, v_t, x_0, num_steps: int = 1):
+ def decode(self, v_t: FlowNet, x_0: torch.Tensor, num_steps: int = 1) -> torch.Tensor:
return ot_decode(v_t, x_0, num_steps)
@@ -100,18 +104,20 @@ class LSD(FlowType):
self.w_s_t = MLP(2, [w_t_dims] * w_t_depth + [1])
self.w_s_t.apply(zero_init)
- def sample_t(self, x) -> torch.Tensor:
+ def sample_t(self, x: torch.Tensor) -> torch.Tensor:
return torch.sigmoid(torch.randn_like(x[..., :1]) * self.lognorm_std + self.lognorm_mean)
- def sample_s_t(self, x) -> tuple[torch.Tensor, torch.Tensor]:
+ def sample_s_t(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
logits = torch.randn_like(x[..., :2]) * self.lognorm_std + self.lognorm_mean
return torch.sigmoid(logits.min(-1)[0])[..., None], torch.sigmoid(logits.max(-1)[0])[
..., None
]
- def loss(self, v_t, x_0, x_1):
+ def loss(
+ self, v_t: FlowNet, x_0: torch.Tensor, x_1: torch.Tensor
+ ) -> tuple[torch.Tensor, dict[str, torch.Tensor], torch.Tensor]:
x, e = x_1, x_0
- metrics = {}
+ metrics: dict[str, torch.Tensor] = {}
# Diagonal (instantaneous flow-matching) term at s == t.
t = self.sample_t(x)
@@ -158,12 +164,12 @@ class LSD(FlowType):
loss = self.p_equal * flow_diag + distill_w * flow_distill
return loss, metrics, t
- def decode(self, v_t, x_0, num_steps: int = 1):
+ def decode(self, v_t: FlowNet, x_0: torch.Tensor, num_steps: int = 1) -> torch.Tensor:
return lsd_decode(v_t, x_0, num_steps)
FLOW_TYPES: dict[str, type[FlowType]] = {"flow_matching": FlowMatching, "lsd": LSD}
-def build_flow(name: str, **kwargs) -> FlowType:
+def build_flow(name: str, **kwargs: object) -> FlowType:
return FLOW_TYPES[name](**kwargs)
diff --git a/training/modules/utils.py b/training/modules/utils.py
index cea9442..0e13cc3 100644
--- a/training/modules/utils.py
+++ b/training/modules/utils.py
@@ -2,9 +2,11 @@
init, streaming-state helpers, and small blocks used by samplers.py."""
import math
+from collections.abc import Callable
import torch
from torch import nn
+from torch.autograd.function import BackwardCFunction, FunctionCtx
from pocket_tts.modules.mlp import ResBlock, SimpleMLPAdaLN, TimestepEmbedder
from pocket_tts.modules.stateful_module import ModelState, StatefulModule
@@ -15,16 +17,16 @@ def _as_linear(module: nn.Module) -> nn.Linear:
return module
-def _zero_linear(module: nn.Module) -> None:
+def _zero_linear(module: nn.Module):
linear = _as_linear(module)
nn.init.constant_(linear.weight, 0)
nn.init.constant_(linear.bias, 0)
-def dit_init(head: SimpleMLPAdaLN) -> None:
+def dit_init(head: SimpleMLPAdaLN):
"""The MAR/DiT init: xavier everywhere, zero adaLN modulations and output."""
- def _basic_init(module):
+ def _basic_init(module: nn.Module):
if isinstance(module, nn.Linear):
torch.nn.init.xavier_uniform_(module.weight)
if module.bias is not None:
@@ -42,7 +44,7 @@ def dit_init(head: SimpleMLPAdaLN) -> None:
_zero_linear(head.final_layer.linear)
-def gaussian_init(module: nn.Module) -> None:
+def gaussian_init(module: nn.Module):
"""Backbone init: truncated normal with std 1/sqrt(fan_in) (xlformers-style)."""
for m in module.modules():
if isinstance(m, nn.Linear):
@@ -55,19 +57,19 @@ def gaussian_init(module: nn.Module) -> None:
nn.init.trunc_normal_(m.weight, mean=0.0, std=std, a=-3 * std, b=3 * std)
-def disable_grad(module: nn.Module) -> None:
+def disable_grad(module: nn.Module):
for p in module.parameters():
p.requires_grad = False
-def set_state_padding(model_state: ModelState, pad: torch.Tensor) -> None:
+def set_state_padding(model_state: ModelState, pad: torch.Tensor):
"""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:
st["pad"].copy_(pad.to(st["pad"].device))
-def stamp_state_names(module: nn.Module) -> None:
+def stamp_state_names(module: nn.Module):
"""Streaming state lookup needs each StatefulModule to know its own name."""
for module_name, sub in module.named_modules():
if isinstance(sub, StatefulModule):
@@ -88,7 +90,7 @@ class MLP(nn.Sequential):
return super().forward(torch.cat((input, *rest), dim=-1))
-def zero_init(m: nn.Module) -> None:
+def zero_init(m: nn.Module):
if isinstance(m, nn.Linear):
nn.init.zeros_(m.weight)
if m.bias is not None:
@@ -99,21 +101,24 @@ class RunOnlyInputGrad(torch.autograd.Function):
"""y = f(x) whose backward only propagates to x, never to f's parameters."""
@staticmethod
- def forward(ctx, x, f):
+ def forward(
+ ctx: FunctionCtx, x: torch.Tensor, f: Callable[[torch.Tensor], torch.Tensor]
+ ) -> torch.Tensor:
with torch.enable_grad():
y = f(x)
ctx.save_for_backward(x, y)
return y.detach()
@staticmethod
- def backward(ctx, *grad_outputs):
+ def backward(ctx: BackwardCFunction, *grad_outputs: torch.Tensor) -> tuple[torch.Tensor, None]:
(grad_output,) = grad_outputs
- x, y = ctx.saved_tensors
+ # torch's stub declares saved_tensors as a 1-tuple; it is variadic at runtime.
+ x, y = ctx.saved_tensors # ty: ignore[invalid-assignment]
gx = torch.autograd.grad(outputs=y, inputs=x, grad_outputs=grad_output, retain_graph=False)[
0
]
return gx, None
-def f_grad_x_only(f, x):
+def f_grad_x_only(f: Callable[[torch.Tensor], torch.Tensor], x: torch.Tensor) -> torch.Tensor:
return RunOnlyInputGrad.apply(x, f)
diff --git a/training/scripts/align_data.py b/training/scripts/align_data.py
index f41f549..189441e 100644
--- a/training/scripts/align_data.py
+++ b/training/scripts/align_data.py
@@ -26,9 +26,11 @@ import logging
import queue
import re
import threading
-from collections.abc import Callable
-from typing import Annotated, Any
+from collections.abc import Callable, Iterator
+from typing import TYPE_CHECKING, Annotated, Any, TextIO
+import numpy as np
+import numpy.typing as npt
import sphn
import torch
import typer
@@ -37,8 +39,14 @@ from tqdm import tqdm
from pocket_tts.data.audio_utils import convert_audio
+if TYPE_CHECKING:
+ from transformers import Wav2Vec2ForCTC
+
logger = logging.getLogger("align")
+# (entry, wav) or (entry, exception) as handed from the reader thread to the aligner.
+LoadedEntry = tuple[dict[str, Any], npt.NDArray[np.float32] | Exception]
+
app = typer.Typer(pretty_exceptions_show_locals=False)
@@ -146,7 +154,9 @@ def _tokens_for(words: list[str], vocab: dict[str, int], delim: int) -> tuple[li
return tokens, word_of
-def _load_ctc_model(model_name: str, device: torch.device):
+def _load_ctc_model(
+ model_name: str, device: torch.device
+) -> "tuple[Wav2Vec2ForCTC, dict[str, int], int, int, Callable[[str], str], int, bool]":
"""(model, vocab, blank id, word-delimiter id, case fold, sample rate, use_bf16) for `model_name`."""
import transformers
@@ -215,7 +225,7 @@ def main(
"output order is restored per window"
),
] = 256,
-) -> None:
+):
logging.basicConfig(
level=logging.INFO,
format="[%(asctime)s %(levelname)s %(name)s] %(message)s",
@@ -239,7 +249,7 @@ def main(
bar_format="{l_bar}{bar}| {n:.1f}/{total:.1f}h [{elapsed}<{remaining}, {rate_fmt}{postfix}]",
)
- def read_entries(fin, q):
+ def read_entries(fin: TextIO, q: queue.Queue[LoadedEntry | None]):
for line in fin:
entry = json.loads(line)
if (entry["path"], float(entry.get("start", 0.0))) in done:
@@ -262,7 +272,7 @@ def main(
n_ok = n_skipped = 0
- def skip(entry, exc):
+ def skip(entry: dict[str, Any], exc: Exception):
nonlocal n_skipped
n_skipped += 1
if n_skipped % 100 == 1:
@@ -278,10 +288,10 @@ def main(
with open(input_jsonl) as fin, open(output_jsonl, "a" if resume else "w", buffering=1) as fout:
# (entry, wav) or (entry, exception); None once the manifest is exhausted.
- q: queue.Queue[tuple[Any, Any] | None] = queue.Queue(maxsize=sort_window * 2)
+ q: queue.Queue[LoadedEntry | None] = queue.Queue(maxsize=sort_window * 2)
threading.Thread(target=read_entries, args=(fin, q), daemon=True).start()
- def windows():
+ def windows() -> Iterator[list[LoadedEntry]]:
buf, eof = [], False
while not eof:
while len(buf) < sort_window:
diff --git a/training/scripts/precompute_latents.py b/training/scripts/precompute_latents.py
index 6573c5d..a5b79ea 100644
--- a/training/scripts/precompute_latents.py
+++ b/training/scripts/precompute_latents.py
@@ -14,6 +14,8 @@ import torch
import typer
from tqdm import tqdm
+from pocket_tts.models.mimi import MimiModel
+from pocket_tts.utils.config import Config
from pocket_tts.utils.utils import download_if_necessary
from training.args import load_args
from training.dataloader import Entry, _load_window
@@ -61,7 +63,7 @@ def _chunk_jobs(lines: list[str], idxs: list[int], sample_rate: int) -> list[Dec
return [(e.path, e.start, e.duration, sample_rate) for e in map(_parse_entry, chunk)]
-def mimi_encode_hash(mimi) -> str:
+def mimi_encode_hash(mimi: MimiModel) -> str:
"""Hash of the weights on the encode path (encoder, encoder transformer,
downsample): identifies which Mimi produced a latents store."""
h = hashlib.sha256()
@@ -75,7 +77,7 @@ def mimi_encode_hash(mimi) -> str:
return h.hexdigest()
-def load_frozen_mimi(config) -> torch.nn.Module:
+def load_frozen_mimi(config: Config) -> MimiModel:
mimi = build_mimi(config.mimi)
weights_file = download_if_necessary(str(config.weights_path))
state = safetensors.torch.load_file(weights_file)
@@ -100,7 +102,7 @@ def load_frozen_mimi(config) -> torch.nn.Module:
@torch.no_grad()
-def measure_stitch_frames(mimi, audio: torch.Tensor) -> tuple[int, float]:
+def measure_stitch_frames(mimi: MimiModel, audio: torch.Tensor) -> tuple[int, float]:
fs = mimi.frame_size
full = mimi.encode_to_latent(audio)
k = full.shape[1] // 2
@@ -120,7 +122,13 @@ def measure_stitch_frames(mimi, audio: torch.Tensor) -> tuple[int, float]:
return frames + CALIBRATION_MARGIN_FRAMES, floor
-def _calibrate(pool, lines: list[str], mimi, batch_size: int, device) -> tuple[int, float]:
+def _calibrate(
+ pool: ProcessPoolExecutor,
+ lines: list[str],
+ mimi: MimiModel,
+ batch_size: int,
+ device: torch.device,
+) -> tuple[int, float]:
longest = sorted(map(_parse_entry, lines[:CALIBRATION_POOL_LINES]), key=lambda e: -e.duration)
jobs = [(e.path, e.start, e.duration, mimi.sample_rate) for e in longest[:batch_size]]
calib = list(pool.map(_decode_one, jobs))
@@ -136,7 +144,7 @@ def _entry_frames(n_samples: int, sample_rate: int, frame_rate: float) -> int:
return max(1, int(n_samples * frame_rate / sample_rate))
-def _atomic_write_text(path: Path, text: str) -> None:
+def _atomic_write_text(path: Path, text: str):
tmp = path.with_suffix(f".tmp.{os.getpid()}")
tmp.write_text(text)
tmp.rename(path)
@@ -179,8 +187,13 @@ def _pending_chunks(
def _write_chunk(
- latents: torch.Tensor, lens: list[int], idxs: list[int], manifest: Path, mimi, tag: str
-) -> None:
+ latents: torch.Tensor,
+ lens: list[int],
+ idxs: list[int],
+ manifest: Path,
+ mimi: MimiModel,
+ tag: str,
+):
for b, n_samples in enumerate(lens):
frames = min(_entry_frames(n_samples, mimi.sample_rate, mimi.frame_rate), latents.shape[1])
path = manifest.parent / _latents_name(manifest, idxs[b], tag)
@@ -192,9 +205,9 @@ def _write_chunk(
def _encode_pending(
- pool,
- mimi,
- device,
+ pool: ProcessPoolExecutor,
+ mimi: MimiModel,
+ device: torch.device,
lines: list[str],
manifest: Path,
batch_size: int,
@@ -202,7 +215,7 @@ def _encode_pending(
tag: str,
worker: int = 0,
num_workers: int = 1,
-) -> None:
+):
pending = _pending_chunks(lines, manifest, batch_size, tag, worker, num_workers)
lookahead = decode_workers + 2 # keep every decode worker busy
futures = {
@@ -226,10 +239,10 @@ def _write_manifest_and_meta(
new_lines: list[str],
stitch_frames: int,
floor: float,
- mimi,
+ mimi: MimiModel,
weights_path: str,
mimi_hash: str,
-) -> None:
+):
out_manifest = manifest.with_name(manifest.stem + "_latents.jsonl")
_atomic_write_text(out_manifest, "\n".join(new_lines) + "\n")
meta = {
@@ -246,14 +259,14 @@ def _write_manifest_and_meta(
def precompute_manifest(
manifest: Path,
- mimi,
- device,
+ mimi: MimiModel,
+ device: torch.device,
batch_size: int,
decode_workers: int,
weights_path: str,
worker: int = 0,
num_workers: int = 1,
-) -> None:
+):
"""Encode a manifest's utterances to per-utterance latents files.
With num_workers > 1 each worker encodes a strided subset of chunks;
@@ -284,7 +297,7 @@ def precompute_manifest(
@app.command()
-def main(config: str, batch_size: int = 16, decode_workers: int = 0) -> None:
+def main(config: str, batch_size: int = 16, decode_workers: int = 0):
logging.basicConfig(level=logging.INFO)
args = load_args(config)
model_config = load_model_config(args.model_config, args.model_overrides)
diff --git a/training/scripts/prepare_data.py b/training/scripts/prepare_data.py
index 7bfd807..290aee1 100644
--- a/training/scripts/prepare_data.py
+++ b/training/scripts/prepare_data.py
@@ -53,7 +53,7 @@ class Utterance(BaseModel):
set: str # "train", "dev", "test", ...
-def download(url: str, dest: Path, retries: int = 5, timeout: float = 30) -> None:
+def download(url: str, dest: Path, retries: int = 5, timeout: float = 30):
"""Stream `url` to `dest`, retrying transient failures like curl's --retry."""
for attempt in range(retries + 1):
try:
@@ -69,7 +69,7 @@ def download(url: str, dest: Path, retries: int = 5, timeout: float = 30) -> Non
time.sleep(min(2**attempt, 10))
-def align(manifest: Path, out: Path, shards: int, model: str, what: str = "manifest") -> None:
+def align(manifest: Path, out: Path, shards: int, model: str, what: str = "manifest"):
if out.exists():
logger.info(f"{what} {out.resolve()} exists, skipping")
return
@@ -129,7 +129,7 @@ def align(manifest: Path, out: Path, shards: int, model: str, what: str = "manif
logger.info(f"merged {shards} shards -> {out.name}")
-def attach_hf_alignments(manifest: Path, out: Path, repo: str, audio_root: Path) -> None:
+def attach_hf_alignments(manifest: Path, out: Path, repo: str, audio_root: Path):
"""Join a raw manifest against the published word alignments: rows match
on NVIDIA's per-utterance `audio_filepath`, kept in each row as the join
key since multiple rows can share one chapter file path. The published
@@ -257,7 +257,7 @@ def prepare_hifitts2(
def chapter_path(ch: dict[str, Any]) -> Path:
return audio_root / (Path(ch["chapter_filepath"]).stem + ".mp3")
- def fetch_chapter(ch: dict[str, Any]) -> None:
+ def fetch_chapter(ch: dict[str, Any]):
"""Download chapter `ch`'s whole audio file, if not already present.
One download per chapter, shared by every utterance in it: the
@@ -374,7 +374,7 @@ def main(
verbose: Annotated[
bool, typer.Option("--verbose", "-v", help="log the reason each chapter was skipped")
] = False,
-) -> None:
+):
logging.basicConfig(
level=logging.INFO,
format="[%(asctime)s %(levelname)s %(name)s] %(message)s",
diff --git a/training/scripts/shrink_checkpoint.py b/training/scripts/shrink_checkpoint.py
index da17804..c764317 100644
--- a/training/scripts/shrink_checkpoint.py
+++ b/training/scripts/shrink_checkpoint.py
@@ -51,7 +51,7 @@ def shrink(
return out, keep
-def main() -> None:
+def main():
parser = argparse.ArgumentParser()
parser.add_argument("checkpoint")
parser.add_argument("--layers", type=int, required=True, help="student depth")
diff --git a/training/scripts/train_tokenizer.py b/training/scripts/train_tokenizer.py
index ffc5aca..65fe9b0 100644
--- a/training/scripts/train_tokenizer.py
+++ b/training/scripts/train_tokenizer.py
@@ -18,6 +18,7 @@ Usage:
import json
import tempfile
+from collections.abc import Iterator
from pathlib import Path
from typing import Annotated, Literal
@@ -27,7 +28,7 @@ import typer
app = typer.Typer(pretty_exceptions_show_locals=False)
-def iter_texts(paths: list[Path]):
+def iter_texts(paths: list[Path]) -> Iterator[str]:
for p in paths:
with open(p) as f:
for line in f:
@@ -54,7 +55,7 @@ def main(
float, typer.Option(help="lower to 0.9995 for large-alphabet languages (e.g. CJK)")
] = 1.0,
model_type: Annotated[Literal["bpe", "unigram", "char"], typer.Option()] = "bpe",
-) -> None:
+):
Path(output_prefix).parent.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False) as tmp:
n = 0
diff --git a/training/tests/test_dataloader.py b/training/tests/test_dataloader.py
index 5c9e532..6ab40ba 100644
--- a/training/tests/test_dataloader.py
+++ b/training/tests/test_dataloader.py
@@ -1,8 +1,11 @@
"""Dataloader behaviour that silently degrades training when it breaks."""
import json
+from pathlib import Path
+from typing import Any
import numpy as np
+import numpy.typing as npt
import sphn
from training.dataloader import DataLoader, load_entries
@@ -10,12 +13,12 @@ from training.dataloader import DataLoader, load_entries
SR = 24000
-def _write_wav(path, seconds=6.0):
+def _write_wav(path: Path, seconds: float = 6.0):
t = np.linspace(0, seconds, int(seconds * SR), endpoint=False)
sphn.write_wav(str(path), (0.2 * np.sin(2 * np.pi * 140 * t)).astype(np.float32), SR)
-def _manifest(tmp_path, n=8, words=True, duration=6.0):
+def _manifest(tmp_path: Path, n: int = 8, words: bool = True, duration: float = 6.0) -> str:
wav = tmp_path / "a.flac"
_write_wav(wav, duration)
path = tmp_path / "m.jsonl"
@@ -31,7 +34,7 @@ def _manifest(tmp_path, n=8, words=True, duration=6.0):
return str(path)
-def _loader(manifest, **kw):
+def _loader(manifest: str, **kw: Any) -> DataLoader: # noqa: ANN401 -- DataLoader passthrough
kw.setdefault("batch_size", 2)
return DataLoader(
manifest,
@@ -49,30 +52,30 @@ def _loader(manifest, **kw):
)
-def test_rank_sharding_partitions_entries_without_overlap(tmp_path):
+def test_rank_sharding_partitions_entries_without_overlap(tmp_path: Path):
m = _manifest(tmp_path, n=8)
shards = [load_entries(m, rank, 4) for rank in range(4)]
assert sum(len(s) for s in shards) == 8
assert all(len(s) == 2 for s in shards)
-def test_prompt_respects_the_configured_cap(tmp_path):
+def test_prompt_respects_the_configured_cap(tmp_path: Path):
batch = next(iter(_loader(_manifest(tmp_path), max_voice_prompt_sec=1.0)))
assert (batch.num_voice_prompt_frames.float() / 12.5).max().item() <= 1.0 + 1e-6
-def test_batches_have_the_requested_size(tmp_path):
+def test_batches_have_the_requested_size(tmp_path: Path):
batch = next(iter(_loader(_manifest(tmp_path, n=8), batch_size=4)))
assert batch.audio.shape[0] == 4
assert len(batch.text_tokens) == 4
-def test_target_audio_never_exceeds_max_duration(tmp_path):
+def test_target_audio_never_exceeds_max_duration(tmp_path: Path):
batch = next(iter(_loader(_manifest(tmp_path, duration=30.0), max_duration_sec=5.0)))
assert batch.audio.shape[-1] <= int(5.0 * SR) + 1
-def test_unaligned_manifest_still_yields_batches(tmp_path):
+def test_unaligned_manifest_still_yields_batches(tmp_path: Path):
"""Manifests without word alignments are a documented input: the loader
falls back to a random window as the prompt instead of hanging."""
loader = _loader(_manifest(tmp_path, n=8, words=False))
@@ -80,7 +83,7 @@ def test_unaligned_manifest_still_yields_batches(tmp_path):
assert batch.audio.shape[0] == 2
-def test_entry_start_offsets_into_a_shared_file(tmp_path):
+def test_entry_start_offsets_into_a_shared_file(tmp_path: Path):
"""Two utterances can share one audio file: each entry reads its own
window, at `start`, out of the shared file."""
low_hz, high_hz = 220, 880
@@ -109,7 +112,7 @@ def test_entry_start_offsets_into_a_shared_file(tmp_path):
low_wav, *_ = loader._sample(low_entry)
high_wav, *_ = loader._sample(high_entry)
- def dominant_freq(x):
+ def dominant_freq(x: npt.NDArray[np.float32]) -> float:
spectrum = np.abs(np.fft.rfft(x))
freqs = np.fft.rfftfreq(len(x), d=1 / SR)
return freqs[np.argmax(spectrum)]
diff --git a/training/tests/test_eval_naming.py b/training/tests/test_eval_naming.py
index 2b91efc..7af9acb 100644
--- a/training/tests/test_eval_naming.py
+++ b/training/tests/test_eval_naming.py
@@ -8,8 +8,8 @@ import pytest
from training.eval.librispeech import DEFAULT_ASR, eval_dir_name
-def make_args(**over):
- base = dict(
+def make_args(**over: object) -> Namespace:
+ base: dict[str, object] = dict(
temp=0.3, cfg=2.0, use_ema=True, num_items=None, seed=0, asr=DEFAULT_ASR, prompt_root=None
)
base.update(over)
@@ -30,7 +30,7 @@ def test_default_name_is_bare():
(dict(prompt_root="/data/libri_prompts_doraclean"), "doraclean"),
],
)
-def test_each_knob_marks_the_name(over, fragment):
+def test_each_knob_marks_the_name(over: dict[str, object], fragment: str):
assert fragment in eval_dir_name(make_args(**over), 400000)
diff --git a/training/tests/test_prepare_data.py b/training/tests/test_prepare_data.py
index 6dab641..e348087 100644
--- a/training/tests/test_prepare_data.py
+++ b/training/tests/test_prepare_data.py
@@ -4,19 +4,23 @@ chapter share one manifest `path`, distinguished only by `start`."""
import gzip
import json
from pathlib import Path
+from typing import Any
import huggingface_hub
+import pytest
from training.scripts import prepare_data
-def _write_jsonl(path, records):
+def _write_jsonl(path: Path, records: list[dict[str, Any]]):
with open(path, "w") as f:
for r in records:
f.write(json.dumps(r) + "\n")
-def test_utterances_in_one_chapter_share_the_manifest_path(tmp_path, monkeypatch):
+def test_utterances_in_one_chapter_share_the_manifest_path(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+):
chapters_json = tmp_path / "chapters.json"
manifest_json = tmp_path / "manifest.json"
_write_jsonl(
@@ -53,10 +57,10 @@ def test_utterances_in_one_chapter_share_the_manifest_path(tmp_path, monkeypatch
],
)
- def fake_hf_hub_download(repo, filename, repo_type):
+ def fake_hf_hub_download(repo: str, filename: str, repo_type: str | None) -> str:
return str(chapters_json) if "chapters" in filename else str(manifest_json)
- def fake_download(url, dest, **kwargs):
+ def fake_download(url: str, dest: Path, **kwargs: float):
# Simulate a successful download: touch the destination.
open(dest, "w").close()
@@ -91,7 +95,9 @@ def test_utterances_in_one_chapter_share_the_manifest_path(tmp_path, monkeypatch
assert list(audio_out.rglob("*.mp3")) == [audio_out / "hifitts2_audio" / "ch1.mp3"]
-def test_hf_alignments_join_on_utterance_id_not_path(tmp_path, monkeypatch):
+def test_hf_alignments_join_on_utterance_id_not_path(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+):
"""Rows that share a chapter file's `path` still join correctly, because
the join key is each row's `audio_filepath`, not its `path`."""
# published alignments: two utterances, utterance-relative timestamps
diff --git a/training/tests/test_smoke.py b/training/tests/test_smoke.py
index a387c28..fb66b4e 100644
--- a/training/tests/test_smoke.py
+++ b/training/tests/test_smoke.py
@@ -8,6 +8,7 @@ import sys
from pathlib import Path
import numpy as np
+import numpy.typing as npt
import pytest
import sentencepiece as spm
import torch
@@ -68,7 +69,9 @@ def tiny_model(flow_type: str, context: int | None = None) -> TrainableTTS:
return TrainableTTS(flow_lm, flow, args)
-def make_batch(B=3, T=11):
+def make_batch(
+ B: int = 3, T: int = 11
+) -> tuple[torch.Tensor, torch.Tensor, list[torch.Tensor], torch.Tensor]:
latents = torch.randn(B, T, LDIM)
mask = torch.arange(T)[None, :] < torch.tensor([T, T - 3, T - 5])[:, None]
text = [torch.randint(0, 10, (n,)) for n in (4, 2, 6)]
@@ -77,7 +80,7 @@ def make_batch(B=3, T=11):
@pytest.mark.parametrize("flow_type", ["lsd", "flow_matching"])
-def test_train_step(flow_type):
+def test_train_step(flow_type: str):
model = tiny_model(flow_type)
model.train()
loss, metrics = model(*make_batch())
@@ -90,7 +93,7 @@ def test_train_step(flow_type):
@pytest.mark.parametrize("flow_type,cfg", [("lsd", 1.0), ("flow_matching", 1.0)])
-def test_generate(flow_type, cfg):
+def test_generate(flow_type: str, cfg: float):
model = tiny_model(flow_type)
tokens = torch.randint(0, 10, (5,))
voice = torch.randn(4, LDIM)
@@ -133,7 +136,7 @@ def test_cfg_distill():
@pytest.mark.parametrize("num_time_conds", [0, 1, 2])
-def test_head_supports_every_time_cond_count(num_time_conds):
+def test_head_supports_every_time_cond_count(num_time_conds: int):
"""The head runs with 0, 1 or 2 time conditions."""
head = SimpleMLPAdaLN(LDIM, 16, LDIM, DIM, 2, num_time_conds)
assert len(head.time_embed) == num_time_conds
@@ -265,7 +268,7 @@ def test_ema_load_drops_untracked_keys():
torch.testing.assert_close(model.state_dict()[k], v)
-def test_prefix_prompt(monkeypatch):
+def test_prefix_prompt(monkeypatch: pytest.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,9 +284,9 @@ def test_prefix_prompt(monkeypatch):
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)
- calls = []
+ calls: list[tuple[float, float]] = []
- def fake_load_window(path, start, dur, sr):
+ def fake_load_window(path: str, start: float, dur: float, sr: int) -> npt.NDArray[np.float32]:
calls.append((start, dur))
return np.zeros(max(1, int(dur * sr)), dtype=np.float32)
@@ -298,7 +301,7 @@ def test_prefix_prompt(monkeypatch):
assert t_dur >= 20.0 - 5.5 - 0.5, "target keeps most of the utterance"
-def test_train_tokenizer(tmp_path):
+def test_train_tokenizer(tmp_path: Path):
manifest = tmp_path / "m.jsonl"
lines = [
json.dumps({"transcript": f"hello world number {i} testing tokenizers"}) for i in range(64)
@@ -329,7 +332,7 @@ def test_grad_accum_matches_big_batch():
xs = torch.randn(8, 4)
ys = torch.randn(8, 1)
- def loss_of(x, y):
+ def loss_of(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
return torch.nn.functional.mse_loss(net(x), y, reduction="mean")
def grad_of(p: torch.nn.Parameter) -> torch.Tensor:
diff --git a/training/tests/test_units.py b/training/tests/test_units.py
index 7c487ba..3aaf03a 100644
--- a/training/tests/test_units.py
+++ b/training/tests/test_units.py
@@ -1,5 +1,7 @@
"""Unit tests for the pure functions the training loop leans on."""
+from typing import Any
+
import pytest
import torch
from torch import nn
@@ -11,7 +13,7 @@ from training.scripts.shrink_checkpoint import select_layers, shrink
from training.train_utils import lr_at
-def _args(**kw) -> TrainArgs:
+def _args(**kw: Any) -> TrainArgs: # noqa: ANN401 -- TrainArgs/OptimArgs passthrough
optim = OptimArgs(**kw.pop("optim", {}))
return TrainArgs(optim=optim, **kw)
@@ -66,7 +68,7 @@ class TestSelectLayers:
class TestEMA:
- def _model(self):
+ def _model(self) -> nn.Linear:
m = nn.Linear(2, 2, bias=True)
with torch.no_grad():
m.weight.fill_(1.0)
@@ -98,7 +100,7 @@ class TestEMA:
class TestDistillProb:
- def _v(self, s, t, x):
+ def _v(self, s: torch.Tensor, t: torch.Tensor, x: torch.Tensor) -> torch.Tensor:
return x * (s + t)
def test_skip_rate_matches_probability(self):
diff --git a/training/train.py b/training/train.py
index 43b5638..ed24721 100644
--- a/training/train.py
+++ b/training/train.py
@@ -19,6 +19,7 @@ import sys
import time
from dataclasses import dataclass
from pathlib import Path
+from types import FrameType
import torch
from torch import nn
@@ -162,7 +163,7 @@ def setup(config_path: str) -> Run:
)
-def main(config_path: str) -> None:
+def main(config_path: str):
run = setup(config_path)
# Unpacked for the hot loop; the thin ones stay run.* at their call sites.
args, model, mimi = run.args, run.model, run.mimi
@@ -196,7 +197,7 @@ def main(config_path: str) -> None:
# checkpoint inside that window so a cancelled job resumes losslessly.
stop_requested = False
- def _request_stop(signum, frame):
+ def _request_stop(signum: int, frame: FrameType | None):
nonlocal stop_requested
stop_requested = True
@@ -308,7 +309,13 @@ def main(config_path: str) -> None:
@torch.no_grad()
def validate(
- model, mimi, args: TrainArgs, device, rank: int, world_size: int, step: int
+ model: TrainableTTS,
+ mimi: MimiModel,
+ args: TrainArgs,
+ device: torch.device,
+ rank: int,
+ world_size: int,
+ step: int,
) -> dict[str, float]:
model.eval()
tokenize = model.flow_lm.conditioner.tokenizer.sp.encode
diff --git a/training/train_utils.py b/training/train_utils.py
index f221830..c579757 100644
--- a/training/train_utils.py
+++ b/training/train_utils.py
@@ -5,15 +5,19 @@ import logging
import math
import subprocess
import time
+from collections.abc import Callable
from pathlib import Path
from typing import Any
import soundfile
import torch
+from pocket_tts.models.flow_lm import FlowLMModel
+from pocket_tts.models.mimi import MimiModel
from pocket_tts.modules.stateful_module import init_states
from training.args import TrainArgs
from training.modules.builders import load_model_config
+from training.modules.model import TrainableTTS
logger = logging.getLogger("train")
@@ -21,7 +25,7 @@ LOG_FORMAT = "[%(asctime)s %(levelname)s %(name)s] %(message)s"
LOG_DATEFMT = "%d-%m %H:%M:%S"
-def setup_logging(level: int = logging.INFO) -> None:
+def setup_logging(level: int = logging.INFO):
logging.basicConfig(level=level, format=LOG_FORMAT, datefmt=LOG_DATEFMT)
@@ -45,7 +49,13 @@ class ProgressLog:
self.path = Path(path)
self.enabled = enabled
- def log(self, event: str, step: int, metrics: dict[str, Any] | None = None, **fields) -> None:
+ def log(
+ self,
+ event: str,
+ step: int,
+ metrics: dict[str, Any] | None = None,
+ **fields: str | float | None,
+ ):
if not self.enabled:
return
record = {
@@ -63,7 +73,7 @@ class ProgressLog:
def git_commit() -> str | None:
"""HEAD's short sha, suffixed "-dirty" when the tree has uncommitted changes."""
- def run(*cmd):
+ def run(*cmd: str) -> str | None:
try:
out = subprocess.run(cmd, capture_output=True, text=True, timeout=10, check=False)
except (OSError, subprocess.SubprocessError):
@@ -77,7 +87,7 @@ def git_commit() -> str | None:
return sha.strip() + ("-dirty" if dirty else "")
-def _compile_models(model, mimi) -> None:
+def _compile_models(model: TrainableTTS, mimi: MimiModel):
"""Per-layer compilation: whole-module compile trips dynamo on the
streaming-state plumbing, individual layers and the flow head are clean.
In-place .compile() (not torch.compile(module)) so state_dict keys stay
@@ -85,7 +95,7 @@ def _compile_models(model, mimi) -> None:
The frozen Mimi encoder runs under no_grad outside the DDP module, so
compiling it is safe on any GPU count (~6ms/step)."""
- def _compile_backbone(fl):
+ def _compile_backbone(fl: FlowLMModel):
for layer in fl.transformer.layers:
layer.compile(dynamic=True)
@@ -111,7 +121,16 @@ def lr_at(step: int, args: TrainArgs) -> float:
@torch.no_grad()
-def write_samples(model, mimi, tokenize, args, run_dir, step, voice_latents, device):
+def write_samples(
+ model: TrainableTTS,
+ mimi: MimiModel,
+ tokenize: Callable[[str], list[int]],
+ args: TrainArgs,
+ run_dir: Path,
+ step: int,
+ voice_latents: torch.Tensor,
+ device: torch.device,
+):
"""Synthesize the configured sentences from the live (raw) weights."""
out_dir = run_dir / "samples"
out_dir.mkdir(exist_ok=True)
@@ -140,7 +159,9 @@ def write_samples(model, mimi, tokenize, args, run_dir, step, voice_latents, dev
logger.info(f"wrote {len(tokens)} samples at step {step}")
-def ensure_train_latents(args: TrainArgs, mimi, device, rank: int, world_size: int) -> None:
+def ensure_train_latents(
+ args: TrainArgs, mimi: MimiModel, device: torch.device, rank: int, world_size: int
+):
"""Train from precomputed latents, encoding them first if needed.
The latents store is keyed by a hash of Mimi's encode-path weights, so
diff --git a/uv.lock b/uv.lock
index b3c34b7..4bbe920 100644
--- a/uv.lock
+++ b/uv.lock
@@ -1531,7 +1531,7 @@ requires-dist = [
{ name = "torch", specifier = ">=2.5.0" },
{ name = "torchao", marker = "extra == 'quantize'", specifier = ">=0.16.0" },
{ name = "typer", specifier = ">=0.10.0" },
- { name = "typing-extensions", specifier = ">=4.0.0" },
+ { name = "typing-extensions", specifier = ">=4.10.0" },
{ name = "uvicorn", specifier = ">=0.13.0" },
]
provides-extras = ["audio", "quantize"]