Download scripts/port.py from matthiastl/tyger-coreml: direct link, hf CLI and curl.
- Browser
- Download file 5.12 kB
-
https://huggingface.co/matthiastl/tyger-coreml/resolve/main/scripts/port.py
- Command line
-
hf download hf://matthiastl/tyger-coreml/scripts/port.py
-
curl -L -o port.py https://huggingface.co/matthiastl/tyger-coreml/resolve/main/scripts/port.py
5.12 kB
| """tyger's CPU port: numpy log-mels and the ONNX encoder to layer 15, with the same windows and hops as the reference. | |
| python -I port.py features --model export/l15.int8.onnx --out runs/int8 | |
| python -I port.py speed --model export/l15.int8.onnx --threads 4 | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| 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 tyger_ref as tr # noqa: E402 | |
| from l15 import LogMel # noqa: E402 (numpy part only; l15 imports torch, present in this venv) | |
| def session(path: Path, threads: int): | |
| import onnxruntime as ort | |
| opts = ort.SessionOptions() | |
| opts.intra_op_num_threads = threads | |
| opts.inter_op_num_threads = 1 | |
| opts.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL | |
| opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL | |
| return ort.InferenceSession(str(path), opts, providers=["CPUExecutionProvider"]) | |
| class Encoder: | |
| """window -> (frames, 1024) layer 15, all-zero windows cached by length (as the reference and tyger-s2s do).""" | |
| def __init__(self, model: Path, threads: int): | |
| self.sess = session(model, threads) | |
| self.mel = LogMel(np.load(HERE / "data" / "mel_filters.npy")) | |
| 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)] | |
| out = self.sess.run(None, {"mel": self.mel(wav)[None]})[0][0] | |
| if not wav.any(): | |
| self._zero[len(wav)] = out | |
| return out | |
| class TurnTaker: | |
| """The GRU, one frame per call, in ONNX Runtime.""" | |
| def __init__(self, model: Path, threads: int): | |
| self.sess = session(model, threads) | |
| self.state = np.zeros((3, 1, 768), np.float32) | |
| def reset(self): | |
| self.state[:] = 0 | |
| def __call__(self, hu, ha, db, prev): | |
| out, self.state = self.sess.run(None, { | |
| "user": hu[None].astype(np.float32), "agent": ha[None].astype(np.float32), | |
| "energy_db": np.array([db], np.float32), "previous_state": np.array([prev], np.int64), | |
| "state_in": self.state}) | |
| return out[0] | |
| def main() -> None: | |
| parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) | |
| sub = parser.add_subparsers(dest="command", required=True) | |
| f = sub.add_parser("features") | |
| f.add_argument("--model", type=Path, required=True) | |
| f.add_argument("--out", type=Path, required=True) | |
| f.add_argument("--limit", type=int, default=0) | |
| f.add_argument("--threads", type=int, default=4) | |
| s = sub.add_parser("speed", help="RULE.md part 3: p90 time per hop, both streams speech, 200 hops") | |
| s.add_argument("--model", type=Path, required=True) | |
| s.add_argument("--threads", type=int, default=4) | |
| s.add_argument("--hops", type=int, default=200) | |
| args = parser.parse_args() | |
| encode = Encoder(args.model, args.threads) | |
| if args.command == "features": | |
| args.out.mkdir(parents=True, exist_ok=True) | |
| t_all = time.perf_counter() | |
| for name, mode, user, agent in tr.segments(args.limit): | |
| path = args.out / f"{name}-{mode}.npz" | |
| if path.exists(): | |
| continue | |
| timings: list[float] = [] | |
| hu, ha, act = tr.run(encode, user, agent, timings) | |
| np.savez(path, hu=hu, ha=ha, act=act, hop_seconds=np.array(timings)) | |
| print(f"{name} {mode}: {len(act)} frames, median hop {np.median(timings) * 1e3:.0f} ms", flush=True) | |
| print(f"done in {(time.perf_counter() - t_all) / 60:.1f} min", flush=True) | |
| return | |
| # speed: the first call laid out as the speaking segments are (user from the annotation's start, agent the same | |
| # call 60 s later, both speech), long enough for 200 hops after the window fills; the time of a hop is everything | |
| # the port does for it: both windows' log-mels and encodes, and the GRU's 4 frames. | |
| turn_taker = TurnTaker(HERE / "export" / "turn_taker.onnx", args.threads) | |
| _, call, start = next(tr.calls()) | |
| need = (args.hops + 30) * tr.HOP_N | |
| user, agent = call[start:start + need], call[start + 60 * tr.SR:start + 60 * tr.SR + need] | |
| assert len(agent) == need, "call too short for the speed test" | |
| times = [] | |
| for k, (win_u, win_a) in enumerate(tr.hops(user, agent)): | |
| t0 = time.perf_counter() | |
| hu, ha, act = tr.hop_frames(encode, win_u, win_a) | |
| for i in range(len(act)): | |
| turn_taker(hu[i], ha[i], float(act[i]), 2) | |
| times.append(time.perf_counter() - t0) | |
| steady = np.array(times[25:25 + args.hops]) # after the window reaches 8 s | |
| print(f"{args.model.name}, {args.threads} threads: {len(steady)} hops with full 8 s windows, " | |
| f"median {np.median(steady) * 1e3:.0f} ms, p90 {np.percentile(steady, 90) * 1e3:.0f} ms, " | |
| f"max {steady.max() * 1e3:.0f} ms per 320 ms hop -> {'PASS' if np.percentile(steady, 90) < 0.32 else 'FAIL'}") | |
| if __name__ == "__main__": | |
| main() | |