File size: 7,436 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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
#!/usr/bin/env python3
"""Two-stage aurora: stage 1 = cached causal track (10 ms, mean of last 110 frame logits); stage 2 = window verifier
run ONLY at stage-1 candidate times (every 100 ms while stage 1 >= T1MIN), on the 1.5 s window ending D s after the candidate.

  python cascade.py cands S1TAG VER_CKPT VTAG [workers]
      -> runs/vf_eval/casc_S1TAG_VTAG.npz : per item (en_dev2 keyword clips, en_dev2 English negatives, 465 h Vietnamese dev)
         candidate stage-1 scores and stage-2 scores for D in DS.
  python cascade.py sweep S1TAG VTAG
      -> grid of (T1, T2, D): en_dev2 misses, English FA, Vietnamese FA.
Same audio protocol as vf_cache.py (1 s pad, 1e-3 pink floor seeded by the en_dev2 row index)."""
import json, os, subprocess, sys
from multiprocessing import get_context
from pathlib import Path

import numpy as np

T1MIN, DS, SR, WIN = 0.80, (0.0, 0.1, 0.2), 16000, 24000
GRID = int(os.environ.get("CASC_GRID", "10"))  # verifier call spacing in 10 ms steps (10 = 100 ms)
K = "/home/user/Downloads/vita-kws"
V = Path("/data/ext/vita_fa2")
sys.path.insert(0, K + "/plans_local/fa2")
M = FE = None


def track110(d):
    c = np.concatenate([[0.0], np.cumsum(d, dtype=np.float64)]); ks = np.arange(146, len(d)); lo = np.maximum(0, ks + 1 - 110)
    return 1 / (1 + np.exp(-(c[ks + 1] - c[lo]) / (ks + 1 - lo))), (ks + 1) * 160  # prob, end sample


def cands(d):
    """Candidate end samples: every 10th step (100 ms) among steps with prob >= T1MIN."""
    t, e = track110(d)
    idx = np.flatnonzero(t >= T1MIN)
    if len(idx) == 0:
        return np.zeros(0), np.zeros(0, np.int64)
    keep = [idx[0]]
    for k in idx[1:]:
        if k - keep[-1] >= GRID:
            keep.append(k)
    keep = np.array(keep)
    return t[keep], e[keep]


def init(ck):
    global M, FE
    import torch
    torch.set_num_threads(1)
    sys.path.insert(0, K + "/src")
    from vitakws.models.bcresnet import BCResNet
    c = torch.load(ck, map_location="cpu", weights_only=False)
    cfg = c["config"]; mc = cfg["model"]
    M = BCResNet(num_classes=len(cfg["data"]["classes"]), tau=mc["tau"], n_mels=cfg["features"]["n_mels"], ssn_groups=mc["ssn_groups"],
                 dropout=mc["dropout"], causal=mc["causal"], time_pool=mc["time_pool"])
    M.load_state_dict(c["model"]); M.eval()
    sys.path.insert(0, "/home/user/Downloads/aurora_kws_release/inference")
    from features_np import FeatureConfig, logmel_numpy
    f = FeatureConfig(**{k: cfg["features"][k] for k in ("sample_rate", "n_fft", "win_length", "hop_length", "n_mels", "f_min", "f_max", "log_eps")})
    FE = lambda x: logmel_numpy(x, f)


def verify(x, ends):
    """Stage-2 prob for windows ending at each end sample + D (all D)."""
    import torch
    out = np.zeros((len(ends), len(DS)), np.float32)
    if len(ends) == 0:
        return out
    wins = []
    for e in ends:
        for D in DS:
            b = int(e + D * SR)
            seg = x[max(0, b - WIN):min(len(x), b)]
            if len(seg) < WIN:
                seg = np.concatenate([np.zeros(WIN - len(seg), np.float32), seg])
            wins.append(FE(seg)[:, :147])
    X = torch.from_numpy(np.stack(wins)[:, None]).float()
    with torch.no_grad():
        P = np.concatenate([torch.softmax(M(X[i:i + 256]), 1)[:, 1].numpy() for i in range(0, len(X), 256)])
    return P.reshape(len(ends), len(DS))


def pink(n, i):
    r = np.random.default_rng(i)
    sp = np.fft.rfft(r.standard_normal(n)); q = np.fft.rfftfreq(n); q[0] = q[1]
    x = np.fft.irfft(sp / np.sqrt(q), n)
    return (x / (np.sqrt((x ** 2).mean()) + 1e-12)).astype(np.float32)


