#!/usr/bin/env python3 """End-of-keyword head on a FROZEN causal wake model (wake decisions unchanged, same FA / detection). Per 10 ms frame it predicts "the keyword has ended by now". Use: after the wake fires, start ASR at the first frame where p_end >= 0.5 (audio kept in a ring buffer, so no command audio is lost). Training windows: keyword placed with trail in [-0.15, 0.6] s, and half of them followed by Vietnamese speech (the user's command spoken straight after the keyword), then the model's own noise/RIR augmentation. python end_head.py train CKPT OUT [steps] python end_head.py eval CKPT OUT N T""" import json, sys import numpy as np import torch, torch.nn as nn, torch.nn.functional as F K = "/home/user/Downloads/vita-kws" sys.path.insert(0, K + "/src"); sys.path.insert(0, K + "/plans_local") from vitakws.engine import load_checkpoint # noqa from vitakws.config import augment_config, feature_config # noqa from vitakws.data.augment import Augmenter # noqa from vitakws.data.manifest import read_manifest # noqa from vitakws.data.dataset import place_keyword # noqa from vitakws.data import audio # noqa SR, HOP = 16000, 160 THS, CAPS, HOLDS = (0.3, 0.4, 0.5, 0.6), (0.2, 0.25, 0.3, 0.8), (0.1, 0.15, 0.2, 0.25) def speech_end(w, drop=30, floor=-55): n = HOP; e = np.array([np.sqrt((w[i:i + n] ** 2).mean()) + 1e-9 for i in range(0, len(w) - n + 1, n)]) if not len(e): return None db = 20 * np.log10(e); th = max(db.max() - drop, floor); idx = np.flatnonzero(db >= th) return int((idx[-1] + 1) * n) if len(idx) else None class EndHead(nn.Module): # causal: left-padded temporal conv over frozen per-frame embeddings def __init__(self, dim, hid=32, k=5): super().__init__(); self.k = k self.c1 = nn.Conv1d(dim, hid, k); self.c2 = nn.Conv1d(hid, hid, k); self.o = nn.Conv1d(hid, 1, 1) def forward(self, f): # [B, D, T] -> [B, T] logits x = F.relu(self.c1(F.pad(f, (self.k - 1, 0)))); x = F.relu(self.c2(F.pad(x, (self.k - 1, 0)))) return self.o(x).squeeze(1) class EndHead2(nn.Module): # causal dilated temporal convs over [frozen embeddings ; log-mel] def __init__(self, dim, hid=64, k=5, dils=(1, 2, 4), nout=1): super().__init__(); self.k, self.dils = k, dils self.inp = nn.Conv1d(dim, hid, 1) self.cs = nn.ModuleList([nn.Conv1d(hid, hid, k, dilation=d) for d in dils]); self.o = nn.Conv1d(hid, nout, 1) def forward(self, f, all_out=False): # channel 0 = p_end logit; channel 1 (v4) = time-to-end regression x = F.relu(self.inp(f)) for c, d in zip(self.cs, self.dils): x = x + F.relu(c(F.pad(x, ((self.k - 1) * d, 0)))) y = self.o(x) return y if all_out else y[:, 0] V2 = __import__("os").environ.get("EH_V2") == "1" EH_END = (40, -60) if __import__("os").environ.get("EH_V3") == "1" else (30, -55) # v3: same word-end definition as the eval def feats(model, m): # m: [B,1,mels,T] f = model.frame_features(m) if V2: mel = m[:, 0, :, :f.shape[2]]; mel = (mel - mel.mean(dim=1, keepdim=True)) / 5.0 # per-frame (causal); keeps loudness shape f = torch.cat([f, mel], 1) return f V4 = __import__("os").environ.get("EH_V4") == "1" # v4: + duration-aware target (time until keyword end), Next-Turn style multi-task def mk_head(D): return EndHead2(D, nout=2 if V4 else 1) if V2 else EndHead(D) class EndSet(torch.utils.data.Dataset): def __init__(self, kws, speech, aug, n, seed=0): self.kws, self.speech, self.aug, self.n, self.seed = kws, speech, aug, n, seed def __len__(self): return self.n def __getitem__(self, i): rng = np.random.default_rng([self.seed, i]); W = int(1.5 * SR) while True: w = audio.load(self.kws[int(rng.integers(len(self.kws)))], SR); e = speech_end(w, *EH_END) if e is not None and e > 0.3 * SR: break trail = int(rng.uniform(-0.15, 0.6) * SR) x = place_keyword(w, e, W, trail).astype(np.float32); pos = W - trail # keyword end inside the window if rng.random() < 0.5 and trail > 0.05 * SR: # command spoken right after the keyword g = int(rng.uniform(0.0, 0.2) * SR); room = trail - g if room > 0.05 * SR: p = self.speech[int(rng.integers(len(self.speech)))] try: c = audio.load(p, SR, start=0.0, duration=room / SR + 0.05)[:room] except Exception: c = np.zeros(0, np.float32) if len(c): ref = np.sqrt(np.mean(w ** 2) + 1e-10); rms = np.sqrt(np.mean(c ** 2) + 1e-10) if rms > 1e-4: x[pos + g:pos + g + len(c)] += (c * ref / rms * 10 ** (rng.uniform(-6, 3) / 20)).astype(np.float32) if self.aug is not None: x = self.aug(x, rng) return torch.from_numpy(x.astype(np.float32)), pos def labels(pos, T, dev): # frame j covers audio up to (j+1)*HOP j = torch.arange(T, device=dev)[None, :] return ((j + 1) * HOP >= pos[:, None].to(dev)).float() def train(ck, out, steps): dev = torch.device("cuda" if torch.cuda.is_available() else "cpu") model, fe, cfg, _, _ = load_checkpoint(ck, dev) for p in model.parameters(): p.requires_grad_(False) items = read_manifest(K + "/data/aurora/manifest_hp6.jsonl"); tr = [i for i in items if i.split == "train"] kws = [i.audio for i in tr if i.label == "aurora"] speech = [i.audio for i in tr if i.kind == "negative_speech"] a = cfg["augment"] aug = Augmenter(augment_config(cfg), SR, [i.audio for i in tr if i.kind in a["noise_from_kinds"]], [i.audio for i in tr if i.kind in a.get("babble_from_kinds", [])]) print(len(kws), "keyword clips", len(speech), "speech clips", flush=True) dl = torch.utils.data.DataLoader(EndSet(kws, speech, aug, steps * 64), batch_size=64, num_workers=8, drop_last=True) with torch.no_grad(): m = fe(torch.zeros(1, SR, device=dev)); m = m.unsqueeze(1) if m.dim() == 3 else m; D = feats(model, m).shape[1] head = mk_head(D).to(dev); opt = torch.optim.AdamW(head.parameters(), 2e-3, weight_decay=1e-4) sched = torch.optim.lr_scheduler.OneCycleLR(opt, 2e-3, total_steps=steps) for s, (x, pos) in enumerate(dl): x = x.to(dev) with torch.no_grad(): m = fe(x); m = m.unsqueeze(1) if m.dim() == 3 else m; f = feats(model, m) if V4: yo = head(f, all_out=True); lg = yo[:, 0]; y = labels(pos, lg.shape[1], dev) j = torch.arange(lg.shape[1], device=dev)[None, :]; tte = ((pos[:, None].to(dev) - (j + 1) * HOP) / SR).clamp(-0.3, 0.6) / 0.3 lb = F.binary_cross_entropy_with_logits(lg, y); lr_ = F.smooth_l1_loss(yo[:, 1], tte.float()); loss = lb + 0.5 * lr_ if s % 200 == 0: print(f" bce {lb.item():.4f} dur {lr_.item():.4f} tte range {tte.min().item():.2f}..{tte.max().item():.2f}", flush=True) else: lg = head(f); y = labels(pos, lg.shape[1], dev) loss = F.binary_cross_entropy_with_logits(lg, y) opt.zero_grad(); loss.backward(); opt.step(); sched.step() if s % 200 == 0: print(f"step {s} loss {loss.item():.4f}", flush=True) torch.save({"head": head.state_dict(), "dim": D, "ckpt": ck}, out); print("saved", out, sum(p.numel() for p in head.parameters()), "params") def evaluate(ck, out, N, T): sys.argv = [sys.argv[0], "runs/en13_ft2_causal_mel80/best.pt", "stream", "/dev/null"] import stream_eval as S # noqa dev = torch.device("cpu"); torch.set_num_threads(8) model, fe, cfg, _, _ = load_checkpoint(ck, dev); z = torch.load(out); head = mk_head(z["dim"]); head.load_state_dict(z["head"]); head.eval() rows = [json.loads(l) for l in open(K + "/data/aurora/manifest_en4_real85.jsonl")] clips = [r["audio"] for r in rows if r["label"] == "aurora" and r.get("split") == "dev" and "fish_s2" in r["audio"]] vs = [i.audio for i in read_manifest(K + "/data/aurora/manifest_hp6.jsonl") if i.split == "dev" and i.kind == "negative_speech"] rng = np.random.default_rng(0); res = {"silence": [], "command": []}; base = [] for ci, p in enumerate(clips): w0 = audio.load(p, SR); se = S.speech_end(w0, drop=40, floor=-60) if se is None: continue for cond in res: w = np.concatenate([np.zeros(SR, np.float32), w0[:int(se * SR)], np.zeros(SR, np.float32)]); kend = 1.0 + se if cond == "command": # Vietnamese command 0-150 ms after the keyword c = audio.load(vs[int(rng.integers(len(vs)))], SR, start=0.0, duration=0.9) g = int((1.0 + se + rng.uniform(0, 0.15)) * SR); c = c[:len(w) - g] ref = np.sqrt(np.mean(w0 ** 2) + 1e-10); rms = np.sqrt(np.mean(c ** 2) + 1e-10) if rms > 1e-4: w[g:g + len(c)] += c * ref / rms x = (w + 1e-3 * rng.standard_normal(len(w))).astype(np.float32) with torch.no_grad(): m = fe(torch.from_numpy(x)[None]); m = m.unsqueeze(1) if m.dim() == 3 else m f = model.frame_features(m); L = model.classifier(f.unsqueeze(2)).squeeze(2)[0].numpy(); pe = torch.sigmoid(head(feats(model, m)))[0].numpy() d = L[1] - L[0]; c_ = np.concatenate([[0.0], np.cumsum(d, dtype=np.float64)]); ks = np.arange(146, len(d)); lo = np.maximum(0, ks + 1 - N) t = 1 / (1 + np.exp(-(c_[ks + 1] - c_[lo]) / (ks + 1 - lo))); h = np.flatnonzero(t >= T) if not len(h): continue fr = ks[h[0]]; fire = (fr + 1) * 0.01 r = [fire - kend] for th in THS: g2 = np.flatnonzero(pe[fr:] >= th); est = (fr + g2[0] + 1) * 0.01 if len(g2) else fire + 0.8 for cap in CAPS: r.append(min(est, fire + cap) - kend) for H in HOLDS: r.append(fire + H - kend) res[cond].append(r) if ci % 500 == 0: print(ci, flush=True) for cond, v in res.items(): v = np.array(v) * 1e3 names = ["wake time"] + [f"head p>={th} cap {int(cap*1e3)}" for th in THS for cap in CAPS] + [f"hold {int(H*1e3)} ms" for H in HOLDS] for col, name in enumerate(names): q = np.percentile(v[:, col], [10, 50, 90]) print(f"{cond:8s} {name:22s} n={len(v)} p10 {q[0]:5.0f} p50 {q[1]:5.0f} p90 {q[2]:5.0f} | within 50 ms {100*np.mean(np.abs(v[:, col]) <= 50):3.0f}%" f" before end {100*np.mean(v[:, col] < 0):3.0f}% >150 ms late {100*np.mean(v[:, col] > 150):3.0f}%") if __name__ == "__main__": if sys.argv[1] == "train": train(sys.argv[2], sys.argv[3], int(sys.argv[4]) if len(sys.argv) > 4 else 3000) else: evaluate(sys.argv[2], sys.argv[3], int(sys.argv[4]), float(sys.argv[5]))