"""Train or fine-tune BC-ResNet. vitakws-train --config configs/hey_vita.yaml vitakws-train --config configs/hey_vita.yaml --set train.epochs=30 model.tau=3 vitakws-train --config configs/finetune.yaml --set finetune.init_from=runs/base/best.pt """ from __future__ import annotations import argparse import copy import math import sys import time from pathlib import Path import numpy as np import torch import torch.nn.functional as F import yaml from torch.utils.data import DataLoader from vitakws import metrics as M from vitakws.config import augment_config, feature_config, load_config from vitakws.data.augment import Augmenter from vitakws.data.dataset import KwsDataset, balanced_sampler from vitakws.data.manifest import GROUP_FIELDS, Item, read_manifest, summarize from vitakws.engine import ( build_label_map, build_model, eval_dataset, load_checkpoint, load_matching_weights, pick_device, predict, save_checkpoint, ) from vitakws.features import LogMel, spec_augment from vitakws.logging_utils import RunLogger from vitakws.models import BCResNet class ModelEma: """Exponential moving average of the weights; the averaged copy is what gets evaluated.""" def __init__(self, model: torch.nn.Module, decay: float): self.decay = decay self.updates = 0 self.model = copy.deepcopy(model).eval() for p in self.model.parameters(): p.requires_grad_(False) @torch.no_grad() def update(self, model: torch.nn.Module) -> None: self.updates += 1 # Ramp the decay up so the average is not stuck on the random initial weights. decay = min(self.decay, (1.0 + self.updates) / (10.0 + self.updates)) source = model.state_dict() for name, value in self.model.state_dict().items(): if value.dtype.is_floating_point: # lerp leaves a value untouched when both sides are equal, so frozen # layers stay bit-identical to the checkpoint they were loaded from. value.lerp_(source[name].detach(), 1.0 - decay) else: value.copy_(source[name]) def lr_at(step: int, total: int, warmup: int, base_lr: float) -> float: """Linear warm-up, then cosine decay to zero.""" if step < warmup: return base_lr * (step + 1) / max(warmup, 1) progress = (step - warmup) / max(total - warmup, 1) return 0.5 * base_lr * (1.0 + math.cos(math.pi * min(progress, 1.0))) def loss_fn( logits: torch.Tensor, target: torch.Tensor, label_smoothing: float, focal_gamma: float, class_weights: torch.Tensor | None, ) -> torch.Tensor: loss = F.cross_entropy( logits, target, weight=class_weights, label_smoothing=label_smoothing, reduction="none" ) if focal_gamma > 0: p_true = torch.softmax(logits.detach(), dim=1).gather(1, target[:, None]).squeeze(1) loss = loss * (1.0 - p_true) ** focal_gamma return loss.mean() def freeze_for_finetune(model: BCResNet, freeze_stages: int) -> list[torch.nn.Module]: """Freeze the head and the first ``freeze_stages`` stages; returns the frozen modules.""" if freeze_stages <= 0: return [] frozen: list[torch.nn.Module] = [model.head] for stage in model.stage_modules()[:freeze_stages]: frozen += stage for module in frozen: for p in module.parameters(): p.requires_grad_(False) return frozen def build_optimizer(model: BCResNet, cfg: dict) -> torch.optim.Optimizer: t, mult = cfg["train"], cfg["finetune"]["backbone_lr_mult"] head = [p for p in model.classifier.parameters() if p.requires_grad] head_ids = {id(p) for p in head} body = [p for p in model.parameters() if p.requires_grad and id(p) not in head_ids] groups = [{"params": body, "lr_mult": mult}, {"params": head, "lr_mult": 1.0}] groups = [g for g in groups if g["params"]] if t["optimizer"] == "sgd": return torch.optim.SGD( groups, lr=t["lr"], momentum=t["momentum"], weight_decay=t["weight_decay"], nesterov=True, ) if t["optimizer"] == "adamw": return torch.optim.AdamW(groups, lr=t["lr"], weight_decay=t["weight_decay"]) raise ValueError(f"train.optimizer must be 'sgd' or 'adamw', got {t['optimizer']!r}") def evaluate_split( model: torch.nn.Module, frontend: LogMel, dataset: KwsDataset, device: torch.device, target_far: float, prefix: str, num_workers: int = 0, ) -> tuple[dict[str, float], dict]: """Flat scalar metrics (for logging) and the raw arrays (for reports).""" probs, targets, loss = predict(model, frontend, dataset, device, num_workers=num_workers) label_map = dataset.label_map out = {f"{prefix}/loss": loss} if len(targets) == 0: return out, {"probs": probs, "targets": targets} clip = M.clip_metrics(probs, targets, label_map.keyword_ids, target_far) out.update({f"{prefix}/{k}": v for k, v in clip.items() if not k.startswith("num_")}) for name, value in M.per_class_recall(probs, targets, label_map.classes).items(): out[f"{prefix}/recall/{name}"] = value scores = M.keyword_scores(probs, label_map.keyword_ids) is_pos = np.isin(targets, label_map.keyword_ids) threshold = clip["threshold_at_far"] groups = {} if not math.isnan(threshold): for field in (*GROUP_FIELDS, "label"): values = [getattr(i, field) for i in dataset.items] groups[field] = M.grouped_rates(scores, is_pos, values, threshold) for value, rates in groups[field].items(): if rates["num_pos"]: out[f"{prefix}/frr/{field}/{value}"] = rates["frr"] if rates["num_neg"]: out[f"{prefix}/far/{field}/{value}"] = rates["far"] raw = { "probs": probs, "targets": targets, "scores": scores, "is_pos": is_pos, "groups": groups, "clip": clip, } return out, raw def selection_value(metrics: dict[str, float], name: str) -> float: """Lower is better. Falls back to the loss when the metric is undefined.""" value = metrics.get(f"dev/{name}", float("nan")) if math.isnan(value): return metrics.get("dev/loss", float("inf")) return -value if name == "accuracy" else value def train(cfg: dict) -> dict: torch.manual_seed(cfg["seed"]) np.random.seed(cfg["seed"]) t, d, a = cfg["train"], cfg["data"], cfg["augment"] device = pick_device(t["device"]) run_dir = Path(cfg["output_dir"]) / cfg["run_name"] run_dir.mkdir(parents=True, exist_ok=True) (run_dir / "config.yaml").write_text(yaml.safe_dump(cfg, sort_keys=False, allow_unicode=True)) label_map = build_label_map(cfg) feat_cfg = feature_config(cfg) items = read_manifest(d["manifest"]) train_items: list[Item] = [i for i in items if i.split == "train"] dev_items: list[Item] = [i for i in items if i.split == "dev"] if not train_items: raise ValueError(f"{d['manifest']} has no items with split=train") if not dev_items: raise ValueError(f"{d['manifest']} has no items with split=dev") print(f"train: {summarize(train_items)}") print(f"dev: {summarize(dev_items)}") noise_files = [i.audio for i in train_items if i.kind in a["noise_from_kinds"]] babble_files = [i.audio for i in train_items if i.kind in a.get("babble_from_kinds", [])] augmenter = Augmenter(augment_config(cfg), feat_cfg.sample_rate, noise_files, babble_files) train_set = KwsDataset( train_items, label_map, feat_cfg.sample_rate, d["window_seconds"], augmenter=augmenter, train=True, seed=cfg["seed"], align_short_negatives=d["align_short_negatives"], context_files=[i.audio for i in train_items if i.kind in d["context_from_kinds"]], context_prob=d["context_prob"], context_gap_s=tuple(d["context_gap_s"]), context_gain_db=tuple(d["context_gain_db"]), trail_range=tuple(d["trail_range"]), ) dev_set = eval_dataset(dev_items, label_map, cfg) sampler = balanced_sampler( train_items, d["kind_ratios"], t["steps_per_epoch"] * t["batch_size"], d["window_seconds"], generator=torch.Generator().manual_seed(cfg["seed"]), ) loader = DataLoader( train_set, batch_size=t["batch_size"], sampler=sampler, num_workers=d["num_workers"], drop_last=True, persistent_workers=d["num_workers"] > 0, pin_memory=device.type == "cuda", ) model = build_model(cfg).to(device) frontend = LogMel(feat_cfg).to(device) frozen: list[torch.nn.Module] = [] if cfg["finetune"]["init_from"]: skipped = load_matching_weights(model, cfg["finetune"]["init_from"]) print( f"initialised from {cfg['finetune']['init_from']}; re-initialised: {skipped or 'none'}" ) frozen = freeze_for_finetune(model, cfg["finetune"]["freeze_stages"]) n_frames = feat_cfg.num_frames(train_set.window) print( f"BC-ResNet-{cfg['model']['tau']:g}: {model.num_parameters():,} parameters, " f"{len(label_map.classes)} classes, input {feat_cfg.n_mels}x{n_frames} frames, " f"receptive field {model.receptive_field_frames()} frames, device {device}" ) teacher = None teacher_frontend, teacher_feat_cfg = None, None if t["distill_from"]: # "a.pt" or a weighted ensemble "a.pt*0.85+b.pt*0.15" (teacher logits = weighted sum of member logits) members = [] for part in t["distill_from"].split("+"): path, w = part.rsplit("*", 1) if "*" in part else (part, None) m_, t_fe, teacher_cfg, _, _ = load_checkpoint(path, device) if teacher_cfg["features"] != cfg["features"]: # cross-feature distillation (e.g. 80-mel teacher -> 40-mel student): the teacher gets its own log-mel of the same audio if teacher_frontend is not None and teacher_cfg["features"] != teacher_feat_cfg: raise ValueError("distill_from: ensemble members must share features") teacher_frontend, teacher_feat_cfg = t_fe.to(device).eval(), teacher_cfg["features"] members.append((m_.eval(), None if w is None else float(w))) if any(w is None for _, w in members): members = [(m_, 1.0 / len(members)) for m_, _ in members] class _Ensemble(torch.nn.Module): def __init__(self, ms): super().__init__() self.ms = torch.nn.ModuleList([m_ for m_, _ in ms]) self.ws = [w for _, w in ms] def forward(self, x): return sum(w * m_(x) for m_, w in zip(self.ms, self.ws)) def num_parameters(self): return sum(m_.num_parameters() for m_ in self.ms) teacher = members[0][0] if len(members) == 1 else _Ensemble(members).eval() print(f"distilling from {t['distill_from']} ({teacher.num_parameters():,} parameters)") optimizer = build_optimizer(model, cfg) ema = ModelEma(model, t["ema_decay"]) if t["ema_decay"] > 0 else None class_weights = ( torch.tensor(t["class_weights"], dtype=torch.float32, device=device) if t["class_weights"] else None ) use_amp = t["amp"] and device.type == "cuda" scaler = torch.amp.GradScaler(device.type, enabled=use_amp) aug_gen = torch.Generator().manual_seed(cfg["seed"] + 1) logger = RunLogger(run_dir, cfg) logger.summary({"params": model.num_parameters()}) total_steps = t["epochs"] * t["steps_per_epoch"] warmup_steps = t["warmup_epochs"] * t["steps_per_epoch"] step, best_value, best = 0, float("inf"), {} for epoch in range(1, t["epochs"] + 1): model.train() for module in frozen: module.eval() # keep batch-norm statistics of frozen layers fixed seen, loss_sum, correct, started = 0, 0.0, 0, time.time() for wave, target, _ in loader: lr = lr_at(step, total_steps, warmup_steps, t["lr"]) for group in optimizer.param_groups: group["lr"] = lr * group["lr_mult"] wave, target = wave.to(device, non_blocking=True), target.to(device, non_blocking=True) with torch.no_grad(): feats = frontend(wave) if a["enabled"]: feats = spec_augment( feats, freq_masks=a["spec_freq_masks"], freq_width=a["spec_freq_width"], time_masks=a["spec_time_masks"], time_width=a["spec_time_width"], generator=aug_gen, ) with torch.autocast(device.type, enabled=use_amp): logits = model(feats) loss = loss_fn( logits.float(), target, t["label_smoothing"], t["focal_gamma"], class_weights ) if teacher is not None: with torch.no_grad(), torch.autocast(device.type, enabled=use_amp): teacher_logits = teacher(teacher_frontend(wave) if teacher_frontend is not None else feats) temp = t["distill_temp"] soft = F.kl_div( F.log_softmax(logits.float() / temp, dim=1), F.softmax(teacher_logits.float() / temp, dim=1), reduction="batchmean", ) * temp**2 loss = (1 - t["distill_weight"]) * loss + t["distill_weight"] * soft optimizer.zero_grad(set_to_none=True) scaler.scale(loss).backward() if t["grad_clip"] > 0: scaler.unscale_(optimizer) torch.nn.utils.clip_grad_norm_(model.parameters(), t["grad_clip"]) scaler.step(optimizer) scaler.update() if ema is not None: ema.update(model) step += 1 seen += len(target) loss_sum += loss.item() * len(target) correct += (logits.argmax(dim=1) == target).sum().item() if step % t["log_every"] == 0: logger.log({"train/loss": loss.item(), "train/lr": lr, "epoch": epoch}, step) eval_model = ema.model if ema is not None else model dev_metrics, _ = evaluate_split( eval_model, frontend, dev_set, device, t["select_far"], "dev", d["num_workers"] ) epoch_metrics = { "epoch": epoch, "train/epoch_loss": loss_sum / max(seen, 1), "train/epoch_accuracy": correct / max(seen, 1), "train/samples_per_second": seen / max(time.time() - started, 1e-9), **dev_metrics, } logger.log(epoch_metrics, step) value = selection_value(dev_metrics, t["select_metric"]) save_checkpoint(run_dir / "last.pt", eval_model, cfg, epoch=epoch, metrics=dev_metrics) marker = "" if value < best_value: best_value, best = value, {"epoch": epoch, **dev_metrics} save_checkpoint(run_dir / "best.pt", eval_model, cfg, epoch=epoch, metrics=dev_metrics) marker = " * best" print( f"epoch {epoch:3d}/{t['epochs']} loss {epoch_metrics['train/epoch_loss']:.4f} " f"acc {epoch_metrics['train/epoch_accuracy']:.3f} " f"dev loss {dev_metrics['dev/loss']:.4f} " f"dev acc {dev_metrics.get('dev/accuracy', float('nan')):.3f} " f"dev FRR@FAR={t['select_far']:g} {dev_metrics.get('dev/frr_at_far', float('nan')):.4f}" f"{marker}" ) logger.summary({"params": model.num_parameters(), **{f"best/{k}": v for k, v in best.items()}}) if cfg["wandb"]["log_checkpoint"]: logger.artifact(f"{cfg['run_name']}-best", run_dir / "best.pt") logger.close() print(f"best epoch {best.get('epoch')}; checkpoints in {run_dir}") return best def main(argv: list[str] | None = None) -> None: parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawTextHelpFormatter ) parser.add_argument("--config", help="YAML config; defaults are in vitakws/config.py") parser.add_argument( "--set", nargs="*", default=[], metavar="KEY=VALUE", help="config overrides" ) args = parser.parse_args(argv) # Show each epoch line as it happens, also when output goes to a file or pipe. sys.stdout.reconfigure(line_buffering=True) train(load_config(args.config, args.set)) if __name__ == "__main__": main()