File size: 4,184 Bytes
a1fe2e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
"""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)