def job_dev(a):
    i, path, pos, d = a
    s1, ends = cands(d)
    if len(ends) == 0:
        return s1, ends, np.zeros((0, len(DS)), np.float32)
    sys.path.insert(0, K + "/src")
    from vitakws.data import audio
    w = audio.load(path, SR)
    if pos:
        w = np.concatenate([np.zeros(SR, np.float32), w, np.zeros(SR, np.float32)])
    x = (w + 1e-3 * pink(len(w), i)).astype(np.float32)
    if len(x) < WIN:
        x = np.concatenate([np.zeros(WIN - len(x), np.float32), x])
    return s1, ends, verify(x, ends)


def job_vi(a):
    path, npy = a
    s1, ends = cands(np.load(npy))
    if len(ends) == 0:
        return s1, ends, np.zeros((0, len(DS)), np.float32)
    S = []
    for e in ends:  # decode only 1.5 s + D around each candidate
        b0 = max(0, e - WIN) / SR; dur = (min(e, WIN) + max(DS) * SR) / SR
        raw = subprocess.run(["ffmpeg", "-v", "error", "-ss", f"{b0:.3f}", "-t", f"{dur:.3f}", "-i", path, "-f", "f32le", "-ac", "1", "-ar", "16000", "-"],
                             capture_output=True).stdout
        seg = np.frombuffer(raw, np.float32).copy()
        S.append(verify(seg, np.array([min(e, WIN)]))[0])
    return s1, ends, np.array(S, np.float32)


def build(s1tag, ck, vtag, workers):
    import vf_score
    z = vf_score.load(s1tag)
    rows = [json.loads(l) for l in open(K + "/data/aurora/en_dev2.jsonl")]
    NK = {"negative", "negative_speech", "background", "hard_negative"}
    pos_rows = [(i, r) for i, r in enumerate(rows) if r["label"] not in NK]
    neg_rows = [(i, r) for i, r in enumerate(rows) if r["label"] in NK]
    assert len(pos_rows) == len(z["pos"]) and len(neg_rows) == len(z["neg"])
    jobs = [(i, r["audio"], True, d) for (i, r), d in zip(pos_rows, z["pos"])] + [(i, r["audio"], False, d) for (i, r), d in zip(neg_rows, z["neg"])]
    vi = [(l.strip(), V / "cache" / (s1tag + "g") / (Path(l.strip()).stem + ".npy")) for l in open(V / "fa_dev_all6.txt") if l.strip()]
    vi = [(p, str(n)) for p, n in vi if n.exists()]
    with get_context("fork").Pool(workers, initializer=init, initargs=(ck,)) as P:
        R = list(P.imap(job_dev, jobs, chunksize=16))
        print("dev done", flush=True)
        RV = list(P.imap(job_vi, vi, chunksize=1))
    npos = len(pos_rows)
    out = {"pos": R[:npos], "neg": R[npos:], "vi": RV}
    np.savez(f"{K}/runs/vf_eval/casc_{s1tag}_{vtag}.npz", data=np.array([out], dtype=object), pos_end=z["pos_end"],
             neg_hours=float(z["neg_hours"]), vi_n=len(vi))
    print("CASC DONE", s1tag, vtag, len(R), "dev items", len(RV), "vi files", flush=True)


def alarms(s1, ends, s2, t1, t2, j):
    ok = (s1 >= t1) & (s2[:, j] >= t2) if len(ends) else np.zeros(0, bool)
    n, nxt = 0, -1
    for e in ends[ok]:
        if e >= nxt:
            n, nxt = n + 1, e + 2 * SR
    return n


def sweep(s1tag, vtag, t1s=(0.8, 0.85, 0.875, 0.9, 0.9375), t2s=(0.0, 0.5, 0.8, 0.9, 0.95, 0.98, 0.99, 0.995, 0.999)):
    z = np.load(f"{K}/runs/vf_eval/casc_{s1tag}_{vtag}.npz", allow_pickle=True)
    d = z["data"][0]; pe = z["pos_end"]
    for j, D in enumerate(DS):
        for t1 in t1s:
            for t2 in t2s:
                miss = 0
                for (s1, ends, s2), e in zip(d["pos"], pe):
                    m = (ends >= e * SR) & (ends <= (e + 1.0) * SR) & (s1 >= t1)
                    if not (m.any() and (s2[m, j] >= t2).any()):
                        miss += 1
                en = sum(alarms(*x, t1, t2, j) for x in d["neg"])
                vn = sum(alarms(*x, t1, t2, j) for x in d["vi"])
                print(f"D={D:.1f} T1={t1} T2={t2}: miss {miss}/{len(pe)}  EN FA {en}  VN FA {vn}", flush=True)


if __name__ == "__main__":
    if sys.argv[1] == "cands":
        build(sys.argv[2], sys.argv[3], sys.argv[4], int(sys.argv[5]) if len(sys.argv) > 5 else 6)
    else:
        sweep(sys.argv[2], sys.argv[3])