aurora-wake-model / code /plans /fa2 /delay387.py
thucdangvan020999's picture
Initial upload: releases, checkpoints, code, docs
a1fe2e2 verified
Raw History Blame Contribute Delete
4.45 kB
#!/usr/bin/env python3
"""Wake delay on clean Fish 'aurora' dev clips (same prep as sd_sweep): ours (sv4045b, N=120, thr 0.95) deciding every
10/30/50/100 ms vs baseline 3.8.7 (third+second INT8, one 1.5 s window every 100 ms, verifier thr 0.95, also 0.9 smooth3).
Also dumps 50 random clips with signals for the visualization.
python delay387.py OUT_DIR [workers]"""
import base64, io, json, os, sys
from multiprocessing import get_context
from pathlib import Path
import numpy as np
K = "/home/user/Downloads/vita-kws"; OUT = Path(sys.argv[1]); WORK = int(sys.argv[2]) if len(sys.argv) > 2 else 12
CK = K + "/runs/soupV40V45_30/best.pt"; N, T = 120, 0.95; STEPS = (1, 3, 5, 10)
C387 = "/home/user/Downloads/wuw/3.8.7_en_zip/3.8.7_en"
sys.argv = [sys.argv[0], "runs/en13_ft2_causal_mel80/best.pt", "stream", "/dev/null"]
sys.path.insert(0, K + "/plans_local"); sys.path.insert(0, "/home/user/Downloads/vita-wakeword-handoff/scripts")
import stream_eval as S # noqa
from bench_stream import StreamScorer, B # noqa
SC = {}
VIZ = set()
def init():
import bench_wuw_testset as BW
SC["s"] = StreamScorer(CK); SC["c"] = BW.make(("tflite", "c", C387))
def job(a):
i, path = a
w = S.audio.load(path, 16000)
se = S.speech_end(w, drop=40, floor=-60); se = None if se is None else se + 1.0
w = np.concatenate([np.zeros(16000, np.float32), w, np.zeros(16000, np.float32)])
x = (w + 1e-3 * S.noise(len(w), np.random.default_rng(i))).astype(np.float32)
if len(x) < 24000: x = np.concatenate([np.zeros(24000 - len(x), np.float32), x])
L = SC["s"].frame_logits(B.logmel_numpy(x, SC["s"].feat)); d = L[1] - L[0]
c = np.concatenate([[0.0], np.cumsum(d, dtype=np.float64)]); ks = np.arange(len(d)); lo = np.maximum(0, ks + 1 - N)
t = 1 / (1 + np.exp(-(c[ks + 1] - c[lo]) / (ks + 1 - lo))); t[:146] = 0.0
res = {"name": Path(path).name, "end": se}
for s in STEPS:
ok = np.flatnonzero((t >= T) & ((ks + 1) % s == 0))
res[f"ours_{s*10}"] = None if not len(ok) else float((ok[0] + 1) * 0.01)
p = SC["c"].windows(x); tm = (24000 + np.arange(len(p)) * 1600) / 16000
h = np.flatnonzero(p >= 0.95); res["c387_095"] = None if not len(h) else float(tm[h[0]])
sm = np.convolve(p, np.ones(3) / 3, mode="full")[:len(p)] if len(p) else p; sm[:2] = [np.mean(p[:k + 1]) for k in range(min(2, len(p)))]
h = np.flatnonzero(sm >= 0.9); res["c387_090s3"] = None if not len(h) else float(tm[h[0]])
if i in VIZ:
b = io.BytesIO(); import soundfile as sf; sf.write(b, x, 16000, format="WAV", subtype="PCM_16")
nf = len(x) // 160
res["viz"] = {"dur": round(len(x) / 16000, 3), "env": [[round(float(x[k*160:(k+1)*160].min()), 4), round(float(x[k*160:(k+1)*160].max()), 4)] for k in range(nf)],
"ours": [round(float(v), 3) for v in t[:nf]], "comp": [[round(float(a), 2), round(float(b_), 3)] for a, b_ in zip(tm, p)],
"wav": base64.b64encode(b.getvalue()).decode()}
return res
if __name__ == "__main__":
rows = [json.loads(l) for l in open(K + "/data/aurora/manifest_en4_real85.jsonl")]
jobs = [(i, r["audio"]) for i, r in enumerate(rows) if r["label"] == "aurora" and r.get("split") == "dev" and "fish_s2" in r["audio"]]
VIZ.update(int(j[0]) for j in np.random.default_rng(50).choice(np.array(jobs, dtype=object), 50, replace=False))
OUT.mkdir(parents=True, exist_ok=True)
with get_context("fork").Pool(WORK, initializer=init) as P:
R = list(P.imap(job, jobs, chunksize=8))
json.dump([r for r in R if "viz" not in r] + [], open(OUT / "delay387_all.json", "w"))
json.dump([r for r in R if "viz" in r], open(OUT / "delay387_viz.json", "w"))
keys = [f"ours_{s*10}" for s in STEPS] + ["c387_095", "c387_090s3"]
print(len(R), "clips")
for k in keys:
v = np.array([r[k] - r["end"] for r in R if r[k] is not None and r["end"] is not None]) * 1000
print(f"{k:12s} fired {len(v)}/{len(R)} delay p10 {np.percentile(v,10):5.0f} p50 {np.percentile(v,50):5.0f} p90 {np.percentile(v,90):5.0f} ms before-end {100*np.mean(v<0):3.0f}%")
# paired: clips where both ours_10 and c387 fired
for k in ("ours_10", "ours_100"):
pr = [(r[k] - r["c387_095"]) * 1000 for r in R if r[k] is not None and r["c387_095"] is not None]
print(f"paired {k} - c387_095: n {len(pr)} median {np.median(pr):.0f} ms, ours earlier in {100*np.mean(np.array(pr)<0):.0f}%")