Skip to content

A TTS that fits in your CPU (and pocket)

Python

Precompute training latents; re-encode only the stitch window (#270)

gabrieldemarmiesse-ai-agent02446576dd13
diff --git a/training/README.md b/training/README.md
index 83bf80c..1f587c3 100644
--- a/training/README.md
+++ b/training/README.md
@@ -172,19 +172,20 @@ If you train on 2k hours of HiFiTTS-2 and batch size 64, this is the metrics pro
See [Evaluate](#Evaluate) for more info about the metrics.
-Regarding timing, this is how long training takes (all with effective batch size 64):
-
-| GPUs | per-GPU batch | steps/s | peak VRAM/GPU | to 200k | to 400k |
-|---|---|---|---|---|---|
-| 1 x L4-23GB | 16 x4 | 0.35 | 15.9 GiB | ~158 h | ~315 h |
-| 1 x L40S-46GB | 64 | 0.77 | 42.0 GiB | ~72 h | ~144 h |
-| 1 x H100-80GB | 64 | 2.17 | 55.9 GiB | ~26 h | ~51 h |
-| 2 x H100-80GB | 32 | 3.92 | 32.4 GiB | ~14 h | ~28 h |
-| 4 x H100-80GB | 16 | 6.25 | 20.0 GiB | ~9 h | ~18 h |
-| 8 x H100-80GB | 8 | 8.69 | 14.2 GiB | ~6.5 h | ~13 h |
-
-Scaling falls off because the per-GPU batch shrinks, not because of
-communication. Distillation adds ~3 h on 8 H100 GPUs.
+Regarding timing: the first run precomputes Mimi latents for the train
+manifest (once, using all GPUs; validation always encodes audio directly),
+then trains from them. On 2000 h of HiFiTTS-2, effective batch size 64:
+
+| GPUs | per-GPU batch | precompute (once) | steps/s | peak VRAM/GPU | to 200k | to 400k |
+|---|---|---|---|---|---|---|
+| 1 x H100-80GB | 64 | ~50 min | 5.05 | 41.5 GiB | ~11 h | ~22 h |
+| 2 x H100-80GB | 32 | ~25 min | 7.97 | 24.9 GiB | ~7 h | ~14 h |
+| 4 x H100-80GB | 16 | ~15 min | 9.79 | 17.2 GiB | ~5.7 h | ~11.4 h |
+| 8 x H100-80GB | 8 | ~10 min | 10.60 | 15.5 GiB | ~5.2 h | ~10.5 h |
+
+Precompute stores ~6 GB of latents per 1000 h of audio next to the manifest.
+`data.precompute: false` skips the precomputing, which will start training
+immediately but at slower speeds.
### Training format
diff --git a/training/args.py b/training/args.py
index e343e08..0cad348 100644
--- a/training/args.py
+++ b/training/args.py
@@ -20,6 +20,10 @@ class DataArgs:
max_voice_prompt_sec: float = 5.0
shuffle: bool = True
loader_procs: int = 3
+ # Precompute Mimi latents for train_jsonl on first run and train from
+ # them (rank 0 encodes once; other ranks wait). False keeps the
+ # on-the-fly audio pipeline.
+ precompute: bool = True
@dataclass
diff --git a/training/dataloader.py b/training/dataloader.py
index 20d633c..2d54b9a 100644
--- a/training/dataloader.py
+++ b/training/dataloader.py
@@ -20,6 +20,7 @@ import numpy as np
import sphn
import torch
import torch.multiprocessing as torch_mp
+from safetensors import safe_open
from pocket_tts.data.audio_utils import convert_audio
@@ -33,6 +34,7 @@ class Entry:
transcript: str
words: list | None = None # [{"word", "start", "end"}] from training.scripts.align_data
start: float = 0.0 # offset of the utterance inside the audio file (long recordings)
+ latents_file: str | None = None
@dataclass
@@ -42,6 +44,8 @@ class Batch:
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
def load_entries(path: str, rank: int, world_size: int) -> list[str]:
@@ -94,6 +98,14 @@ class DataLoader:
self.io_workers = io_workers
self._failures = 0
self.rng = random.Random(seed)
+ self.frame_size = int(sample_rate / frame_rate)
+ meta_path = Path(jsonl).with_suffix(".meta.json")
+ self.stitch_frames = 0
+ if meta_path.exists():
+ meta = json.loads(meta_path.read_text())
+ self.stitch_frames = int(meta["stitch_frames"])
+ self.latents_root = Path(jsonl).parent
+ logger.info(f"latent mode: stitch_frames={self.stitch_frames} from {meta_path.name}")
MIN_CUT_SEC = 1.0 # keep at least this much audio on both sides of a cut
TRAIL_SEC = 0.2 # silence kept after the last word, so EOS has a consistent target
@@ -117,60 +129,66 @@ class DataLoader:
ends = [w["end"] for w in entry.words if w.get("end") is not None]
return max(ends) if ends else None
- def _sample(self, entry: Entry) -> tuple[np.ndarray, torch.Tensor, np.ndarray, int]:
- if entry.words:
- # Cut the utterance at a random point between two aligned words:
- # audio before the cut = voice conditioning, audio after = target,
- # paired with the remaining words as text (see training/scripts/align_data.py).
- cuts = []
- for i in range(1, len(entry.words)):
- prev, cur = entry.words[i - 1], entry.words[i]
- if prev["end"] is None or cur["start"] is None:
- continue
- cut = 0.5 * (prev["end"] + cur["start"])
- if cut >= self.MIN_CUT_SEC and entry.duration - cut >= self.MIN_CUT_SEC:
- cuts.append((cut, i))
- if cuts:
- # The prompt is the (contiguous) start of the utterance.
- # Eligible cuts are word boundaries whose preceding word ends
- # inside the prompt window; the draw is uniform over 1..k
- # eligible words, so prompt length varies and the target
- # keeps most of the utterance.
- window = (
- self.max_voice_prompt_sec if self.max_voice_prompt_sec > 0 else float("inf")
- )
- eligible = [
- (c, i)
- for c, i in cuts
- if entry.words[i - 1].get("end") is not None
- and entry.words[i - 1]["end"] < window
- ]
- cuts = eligible or cuts[:1] # degenerate windows: earliest valid cut
- if cuts:
- cut, i = self.rng.choice(cuts)
- text = " ".join(w["word"] for w in entry.words[i:])
- tokens = torch.tensor(self.tokenize(text), dtype=torch.long)
- # Trim to the last word (plus a short tail) rather than the end
- # of the file: 12% of utterances carry >1s of trailing silence,
- # and training on it teaches the model to emit silence instead of
- # EOS, so generations never terminate. dora does the same thing
- # via align_wav_on_words.
- end = entry.duration
- 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(
- entry.path,
- entry.start + cut,
- min(end - cut, self.max_duration_sec),
- self.sample_rate,
- )
- # 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)
- )
- return wav, tokens, prompt, length
+ def _choose_cut(self, entry: Entry) -> tuple[float, int] | None:
+ # Cut the utterance at a random point between two aligned words:
+ # audio before the cut = voice conditioning, audio after = target,
+ # paired with the remaining words as text (see training/scripts/align_data.py).
+ if not entry.words:
+ return None
+ cuts = []
+ for i in range(1, len(entry.words)):
+ prev, cur = entry.words[i - 1], entry.words[i]
+ if prev["end"] is None or cur["start"] is None:
+ continue
+ cut = 0.5 * (prev["end"] + cur["start"])
+ if cut >= self.MIN_CUT_SEC and entry.duration - cut >= self.MIN_CUT_SEC:
+ cuts.append((cut, i))
+ if cuts:
+ # The prompt is the (contiguous) start of the utterance.
+ # Eligible cuts are word boundaries whose preceding word ends
+ # inside the prompt window; the draw is uniform over 1..k
+ # eligible words, so prompt length varies and the target
+ # keeps most of the utterance.
+ window = self.max_voice_prompt_sec if self.max_voice_prompt_sec > 0 else float("inf")
+ eligible = [
+ (c, i)
+ for c, i in cuts
+ if entry.words[i - 1].get("end") is not None and entry.words[i - 1]["end"] < window
+ ]
+ cuts = eligible or cuts[:1] # degenerate windows: earliest valid cut
+ if not cuts:
+ return None
+ return self.rng.choice(cuts)
+
+ def _sample(self, entry: Entry) -> tuple:
+ if entry.latents_file is not None:
+ return self._sample_latent(entry)
+ chosen = self._choose_cut(entry)
+ if chosen is not None:
+ cut, i = chosen
+ text = " ".join(w["word"] for w in entry.words[i:])
+ tokens = torch.tensor(self.tokenize(text), dtype=torch.long)
+ # Trim to the last word (plus a short tail) rather than the end
+ # of the file: 12% of utterances carry >1s of trailing silence,
+ # and training on it teaches the model to emit silence instead of
+ # EOS, so generations never terminate. dora does the same thing
+ # via align_wav_on_words.
+ end = entry.duration
+ 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(
+ entry.path,
+ entry.start + cut,
+ min(end - cut, self.max_duration_sec),
+ self.sample_rate,
+ )
+ # 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)
+ )
+ return wav, tokens, prompt, length
last = self._last_word_end(entry)
end = min(entry.duration, last + self.TRAIL_SEC) if last is not None else entry.duration
duration = min(end, self.max_duration_sec)
@@ -184,6 +202,85 @@ class DataLoader:
)
return wav, tokens, prompt, length
+ def _load_latents(self, entry: Entry) -> torch.Tensor:
+ path = self.latents_root / entry.latents_file
+ with safe_open(str(path), framework="pt") as f:
+ return f.get_tensor("latents")
+
+ def _latent_cut(self, entry: Entry, stored: int) -> tuple[int, str]:
+ chosen = self._choose_cut(entry)
+ if chosen is None or stored <= 1:
+ return 0, entry.transcript
+ cut, i = chosen
+ cut_frames = min(max(round(cut * self.frame_rate), 1), stored - 1)
+ return cut_frames, " ".join(w["word"] for w in entry.words[i:])
+
+ def _latent_target_frames(self, entry: Entry, cut_frames: int, stored: int) -> int:
+ cut_sec = cut_frames / self.frame_rate
+ end = entry.duration
+ last = self._last_word_end(entry)
+ if last is not None and last > cut_sec:
+ end = min(entry.duration, last + self.TRAIL_SEC)
+ target_frames = int(min(end - cut_sec, self.max_duration_sec) * self.frame_rate)
+ return max(1, min(target_frames, stored - cut_frames))
+
+ def _latent_prompt(self, lat: torch.Tensor, cut_frames: int) -> torch.Tensor:
+ stored = lat.shape[0]
+ cap = (
+ max(1, int(self.max_voice_prompt_sec * self.frame_rate))
+ if self.max_voice_prompt_sec > 0
+ else stored
+ )
+ if cut_frames > 0:
+ return lat[: min(cut_frames, cap)]
+ start = self.rng.randint(0, max(0, stored - cap))
+ return lat[start : start + cap]
+
+ def _sample_latent(self, entry: Entry) -> tuple:
+ assert self.stitch_frames > 0, f"{entry.path}: latents entry but no meta file loaded"
+ lat = self._load_latents(entry)
+ cut_frames, text = self._latent_cut(entry, lat.shape[0])
+ 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(
+ entry.path,
+ entry.start + cut_frames / self.frame_rate,
+ stitch_frames / self.frame_rate,
+ self.sample_rate,
+ )
+ tail = lat[cut_frames + stitch_frames : cut_frames + target_frames]
+ return stitch, tokens, self._latent_prompt(lat, cut_frames), tail, target_frames
+
+ @staticmethod
+ def _pad_latents(seqs: tuple, min_len: int) -> torch.Tensor:
+ length = max(min_len, max(s.shape[0] for s in seqs))
+ out = torch.zeros(len(seqs), length, seqs[0].shape[-1])
+ for b, s in enumerate(seqs):
+ out[b, : s.shape[0]] = s
+ return out
+
+ def _collate_stitch_audio(self, stitches: tuple) -> torch.Tensor:
+ stitch_samples = self.stitch_frames * self.frame_size
+ audio = torch.zeros(len(stitches), 1, stitch_samples)
+ for b, w in enumerate(stitches):
+ n = min(len(w), stitch_samples)
+ audio[b, 0, :n] = torch.from_numpy(w[:n])
+ return audio
+
+ def _collate_latent(self, batch: list[tuple]) -> Batch:
+ stitches, tokens, prompts, tails, target_frames = zip(*batch, strict=True)
+ num_prompt_frames = torch.tensor([max(1, p.shape[0]) for p in prompts], dtype=torch.long)
+ return Batch(
+ self._collate_stitch_audio(stitches),
+ torch.tensor(target_frames, dtype=torch.long),
+ list(tokens),
+ torch.zeros(len(stitches), 1, 0),
+ num_prompt_frames,
+ tail_latents=self._pad_latents(tails, 0),
+ prompt_latents=self._pad_latents(prompts, 1),
+ )
+
def get_entry(self, index: int) -> Entry:
d = json.loads(self.entries[index])
return Entry(
@@ -192,6 +289,7 @@ class DataLoader:
d["transcript"],
d.get("words"),
float(d.get("start", 0.0)),
+ d.get("latents_file"),
)
def _sample_or_none(self, entry: Entry) -> tuple | None:
@@ -239,6 +337,9 @@ class DataLoader:
continue
batch, samples = samples[: self.batch_size], samples[self.batch_size :]
yielded += 1
+ if self.stitch_frames:
+ yield self._collate_latent(batch)
+ continue
wavs, tokens, prompts, prompt_lens = zip(*batch, strict=True)
max_len = max(len(w) for w in wavs)
audio = torch.zeros(len(wavs), 1, max_len)
@@ -358,6 +459,17 @@ def _prefetch(iterator: Iterator[Batch], depth: int = 4) -> Iterator[Batch]:
@torch.no_grad()
def encode_batch(mimi, batch, device):
+ 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]
+ 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]
diff --git a/training/scripts/precompute_latents.py b/training/scripts/precompute_latents.py
new file mode 100644
index 0000000..762fab6
--- /dev/null
+++ b/training/scripts/precompute_latents.py
@@ -0,0 +1,296 @@
+import hashlib
+import json
+import logging
+import multiprocessing
+import os
+import time
+
+os.environ.setdefault("POCKET_TTS_NO_BEARTYPE", "1")
+from concurrent.futures import ProcessPoolExecutor
+from pathlib import Path
+
+import numpy as np
+import safetensors.torch
+import torch
+import typer
+from tqdm import tqdm
+
+from pocket_tts.utils.utils import download_if_necessary
+from training.args import load_args
+from training.dataloader import Entry, _load_window
+from training.modules.builders import build_mimi, load_model_config
+
+logger = logging.getLogger("precompute_latents")
+app = typer.Typer(pretty_exceptions_show_locals=False)
+
+CALIBRATION_POOL_LINES = 4096
+CALIBRATION_MARGIN_FRAMES = 4
+
+
+def default_decode_workers() -> int:
+ """Size the decode pool from the cores this process may actually use."""
+ return max(4, len(os.sched_getaffinity(0)) - 2)
+
+
+def _decode_one(job: tuple) -> np.ndarray:
+ path, start, duration, sample_rate = job
+ return _load_window(path, start, duration, sample_rate)
+
+
+def _decode_chunk(jobs: list[tuple]) -> tuple[np.ndarray, list[int]]:
+ wavs = [_load_window(p, s, d, sr) for (p, s, d, sr) in jobs]
+ max_len = max(len(w) for w in wavs)
+ batch = np.zeros((len(wavs), 1, max_len), dtype=np.float32)
+ for b, w in enumerate(wavs):
+ batch[b, 0, : len(w)] = w
+ return batch, [len(w) for w in wavs]
+
+
+def _parse_entry(line: str) -> Entry:
+ d = json.loads(line)
+ return Entry(
+ d["path"], float(d["duration"]), d["transcript"], d.get("words"), float(d.get("start", 0.0))
+ )
+
+
+def _chunk_jobs(lines: list[str], idxs: list[int], sample_rate: int) -> list[tuple]:
+ chunk = [lines[i] for i in idxs]
+ return [(e.path, e.start, e.duration, sample_rate) for e in map(_parse_entry, chunk)]
+
+
+def mimi_encode_hash(mimi) -> str:
+ """Hash of the weights on the encode path (encoder, encoder transformer,
+ downsample): identifies which Mimi produced a latents store."""
+ h = hashlib.sha256()
+ for name in ("encoder", "encoder_transformer", "downsample"):
+ module = getattr(mimi, name, None)
+ if module is None:
+ continue
+ for k, v in sorted(module.state_dict().items()):
+ h.update(f"{name}.{k}:{tuple(v.shape)}".encode())
+ h.update(v.detach().cpu().contiguous().numpy().tobytes())
+ return h.hexdigest()
+
+
+def load_frozen_mimi(config) -> torch.nn.Module:
+ mimi = build_mimi(config.mimi)
+ weights_file = download_if_necessary(str(config.weights_path))
+ state = safetensors.torch.load_file(weights_file)
+ mimi_state = {k.removeprefix("mimi."): v for k, v in state.items() if k.startswith("mimi.")}
+ mimi.load_state_dict(mimi_state, strict=True)
+ encoder_max = max(
+ v.abs().max().item() for k, v in mimi_state.items() if k.startswith("encoder.")
+ )
+ if encoder_max == 0:
+ raise SystemExit(
+ f"{config.weights_path} ships an all-zero Mimi encoder (a release without "
+ "voice cloning). Point the config at weights with a real encoder."
+ )
+ mimi.eval()
+ for p in mimi.parameters():
+ p.requires_grad_(False)
+ # Same per-module compile as training; dynamic shapes because chunks pad
+ # to their own longest row.
+ mimi.encoder.compile(dynamic=True)
+ mimi.encoder_transformer.compile(dynamic=True)
+ return mimi
+
+
+def measure_stitch_frames(mimi, audio: torch.Tensor) -> tuple[int, float]:
+ fs = mimi.frame_size
+ full = mimi.encode_to_latent(audio)
+ k = full.shape[1] // 2
+ cold = mimi.encode_to_latent(audio[..., k * fs :])
+ n = min(cold.shape[1], full.shape[1] - k) - 1
+ rel = (cold[:, :n] - full[:, k : k + n]).norm(dim=-1) / (full[:, k : k + n].norm(dim=-1) + 1e-8)
+ rel = rel.max(dim=0).values
+ prompt_cold = mimi.encode_to_latent(audio[..., : k * fs])
+ pn = min(prompt_cold.shape[1], k) - 1
+ floor = (
+ ((prompt_cold[:, :pn] - full[:, :pn]).norm(dim=-1) / (full[:, :pn].norm(dim=-1) + 1e-8))
+ .max()
+ .item()
+ )
+ above = (rel > max(3 * floor, 1e-3)).nonzero()
+ frames = int(above.max().item()) + 1 if above.numel() else 0
+ return frames + CALIBRATION_MARGIN_FRAMES, floor
+
+
+def _calibrate(pool, lines: list[str], mimi, batch_size: int, device) -> tuple[int, float]:
+ longest = sorted(map(_parse_entry, lines[:CALIBRATION_POOL_LINES]), key=lambda e: -e.duration)
+ jobs = [(e.path, e.start, e.duration, mimi.sample_rate) for e in longest[:batch_size]]
+ calib = list(pool.map(_decode_one, jobs))
+ max_len = max(len(w) for w in calib)
+ max_len -= max_len % mimi.frame_size
+ audio = torch.zeros(len(calib), 1, max_len)
+ for b, w in enumerate(calib):
+ audio[b, 0, : min(len(w), max_len)] = torch.from_numpy(w[:max_len])
+ return measure_stitch_frames(mimi, audio.to(device))
+
+
+def _entry_frames(n_samples: int, sample_rate: int, frame_rate: float) -> int:
+ return max(1, int(n_samples * frame_rate / sample_rate))
+
+
+def _latents_name(manifest: Path, idx: int, tag: str) -> str:
+ return f"latents/{tag}/{manifest.stem}_{idx:08d}.safetensors"
+
+
+def _annotated_lines(lines: list[str], manifest: Path, tag: str) -> list[str]:
+ out = []
+ for idx, line in enumerate(lines):
+ d = json.loads(line)
+ d["latents_file"] = _latents_name(manifest, idx, tag)
+ out.append(json.dumps(d))
+ return out
+
+
+def _pending_chunks(
+ lines: list[str],
+ manifest: Path,
+ batch_size: int,
+ tag: str,
+ worker: int = 0,
+ num_workers: int = 1,
+) -> list[list[int]]:
+ # Chunk in duration order: a chunk pads to its longest row, so grouping
+ # similar lengths avoids spending encode FLOPs on padding. Latents files
+ # are named by manifest index, so encode order is free. Workers take
+ # strided chunks, so several GPUs can encode one manifest concurrently.
+ order = sorted(range(len(lines)), key=lambda i: json.loads(lines[i])["duration"])
+ pending = []
+ for n, chunk_start in enumerate(range(0, len(order), batch_size)):
+ if n % num_workers != worker:
+ continue
+ idxs = order[chunk_start : chunk_start + batch_size]
+ if any(not (manifest.parent / _latents_name(manifest, idx, tag)).exists() for idx in idxs):
+ pending.append(idxs)
+ return pending
+
+
+def _write_chunk(
+ latents: torch.Tensor, lens: list[int], idxs: list[int], manifest: Path, mimi, tag: str
+) -> None:
+ for b, n_samples in enumerate(lens):
+ frames = min(_entry_frames(n_samples, mimi.sample_rate, mimi.frame_rate), latents.shape[1])
+ path = manifest.parent / _latents_name(manifest, idxs[b], tag)
+ tmp = path.with_suffix(".tmp")
+ safetensors.torch.save_file({"latents": latents[b, :frames].contiguous()}, str(tmp))
+ tmp.rename(path)
+
+
+def _encode_pending(
+ pool,
+ mimi,
+ device,
+ lines: list[str],
+ manifest: Path,
+ batch_size: int,
+ decode_workers: int,
+ tag: str,
+ worker: int = 0,
+ num_workers: int = 1,
+) -> None:
+ pending = _pending_chunks(lines, manifest, batch_size, tag, worker, num_workers)
+ lookahead = decode_workers + 2 # keep every decode worker busy
+ futures = {
+ i: pool.submit(_decode_chunk, _chunk_jobs(lines, idxs, mimi.sample_rate))
+ for i, idxs in enumerate(pending[:lookahead])
+ }
+ submitted = len(futures)
+ for i, idxs in enumerate(tqdm(pending, desc=f"encode {manifest.name}")):
+ arr, lens = futures.pop(i).result()
+ if submitted < len(pending):
+ jobs = _chunk_jobs(lines, pending[submitted], mimi.sample_rate)
+ futures[submitted] = pool.submit(_decode_chunk, jobs)
+ submitted += 1
+ with torch.no_grad():
+ latents = mimi.encode_to_latent(torch.from_numpy(arr).to(device)).cpu()
+ _write_chunk(latents, lens, idxs, manifest, mimi, tag)
+
+
+def _write_manifest_and_meta(
+ manifest: Path,
+ new_lines: list[str],
+ stitch_frames: int,
+ floor: float,
+ mimi,
+ weights_path: str,
+ mimi_hash: str,
+) -> None:
+ out_manifest = manifest.with_name(manifest.stem + "_latents.jsonl")
+ out_manifest.write_text("\n".join(new_lines) + "\n")
+ meta = {
+ "stitch_frames": stitch_frames,
+ "noise_floor": floor,
+ "frame_rate": mimi.frame_rate,
+ "weights_path": weights_path,
+ "mimi_hash": mimi_hash,
+ }
+ meta_path = manifest.with_name(manifest.stem + "_latents.meta.json")
+ meta_path.write_text(json.dumps(meta, indent=2) + "\n")
+ logger.info(f"wrote {out_manifest} and {meta_path}")
+
+
+def precompute_manifest(
+ manifest: Path,
+ mimi,
+ device,
+ batch_size: int,
+ decode_workers: int,
+ weights_path: str,
+ worker: int = 0,
+ num_workers: int = 1,
+) -> None:
+ """Encode a manifest's utterances to per-utterance latents files.
+
+ With num_workers > 1 each worker encodes a strided subset of chunks;
+ worker 0 waits for the others' files and writes the manifest and meta.
+ """
+ lines = manifest.read_text().splitlines()
+ mimi_hash = mimi_encode_hash(mimi)
+ tag = mimi_hash[:8]
+ (manifest.parent / "latents" / tag).mkdir(parents=True, exist_ok=True)
+ decode_workers = decode_workers or default_decode_workers()
+ pool = ProcessPoolExecutor(
+ max_workers=decode_workers, mp_context=multiprocessing.get_context("spawn")
+ )
+ if worker == 0:
+ stitch_frames, floor = _calibrate(pool, lines, mimi, batch_size, device)
+ logger.info(f"{manifest.name}: stitch_frames={stitch_frames} (noise floor {floor:.1e})")
+ _encode_pending(
+ pool, mimi, device, lines, manifest, batch_size, decode_workers, tag, worker, num_workers
+ )
+ if worker != 0:
+ return
+ while _pending_chunks(lines, manifest, batch_size, tag):
+ time.sleep(5)
+ new_lines = _annotated_lines(lines, manifest, tag)
+ _write_manifest_and_meta(
+ manifest, new_lines, stitch_frames, floor, mimi, weights_path, mimi_hash
+ )
+
+
+def main(config: str, batch_size: int = 16, decode_workers: int = 0) -> None:
+ logging.basicConfig(level=logging.INFO)
+ args = load_args(config)
+ model_config = load_model_config(args.model_config, args.model_overrides)
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
+ torch.backends.cuda.matmul.allow_tf32 = True
+ mimi = load_frozen_mimi(model_config).to(device)
+ if not args.data.train_jsonl:
+ raise SystemExit("the config has no data.train_jsonl to precompute")
+ precompute_manifest(
+ Path(args.data.train_jsonl),
+ mimi,
+ device,
+ batch_size,
+ decode_workers,
+ str(model_config.weights_path),
+ )
+
+
+if __name__ == "__main__":
+ app()
diff --git a/training/train.py b/training/train.py
index 8357201..cc0c005 100644
--- a/training/train.py
+++ b/training/train.py
@@ -45,6 +45,7 @@ from training.train_utils import (
ProgressLog,
_compile_models,
add_file_logging,
+ ensure_train_latents,
git_commit,
lr_at,
setup_logging,
@@ -103,13 +104,19 @@ def setup(config_path: str) -> Run:
" python -m training.scripts.prepare_data --hours 200\n"
"or point data.train_jsonl / data.valid_jsonl at your own manifests."
)
-
+ if args.data.valid_jsonl and Path(args.data.valid_jsonl).with_suffix(".meta.json").exists():
+ raise SystemExit(
+ f"valid_jsonl is a precomputed-latents manifest: {args.data.valid_jsonl}\n"
+ "Validation must encode audio directly so its metrics stay exact and "
+ "comparable; point valid_jsonl at the original manifest."
+ )
if rank == 0:
save_args(args, run_dir / "args.yaml")
model, mimi, _config = build_models(args)
model.to(device)
mimi.to(device)
+ ensure_train_latents(args, mimi, device, rank, world_size)
n_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
if rank == 0:
logger.info(f"flow_lm + objective: {n_params / 1e6:.1f}M trainable params")
@@ -249,7 +256,8 @@ def main(config_path: str) -> None:
logger.info(f"per-step logging done, logging every {args.log_freq} steps from now on")
if sample_voice is None:
- sample_voice = voice_prompt_latents[0].detach().clone()
+ n = int(num_voice_prompt_frames[0])
+ sample_voice = voice_prompt_latents[0, :n].detach().clone()
if (
rank == 0
and args.sample_sentences
diff --git a/training/train_utils.py b/training/train_utils.py
index 29a461e..617a1ed 100644
--- a/training/train_utils.py
+++ b/training/train_utils.py
@@ -12,6 +12,7 @@ import torch
from pocket_tts.modules.stateful_module import init_states
from training.args import TrainArgs
+from training.modules.builders import load_model_config
logger = logging.getLogger("train")
@@ -136,3 +137,65 @@ def write_samples(model, mimi, tokenize, args, run_dir, step, voice_latents, dev
)
model.train()
logger.info(f"wrote {len(tokens)} samples at step {step}")
+
+
+def ensure_train_latents(args: TrainArgs, mimi, device, rank: int, world_size: int) -> None:
+ """Train from precomputed latents, encoding them first if needed.
+
+ The latents store is keyed by a hash of Mimi's encode-path weights, so
+ changed weights trigger a fresh precompute instead of silently serving
+ stale latents. Every rank encodes a strided share of the chunks;
+ completion is signaled through the shared filesystem (an NCCL barrier
+ would time out).
+ """
+ from training.scripts.precompute_latents import mimi_encode_hash, precompute_manifest
+
+ train_path = Path(args.data.train_jsonl)
+ if train_path.stem.endswith("_latents"):
+ audio_manifest = train_path.with_name(
+ train_path.stem.removesuffix("_latents") + train_path.suffix
+ )
+ elif args.data.precompute:
+ audio_manifest = train_path
+ else:
+ return
+ latents_manifest = audio_manifest.with_name(audio_manifest.stem + "_latents.jsonl")
+ meta_path = latents_manifest.with_suffix(".meta.json")
+ current = mimi_encode_hash(mimi)
+
+ def is_fresh() -> bool:
+ if not meta_path.exists():
+ return False
+ return json.loads(meta_path.read_text()).get("mimi_hash") == current
+
+ if not is_fresh():
+ if not args.data.precompute:
+ raise SystemExit(
+ f"{latents_manifest} was precomputed with different Mimi weights "
+ "and data.precompute is off; re-run training.scripts.precompute_latents."
+ )
+ if not audio_manifest.exists():
+ raise SystemExit(
+ f"latents are stale (Mimi weights changed) and the audio manifest "
+ f"{audio_manifest} is missing; cannot re-encode."
+ )
+ if rank == 0:
+ logger.info(f"precomputing latents for {audio_manifest.name} (one-time)")
+ config = load_model_config(args.model_config, args.model_overrides)
+ precompute_manifest(
+ audio_manifest,
+ mimi,
+ device,
+ 32,
+ 0,
+ str(config.weights_path),
+ worker=rank,
+ num_workers=world_size,
+ )
+ waited = 0
+ while not is_fresh():
+ time.sleep(10)
+ waited += 10
+ if waited > 24 * 3600:
+ raise SystemExit("gave up waiting for the latents precompute to finish")
+ args.data.train_jsonl = str(latents_manifest)