Skip to content

A TTS that fits in your CPU (and pocket)

Python
17.0 KB
Raw Blame
"""Train a CALM-style TTS on top of the pocket-tts modules.

Usage:
    torchrun --nproc-per-node 8 -m training.train training/configs/scratch.yaml
"""

import os

# Utterances are variable-length, so the default caching allocator fragments and
# a batch that fits can still fail to allocate; expandable segments keep the
# reserved memory flat at no throughput cost. Set only from the entry point,
# and before torch is imported: the allocator reads it when it initializes.
if __name__ == "__main__":
    os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")

import logging
import multiprocessing
import signal
import sys
import time
from dataclasses import dataclass
from pathlib import Path
from types import FrameType

import torch
from torch import nn
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, _prefetch, encode_batch
from training.dataloader.teacher_cache import cached_batches
from training.distributed import (
    average_grads,
    avg_across_ranks,
    exit_training,
    get_rank,
    get_world_size,
    init_distributed,
    is_torchrun,
)
from training.modules.builders import build_models
from training.modules.model import TrainableTTS
from training.refl import Rewards, refl_loss
from training.train_utils import (
    ProgressLog,
    _compile_models,
    add_file_logging,
    build_optimizer,
    check_manifest_sizes,
    ensure_train_latents,
    git_commit,
    lr_at,
    rss_gib,
    setup_logging,
    write_samples,
)

logger = logging.getLogger("train")

VERBOSE_STEPS = 10  # log every step at the start of a run, then every log_freq


@dataclass
class Run:
    """Everything the training loop needs, assembled before the first step."""

    args: TrainArgs
    model: TrainableTTS  # unwrapped, for EMA/checkpointing
    wrapped: nn.Module  # DDP-wrapped when distributed, else the model itself
    mimi: MimiModel
    optimizer: torch.optim.Optimizer
    ema: EMA | None
    start_step: int
    device: torch.device
    rank: int
    world_size: int
    progress: ProgressLog


