File size: 3,235 Bytes
0e0cc3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Export countmodel.pt to ONNX for browser inference."""
from __future__ import annotations

import argparse
import sys
from pathlib import Path

import numpy as np
import onnx
import onnxruntime as ort
import torch

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))


def load_model(weights: Path, conf: float = 0.6) -> torch.nn.Module:
    wrapped = torch.hub.load(
        str(ROOT / "yolov5"),
        "custom",
        path=str(weights),
        source="local",
        force_reload=False,
    )
    model = wrapped.model if hasattr(wrapped, "model") else wrapped
    model.conf = conf
    model.max_det = 4000
    model.eval()
    model.cpu()
    return model


def export_onnx(model: torch.nn.Module, output: Path, imgsz: int = 640, opset: int = 12) -> None:
    dummy = torch.zeros(1, 3, imgsz, imgsz)
    output.parent.mkdir(parents=True, exist_ok=True)
    torch.onnx.export(
        model,
        dummy,
        str(output),
        opset_version=opset,
        input_names=["images"],
        output_names=["output"],
        dynamic_axes={"images": {0: "batch"}, "output": {0: "batch"}},
    )
    # simplify if onnxsim available
    try:
        import onnxsim

        model_onnx = onnx.load(str(output))
        model_simp, check = onnxsim.simplify(model_onnx)
        if check:
            onnx.save(model_simp, str(output))
            print(f"Simplified ONNX saved to {output}")
        else:
            print("ONNX simplify check failed; keeping original export")
    except Exception as exc:
        print(f"ONNX simplify skipped: {exc}")


def quantize_int8(fp32_path: Path, int8_path: Path) -> None:
    from onnxruntime.quantization import QuantType, quantize_dynamic

    quantize_dynamic(
        str(fp32_path),
        str(int8_path),
        weight_type=QuantType.QUInt8,
    )
    print(f"INT8 model saved to {int8_path}")


def parity_check(model: torch.nn.Module, onnx_path: Path, imgsz: int = 640) -> None:
    dummy = np.random.randint(0, 255, (imgsz, imgsz, 3), dtype=np.uint8)
    img = dummy.astype(np.float32) / 255.0
    img_chw = np.transpose(img, (2, 0, 1))
    tensor = torch.from_numpy(img_chw).unsqueeze(0)

    with torch.inference_mode():
        pt_out = model(tensor)[0].numpy()

    sess = ort.InferenceSession(str(onnx_path), providers=["CPUExecutionProvider"])
    ort_out = sess.run(None, {"images": tensor.numpy()})[0]

    diff = np.abs(pt_out - ort_out).max()
    print(f"Parity max abs diff: {diff:.6f}")
    if diff > 0.05:
        print("WARNING: ONNX output differs significantly from PyTorch")


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--weights", type=Path, default=ROOT / "countmodel.pt")
    parser.add_argument("--out-dir", type=Path, default=ROOT / "frontend" / "public" / "models")
    parser.add_argument("--imgsz", type=int, default=1024)
    args = parser.parse_args()

    model = load_model(args.weights)
    fp32_path = args.out_dir / "countmodel.onnx"
    int8_path = args.out_dir / "countmodel-int8.onnx"

    export_onnx(model, fp32_path, imgsz=args.imgsz)
    parity_check(model, fp32_path, imgsz=args.imgsz)
    quantize_int8(fp32_path, int8_path)


if __name__ == "__main__":
    main()