A TTS that fits in your CPU (and pocket)
Python
Optionally generate each chunk of a long text as a continuation of the previous one (#401)
manu-lm2dae420ca04c
diff --git a/docs/API Reference/python-api.md b/docs/API Reference/python-api.mdindex ca44f84..bb36d80 100644--- a/docs/API Reference/python-api.md+++ b/docs/API Reference/python-api.md@@ -125,15 +125,17 @@ voice_state = model.get_state_for_audio_prompt()```-##### `generate_audio(model_state, text_to_generate, frames_after_eos=None, copy_state=True)`+##### `generate_audio(model_state, text_to_generate, max_tokens=None, frames_after_eos=None, copy_state=True, teacher_force_previous_chunk=False)`Generate complete audio tensor from text input.**Parameters:**- `model_state` (dict): Model state from `get_state_for_audio_prompt()`- `text_to_generate` (str): Text to convert to speech+- `max_tokens` (int | None): Long texts are generated in chunks of at most this many tokens (default: None, which means 50, or 25 with `teacher_force_previous_chunk`)- `frames_after_eos` (int | None): Frames to generate after EOS detection (default: None)- `copy_state` (bool): Whether to copy the state (default: True)+- `teacher_force_previous_chunk` (bool): Generate each chunk after the first as the continuation of the previous one: the text of both chunks is given and the previous chunk's generated audio latents are teacher-forced before the new frames are generated. By default every chunk starts afresh from the voice prompt. Slightly slower (one prefill of the previous chunk per chunk). Forces `copy_state=True` (default: False)**Returns:**- `torch.Tensor`: Audio 1D tensor with shape [samples]@@ -153,7 +155,7 @@ print(f"Generated audio shape: {audio.shape}")print(f"Audio duration: {audio.shape[-1] / model.sample_rate:.2f} seconds")```-##### `generate_audio_stream(model_state, text_to_generate, frames_after_eos=None, copy_state=True)`+##### `generate_audio_stream(model_state, text_to_generate, max_tokens=None, frames_after_eos=None, copy_state=True, stop=None, teacher_force_previous_chunk=False)`Generate audio streaming chunks from text input.diff --git a/docs/CLI Commands/generate.md b/docs/CLI Commands/generate.mdindex 888c41d..8e5284b 100644--- a/docs/CLI Commands/generate.md+++ b/docs/CLI Commands/generate.md@@ -29,6 +29,8 @@ This will generate a WAV file `./tts_output.wav` with the default text and voice- `--noise-clamp NOISE_CLAMP`: Noise clamp value (default: None)- `--eos-threshold EOS_THRESHOLD`: EOS threshold (default: -4.0)- `--frames-after-eos FRAMES_AFTER_EOS`: Number of frames to generate after EOS (default: None, auto-calculated based on the text length). Each frame is 80ms.+- `--max-tokens MAX_TOKENS`: Long texts are generated in chunks of at most this many tokens (default: 50, or 25 with `--teacher-force-previous-chunk`)+- `--teacher-force-previous-chunk`: Generate each chunk of a long text as the continuation of the previous one (the previous chunk's audio latents are teacher-forced, with the text of both chunks) instead of starting afresh from the voice prompt (default: False). Slightly slower.### Performance Optionsdiff --git a/pocket_tts/default_parameters.py b/pocket_tts/default_parameters.pyindex b15599d..3b1eb48 100644--- a/pocket_tts/default_parameters.py+++ b/pocket_tts/default_parameters.py@@ -8,6 +8,8 @@ DEFAULT_EOS_THRESHOLD = -4.0DEFAULT_FRAMES_AFTER_EOS = None# TODO: make this dynamic since english_2026-04 supports bigger chunksMAX_TOKEN_PER_CHUNK = 50+# With teacher_force_previous_chunk, the text of two chunks is fed at once.+MAX_TOKEN_PER_CHUNK_TEACHER_FORCED = 25DEFAULT_TEXT_FOR_LANGUAGE = {"english": (diff --git a/pocket_tts/main.py b/pocket_tts/main.pyindex 86a90e4..682e725 100644--- a/pocket_tts/main.py+++ b/pocket_tts/main.py@@ -21,6 +21,7 @@ from pocket_tts.default_parameters import (DEFAULT_NOISE_CLAMP,DEFAULT_SAMPLER_DECODE_STEPS,MAX_TOKEN_PER_CHUNK,+ MAX_TOKEN_PER_CHUNK_TEACHER_FORCED,get_default_text_for_language,get_default_voice_for_language,)@@ -330,8 +331,19 @@ def generate(] = "./tts_output.wav",device: Annotated[str, typer.Option(help="Device to use")] = "cpu",max_tokens: Annotated[- int, typer.Option(help="Maximum number of tokens per chunk.")- ] = MAX_TOKEN_PER_CHUNK,+ int | None,+ typer.Option(+ help=f"Maximum number of tokens per chunk. Defaults to {MAX_TOKEN_PER_CHUNK}, "+ f"or {MAX_TOKEN_PER_CHUNK_TEACHER_FORCED} with --teacher-force-previous-chunk."+ ),+ ] = None,+ teacher_force_previous_chunk: Annotated[+ bool,+ typer.Option(+ help="Generate each chunk of a long text as the continuation of the previous one "+ "(its audio teacher-forced) instead of starting afresh from the voice prompt."+ ),+ ] = False,quantize: Annotated[bool, typer.Option(help="Apply int8 quantization to reduce memory usage")] = False,@@ -372,6 +384,7 @@ def generate(text_to_generate=text,frames_after_eos=frames_after_eos,max_tokens=max_tokens,+ teacher_force_previous_chunk=teacher_force_previous_chunk,)stream_audio_chunks(output_path, audio_chunks, tts_model.config.mimi.sample_rate)diff --git a/pocket_tts/models/tts_model.py b/pocket_tts/models/tts_model.pyindex 5f478bd..7e188b6 100644--- a/pocket_tts/models/tts_model.py+++ b/pocket_tts/models/tts_model.py@@ -26,6 +26,7 @@ from pocket_tts.default_parameters import (DEFAULT_NOISE_CLAMP,DEFAULT_SAMPLER_DECODE_STEPS,MAX_TOKEN_PER_CHUNK,+ MAX_TOKEN_PER_CHUNK_TEACHER_FORCED,)from pocket_tts.models.flow_lm import FlowLMModelfrom pocket_tts.models.mimi import build_mimi@@ -86,6 +87,9 @@ class TTSModel(nn.Module):# EOS is ignored on the first frames: before speech starts, the EOS logit of some voices can# cross the threshold, and a short text then ends before the word is spoken._MIN_FRAMES_BEFORE_EOS = 6+ # teacher_force_previous_chunk: the Mimi decoder of a chunk first runs over the last forced+ # frames (about 1 s), so that its audio follows on from the previous chunk's.+ _DECODER_WARMUP_FRAMES = 12def __init__(self,@@ -513,6 +517,7 @@ class TTSModel(nn.Module):result_queue: ResultQueue,mimi_sequence_length: int,mimi_steps_per_latent: int,+ warmup_latents: torch.Tensor | None = None,):"""Worker thread function for decoding audio latents from queue with immediate streaming."""try:@@ -522,6 +527,16 @@ class TTSModel(nn.Module):# as a click at the start of every chunk: fade the first 5 ms in. (The longer burst some# voices produced came from prompts ending on speech, handled by end_on_pause.)fade_in: torch.Tensor | None = torch.linspace(0, 1, self.config.mimi.sample_rate // 200)+ if warmup_latents is not None:+ # Continuation of the previous chunk: run the decoder over its last frames (audio+ # dropped) so the new chunk's audio follows on without a fresh-state transient.+ self.mimi.decode_from_latent(+ warmup_latents * self.flow_lm.emb_std + self.flow_lm.emb_mean, mimi_state+ )+ increment_steps(+ self.mimi, mimi_state, increment=mimi_steps_per_latent * warmup_latents.shape[1]+ )+ fade_in = Nonewhile True:latent = latents_queue.get()if latent is None:@@ -583,9 +598,10 @@ class TTSModel(nn.Module):self,model_state: ModelState,text_to_generate: str,- max_tokens: int = MAX_TOKEN_PER_CHUNK,+ max_tokens: int | None = None,frames_after_eos: int | None = None,copy_state: bool = True,+ teacher_force_previous_chunk: bool = False,) -> torch.Tensor:"""Generate complete audio tensor from text input.@@ -609,6 +625,14 @@ class TTSModel(nn.Module):copy_state: Whether to create a deep copy of the model state beforegeneration. If True, preserves the original state for reuse.If False, modifies the input state in-place. Defaults to True.+ max_tokens: Long texts are generated in chunks of at most this many tokens.+ Defaults to 50, or 25 with `teacher_force_previous_chunk`.+ teacher_force_previous_chunk: When True, each chunk after the first is generated+ from the voice prompt with the text of the previous chunk and of this one, the+ previous chunk's generated latents being teacher-forced as the first frames, so+ that the new chunk continues the previous one instead of starting afresh. Costs+ one prefill of the previous chunk's frames and text per chunk. Forces+ `copy_state=True`. Defaults to False.Returns:torch.Tensor: Generated audio tensor with shape [channels, samples]@@ -642,6 +666,7 @@ class TTSModel(nn.Module):frames_after_eos=frames_after_eos,copy_state=copy_state,max_tokens=max_tokens,+ teacher_force_previous_chunk=teacher_force_previous_chunk,):audio_chunks.append(chunk)return torch.cat(audio_chunks, dim=0)@@ -651,10 +676,11 @@ class TTSModel(nn.Module):self,model_state: ModelState,text_to_generate: str,- max_tokens: int = MAX_TOKEN_PER_CHUNK,+ max_tokens: int | None = None,frames_after_eos: int | None = None,copy_state: bool = True,stop: threading.Event | None = None,+ teacher_force_previous_chunk: bool = False,) -> Iterator[torch.Tensor]:"""Generate audio streaming chunks from text input.@@ -677,6 +703,14 @@ class TTSModel(nn.Module):copy_state: Whether to create a deep copy of the model state beforegeneration. If True, preserves the original state for reuse.If False, modifies the input state in-place. Defaults to True.+ max_tokens: Long texts are generated in chunks of at most this many tokens.+ Defaults to 50, or 25 with `teacher_force_previous_chunk`.+ teacher_force_previous_chunk: When True, each chunk after the first is generated+ from the voice prompt with the text of the previous chunk and of this one, the+ previous chunk's generated latents being teacher-forced as the first frames, so+ that the new chunk continues the previous one instead of starting afresh. Costs+ one prefill of the previous chunk's frames and text per chunk. Forces+ `copy_state=True`. Defaults to False.stop: Optional event for cancelling the generation, for instancewhen the user interrupts the playback. Once set, no new framesare generated and the stream ends early.@@ -714,10 +748,14 @@ class TTSModel(nn.Module):if stop is None:stop = threading.Event()- # This is a very simplistic way of handling long texts. We could do much better- # by using teacher forcing, but it would be a bit slower.- # TODO: add the teacher forcing method for long texts where we use the audio of one chunk- # as conditioning for the next chunk.+ if max_tokens is None:+ max_tokens = (+ MAX_TOKEN_PER_CHUNK_TEACHER_FORCED+ if teacher_force_previous_chunk+ else MAX_TOKEN_PER_CHUNK+ )+ # Long texts are generated chunk by chunk. By default every chunk starts afresh from the+ # voice prompt; with teacher_force_previous_chunk it continues the previous one.chunks = split_into_best_sentences(self.flow_lm.conditioner.tokenizer,text_to_generate,@@ -729,10 +767,26 @@ class TTSModel(nn.Module):replace_characters=self.replace_characters,)+ prev_chunk: str | None = None+ prev_latents: list[torch.Tensor] = []for chunk in chunks:if stop.is_set():break- text_to_generate, frames_after_eos_guess = prepare_text_prompt(+ forced, text_chunk = None, chunk+ if teacher_force_previous_chunk and prev_latents:+ forced = torch.cat(prev_latents, dim=1)+ text_chunk = f"{prev_chunk} {chunk}"+ prev_chunk, prev_latents = chunk, []+ text_to_generate, _ = prepare_text_prompt(+ text_chunk,+ self.pad_with_spaces_for_short_inputs,+ self.remove_semicolons,+ self.append_terminal_punctuation,+ self.capitalize_first_letter,+ self.replace_characters,+ )+ # The EOS delay depends on the new chunk only.+ _, frames_after_eos_guess = prepare_text_prompt(chunk,self.pad_with_spaces_for_short_inputs,self.remove_semicolons,@@ -748,8 +802,10 @@ class TTSModel(nn.Module):model_state=model_state,text_to_generate=text_to_generate,frames_after_eos=effective_frames,- copy_state=copy_state,+ copy_state=copy_state or teacher_force_previous_chunk,stop=stop,+ latents_out=prev_latents if teacher_force_previous_chunk else None,+ forced_latents=forced,)@torch.no_grad@@ -760,15 +816,22 @@ class TTSModel(nn.Module):frames_after_eos: int,copy_state: bool,stop: threading.Event,+ latents_out: list[torch.Tensor] | None = None,+ forced_latents: torch.Tensor | None = None,) -> Iterator[torch.Tensor]:if copy_state:model_state = copy.deepcopy(model_state)prepared = self.flow_lm.conditioner.prepare(text_to_generate)token_count = prepared.shape[1]+ # With forced frames the text also holds the previous chunk's: a looser upper bound.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+ warmup = None+ if forced_latents is not None:+ warmup = forced_latents[:, -self._DECODER_WARMUP_FRAMES :]+ n_warmup = 0 if warmup is None else warmup.shape[1]+ mimi_sequence_length = (max_gen_len + n_warmup) * mimi_steps_per_latent# Set up multithreaded generation and decodinglatents_queue: LatentQueue = queue.Queue()@@ -777,7 +840,7 @@ class TTSModel(nn.Module):# Start decoder worker threaddecoder_thread = threading.Thread(target=self._decode_audio_worker,- args=(latents_queue, result_queue, mimi_sequence_length, mimi_steps_per_latent),+ args=(latents_queue, result_queue, mimi_sequence_length, mimi_steps_per_latent, warmup),daemon=True,)logger.info("starting timer now!")@@ -793,6 +856,8 @@ class TTSModel(nn.Module):latents_queue=latents_queue,result_queue=result_queue,stop=stop,+ latents_out=latents_out,+ forced_latents=forced_latents,)# Stream audio chunks as they become available@@ -842,19 +907,41 @@ class TTSModel(nn.Module):latents_queue: LatentQueue,result_queue: ResultQueue,stop: threading.Event,+ latents_out: list[torch.Tensor] | None = None,+ forced_latents: torch.Tensor | None = None,):token_count = prepared.shape[1]+ n_forced = 0 if forced_latents is None else forced_latents.shape[1]current_end = self._flow_lm_current_end(model_state)- required_len = current_end + token_count + max_gen_len+ required_len = current_end + token_count + n_forced + max_gen_lenself._expand_kv_cache(model_state, sequence_length=required_len)+ first_input = Nonewith display_execution_time("Prompting text"):- self._run_flow_lm_and_increment_step(model_state=model_state, text_tokens=prepared)+ if forced_latents is None or n_forced == 0:+ self._run_flow_lm_and_increment_step(model_state=model_state, text_tokens=prepared)+ else:+ # Teacher forcing: BOS then every forced frame but the last, which is the input+ # of the first generated step. The outputs of this prefill, EOS included, are+ # discarded: EOS can only fire on new frames.+ bos = torch.full_like(forced_latents[:, :1], float("NaN"))+ self._run_flow_lm_and_increment_step(+ model_state=model_state,+ text_tokens=prepared,+ backbone_input_latents=torch.cat([bos, forced_latents[:, :-1]], dim=1),+ )+ first_input = forced_latents[:, -1:]def run_generation():try:self._autoregressive_generation(- model_state, max_gen_len, frames_after_eos, latents_queue, stop+ model_state,+ max_gen_len,+ frames_after_eos,+ latents_queue,+ stop,+ latents_out,+ first_input,)except Exception as e:logger.error(f"Error in autoregressive generation: {e}")@@ -877,13 +964,17 @@ class TTSModel(nn.Module):frames_after_eos: int,latents_queue: LatentQueue,stop: threading.Event,+ latents_out: list[torch.Tensor] | None = None,+ first_input: torch.Tensor | None = None,):- backbone_input = torch.full(- (1, 1, self.flow_lm.ldim),- fill_value=float("NaN"),- device=next(iter(self.flow_lm.parameters())).device,- dtype=self.flow_lm.dtype,- )+ backbone_input = first_input+ if backbone_input is None:+ backbone_input = torch.full(+ (1, 1, self.flow_lm.ldim),+ fill_value=float("NaN"),+ device=next(iter(self.flow_lm.parameters())).device,+ dtype=self.flow_lm.dtype,+ )steps_times = []eos_step = Nonefor generation_step in range(max_gen_len):@@ -903,6 +994,8 @@ class TTSModel(nn.Module):break# Add generated latent to queue for immediate decoding+ if latents_out is not None:+ latents_out.append(next_latent)latents_queue.put(next_latent)backbone_input = next_latentassert timer.elapsed_time_ms is not Nonediff --git a/tests/test_teacher_force_previous_chunk.py b/tests/test_teacher_force_previous_chunk.pynew file mode 100644index 0000000..13b70d3--- /dev/null+++ b/tests/test_teacher_force_previous_chunk.py@@ -0,0 +1,83 @@+"""Tests for teacher_force_previous_chunk (long texts generated as continuations)."""++from typing import Any++import pytest+import torch++from pocket_tts import TTSModel+from pocket_tts.models.text_chunking import split_into_best_sentences++# Four sentences: several chunks at 25 tokens, two at the default 50.+TEXT = (+ "The old lighthouse keeper climbed the stairs every evening. "+ "He lit the lamp and watched the ships pass by in the dark. "+ "In the morning, he wrote everything down in a small notebook. "+ "Years later, his granddaughter found it in a box under the bed."+)++[email protected](scope="module")+def model() -> TTSModel:+ return TTSModel.load_model()+++def _chunks(model: TTSModel, max_tokens: int) -> list[str]:+ return split_into_best_sentences(+ model.flow_lm.conditioner.tokenizer,+ TEXT,+ max_tokens,+ model.pad_with_spaces_for_short_inputs,+ remove_semicolons=model.remove_semicolons,+ append_terminal_punctuation=model.append_terminal_punctuation,+ capitalize_first_letter=model.capitalize_first_letter,+ replace_characters=model.replace_characters,+ )+++def test_flag_off_generates_every_chunk_afresh_from_the_voice(model: TTSModel):+ voice_state = model.get_state_for_audio_prompt("alba")+ chunks = _chunks(model, 50)+ assert len(chunks) > 1++ torch.manual_seed(0)+ audio = model.generate_audio(voice_state, TEXT, teacher_force_previous_chunk=False)+ torch.manual_seed(0)+ separate = [model.generate_audio(voice_state, chunk) for chunk in chunks]++ assert torch.equal(audio, torch.cat(separate))+++def test_flag_on_continues_the_previous_chunk(model: TTSModel, monkeypatch: pytest.MonkeyPatch):+ voice_state = model.get_state_for_audio_prompt("alba")+ chunks = _chunks(model, 25)+ assert len(chunks) > 2++ calls: list[dict[str, Any]] = []+ original = model._generate_audio_stream_short_text++ def record(**kwargs: Any): # noqa: ANN401 -- passthrough to the wrapped method+ call = {"kwargs": kwargs, "samples": 0}+ calls.append(call)+ for audio in original(**kwargs):+ call["samples"] += audio.shape[-1]+ yield audio++ monkeypatch.setattr(model, "_generate_audio_stream_short_text", record)+ torch.manual_seed(0)+ audio = model.generate_audio(voice_state, TEXT, teacher_force_previous_chunk=True)++ assert len(calls) == len(chunks) # max_tokens defaults to 25+ assert calls[0]["kwargs"]["forced_latents"] is None+ for prev, call, chunk in zip(calls[:-1], calls[1:], chunks[1:], strict=True):+ forced = call["kwargs"]["forced_latents"]+ # The forced prefix is exactly what the previous chunk generated (and played)...+ assert torch.equal(forced, torch.cat(prev["kwargs"]["latents_out"], dim=1))+ assert prev["samples"] == forced.shape[1] * model.mimi.frame_size+ # ...with the text of both chunks.+ assert chunk.strip(" .").lower() in call["kwargs"]["text_to_generate"].lower()+ # EOS is not taken from the forced frames: the new words get audio of their own.+ assert call["samples"] >= 0.1 * len(chunk.split()) * model.sample_rate++ seconds = audio.shape[-1] / model.sample_rate+ assert 0.2 * len(TEXT.split()) <= seconds <= 0.8 * len(TEXT.split())