File size: 4,792 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
"""RULE-coreml.md: the Core ML encoder on a Mac (ONNX Runtime's Core ML provider, CPU and Neural Engine).

`prepare` writes expected.f32: the turn-taker's outputs here on openyap.py's 230 hops,
for the phone to compare with. Also prints the hop times here.
`features` writes the CallHome features for turns.py (RULE.md parts 1 and 2), as `port.py features` does. Run once.
A model for both streams at once gets both windows in one prediction, as on the phone.

    python -I -B phone_coreml.py prepare --model export/l15.static.b2.fp16.onnx
    python -I -B phone_coreml.py features --model export/l15.static.b2.fp16.onnx --out runs/coreml
"""
from __future__ import annotations

import argparse
import json
import sys
import time
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 coreml_try as ct  # noqa: E402
import openyap as pb  # noqa: E402
import port  # noqa: E402
import tyger_ref as tr  # noqa: E402
from l15 import LogMel  # noqa: E402
from vendor.tyger_s2s.constants import SPEAK  # noqa: E402


class Encoder:
    """window -> (frames, 1024); log-mels padded on the right to 801 frames; all-zero windows cached by length."""

    def __init__(self, model: Path, units: str = "CPUAndNeuralEngine"):
        self.sess = ct.session(model, units)
        self.mel = LogMel(np.load(HERE / "data" / "mel_filters.npy"))
        self.dtype = np.float16 if "float16" in self.sess.get_inputs()[0].type else np.float32
        self._zero: dict[int, np.ndarray] = {}

    def __call__(self, wav: np.ndarray) -> np.ndarray:
        if not wav.any() and len(wav) in self._zero:
            return self._zero[len(wav)]
        mel = self.mel(wav)
        x = np.zeros((1, 801, 128), self.dtype)
        x[0, :len(mel)] = mel
        out = self.sess.run(None, {"mel": x})[0][0, :(len(mel) - 1) // 8 + 1].astype(np.float32)
        if not wav.any():
            self._zero[len(wav)] = out
        return out


class PairEncoder(Encoder):
    """Both streams' windows -> their (frames, 1024), one prediction."""

    def pair(self, win_u: np.ndarray, win_a: np.ndarray):
        mels = [self.mel(w) for w in (win_u, win_a)]
        x = np.zeros((2, 801, 128), self.dtype)
        for i, m in enumerate(mels):
            x[i, :len(m)] = m
        out = self.sess.run(None, {"mel": x})[0].astype(np.float32)
        n = (len(mels[0]) - 1) // 8 + 1
        return out[0, :n], out[1, :n]

    def hop_frames(self, win_u, win_a):
        hu, ha = self.pair(win_u, win_a)
        act = tr.frame_energy(win_u)
        n = min(tr.HOP_FRAMES, len(hu), len(ha), len(act))
        return hu[-n:], ha[-n:], act[-n:]

    def run(self, user, agent):
        hus, has, acts = zip(*(self.hop_frames(u, a) for u, a in tr.hops(user, agent)))
        return np.concatenate(hus), np.concatenate(has), np.concatenate(acts)


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("command", choices=["prepare", "features"])
    parser.add_argument("--model", type=Path, required=True)
    parser.add_argument("--out", type=Path)
    args = parser.parse_args()
    two = ".b2." in args.model.name
    encode = (PairEncoder if two else Encoder)(args.model)
    hop_frames = encode.hop_frames if two else (lambda u, a: tr.hop_frames(encode, u, a))
    if args.command == "features":
        args.out.mkdir(parents=True, exist_ok=False)
        for name, mode, user, agent in tr.segments(0):
            hu, ha, act = encode.run(user, agent) if two else tr.run(encode, user, agent)
            np.savez(args.out / f"{name}-{mode}.npz", hu=hu, ha=ha, act=act)
            print(name, mode, len(act), flush=True)
        return
    user, agent = pb.audio()
    tt = port.TurnTaker(HERE / "export" / "turn_taker.onnx", 2)
    outs, times = [], []
    for win_u, win_a in tr.hops(user, agent):
        t0 = time.perf_counter()
        hu, ha, act = hop_frames(win_u, win_a)
        for i in range(len(act)):
            outs.append(tt(hu[i], ha[i], float(act[i]), SPEAK))
        times.append((time.perf_counter() - t0) * 1e3)
    outs = np.stack(outs).astype("<f4")
    assert outs.shape == (pb.HOPS * 4, 8), outs.shape
    outs.tofile(HERE / "expected.f32")
    t = np.sort(times[pb.WARMUP:pb.WARMUP + pb.TIMED])
    row = {"median_ms": float(t[len(t) // 2]), "p90_ms": float(t[len(t) * 90 // 100]), "max_ms": float(t[-1])}
    print("M4 Max, Python, hop:", row)
    if args.out:
        args.out.write_text(json.dumps({"machine": "Apple M4 Max", "runtime": "Python + onnxruntime Core ML provider",
                                        "model": args.model.name, "hops_timed": pb.TIMED, **row}, indent=1) + "\n")


if __name__ == "__main__":
    main()