"""Shared building blocks for training, evaluation, export and mining.""" from __future__ import annotations from pathlib import Path import numpy as np import torch from torch.utils.data import DataLoader from vitakws.config import feature_config from vitakws.data.augment import AugmentConfig, Augmenter from vitakws.data.dataset import KwsDataset from vitakws.data.manifest import Item, LabelMap from vitakws.features import LogMel from vitakws.models import BCResNet def pick_device(name: str = "auto") -> torch.device: if name != "auto": return torch.device(name) if torch.cuda.is_available(): return torch.device("cuda") return torch.device("cpu") def build_label_map(cfg: dict) -> LabelMap: return LabelMap(cfg["data"]["classes"], cfg["data"]["label_map"]) def build_model(cfg: dict) -> BCResNet: m = cfg["model"] return BCResNet( num_classes=len(cfg["data"]["classes"]), tau=m["tau"], n_mels=cfg["features"]["n_mels"], ssn_groups=m["ssn_groups"], dropout=m["dropout"], causal=m["causal"], time_pool=m["time_pool"], ) def save_checkpoint(path: Path, model: BCResNet, cfg: dict, **extra) -> None: path.parent.mkdir(parents=True, exist_ok=True) tmp = path.with_suffix(path.suffix + ".tmp") torch.save({"model": model.state_dict(), "config": cfg, **extra}, tmp) tmp.replace(path) def load_checkpoint(path: str | Path, device: str | torch.device = "cpu"): """Returns (model in eval mode, front end, config, label map, raw checkpoint dict).""" ckpt = torch.load(str(path), map_location="cpu", weights_only=False) cfg = ckpt["config"] model = build_model(cfg) model.load_state_dict(ckpt["model"]) model.to(device).eval() frontend = LogMel(feature_config(cfg)).to(device).eval() return model, frontend, cfg, build_label_map(cfg), ckpt def load_matching_weights(model: BCResNet, path: str | Path) -> list[str]: """Initialise from a checkpoint, skipping tensors whose shape differs. Lets a model pre-trained on other classes (or another keyword) seed a new one: everything except the mismatched classifier is reused. Returns the names that were skipped. """ source = torch.load(str(path), map_location="cpu", weights_only=False)["model"] target = model.state_dict() usable = {k: v for k, v in source.items() if k in target and v.shape == target[k].shape} model.load_state_dict(usable, strict=False) return sorted(set(target) - set(usable)) def eval_dataset(items: list[Item], label_map: LabelMap, cfg: dict) -> KwsDataset: """Deterministic windows with only the noise floor added (no random augmentation).""" sr = cfg["features"]["sample_rate"] floor = AugmentConfig(enabled=False, floor_dbfs=tuple(cfg["augment"]["floor_dbfs"])) return KwsDataset( items, label_map, sr, cfg["data"]["window_seconds"], augmenter=Augmenter(floor, sr), train=False, seed=cfg["seed"], align_short_negatives=cfg["data"].get("align_short_negatives", 0.0), ) @torch.no_grad() def predict( model: torch.nn.Module, frontend: LogMel, dataset: KwsDataset, device: torch.device, batch_size: int = 256, num_workers: int = 0, ) -> tuple[np.ndarray, np.ndarray, float]: """Class probabilities [N, C], targets [N] and mean cross-entropy over a dataset.""" loader = DataLoader(dataset, batch_size=batch_size, shuffle=False, num_workers=num_workers) model.eval() probs, targets, loss_sum = [], [], 0.0 for wave, target, _ in loader: logits = model(frontend(wave.to(device))) loss_sum += torch.nn.functional.cross_entropy( logits, target.to(device), reduction="sum" ).item() probs.append(torch.softmax(logits, dim=1).cpu().numpy()) targets.append(target.numpy()) if not probs: n_cls = len(dataset.label_map.classes) return np.zeros((0, n_cls), np.float32), np.zeros(0, np.int64), float("nan") probs, targets = np.concatenate(probs), np.concatenate(targets) return probs, targets, loss_sum / len(targets)