Skip to content

A TTS that fits in your CPU (and pocket)

Python

Distillation from a teacher cache (distill_teacher_cache) (#402)

manu-lm77c3d76b63d6
diff --git a/training/README.md b/training/README.md
index a1aa049..65881cc 100644
--- a/training/README.md
+++ b/training/README.md
@@ -191,6 +191,45 @@ can expect:
| 1 x H100 | 64 | 10.5 | 9.8 GiB | ~5.3 h |
| 8 x H100 | 8 | 21.3 | 3.8 GiB | ~2.6 h |
+### Faster distillation from a teacher cache
+
+Most of a distillation step is the teacher: two forward passes of the deep model (with and
+without conditioning, for the guidance), plus the Mimi encoding of the batch. Since the teacher
+is frozen, its target can be computed once instead, and the student trained from that cache:
+
+```bash
+# Once, on any number of GPUs (one part per GPU; resumable, re-run a part to finish it):
+for h in 0 1 2 3; do
+ CUDA_VISIBLE_DEVICES=$h uv run python -m training.scripts.build_teacher_cache \
+ training/configs/depth_distill.yaml data/teacher_cache --rows 1000000 \
+ --part $h --parts 4 &
+done; wait
+# Then train with `distill_teacher_cache: data/teacher_cache` added to the same config.
+```
+
+The script draws the rows with the training loader and the config's data settings (crops,
+voice prompts, text augmentations) and stores each one with the teacher's guided target. The
+run then needs neither the teacher, nor the loader, nor Mimi: distilling the released 24-layer
+English teacher into 6 layers at batch size 64 on one H100 ran at 27.5 steps/s from a cache vs
+8.4 steps/s online (3.3x), with the same loss curve (distill_mse 0.0975 vs 0.0983 over steps
+600-800 of an 800-step run) and 7.4 vs 8.9 GiB peak memory. The cached targets match the online
+teacher's to a relative MSE of 2e-4 (they are stored in bf16).
+
+What to know before using it:
+- Disk: the target takes 2 bytes per frame per backbone channel, 2 KB per 80 ms frame for the
+ English models (d_model 1024): ~200 KB per HiFiTTS-2 row, ~200 GB per million rows. Size
+ `--rows` to what the run reads, `max_steps x batch_size x grad_accum_steps x GPUs`.
+- Building costs about the teacher's share of an online run (51k rows took 2 min on one H100
+ with 4 parts), so the cache pays off when several runs read it: a sweep over student settings,
+ replicates, restarts.
+- The cache fixes the data: which rows, their crops and prompts, and their order are drawn once at
+ build time, with `--seed`. A resumed run skips the rows it already used, and a run longer than
+ the cache starts over from its first row (training on the same crops again).
+- The cache is tied to the config it was built with: rebuild it after changing the teacher,
+ `distill_cfg_coef`, the data or its settings.
+- The run does no validation, which needs the teacher's targets; evaluate the checkpoints instead
+ (see [Evaluate](#evaluate)).
+
### Training format
By default, the training saves:
diff --git a/training/args.py b/training/args.py
index 53bf0b7..d4d16a0 100644
--- a/training/args.py
+++ b/training/args.py
@@ -203,6 +203,13 @@ class TrainArgs:
# Seed from student_init_from's (and head_init_from's) EMA shadow instead of its raw
# weights (raw weights when the checkpoint carries no EMA).
init_from_use_ema: bool = True
+ # A teacher cache (training/scripts/build_teacher_cache.py): rows of train_jsonl with the
+ # teacher's guided target stored next to them. Distillation then reads its rows and targets
+ # from the cache instead of the loader and never runs the teacher, ~3x faster per step.
+ # The cache fixes the rows, crops and their order (resuming skips the rows already used),
+ # and is re-read from the start when a run outlasts it. No validation runs (it would need
+ # the teacher).
+ distill_teacher_cache: str = ""
# Head distillation: train a new sampler head (flow_net, shaped by the config's flow_lm.flow,
# any flow.type) against a frozen one, on the frozen backbone's outputs; nothing else
@@ -242,6 +249,11 @@ class TrainArgs:
"distillation needs a teacher: set distill_teacher_config, or "
"start_from_pretrained: true to distil a frozen copy of the model itself"
)
+ if self.distill_teacher_cache and not self.distill_cfg_coef > 0:
+ raise ValueError("distill_teacher_cache is for distillation runs: set distill_cfg_coef")
+ if self.distill_teacher_cache and self.stats_ema_steps:
+ # The cached targets were computed on latents normalized with fixed statistics.
+ raise ValueError("distill_teacher_cache needs stats_ema_steps: 0")
if self.head_distill and self.distill_cfg_coef > 0:
raise ValueError("head_distill and distill_cfg_coef are separate runs: set one")
if self.head_distill_loss not in ("mse", "drifting"):
diff --git a/training/dataloader/loader.py b/training/dataloader/loader.py
index 350ca46..a885a4d 100644
--- a/training/dataloader/loader.py
+++ b/training/dataloader/loader.py
@@ -15,7 +15,7 @@ import threading
from collections.abc import Callable, Iterator
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
-from typing import Any
+from typing import Any, TypeVar
import numpy as np
import numpy.typing as npt
@@ -29,9 +29,12 @@ from .types import Batch, Entry
logger = logging.getLogger(__name__)
-def _prefetch(iterator: Iterator[Batch], depth: int = 4) -> Iterator[Batch]:
+T = TypeVar("T")
+
+
+def _prefetch(iterator: Iterator[T], depth: int = 4) -> Iterator[T]:
"""Run the (synchronous, IO-bound) loader in a background thread."""
- q: queue.Queue[Batch | BaseException | None] = queue.Queue(maxsize=depth)
+ q: queue.Queue[T | BaseException | None] = queue.Queue(maxsize=depth)
def worker():
try:
diff --git a/training/dataloader/teacher_cache.py b/training/dataloader/teacher_cache.py
new file mode 100644
index 0000000..d02827d
--- /dev/null
+++ b/training/dataloader/teacher_cache.py
@@ -0,0 +1,105 @@
+"""Teacher caches: distillation rows with the teacher's target stored next to them.
+
+A cache is a directory of files 000000.pt, 000001.pt, ... (training/scripts/build_teacher_cache.py
+writes them), each a list of `rows_per_file` rows (see meta.json), each row a dict of
+
+ "latents": [n, C] float32 raw codec latents of the target audio
+ "text": [L] long text tokens
+ "voice": [nv, C] float32 raw codec latents of the voice prompt
+ "z": [n + 1, dim] bfloat16 guided teacher z (TrainableTTS.teacher_z) at positions 0..n,
+ position n being the stop decision after the last frame
+"""
+
+import json
+import logging
+from collections.abc import Iterator
+from pathlib import Path
+
+import torch
+import torch.nn.functional as F
+from torch.nn.utils.rnn import pad_sequence
+
+from ..modules.model import TrainableTTS
+
+logger = logging.getLogger(__name__)
+CPU = torch.device("cpu")
+
+Row = dict[str, torch.Tensor]
+# (latents [B, T, C], mask [B, T], text tokens, voice [B, Tv, C], voice frames [B], z [B, T, dim] | None)
+CachedBatch = tuple[
+ torch.Tensor, torch.Tensor, list[torch.Tensor], torch.Tensor, torch.Tensor, torch.Tensor | None
+]
+
+
+def collate(rows: list[Row], device: torch.device = CPU) -> CachedBatch:
+ """Pad rows into a batch, T = longest row + 1 so every row's stop position is in the loss."""
+ n = torch.tensor([r["latents"].shape[0] for r in rows])
+ latents = F.pad(pad_sequence([r["latents"] for r in rows], batch_first=True), (0, 0, 0, 1))
+ mask = torch.arange(latents.shape[1])[None, :] < n[:, None]
+ voice = pad_sequence([r["voice"] for r in rows], batch_first=True)
+ num_voice_frames = torch.tensor([r["voice"].shape[0] for r in rows])
+ z = pad_sequence([r["z"] for r in rows], batch_first=True) if "z" in rows[0] else None
+ return (
+ latents.to(device),
+ mask.to(device),
+ [r["text"] for r in rows],
+ voice.to(device),
+ num_voice_frames.to(device),
+ None if z is None else z.to(device),
+ )
+
+
+def teacher_rows(
+ model: TrainableTTS,
+ latents: torch.Tensor, # [B, T, C], encode_batch's outputs
+ mask: torch.Tensor,
+ text_tokens: list[torch.Tensor],
+ voice_latents: torch.Tensor,
+ num_voice_prompt_frames: torch.Tensor,
+) -> list[Row]:
+ """A loader batch as unpadded CPU rows, each with its teacher target."""
+ n = mask.sum(1).tolist()
+ nv = num_voice_prompt_frames.tolist()
+ rows = [
+ {
+ "latents": latents[b, : n[b]].cpu(),
+ "text": text_tokens[b],
+ "voice": voice_latents[b, : nv[b]].cpu(),
+ }
+ for b in range(len(n))
+ ]
+ lat, _, text, voice, nvf, _ = collate(rows, latents.device)
+ fl = model.flow_lm
+ z = model.teacher_z((lat - fl.emb_mean) / fl.emb_std, text, voice, nvf)
+ for b, row in enumerate(rows):
+ row["z"] = z[b, : n[b] + 1].to(torch.bfloat16).cpu()
+ return rows
+
+
+def cached_batches(
+ path: str | Path,
+ batch_size: int,
+ rank: int,
+ world_size: int,
+ skip_rows: int = 0,
+ device: torch.device = CPU,
+) -> Iterator[CachedBatch]:
+ """Batches of consecutive rows of this rank's files (every world_size-th), after skipping
+ skip_rows of them (a resumed run's). Starts over when the files run out."""
+ root = Path(path)
+ meta = json.loads((root / "meta.json").read_text())
+ files = [root / f"{g:06d}.pt" for g in range(rank, meta["files"], world_size)]
+ missing = [f.name for f in files if not f.exists()]
+ if not files or missing:
+ raise SystemExit(f"teacher cache {root} is incomplete (rank {rank} misses {missing[:5]})")
+ k, skip = divmod(skip_rows, meta["rows_per_file"])
+ rows: list[Row] = []
+ while True:
+ if k % len(files) == 0 and k:
+ logger.info(f"teacher cache: starting pass {k // len(files) + 1} over {root}")
+ rows += torch.load(files[k % len(files)])[skip:]
+ skip, k = 0, k + 1
+ while len(rows) >= batch_size:
+ yield collate(rows[:batch_size], device)
+ rows = rows[batch_size:]
diff --git a/training/modules/builders.py b/training/modules/builders.py
index 386eeea..50fa32f 100644
--- a/training/modules/builders.py
+++ b/training/modules/builders.py
@@ -110,8 +110,9 @@ def attach_distillation(model: TrainableTTS, flow_lm: FlowLMModel, args: TrainAr
stamp_state_names(teacher)
# nn.Module.__setattr__ would register an nn.Module value as a submodule,
# pulling the (frozen) teacher into model.parameters()/state_dict() and
- # DDP's broadcast; __dict__ keeps it reachable without that.
- model.__dict__["distill_teacher"] = teacher
+ # DDP's broadcast; __dict__ keeps it reachable without that. A run on a teacher cache
+ # reads precomputed targets: the teacher only seeded the student and is dropped.
+ model.__dict__["distill_teacher"] = None if args.distill_teacher_cache else teacher
# Only the backbone (and conditioning) learn; the per-frame heads keep
# the teacher's weights so single-pass generation stays calibrated.
disable_grad(flow_lm.flow_net)
diff --git a/training/modules/model.py b/training/modules/model.py
index 0a96553..a9fd682 100644
--- a/training/modules/model.py
+++ b/training/modules/model.py
@@ -91,6 +91,7 @@ class TrainableTTS(nn.Module):
update_stats: bool = False,
num_voice_prompt_frames: torch.Tensor
| None = None, # [B] valid voice frames (rest is padding)
+ z_target: torch.Tensor | None = None, # [B, T, dim] cached teacher_z (teacher caches)
) -> tuple[torch.Tensor, dict[str, torch.Tensor]]:
fl = self.flow_lm
C = latents.shape[-1]
@@ -107,15 +108,10 @@ class TrainableTTS(nn.Module):
z = self.backbone_z(fl, *inputs, cfg_dropout=self.training) # [B, T, dim]
- if self.distill_teacher is not None:
+ if self.distill_teacher is not None or z_target is not None:
# Latent CFG distillation: the student's backbone regresses onto the
# teacher's guidance-combined output; flow/EOS heads stay frozen.
- teacher = self.distill_teacher.to(latents.device)
- with torch.no_grad():
- z_t = self.backbone_z(teacher, *inputs, cfg_dropout=False)
- if self.args.distill_cfg_coef != 1.0:
- z_null = self.backbone_z(teacher, *inputs, cfg_dropout=False, force_null=True)
- z_t = z_null + self.args.distill_cfg_coef * (z_t - z_null)
+ z_t = self.teacher_z(*inputs) if z_target is None else z_target
shifted_mask = torch.cat([mask[:, :1], mask[:, :-1]], dim=1)
denom = shifted_mask.sum().clamp(min=1)
@@ -159,6 +155,25 @@ class TrainableTTS(nn.Module):
metrics.update(flow_loss=flow_loss.detach(), eos_loss=eos_loss.detach(), loss=loss.detach())
return loss, metrics
+ @torch.no_grad()
+ def teacher_z(
+ self,
+ normalized_latents: torch.Tensor, # [B, T, C]
+ text_tokens: list[torch.Tensor],
+ voice_latents: torch.Tensor,
+ num_voice_prompt_frames: torch.Tensor | None,
+ ) -> torch.Tensor:
+ """The distillation target [B, T, dim]: the teacher's teacher-forced z, guidance-combined."""
+ teacher = self.distill_teacher
+ assert teacher is not None
+ teacher = teacher.to(normalized_latents.device)
+ inputs = (normalized_latents, text_tokens, voice_latents, num_voice_prompt_frames)
+ z_t = self.backbone_z(teacher, *inputs, cfg_dropout=False)
+ if self.args.distill_cfg_coef != 1.0:
+ z_null = self.backbone_z(teacher, *inputs, cfg_dropout=False, force_null=True)
+ z_t = z_null + self.args.distill_cfg_coef * (z_t - z_null)
+ return z_t
+
def _head_distill(self, z: torch.Tensor) -> tuple[torch.Tensor, dict[str, torch.Tensor]]:
"""The new head (flow_lm.flow_net) learns the frozen head's samples for the backbone
outputs `z` [N, dim] of the valid frames."""
diff --git a/training/scripts/build_teacher_cache.py b/training/scripts/build_teacher_cache.py
new file mode 100644
index 0000000..104b3d1
--- /dev/null
+++ b/training/scripts/build_teacher_cache.py
@@ -0,0 +1,125 @@
+"""Build a teacher cache (training/dataloader/teacher_cache.py) for a distillation config.
+
+Runs the config's distillation teacher once over --rows rows of its train_jsonl (rounded up to
+whole files), drawn by the training loader with the config's data settings (same crops, voice
+prompts and text augmentations; seeded by --seed), and stores every row with its guided target.
+Train from it by adding `distill_teacher_cache: OUT` to the same config.
+
+Work splits over --parts processes, e.g. one per GPU (or several per GPU when the loader is the
+bottleneck): part h reads shard h of the manifest and writes the files h, h + parts, ...
+Re-running a part skips the files it already wrote (its loader replays up to there), so a
+killed job resumes; keep the config, --parts and --seed unchanged.
+
+ for h in 0 1 2 3; do
+ CUDA_VISIBLE_DEVICES=$h uv run python -m training.scripts.build_teacher_cache \\
+ training/configs/depth_distill.yaml data/teacher_cache --rows 1000000 \\
+ --part $h --parts 4 &
+ done; wait
+"""
+
+import json
+import logging
+import math
+import time
+from pathlib import Path
+from typing import Annotated
+
+import torch
+import typer
+
+from training.args import load_args
+from training.dataloader import DataLoader, encode_batch
+from training.dataloader.teacher_cache import teacher_rows
+from training.modules.builders import build_models
+from training.train_utils import ensure_train_latents, setup_logging
+
+logger = logging.getLogger("build_teacher_cache")
+app = typer.Typer(pretty_exceptions_show_locals=False)
+
+
+def main(
+ config: str,
+ out: str,
+ rows: Annotated[int, typer.Option(help="rows to cache, rounded up to whole files")],
+ part: int = 0,
+ parts: int = 1,
+ seed: int = 0,
+ batches_per_file: int = 8,
+):
+ setup_logging()
+ torch.backends.cuda.matmul.allow_tf32 = True
+ torch.backends.cuda.enable_cudnn_sdp(False) # as in training
+ args = load_args(config)
+ if not args.distill_cfg_coef > 0:
+ raise SystemExit(f"{config} is not a distillation config (distill_cfg_coef is 0)")
+ args.distill_teacher_cache = "" # this run computes the targets: keep the teacher
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
+ model, mimi, _ = build_models(args)
+ model.to(device).eval()
+ mimi.to(device)
+ ensure_train_latents(args, mimi, device, part, parts)
+
+ root = Path(out)
+ root.mkdir(parents=True, exist_ok=True)
+ rows_per_file = batches_per_file * args.batch_size
+ meta = {
+ "config": config,
+ "train_jsonl": args.data.train_jsonl,
+ "teacher": args.distill_teacher_weights or "a frozen copy of the student",
+ "distill_cfg_coef": args.distill_cfg_coef,
+ "files": math.ceil(rows / rows_per_file),
+ "rows_per_file": rows_per_file,
+ "parts": parts,
+ "seed": seed,
+ }
+ meta_path = root / "meta.json"
+ if meta_path.exists() and json.loads(meta_path.read_text()) != meta:
+ raise SystemExit(f"{meta_path} was written with other settings: {meta_path.read_text()}")
+ tmp = root / f"meta.json.{part}.tmp"
+ tmp.write_text(json.dumps(meta, indent=1))
+ tmp.rename(meta_path)
+
+ loader = iter(
+ DataLoader(
+ args.data.train_jsonl,
+ model.flow_lm.conditioner.tokenizer.encode,
+ args.batch_size,
+ mimi.sample_rate,
+ mimi.frame_rate,
+ args.data.max_duration_sec,
+ args.data.max_voice_prompt_sec,
+ part,
+ parts,
+ seed=seed + part,
+ shuffle=args.data.shuffle,
+ num_bucket_batches=args.data.num_bucket_batches,
+ prompt_trim_max_sec=args.data.prompt_trim_max_sec,
+ final_punct_dropout=args.data.final_punct_dropout,
+ )
+ )
+ autocast = torch.autocast(
+ device_type=device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"
+ )
+ for g in range(part, meta["files"], parts):
+ path = root / f"{g:06d}.pt"
+ batches = [next(loader) for _ in range(batches_per_file)]
+ if path.exists():
+ continue
+ start = time.time()
+ file_rows = []
+ for batch in batches:
+ latents, mask, voice, num_voice_frames = encode_batch(mimi, batch, device)
+ with autocast:
+ file_rows += teacher_rows(
+ model, latents, mask, batch.text_tokens, voice, num_voice_frames
+ )
+ tmp = path.with_suffix(".tmp")
+ torch.save(file_rows, tmp)
+ tmp.rename(path)
+ logger.info(f"{path}: {len(file_rows)} rows in {time.time() - start:.1f}s")
+ logger.info(f"part {part} of {parts} done")
+
+
+if __name__ == "__main__":
+ app()
diff --git a/training/tests/test_smoke.py b/training/tests/test_smoke.py
index 01b7b77..ce0af72 100644
--- a/training/tests/test_smoke.py
+++ b/training/tests/test_smoke.py
@@ -34,6 +34,7 @@ from pocket_tts.utils.config import CONFIGS_DIR, load_config
from training.args import ReflArgs, TrainArgs
from training.checkpointing import EMA
from training.dataloader import DataLoader, Entry
+from training.dataloader.teacher_cache import cached_batches, collate, teacher_rows
from training.modules.builders import head_from_state
from training.modules.model import TrainableTTS
from training.modules.samplers import build_flow
@@ -234,6 +235,49 @@ def test_distill_into_a_narrower_student():
assert model.flow_lm.out_eos.weight.grad is None
+def test_teacher_cache_matches_the_online_teacher(tmp_path: Path):
+ """The loss on cached targets equals the loss with the online teacher on the same batch
+ (padding past each row's frames and voice prompt included), and a student without a
+ teacher trains from the cache files, resuming at the right row."""
+ model = tiny_model("lsd")
+ model.args.distill_cfg_coef = 3.0 # the target differs from the student
+ model.args.text_dropout = model.args.voice_dropout = 0.0
+ model.__dict__["distill_teacher"] = copy.deepcopy(model.flow_lm).requires_grad_(False)
+ model.flow_lm.flow_net.requires_grad_(False)
+ model.flow_lm.out_eos.requires_grad_(False)
+ latents, _, text, voice = make_batch()
+ mask = torch.arange(11)[None, :] < torch.tensor([10, 8, 6])[:, None]
+ voice_frames = torch.tensor([5, 3, 4])
+ online, _ = model(latents, mask, text, voice, num_voice_prompt_frames=voice_frames)
+
+ rows = teacher_rows(model, latents, mask, text, voice, voice_frames)
+ lat, mask2, text2, voice2, voice_frames2, z_target = collate(rows)
+ assert torch.equal(lat[:, :10], latents[:, :10] * mask[:, :10, None])
+ cached, _ = model(
+ lat, mask2, text2, voice2, num_voice_prompt_frames=voice_frames2, z_target=z_target
+ )
+ torch.testing.assert_close(cached, online, rtol=2e-3, atol=0) # targets stored in bf16
+
+ torch.save(rows[:2], tmp_path / "000000.pt") # the rows read: 0 1 | 1 2 | 0 1 | ...
+ torch.save(rows[1:], tmp_path / "000001.pt")
+ (tmp_path / "meta.json").write_text(json.dumps({"files": 2, "rows_per_file": 2}))
+ model.__dict__["distill_teacher"] = None
+ optimizer = build_optimizer(model, model.args, torch.device("cpu"), rank=0)
+ weight = model.flow_lm.transformer.get_parameter("layers.0.linear1.weight")
+ before = weight.detach().clone()
+ loader = cached_batches(tmp_path, 3, rank=0, world_size=1)
+ lat, mask2, text2, voice2, voice_frames2, z_target = next(loader)
+ assert voice2.shape[1] == 5 and voice_frames2.tolist() == [5, 3, 3]
+ loss, _ = model(
+ lat, mask2, text2, voice2, num_voice_prompt_frames=voice_frames2, z_target=z_target
+ )
+ loss.backward()
+ optimizer.step()
+ assert loss.isfinite() and not torch.equal(weight, before)
+ resumed = next(cached_batches(tmp_path, 3, rank=0, world_size=1, skip_rows=3))
+ assert torch.equal(resumed[0], next(loader)[0]) # rows 2 0 1, wrapping into the second pass
+
+
@pytest.mark.parametrize(
"flow_type,loss_name", [("lsd", "mse"), ("drifting", "mse"), ("drifting", "drifting")]
)
diff --git a/training/train.py b/training/train.py
index b2f17d3..8fdd524 100644
--- a/training/train.py
+++ b/training/train.py
@@ -28,7 +28,8 @@ from torch.nn.parallel import DistributedDataParallel as DDP
from pocket_tts.models.mimi import MimiModel
from training.args import TrainArgs, dump_args, load_args, save_args
from training.checkpointing import EMA, latest_checkpoint, load_checkpoint, save_checkpoint
-from training.dataloader import DataLoader, SubprocessDataLoader, encode_batch
+from training.dataloader import DataLoader, SubprocessDataLoader, _prefetch, encode_batch
+from training.dataloader.teacher_cache import cached_batches
from training.distributed import (
average_grads,
avg_across_ranks,
@@ -112,7 +113,8 @@ def setup(config_path: str) -> Run:
"Validation must encode audio directly so its metrics stay exact and "
"comparable; point valid_jsonl at the original manifest."
)
- check_manifest_sizes(args, world_size)
+ if not args.distill_teacher_cache:
+ check_manifest_sizes(args, world_size)
if rank == 0:
save_args(args, run_dir / "args.yaml")
@@ -123,7 +125,8 @@ def setup(config_path: str) -> Run:
p.requires_grad_(False)
model.to(device)
mimi.to(device)
- ensure_train_latents(args, mimi, device, rank, world_size)
+ if not args.distill_teacher_cache:
+ 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")
@@ -178,27 +181,37 @@ def main(config_path: str):
sentence_piece = model.flow_lm.conditioner.tokenizer
tokenize = sentence_piece.encode
- train_data = SubprocessDataLoader(
- args.data.train_jsonl,
- sentence_piece,
- args.batch_size,
- mimi.sample_rate,
- mimi.frame_rate,
- args.data.max_duration_sec,
- args.data.max_voice_prompt_sec,
- rank,
- run.world_size,
- # Fold the resume step into the seed: the loader keeps no state
- # across restarts, so a fixed seed would replay the same
- # permutation from the top and bias coverage toward its head.
- seed=args.seed + start_step,
- shuffle=args.data.shuffle,
- num_procs=args.data.loader_procs,
- num_bucket_batches=args.data.num_bucket_batches,
- prompt_trim_max_sec=args.data.prompt_trim_max_sec,
- final_punct_dropout=args.data.final_punct_dropout,
- )
- train_loader = iter(train_data)
+ cache = train_data = None
+ if args.distill_teacher_cache:
+ # Rows and targets from the cache: no loader, no Mimi encoding, no teacher.
+ skip = start_step * args.grad_accum_steps * args.batch_size
+ cache = _prefetch(
+ cached_batches(
+ args.distill_teacher_cache, args.batch_size, rank, run.world_size, skip, device
+ )
+ )
+ else:
+ train_data = SubprocessDataLoader(
+ args.data.train_jsonl,
+ sentence_piece,
+ args.batch_size,
+ mimi.sample_rate,
+ mimi.frame_rate,
+ args.data.max_duration_sec,
+ args.data.max_voice_prompt_sec,
+ rank,
+ run.world_size,
+ # Fold the resume step into the seed: the loader keeps no state
+ # across restarts, so a fixed seed would replay the same
+ # permutation from the top and bias coverage toward its head.
+ seed=args.seed + start_step,
+ shuffle=args.data.shuffle,
+ num_procs=args.data.loader_procs,
+ num_bucket_batches=args.data.num_bucket_batches,
+ prompt_trim_max_sec=args.data.prompt_trim_max_sec,
+ final_punct_dropout=args.data.final_punct_dropout,
+ )
+ train_loader = iter(train_data)
autocast = torch.autocast(
device_type=device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"
@@ -227,24 +240,36 @@ def main(config_path: str):
group["lr"] = lr * group.get("lr_scale", 1.0)
optimizer.zero_grad()
for micro in range(args.grad_accum_steps):
- batch = next(train_loader)
- latents, mask, voice_prompt_latents, num_voice_prompt_frames = encode_batch(
- mimi, batch, device
- )
+ if cache is not None:
+ (
+ latents,
+ mask,
+ text_tokens,
+ voice_prompt_latents,
+ num_voice_prompt_frames,
+ z_target,
+ ) = next(cache)
+ else:
+ batch = next(train_loader)
+ latents, mask, voice_prompt_latents, num_voice_prompt_frames = encode_batch(
+ mimi, batch, device
+ )
+ text_tokens, z_target = batch.text_tokens, None
with autocast:
loss, metrics = run.wrapped(
latents,
mask,
- batch.text_tokens,
+ text_tokens,
voice_prompt_latents,
update_stats=step < args.stats_ema_steps,
num_voice_prompt_frames=num_voice_prompt_frames,
+ z_target=z_target,
)
if refl_rewards is not None:
reward_loss, refl_stats = refl_loss(
model,
sentence_piece.decode,
- batch.text_tokens,
+ text_tokens,
voice_prompt_latents,
num_voice_prompt_frames,
mask,
@@ -285,7 +310,8 @@ def main(config_path: str):
args.run_dir, step + 1, model, optimizer, ema, args.num_ckpt_keep, mimi
)
progress.log("checkpoint", step + 1)
- train_data.close()
+ if train_data is not None:
+ train_data.close()
shutdown_distributed()
return
@@ -318,7 +344,9 @@ def main(config_path: str):
):
write_samples(model, mimi, tokenize, args, args.run_dir, step + 1, sample_voice, device)
- if (step + 1) % args.valid_freq == 0 and args.data.valid_jsonl:
+ # A teacher-cache run has no teacher to compute the validation targets with.
+ valid = args.data.valid_jsonl and not args.distill_teacher_cache
+ if valid and (step + 1) % args.valid_freq == 0:
valid_metrics = validate(model, mimi, args, device, rank, run.world_size, step + 1)
progress.log("valid", step + 1, valid_metrics)
model.train()
@@ -335,7 +363,8 @@ def main(config_path: str):
if device.type == "cuda":
logger.info(f"peak GPU memory {torch.cuda.max_memory_allocated() / 2**30:.1f} GiB")
logger.info("done")
- train_data.close()
+ if train_data is not None:
+ train_data.close()
shutdown_distributed()