A TTS that fits in your CPU (and pocket)
Python
Load tokenizers from tokenizer.json, keeping .model support (#317)
manu-lm4367c363ba6b
diff --git a/pocket_tts/config/english.yaml b/pocket_tts/config/english.yamlindex df05900..586e8af 100644--- a/pocket_tts/config/english.yaml+++ b/pocket_tts/config/english.yaml@@ -21,8 +21,8 @@ flow_lm:lookup_table:dim: 1024n_bins: 4000- tokenizer: sentencepiece- tokenizer_path: hf://kyutai/pocket-tts-without-voice-cloning/languages/english/tokenizer.model@d29db7978e464fb90cb3359ee0c69a273b9142cc+ tokenizer: tokenizers+ tokenizer_path: hf://kyutai/pocket-tts-without-voice-cloning/languages/english/tokenizer.json@00eac05ed3d16bdc3f6b5d598874019c34a89214#weights_path: final.safetensorsmimi:diff --git a/pocket_tts/config/english_2026-01.yaml b/pocket_tts/config/english_2026-01.yamlindex a730f60..67a992a 100644--- a/pocket_tts/config/english_2026-01.yaml+++ b/pocket_tts/config/english_2026-01.yaml@@ -20,8 +20,8 @@ flow_lm:lookup_table:dim: 1024n_bins: 4000- tokenizer: sentencepiece- tokenizer_path: hf://kyutai/pocket-tts-without-voice-cloning/tokenizer.model@d29db7978e464fb90cb3359ee0c69a273b9142cc+ tokenizer: tokenizers+ tokenizer_path: hf://kyutai/pocket-tts-without-voice-cloning/tokenizer.json@00eac05ed3d16bdc3f6b5d598874019c34a89214#weights_path: flow_lm_b6369a24.safetensorsmimi:diff --git a/pocket_tts/config/english_2026-04.yaml b/pocket_tts/config/english_2026-04.yamlindex 13c1a62..923b060 100644--- a/pocket_tts/config/english_2026-04.yaml+++ b/pocket_tts/config/english_2026-04.yaml@@ -21,8 +21,8 @@ flow_lm:lookup_table:dim: 1024n_bins: 4000- tokenizer: sentencepiece- tokenizer_path: hf://kyutai/pocket-tts-without-voice-cloning/languages/english_2026-04/tokenizer.model@d29db7978e464fb90cb3359ee0c69a273b9142cc+ tokenizer: tokenizers+ tokenizer_path: hf://kyutai/pocket-tts-without-voice-cloning/languages/english_2026-04/tokenizer.json@00eac05ed3d16bdc3f6b5d598874019c34a89214#weights_path: final.safetensorsmimi:diff --git a/pocket_tts/config/english_2026-04_24l.yaml b/pocket_tts/config/english_2026-04_24l.yamlindex 4883d24..61d4b00 100644--- a/pocket_tts/config/english_2026-04_24l.yaml+++ b/pocket_tts/config/english_2026-04_24l.yaml@@ -17,8 +17,8 @@ flow_lm:lookup_table:dim: 1024n_bins: 4000- tokenizer: sentencepiece- tokenizer_path: hf://kyutai/pocket-tts-without-voice-cloning/languages/english_2026-04_24l/tokenizer.model@e81d79e8194ad4c7ce879c87a4258ef20cbf2487+ tokenizer: tokenizers+ tokenizer_path: hf://kyutai/pocket-tts-without-voice-cloning/languages/english_2026-04_24l/tokenizer.json@00eac05ed3d16bdc3f6b5d598874019c34a89214mimi:dtype: float32sample_rate: 24000diff --git a/pocket_tts/config/english_2026-09.yaml b/pocket_tts/config/english_2026-09.yamlindex 15ebc97..fd72050 100644--- a/pocket_tts/config/english_2026-09.yaml+++ b/pocket_tts/config/english_2026-09.yaml@@ -23,8 +23,8 @@ flow_lm:lookup_table:dim: 1024n_bins: 4000- tokenizer: sentencepiece- tokenizer_path: hf://kyutai/pocket-tts-without-voice-cloning/languages/english_2026-09/tokenizer.model@e7205b6ee50e654a5ea19f0e9df2b0813b05e921+ tokenizer: tokenizers+ tokenizer_path: hf://kyutai/pocket-tts-without-voice-cloning/languages/english_2026-09/tokenizer.json@00eac05ed3d16bdc3f6b5d598874019c34a89214#weights_path: final.safetensorsmimi:diff --git a/pocket_tts/config/english_2026-09_24l.yaml b/pocket_tts/config/english_2026-09_24l.yamlindex 33c13fc..13ff891 100644--- a/pocket_tts/config/english_2026-09_24l.yaml+++ b/pocket_tts/config/english_2026-09_24l.yaml@@ -18,8 +18,8 @@ flow_lm:lookup_table:dim: 1024n_bins: 4000- tokenizer: sentencepiece- tokenizer_path: hf://kyutai/pocket-tts-without-voice-cloning/languages/english_2026-09_24l/tokenizer.model@e7205b6ee50e654a5ea19f0e9df2b0813b05e921+ tokenizer: tokenizers+ tokenizer_path: hf://kyutai/pocket-tts-without-voice-cloning/languages/english_2026-09_24l/tokenizer.json@00eac05ed3d16bdc3f6b5d598874019c34a89214mimi:dtype: float32sample_rate: 24000diff --git a/pocket_tts/config/french_24l.yaml b/pocket_tts/config/french_24l.yamlindex dfd815a..a771036 100644--- a/pocket_tts/config/french_24l.yaml+++ b/pocket_tts/config/french_24l.yaml@@ -21,8 +21,8 @@ flow_lm:lookup_table:dim: 1024n_bins: 4000- tokenizer: sentencepiece- tokenizer_path: hf://kyutai/pocket-tts-without-voice-cloning/languages/french_24l/tokenizer.model@d29db7978e464fb90cb3359ee0c69a273b9142cc+ tokenizer: tokenizers+ tokenizer_path: hf://kyutai/pocket-tts-without-voice-cloning/languages/french_24l/tokenizer.json@00eac05ed3d16bdc3f6b5d598874019c34a89214#weights_path: partial.safetensorsmimi:diff --git a/pocket_tts/config/german.yaml b/pocket_tts/config/german.yamlindex 9ac6414..bbd19fd 100644--- a/pocket_tts/config/german.yaml+++ b/pocket_tts/config/german.yaml@@ -20,8 +20,8 @@ flow_lm:lookup_table:dim: 1024n_bins: 4000- tokenizer: sentencepiece- tokenizer_path: hf://kyutai/pocket-tts-without-voice-cloning/languages/german/tokenizer.model@d29db7978e464fb90cb3359ee0c69a273b9142cc+ tokenizer: tokenizers+ tokenizer_path: hf://kyutai/pocket-tts-without-voice-cloning/languages/german/tokenizer.json@00eac05ed3d16bdc3f6b5d598874019c34a89214#weights_path: partial.safetensorsmimi:diff --git a/pocket_tts/config/german_24l.yaml b/pocket_tts/config/german_24l.yamlindex 17fd263..25cfcbc 100644--- a/pocket_tts/config/german_24l.yaml+++ b/pocket_tts/config/german_24l.yaml@@ -20,8 +20,8 @@ flow_lm:lookup_table:dim: 1024n_bins: 4000- tokenizer: sentencepiece- tokenizer_path: hf://kyutai/pocket-tts-without-voice-cloning/languages/german_24l/tokenizer.model@d29db7978e464fb90cb3359ee0c69a273b9142cc+ tokenizer: tokenizers+ tokenizer_path: hf://kyutai/pocket-tts-without-voice-cloning/languages/german_24l/tokenizer.json@00eac05ed3d16bdc3f6b5d598874019c34a89214#weights_path: partial.safetensorsmimi:diff --git a/pocket_tts/config/italian.yaml b/pocket_tts/config/italian.yamlindex 5cf7392..2f3e773 100644--- a/pocket_tts/config/italian.yaml+++ b/pocket_tts/config/italian.yaml@@ -19,8 +19,8 @@ flow_lm:lookup_table:dim: 1024n_bins: 4000- tokenizer: sentencepiece- tokenizer_path: hf://kyutai/pocket-tts-without-voice-cloning/languages/italian/tokenizer.model@d29db7978e464fb90cb3359ee0c69a273b9142cc+ tokenizer: tokenizers+ tokenizer_path: hf://kyutai/pocket-tts-without-voice-cloning/languages/italian/tokenizer.json@00eac05ed3d16bdc3f6b5d598874019c34a89214#weights_path: partial.safetensorsmimi:diff --git a/pocket_tts/config/italian_24l.yaml b/pocket_tts/config/italian_24l.yamlindex a1ed4f6..83f1308 100644--- a/pocket_tts/config/italian_24l.yaml+++ b/pocket_tts/config/italian_24l.yaml@@ -19,8 +19,8 @@ flow_lm:lookup_table:dim: 1024n_bins: 4000- tokenizer: sentencepiece- tokenizer_path: hf://kyutai/pocket-tts-without-voice-cloning/languages/italian_24l/tokenizer.model@d29db7978e464fb90cb3359ee0c69a273b9142cc+ tokenizer: tokenizers+ tokenizer_path: hf://kyutai/pocket-tts-without-voice-cloning/languages/italian_24l/tokenizer.json@00eac05ed3d16bdc3f6b5d598874019c34a89214#weights_path: partial.safetensorsmimi:diff --git a/pocket_tts/config/portuguese.yaml b/pocket_tts/config/portuguese.yamlindex ea57c23..a071fc9 100644--- a/pocket_tts/config/portuguese.yaml+++ b/pocket_tts/config/portuguese.yaml@@ -19,8 +19,8 @@ flow_lm:lookup_table:dim: 1024n_bins: 4000- tokenizer: sentencepiece- tokenizer_path: hf://kyutai/pocket-tts-without-voice-cloning/languages/portuguese/tokenizer.model@d29db7978e464fb90cb3359ee0c69a273b9142cc+ tokenizer: tokenizers+ tokenizer_path: hf://kyutai/pocket-tts-without-voice-cloning/languages/portuguese/tokenizer.json@00eac05ed3d16bdc3f6b5d598874019c34a89214#weights_path: partial.safetensorsmimi:diff --git a/pocket_tts/config/portuguese_24l.yaml b/pocket_tts/config/portuguese_24l.yamlindex d84bde1..ca3314a 100644--- a/pocket_tts/config/portuguese_24l.yaml+++ b/pocket_tts/config/portuguese_24l.yaml@@ -19,8 +19,8 @@ flow_lm:lookup_table:dim: 1024n_bins: 4000- tokenizer: sentencepiece- tokenizer_path: hf://kyutai/pocket-tts-without-voice-cloning/languages/portuguese_24l/tokenizer.model@d29db7978e464fb90cb3359ee0c69a273b9142cc+ tokenizer: tokenizers+ tokenizer_path: hf://kyutai/pocket-tts-without-voice-cloning/languages/portuguese_24l/tokenizer.json@00eac05ed3d16bdc3f6b5d598874019c34a89214#weights_path: partial.safetensorsmimi:diff --git a/pocket_tts/config/spanish.yaml b/pocket_tts/config/spanish.yamlindex f974781..2fc23a6 100644--- a/pocket_tts/config/spanish.yaml+++ b/pocket_tts/config/spanish.yaml@@ -19,8 +19,8 @@ flow_lm:lookup_table:dim: 1024n_bins: 4000- tokenizer: sentencepiece- tokenizer_path: hf://kyutai/pocket-tts-without-voice-cloning/languages/spanish/tokenizer.model@d29db7978e464fb90cb3359ee0c69a273b9142cc+ tokenizer: tokenizers+ tokenizer_path: hf://kyutai/pocket-tts-without-voice-cloning/languages/spanish/tokenizer.json@00eac05ed3d16bdc3f6b5d598874019c34a89214#weights_path: partial.safetensorsmimi:diff --git a/pocket_tts/config/spanish_24l.yaml b/pocket_tts/config/spanish_24l.yamlindex 1651623..4f618c9 100644--- a/pocket_tts/config/spanish_24l.yaml+++ b/pocket_tts/config/spanish_24l.yaml@@ -19,8 +19,8 @@ flow_lm:lookup_table:dim: 1024n_bins: 4000- tokenizer: sentencepiece- tokenizer_path: hf://kyutai/pocket-tts-without-voice-cloning/languages/spanish_24l/tokenizer.model@d29db7978e464fb90cb3359ee0c69a273b9142cc+ tokenizer: tokenizers+ tokenizer_path: hf://kyutai/pocket-tts-without-voice-cloning/languages/spanish_24l/tokenizer.json@00eac05ed3d16bdc3f6b5d598874019c34a89214#weights_path: partial.safetensorsmimi:diff --git a/pocket_tts/models/flow_lm.py b/pocket_tts/models/flow_lm.pyindex e831b12..cc328cb 100644--- a/pocket_tts/models/flow_lm.py+++ b/pocket_tts/models/flow_lm.py@@ -231,6 +231,7 @@ class FlowLMModel(nn.Module):tokenizer_path=str(config.lookup_table.tokenizer_path),dim=config.lookup_table.dim,output_dim=d_model,+ tokenizer=config.lookup_table.tokenizer,)transformer = StreamingTransformer.from_pydantic_config(config.transformer)diff --git a/pocket_tts/models/text_chunking.py b/pocket_tts/models/text_chunking.pyindex a2756db..07fd001 100644--- a/pocket_tts/models/text_chunking.py+++ b/pocket_tts/models/text_chunking.py@@ -6,7 +6,7 @@ boundaries and regrouped into chunks that fit `max_tokens`.import logging-from pocket_tts.modules.text_conditioner import SentencePieceTokenizer+from pocket_tts.modules.text_conditioner import Tokenizerlogger = logging.getLogger(__name__)@@ -73,11 +73,11 @@ def _ensure_terminal_punctuation(text: str) -> str:def _is_decimal_period_boundary(- list_of_tokens: list[int], segment_start_idx: int, tokenizer: SentencePieceTokenizer+ list_of_tokens: list[int], segment_start_idx: int, tokenizer: Tokenizer) -> bool:"""Return True when segment_start_idx begins right after a decimal period."""- prefix = tokenizer.sp.decode(list_of_tokens[:segment_start_idx])- suffix = tokenizer.sp.decode(list_of_tokens[segment_start_idx:])+ prefix = tokenizer.decode(list_of_tokens[:segment_start_idx])+ suffix = tokenizer.decode(list_of_tokens[segment_start_idx:])return (len(prefix) >= 2and prefix[-1] == "."@@ -90,7 +90,7 @@ def _is_decimal_period_boundary(def _find_boundary_indices(list_of_tokens: list[int],boundary_tokens: list[int],- tokenizer: SentencePieceTokenizer | None = None,+ tokenizer: Tokenizer | None = None,skip_decimal_periods: bool = False,) -> list[int]:"""Find token indices where text should be split based on boundary tokens.@@ -121,20 +121,20 @@ def _find_boundary_indices(def _segments_from_boundaries(- list_of_tokens: list[int], boundary_indices: list[int], tokenizer: SentencePieceTokenizer+ list_of_tokens: list[int], boundary_indices: list[int], tokenizer: Tokenizer) -> list[tuple[int, str]]:"""Decode token segments between boundary indices into (token_count, text) pairs."""segments = []for i in range(len(boundary_indices) - 1):start = boundary_indices[i]end = boundary_indices[i + 1]- text = tokenizer.sp.decode(list_of_tokens[start:end])+ text = tokenizer.decode(list_of_tokens[start:end])segments.append((end - start, text))return segmentsdef split_into_best_sentences(- tokenizer: SentencePieceTokenizer,+ tokenizer: Tokenizer,text_to_generate: str,max_tokens: int,pad_with_spaces_for_short_inputs: bool,diff --git a/pocket_tts/modules/text_conditioner.py b/pocket_tts/modules/text_conditioner.pyindex f98a7e1..f72d689 100644--- a/pocket_tts/modules/text_conditioner.py+++ b/pocket_tts/modules/text_conditioner.py@@ -1,6 +1,8 @@import logging+from collections.abc import Callableimport sentencepiece+import tokenizersimport torchfrom torch import nn@@ -30,23 +32,83 @@ class SentencePieceTokenizer:f"sentencepiece tokenizer has vocab size={self.sp.vocab_size()} but nbins={nbins} was specified")+ def encode(self, text: str) -> list[int]:+ return self.sp.encode(text, out_type=int)++ def decode(self, tokens: list[int]) -> str:+ return self.sp.decode(tokens)++ def serialize(self) -> tuple[str, bytes]:+ """(kind, payload) for `encoder_from_serialized`, to cross a process boundary."""+ return "sentencepiece", self.sp.serialized_model_proto()++ def __call__(self, text: str) -> torch.Tensor:+ return torch.tensor(self.encode(text))[None, :]+++class JsonTokenizer:+ """A `tokenizer.json` (HuggingFace tokenizers) holding the same vocabulary.++ Converted from the SentencePiece model, so it produces identical token ids;+ it loads without the sentencepiece runtime and is the format the released+ configs point at. `.model` files stay supported for models trained elsewhere.+ """++ def __init__(self, nbins: int, tokenizer_path: str):+ logger.info("Loading tokenizers json from %s", tokenizer_path)+ local_path = download_if_necessary(tokenizer_path)+ self.tokenizer = tokenizers.Tokenizer.from_file(str(local_path))+ vocab_size = self.tokenizer.get_vocab_size()+ assert nbins == vocab_size, (+ f"tokenizer has vocab size={vocab_size} but nbins={nbins} was specified"+ )++ def encode(self, text: str) -> list[int]:+ return self.tokenizer.encode(text).ids++ def decode(self, tokens: list[int]) -> str:+ return self.tokenizer.decode(tokens)++ def serialize(self) -> tuple[str, bytes]:+ return "tokenizers", self.tokenizer.to_str().encode()+def __call__(self, text: str) -> torch.Tensor:- return torch.tensor(self.sp.encode(text, out_type=int))[None, :]+ return torch.tensor(self.encode(text))[None, :]+++Tokenizer = SentencePieceTokenizer | JsonTokenizer+++def encoder_from_serialized(kind: str, payload: bytes) -> Callable[[str], list[int]]:+ """Rebuild just the text -> ids function in a worker process."""+ if kind == "tokenizers":+ tokenizer = tokenizers.Tokenizer.from_str(payload.decode())+ return lambda text: tokenizer.encode(text).ids+ sp = sentencepiece.SentencePieceProcessor()+ sp.load_from_serialized_proto(payload)+ return lambda text: sp.encode(text, out_type=int)+++def build_tokenizer(nbins: int, tokenizer_path: str, kind: str = "sentencepiece") -> Tokenizer:+ """Pick the backend from the config's `tokenizer` field, else from the suffix."""+ if kind in ("tokenizers", "json") or str(tokenizer_path).split("@")[0].endswith(".json"):+ return JsonTokenizer(nbins, tokenizer_path)+ return SentencePieceTokenizer(nbins, tokenizer_path)DEFAULT_TOKENIZER_N_BINS = 4000DEFAULT_TOKENIZER_PATH = ("hf://kyutai/pocket-tts-without-voice-cloning/"- "tokenizer.model@d4fdd22ae8c8e1cb3634e150ebeff1dab2d16df3"+ "tokenizer.json@00eac05ed3d16bdc3f6b5d598874019c34a89214")-def get_default_tokenizer() -> SentencePieceTokenizer:+def get_default_tokenizer() -> Tokenizer:"""Return a SentencePieceTokenizer with the default model path and vocab size.Downloads the tokenizer model from HuggingFace on first use."""- return SentencePieceTokenizer(DEFAULT_TOKENIZER_N_BINS, DEFAULT_TOKENIZER_PATH)+ return build_tokenizer(DEFAULT_TOKENIZER_N_BINS, DEFAULT_TOKENIZER_PATH)class LUTConditioner(nn.Module):@@ -60,11 +122,18 @@ class LUTConditioner(nn.Module):possible_values (list[str] or None): list of possible values for the tokenizer."""- def __init__(self, n_bins: int, tokenizer_path: str, dim: int, output_dim: int):+ def __init__(+ self,+ n_bins: int,+ tokenizer_path: str,+ dim: int,+ output_dim: int,+ tokenizer: str = "sentencepiece",+ ):super().__init__()self.dim = dimself.output_dim = output_dim- self.tokenizer = SentencePieceTokenizer(n_bins, tokenizer_path)+ self.tokenizer = build_tokenizer(n_bins, tokenizer_path, tokenizer)self.embed = nn.Embedding(n_bins + 1, self.dim) # n_bins + 1 for padding.def prepare(self, x: str) -> torch.Tensor:diff --git a/pyproject.toml b/pyproject.tomlindex 420817e..403ca8c 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -10,6 +10,7 @@ dependencies = ["torch>=2.5.0","pydantic>=2","sentencepiece>=0.2.1",+ "tokenizers>=0.21","safetensors>=0.4.0","typer>=0.10.0","typing_extensions>=4.10.0",diff --git a/tests/test_split_sentences.py b/tests/test_split_sentences.pyindex 87aa5f0..dd5f2a2 100644--- a/tests/test_split_sentences.py+++ b/tests/test_split_sentences.py@@ -3,15 +3,15 @@import pytestfrom pocket_tts.models.tts_model import prepare_text_prompt, split_into_best_sentences-from pocket_tts.modules.text_conditioner import SentencePieceTokenizer, get_default_tokenizer+from pocket_tts.modules.text_conditioner import Tokenizer, get_default_tokenizer@pytest.fixture(scope="session")-def tokenizer() -> SentencePieceTokenizer:+def tokenizer() -> Tokenizer:return get_default_tokenizer()-def test_short_text_single_chunk(tokenizer: SentencePieceTokenizer):+def test_short_text_single_chunk(tokenizer: Tokenizer):"""Short text should produce a single chunk."""chunks = split_into_best_sentences(tokenizer,@@ -23,7 +23,7 @@ def test_short_text_single_chunk(tokenizer: SentencePieceTokenizer):assert len(chunks) == 1-def test_multiple_sentences_split(tokenizer: SentencePieceTokenizer):+def test_multiple_sentences_split(tokenizer: Tokenizer):"""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: SentencePieceTokenizer):assert len(chunks) > 1-def test_long_sentence_with_commas_is_split(tokenizer: SentencePieceTokenizer):+def test_long_sentence_with_commas_is_split(tokenizer: Tokenizer):"""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 exampletext = (@@ -53,7 +53,7 @@ def test_long_sentence_with_commas_is_split(tokenizer: SentencePieceTokenizer):assert phrase in rejoined, f"'{phrase}' should be preserved after splitting"-def test_long_sentence_with_commas_respects_max_tokens(tokenizer: SentencePieceTokenizer):+def test_long_sentence_with_commas_respects_max_tokens(tokenizer: Tokenizer):"""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: SentencePieceT)-def test_mixed_sentences_and_commas(tokenizer: SentencePieceTokenizer):+def test_mixed_sentences_and_commas(tokenizer: Tokenizer):"""Text with both sentence boundaries and long comma-separated clauses."""text = ("Short sentence. "@@ -87,7 +87,7 @@ def test_mixed_sentences_and_commas(tokenizer: SentencePieceTokenizer):assert len(chunks) >= 3-def test_no_commas_no_periods_stays_single_chunk(tokenizer: SentencePieceTokenizer):+def test_no_commas_no_periods_stays_single_chunk(tokenizer: Tokenizer):"""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: SentencePieceTokenizassert len(chunks) == 1-def test_semicolons_and_colons_also_split(tokenizer: SentencePieceTokenizer):+def test_semicolons_and_colons_also_split(tokenizer: Tokenizer):"""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: SentencePieceTokenizer):assert len(chunks) > 1-def test_short_sentence_not_affected_by_comma_splitting(tokenizer: SentencePieceTokenizer):+def test_short_sentence_not_affected_by_comma_splitting(tokenizer: Tokenizer):"""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: SentencePieceassert "world" in chunks[0].lower()-def test_empty_string_raises(tokenizer: SentencePieceTokenizer):+def test_empty_string_raises(tokenizer: Tokenizer):"""Empty input should raise ValueError from prepare_text_prompt."""with pytest.raises(ValueError, match="empty"):split_into_best_sentences(@@ -138,7 +138,7 @@ def test_terminal_punctuation_can_be_disabled_for_punctuation_free_training():assert text == "नमस्ते आज आपका दिन कैसा रहा"-def test_decimals_are_not_split_on_period(tokenizer: SentencePieceTokenizer):+def test_decimals_are_not_split_on_period(tokenizer: Tokenizer):"""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."@@ -151,7 +151,7 @@ def test_decimals_are_not_split_on_period(tokenizer: SentencePieceTokenizer):assert "98. 6" not in chunks[0]-def test_multiple_decimals_in_one_sentence(tokenizer: SentencePieceTokenizer):+def test_multiple_decimals_in_one_sentence(tokenizer: Tokenizer):"""Several decimals in one sentence should stay intact."""text = "Pi is 3.14 and e is 2.718."chunks = split_into_best_sentences(@@ -164,7 +164,7 @@ def test_multiple_decimals_in_one_sentence(tokenizer: SentencePieceTokenizer):assert "2. 718" not in chunks[0]-def test_decimal_followed_by_sentence_boundary(tokenizer: SentencePieceTokenizer):+def test_decimal_followed_by_sentence_boundary(tokenizer: Tokenizer):"""Decimals should be preserved while real sentence boundaries still split."""text = ("The average human body temperature is 98.6°F, "@@ -183,7 +183,7 @@ def test_decimal_followed_by_sentence_boundary(tokenizer: SentencePieceTokenizerassert "3. 14" not in rejoined-def test_sentence_period_after_decimal_still_splits(tokenizer: SentencePieceTokenizer):+def test_sentence_period_after_decimal_still_splits(tokenizer: Tokenizer):"""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(@@ -195,7 +195,7 @@ def test_sentence_period_after_decimal_still_splits(tokenizer: SentencePieceTokeassert "2. 0" not in chunks[0]-def test_oversized_clause_without_commas_still_returns(tokenizer: SentencePieceTokenizer):+def test_oversized_clause_without_commas_still_returns(tokenizer: Tokenizer):"""A long clause with no split points should still be returned (not dropped)."""# 20 words with no punctuation at all - no way to splittext = " ".join(f"word{i}" for i in range(20))diff --git a/tests/test_tokenizer_backends.py b/tests/test_tokenizer_backends.pynew file mode 100644index 0000000..0b8e816--- /dev/null+++ b/tests/test_tokenizer_backends.py@@ -0,0 +1,74 @@+"""The tokenizer.json backend must reproduce the SentencePiece ids exactly."""++from pathlib import Path++import pytest++from pocket_tts.modules.text_conditioner import (+ DEFAULT_TOKENIZER_N_BINS,+ JsonTokenizer,+ SentencePieceTokenizer,+ build_tokenizer,+)++SP_PATH = (+ "hf://kyutai/pocket-tts-without-voice-cloning/"+ "tokenizer.model@d4fdd22ae8c8e1cb3634e150ebeff1dab2d16df3"+)+JSON_PATH = (+ "hf://kyutai/pocket-tts-without-voice-cloning/"+ "tokenizer.json@00eac05ed3d16bdc3f6b5d598874019c34a89214"+)+# Leading and repeated whitespace exercise SentencePiece's add_dummy_prefix, the+# one place the two implementations can disagree.+TEXTS = [+ "Hello, world!",+ "café",+ " Hello, world!",+ " hello ",+ " ",+ "",+ "14½-13½",+ "Donkey kong uses the front lever to dodge the smash attack from fox.",+]++[email protected]("text", TEXTS)+def test_json_matches_sentencepiece(text: str) -> None:+ sp = SentencePieceTokenizer(DEFAULT_TOKENIZER_N_BINS, SP_PATH)+ js = JsonTokenizer(DEFAULT_TOKENIZER_N_BINS, JSON_PATH)+ assert js.encode(text) == sp.encode(text)+ assert js.decode(js.encode(text)) == sp.decode(sp.encode(text))+++def test_build_tokenizer_picks_the_backend() -> None:+ assert isinstance(build_tokenizer(DEFAULT_TOKENIZER_N_BINS, JSON_PATH), JsonTokenizer)+ # A community model trained before this change keeps working.+ assert isinstance(build_tokenizer(DEFAULT_TOKENIZER_N_BINS, SP_PATH), SentencePieceTokenizer)+ assert isinstance(+ build_tokenizer(DEFAULT_TOKENIZER_N_BINS, SP_PATH, "sentencepiece"), SentencePieceTokenizer+ )++[email protected]("path", [SP_PATH, JSON_PATH])+def test_serialize_round_trips_through_a_worker_payload(path: str) -> None:+ from pocket_tts.modules.text_conditioner import encoder_from_serialized++ tokenizer = build_tokenizer(DEFAULT_TOKENIZER_N_BINS, path)+ encode = encoder_from_serialized(*tokenizer.serialize())+ for text in TEXTS:+ assert encode(text) == tokenizer.encode(text)+++def test_convert_tokenizer_reproduces_sentencepiece() -> None:+ """The shipped tokenizer.json is what training/scripts/convert_tokenizer.py emits."""+ import sentencepiece as spm++ from pocket_tts.utils.utils import download_if_necessary+ from training.scripts.convert_tokenizer import CHECKS, build++ model = download_if_necessary(SP_PATH)+ tokenizer = build(Path(model))+ sp = spm.SentencePieceProcessor(model_file=str(model))+ for text in CHECKS + TEXTS:+ assert tokenizer.encode(text).ids == sp.encode(text, out_type=int), textdiff --git a/training/dataloader/subproc.py b/training/dataloader/subproc.pyindex 7030d50..ea841ac 100644--- a/training/dataloader/subproc.py+++ b/training/dataloader/subproc.py@@ -12,9 +12,10 @@ import queuefrom collections.abc import Iteratorfrom typing import Any-import sentencepieceimport torch.multiprocessing as torch_mp+from pocket_tts.modules.text_conditioner import Tokenizer, encoder_from_serialized+from .loader import DataLoaderfrom .types import Batch@@ -23,13 +24,11 @@ logger = logging.getLogger(__name__)def _feed_queue(q: "multiprocessing.queues.Queue[Batch]", # not subscriptable at runtime on 3.10- sentence_piece_proto: bytes,+ serialized_tokenizer: tuple[str, 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)- loader = DataLoader(tokenize=sentence_piece.encode, **loader_kwargs)+ loader = DataLoader(tokenize=encoder_from_serialized(*serialized_tokenizer), **loader_kwargs)for batch in loader:q.put(batch)@@ -38,7 +37,7 @@ class SubprocessDataLoader:def __init__(self,jsonl: str,- sentence_piece: sentencepiece.SentencePieceProcessor,+ sentence_piece: Tokenizer,batch_size: int,sample_rate: int,frame_rate: float,@@ -77,7 +76,7 @@ class SubprocessDataLoader:}proc = ctx.Process(target=_feed_queue,- args=(self._queue, sentence_piece.serialized_model_proto(), loader_kwargs),+ args=(self._queue, sentence_piece.serialize(), loader_kwargs),daemon=True,name=f"dataloader-{i}",)diff --git a/training/eval/librispeech.py b/training/eval/librispeech.pyindex 3026a6d..ec3b804 100644--- a/training/eval/librispeech.py+++ b/training/eval/librispeech.py@@ -286,7 +286,7 @@ def score_items(except ImportError:pass- sp_encode = model.flow_lm.conditioner.tokenizer.sp.encode+ sp_encode = model.flow_lm.conditioner.tokenizer.encodeif args.match_train_text:def tokenize(text: str) -> list[int]:diff --git a/training/scripts/convert_tokenizer.py b/training/scripts/convert_tokenizer.pynew file mode 100644index 0000000..4755c9f--- /dev/null+++ b/training/scripts/convert_tokenizer.py@@ -0,0 +1,182 @@+"""Convert a SentencePiece .model to the tokenizer.json the configs load.++Handles both model types: unigram maps onto tokenizers.Unigram directly, and+bpe onto tokenizers.BPE, whose merges sentencepiece does not store -- they are+reconstructed by taking every (left, right) whose concatenation is itself a+piece, ordered by the merged piece's score.++The .model's normalizer_spec is reproduced as well. sentencepiece applies it+before segmentation, so a converter that skips it silently changes the ids: the+released tokenizers use `identity`, but a tokenizer trained with sentencepiece's+own defaults NFKC-folds (one half becomes 1/2) and collapses repeated spaces.++Conversion is only useful if it is exact, so this checks every sentence it can+against sentencepiece and exits non-zero on any mismatch.++ python -m training.scripts.convert_tokenizer data/tokenizer.model \+ --out data/tokenizer.json --texts data/valid.jsonl+"""++import json+from pathlib import Path+from typing import Annotated, Any++import sentencepiece as spm+import typer+from tokenizers import AddedToken, Regex, Tokenizer+from tokenizers.decoders import ByteFallback, Fuse+from tokenizers.decoders import Metaspace as MetaspaceDecoder+from tokenizers.decoders import Sequence as DecoderSequence+from tokenizers.models import BPE, Unigram+from tokenizers.normalizers import Precompiled, Prepend, Replace, Strip+from tokenizers.normalizers import Sequence as NormalizerSequence+from tokenizers.pre_tokenizers import Metaspace++app = typer.Typer(pretty_exceptions_show_locals=False)++# The two .model fields this needs live in submessages of ModelProto, and+# sentencepiece's generated protobuf bindings need protobuf installed, which the+# runtime does not otherwise require. Reading the handful of fields directly off+# the wire keeps the script dependency-free; a misread cannot ship silently+# because every conversion is checked against sentencepiece below.+MODEL_TYPES = {1: "UNIGRAM", 2: "BPE", 3: "WORD", 4: "CHAR"}+++def _fields(buf: bytes) -> dict[int, list[Any]]:+ """{field number: values} of one protobuf message, varints and byte strings."""+ out: dict[int, list[Any]] = {}+ i = 0+ while i < len(buf):+ key, i = _varint(buf, i)+ field, wire = key >> 3, key & 7+ if wire == 0:+ value, i = _varint(buf, i)+ elif wire == 2:+ length, i = _varint(buf, i)+ value, i = buf[i : i + length], i + length+ elif wire == 5:+ value, i = buf[i : i + 4], i + 4+ elif wire == 1:+ value, i = buf[i : i + 8], i + 8+ else:+ raise ValueError(f"unsupported wire type {wire}")+ out.setdefault(field, []).append(value)+ return out+++def _varint(buf: bytes, i: int) -> tuple[int, int]:+ value = shift = 0+ while True:+ byte = buf[i]+ i += 1+ value |= (byte & 0x7F) << shift+ if not byte & 0x80:+ return value, i+ shift += 7+++# Whitespace cases first: they exercise add_dummy_prefix and the whitespace rules,+# where the two implementations are easiest to get subtly wrong.+CHECKS = ["", " ", " hello ", " Hello, world!", "Hello, world!", "café", "14½-13½", "日本語", "£"]+++def _merges(vocab: dict[str, int], scores: dict[str, float]) -> list[tuple[str, str]]:+ pieces = set(vocab)+ merges = [+ (scores[piece], piece[:i], piece[i:])+ for piece in vocab+ for i in range(1, len(piece))+ if piece[:i] in pieces and piece[i:] in pieces+ ]+ merges.sort(key=lambda m: m[0], reverse=True)+ return [(left, right) for _, left, right in merges]+++def _normalizer(spec: dict[int, list[Any]]) -> NormalizerSequence:+ """NormalizerSpec: 2 precompiled_charsmap, 3 add_dummy_prefix, 4 remove_extra_whitespaces."""+ charsmap = spec.get(2, [b""])[0]+ add_dummy_prefix = spec.get(3, [1])[0]+ remove_extra_whitespaces = spec.get(4, [1])[0]+ steps: list[Any] = []+ if charsmap:+ steps.append(Precompiled(charsmap))+ if remove_extra_whitespaces:+ steps.append(Replace(Regex(" {2,}"), " "))+ steps.append(Strip())+ if add_dummy_prefix:+ # sentencepiece prepends unconditionally; Metaspace's own prepend_scheme+ # would skip a string that already starts with the marker.+ steps.append(Prepend(prepend="▁"))+ return NormalizerSequence(steps)+++def build(model_path: Path) -> Tokenizer:+ sp = spm.SentencePieceProcessor(model_file=str(model_path))+ pieces = [(sp.id_to_piece(i), sp.get_score(i)) for i in range(sp.get_piece_size())]++ # ModelProto: 2 trainer_spec (3 model_type), 3 normalizer_spec.+ proto = _fields(model_path.read_bytes())+ trainer_spec = _fields(proto[2][0])+ model_type = MODEL_TYPES.get(trainer_spec.get(3, [1])[0], "UNKNOWN")+ if model_type == "UNIGRAM":+ model = Unigram(pieces, unk_id=sp.unk_id(), byte_fallback=True)+ elif model_type == "BPE":+ vocab = {piece: i for i, (piece, _) in enumerate(pieces)}+ model = BPE(+ vocab,+ _merges(vocab, dict(pieces)),+ unk_token=sp.id_to_piece(sp.unk_id()),+ fuse_unk=True,+ byte_fallback=True,+ )+ else:+ raise typer.BadParameter(f"unsupported sentencepiece model type {model_type}")++ tokenizer = Tokenizer(model)+ tokenizer.normalizer = _normalizer(_fields(proto[3][0]))+ tokenizer.pre_tokenizer = Metaspace(prepend_scheme="always")+ tokenizer.decoder = DecoderSequence(+ [MetaspaceDecoder(prepend_scheme="always"), ByteFallback(), Fuse()]+ )+ for i in range(sp.get_piece_size()):+ if sp.is_control(i) or sp.is_unknown(i):+ tokenizer.add_special_tokens([AddedToken(sp.id_to_piece(i), special=True)])+ return tokenizer+++def main(+ model: Annotated[Path, typer.Argument(help="the SentencePiece .model to convert")],+ out: Annotated[+ Path | None, typer.Option(help="default: tokenizer.json beside the model")+ ] = None,+ texts: Annotated[+ Path | None, typer.Option(help="extra sentences to check: a manifest jsonl or one per line")+ ] = None,+) -> None:+ tokenizer = build(model)+ sp = spm.SentencePieceProcessor(model_file=str(model))++ checks = list(CHECKS)+ if texts is not None:+ for line in texts.read_text().splitlines():+ line = line.strip()+ if line.startswith("{"):+ line = json.loads(line).get("transcript", "")+ if line:+ checks.append(line)+ mismatched = [t for t in checks if tokenizer.encode(t).ids != sp.encode(t, out_type=int)]+ if mismatched:+ for text in mismatched[:5]:+ print(f"MISMATCH {text[:60]!r}")+ print(f" json {tokenizer.encode(text).ids[:12]}")+ print(f" spm {sp.encode(text, out_type=int)[:12]}")+ raise SystemExit(f"{len(mismatched)}/{len(checks)} texts tokenize differently; not written")++ out = out or model.with_name("tokenizer.json")+ tokenizer.save(str(out))+ print(f"wrote {out} ({len(checks)} texts match sentencepiece exactly)")+++if __name__ == "__main__":+ app()diff --git a/training/scripts/train_tokenizer.py b/training/scripts/train_tokenizer.pyindex 65fe9b0..1252393 100644--- a/training/scripts/train_tokenizer.py+++ b/training/scripts/train_tokenizer.py@@ -11,6 +11,14 @@ field, e.g. the training manifests) or plain-text files (one utterance perline). Point the model config's lookup_table.tokenizer_path at the produced<prefix>.model to train with it.+The defaults reproduce the spec the released tokenizers were trained with, read+back off one of their .model files: unigram, vocab 4000, character coverage+0.9995, pieces at most 6 characters, digits split, byte fallback, a pad id, and+normalization left off ("identity", no whitespace squashing) so the text reaches+the model as written. sentencepiece's own defaults differ on every one of those,+and the normalization ones change what the tokenizer does to text at inference,+not just how it segments.+Usage:python -m training.scripts.train_tokenizer out/tokenizer \data/train.jsonl [more files ...]@@ -52,9 +60,9 @@ def main(typer.Option(help="the model config's lookup_table.n_bins must be set to this exact value"),] = 4000,character_coverage: Annotated[- 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",+ float, typer.Option(help="raise to 1.0 for a small alphabet to keep every character")+ ] = 0.9995,+ model_type: Annotated[Literal["unigram", "bpe", "char"], typer.Option()] = "unigram",):Path(output_prefix).parent.mkdir(parents=True, exist_ok=True)with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False) as tmp:@@ -70,9 +78,20 @@ def main(vocab_size=vocab_size,character_coverage=character_coverage,model_type=model_type,+ # The rest reproduces the spec the released tokenizers were trained with.+ normalization_rule_name="identity",+ remove_extra_whitespaces=False,+ max_sentencepiece_length=6,+ allow_whitespace_only_pieces=True,+ split_digits=True,+ byte_fallback=True,+ pad_id=3,+ input_sentence_size=10_000_000,+ shuffle_input_sentence=True,)sp = spm.SentencePieceProcessor(model_file=output_prefix + ".model")print(f"wrote {output_prefix}.model (vocab {sp.get_piece_size()})")+ print(f"convert it with: python -m training.scripts.convert_tokenizer {output_prefix}.model")if __name__ == "__main__":diff --git a/training/tests/test_smoke.py b/training/tests/test_smoke.pyindex 7ab9dae..ec62561 100644--- a/training/tests/test_smoke.py+++ b/training/tests/test_smoke.py@@ -14,6 +14,8 @@ import sentencepiece as spmimport torchfrom torch import nn+from training.scripts.convert_tokenizer import MODEL_TYPES, _fields+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))import training.dataloader.audio as td_audio@@ -303,8 +305,12 @@ def test_prefix_prompt(monkeypatch: pytest.MonkeyPatch):def test_train_tokenizer(tmp_path: Path):manifest = tmp_path / "m.jsonl"+ # Unigram, the default, seeds its vocabulary from the substrings it sees, so a+ # corpus of one repeated sentence cannot fill 64 pieces. Vary the words.+ words = [f"{a}{b}{c}" for a in "bcdfgpst" for b in "aeiou" for c in "lmnrs"]lines = [- json.dumps({"transcript": f"hello world number {i} testing tokenizers"}) for i in range(64)+ json.dumps({"transcript": " ".join(words[i % len(words) :][:6] or words[:6])})+ for i in range(64)]manifest.write_text("\n".join(lines))prefix = tmp_path / "tok"@@ -316,12 +322,12 @@ def test_train_tokenizer(tmp_path: Path):str(prefix),str(manifest),"--vocab-size",- "64",+ "320",],check=True,)sp = spm.SentencePieceProcessor(model_file=str(prefix) + ".model")- assert sp.get_piece_size() == 64+ assert sp.get_piece_size() == 320assert sp.encode("hello world") != []@@ -348,3 +354,37 @@ def test_grad_accum_matches_big_batch():(loss_of(xs[half], ys[half]) / 2).backward()for g, p in zip(big, net.parameters(), strict=True):assert torch.allclose(g, grad_of(p), atol=1e-6)+++def test_train_tokenizer_matches_the_released_spec(tmp_path: Path):+ """A tokenizer trained by the script carries the spec the released ones have."""+ manifest = tmp_path / "m.jsonl"+ words = [f"{a}{b}{c}" for a in "bcdfgpst" for b in "aeiou" for c in "lmnrs"]+ manifest.write_text(+ "\n".join(+ json.dumps({"transcript": " ".join(words[i % len(words) :][:6])}) for i in range(64)+ )+ )+ prefix = tmp_path / "tok"+ subprocess.run(+ [+ sys.executable,+ "-m",+ "training.scripts.train_tokenizer",+ str(prefix),+ str(manifest),+ "--vocab-size",+ "320",+ ],+ check=True,+ )+ spec = _fields((prefix.with_suffix(".model")).read_bytes())+ trainer, normalizer = _fields(spec[2][0]), _fields(spec[3][0])+ assert MODEL_TYPES[trainer.get(3, [1])[0]] == "UNIGRAM"+ assert trainer[20][0] == 6 # max_sentencepiece_length+ assert trainer[25][0] == 1 # split_digits+ assert trainer[26][0] == 1 # allow_whitespace_only_pieces+ assert trainer[35][0] == 1 # byte_fallback+ assert trainer[43][0] == 3 # pad_id+ assert normalizer.get(4, [1])[0] == 0 # remove_extra_whitespaces off+ assert not normalizer.get(2, [b""])[0] # identity: no precompiled charsmapdiff --git a/training/train.py b/training/train.pyindex 60e054a..313bf6a 100644--- a/training/train.py+++ b/training/train.py@@ -168,7 +168,7 @@ def main(config_path: str):optimizer, ema, device, rank = run.optimizer, run.ema, run.device, run.rankprogress, start_step = run.progress, run.start_step- sentence_piece = model.flow_lm.conditioner.tokenizer.sp+ sentence_piece = model.flow_lm.conditioner.tokenizertokenize = sentence_piece.encodetrain_loader = iter(SubprocessDataLoader(@@ -324,7 +324,7 @@ def validate(step: int,) -> dict[str, float]:model.eval()- tokenize = model.flow_lm.conditioner.tokenizer.sp.encode+ tokenize = model.flow_lm.conditioner.tokenizer.encodeloader = iter(DataLoader(args.data.valid_jsonl,diff --git a/uv.lock b/uv.lockindex bde5861..e9f570b 100644--- a/uv.lock+++ b/uv.lock@@ -1483,6 +1483,7 @@ dependencies = [{ name = "scipy", version = "1.17.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" },{ name = "scipy", version = "1.18.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" },{ name = "sentencepiece" },+ { name = "tokenizers" },{ name = "torch" },{ name = "typer" },{ name = "typing-extensions" },@@ -1531,6 +1532,7 @@ requires-dist = [{ name = "safetensors", specifier = ">=0.4.0" },{ name = "scipy", specifier = ">=1.5.0" },{ name = "sentencepiece", specifier = ">=0.2.1" },+ { name = "tokenizers", specifier = ">=0.21" },{ name = "soundfile", marker = "extra == 'audio'", specifier = ">=0.12.0" },{ name = "torch", specifier = ">=2.5.0" },{ name = "torchao", marker = "extra == 'quantize'", specifier = ">=0.16.0" },