def setup(config_path: str) -> Run:
    """Resolve the config, build the models, restore any checkpoint."""
    setup_logging()
    torch.backends.cuda.matmul.allow_tf32 = True  # fp32 islands (Mimi encode)
    # cuDNN's bf16 SDPA backward emits NaN at larger batch shapes and is not faster.
    torch.backends.cuda.enable_cudnn_sdp(False)
    args = load_args(config_path)
    device = init_distributed()
    rank, world_size = get_rank(), get_world_size()
    torch.manual_seed(args.seed + rank)
    run_dir = args.run_dir
    log_path = add_file_logging(run_dir, rank)
    progress = ProgressLog(run_dir / "progress.jsonl", enabled=rank == 0)
    if rank == 0:
        logger.info(f"logging to {log_path}")
        gpu = torch.cuda.get_device_name(device) if device.type == "cuda" else "cpu"
        logger.info(f"torch {torch.__version__} | {device} ({gpu}) | world size {world_size}")
        logger.info(f"resolved config from {config_path}:\n{dump_args(args).rstrip()}")

    for name, path in (
        ("train_jsonl", args.data.train_jsonl),
        ("valid_jsonl", args.data.valid_jsonl),
    ):
        if path and not Path(path).exists():
            raise SystemExit(
                f"{name} not found: {path}\n"
                "Prepare a dataset first, e.g.:\n"
                "    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 not args.distill_teacher_cache:
        check_manifest_sizes(args, world_size)
    if rank == 0:
        save_args(args, run_dir / "args.yaml")

    model, mimi, _config = build_models(args)
    if args.freeze_head:
        for name, p in model.named_parameters():
            if "flow_net." in name:
                p.requires_grad_(False)
    model.to(device)
    mimi.to(device)
    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")

    optimizer = build_optimizer(model, args, device, rank)
    ema = EMA(model, args.ema_decay) if args.ema_decay > 0 else None

    start_step = 0
    ckpt = latest_checkpoint(run_dir)
    if ckpt is not None:
        start_step = load_checkpoint(ckpt, model, optimizer, ema)
    progress.log(
        "run_start",
        start_step,
        config=config_path,
        world_size=world_size,
        max_steps=args.max_steps,
        commit=git_commit(),
    )

    wrapped: nn.Module = model
    if is_torchrun() and args.refl.enabled:
        # REFL averages its gradients itself; the ranks start from rank 0's weights, as under DDP.
        for t in model.state_dict().values():
            torch.distributed.broadcast(t, 0)
    elif is_torchrun():
        wrapped = DDP(model, device_ids=[device.index], find_unused_parameters=not args.compile)
    if args.compile:
        _compile_models(model, mimi)

    return Run(
        args=args,
        model=model,
        wrapped=wrapped,
        mimi=mimi,
        optimizer=optimizer,
        ema=ema,
        start_step=start_step,
        device=device,
        rank=rank,
        world_size=world_size,
        progress=progress,
    )


def main(config_path: str):
    run = setup(config_path)
    # Unpacked for the hot loop; the thin ones stay run.* at their call sites.
    args, model, mimi = run.args, run.model, run.mimi
    optimizer, ema, device, rank = run.optimizer, run.ema, run.device, run.rank
    progress, start_step = run.progress, run.start_step

    sentence_piece = model.flow_lm.conditioner.tokenizer
    tokenize = sentence_piece.encode
    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"
    )
    refl_rewards = Rewards(args.refl, device, mimi) if args.refl.enabled else None
    model.train()
    # scancel sends SIGTERM 30s (KillWait) before SIGKILL; finish the step and
    # checkpoint inside that window so a cancelled job resumes losslessly.
    stop_requested = False

    def _request_stop(signum: int, frame: FrameType | None):
        nonlocal stop_requested
        stop_requested = True

    signal.signal(signal.SIGTERM, _request_stop)
    signal.signal(signal.SIGUSR1, _request_stop)
    # graceful stop with no 30 s deadline: `touch <run_dir>/STOP`, the run checkpoints after
    # its current step and exits. A STOP left from the last stop is renamed so a resume runs.
    _stop_file = os.path.join(args.run_dir, "STOP")
    if rank == 0 and os.path.exists(_stop_file):
        os.rename(_stop_file, f"{_stop_file}.used_{int(time.time())}")
    if run.world_size > 1:
        torch.distributed.barrier()
    if rank == 0:
        logger.info("starting training loop, first step can take a few minutes (compilation etc.)")
    last_log = time.time()
    steps_since_log = 0
    sample_voice = None
    for step in range(start_step, args.max_steps):
        step_start = time.time()
        lr = lr_at(step, args)
        for group in optimizer.param_groups:
            group["lr"] = lr * group.get("lr_scale", 1.0)
        optimizer.zero_grad()
        for micro in range(args.grad_accum_steps):
            # Under DDP, all-reduce only on the last micro-batch. DDP decides at forward time
            # whether the backward synchronizes, so the flag (what DDP.no_sync sets) goes first.
            if isinstance(run.wrapped, DDP):
                run.wrapped.require_backward_grad_sync = micro == args.grad_accum_steps - 1
            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,
                    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,
                    text_tokens,
                    voice_prompt_latents,
                    num_voice_prompt_frames,
                    mask,
                    refl_rewards,
                    args.refl,
                )
                metrics.update(refl_stats)
                if reward_loss is not None:
                    loss = loss + reward_loss
            (loss / args.grad_accum_steps).backward()
        if refl_rewards is not None and run.world_size > 1:
            average_grads([p for p in model.parameters() if p.requires_grad])
        grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), args.optim.max_norm)
        if not torch.isfinite(grad_norm):
            # Stop before the NaN reaches the weights: the run would otherwise
            # keep training and checkpointing garbage, and auto-resume reloads it.
            raise SystemExit(f"non-finite gradient at step {step}")
        optimizer.step()
        if ema is not None:
            ema.update(model)

        stop = torch.tensor(
            float(stop_requested or os.path.exists(os.path.join(args.run_dir, "STOP"))),
            device=device,
        )
        if run.world_size > 1:
            torch.distributed.all_reduce(stop, op=torch.distributed.ReduceOp.MAX)
        if stop.item():
            if rank == 0:
                logger.info(
                    f"termination signal received: checkpointing step {step + 1} before exit"
                )
                save_checkpoint(
                    args.run_dir, step + 1, model, optimizer, ema, args.num_ckpt_keep, mimi
                )
                progress.log("checkpoint", step + 1)
            if train_data is not None:
                train_data.close()
            exit_training()

        steps_since_log += 1
        if rank == 0 and step == start_step and args.compile:
            logger.info(f"first step took {time.time() - step_start:.0f}s, including compilation")

        verbose = step - start_step < VERBOSE_STEPS
        if rank == 0 and (verbose or (step + 1) % args.log_freq == 0):
            now = time.time()
            speed = steps_since_log / (now - last_log)
            last_log, steps_since_log = now, 0
            values = {k: v.item() for k, v in metrics.items() if v.numel() == 1}
            shown = {k: f"{v:.4f}" for k, v in values.items()}
            # Host memory of this process and of its children (the dataloader processes): a
            # steady climb over a long run points at a leak before the node starts swapping.
            rss, child_rss = (
                rss_gib(os.getpid()),
                sum(rss_gib(p.pid) for p in multiprocessing.active_children() if p.pid),
            )
            logger.info(
                f"step {step + 1} | lr {lr:.2e} | grad {grad_norm:.2f} | {speed:.2f} it/s | "
                f"rss {rss:.1f}+{child_rss:.1f} GiB | {shown}"
            )
            progress.log(
                "train",
                step + 1,
                values,
                lr=lr,
                grad_norm=grad_norm.item(),
                it_s=speed,
                rss_gib=rss,
                child_rss_gib=child_rss,
            )
        if rank == 0 and step - start_step == VERBOSE_STEPS - 1:
            logger.info(f"per-step logging done, logging every {args.log_freq} steps from now on")

        if sample_voice is None:
            n = int(num_voice_prompt_frames[0])
            sample_voice = voice_prompt_latents[0, :n].detach().clone()
        if (
            rank == 0
            and args.sample_sentences
            and args.sample_freq > 0
            and (step + 1) % args.sample_freq == 0
        ):
            write_samples(model, mimi, tokenize, args, args.run_dir, step + 1, sample_voice, device)

        # 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()

        if rank == 0 and (step + 1) % args.ckpt_freq == 0:
            save_checkpoint(args.run_dir, step + 1, model, optimizer, ema, args.num_ckpt_keep, mimi)
            progress.log("checkpoint", step + 1)

    if rank == 0:
        save_checkpoint(
            args.run_dir, args.max_steps, model, optimizer, ema, args.num_ckpt_keep, mimi
        )
        progress.log("checkpoint", args.max_steps)
        if device.type == "cuda":
            logger.info(f"peak GPU memory {torch.cuda.max_memory_allocated() / 2**30:.1f} GiB")
        logger.info("done")
    if train_data is not None:
        train_data.close()
    exit_training()


