"""Export v4 stage-2 candidates (S/M/L BC-ResNet heads, M-hybrid BC-ResNet+GRU) and the stage-1 trunk with the feature tap, as cached-stream LiteRT: FP32, dynamic INT8 (as baseline 3.8.7), static INT8. Random weights (compute and latency do not depend on trained values). Also checks stream == full-sequence parity in PyTorch. exp/bin/python v4_export.py OUTDIR""" import os, sys, json, numpy as np, torch, torch.nn as nn, torch.nn.functional as F sys.path.insert(0, "/home/user/Downloads/vita-kws/plans_local"); sys.path.insert(0, "/home/user/Downloads/vita-kws/src") from vitakws.models.bcresnet import BCResNet import litert_torch from ai_edge_quantizer import quantizer, recipe OUT = sys.argv[1]; os.makedirs(OUT, exist_ok=True); torch.manual_seed(0) W = 60 # verifier window, frames at 20 ms (1.2 s) def tconv(conv, x, c): y = torch.cat([c, x], dim=3); k = c.shape[3]; return conv.conv(y), y[:, :, :, -k:] def run_block(b, h, c): ident = h if b.transition is not None: h = b.transition(h) x2 = b.ssn(b.freq_conv(h)); x1 = x2.mean(dim=2, keepdim=True) y, c2 = tconv(b.time_conv, x1, c); x1 = b.point_conv(F.silu(b.time_bn(y))) h = x2 + x1 if b.has_identity: h = h + ident return F.relu(h), c2 class Trunk(nn.Module): """Stage 1 (s1bc3) stream step that also returns the stage-2 tap features (every frame; caller keeps every 2nd).""" def __init__(s, m): super().__init__(); s.m = m def forward(s, x, *caches): m = s.m; out = []; h, c = tconv(m.head[0], x, caches[0]); out.append(c); h = m.head[2](m.head[1](h)) tap = None for i, b in enumerate(m.blocks): h, c = run_block(b, h, caches[i + 1]); out.append(c) if i == 3: tap = h y, c = tconv(m.neck[0], h, caches[len(m.blocks) + 1]); out.append(c) l = m.classifier(m.neck[3](m.neck[2](m.neck[1](y)))).squeeze(2) return (l, tap, *out) class Head(nn.Module): """Stage 2: adapter + stages 3-4 (+ neck) or stage 3 + GRU, then attention pooling over the last W frames.""" def __init__(s, v, chin, gru=0): super().__init__(); chv = v.blocks[3].point_conv.out_channels s.adapter = nn.Conv2d(chin, chv, 1, bias=False); s.gru = gru if gru: s.blocks = v.blocks[4:8]; ch = v.blocks[7].point_conv.out_channels s.proj = nn.Linear(ch * 5, gru); s.wi = nn.Linear(gru, 3 * gru); s.wh = nn.Linear(gru, 3 * gru) s.cls = nn.Linear(gru, 2); s.att = nn.Linear(gru, 1) else: s.blocks = v.blocks[4:]; s.neck = v.neck; s.cls = v.classifier; s.att = nn.Conv2d(v.embed_dim, 1, 1) def forward(s, x, *caches): caches = list(caches); out = []; h = s.adapter(x); j = 0 for b in s.blocks: h, c = run_block(b, h, caches[j]); out.append(c); j += 1 if s.gru: T = h.shape[3]; z = s.proj(h.permute(0, 3, 1, 2).reshape(1, T, -1)); hs = caches[j]; j += 1; seq = [] for t in range(T): gi = s.wi(z[:, t]); gh = s.wh(hs); ir, iz, inn = gi.chunk(3, -1); hr, hz, hn = gh.chunk(3, -1) r = torch.sigmoid(ir + hr); u = torch.sigmoid(iz + hz); n = torch.tanh(inn + r * hn); hs = (1 - u) * n + u * hs seq.append(hs) out.append(hs); e = torch.stack(seq, 2) # [1,G,T] logit = s.cls(e.transpose(1, 2)).transpose(1, 2); score = s.att(e.transpose(1, 2)).transpose(1, 2) else: y, c = tconv(s.neck[0], h, caches[j]); out.append(c); j += 1 e = s.neck[3](s.neck[2](s.neck[1](y))); logit = s.cls(e).squeeze(2); score = s.att(e).squeeze(2) hist = torch.cat([caches[j], torch.cat([score, logit], 1)], 2)[:, :, -W:]; out.append(hist) # [1,3,W] a = torch.softmax(hist[:, :1], dim=2); pooled = (a * hist[:, 1:]).sum(2); p = torch.softmax(pooled, 1)[:, 1:] return (p, *out) def init_caches(s, x): cs = []; h = s.adapter(x) with torch.no_grad(): for b in s.blocks: y = b.transition(h) if b.transition is not None else h cs.append(torch.zeros(1, y.shape[1], 1, b.time_conv.time_pad[0])); h = b(h) if s.gru: cs.append(torch.zeros(1, s.gru)) else: cs.append(torch.zeros(1, h.shape[1], h.shape[2], s.neck[0].time_pad[0])) cs.append(torch.full((1, 3, W), -30.0)); return cs def export(mod, args, name, calib): fp = f"{OUT}/{name}.tflite"; litert_torch.convert(mod, args).export(fp); res = {"fp32": fp} qt = quantizer.Quantizer(fp); qt.load_quantization_recipe(recipe.dynamic_wi8_afp32()); q = f"{OUT}/{name}_dint8.tflite" qt.quantize().export_model(q, overwrite=True); res["dint8"] = q try: from ai_edge_litert.interpreter import Interpreter it = Interpreter(fp); key = list(it.get_signature_list())[0]; names = it.get_signature_list()[key]["inputs"] det = it.get_signature_runner(key).get_input_details() samples = [{n: (np.random.randn(*det[n]["shape"]) * 2).astype(np.float32) for n in names} for _ in range(calib)] qt = quantizer.Quantizer(fp); qt.load_quantization_recipe(recipe.static_wi8_ai8()) cr = qt.calibrate({key: samples}); s = f"{OUT}/{name}_sint8.tflite"; qt.quantize(cr).export_model(s, overwrite=True); res["sint8"] = s except Exception as e: res["sint8_error"] = repr(e)[:300] return res rep = {} s1 = BCResNet(2, tau=3, n_mels=40, causal=True).eval(); tr = Trunk(s1).eval() from stream_bcresnet import StreamBCResNet c1 = StreamBCResNet(s1).init_caches(torch.zeros(1, 1, 40, 147)) rep["s1tap_T10"] = export(tr, (torch.zeros(1, 1, 40, 10), *c1), "s1tap_T10", 8) with torch.no_grad(): tap = tr(torch.randn(1, 1, 40, 10), *c1)[1] chin, fq = tap.shape[1], tap.shape[2] for name, tau, gru in [("v4S", 6, 0), ("v4M", 10, 0), ("v4L", 16, 0), ("v4Mgru", 10, 128)]: v = BCResNet(2, tau=tau, n_mels=40, causal=True); hd = Head(v, chin, gru).eval() for mod in hd.modules(): # non-trivial BN stats so INT8 ranges are realistic if isinstance(mod, nn.BatchNorm2d): mod.running_var.uniform_(0.5, 2.0); mod.running_mean.normal_(0, 0.5) # parity: one 60-frame call == 12 calls of 5 frames with torch.no_grad(): X = torch.randn(1, chin, fq, 60); cs = hd.init_caches(X[..., :5]); pA = hd(X, *cs)[0] cs = hd.init_caches(X[..., :5]) for t in range(0, 60, 5): o = hd(X[..., t:t + 5], *cs); cs = list(o[1:]) pB = o[0] params = sum(p.numel() for p in hd.parameters()) rep[name] = {"params": params, "parity_60_vs_12x5": float((pA - pB).abs().max())} for T in (60, 30, 5): rep[name][f"T{T}"] = export(hd, (torch.zeros(1, chin, fq, T), *hd.init_caches(torch.zeros(1, chin, fq, T))), f"{name}_T{T}", 8) print(name, json.dumps(rep[name])[:400], flush=True) json.dump(rep, open(f"{OUT}/v4_export.json", "w"), indent=1); print("EXPORT DONE")