A TTS that fits in your CPU (and pocket)
Python
Move text conditioning into modules/text_conditioner.py (#275)
manu-lm7809e76aa94d
diff --git a/pocket_tts/conditioners/__init__.py b/pocket_tts/conditioners/__init__.pydeleted file mode 100644index e69de29..0000000diff --git a/pocket_tts/conditioners/base.py b/pocket_tts/conditioners/base.pydeleted file mode 100644index 03bdcc8..0000000--- a/pocket_tts/conditioners/base.py+++ /dev/null@@ -1,7 +0,0 @@-from typing import NamedTuple--import torch---class TokenizedText(NamedTuple):- tokens: torch.Tensor # should be long tensor.diff --git a/pocket_tts/models/flow_lm.py b/pocket_tts/models/flow_lm.pyindex f044270..8eb0263 100644--- a/pocket_tts/models/flow_lm.py+++ b/pocket_tts/models/flow_lm.py@@ -6,8 +6,8 @@ from beartype.typing import Callablefrom torch import nnfrom typing_extensions import Self-from pocket_tts.conditioners.text import LUTConditionerfrom pocket_tts.modules.mlp import SimpleMLPAdaLN+from pocket_tts.modules.text_conditioner import LUTConditionerfrom pocket_tts.modules.transformer import StreamingTransformerfrom pocket_tts.utils.config import FlowLMConfigdiff --git a/pocket_tts/models/text_chunking.py b/pocket_tts/models/text_chunking.pyindex bc28255..1d48f6c 100644--- a/pocket_tts/models/text_chunking.py+++ b/pocket_tts/models/text_chunking.py@@ -114,9 +114,9 @@ def split_into_best_sentences()text_to_generate = text_to_generate.strip()tokens = tokenizer(text_to_generate)- list_of_tokens = tokens.tokens[0].tolist()+ list_of_tokens = tokens[0].tolist()- _, *end_of_sentence_tokens = tokenizer(".!...?").tokens[0].tolist()+ _, *end_of_sentence_tokens = tokenizer(".!...?")[0].tolist()sentence_boundaries = _find_boundary_indices(list_of_tokens, end_of_sentence_tokens, tokenizer, skip_decimal_periods=True)@@ -125,13 +125,13 @@ def split_into_best_sentences()# Sub-split oversized sentences on commas, semicolons, and colons to prevent skipped words- _, *fallback_tokens = tokenizer(",;:").tokens[0].tolist()+ _, *fallback_tokens = tokenizer(",;:")[0].tolist()refined_segments = []for nb_tokens, text in nb_tokens_and_sentences:if nb_tokens <= max_tokens:refined_segments.append((nb_tokens, text))else:- sub_tokens = tokenizer(text.strip()).tokens[0].tolist()+ sub_tokens = tokenizer(text.strip())[0].tolist()sub_boundaries = _find_boundary_indices(sub_tokens, fallback_tokens)sub_segments = _segments_from_boundaries(sub_tokens, sub_boundaries, tokenizer)if len(sub_segments) > 1:@@ -161,7 +161,7 @@ def split_into_best_sentences(chunks.append(current_chunk.strip())for chunk in chunks:- chunk_tokens = tokenizer(chunk.strip()).tokens[0].tolist()+ chunk_tokens = tokenizer(chunk.strip())[0].tolist()if len(chunk_tokens) > max_tokens:logger.warning("Chunk has %d tokens (max %d), generation may skip words: '%.50s...'",diff --git a/pocket_tts/models/tts_model.py b/pocket_tts/models/tts_model.pyindex 347a0d0..2fb6a7a 100644--- a/pocket_tts/models/tts_model.py+++ b/pocket_tts/models/tts_model.py@@ -17,7 +17,6 @@ from torch import nnfrom torch.nn import functional as Ffrom typing_extensions import Self-from pocket_tts.conditioners.base import TokenizedTextfrom pocket_tts.data.audio import audio_readfrom pocket_tts.data.audio_utils import convert_audiofrom pocket_tts.default_parameters import (@@ -400,7 +399,7 @@ class TTSModel(nn.Module):backbone_input_latents: torch.Tensor,audio_conditioning: torch.Tensor,) -> tuple[torch.Tensor, torch.Tensor]:- text_embeddings = self.flow_lm.conditioner(TokenizedText(text_tokens))+ text_embeddings = self.flow_lm.conditioner(text_tokens)text_embeddings = torch.cat([text_embeddings, audio_conditioning], dim=1)output_embeddings, is_eos = self.flow_lm._sample_next_latent(@@ -680,7 +679,7 @@ class TTSModel(nn.Module):model_state = copy.deepcopy(model_state)prepared = self.flow_lm.conditioner.prepare(text_to_generate)- token_count = prepared.tokens.shape[1]+ token_count = prepared.shape[1]max_gen_len = self._estimate_max_gen_len(token_count)mimi_steps_per_latent = int(self.mimi.encoder_frame_rate / self.mimi.frame_rate)mimi_sequence_length = max_gen_len * mimi_steps_per_latent@@ -750,21 +749,19 @@ class TTSModel(nn.Module):def _generate(self,model_state: dict,- prepared: TokenizedText,+ prepared: torch.Tensor,max_gen_len: int,frames_after_eos: int,latents_queue: queue.Queue,result_queue: queue.Queue,):- token_count = prepared.tokens.shape[1]+ token_count = prepared.shape[1]current_end = self._flow_lm_current_end(model_state)required_len = current_end + token_count + max_gen_lenself._expand_kv_cache(model_state, sequence_length=required_len)with display_execution_time("Prompting text"):- self._run_flow_lm_and_increment_step(- model_state=model_state, text_tokens=prepared.tokens- )+ self._run_flow_lm_and_increment_step(model_state=model_state, text_tokens=prepared)def run_generation():try:diff --git a/pocket_tts/conditioners/text.py b/pocket_tts/modules/text_conditioner.pysimilarity index 82%rename from pocket_tts/conditioners/text.pyrename to pocket_tts/modules/text_conditioner.pyindex 3b05e43..056f28c 100644--- a/pocket_tts/conditioners/text.py+++ b/pocket_tts/modules/text_conditioner.py@@ -4,7 +4,6 @@ import sentencepieceimport torchfrom torch import nn-from pocket_tts.conditioners.base import TokenizedTextfrom pocket_tts.utils.utils import download_if_necessarylogger = logging.getLogger(__name__)@@ -31,8 +30,8 @@ class SentencePieceTokenizer:f"sentencepiece tokenizer has vocab size={self.sp.vocab_size()} but nbins={nbins} was specified")- def __call__(self, text: str) -> TokenizedText:- return TokenizedText(torch.tensor(self.sp.encode(text, out_type=int))[None, :])+ def __call__(self, text: str) -> torch.Tensor:+ return torch.tensor(self.sp.encode(text, out_type=int))[None, :]DEFAULT_TOKENIZER_N_BINS = 4000@@ -68,10 +67,8 @@ class LUTConditioner(nn.Module):self.tokenizer = SentencePieceTokenizer(n_bins, tokenizer_path)self.embed = nn.Embedding(n_bins + 1, self.dim) # n_bins + 1 for padding.- def prepare(self, x: str) -> TokenizedText:- tokens = self.tokenizer(x)- tokens = tokens[0].to(self.embed.weight.device)- return TokenizedText(tokens)+ def prepare(self, x: str) -> torch.Tensor:+ return self.tokenizer(x).to(self.embed.weight.device)- def forward(self, inputs: TokenizedText) -> torch.Tensor:- return self.embed(inputs[0])+ def forward(self, tokens: torch.Tensor) -> torch.Tensor:+ return self.embed(tokens)diff --git a/tests/test_generation_regressions.py b/tests/test_generation_regressions.pyindex ce43227..04eb59f 100644--- a/tests/test_generation_regressions.py+++ b/tests/test_generation_regressions.py@@ -5,7 +5,6 @@ import pytestimport torchimport pocket_tts.models.tts_model as tts_model_module-from pocket_tts.conditioners.base import TokenizedTextfrom pocket_tts.models.tts_model import TTSModel, _is_safetensors_source@@ -60,7 +59,7 @@ def test_generate_reports_autoregressive_errors_before_decoder_done():TTSModel._generate(model,model_state={},- prepared=TokenizedText(torch.zeros((1, 1), dtype=torch.long)),+ prepared=torch.zeros((1, 1), dtype=torch.long),max_gen_len=1,frames_after_eos=1,latents_queue=latents_queue,diff --git a/tests/test_split_sentences.py b/tests/test_split_sentences.pyindex bfdeb50..aa2abff 100644--- a/tests/test_split_sentences.py+++ b/tests/test_split_sentences.py@@ -2,8 +2,8 @@import pytest-from pocket_tts.conditioners.text import get_default_tokenizerfrom pocket_tts.models.tts_model import split_into_best_sentences+from pocket_tts.modules.text_conditioner import get_default_tokenizer@pytest.fixture(scope="session")@@ -65,7 +65,7 @@ def test_long_sentence_with_commas_respects_max_tokens(tokenizer):tokenizer, text, max_tokens, pad_with_spaces_for_short_inputs=False, remove_semicolons=False)for chunk in chunks:- token_count = len(tokenizer(chunk.strip()).tokens[0].tolist())+ token_count = len(tokenizer(chunk.strip())[0].tolist())# Allow some tolerance since comma clauses may vary in sizeassert token_count <= max_tokens * 2, (f"Chunk '{chunk[:50]}...' has {token_count} tokens, expected ~{max_tokens}"diff --git a/training/modules/conditioner.py b/training/modules/conditioner.pyindex 626a3d1..44bd77d 100644--- a/training/modules/conditioner.py+++ b/training/modules/conditioner.py@@ -9,8 +9,6 @@ import torchimport torch.nn.functional as Ffrom torch import nn-from pocket_tts.conditioners.base import TokenizedText-from ..args import TrainArgs@@ -70,7 +68,7 @@ def build_sequences_with_conditions(text_pad_cpu = torch.full((B, Lmax), pad_id, dtype=torch.long)for b, t in enumerate(text_tokens):text_pad_cpu[b, : t.shape[0]] = t- text_emb = fl.conditioner(TokenizedText(text_pad_cpu.to(device))).to(dtype)+ text_emb = fl.conditioner(text_pad_cpu.to(device)).to(dtype)t_len_cpu = text_lens_cpu * keep_text_cpuprefix_lengths_cpu = 1 + v_len_cpu + t_len_cpudiff --git a/training/modules/model.py b/training/modules/model.pyindex 538e696..3c8e36d 100644--- a/training/modules/model.py+++ b/training/modules/model.py@@ -16,7 +16,6 @@ import torchimport torch.nn.functional as Ffrom torch import nn-from pocket_tts.conditioners.base import TokenizedTextfrom pocket_tts.modules.stateful_module import increment_steps, init_statesfrom ..args import TrainArgs@@ -146,7 +145,7 @@ class TrainableTTS(nn.Module):rows = []for tokens, voice in zip(text_tokens, voice_latents, strict=True):- t_emb = fl.conditioner(TokenizedText(tokens[None].to(device)))[0]+ t_emb = fl.conditioner(tokens[None].to(device))[0]v_emb = F.linear(voice[None].to(device, fl.speaker_proj_weight.dtype), fl.speaker_proj_weight)[0]diff --git a/training/tests/test_smoke.py b/training/tests/test_smoke.pyindex 0df5806..9d7d285 100644--- a/training/tests/test_smoke.py+++ b/training/tests/test_smoke.py@@ -16,11 +16,10 @@ from torch import nnsys.path.insert(0, str(Path(__file__).resolve().parents[2]))import training.dataloader as td-from pocket_tts.conditioners.base import TokenizedText-from pocket_tts.conditioners.text import LUTConditionerfrom pocket_tts.models.flow_lm import FlowLMModelfrom pocket_tts.modules.mlp import SimpleMLPAdaLNfrom pocket_tts.modules.stateful_module import init_states+from pocket_tts.modules.text_conditioner import LUTConditionerfrom pocket_tts.modules.transformer import StreamingTransformerfrom training.args import TrainArgsfrom training.checkpointing import EMA@@ -42,8 +41,8 @@ class DummyConditioner(LUTConditioner):self.output_dim = dimself.embed = nn.Embedding(n_bins + 1, dim)- def forward(self, inputs: TokenizedText) -> torch.Tensor:- return self.embed(inputs[0])+ def forward(self, tokens: torch.Tensor) -> torch.Tensor:+ return self.embed(tokens)def tiny_model(flow_type: str, context: int | None = None) -> TrainableTTS: