thucdangvan020999's picture
Initial upload: releases, checkpoints, code, docs
a1fe2e2 verified
Raw History Blame Contribute Delete
4.3 kB
"""Export a checkpoint to ONNX for the device.
Writes
model.onnx input ``logmel`` [batch, 1, n_mels, frames] -> output ``logits`` [batch, classes]
model.json everything the device needs besides the weights: front-end
parameters, class names, window and hop, smoothing, threshold
The front end is not part of the graph; the device computes log-mel itself
following ``vitakws.features.logmel_numpy``. The export is checked against the
PyTorch model before it is accepted.
vitakws-export --checkpoint runs/hey_vita/best.pt --out export/hey_vita --threshold 0.8
"""
from __future__ import annotations
import argparse
import json
from pathlib import Path
import numpy as np
import torch
from vitakws.config import feature_config
from vitakws.engine import load_checkpoint
from vitakws.features import logmel_numpy
MAX_ABS_DIFF = 1e-3
def export_onnx(model: torch.nn.Module, n_mels: int, frames: int, path: Path, opset: int) -> None:
dummy = torch.zeros(1, 1, n_mels, frames)
torch.onnx.export(
model,
(dummy,),
str(path),
input_names=["logmel"],
output_names=["logits"],
dynamic_axes={"logmel": {0: "batch"}, "logits": {0: "batch"}},
opset_version=opset,
dynamo=False,
)
def check_parity(model: torch.nn.Module, path: Path, feats: np.ndarray) -> float:
import onnxruntime as ort
session = ort.InferenceSession(str(path), providers=["CPUExecutionProvider"])
got = session.run(None, {"logmel": feats})[0]
with torch.no_grad():
want = model(torch.from_numpy(feats)).numpy()
return float(np.abs(got - want).max())
def main(argv: list[str] | None = None) -> None:
parser = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawTextHelpFormatter
)
parser.add_argument("--checkpoint", required=True)
parser.add_argument("--out", required=True, help="output folder")
parser.add_argument(
"--threshold",
type=float,
default=0.5,
help="detection threshold to ship; take it from vitakws-eval --stream",
)
parser.add_argument("--hop-seconds", type=float, default=0.1)
parser.add_argument("--smooth-windows", type=int, default=3)
parser.add_argument("--refractory-seconds", type=float, default=2.0)
parser.add_argument("--opset", type=int, default=17)
args = parser.parse_args(argv)
model, _, cfg, label_map, ckpt = load_checkpoint(args.checkpoint, "cpu")
feat_cfg = feature_config(cfg)
window = int(round(cfg["data"]["window_seconds"] * feat_cfg.sample_rate))
frames = feat_cfg.num_frames(window)
out = Path(args.out)
out.mkdir(parents=True, exist_ok=True)
onnx_path = out / "model.onnx"
export_onnx(model, feat_cfg.n_mels, frames, onnx_path, args.opset)
rng = np.random.default_rng(0)
waves = rng.standard_normal((4, window)).astype(np.float32) * 0.05
feats = np.stack([logmel_numpy(w, feat_cfg) for w in waves])[:, None]
diff = check_parity(model, onnx_path, feats)
if diff > MAX_ABS_DIFF:
raise SystemExit(
f"ONNX output differs from PyTorch by {diff:.2e} (limit {MAX_ABS_DIFF:.0e})"
)
meta = {
"format": "vitakws-onnx-v1",
"classes": label_map.classes,
"keyword_class_ids": label_map.keyword_ids,
"features": feat_cfg.to_dict(),
"window_samples": window,
"window_frames": frames,
"input": {"name": "logmel", "shape": ["batch", 1, feat_cfg.n_mels, frames]},
"output": {"name": "logits", "activation": "softmax"},
"stream": {
"hop_seconds": args.hop_seconds,
"smooth_windows": args.smooth_windows,
"threshold": args.threshold,
"refractory_seconds": args.refractory_seconds,
},
"model": {**cfg["model"], "parameters": model.num_parameters()},
"source_checkpoint": str(args.checkpoint),
"source_epoch": ckpt.get("epoch"),
}
(out / "model.json").write_text(json.dumps(meta, indent=2), encoding="utf-8")
size_kb = onnx_path.stat().st_size / 1024
print(f"wrote {onnx_path} ({size_kb:.0f} KB) and {out / 'model.json'}")
print(f"ONNX matches PyTorch within {diff:.2e}")
if __name__ == "__main__":
main()