File size: 2,308 Bytes
5a26b95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Model conversion: FaceNet .pt -> ONNX, and ONNX -> TorchScript .pt (ArcFace / SFace). Each result is checked against its source.
    python convert.py        prepare every model in both formats (downloads what is missing) - e.g. for an offline install"""
import numpy as np
import torch


def facenet_net(pt_path):  # original facenet-pytorch weights -> InceptionResnetV1 (embedding output)
    from facenet_pytorch import InceptionResnetV1
    sd = torch.load(pt_path, map_location="cpu", weights_only=True)  # plain tensors only: a model file cannot run code
    net = InceptionResnetV1(); net.load_state_dict({k: v for k, v in sd.items() if not k.startswith("logits")})  # classifier unused
    return net.eval()


def _check(ref, out, what):
    cos = float(np.min(np.sum(ref * out, 1) / np.linalg.norm(ref, axis=1) / np.linalg.norm(out, axis=1)))
    print("%s: max abs diff %.2e, min cosine %.6f" % (what, np.abs(ref - out).max(), cos))
    if cos < 0.9999: raise RuntimeError("converted model does not match the original (%s)" % what)


def facenet_to_onnx(pt_path, onnx_path):
    import onnxruntime as ort
    net, x = facenet_net(pt_path), torch.randn(2, 3, 160, 160)
    torch.onnx.export(net, x, onnx_path, opset_version=13, input_names=["input"], output_names=["embedding"],
                      dynamic_axes={"input": {0: "batch"}, "embedding": {0: "batch"}})
    with torch.no_grad(): ref = net(x).numpy()
    _check(ref, ort.InferenceSession(onnx_path, providers=["CPUExecutionProvider"]).run(None, {"input": x.numpy()})[0], "FaceNet .pt -> ONNX")


def onnx_to_torchscript(onnx_path, pt_path, batch1=False):
    import onnxruntime as ort
    from onnx2torch import convert
    x = torch.randn(1 if batch1 else 2, 3, 112, 112)
    with torch.no_grad(): ts = torch.jit.trace(convert(onnx_path).eval(), x)
    ts.save(pt_path); s = ort.InferenceSession(onnx_path, providers=["CPUExecutionProvider"])
    with torch.no_grad(): out = torch.jit.load(pt_path).eval()(x).numpy()
    _check(s.run(None, {s.get_inputs()[0].name: x.numpy()})[0], out, "ONNX -> TorchScript")


if __name__ == "__main__":
    from core import MODELS, ensure_model  # here, not at the top: core imports this module
    for key in MODELS:
        for runtime in ("onnx", "pt"): print(ensure_model(key, print, runtime))