#!/usr/bin/env python3 """DEPLOYMENT-EXACT scoring for a CAUSAL streaming verifier: per open-gate span (m_W(0.6) >= 0.7), the verifier starts with zero state 1.5 s before the first gated point (catch-up over the ring buffer) and streams to the last one; score at each gated point = softmax(mean of the last 147 frame logits). Points outside spans get 0. Same output format as gate_eval_step.py. (was: v3 pipeline (no stage-2 catch-up): stage-1 stream gate -> ONE-SHOT verifier on the last 1.5 s, every 100 ms while gated. For each clip/file: s1 = s1bc3 track (pooled to 20 ms); grid g = 0.1 s steps; m_W(g) = max s1 over (g - W, g] for W in WS. Every grid point with max_W m_W(g) >= TMIN is scored by each verifier on the 147 log-mel frames ending at g (whole-file log-mel, center=False, sliced exactly like a device ring buffer; 1.5 s of zeros before the clip). python gate_eval.py SET OUT.pkl VERIFIER_CKPT [VERIFIER_CKPT ...] SET = clean|far|car|delay|fa|cardev Saves per item: g [n], m [len(WS), n], v [n_ver, n] plus labels (pos, end) / hours. Score with gate_score.py. """ import json, os, pickle, subprocess, sys from multiprocessing import get_context from pathlib import Path import numpy as np K = "/home/user/Downloads/vita-kws"; H = os.path.dirname(os.path.abspath(__file__)); SR = 16000 SET, OUT = sys.argv[1:3]; VERS = sys.argv[3:] STEP = float(os.environ.get("GSTEP", "0.1")); CATCH = int(os.environ.get("CATCH", "147")); TMIN = 0.3; WS = (0.3, 0.6, 1.0); NF = 147; PADF = 150 # 1.5 s zero lead = 150 hops V = "/data/ext/vita_fa2"; TW = "/tmp/claude-1000/-home-user-Downloads-vita-wakeword-handoff/76566f21-879a-47b4-93d7-fe8a82af41ba/scratchpad/twbench/f32" sys.path.insert(0, K + "/src"); sys.path.insert(0, K + "/plans_local/fa2"); sys.path.insert(0, H) import cascade as C # noqa def grid(d1, n_frames): """Grid times g, gate levels m [len(WS), n] (only points with some m >= TMIN), and the clip frame index of each window end.""" s1 = C.s2_track(np.asarray(d1, np.float64), 60); s1 = s1[:len(s1) // 2 * 2].reshape(-1, 2).max(1) ta = (2 * np.arange(len(s1)) + 2) * 0.01 # time each pooled stage-1 value is available G = np.arange(1, int(n_frames / (STEP * 100)) + 1) * STEP; ms = [] for W in WS: m = np.zeros(len(G)) for i in np.flatnonzero(s1 >= TMIN): # gate opened by this value for g in [ta, ta + W) lo = int(np.ceil(ta[i] / STEP - 1e-9)); hi = int(np.ceil((ta[i] + W) / STEP - 1e-9)) lo = max(lo, 1) - 1; hi = min(hi, len(G)) if hi > lo: m[lo:hi] = np.maximum(m[lo:hi], s1[i]) ms.append(m) ms = np.array(ms); keep = np.flatnonzero(ms.max(0) >= TMIN) kf = np.floor((G[keep] * SR - 512) / 160).astype(np.int64) # last full frame ending by g return G[keep], ms[:, keep], kf def load_vers(): import torch from vitakws.models.bcresnet import BCResNet from vitakws.features import FeatureConfig, LogMel ms = [] for ck in VERS: 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.cuda().eval() fe = LogMel(FeatureConfig(**{k: cfg["features"][k] for k in ("sample_rate", "n_fft", "win_length", "hop_length", "n_mels", "f_min", "f_max", "log_eps")})).cuda() ms.append((m, fe)) return ms def score(x, kf, sel=None): import torch out = np.zeros((len(MS), len(kf)), np.float32) if not len(kf) or sel is None or not sel.any(): return out xx = np.concatenate([np.zeros(PADF * 160, np.float32), x]) idx = np.flatnonzero(sel); spans = np.split(idx, np.flatnonzero(np.diff(idx) > 1) + 1) with torch.no_grad(): for vi, (m, fe) in enumerate(MS): for sp in spans: f0 = int(kf[sp[0]]) + PADF - CATCH + 1; f1 = int(kf[sp[-1]]) + PADF # catch-up starts CATCH frames before the first point seg = xx[max(0, f0) * 160: f1 * 160 + 512] g_ = fe(torch.from_numpy(np.ascontiguousarray(seg)).cuda()[None]); g_ = g_.reshape(1, 1, g_.shape[-2], g_.shape[-1]) L = m.frame_logits(g_)[0].float().cpu().numpy() # [2, frames], causal: frame j sees only frames <= j of this span c = np.concatenate([np.zeros((2, 1)), np.cumsum(L, 1)], 1); base = max(0, f0) for j in sp: e = int(kf[j]) + PADF - base + 1; b = max(0, e - NF); z = (c[:, e] - c[:, b]) / (e - b); z = z - z.max() out[vi, j] = float(np.exp(z[1]) / np.exp(z).sum()) return out def job(a): kind, key = a if kind == "dev": return T.prep(key)[1] if kind == "delay": return np.fromfile(key, dtype="= 0.7) print(SET, b0, len(todo), flush=True) for i, m in enumerate(meta): r = {"g": m["g"], "m": m["m"], "v": it.get(i, np.zeros((len(MS), 0), np.float32)), "pos": m["pos"], "end": m["end"]} r.update({k: m[k] for k in ("hours", "stem", "name") if k in m}); res["items"].append(r) pickle.dump(res, open(OUT, "wb")); print("GATE DONE", SET, len(res["items"]), flush=True) if __name__ == "__main__": main()