@torch.no_grad()
def validate(
    model: TrainableTTS,
    mimi: MimiModel,
    args: TrainArgs,
    device: torch.device,
    rank: int,
    world_size: int,
    step: int,
) -> dict[str, float]:
    model.eval()
    tokenize = model.flow_lm.conditioner.tokenizer.encode
    loader = iter(
        DataLoader(
            args.data.valid_jsonl,
            tokenize,
            args.batch_size,
            mimi.sample_rate,
            mimi.frame_rate,
            args.data.max_duration_sec,
            args.data.max_voice_prompt_sec,
            rank,
            world_size,
            seed=0,
            shuffle=False,
        )
    )
    autocast = torch.autocast(
        device_type=device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"
    )
    totals: dict[str, float] = {}
    n = 0
    for _ in range(args.num_valid_batches):
        try:
            batch = next(loader)
        except StopIteration:
            break
        latents, mask, voice_prompt_latents, num_voice_prompt_frames = encode_batch(
            mimi, batch, device
        )
        with autocast:
            _, metrics = model(
                latents,
                mask,
                batch.text_tokens,
                voice_prompt_latents,
                num_voice_prompt_frames=num_voice_prompt_frames,
            )
        for k, v in metrics.items():
            if v.numel() == 1:
                totals[k] = totals.get(k, 0.0) + v.item()
        n += 1
    averaged = {k: avg_across_ranks(v / max(1, n)) for k, v in totals.items()}
    if rank == 0:
        shown = {k: f"{v:.4f}" for k, v in averaged.items()}
        logger.info(f"valid @ step {step}: {shown}")
    return averaged


if __name__ == "__main__":
    assert len(sys.argv) == 2, "usage: python -m training.train <config.yaml>"
    main(sys.argv[1])