Download benchmark.py from saalse/wespeaker-resnet293-lm-coreml: direct link, hf CLI and curl.
- Browser
- Download file 4.04 kB
-
https://huggingface.co/saalse/wespeaker-resnet293-lm-coreml/resolve/main/benchmark.py
- Command line
-
hf download hf://saalse/wespeaker-resnet293-lm-coreml/benchmark.py
-
curl -L -o benchmark.py https://huggingface.co/saalse/wespeaker-resnet293-lm-coreml/resolve/main/benchmark.py
4.04 kB
| """Check the Core ML package against the PyTorch original on CPU, GPU and Neural Engine, and time it. | |
| python benchmark.py --checkpoint avg_model.pt clips/*.wav | |
| For every 3 s window of the given 16 kHz mono WAV files it compares the Core ML embedding on each | |
| compute unit with WeSpeaker's PyTorch network (CMN applied to the fbank outside the network, as | |
| WeSpeaker does). Then it times batch-1 predictions on each unit and reports where Core ML plans | |
| the work (MLComputePlan). Run each unit in a fresh process for clean load times (--unit). | |
| """ | |
| import argparse, collections, json, shutil, time | |
| from pathlib import Path | |
| import coremltools as ct | |
| import numpy as np | |
| import soundfile as sf | |
| import torch | |
| from convert import OUT, checkpoint, load | |
| from fbank import WINDOW_SECONDS, fbank, windows | |
| UNITS = ["CPU_ONLY", "CPU_AND_GPU", "CPU_AND_NE"] | |
| def compiled(pkg): | |
| mlc = Path(pkg).with_suffix(".mlmodelc") | |
| if not mlc.exists(): | |
| shutil.move(ct.models.utils.compile_model(str(pkg)), mlc) | |
| return mlc | |
| def plan_share(mlc, unit): | |
| from coremltools.models.compute_plan import MLComputePlan | |
| plan = MLComputePlan.load_from_path(path=str(mlc), compute_units=getattr(ct.ComputeUnit, unit)) | |
| cost = collections.Counter() | |
| for op in plan.model_structure.program.functions["main"].block.operations: | |
| usage = plan.get_compute_device_usage_for_mlprogram_operation(op) | |
| if usage is None: | |
| continue | |
| dev = type(usage.preferred_compute_device).__name__.replace("ML", "").replace("ComputeDevice", "") | |
| est = plan.get_estimated_cost_for_mlprogram_operation(op) | |
| cost[dev] += est.weight if est else 0 | |
| total = sum(cost.values()) or 1 | |
| return {k: round(v / total, 3) for k, v in cost.items()} | |
| def unit_norm(e): | |
| return e / np.linalg.norm(e, axis=-1, keepdims=True) | |
| def main(): | |
| ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) | |
| ap.add_argument("wavs", nargs="+", type=Path) | |
| ap.add_argument("--checkpoint", type=Path) | |
| ap.add_argument("--model", default=OUT) | |
| ap.add_argument("--unit", dest="units", action="append", choices=UNITS + ["ALL"], | |
| help="compute unit, repeat for several (default: CPU, GPU, Neural Engine)") | |
| ap.add_argument("--timed", type=int, default=300, help="predictions to time per unit") | |
| args = ap.parse_args() | |
| args.units = args.units or UNITS | |
| feats = [] | |
| for p in args.wavs: | |
| x, sr = sf.read(p, dtype="float32") | |
| if sr != 16000 or x.ndim != 1: | |
| raise SystemExit(f"{p}: need 16 kHz mono") | |
| feats += [fbank(w) for w in windows(x)] | |
| F = np.stack(feats) | |
| print(f"{len(args.wavs)} files, {len(F)} windows of {WINDOW_SECONDS} s") | |
| torch.set_num_threads(4) | |
| ref_model = load(checkpoint(args.checkpoint), cmn=False) | |
| with torch.no_grad(): | |
| cmn = F - F.mean(axis=1, keepdims=True) | |
| ref = unit_norm(ref_model(torch.from_numpy(cmn)).numpy()) | |
| mlc = compiled(args.model) | |
| results = [] | |
| for unit in args.units: | |
| t = time.time() | |
| model = ct.models.CompiledMLModel(str(mlc), compute_units=getattr(ct.ComputeUnit, unit)) | |
| load_s = time.time() - t | |
| t = time.time() | |
| model.predict({"fbank": F[:1]}) | |
| first_s = time.time() - t | |
| emb = unit_norm(np.stack([model.predict({"fbank": f[None]})["embedding"][0] for f in F])) | |
| cos = (emb * ref).sum(axis=1) | |
| n = max(args.timed, 1) | |
| t = time.time() | |
| for i in range(n): | |
| model.predict({"fbank": F[i % len(F)][None]}) | |
| ms = (time.time() - t) / n * 1000 | |
| rec = dict(unit=unit, load_s=round(load_s, 2), first_call_s=round(first_s, 3), ms_per_window=round(ms, 2), | |
| x_realtime=round(WINDOW_SECONDS * 1000 / ms), cos_min=round(float(cos.min()), 5), | |
| cos_median=round(float(np.median(cos)), 5), plan=plan_share(mlc, unit)) | |
| results.append(rec) | |
| print(json.dumps(rec), flush=True) | |
| return results | |
| if __name__ == "__main__": | |
| main() | |