A TTS that fits in your CPU (and pocket)
Python
Split the dataloader into a package (#286)
manu-lm1bb4ee25f0ca
diff --git a/training/dataloader/__init__.py b/training/dataloader/__init__.pynew file mode 100644index 0000000..1875e88--- /dev/null+++ b/training/dataloader/__init__.py@@ -0,0 +1,20 @@+"""Data loading: manifest access, sampling, batching, subprocess feeding."""++from training.dataloader.audio import _load_window+from training.dataloader.encode import encode_batch+from training.dataloader.loader import DataLoader, _prefetch+from training.dataloader.manifest import LazyEntries, load_entries+from training.dataloader.subproc import SubprocessDataLoader+from training.dataloader.types import Batch, Entry++__all__ = [+ "Batch",+ "DataLoader",+ "Entry",+ "LazyEntries",+ "SubprocessDataLoader",+ "_load_window",+ "_prefetch",+ "encode_batch",+ "load_entries",+]diff --git a/training/dataloader/audio.py b/training/dataloader/audio.pynew file mode 100644index 0000000..6c2d41c--- /dev/null+++ b/training/dataloader/audio.py@@ -0,0 +1,29 @@+"""Data loading: jsonl manifests of single utterances (moshi-finetune style).++Each line is {"path": ..., "duration": ..., "transcript": ...}. One sample =+one utterance (cropped to max_duration_sec) + its transcript tokens + a voice+prompt (a random window elsewhere in the same file). Lines are sharded across+ranks by line index.+"""++import logging++import numpy as np+import numpy.typing as npt+import sphn+import torch++from pocket_tts.data.audio_utils import convert_audio++logger = logging.getLogger(__name__)+++def _load_window(+ path: str, start_sec: float, duration_sec: float, sample_rate: int+) -> npt.NDArray[np.float32]:+ wav, sr = sphn.read(path, start_sec=start_sec, duration_sec=duration_sec)+ wav = wav.mean(axis=0) # mono+ if sr != sample_rate:+ resampled = convert_audio(torch.from_numpy(wav)[None], int(sr), int(sample_rate), 1)+ wav = resampled[0].numpy()+ return wavdiff --git a/training/dataloader/encode.py b/training/dataloader/encode.pynew file mode 100644index 0000000..d18e94e--- /dev/null+++ b/training/dataloader/encode.py@@ -0,0 +1,45 @@+"""Data loading: jsonl manifests of single utterances (moshi-finetune style).++Each line is {"path": ..., "duration": ..., "transcript": ...}. One sample =+one utterance (cropped to max_duration_sec) + its transcript tokens + a voice+prompt (a random window elsewhere in the same file). Lines are sharded across+ranks by line index.+"""++import logging++import torch++from pocket_tts.models.mimi import MimiModel++from .types import Batch++logger = logging.getLogger(__name__)++[email protected]_grad()+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]+ )+ return latents.float(), mask, voice_prompt_latents.float(), num_voice_prompt_frames+ audio = batch.audio.to(device)+ latents = mimi.encode_to_latent(audio) # [B, T, C]+ 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]+ voice_prompt_latents = mimi.encode_to_latent(batch.voice_audio.to(device))+ num_voice_prompt_frames = batch.num_voice_prompt_frames.to(device).clamp(+ max=voice_prompt_latents.shape[1]+ )+ return latents.float(), mask, voice_prompt_latents.float(), num_voice_prompt_framesdiff --git a/training/dataloader.py b/training/dataloader/loader.pysimilarity index 63%rename from training/dataloader.pyrename to training/dataloader/loader.pyindex 9e09de4..505209c 100644--- a/training/dataloader.py+++ b/training/dataloader/loader.py@@ -8,134 +8,41 @@ ranks by line index.import jsonimport logging-import multiprocessing.queues-import osimport queueimport randomimport threadingfrom collections.abc import Callable, Iteratorfrom concurrent.futures import ThreadPoolExecutor-from dataclasses import dataclassfrom pathlib import Pathfrom typing import Anyimport numpy as npimport numpy.typing as npt-import sentencepiece-import sphnimport torch-import torch.multiprocessing as torch_mpfrom safetensors import safe_open-from pocket_tts.data.audio_utils import convert_audio-from pocket_tts.models.mimi import MimiModel+from . import audio+from .manifest import load_entries+from .types import Batch, Entrylogger = logging.getLogger(__name__)-@dataclass-class Entry:- path: str- duration: float- transcript: str- words: list[dict[str, Any]] | None = None # [{"word", "start", "end"}] from align_data- start: float = 0.0 # offset of the utterance inside the audio file (long recordings)- latents_file: str | None = None---@dataclass-class Batch:- audio: torch.Tensor # [B, 1, samples], zero-padded- num_audio_frames: torch.Tensor # [B] valid codec frames per sample- text_tokens: list[torch.Tensor] # ragged, one [L_b] long tensor per sample- voice_audio: torch.Tensor # [B, 1, prompt_samples]- num_voice_prompt_frames: torch.Tensor # [B] valid codec frames of each voice prompt- tail_latents: torch.Tensor | None = None- prompt_latents: torch.Tensor | None = None---class LazyEntries:- """This rank's stride of manifest lines, read on demand via an offset index.-- Large manifests (tens of GB) would otherwise be held as per-process string- lists by every loader subprocess. The index is a uint64 array of line-start- offsets cached next to the manifest; the lines themselves stay on disk and- are served through the (shared, reclaimable) page cache.- """-- def __init__(self, path: str, rank: int, world_size: int) -> None:- self._path = Path(path)- self._rank = rank- self._world = world_size- self._offsets = None- self._file = None- self._ensure_index()-- def _index_path(self) -> Path:- return self._path.with_name(self._path.name + ".idx")-- def _ensure_index(self) -> None:- idx = self._index_path()- src = self._path.stat()- if idx.exists():- meta = idx.stat()- if meta.st_mtime >= src.st_mtime and meta.st_size > 8:- return- offsets = [0]- with self._path.open("rb") as f:- for line in f:- offsets.append(offsets[-1] + len(line))- arr = np.asarray(offsets, dtype=np.uint64)- tmp = idx.with_name(idx.name + f".tmp.{os.getpid()}")- arr.tofile(tmp)- os.replace(tmp, idx) # concurrent builders write identical content- logger.info(f"indexed {len(arr) - 1} lines of {self._path.name}")-- def _load(self) -> None:- all_offsets = np.fromfile(self._index_path(), dtype=np.uint64)- starts, ends = all_offsets[:-1], all_offsets[1:]- self._starts = starts[self._rank :: self._world]- self._ends = ends[self._rank :: self._world]- self._offsets = True-- def __len__(self) -> int:- if self._offsets is None:- self._load()- return len(self._starts)-- def __getitem__(self, i: int) -> str:- if self._offsets is None:- self._load()- if self._file is None:- self._file = self._path.open("rb")- self._file.seek(int(self._starts[i]))- return self._file.read(int(self._ends[i] - self._starts[i])).decode()-- def __getstate__(self) -> dict[str, object]:- return {"_path": self._path, "_rank": self._rank, "_world": self._world}-- def __setstate__(self, state: dict[str, object]) -> None:- self.__dict__.update(state)- self._offsets = None- self._file = None---def load_entries(path: str, rank: int, world_size: int) -> LazyEntries:- entries = LazyEntries(path, rank, world_size)- logger.info(f"indexed {len(entries)} entries from {path} (rank {rank}/{world_size})")- assert len(entries), f"no entries for rank {rank} in {path}"- return entries+def _prefetch(iterator: Iterator[Batch], depth: int = 4) -> Iterator[Batch]:+ """Run the (synchronous, IO-bound) loader in a background thread."""+ q: queue.Queue[Batch | None] = queue.Queue(maxsize=depth)+ def worker():+ for item in iterator:+ q.put(item)+ q.put(None)-def _load_window(- path: str, start_sec: float, duration_sec: float, sample_rate: int-) -> npt.NDArray[np.float32]:- wav, sr = sphn.read(path, start_sec=start_sec, duration_sec=duration_sec)- wav = wav.mean(axis=0) # mono- if sr != sample_rate:- resampled = convert_audio(torch.from_numpy(wav)[None], int(sr), int(sample_rate), 1)- wav = resampled[0].numpy()- return wav+ threading.Thread(target=worker, daemon=True).start()+ while True:+ item = q.get()+ if item is None:+ return+ yield itemclass DataLoader:@@ -247,7 +154,7 @@ class DataLoader:last = self._last_word_end(entry)if last is not None and last > cut:end = min(entry.duration, last + self.TRAIL_SEC)- wav = _load_window(+ wav = audio._load_window(entry.path,entry.start + cut,min(end - cut, self.max_duration_sec),@@ -256,19 +163,21 @@ class DataLoader:# The prompt is everything from the utterance start to the# cut (bounded by the window via cut selection).prompt, length = self._cap_prompt(- _load_window(entry.path, entry.start, cut, self.sample_rate)+ audio._load_window(entry.path, entry.start, cut, self.sample_rate))return wav, tokens, prompt, lengthlast = self._last_word_end(entry)end = min(entry.duration, last + self.TRAIL_SEC) if last is not None else entry.durationduration = min(end, self.max_duration_sec)- wav = _load_window(entry.path, entry.start, duration, self.sample_rate)+ wav = audio._load_window(entry.path, entry.start, duration, self.sample_rate)tokens = torch.tensor(self.tokenize(entry.transcript), dtype=torch.long)# No alignment: voice prompt from a random window of the same file.fallback_sec = self.max_voice_prompt_sec if self.max_voice_prompt_sec > 0 else 3.0prompt_start = self.rng.uniform(0, max(0.0, entry.duration - fallback_sec))prompt, length = self._cap_prompt(- _load_window(entry.path, entry.start + prompt_start, fallback_sec, self.sample_rate)+ audio._load_window(+ entry.path, entry.start + prompt_start, fallback_sec, self.sample_rate+ ))return wav, tokens, prompt, length@@ -315,7 +224,7 @@ class DataLoader:tokens = torch.tensor(self.tokenize(text), dtype=torch.long)target_frames = self._latent_target_frames(entry, cut_frames, lat.shape[0])stitch_frames = min(self.stitch_frames, target_frames)- stitch = _load_window(+ stitch = audio._load_window(entry.path,entry.start + cut_frames / self.frame_rate,stitch_frames / self.frame_rate,@@ -433,127 +342,3 @@ class DataLoader:f"no readable samples in {self.jsonl}: every entry failed to load "f"({self._failures} failures). Check the paths in the manifest.")---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)- loader = DataLoader(tokenize=sentence_piece.encode, **loader_kwargs)- for batch in loader:- q.put(batch)---class SubprocessDataLoader:- def __init__(- self,- jsonl: str,- sentence_piece: sentencepiece.SentencePieceProcessor,- batch_size: int,- sample_rate: int,- frame_rate: float,- max_duration_sec: float,- max_voice_prompt_sec: float,- rank: int,- world_size: int,- seed: int = 0,- shuffle: bool = True,- io_workers: int = 16,- num_procs: int = 3,- depth: int = 8,- ):- ctx = torch_mp.get_context("spawn")- self._queue = ctx.Queue(maxsize=depth)- self._procs = []- for i in range(num_procs):- loader_kwargs = {- "jsonl": jsonl,- "batch_size": batch_size,- "sample_rate": sample_rate,- "frame_rate": frame_rate,- "max_duration_sec": max_duration_sec,- "max_voice_prompt_sec": max_voice_prompt_sec,- "rank": rank * num_procs + i,- "world_size": world_size * num_procs,- "seed": seed + rank * num_procs + i,- "shuffle": shuffle,- "io_workers": io_workers,- }- proc = ctx.Process(- target=_feed_queue,- args=(self._queue, sentence_piece.serialized_model_proto(), loader_kwargs),- daemon=True,- name=f"dataloader-{i}",- )- proc.start()- self._procs.append(proc)-- def _check_procs(self):- dead = [p for p in self._procs if not p.is_alive()]- if dead:- raise RuntimeError(- f"dataloader subprocess(es) died (exit codes "- f"{[p.exitcode for p in dead]}), check their tracebacks above"- )-- def __iter__(self) -> Iterator[Batch]:- batches = 0- while True:- try:- batch = self._queue.get(timeout=60)- except queue.Empty:- self._check_procs()- continue- batches += 1- if batches % 100 == 0:- self._check_procs()- yield batch---def _prefetch(iterator: Iterator[Batch], depth: int = 4) -> Iterator[Batch]:- """Run the (synchronous, IO-bound) loader in a background thread."""- q: queue.Queue[Batch | None] = queue.Queue(maxsize=depth)-- def worker():- for item in iterator:- q.put(item)- q.put(None)-- threading.Thread(target=worker, daemon=True).start()- while True:- item = q.get()- if item is None:- return- yield item--[email protected]_grad()-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]- )- return latents.float(), mask, voice_prompt_latents.float(), num_voice_prompt_frames- audio = batch.audio.to(device)- latents = mimi.encode_to_latent(audio) # [B, T, C]- 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]- voice_prompt_latents = mimi.encode_to_latent(batch.voice_audio.to(device))- num_voice_prompt_frames = batch.num_voice_prompt_frames.to(device).clamp(- max=voice_prompt_latents.shape[1]- )- return latents.float(), mask, voice_prompt_latents.float(), num_voice_prompt_framesdiff --git a/training/dataloader/manifest.py b/training/dataloader/manifest.pynew file mode 100644index 0000000..7bf8646--- /dev/null+++ b/training/dataloader/manifest.py@@ -0,0 +1,82 @@+"""Manifest access for large jsonl datasets."""++import logging+import os+from pathlib import Path++import numpy as np++logger = logging.getLogger(__name__)+++class LazyEntries:+ """This rank's stride of manifest lines, read on demand via an offset index.++ Large manifests (tens of GB) would otherwise be held as per-process string+ lists by every loader subprocess. The index is a uint64 array of line-start+ offsets cached next to the manifest; the lines themselves stay on disk and+ are served through the (shared, reclaimable) page cache.+ """++ def __init__(self, path: str, rank: int, world_size: int) -> None:+ self._path = Path(path)+ self._rank = rank+ self._world = world_size+ self._offsets = None+ self._file = None+ self._ensure_index()++ def _index_path(self) -> Path:+ return self._path.with_name(self._path.name + ".idx")++ def _ensure_index(self) -> None:+ idx = self._index_path()+ src = self._path.stat()+ if idx.exists():+ meta = idx.stat()+ if meta.st_mtime >= src.st_mtime and meta.st_size > 8:+ return+ offsets = [0]+ with self._path.open("rb") as f:+ for line in f:+ offsets.append(offsets[-1] + len(line))+ arr = np.asarray(offsets, dtype=np.uint64)+ tmp = idx.with_name(idx.name + f".tmp.{os.getpid()}")+ arr.tofile(tmp)+ os.replace(tmp, idx) # concurrent builders write identical content+ logger.info(f"indexed {len(arr) - 1} lines of {self._path.name}")++ def _load(self) -> None:+ all_offsets = np.fromfile(self._index_path(), dtype=np.uint64)+ starts, ends = all_offsets[:-1], all_offsets[1:]+ self._starts = starts[self._rank :: self._world]+ self._ends = ends[self._rank :: self._world]+ self._offsets = True++ def __len__(self) -> int:+ if self._offsets is None:+ self._load()+ return len(self._starts)++ def __getitem__(self, i: int) -> str:+ if self._offsets is None:+ self._load()+ if self._file is None:+ self._file = self._path.open("rb")+ self._file.seek(int(self._starts[i]))+ return self._file.read(int(self._ends[i] - self._starts[i])).decode()++ def __getstate__(self) -> dict[str, object]:+ return {"_path": self._path, "_rank": self._rank, "_world": self._world}++ def __setstate__(self, state: dict[str, object]) -> None:+ self.__dict__.update(state)+ self._offsets = None+ self._file = None+++def load_entries(path: str, rank: int, world_size: int) -> LazyEntries:+ entries = LazyEntries(path, rank, world_size)+ logger.info(f"indexed {len(entries)} entries from {path} (rank {rank}/{world_size})")+ assert len(entries), f"no entries for rank {rank} in {path}"+ return entriesdiff --git a/training/dataloader/subproc.py b/training/dataloader/subproc.pynew file mode 100644index 0000000..c1b4f8b--- /dev/null+++ b/training/dataloader/subproc.py@@ -0,0 +1,100 @@+"""Data loading: jsonl manifests of single utterances (moshi-finetune style).++Each line is {"path": ..., "duration": ..., "transcript": ...}. One sample =+one utterance (cropped to max_duration_sec) + its transcript tokens + a voice+prompt (a random window elsewhere in the same file). Lines are sharded across+ranks by line index.+"""++import logging+import multiprocessing.queues+import queue+from collections.abc import Iterator+from typing import Any++import sentencepiece+import torch.multiprocessing as torch_mp++from .loader import DataLoader+from .types import Batch++logger = logging.getLogger(__name__)+++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)+ loader = DataLoader(tokenize=sentence_piece.encode, **loader_kwargs)+ for batch in loader:+ q.put(batch)+++class SubprocessDataLoader:+ def __init__(+ self,+ jsonl: str,+ sentence_piece: sentencepiece.SentencePieceProcessor,+ batch_size: int,+ sample_rate: int,+ frame_rate: float,+ max_duration_sec: float,+ max_voice_prompt_sec: float,+ rank: int,+ world_size: int,+ seed: int = 0,+ shuffle: bool = True,+ io_workers: int = 16,+ num_procs: int = 3,+ depth: int = 8,+ ):+ ctx = torch_mp.get_context("spawn")+ self._queue = ctx.Queue(maxsize=depth)+ self._procs = []+ for i in range(num_procs):+ loader_kwargs = {+ "jsonl": jsonl,+ "batch_size": batch_size,+ "sample_rate": sample_rate,+ "frame_rate": frame_rate,+ "max_duration_sec": max_duration_sec,+ "max_voice_prompt_sec": max_voice_prompt_sec,+ "rank": rank * num_procs + i,+ "world_size": world_size * num_procs,+ "seed": seed + rank * num_procs + i,+ "shuffle": shuffle,+ "io_workers": io_workers,+ }+ proc = ctx.Process(+ target=_feed_queue,+ args=(self._queue, sentence_piece.serialized_model_proto(), loader_kwargs),+ daemon=True,+ name=f"dataloader-{i}",+ )+ proc.start()+ self._procs.append(proc)++ def _check_procs(self):+ dead = [p for p in self._procs if not p.is_alive()]+ if dead:+ raise RuntimeError(+ f"dataloader subprocess(es) died (exit codes "+ f"{[p.exitcode for p in dead]}), check their tracebacks above"+ )++ def __iter__(self) -> Iterator[Batch]:+ batches = 0+ while True:+ try:+ batch = self._queue.get(timeout=60)+ except queue.Empty:+ self._check_procs()+ continue+ batches += 1+ if batches % 100 == 0:+ self._check_procs()+ yield batchdiff --git a/training/dataloader/types.py b/training/dataloader/types.pynew file mode 100644index 0000000..d3c6c58--- /dev/null+++ b/training/dataloader/types.py@@ -0,0 +1,36 @@+"""Data loading: jsonl manifests of single utterances (moshi-finetune style).++Each line is {"path": ..., "duration": ..., "transcript": ...}. One sample =+one utterance (cropped to max_duration_sec) + its transcript tokens + a voice+prompt (a random window elsewhere in the same file). Lines are sharded across+ranks by line index.+"""++import logging+from dataclasses import dataclass+from typing import Any++import torch++logger = logging.getLogger(__name__)+++@dataclass+class Entry:+ path: str+ duration: float+ transcript: str+ words: list[dict[str, Any]] | None = None # [{"word", "start", "end"}] from align_data+ start: float = 0.0 # offset of the utterance inside the audio file (long recordings)+ latents_file: str | None = None+++@dataclass+class Batch:+ audio: torch.Tensor # [B, 1, samples], zero-padded+ num_audio_frames: torch.Tensor # [B] valid codec frames per sample+ text_tokens: list[torch.Tensor] # ragged, one [L_b] long tensor per sample+ voice_audio: torch.Tensor # [B, 1, prompt_samples]+ num_voice_prompt_frames: torch.Tensor # [B] valid codec frames of each voice prompt+ tail_latents: torch.Tensor | None = None+ prompt_latents: torch.Tensor | None = Nonediff --git a/training/tests/test_smoke.py b/training/tests/test_smoke.pyindex fb66b4e..7ab9dae 100644--- a/training/tests/test_smoke.py+++ b/training/tests/test_smoke.py@@ -16,7 +16,7 @@ from torch import nnsys.path.insert(0, str(Path(__file__).resolve().parents[2]))-import training.dataloader as td+import training.dataloader.audio as td_audiofrom pocket_tts.models.flow_lm import FlowLMModelfrom pocket_tts.modules.mlp import SimpleMLPAdaLNfrom pocket_tts.modules.stateful_module import init_states@@ -290,7 +290,7 @@ def test_prefix_prompt(monkeypatch: pytest.MonkeyPatch):calls.append((start, dur))return np.zeros(max(1, int(dur * sr)), dtype=np.float32)- monkeypatch.setattr(td, "_load_window", fake_load_window)+ monkeypatch.setattr(td_audio, "_load_window", fake_load_window)for _ in range(50):calls.clear()wav, tokens, prompt, plen = dl._sample(entry)