muaalem-streaming / train.py
mahmud71's picture
Muaalem streaming: INT8 ONNX, source and model card
21f5301 verified
Raw History Blame Contribute Delete
19 kB
"""Fine-tunes Muaalem mini to stream (see README and the plan doc).
Starts from Muaalem mini's weights (or the latest checkpoint found), and
trains with CTC loss against today's model's letters, each batch at a random
chunk size, every frame seeing only its chunk and `--left` frames before it.
Stops by itself after `--hours` and saves everything needed to continue
exactly where it left off; run the same command again to continue.
# one GPU, or CPU for a quick try
python train.py --data DATA --out OUT [--hours 6]
# two GPUs (Kaggle's T4 x2)
torchrun --nproc_per_node=2 train.py --data DATA --out OUT --hours 6
DATA: the output of prepare_data.py (train/, heldout/, norm_stats.json).
OUT: ckpt_latest.pt (everything), best.pt (averaged weights only, the best
progress check so far), log.jsonl.
--resume-from DIR ...: more places to look for ckpt_latest.pt (Kaggle mounts
the previous session's output under /kaggle/input).
--run TAG: a separate run (checkpoint ckpt_TAG_latest.pt), so it never
resumes another run's checkpoint by mistake.
--init NAME: with no checkpoint of this run yet, start from the averaged
weights in the first file called NAME (e.g. best.pt) under --resume-from.
--augment SHARE: make that share of the training pieces reel-like
(augment.py); progress checks then also score reel-like held-out pieces.
"""
from __future__ import annotations
import argparse
import io
import json
import math
import os
import random
import time
from pathlib import Path
import numpy as np
import pyarrow.parquet as pq
import soundfile as sf
import torch
import torch.distributed as dist
import torch.nn.functional as F
from torch.utils.data import DataLoader, IterableDataset, get_worker_info
from augment import degrade, reel_like
from features import Fbank, NormStats, running_normalize, stack_pairs
from streaming_model import StreamingMuaalem, download, load_muaalem
from units import edit_distance
# -- data ---------------------------------------------------------------------
def row_groups(folder: Path) -> list[tuple[str, int]]:
out = []
for path in sorted(folder.glob("*.parquet")):
for g in range(pq.ParquetFile(path).num_row_groups):
out.append((str(path), g))
return out
def read_group(path: str, group: int) -> list[tuple[np.ndarray, bytes]]:
table = pq.ParquetFile(path).read_row_group(group, columns=["flac", "labels"])
out = []
for flac, labels in zip(table.column("flac").to_pylist(), table.column("labels").to_pylist()):
samples, _ = sf.read(io.BytesIO(flac), dtype="int16")
out.append((samples, labels))
return out
class Pieces(IterableDataset):
"""Streams batches of training pieces.
Each epoch shuffles the row groups (seeded by the epoch), shares them
out across GPUs and loader workers, and shuffles pieces through a buffer.
Batches are cut from the buffer sorted by length, so little is padding.
`skip` row groups of the starting epoch are skipped (resuming).
"""
def __init__(self, groups, batch, rank, world, seed, epoch, skip, buffer=512, augment=0.0):
self.augment = augment
self.groups, self.batch = groups, batch
self.rank, self.world, self.seed = rank, world, seed
self.epoch, self.skip, self.buffer = epoch, skip, buffer
def __iter__(self):
info = get_worker_info()
worker, workers = (info.id, info.num_workers) if info else (0, 1)
stride = self.world * workers
me = self.rank * workers + worker
epoch, skip = self.epoch, self.skip
while True:
order = list(range(len(self.groups)))
random.Random(self.seed + epoch).shuffle(order)
rng = random.Random(self.seed * 1000 + epoch * 100 + me)
pool = []
for k in range(skip, len(order)):
if k % stride != me:
continue
pool.extend(read_group(*self.groups[order[k]]))
while len(pool) >= self.buffer:
yield from self._drain(pool, rng, epoch, k + 1, keep=self.buffer // 2)
yield from self._drain(pool, rng, epoch, len(order), keep=0)
epoch, skip = epoch + 1, 0
def _drain(self, pool, rng, epoch, position, keep):
rng.shuffle(pool)
take = pool[keep:]
del pool[keep:]
take.sort(key=lambda p: len(p[0]))
batches = [take[i : i + self.batch] for i in range(0, len(take), self.batch)]
rng.shuffle(batches)
for b in batches:
if len(b) == self.batch:
batch = collate(b)
if self.augment:
# Here in the loader workers, on the CPU, ahead of the GPU:
# FFTs of many lengths on the GPU broke cuFFT (run r2-1).
g = torch.Generator().manual_seed(rng.randrange(2**62))
batch["audio"] = reel_like(batch["audio"], batch["samples"], g, share=self.augment)
yield batch | {"epoch": epoch, "position": position}
def collate(pieces):
lengths = torch.tensor([len(a) for a, _ in pieces])
audio = torch.zeros(len(pieces), int(lengths.max()))
for i, (a, _) in enumerate(pieces):
audio[i, : len(a)] = torch.from_numpy(a.astype(np.float32) / 32768)
labels = [torch.tensor(list(l), dtype=torch.long) for _, l in pieces]
return {
"audio": audio,
"samples": lengths,
"targets": torch.cat(labels),
"target_lengths": torch.tensor([len(l) for l in labels]),
}
def heldout_set(folder: Path, count: int) -> list[tuple[np.ndarray, bytes]]:
out = []
for path, g in row_groups(folder):
out.extend(read_group(path, g))
if len(out) >= count:
break
return out[:count]
# -- model inputs ---------------------------------------------------------------
def model_inputs(fbank, stats, audio, samples, chunk):
raw = fbank(audio)
frames = torch.tensor([Fbank.frames(int(s)) for s in samples], device=audio.device)
frames = frames - frames % 2
features = stack_pairs(running_normalize(raw, frames, 2 * chunk, stats))
return features, frames // 2
# -- progress check ---------------------------------------------------------------
@torch.no_grad()
def agreement(model, fbank, stats, pieces, chunk, device, batch=8) -> float:
"""Percent of letters the same as today's model's, on held-out reciters."""
model.eval()
errors = total = 0
for i in range(0, len(pieces), batch):
part = collate(pieces[i : i + batch])
features, lengths = model_inputs(fbank, stats, part["audio"].to(device), part["samples"], chunk)
with torch.autocast(device.type, dtype=torch.float16, enabled=device.type == "cuda"):
logits, out_lengths = model(features, lengths.to(device), chunk=chunk)
ids = logits.argmax(-1).cpu()
for k, (_, labels) in enumerate(pieces[i : i + batch]):
seq, prev = [], None
for s in ids[k, : int(out_lengths[k])].tolist():
if s != prev and s != 0:
seq.append(s)
prev = s
errors += edit_distance(list(labels), seq)
total += len(labels)
return 100 * (1 - errors / max(1, total))
# -- checkpoints --------------------------------------------------------------------
def find_checkpoint(places: list[Path], name: str = "ckpt_latest.pt") -> Path | None:
best, best_step = None, -1
for place in places:
for path in place.glob(f"**/{name}") if place.exists() else []:
try:
step = torch.load(path, map_location="cpu", weights_only=False, mmap=True)["step"]
except Exception:
continue
if step > best_step:
best, best_step = path, step
return best
def save(path: Path, payload: dict) -> None:
tmp = path.with_suffix(".tmp")
torch.save(payload, tmp)
os.replace(tmp, path)
def learning_rate(step: int, args) -> float:
if step < args.warmup:
return args.lr * (step + 1) / args.warmup
progress = min(1.0, (step - args.warmup) / max(1, args.steps - args.warmup))
return args.lr * (0.1 + 0.9 * 0.5 * (1 + math.cos(math.pi * progress)))
# -- main ---------------------------------------------------------------------------
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--data", type=Path, required=True)
parser.add_argument("--out", type=Path, required=True)
parser.add_argument("--resume-from", type=Path, nargs="*", default=[])
parser.add_argument("--hours", type=float, default=6.0)
parser.add_argument("--steps", type=int, default=10_000)
parser.add_argument("--batch", type=int, default=8, help="pieces per GPU per round")
parser.add_argument("--accum", type=int, default=2, help="rounds per step")
parser.add_argument("--lr", type=float, default=5e-5)
parser.add_argument("--warmup", type=int, default=500)
parser.add_argument("--chunks", type=int, nargs="+", default=[16, 32, 64])
parser.add_argument("--left", type=int, default=192)
parser.add_argument("--ema", type=float, default=0.999)
parser.add_argument("--eval-every", type=int, default=1000)
parser.add_argument("--eval-pieces", type=int, default=300)
parser.add_argument("--save-minutes", type=float, default=20)
parser.add_argument("--workers", type=int, default=3)
parser.add_argument("--seed", type=int, default=1)
parser.add_argument("--run", default="")
parser.add_argument("--init", default="")
parser.add_argument("--augment", type=float, default=0.0)
args = parser.parse_args()
ckpt_name = f"ckpt_{args.run}_latest.pt" if args.run else "ckpt_latest.pt"
began = time.time()
distributed = "RANK" in os.environ
if distributed:
dist.init_process_group("nccl")
rank, world = dist.get_rank(), dist.get_world_size()
torch.cuda.set_device(int(os.environ["LOCAL_RANK"]))
else:
rank, world = 0, 1
device = torch.device("cuda", torch.cuda.current_device()) if torch.cuda.is_available() else torch.device("cpu")
main_rank = rank == 0
say = (lambda *a: print(*a, flush=True)) if main_rank else (lambda *a: None)
args.out.mkdir(parents=True, exist_ok=True)
model = StreamingMuaalem(load_muaalem(download()), left=args.left).to(device)
model.checkpointing = device.type == "cuda"
ema = {k: v.detach().clone().float() for k, v in model.state_dict().items()}
optimizer = torch.optim.AdamW(model.parameters(), lr=args.lr, betas=(0.9, 0.98), weight_decay=0.01)
scaler = torch.amp.GradScaler(enabled=device.type == "cuda")
fbank = Fbank().to(device)
stats = NormStats.load(args.data / "norm_stats.json").to(device)
step, epoch, position, best = 0, 0, 0, -1.0
found = find_checkpoint([args.out, *args.resume_from], ckpt_name)
start = None if found or not args.init else next(
(q for place in args.resume_from if place.exists() for q in sorted(place.glob(f"**/{args.init}"))), None
)
if args.init and not found and not start:
raise SystemExit(f"--init {args.init}: no such file under {args.resume_from}")
if start:
saved = torch.load(start, map_location="cpu", weights_only=False)
weights = {k: v.float() for k, v in saved.get("ema", saved).items()}
model.load_state_dict(weights)
ema = {k: v.detach().clone().float().to(device) for k, v in model.state_dict().items()}
say(f"starting from {start} (step {saved.get('step')}, {saved.get('percent')}%), memory {args.left} frames")
if found:
state = torch.load(found, map_location="cpu", weights_only=False)
model.load_state_dict(state["model"])
# The checkpoint loads onto the CPU; the averaged weights must sit on
# the model's device, as they do on a fresh start.
ema = {k: v.float().to(device) for k, v in state["ema"].items()}
optimizer.load_state_dict(state["optimizer"])
scaler.load_state_dict(state["scaler"])
step, epoch, position, best = state["step"], state["epoch"], state["position"], state["best"]
random.setstate(state["python_rng"])
torch.set_rng_state(state["torch_rng"])
say(f"resumed from {found} at step {step} (epoch {epoch}, group {position})")
elif not start:
say("starting from Muaalem mini's weights")
net = torch.nn.parallel.DistributedDataParallel(model, device_ids=[device.index]) if distributed else model
groups = row_groups(args.data / "train")
loader = DataLoader(
Pieces(groups, args.batch, rank, world, args.seed, epoch, position, augment=args.augment),
batch_size=None,
num_workers=args.workers,
persistent_workers=args.workers > 0,
prefetch_factor=4 if args.workers > 0 else None,
)
heldout = heldout_set(args.data / "heldout", args.eval_pieces) if main_rank else []
# The same held-out pieces made reel-like, the same way every session.
heldout_reel = []
if args.augment and main_rank:
g = torch.Generator().manual_seed(12345)
for i, (a, labels) in enumerate(heldout):
other = heldout[(i + 1) % len(heldout)][0]
x = torch.from_numpy(a.astype(np.float32) / 32768)
crowd = torch.from_numpy(np.resize(other, len(a)).astype(np.float32) / 32768)
heldout_reel.append(((degrade(x, g, crowd).numpy() * 32767).astype(np.int16), labels))
say(f"{len(groups)} row groups of training pieces; {len(heldout)} held-out pieces; {world} GPU(s)")
def checkpoint() -> None:
if main_rank:
save(
args.out / ckpt_name,
{
"step": step,
"epoch": epoch,
"position": position,
"best": best,
"model": model.state_dict(),
"ema": ema,
"optimizer": optimizer.state_dict(),
"scaler": scaler.state_dict(),
"python_rng": random.getstate(),
"torch_rng": torch.get_rng_state(),
"args": vars(args) | {"data": str(args.data), "out": str(args.out), "resume_from": []},
},
)
def log(entry: dict) -> None:
if main_rank:
entry |= {"step": step, "hours": round((time.time() - began) / 3600, 3)}
with open(args.out / "log.jsonl", "a") as f:
f.write(json.dumps(entry) + "\n")
print(json.dumps(entry), flush=True)
def progress_check() -> None:
nonlocal best
if not main_rank:
return
live = {k: v.clone() for k, v in model.state_dict().items()}
model.load_state_dict({k: v.to(live[k].dtype) for k, v in ema.items()})
clean = agreement(model, fbank, stats, heldout, 32, device)
reel = agreement(model, fbank, stats, heldout_reel, 32, device) if heldout_reel else None
model.load_state_dict(live)
model.train()
log({"check": "letters same as today's model, held-out reciters, chunk 32", "percent": round(clean, 2)}
| ({"reel_like": round(reel, 2)} if reel is not None else {}))
# Clean and reel-like count equally once training on reel-like audio.
score = clean if reel is None else (clean + reel) / 2
if score > best:
best = score
save(args.out / "best.pt", {"ema": ema, "step": step, "percent": clean, "reel_like": reel, "left": args.left, "run": args.run})
if step == 0:
progress_check()
model.train()
last_save = time.time()
batches = iter(loader)
window_loss, window_steps, window_started = 0.0, 0, time.time()
while step < args.steps:
chunk = random.Random(args.seed * 7919 + step).choice(args.chunks) # same on every GPU
for g in optimizer.param_groups:
g["lr"] = learning_rate(step, args)
optimizer.zero_grad(set_to_none=True)
total = 0.0
for k in range(args.accum):
batch = next(batches)
epoch, position = batch["epoch"], batch["position"]
features, lengths = model_inputs(fbank, stats, batch["audio"].to(device), batch["samples"], chunk)
sync = k == args.accum - 1 or not distributed
context = net.no_sync() if not sync else torch.enable_grad()
with context:
with torch.autocast(device.type, dtype=torch.float16, enabled=device.type == "cuda"):
logits, out_lengths = net(features, lengths.to(device), chunk=chunk)
log_probs = F.log_softmax(logits.float(), dim=-1).transpose(0, 1)
loss = F.ctc_loss(
log_probs,
batch["targets"].to(device),
out_lengths.to(device),
batch["target_lengths"].to(device),
blank=0,
reduction="mean",
zero_infinity=True,
)
scaler.scale(loss / args.accum).backward()
total += loss.item() / args.accum
scaler.unscale_(optimizer)
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
scaler.step(optimizer)
scaler.update()
with torch.no_grad():
for name, value in model.state_dict().items():
if value.dtype.is_floating_point:
ema[name].mul_(args.ema).add_(value.float(), alpha=1 - args.ema)
else:
ema[name].copy_(value)
step += 1
window_loss += total
window_steps += 1
if step % 50 == 0 or step == 1:
seconds = time.time() - window_started
log({"loss": round(window_loss / window_steps, 4), "lr": learning_rate(step, args), "steps_per_hour": round(3600 * window_steps / seconds), "chunk": chunk})
window_loss, window_steps, window_started = 0.0, 0, time.time()
if step % args.eval_every == 0:
progress_check()
out_of_time = time.time() - began > args.hours * 3600
due = time.time() - last_save > args.save_minutes * 60
flags = torch.tensor([float(out_of_time), float(due)], device=device)
if distributed:
dist.all_reduce(flags, op=dist.ReduceOp.MAX)
if flags[1] or flags[0]:
checkpoint()
last_save = time.time()
if flags[0]:
say(f"time limit reached at step {step}; run again to continue")
break
if step >= args.steps:
progress_check()
checkpoint()
say(f"finished {step} steps; best held-out agreement {best:.2f}%")
if distributed:
dist.destroy_process_group()
if __name__ == "__main__":
main()