Download code/tt_visionpilot/tools/fold.py from changh95/auto_steer-p150: direct link, hf CLI and curl.
- Browser
- Download file 4.21 kB
-
https://huggingface.co/changh95/auto_steer-p150/resolve/main/code/tt_visionpilot/tools/fold.py
- Command line
-
hf download hf://changh95/auto_steer-p150/code/tt_visionpilot/tools/fold.py
-
curl -L -o fold.py https://huggingface.co/changh95/auto_steer-p150/resolve/main/code/tt_visionpilot/tools/fold.py
4.21 kB
| # SPDX-License-Identifier: Apache-2.0 | |
| """Fold the published VisionPilot ONNX files for the port, and write CPU goldens (host tool, needs onnxruntime). | |
| python -m tt_visionpilot.tools.fold --weights DIR --out DIR [--images a.jpg b.jpg ...] | |
| For each network: fix the batch to 1, let onnxruntime fold constants at its *basic* level (constant folding, | |
| Conv + BatchNorm fusion; no provider-specific ops), save ``<out>/folded/<net>.onnx``, then run the ORIGINAL file in | |
| onnxruntime (fp32, CPU) on the sample images and save ``<out>/golden/<net>.npz`` (inputs and outputs). The goldens | |
| come from the unfolded file so a folding error would show up as a mismatch. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import hashlib | |
| import json | |
| import os | |
| from pathlib import Path | |
| import numpy as np | |
| from ..models import NETWORKS, network_input, preprocess_front | |
| def _sha256(path: Path) -> str: | |
| h = hashlib.sha256() | |
| with open(path, "rb") as f: | |
| for chunk in iter(lambda: f.read(1 << 20), b""): | |
| h.update(chunk) | |
| return h.hexdigest() | |
| def fold(src: Path, dst: Path) -> None: | |
| import onnx | |
| import onnxruntime as ort | |
| m = onnx.load(str(src)) | |
| for v in list(m.graph.input) + list(m.graph.output): | |
| dims = v.type.tensor_type.shape.dim | |
| if dims and dims[0].dim_param: | |
| dims[0].dim_value = 1 | |
| tmp = dst.with_suffix(".b1.onnx") | |
| onnx.save(m, str(tmp)) | |
| so = ort.SessionOptions() | |
| so.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_BASIC | |
| so.optimized_model_filepath = str(dst) | |
| so.intra_op_num_threads = int(os.environ.get("VP_THREADS", "4")) | |
| ort.InferenceSession(str(tmp), so, providers=["CPUExecutionProvider"]) | |
| tmp.unlink() | |
| def main(argv=None) -> int: | |
| import cv2 | |
| import onnxruntime as ort | |
| ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) | |
| ap.add_argument("--weights", required=True, help="directory with the published <net>_fp32.onnx files") | |
| ap.add_argument("--out", required=True) | |
| ap.add_argument("--images", nargs="*", default=[], help="camera images for the goldens (BGR files)") | |
| args = ap.parse_args(argv) | |
| out = Path(args.out) | |
| (out / "folded").mkdir(parents=True, exist_ok=True) | |
| (out / "golden").mkdir(parents=True, exist_ok=True) | |
| frames = [cv2.imread(p, cv2.IMREAD_COLOR) for p in args.images] | |
| if any(f is None for f in frames): | |
| raise SystemExit(f"unreadable image in {args.images}") | |
| if not frames: | |
| rng = np.random.default_rng(0) | |
| frames = [cv2.GaussianBlur(rng.integers(0, 256, (720, 1280, 3), np.uint8), (0, 0), 3) for _ in range(2)] | |
| record = {} | |
| for name, spec in NETWORKS.items(): | |
| src = Path(args.weights) / spec.onnx_file | |
| dst = out / "folded" / f"{name}.onnx" | |
| fold(src, dst) | |
| so = ort.SessionOptions() | |
| so.intra_op_num_threads = int(os.environ.get("VP_THREADS", "4")) | |
| sess = ort.InferenceSession(str(src), so, providers=["CPUExecutionProvider"]) | |
| resized = [preprocess_front(f) for f in frames] | |
| samples = {} | |
| for k in range(len(frames) - (1 if spec.two_frames else 0)): | |
| feeds = {} | |
| if spec.two_frames: | |
| feeds[spec.inputs[0]] = network_input(spec, resized[k]) | |
| feeds[spec.inputs[1]] = network_input(spec, resized[k + 1]) | |
| else: | |
| feeds[spec.inputs[0]] = network_input(spec, resized[k]) | |
| outs = sess.run(None, feeds) | |
| for key, v in feeds.items(): | |
| samples[f"{k}/in/{key}"] = v | |
| for o, v in zip(sess.get_outputs(), outs): | |
| samples[f"{k}/out/{o.name}"] = v | |
| np.savez_compressed(out / "golden" / f"{name}.npz", **samples) | |
| record[name] = {"source": str(src), "source_sha256": _sha256(src), "folded_sha256": _sha256(dst), | |
| "samples": len(frames) - (1 if spec.two_frames else 0), "images": args.images, | |
| "onnxruntime": ort.__version__} | |
| print(name, json.dumps(record[name])) | |
| (out / "fold_record.json").write_text(json.dumps(record, indent=2) + "\n") | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |