Download code/plans/s1/gate_eval.py from thucdangvan020999/aurora-wake-model: direct link, hf CLI and curl.
- Browser
- Download file 7.48 kB
-
https://huggingface.co/thucdangvan020999/aurora-wake-model/resolve/main/code/plans/s1/gate_eval.py
- Command line
-
hf download hf://thucdangvan020999/aurora-wake-model/code/plans/s1/gate_eval.py
-
curl -L -o gate_eval.py https://huggingface.co/thucdangvan020999/aurora-wake-model/resolve/main/code/plans/s1/gate_eval.py
7.48 kB
| #!/usr/bin/env python3 | |
| """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:] | |
| 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 / 10) + 1) * 0.1; 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] / 0.1 - 1e-9)); hi = int(np.ceil((ta[i] + W) / 0.1 - 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): | |
| import torch | |
| out = np.zeros((len(MS), len(kf)), np.float32) | |
| if not len(kf): return out | |
| xx = np.concatenate([np.zeros(PADF * 160, np.float32), x]) | |
| with torch.no_grad(): | |
| for vi, (m, fe) in enumerate(MS): | |
| CH = 60000; parts = [] # log-mel in 10-min chunks (center=False -> identical frames), kept on CPU | |
| for c0 in range(0, max(1, (len(xx) - 512) // 160 + 1), CH): | |
| seg = xx[c0 * 160: (c0 + CH - 1) * 160 + 512] | |
| if len(seg) < 512: break | |
| g_ = fe(torch.from_numpy(np.ascontiguousarray(seg)).cuda()[None]); parts.append(g_.reshape(g_.shape[-2], g_.shape[-1]).cpu()) | |
| f = torch.cat(parts, 1) # [mels, frames] | |
| idx = torch.from_numpy(kf + PADF)[:, None] + torch.arange(-NF + 1, 1)[None] | |
| idx = idx.clamp(0, f.shape[1] - 1) | |
| for b in range(0, len(kf), 512): | |
| w = f[:, idx[b:b + 512]].permute(1, 0, 2)[:, None].cuda() # [B, 1, mels, 147] | |
| out[vi, b:b + 512] = torch.softmax(m(w), 1)[:, 1].cpu().numpy() | |
| return out | |
| def job(a): | |
| kind, key = a | |
| if kind == "dev": return T.prep(key)[1] | |
| if kind == "delay": return np.fromfile(key, dtype="<f4") | |
| raw = subprocess.run(["ffmpeg", "-nostdin", "-v", "error", "-i", key, "-f", "f32le", "-ac", "1", "-ar", "16000", "-"], capture_output=True).stdout | |
| return np.frombuffer(raw, dtype=np.float32).copy() | |
| def main(): | |
| global MS, T | |
| res = {"WS": WS, "TMIN": TMIN, "vers": VERS, "set": SET, "items": []} | |
| jobs, meta = [], [] | |
| if SET in ("clean", "far", "car"): | |
| sys.argv = ["s1_tracks", "", "", SET]; import s1_tracks as T # noqa | |
| rows = [json.loads(l) for l in open(K + "/data/aurora/en_dev2.jsonl")]; NK = {"negative", "negative_speech", "background", "hard_negative"} | |
| if SET != "clean": rows = [r for r in rows if r["label"] not in NK] | |
| nm = "cache" if SET == "clean" else SET | |
| z1 = np.load(f"{K}/runs/vf_eval/{nm}_s1bc3.npz", allow_pickle=True); z2 = np.load(f"{K}/runs/vf_eval/{nm}_sv4045b.npz", allow_pickle=True) | |
| ip1 = iter(z1["pos"]); in1 = iter(z1["neg"] if "neg" in z1 else ()); ie = iter(z2["pos_end"]) | |
| for i, r in enumerate(rows): | |
| pos = r["label"] not in NK; d1 = next(ip1) if pos else next(in1) | |
| jobs.append(("dev", (i, r))); meta.append({"pos": pos, "end": float(next(ie)) if pos else None, "d1": d1}) | |
| res["neg_hours"] = float(z2["neg_hours"]) if SET == "clean" else 0.0 | |
| elif SET == "delay": | |
| T = None; z1 = np.load(C.E1 / "delay_s2_s1bc3.npz", allow_pickle=True); mt = {m["name"]: m for m in json.load(open(TW + "/meta.json"))} | |
| for nm_, d1 in zip(z1["names"], z1["pos"]): | |
| jobs.append(("delay", f"{TW}/{nm_}.f32")); meta.append({"pos": True, "end": mt[nm_]["end"], "d1": d1, "name": str(nm_)}) | |
| else: | |
| T = None | |
| s1d, lst = (C.CACHE / "s1bc3g", V + "/fa_dev_all6.txt") if SET == "fa" else (C.CACHE / "s1bc3_cdg", V + "/fa_cardev_1129.txt") | |
| src = {Path(l.strip()).stem: l.strip() for l in open(lst) if l.strip()} | |
| for st, path in sorted(src.items()): | |
| p1 = s1d / f"{st}.npy" | |
| if not p1.exists(): continue | |
| d1 = np.load(p1); meta.append({"pos": False, "end": None, "hours": len(d1) / 360000, "stem": st, "d1": d1}); jobs.append(("fa", path)) | |
| res["hours"] = sum(m["hours"] for m in meta) | |
| for m in meta: | |
| m["g"], m["m"], m["kf"] = grid(m["d1"], len(m["d1"])); m["d1"] = None | |
| MS = load_vers(); it = {} | |
| todo = [i for i, j in enumerate(jobs) if len(meta[i]["g"])] | |
| with get_context("fork").Pool(4) as P: | |
| B = 8 if SET in ("fa", "cardev") else 256 | |
| for b0 in range(0, len(todo), B): | |
| idx = todo[b0:b0 + B] | |
| for i, x in zip(idx, P.imap(job, [jobs[i] for i in idx], chunksize=1 if B == 8 else 16)): | |
| it[i] = score(x, meta[i]["kf"]) | |
| 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() | |