File size: 4,570 Bytes
d65bf0f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 | """ios/Tyger.m against the Python version (phone_coreml.PairEncoder, the ONNX turn-taker, tyger-s2s's rules.py): the
same events, on the same frames, over 6.4 minutes of Open Yap audio with barge-ins, mode changes and resets. Builds
test_runtime.m for the Mac it runs on. Needs Xcode and onnxruntime.xcframework (the iOS package also has a macOS slice).
python -I -B test_runtime.py --onnxruntime path/to/onnxruntime.xcframework
"""
from __future__ import annotations
import argparse
import subprocess
import sys
import tempfile
from pathlib import Path
import numpy as np
HERE = Path(__file__).parent
sys.path[:0] = [str(HERE), str(HERE.parent)]
import openyap # noqa: E402
import phone_coreml as pc # noqa: E402
import port # noqa: E402
from vendor.tyger_s2s import rules # noqa: E402
from vendor.tyger_s2s.constants import HOP_N, SR, TURN_MAX_S # 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)
KIND = {"ENDPOINT": 1, "BACKCHANNEL": 2, "BARGE": 3}
HOPS, START_S = 1200, 600
def python_events(user, agent, encode, tt):
sess, events, listen_for = EarsSession(0, **POLICY), [], 0
for k in range(HOPS):
if k in (130, 260, 261, 390):
sess.reset()
speaking = bool((k // 50) % 2) and listen_for == 0
listen_for = max(listen_for - 1, 0)
mode = "speaking" if speaking else "listen"
u = user[k * HOP_N:(k + 1) * HOP_N]
a = agent[k * HOP_N:(k + 1) * HOP_N] if speaking else np.zeros(HOP_N, np.float32)
if rules.begin_hop(sess, u, a, mode):
tt.reset()
if mode == "listen":
sess.turn_u = sess.turn_u[-int(TURN_MAX_S * SR):]
hu, ha = encode.pair(sess.win_u, sess.win_a)
act = rules.frame_energy(sess.win_u)
if rules.switch_mode(sess, mode):
tt.reset()
barged = False
for i in range(-4, 0):
out = tt(hu[i], ha[i], float(act[i]), sess.prev_state)
evs, _, reset = rules.on_frame(sess, mode, out, float(act[i]), left=-i - 1)
for e in evs:
if e["kind"] in KIND:
events.append((k, i + 4, KIND[e["kind"]]))
barged |= e["kind"] == "BARGE"
if reset:
tt.reset()
if barged:
sess.reset()
listen_for = 20
return events
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--onnxruntime", type=Path, required=True)
args = parser.parse_args()
for conv, a, _ in openyap.conversations():
if conv == openyap.VALIDATION:
break
n, start = HOPS * HOP_N, START_S * SR
user, agent = a[start:start + n].astype("<f4"), a[start + 60 * SR:start + 60 * SR + n].astype("<f4")
encode = pc.PairEncoder(HERE / "export" / "l15.static.b2.fp16.onnx")
want = python_events(user, agent, encode, port.TurnTaker(HERE.parent / "turn_taker.onnx", 2))
with tempfile.TemporaryDirectory() as tmp:
tmp = Path(tmp)
user.tofile(tmp / "u.f32")
agent.tofile(tmp / "a.f32")
subprocess.run(["xcrun", "coremlcompiler", "compile", str(HERE.parent / "TygerEncoder.mlpackage"), str(tmp),
"--platform", "macOS", "--deployment-target", "15.0"], check=True, capture_output=True)
framework = next(args.onnxruntime.glob("macos-*"))
subprocess.run(["clang", "-fobjc-arc", "-O2", "-w", "-mmacosx-version-min=15.0", "-F", str(framework), "-I",
str(HERE.parent / "ios"), str(HERE.parent / "ios" / "Tyger.m"), str(HERE / "test_runtime.m"),
*"-framework onnxruntime -framework CoreML -framework Accelerate -framework Foundation "
"-framework Network -lc++".split(), "-o", str(tmp / "test_runtime")], check=True)
out = subprocess.run([str(tmp / "test_runtime"), str(tmp / "TygerEncoder.mlmodelc"), str(HERE.parent / "turn_taker.onnx"),
str(HERE.parent / "mel_filters.f32"), str(tmp / "u.f32"), str(tmp / "a.f32")],
check=True, capture_output=True, text=True).stdout
got = [tuple(map(int, line.split()[1:4])) for line in out.splitlines() if line.startswith("E ")]
print(f"{len(want)} events in Python, {len(got)} in the runtime: {'identical' if got == want else 'DIFFERENT'}")
raise SystemExit(got != want)
if __name__ == "__main__":
main()
|