Download scripts/turns.py from matthiastl/tyger-coreml: direct link, hf CLI and curl.
- Browser
- Download file 7.75 kB
-
https://huggingface.co/matthiastl/tyger-coreml/resolve/main/scripts/turns.py
- Command line
-
hf download hf://matthiastl/tyger-coreml/scripts/turns.py
-
curl -L -o turns.py https://huggingface.co/matthiastl/tyger-coreml/resolve/main/scripts/turns.py
7.75 kB
| """RULE.md parts 1 and 2: the port's decisions and events against the reference's, on the same test audio. | |
| Each system's layer-15 frames come from its own run (`tyger_ref.py features`, `port.py features`). The reference's | |
| turn-taker is the PyTorch GRU (tyger-s2s's controller.py, fp32); the port's is `export/turn_taker.onnx`. | |
| 1. Frame decisions: the GRU runs freely over each segment (no resets), the previous-state input fixed to the mode's | |
| (LISTEN while listening, SPEAK while speaking, as rules.py sets it). Each decision is compared frame by frame. | |
| 2. Events: each system runs the turn rules (vendor/tyger_s2s/rules.py, the bundle's default policy) with the resets | |
| they call for, as engine.process does. A reference event matches if the port has an event of the same kind within | |
| one frame. Part 2 passes if, pooled over ENDPOINT, BACKCHANNEL and BARGE, at least 95% of the reference's events | |
| match (per-kind shares are reported too). This reading was fixed before any score was seen. | |
| python -I turns.py --reference runs/ref --port runs/int8 --out results/gate-int8.json | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import sys | |
| from pathlib import Path | |
| import numpy as np | |
| HERE = Path(__file__).parent | |
| sys.path[:0] = [str(HERE), str(HERE.parent)] # vendor/ is one level up | |
| import tyger_ref as tr # noqa: E402 | |
| from vendor.tyger_s2s import rules # noqa: E402 | |
| from vendor.tyger_s2s.constants import HOP_FRAMES, HOP_N, LISTEN, SPEAK # noqa: E402 | |
| from vendor.tyger_s2s.session import EarsSession # noqa: E402 | |
| POLICY = dict(ep_thr=0.91, ep_deb=2, barge_thr=0.5, barge_deb=2, bc_thr=0.4, bc_deb=2, bc_refractory=15) | |
| DECISIONS = { # name: (mode, output column, threshold); column 4.. = hazard, yield, backchannel, endpoint | |
| "endpoint >= 0.91": ("listen", 7, 0.91), | |
| "backchannel >= 0.80": ("listen", 6, 0.80), | |
| "backchannel >= 0.40": ("listen", 6, 0.40), | |
| "barge-in >= 0.93": ("speaking", 5, 0.93), | |
| "barge-in >= 0.50": ("speaking", 5, 0.50), | |
| "state (listening)": ("listen", None, None), | |
| "state (speaking)": ("speaking", None, None), | |
| } | |
| EVENTS = ("ENDPOINT", "BACKCHANNEL", "BARGE") | |
| class TorchGRU: | |
| def __init__(self): | |
| import torch | |
| from safetensors.torch import load_file | |
| from vendor.tyger_s2s.controller import TurnTaker | |
| self.torch = torch | |
| self.model = TurnTaker(768, 3) | |
| self.model.load_state_dict(load_file(str(HERE / "data" / "turn_taker.safetensors")), strict=True) | |
| self.model.eval() | |
| self.state = None | |
| def reset(self): | |
| self.state = None | |
| def __call__(self, hu, ha, db, prev): | |
| torch = self.torch | |
| with torch.no_grad(): | |
| act = ((torch.tensor([[float(db)]]) + 50) / 25).clamp(-3, 3) | |
| out, self.state = self.model(torch.from_numpy(hu)[None, None], torch.from_numpy(ha)[None, None], act, | |
| torch.tensor([[prev]]), self.state) | |
| return out[0, 0].numpy() | |
| def free_run(gru, f, mode) -> np.ndarray: | |
| gru.reset() | |
| prev = LISTEN if mode == "listen" else SPEAK | |
| return np.stack([gru(f["hu"][i], f["ha"][i], f["act"][i], prev) for i in range(len(f["act"]))]) | |
| def with_rules(gru, f, mode, user, agent) -> list[tuple[str, int]]: | |
| """(kind, frame) of every event, the turn rules and their resets applied as engine.process applies them.""" | |
| sess = EarsSession(0, **POLICY) | |
| gru.reset() | |
| events = [] | |
| for k in range(len(f["act"]) // HOP_FRAMES): | |
| if rules.begin_hop(sess, user[k * HOP_N:(k + 1) * HOP_N], agent[k * HOP_N:(k + 1) * HOP_N], mode): | |
| gru.reset() | |
| if rules.switch_mode(sess, mode): | |
| gru.reset() | |
| for j in range(HOP_FRAMES): | |
| i = k * HOP_FRAMES + j | |
| out = gru(f["hu"][i], f["ha"][i], f["act"][i], sess.prev_state) | |
| evs, _, reset = rules.on_frame(sess, mode, out, float(f["act"][i]), left=HOP_FRAMES - 1 - j) | |
| events += [(e["kind"], i) for e in evs if e["kind"] in EVENTS] | |
| if reset: | |
| gru.reset() | |
| return events | |
| def main() -> None: | |
| parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) | |
| parser.add_argument("--reference", type=Path, required=True) | |
| parser.add_argument("--port", type=Path, required=True) | |
| parser.add_argument("--out", type=Path, required=True) | |
| parser.add_argument("--limit", type=int, default=0) | |
| args = parser.parse_args() | |
| import port | |
| ref_gru, port_gru = TorchGRU(), port.TurnTaker(HERE / "export" / "turn_taker.onnx", 4) | |
| flips = {name: [0, 0, 0] for name in DECISIONS} # differing frames, frames, frames where either fires | |
| matched = {k: [0, 0] for k in EVENTS} # reference events matched, reference events | |
| port_events = {k: 0 for k in EVENTS} | |
| for name, mode, user, agent in tr.segments(args.limit): | |
| fr = np.load(args.reference / f"{name}-{mode}.npz") | |
| fp = np.load(args.port / f"{name}-{mode}.npz") | |
| assert len(fr["act"]) == len(fp["act"]) and len(fr["act"]) % HOP_FRAMES == 0 | |
| out_r, out_p = free_run(ref_gru, fr, mode), free_run(port_gru, fp, mode) | |
| for dname, (dmode, col, thr) in DECISIONS.items(): | |
| if dmode != mode: | |
| continue | |
| if col is None: | |
| dr, dp = out_r[:, :4].argmax(1), out_p[:, :4].argmax(1) | |
| fires = np.ones(len(dr), bool) | |
| else: | |
| dr, dp = out_r[:, col] >= thr, out_p[:, col] >= thr | |
| fires = dr | dp | |
| flips[dname][0] += int((dr != dp).sum()); flips[dname][1] += len(dr); flips[dname][2] += int(fires.sum()) | |
| ev_r, ev_p = with_rules(ref_gru, fr, mode, user, agent), with_rules(port_gru, fp, mode, user, agent) | |
| for kind, i in ev_r: | |
| matched[kind][1] += 1 | |
| matched[kind][0] += any(k == kind and abs(j - i) <= 1 for k, j in ev_p) | |
| for kind, _ in ev_p: | |
| port_events[kind] += 1 | |
| print(f"{name} {mode}: reference events {len(ev_r)}, port events {len(ev_p)}", flush=True) | |
| result = {"decisions": {}, "events": {}} | |
| ok1 = True | |
| for dname, (d, n, fires) in flips.items(): | |
| share = d / n | |
| ok1 &= share <= 0.01 | |
| result["decisions"][dname] = {"flipped_frames": d, "frames": n, "share": share, | |
| "share_of_firing_frames": d / fires if fires else 0.0} | |
| total_m, total_n = sum(m for m, _ in matched.values()), sum(n for _, n in matched.values()) | |
| pooled = total_m / total_n if total_n else 1.0 | |
| ok2 = pooled >= 0.95 | |
| for kind, (m, n) in matched.items(): | |
| result["events"][kind] = {"reference": n, "matched": m, "port": port_events[kind], "share": m / n if n else None} | |
| result["events"]["pooled_share"] = pooled | |
| result["pass_part1"], result["pass_part2"] = bool(ok1), bool(ok2) | |
| args.out.parent.mkdir(parents=True, exist_ok=True) | |
| args.out.write_text(json.dumps(result, indent=1) + "\n") | |
| print("\n1. frame decisions (port vs reference):") | |
| for dname, r in result["decisions"].items(): | |
| print(f" {dname:22} {r['flipped_frames']:>6} of {r['frames']:>6} frames differ = {r['share']:.3%} " | |
| f"({r['share_of_firing_frames']:.1%} of frames where either fires)") | |
| print("2. events matched within one frame:") | |
| for kind in EVENTS: | |
| r = result["events"][kind] | |
| share = f"{r['share']:.1%}" if r["share"] is not None else "n/a" | |
| print(f" {kind:12} reference {r['reference']:>4}, port {r['port']:>4}, matched {r['matched']:>4} = {share}") | |
| print(f" pooled {pooled:.1%}") | |
| print(f"part 1 {'PASS' if ok1 else 'FAIL'}, part 2 {'PASS' if ok2 else 'FAIL'}") | |
| if __name__ == "__main__": | |
| main() | |