Spaces:
Runtime error
Runtime error
Download scripts/export_onnx.py from npisb/pipecountapp-dev: direct link, hf CLI and curl.
- Browser
- Download file 3.24 kB
-
https://huggingface.co/spaces/npisb/pipecountapp-dev/resolve/a34f5755f8fee2e18fc00a54ec4d76811bf2def0/scripts/export_onnx.py
- Command line
-
hf download hf://spaces/npisb/pipecountapp-dev@a34f5755f8fee2e18fc00a54ec4d76811bf2def0/scripts/export_onnx.py
-
curl -L -o export_onnx.py https://huggingface.co/spaces/npisb/pipecountapp-dev/resolve/a34f5755f8fee2e18fc00a54ec4d76811bf2def0/scripts/export_onnx.py
3.24 kB
| """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() | |